repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
totallybradical/temp_servo2
refs/heads/master
python/tidy/servo_tidy_tests/lints/not_inherited.py
105
class Lint(object): pass
zsl/CodeSample
refs/heads/master
cpp/lib_console_hot_key/consolecolor.py
1
#!/usr/bin/env python #-*- coding:gbk -*- u''' @file consolecolor.py @brief set console color @author hulei @version 1.0 @date 2012-08-25 @copyright 2012 Hulei. All rights reserved. ''' import ctypes import sys _SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute _SetConsoleTextAttribute.argtypes = (ctypes.c_uint32, ctypes.c_uint16) _SetConsoleTextAttribute.restype = ctypes.c_int32 _GetStdHandle = ctypes.windll.kernel32.GetStdHandle _GetStdHandle.argtypes = (ctypes.c_int32,) _GetStdHandle.restype = ctypes.c_uint32 _GetConsoleScreenBufferInfo = ctypes.windll.kernel32.GetConsoleScreenBufferInfo _GetConsoleScreenBufferInfo.argtypes = (ctypes.c_uint32, ctypes.c_void_p) _GetConsoleScreenBufferInfo.restype = ctypes.c_int32 _STDOUT = _GetStdHandle(-11) FOREGROUND_BLUE = 1 FOREGROUND_GREEN = 2 FOREGROUND_RED = 4 FOREGROUND_INTENSITY = 8 BACKGROUND_BLUE = 16 BACKGROUND_GREEN = 32 BACKGROUND_RED = 64 BACKGROUND_INTENSITY = 128 RED = FOREGROUND_RED | FOREGROUND_INTENSITY BLUE = FOREGROUND_BLUE | FOREGROUND_INTENSITY GREEN = FOREGROUND_GREEN | FOREGROUND_INTENSITY SKYBLUE = BLUE | GREEN PURPLE = RED | BLUE VIOLET = PURPLE YELLOW = RED | GREEN WHITE = RED | GREEN | BLUE GRAY = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED BLACK = 0 def set_color(color): _SetConsoleTextAttribute(_STDOUT, color) def get_color(): buf = ctypes.create_string_buffer('0x16' + '\x00' * 21) _GetConsoleScreenBufferInfo(_STDOUT, buf) return ord(buf.raw[8]) def output(msg, color): sys.stdout.flush() origin = get_color() set_color(color) try: sys.stdout.write(msg) sys.stdout.flush() finally: set_color(origin) __all__ = ["FOREGROUND_BLUE", "FOREGROUND_GREEN", "FOREGROUND_RED", "FOREGROUND_INTENSITY", "BACKGROUND_BLUE", "BACKGROUND_GREEN", "BACKGROUND_RED", "BACKGROUND_INTENSITY", "RED", "BLUE", "GREEN", 'SKYBLUE', 'PURPLE', 'VIOLET', 'YELLOW', 'WHITE', 'GRAY', 'BLACK', 'set_color', 'get_color', 'output'] if __name__ == '__main__': output('this is a test for red\n', RED | BACKGROUND_GREEN) output('this is a test for blue\n', BLUE) output('this is a test for dark blue\n', FOREGROUND_BLUE) output('this is a test for yellow\n', YELLOW) output('this is a test for purple\n', PURPLE) output('this is a test for violet\n', VIOLET) output('this is a test for skyblue\n', SKYBLUE) output('this is a test for gray\n', GRAY) output('this is a test for white\n', WHITE) output('this is a test for black\n', BLACK) print 'this is a test for origin' print get_color()
stryder199/RyarkAssignments
refs/heads/master
Assignment2/ttt/ip_address/same_net_ABC_7.py
1
tuples = ('same_net_ABC_7','samenetworkornot', '128','$1','$1','$8', '129','10','$1','$8')
fenginx/django
refs/heads/master
tests/db_functions/comparison/test_cast.py
26
import datetime import decimal import unittest from django.db import connection, models from django.db.models import Avg from django.db.models.expressions import Value from django.db.models.functions import Cast from django.test import ( TestCase, ignore_warnings, override_settings, skipUnlessDBFeature, ) from ..models import Author, DTModel, Fan, FloatModel class CastTests(TestCase): @classmethod def setUpTestData(self): Author.objects.create(name='Bob', age=1, alias='1') def test_cast_from_value(self): numbers = Author.objects.annotate(cast_integer=Cast(Value('0'), models.IntegerField())) self.assertEqual(numbers.get().cast_integer, 0) def test_cast_from_field(self): numbers = Author.objects.annotate(cast_string=Cast('age', models.CharField(max_length=255)),) self.assertEqual(numbers.get().cast_string, '1') def test_cast_to_char_field_without_max_length(self): numbers = Author.objects.annotate(cast_string=Cast('age', models.CharField())) self.assertEqual(numbers.get().cast_string, '1') # Silence "Truncated incorrect CHAR(1) value: 'Bob'". @ignore_warnings(module='django.db.backends.mysql.base') @skipUnlessDBFeature('supports_cast_with_precision') def test_cast_to_char_field_with_max_length(self): names = Author.objects.annotate(cast_string=Cast('name', models.CharField(max_length=1))) self.assertEqual(names.get().cast_string, 'B') @skipUnlessDBFeature('supports_cast_with_precision') def test_cast_to_decimal_field(self): FloatModel.objects.create(f1=-1.934, f2=3.467) float_obj = FloatModel.objects.annotate( cast_f1_decimal=Cast('f1', models.DecimalField(max_digits=8, decimal_places=2)), cast_f2_decimal=Cast('f2', models.DecimalField(max_digits=8, decimal_places=1)), ).get() self.assertEqual(float_obj.cast_f1_decimal, decimal.Decimal('-1.93')) self.assertEqual(float_obj.cast_f2_decimal, decimal.Decimal('3.5')) author_obj = Author.objects.annotate( cast_alias_decimal=Cast('alias', models.DecimalField(max_digits=8, decimal_places=2)), ).get() self.assertEqual(author_obj.cast_alias_decimal, decimal.Decimal('1')) def test_cast_to_integer(self): for field_class in ( models.AutoField, models.BigAutoField, models.IntegerField, models.BigIntegerField, models.SmallIntegerField, models.PositiveIntegerField, models.PositiveSmallIntegerField, ): with self.subTest(field_class=field_class): numbers = Author.objects.annotate(cast_int=Cast('alias', field_class())) self.assertEqual(numbers.get().cast_int, 1) def test_cast_from_db_datetime_to_date(self): dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) DTModel.objects.create(start_datetime=dt_value) dtm = DTModel.objects.annotate( start_datetime_as_date=Cast('start_datetime', models.DateField()) ).first() self.assertEqual(dtm.start_datetime_as_date, datetime.date(2018, 9, 28)) def test_cast_from_db_datetime_to_time(self): dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) DTModel.objects.create(start_datetime=dt_value) dtm = DTModel.objects.annotate( start_datetime_as_time=Cast('start_datetime', models.TimeField()) ).first() rounded_ms = int(round(.234567, connection.features.time_cast_precision) * 10**6) self.assertEqual(dtm.start_datetime_as_time, datetime.time(12, 42, 10, rounded_ms)) def test_cast_from_db_date_to_datetime(self): dt_value = datetime.date(2018, 9, 28) DTModel.objects.create(start_date=dt_value) dtm = DTModel.objects.annotate(start_as_datetime=Cast('start_date', models.DateTimeField())).first() self.assertEqual(dtm.start_as_datetime, datetime.datetime(2018, 9, 28, 0, 0, 0, 0)) def test_cast_from_db_datetime_to_date_group_by(self): author = Author.objects.create(name='John Smith', age=45) dt_value = datetime.datetime(2018, 9, 28, 12, 42, 10, 234567) Fan.objects.create(name='Margaret', age=50, author=author, fan_since=dt_value) fans = Fan.objects.values('author').annotate( fan_for_day=Cast('fan_since', models.DateField()), fans=models.Count('*') ).values() self.assertEqual(fans[0]['fan_for_day'], datetime.date(2018, 9, 28)) self.assertEqual(fans[0]['fans'], 1) def test_cast_from_python_to_date(self): today = datetime.date.today() dates = Author.objects.annotate(cast_date=Cast(today, models.DateField())) self.assertEqual(dates.get().cast_date, today) def test_cast_from_python_to_datetime(self): now = datetime.datetime.now() dates = Author.objects.annotate(cast_datetime=Cast(now, models.DateTimeField())) time_precision = datetime.timedelta( microseconds=10**(6 - connection.features.time_cast_precision) ) self.assertAlmostEqual(dates.get().cast_datetime, now, delta=time_precision) def test_cast_from_python(self): numbers = Author.objects.annotate(cast_float=Cast(decimal.Decimal(0.125), models.FloatField())) cast_float = numbers.get().cast_float self.assertIsInstance(cast_float, float) self.assertEqual(cast_float, 0.125) @unittest.skipUnless(connection.vendor == 'postgresql', 'PostgreSQL test') @override_settings(DEBUG=True) def test_expression_wrapped_with_parentheses_on_postgresql(self): """ The SQL for the Cast expression is wrapped with parentheses in case it's a complex expression. """ list(Author.objects.annotate(cast_float=Cast(Avg('age'), models.FloatField()))) self.assertIn('(AVG("db_functions_author"."age"))::double precision', connection.queries[-1]['sql']) def test_cast_to_text_field(self): self.assertEqual(Author.objects.values_list(Cast('age', models.TextField()), flat=True).get(), '1')
photoninger/ansible
refs/heads/devel
test/units/modules/network/aruba/aruba_module.py
73
# (c) 2016 Red Hat 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 <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_data = {} def load_fixture(name): path = os.path.join(fixture_path, name) if path in fixture_data: return fixture_data[path] with open(path) as f: data = f.read() try: data = json.loads(data) except: pass fixture_data[path] = data return data class TestArubaModule(ModuleTestCase): def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False): self.load_fixtures(commands) if failed: result = self.failed() self.assertTrue(result['failed'], result) else: result = self.changed(changed) self.assertEqual(result['changed'], changed, result) if commands is not None: if sort: self.assertEqual(sorted(commands), sorted(result['commands']), result['commands']) else: self.assertEqual(commands, result['commands'], result['commands']) return result def failed(self): with self.assertRaises(AnsibleFailJson) as exc: self.module.main() result = exc.exception.args[0] self.assertTrue(result['failed'], result) return result def changed(self, changed=False): with self.assertRaises(AnsibleExitJson) as exc: self.module.main() result = exc.exception.args[0] self.assertEqual(result['changed'], changed, result) return result def load_fixtures(self, commands=None): pass
gabrielsimas/selenium
refs/heads/master
py/selenium/selenium.py
69
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC 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 __future__ import unicode_literals __docformat__ = "restructuredtext en" try: import http.client as http_client except ImportError: import httplib as http_client try: import urllib.parse as urllib_parse except ImportError: import urllib as urllib_parse class selenium(object): """ Defines an object that runs Selenium commands. **Element Locators** Element Locators tell Selenium which HTML element a command refers to. The format of a locator is: \ *locatorType*\ **=**\ \ *argument* We support the following strategies for locating elements: * \ **identifier**\ =\ *id*: Select the element with the specified @id attribute. If no match is found, select the first element whose @name attribute is \ *id*. (This is normally the default; see below.) * \ **id**\ =\ *id*: Select the element with the specified @id attribute. * \ **name**\ =\ *name*: Select the first element with the specified @name attribute. * username * name=username The name may optionally be followed by one or more \ *element-filters*, separated from the name by whitespace. If the \ *filterType* is not specified, \ **value**\ is assumed. * name=flavour value=chocolate * \ **dom**\ =\ *javascriptExpression*: Find an element by evaluating the specified string. This allows you to traverse the HTML Document Object Model using JavaScript. Note that you must not return a value in this string; simply make it the last expression in the block. * dom=document.forms['myForm'].myDropdown * dom=document.images[56] * dom=function foo() { return document.links[1]; }; foo(); * \ **xpath**\ =\ *xpathExpression*: Locate an element using an XPath expression. * xpath=//img[@alt='The image alt text'] * xpath=//table[@id='table1']//tr[4]/td[2] * xpath=//a[contains(@href,'#id1')] * xpath=//a[contains(@href,'#id1')]/@class * xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td * xpath=//input[@name='name2' and @value='yes'] * xpath=//\*[text()="right"] * \ **link**\ =\ *textPattern*: Select the link (anchor) element which contains text matching the specified \ *pattern*. * link=The link text * \ **css**\ =\ *cssSelectorSyntax*: Select the element using css selectors. Please refer to CSS2 selectors, CSS3 selectors for more information. You can also check the TestCssLocators test in the selenium test suite for an example of usage, which is included in the downloaded selenium core package. * css=a[href="#id3"] * css=span#firstChild + span Currently the css selector locator supports all css1, css2 and css3 selectors except namespace in css3, some pseudo classes(:nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type, :visited, :hover, :active, :focus, :indeterminate) and pseudo elements(::first-line, ::first-letter, ::selection, ::before, ::after). * \ **ui**\ =\ *uiSpecifierString*: Locate an element by resolving the UI specifier string to another locator, and evaluating it. See the Selenium UI-Element Reference for more details. * ui=loginPages::loginButton() * ui=settingsPages::toggle(label=Hide Email) * ui=forumPages::postBody(index=2)//a[2] Without an explicit locator prefix, Selenium uses the following default strategies: * \ **dom**\ , for locators starting with "document." * \ **xpath**\ , for locators starting with "//" * \ **identifier**\ , otherwise **Element Filters** Element filters can be used with a locator to refine a list of candidate elements. They are currently used only in the 'name' element-locator. Filters look much like locators, ie. \ *filterType*\ **=**\ \ *argument* Supported element-filters are: \ **value=**\ \ *valuePattern* Matches elements based on their values. This is particularly useful for refining a list of similarly-named toggle-buttons. \ **index=**\ \ *index* Selects a single element based on its position in the list (offset from zero). **String-match Patterns** Various Pattern syntaxes are available for matching string values: * \ **glob:**\ \ *pattern*: Match a string against a "glob" (aka "wildmat") pattern. "Glob" is a kind of limited regular-expression syntax typically used in command-line shells. In a glob pattern, "\*" represents any sequence of characters, and "?" represents any single character. Glob patterns match against the entire string. * \ **regexp:**\ \ *regexp*: Match a string using a regular-expression. The full power of JavaScript regular-expressions is available. * \ **regexpi:**\ \ *regexpi*: Match a string using a case-insensitive regular-expression. * \ **exact:**\ \ *string*: Match a string exactly, verbatim, without any of that fancy wildcard stuff. If no pattern prefix is specified, Selenium assumes that it's a "glob" pattern. For commands that return multiple values (such as verifySelectOptions), the string being matched is a comma-separated list of the return values, where both commas and backslashes in the values are backslash-escaped. When providing a pattern, the optional matching syntax (i.e. glob, regexp, etc.) is specified once, as usual, at the beginning of the pattern. """ ### This part is hard-coded in the XSL def __init__(self, host, port, browserStartCommand, browserURL, http_timeout=90): self.host = host self.port = port self.browserStartCommand = browserStartCommand self.browserURL = browserURL self.sessionId = None self.extensionJs = "" self.http_timeout = http_timeout def setExtensionJs(self, extensionJs): self.extensionJs = extensionJs def start(self, browserConfigurationOptions=None, driver=None): start_args = [self.browserStartCommand, self.browserURL, self.extensionJs] if browserConfigurationOptions: start_args.append(browserConfigurationOptions) if driver: start_args.append('webdriver.remote.sessionid=%s' % driver.session_id) # Sessions can take a while to start, specially in grid environments self.http_timeout *= 5 result = self.get_string("getNewBrowserSession", start_args) self.http_timeout /= 5 try: self.sessionId = result except ValueError: raise Exception(result) def stop(self): self.do_command("testComplete", []) self.sessionId = None def do_command(self, verb, args): conn = http_client.HTTPConnection(self.host, self.port, timeout=self.http_timeout) try: body = 'cmd=' + urllib_parse.quote_plus(unicode(verb).encode('utf-8')) for i in range(len(args)): body += '&' + unicode(i+1) + '=' + \ urllib_parse.quote_plus(unicode(args[i]).encode('utf-8')) if (None != self.sessionId): body += "&sessionId=" + unicode(self.sessionId) headers = { "Content-Type": "application/x-www-form-urlencoded; charset=utf-8" } conn.request("POST", "/selenium-server/driver/", body, headers) response = conn.getresponse() data = unicode(response.read(), "UTF-8") if (not data.startswith('OK')): raise Exception(data) return data finally: conn.close() def get_string(self, verb, args): result = self.do_command(verb, args) return result[3:] def get_string_array(self, verb, args): csv = self.get_string(verb, args) if not csv: return [] token = "" tokens = [] escape = False for i in range(len(csv)): letter = csv[i] if (escape): token = token + letter escape = False continue if (letter == '\\'): escape = True elif (letter == ','): tokens.append(token) token = "" else: token = token + letter tokens.append(token) return tokens def get_number(self, verb, args): return int(self.get_string(verb, args)) def get_number_array(self, verb, args): string_array = self.get_string_array(verb, args) num_array = [] for i in string_array: num_array.append(int(i)) return num_array def get_boolean(self, verb, args): boolstr = self.get_string(verb, args) if ("true" == boolstr): return True if ("false" == boolstr): return False raise ValueError("result is neither 'true' nor 'false': " + boolstr) def get_boolean_array(self, verb, args): boolarr = self.get_string_array(verb, args) for i, boolstr in enumerate(boolarr): if ("true" == boolstr): boolarr[i] = True continue if ("false" == boolstr): boolarr[i] = False continue raise ValueError("result is neither 'true' nor 'false': " + boolarr[i]) return boolarr def click(self,locator): """ Clicks on a link, button, checkbox or radio button. If the click action causes a new page to load (like a link usually does), call waitForPageToLoad. 'locator' is an element locator """ self.do_command("click", [locator,]) def double_click(self,locator): """ Double clicks on a link, button, checkbox or radio button. If the double click action causes a new page to load (like a link usually does), call waitForPageToLoad. 'locator' is an element locator """ self.do_command("doubleClick", [locator,]) def context_menu(self,locator): """ Simulates opening the context menu for the specified element (as might happen if the user "right-clicked" on the element). 'locator' is an element locator """ self.do_command("contextMenu", [locator,]) def click_at(self,locator,coordString): """ Clicks on a link, button, checkbox or radio button. If the click action causes a new page to load (like a link usually does), call waitForPageToLoad. 'locator' is an element locator 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. """ self.do_command("clickAt", [locator,coordString,]) def double_click_at(self,locator,coordString): """ Doubleclicks on a link, button, checkbox or radio button. If the action causes a new page to load (like a link usually does), call waitForPageToLoad. 'locator' is an element locator 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. """ self.do_command("doubleClickAt", [locator,coordString,]) def context_menu_at(self,locator,coordString): """ Simulates opening the context menu for the specified element (as might happen if the user "right-clicked" on the element). 'locator' is an element locator 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. """ self.do_command("contextMenuAt", [locator,coordString,]) def fire_event(self,locator,eventName): """ Explicitly simulate an event, to trigger the corresponding "on\ *event*" handler. 'locator' is an element locator 'eventName' is the event name, e.g. "focus" or "blur" """ self.do_command("fireEvent", [locator,eventName,]) def focus(self,locator): """ Move the focus to the specified element; for example, if the element is an input field, move the cursor to that field. 'locator' is an element locator """ self.do_command("focus", [locator,]) def key_press(self,locator,keySequence): """ Simulates a user pressing and releasing a key. 'locator' is an element locator 'keySequence' is Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119". """ self.do_command("keyPress", [locator,keySequence,]) def shift_key_down(self): """ Press the shift key and hold it down until doShiftUp() is called or a new page is loaded. """ self.do_command("shiftKeyDown", []) def shift_key_up(self): """ Release the shift key. """ self.do_command("shiftKeyUp", []) def meta_key_down(self): """ Press the meta key and hold it down until doMetaUp() is called or a new page is loaded. """ self.do_command("metaKeyDown", []) def meta_key_up(self): """ Release the meta key. """ self.do_command("metaKeyUp", []) def alt_key_down(self): """ Press the alt key and hold it down until doAltUp() is called or a new page is loaded. """ self.do_command("altKeyDown", []) def alt_key_up(self): """ Release the alt key. """ self.do_command("altKeyUp", []) def control_key_down(self): """ Press the control key and hold it down until doControlUp() is called or a new page is loaded. """ self.do_command("controlKeyDown", []) def control_key_up(self): """ Release the control key. """ self.do_command("controlKeyUp", []) def key_down(self,locator,keySequence): """ Simulates a user pressing a key (without releasing it yet). 'locator' is an element locator 'keySequence' is Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119". """ self.do_command("keyDown", [locator,keySequence,]) def key_up(self,locator,keySequence): """ Simulates a user releasing a key. 'locator' is an element locator 'keySequence' is Either be a string("\" followed by the numeric keycode of the key to be pressed, normally the ASCII value of that key), or a single character. For example: "w", "\119". """ self.do_command("keyUp", [locator,keySequence,]) def mouse_over(self,locator): """ Simulates a user hovering a mouse over the specified element. 'locator' is an element locator """ self.do_command("mouseOver", [locator,]) def mouse_out(self,locator): """ Simulates a user moving the mouse pointer away from the specified element. 'locator' is an element locator """ self.do_command("mouseOut", [locator,]) def mouse_down(self,locator): """ Simulates a user pressing the left mouse button (without releasing it yet) on the specified element. 'locator' is an element locator """ self.do_command("mouseDown", [locator,]) def mouse_down_right(self,locator): """ Simulates a user pressing the right mouse button (without releasing it yet) on the specified element. 'locator' is an element locator """ self.do_command("mouseDownRight", [locator,]) def mouse_down_at(self,locator,coordString): """ Simulates a user pressing the left mouse button (without releasing it yet) at the specified location. 'locator' is an element locator 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. """ self.do_command("mouseDownAt", [locator,coordString,]) def mouse_down_right_at(self,locator,coordString): """ Simulates a user pressing the right mouse button (without releasing it yet) at the specified location. 'locator' is an element locator 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. """ self.do_command("mouseDownRightAt", [locator,coordString,]) def mouse_up(self,locator): """ Simulates the event that occurs when the user releases the mouse button (i.e., stops holding the button down) on the specified element. 'locator' is an element locator """ self.do_command("mouseUp", [locator,]) def mouse_up_right(self,locator): """ Simulates the event that occurs when the user releases the right mouse button (i.e., stops holding the button down) on the specified element. 'locator' is an element locator """ self.do_command("mouseUpRight", [locator,]) def mouse_up_at(self,locator,coordString): """ Simulates the event that occurs when the user releases the mouse button (i.e., stops holding the button down) at the specified location. 'locator' is an element locator 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. """ self.do_command("mouseUpAt", [locator,coordString,]) def mouse_up_right_at(self,locator,coordString): """ Simulates the event that occurs when the user releases the right mouse button (i.e., stops holding the button down) at the specified location. 'locator' is an element locator 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. """ self.do_command("mouseUpRightAt", [locator,coordString,]) def mouse_move(self,locator): """ Simulates a user pressing the mouse button (without releasing it yet) on the specified element. 'locator' is an element locator """ self.do_command("mouseMove", [locator,]) def mouse_move_at(self,locator,coordString): """ Simulates a user pressing the mouse button (without releasing it yet) on the specified element. 'locator' is an element locator 'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator. """ self.do_command("mouseMoveAt", [locator,coordString,]) def type(self,locator,value): """ Sets the value of an input field, as though you typed it in. Can also be used to set the value of combo boxes, check boxes, etc. In these cases, value should be the value of the option selected, not the visible text. 'locator' is an element locator 'value' is the value to type """ self.do_command("type", [locator,value,]) def type_keys(self,locator,value): """ Simulates keystroke events on the specified element, as though you typed the value key-by-key. This is a convenience method for calling keyDown, keyUp, keyPress for every character in the specified string; this is useful for dynamic UI widgets (like auto-completing combo boxes) that require explicit key events. Unlike the simple "type" command, which forces the specified value into the page directly, this command may or may not have any visible effect, even in cases where typing keys would normally have a visible effect. For example, if you use "typeKeys" on a form element, you may or may not see the results of what you typed in the field. In some cases, you may need to use the simple "type" command to set the value of the field and then the "typeKeys" command to send the keystroke events corresponding to what you just typed. 'locator' is an element locator 'value' is the value to type """ self.do_command("typeKeys", [locator,value,]) def set_speed(self,value): """ Set execution speed (i.e., set the millisecond length of a delay which will follow each selenium operation). By default, there is no such delay, i.e., the delay is 0 milliseconds. 'value' is the number of milliseconds to pause after operation """ self.do_command("setSpeed", [value,]) def get_speed(self): """ Get execution speed (i.e., get the millisecond length of the delay following each selenium operation). By default, there is no such delay, i.e., the delay is 0 milliseconds. See also setSpeed. """ return self.get_string("getSpeed", []) def get_log(self): """ Get RC logs associated with current session. """ return self.get_string("getLog", []) def check(self,locator): """ Check a toggle-button (checkbox/radio) 'locator' is an element locator """ self.do_command("check", [locator,]) def uncheck(self,locator): """ Uncheck a toggle-button (checkbox/radio) 'locator' is an element locator """ self.do_command("uncheck", [locator,]) def select(self,selectLocator,optionLocator): """ Select an option from a drop-down using an option locator. Option locators provide different ways of specifying options of an HTML Select element (e.g. for selecting a specific option, or for asserting that the selected option satisfies a specification). There are several forms of Select Option Locator. * \ **label**\ =\ *labelPattern*: matches options based on their labels, i.e. the visible text. (This is the default.) * label=regexp:^[Oo]ther * \ **value**\ =\ *valuePattern*: matches options based on their values. * value=other * \ **id**\ =\ *id*: matches options based on their ids. * id=option1 * \ **index**\ =\ *index*: matches an option based on its index (offset from zero). * index=2 If no option locator prefix is provided, the default behaviour is to match on \ **label**\ . 'selectLocator' is an element locator identifying a drop-down menu 'optionLocator' is an option locator (a label by default) """ self.do_command("select", [selectLocator,optionLocator,]) def add_selection(self,locator,optionLocator): """ Add a selection to the set of selected options in a multi-select element using an option locator. @see #doSelect for details of option locators 'locator' is an element locator identifying a multi-select box 'optionLocator' is an option locator (a label by default) """ self.do_command("addSelection", [locator,optionLocator,]) def remove_selection(self,locator,optionLocator): """ Remove a selection from the set of selected options in a multi-select element using an option locator. @see #doSelect for details of option locators 'locator' is an element locator identifying a multi-select box 'optionLocator' is an option locator (a label by default) """ self.do_command("removeSelection", [locator,optionLocator,]) def remove_all_selections(self,locator): """ Unselects all of the selected options in a multi-select element. 'locator' is an element locator identifying a multi-select box """ self.do_command("removeAllSelections", [locator,]) def submit(self,formLocator): """ Submit the specified form. This is particularly useful for forms without submit buttons, e.g. single-input "Search" forms. 'formLocator' is an element locator for the form you want to submit """ self.do_command("submit", [formLocator,]) def open(self,url,ignoreResponseCode=True): """ Opens an URL in the test frame. This accepts both relative and absolute URLs. The "open" command waits for the page to load before proceeding, ie. the "AndWait" suffix is implicit. \ *Note*: The URL must be on the same domain as the runner HTML due to security restrictions in the browser (Same Origin Policy). If you need to open an URL on another domain, use the Selenium Server to start a new browser session on that domain. 'url' is the URL to open; may be relative or absolute 'ignoreResponseCode' if set to true: doesnt send ajax HEAD/GET request; if set to false: sends ajax HEAD/GET request to the url and reports error code if any as response to open. """ self.do_command("open", [url,ignoreResponseCode]) def open_window(self,url,windowID): """ Opens a popup window (if a window with that ID isn't already open). After opening the window, you'll need to select it using the selectWindow command. This command can also be a useful workaround for bug SEL-339. In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before the "onLoad" event, for example). In those cases, you can force Selenium to notice the open window's name by using the Selenium openWindow command, using an empty (blank) url, like this: openWindow("", "myFunnyWindow"). 'url' is the URL to open, which can be blank 'windowID' is the JavaScript window ID of the window to select """ self.do_command("openWindow", [url,windowID,]) def select_window(self,windowID): """ Selects a popup window using a window locator; once a popup window has been selected, all commands go to that window. To select the main window again, use null as the target. Window locators provide different ways of specifying the window object: by title, by internal JavaScript "name," or by JavaScript variable. * \ **title**\ =\ *My Special Window*: Finds the window using the text that appears in the title bar. Be careful; two windows can share the same title. If that happens, this locator will just pick one. * \ **name**\ =\ *myWindow*: Finds the window using its internal JavaScript "name" property. This is the second parameter "windowName" passed to the JavaScript method window.open(url, windowName, windowFeatures, replaceFlag) (which Selenium intercepts). * \ **var**\ =\ *variableName*: Some pop-up windows are unnamed (anonymous), but are associated with a JavaScript variable name in the current application window, e.g. "window.foo = window.open(url);". In those cases, you can open the window using "var=foo". If no window locator prefix is provided, we'll try to guess what you mean like this: 1.) if windowID is null, (or the string "null") then it is assumed the user is referring to the original window instantiated by the browser). 2.) if the value of the "windowID" parameter is a JavaScript variable name in the current application window, then it is assumed that this variable contains the return value from a call to the JavaScript window.open() method. 3.) Otherwise, selenium looks in a hash it maintains that maps string names to window "names". 4.) If \ *that* fails, we'll try looping over all of the known windows to try to find the appropriate "title". Since "title" is not necessarily unique, this may have unexpected behavior. If you're having trouble figuring out the name of a window that you want to manipulate, look at the Selenium log messages which identify the names of windows created via window.open (and therefore intercepted by Selenium). You will see messages like the following for each window as it is opened: ``debug: window.open call intercepted; window ID (which you can use with selectWindow()) is "myNewWindow"`` In some cases, Selenium will be unable to intercept a call to window.open (if the call occurs during or before the "onLoad" event, for example). (This is bug SEL-339.) In those cases, you can force Selenium to notice the open window's name by using the Selenium openWindow command, using an empty (blank) url, like this: openWindow("", "myFunnyWindow"). 'windowID' is the JavaScript window ID of the window to select """ self.do_command("selectWindow", [windowID,]) def select_pop_up(self,windowID): """ Simplifies the process of selecting a popup window (and does not offer functionality beyond what ``selectWindow()`` already provides). * If ``windowID`` is either not specified, or specified as "null", the first non-top window is selected. The top window is the one that would be selected by ``selectWindow()`` without providing a ``windowID`` . This should not be used when more than one popup window is in play. * Otherwise, the window will be looked up considering ``windowID`` as the following in order: 1) the "name" of the window, as specified to ``window.open()``; 2) a javascript variable which is a reference to a window; and 3) the title of the window. This is the same ordered lookup performed by ``selectWindow`` . 'windowID' is an identifier for the popup window, which can take on a number of different meanings """ self.do_command("selectPopUp", [windowID,]) def deselect_pop_up(self): """ Selects the main window. Functionally equivalent to using ``selectWindow()`` and specifying no value for ``windowID``. """ self.do_command("deselectPopUp", []) def select_frame(self,locator): """ Selects a frame within the current window. (You may invoke this command multiple times to select nested frames.) To select the parent frame, use "relative=parent" as a locator; to select the top frame, use "relative=top". You can also select a frame by its 0-based index number; select the first frame with "index=0", or the third frame with "index=2". You may also use a DOM expression to identify the frame you want directly, like this: ``dom=frames["main"].frames["subframe"]`` 'locator' is an element locator identifying a frame or iframe """ self.do_command("selectFrame", [locator,]) def get_whether_this_frame_match_frame_expression(self,currentFrameString,target): """ Determine whether current/locator identify the frame containing this running code. This is useful in proxy injection mode, where this code runs in every browser frame and window, and sometimes the selenium server needs to identify the "current" frame. In this case, when the test calls selectFrame, this routine is called for each frame to figure out which one has been selected. The selected frame will return true, while all others will return false. 'currentFrameString' is starting frame 'target' is new frame (which might be relative to the current one) """ return self.get_boolean("getWhetherThisFrameMatchFrameExpression", [currentFrameString,target,]) def get_whether_this_window_match_window_expression(self,currentWindowString,target): """ Determine whether currentWindowString plus target identify the window containing this running code. This is useful in proxy injection mode, where this code runs in every browser frame and window, and sometimes the selenium server needs to identify the "current" window. In this case, when the test calls selectWindow, this routine is called for each window to figure out which one has been selected. The selected window will return true, while all others will return false. 'currentWindowString' is starting window 'target' is new window (which might be relative to the current one, e.g., "_parent") """ return self.get_boolean("getWhetherThisWindowMatchWindowExpression", [currentWindowString,target,]) def wait_for_pop_up(self,windowID,timeout): """ Waits for a popup window to appear and load up. 'windowID' is the JavaScript window "name" of the window that will appear (not the text of the title bar) If unspecified, or specified as "null", this command will wait for the first non-top window to appear (don't rely on this if you are working with multiple popups simultaneously). 'timeout' is a timeout in milliseconds, after which the action will return with an error. If this value is not specified, the default Selenium timeout will be used. See the setTimeout() command. """ self.do_command("waitForPopUp", [windowID,timeout,]) def choose_cancel_on_next_confirmation(self): """ By default, Selenium's overridden window.confirm() function will return true, as if the user had manually clicked OK; after running this command, the next call to confirm() will return false, as if the user had clicked Cancel. Selenium will then resume using the default behavior for future confirmations, automatically returning true (OK) unless/until you explicitly call this command for each confirmation. Take note - every time a confirmation comes up, you must consume it with a corresponding getConfirmation, or else the next selenium operation will fail. """ self.do_command("chooseCancelOnNextConfirmation", []) def choose_ok_on_next_confirmation(self): """ Undo the effect of calling chooseCancelOnNextConfirmation. Note that Selenium's overridden window.confirm() function will normally automatically return true, as if the user had manually clicked OK, so you shouldn't need to use this command unless for some reason you need to change your mind prior to the next confirmation. After any confirmation, Selenium will resume using the default behavior for future confirmations, automatically returning true (OK) unless/until you explicitly call chooseCancelOnNextConfirmation for each confirmation. Take note - every time a confirmation comes up, you must consume it with a corresponding getConfirmation, or else the next selenium operation will fail. """ self.do_command("chooseOkOnNextConfirmation", []) def answer_on_next_prompt(self,answer): """ Instructs Selenium to return the specified answer string in response to the next JavaScript prompt [window.prompt()]. 'answer' is the answer to give in response to the prompt pop-up """ self.do_command("answerOnNextPrompt", [answer,]) def go_back(self): """ Simulates the user clicking the "back" button on their browser. """ self.do_command("goBack", []) def refresh(self): """ Simulates the user clicking the "Refresh" button on their browser. """ self.do_command("refresh", []) def close(self): """ Simulates the user clicking the "close" button in the titlebar of a popup window or tab. """ self.do_command("close", []) def is_alert_present(self): """ Has an alert occurred? This function never throws an exception """ return self.get_boolean("isAlertPresent", []) def is_prompt_present(self): """ Has a prompt occurred? This function never throws an exception """ return self.get_boolean("isPromptPresent", []) def is_confirmation_present(self): """ Has confirm() been called? This function never throws an exception """ return self.get_boolean("isConfirmationPresent", []) def get_alert(self): """ Retrieves the message of a JavaScript alert generated during the previous action, or fail if there were no alerts. Getting an alert has the same effect as manually clicking OK. If an alert is generated but you do not consume it with getAlert, the next Selenium action will fail. Under Selenium, JavaScript alerts will NOT pop up a visible alert dialog. Selenium does NOT support JavaScript alerts that are generated in a page's onload() event handler. In this case a visible dialog WILL be generated and Selenium will hang until someone manually clicks OK. """ return self.get_string("getAlert", []) def get_confirmation(self): """ Retrieves the message of a JavaScript confirmation dialog generated during the previous action. By default, the confirm function will return true, having the same effect as manually clicking OK. This can be changed by prior execution of the chooseCancelOnNextConfirmation command. If an confirmation is generated but you do not consume it with getConfirmation, the next Selenium action will fail. NOTE: under Selenium, JavaScript confirmations will NOT pop up a visible dialog. NOTE: Selenium does NOT support JavaScript confirmations that are generated in a page's onload() event handler. In this case a visible dialog WILL be generated and Selenium will hang until you manually click OK. """ return self.get_string("getConfirmation", []) def get_prompt(self): """ Retrieves the message of a JavaScript question prompt dialog generated during the previous action. Successful handling of the prompt requires prior execution of the answerOnNextPrompt command. If a prompt is generated but you do not get/verify it, the next Selenium action will fail. NOTE: under Selenium, JavaScript prompts will NOT pop up a visible dialog. NOTE: Selenium does NOT support JavaScript prompts that are generated in a page's onload() event handler. In this case a visible dialog WILL be generated and Selenium will hang until someone manually clicks OK. """ return self.get_string("getPrompt", []) def get_location(self): """ Gets the absolute URL of the current page. """ return self.get_string("getLocation", []) def get_title(self): """ Gets the title of the current page. """ return self.get_string("getTitle", []) def get_body_text(self): """ Gets the entire text of the page. """ return self.get_string("getBodyText", []) def get_value(self,locator): """ Gets the (whitespace-trimmed) value of an input field (or anything else with a value parameter). For checkbox/radio elements, the value will be "on" or "off" depending on whether the element is checked or not. 'locator' is an element locator """ return self.get_string("getValue", [locator,]) def get_text(self,locator): """ Gets the text of an element. This works for any element that contains text. This command uses either the textContent (Mozilla-like browsers) or the innerText (IE-like browsers) of the element, which is the rendered text shown to the user. 'locator' is an element locator """ return self.get_string("getText", [locator,]) def highlight(self,locator): """ Briefly changes the backgroundColor of the specified element yellow. Useful for debugging. 'locator' is an element locator """ self.do_command("highlight", [locator,]) def get_eval(self,script): """ Gets the result of evaluating the specified JavaScript snippet. The snippet may have multiple lines, but only the result of the last line will be returned. Note that, by default, the snippet will run in the context of the "selenium" object itself, so ``this`` will refer to the Selenium object. Use ``window`` to refer to the window of your application, e.g. ``window.document.getElementById('foo')`` If you need to use a locator to refer to a single element in your application page, you can use ``this.browserbot.findElement("id=foo")`` where "id=foo" is your locator. 'script' is the JavaScript snippet to run """ return self.get_string("getEval", [script,]) def is_checked(self,locator): """ Gets whether a toggle-button (checkbox/radio) is checked. Fails if the specified element doesn't exist or isn't a toggle-button. 'locator' is an element locator pointing to a checkbox or radio button """ return self.get_boolean("isChecked", [locator,]) def get_table(self,tableCellAddress): """ Gets the text from a cell of a table. The cellAddress syntax tableLocator.row.column, where row and column start at 0. 'tableCellAddress' is a cell address, e.g. "foo.1.4" """ return self.get_string("getTable", [tableCellAddress,]) def get_selected_labels(self,selectLocator): """ Gets all option labels (visible text) for selected options in the specified select or multi-select element. 'selectLocator' is an element locator identifying a drop-down menu """ return self.get_string_array("getSelectedLabels", [selectLocator,]) def get_selected_label(self,selectLocator): """ Gets option label (visible text) for selected option in the specified select element. 'selectLocator' is an element locator identifying a drop-down menu """ return self.get_string("getSelectedLabel", [selectLocator,]) def get_selected_values(self,selectLocator): """ Gets all option values (value attributes) for selected options in the specified select or multi-select element. 'selectLocator' is an element locator identifying a drop-down menu """ return self.get_string_array("getSelectedValues", [selectLocator,]) def get_selected_value(self,selectLocator): """ Gets option value (value attribute) for selected option in the specified select element. 'selectLocator' is an element locator identifying a drop-down menu """ return self.get_string("getSelectedValue", [selectLocator,]) def get_selected_indexes(self,selectLocator): """ Gets all option indexes (option number, starting at 0) for selected options in the specified select or multi-select element. 'selectLocator' is an element locator identifying a drop-down menu """ return self.get_string_array("getSelectedIndexes", [selectLocator,]) def get_selected_index(self,selectLocator): """ Gets option index (option number, starting at 0) for selected option in the specified select element. 'selectLocator' is an element locator identifying a drop-down menu """ return self.get_string("getSelectedIndex", [selectLocator,]) def get_selected_ids(self,selectLocator): """ Gets all option element IDs for selected options in the specified select or multi-select element. 'selectLocator' is an element locator identifying a drop-down menu """ return self.get_string_array("getSelectedIds", [selectLocator,]) def get_selected_id(self,selectLocator): """ Gets option element ID for selected option in the specified select element. 'selectLocator' is an element locator identifying a drop-down menu """ return self.get_string("getSelectedId", [selectLocator,]) def is_something_selected(self,selectLocator): """ Determines whether some option in a drop-down menu is selected. 'selectLocator' is an element locator identifying a drop-down menu """ return self.get_boolean("isSomethingSelected", [selectLocator,]) def get_select_options(self,selectLocator): """ Gets all option labels in the specified select drop-down. 'selectLocator' is an element locator identifying a drop-down menu """ return self.get_string_array("getSelectOptions", [selectLocator,]) def get_attribute(self,attributeLocator): """ Gets the value of an element attribute. The value of the attribute may differ across browsers (this is the case for the "style" attribute, for example). 'attributeLocator' is an element locator followed by an @ sign and then the name of the attribute, e.g. "foo@bar" """ return self.get_string("getAttribute", [attributeLocator,]) def is_text_present(self,pattern): """ Verifies that the specified text pattern appears somewhere on the rendered page shown to the user. 'pattern' is a pattern to match with the text of the page """ return self.get_boolean("isTextPresent", [pattern,]) def is_element_present(self,locator): """ Verifies that the specified element is somewhere on the page. 'locator' is an element locator """ return self.get_boolean("isElementPresent", [locator,]) def is_visible(self,locator): """ Determines if the specified element is visible. An element can be rendered invisible by setting the CSS "visibility" property to "hidden", or the "display" property to "none", either for the element itself or one if its ancestors. This method will fail if the element is not present. 'locator' is an element locator """ return self.get_boolean("isVisible", [locator,]) def is_editable(self,locator): """ Determines whether the specified input element is editable, ie hasn't been disabled. This method will fail if the specified element isn't an input element. 'locator' is an element locator """ return self.get_boolean("isEditable", [locator,]) def get_all_buttons(self): """ Returns the IDs of all buttons on the page. If a given button has no ID, it will appear as "" in this array. """ return self.get_string_array("getAllButtons", []) def get_all_links(self): """ Returns the IDs of all links on the page. If a given link has no ID, it will appear as "" in this array. """ return self.get_string_array("getAllLinks", []) def get_all_fields(self): """ Returns the IDs of all input fields on the page. If a given field has no ID, it will appear as "" in this array. """ return self.get_string_array("getAllFields", []) def get_attribute_from_all_windows(self,attributeName): """ Returns every instance of some attribute from all known windows. 'attributeName' is name of an attribute on the windows """ return self.get_string_array("getAttributeFromAllWindows", [attributeName,]) def dragdrop(self,locator,movementsString): """ deprecated - use dragAndDrop instead 'locator' is an element locator 'movementsString' is offset in pixels from the current location to which the element should be moved, e.g., "+70,-300" """ self.do_command("dragdrop", [locator,movementsString,]) def set_mouse_speed(self,pixels): """ Configure the number of pixels between "mousemove" events during dragAndDrop commands (default=10). Setting this value to 0 means that we'll send a "mousemove" event to every single pixel in between the start location and the end location; that can be very slow, and may cause some browsers to force the JavaScript to timeout. If the mouse speed is greater than the distance between the two dragged objects, we'll just send one "mousemove" at the start location and then one final one at the end location. 'pixels' is the number of pixels between "mousemove" events """ self.do_command("setMouseSpeed", [pixels,]) def get_mouse_speed(self): """ Returns the number of pixels between "mousemove" events during dragAndDrop commands (default=10). """ return self.get_number("getMouseSpeed", []) def drag_and_drop(self,locator,movementsString): """ Drags an element a certain distance and then drops it 'locator' is an element locator 'movementsString' is offset in pixels from the current location to which the element should be moved, e.g., "+70,-300" """ self.do_command("dragAndDrop", [locator,movementsString,]) def drag_and_drop_to_object(self,locatorOfObjectToBeDragged,locatorOfDragDestinationObject): """ Drags an element and drops it on another element 'locatorOfObjectToBeDragged' is an element to be dragged 'locatorOfDragDestinationObject' is an element whose location (i.e., whose center-most pixel) will be the point where locatorOfObjectToBeDragged is dropped """ self.do_command("dragAndDropToObject", [locatorOfObjectToBeDragged,locatorOfDragDestinationObject,]) def window_focus(self): """ Gives focus to the currently selected window """ self.do_command("windowFocus", []) def window_maximize(self): """ Resize currently selected window to take up the entire screen """ self.do_command("windowMaximize", []) def get_all_window_ids(self): """ Returns the IDs of all windows that the browser knows about. """ return self.get_string_array("getAllWindowIds", []) def get_all_window_names(self): """ Returns the names of all windows that the browser knows about. """ return self.get_string_array("getAllWindowNames", []) def get_all_window_titles(self): """ Returns the titles of all windows that the browser knows about. """ return self.get_string_array("getAllWindowTitles", []) def get_html_source(self): """ Returns the entire HTML source between the opening and closing "html" tags. """ return self.get_string("getHtmlSource", []) def set_cursor_position(self,locator,position): """ Moves the text cursor to the specified position in the given input element or textarea. This method will fail if the specified element isn't an input element or textarea. 'locator' is an element locator pointing to an input element or textarea 'position' is the numerical position of the cursor in the field; position should be 0 to move the position to the beginning of the field. You can also set the cursor to -1 to move it to the end of the field. """ self.do_command("setCursorPosition", [locator,position,]) def get_element_index(self,locator): """ Get the relative index of an element to its parent (starting from 0). The comment node and empty text node will be ignored. 'locator' is an element locator pointing to an element """ return self.get_number("getElementIndex", [locator,]) def is_ordered(self,locator1,locator2): """ Check if these two elements have same parent and are ordered siblings in the DOM. Two same elements will not be considered ordered. 'locator1' is an element locator pointing to the first element 'locator2' is an element locator pointing to the second element """ return self.get_boolean("isOrdered", [locator1,locator2,]) def get_element_position_left(self,locator): """ Retrieves the horizontal position of an element 'locator' is an element locator pointing to an element OR an element itself """ return self.get_number("getElementPositionLeft", [locator,]) def get_element_position_top(self,locator): """ Retrieves the vertical position of an element 'locator' is an element locator pointing to an element OR an element itself """ return self.get_number("getElementPositionTop", [locator,]) def get_element_width(self,locator): """ Retrieves the width of an element 'locator' is an element locator pointing to an element """ return self.get_number("getElementWidth", [locator,]) def get_element_height(self,locator): """ Retrieves the height of an element 'locator' is an element locator pointing to an element """ return self.get_number("getElementHeight", [locator,]) def get_cursor_position(self,locator): """ Retrieves the text cursor position in the given input element or textarea; beware, this may not work perfectly on all browsers. Specifically, if the cursor/selection has been cleared by JavaScript, this command will tend to return the position of the last location of the cursor, even though the cursor is now gone from the page. This is filed as SEL-243. This method will fail if the specified element isn't an input element or textarea, or there is no cursor in the element. 'locator' is an element locator pointing to an input element or textarea """ return self.get_number("getCursorPosition", [locator,]) def get_expression(self,expression): """ Returns the specified expression. This is useful because of JavaScript preprocessing. It is used to generate commands like assertExpression and waitForExpression. 'expression' is the value to return """ return self.get_string("getExpression", [expression,]) def get_xpath_count(self,xpath): """ Returns the number of nodes that match the specified xpath, eg. "//table" would give the number of tables. 'xpath' is the xpath expression to evaluate. do NOT wrap this expression in a 'count()' function; we will do that for you. """ return self.get_number("getXpathCount", [xpath,]) def get_css_count(self,css): """ Returns the number of nodes that match the specified css selector, eg. "css=table" would give the number of tables. 'css' is the css selector to evaluate. do NOT wrap this expression in a 'count()' function; we will do that for you. """ return self.get_number("getCssCount", [css,]) def assign_id(self,locator,identifier): """ Temporarily sets the "id" attribute of the specified element, so you can locate it in the future using its ID rather than a slow/complicated XPath. This ID will disappear once the page is reloaded. 'locator' is an element locator pointing to an element 'identifier' is a string to be used as the ID of the specified element """ self.do_command("assignId", [locator,identifier,]) def allow_native_xpath(self,allow): """ Specifies whether Selenium should use the native in-browser implementation of XPath (if any native version is available); if you pass "false" to this function, we will always use our pure-JavaScript xpath library. Using the pure-JS xpath library can improve the consistency of xpath element locators between different browser vendors, but the pure-JS version is much slower than the native implementations. 'allow' is boolean, true means we'll prefer to use native XPath; false means we'll only use JS XPath """ self.do_command("allowNativeXpath", [allow,]) def ignore_attributes_without_value(self,ignore): """ Specifies whether Selenium will ignore xpath attributes that have no value, i.e. are the empty string, when using the non-native xpath evaluation engine. You'd want to do this for performance reasons in IE. However, this could break certain xpaths, for example an xpath that looks for an attribute whose value is NOT the empty string. The hope is that such xpaths are relatively rare, but the user should have the option of using them. Note that this only influences xpath evaluation when using the ajaxslt engine (i.e. not "javascript-xpath"). 'ignore' is boolean, true means we'll ignore attributes without value at the expense of xpath "correctness"; false means we'll sacrifice speed for correctness. """ self.do_command("ignoreAttributesWithoutValue", [ignore,]) def wait_for_condition(self,script,timeout): """ Runs the specified JavaScript snippet repeatedly until it evaluates to "true". The snippet may have multiple lines, but only the result of the last line will be considered. Note that, by default, the snippet will be run in the runner's test window, not in the window of your application. To get the window of your application, you can use the JavaScript snippet ``selenium.browserbot.getCurrentWindow()``, and then run your JavaScript in there 'script' is the JavaScript snippet to run 'timeout' is a timeout in milliseconds, after which this command will return with an error """ self.do_command("waitForCondition", [script,timeout,]) def set_timeout(self,timeout): """ Specifies the amount of time that Selenium will wait for actions to complete. Actions that require waiting include "open" and the "waitFor\*" actions. The default timeout is 30 seconds. 'timeout' is a timeout in milliseconds, after which the action will return with an error """ self.do_command("setTimeout", [timeout,]) def wait_for_page_to_load(self,timeout): """ Waits for a new page to load. You can use this command instead of the "AndWait" suffixes, "clickAndWait", "selectAndWait", "typeAndWait" etc. (which are only available in the JS API). Selenium constantly keeps track of new pages loading, and sets a "newPageLoaded" flag when it first notices a page load. Running any other Selenium command after turns the flag to false. Hence, if you want to wait for a page to load, you must wait immediately after a Selenium command that caused a page-load. 'timeout' is a timeout in milliseconds, after which this command will return with an error """ self.do_command("waitForPageToLoad", [timeout,]) def wait_for_frame_to_load(self,frameAddress,timeout): """ Waits for a new frame to load. Selenium constantly keeps track of new pages and frames loading, and sets a "newPageLoaded" flag when it first notices a page load. See waitForPageToLoad for more information. 'frameAddress' is FrameAddress from the server side 'timeout' is a timeout in milliseconds, after which this command will return with an error """ self.do_command("waitForFrameToLoad", [frameAddress,timeout,]) def get_cookie(self): """ Return all cookies of the current page under test. """ return self.get_string("getCookie", []) def get_cookie_by_name(self,name): """ Returns the value of the cookie with the specified name, or throws an error if the cookie is not present. 'name' is the name of the cookie """ return self.get_string("getCookieByName", [name,]) def is_cookie_present(self,name): """ Returns true if a cookie with the specified name is present, or false otherwise. 'name' is the name of the cookie """ return self.get_boolean("isCookiePresent", [name,]) def create_cookie(self,nameValuePair,optionsString): """ Create a new cookie whose path and domain are same with those of current page under test, unless you specified a path for this cookie explicitly. 'nameValuePair' is name and value of the cookie in a format "name=value" 'optionsString' is options for the cookie. Currently supported options include 'path', 'max_age' and 'domain'. the optionsString's format is "path=/path/, max_age=60, domain=.foo.com". The order of options are irrelevant, the unit of the value of 'max_age' is second. Note that specifying a domain that isn't a subset of the current domain will usually fail. """ self.do_command("createCookie", [nameValuePair,optionsString,]) def delete_cookie(self,name,optionsString): """ Delete a named cookie with specified path and domain. Be careful; to delete a cookie, you need to delete it using the exact same path and domain that were used to create the cookie. If the path is wrong, or the domain is wrong, the cookie simply won't be deleted. Also note that specifying a domain that isn't a subset of the current domain will usually fail. Since there's no way to discover at runtime the original path and domain of a given cookie, we've added an option called 'recurse' to try all sub-domains of the current domain with all paths that are a subset of the current path. Beware; this option can be slow. In big-O notation, it operates in O(n\*m) time, where n is the number of dots in the domain name and m is the number of slashes in the path. 'name' is the name of the cookie to be deleted 'optionsString' is options for the cookie. Currently supported options include 'path', 'domain' and 'recurse.' The optionsString's format is "path=/path/, domain=.foo.com, recurse=true". The order of options are irrelevant. Note that specifying a domain that isn't a subset of the current domain will usually fail. """ self.do_command("deleteCookie", [name,optionsString,]) def delete_all_visible_cookies(self): """ Calls deleteCookie with recurse=true on all cookies visible to the current page. As noted on the documentation for deleteCookie, recurse=true can be much slower than simply deleting the cookies using a known domain/path. """ self.do_command("deleteAllVisibleCookies", []) def set_browser_log_level(self,logLevel): """ Sets the threshold for browser-side logging messages; log messages beneath this threshold will be discarded. Valid logLevel strings are: "debug", "info", "warn", "error" or "off". To see the browser logs, you need to either show the log window in GUI mode, or enable browser-side logging in Selenium RC. 'logLevel' is one of the following: "debug", "info", "warn", "error" or "off" """ self.do_command("setBrowserLogLevel", [logLevel,]) def run_script(self,script): """ Creates a new "script" tag in the body of the current test window, and adds the specified text into the body of the command. Scripts run in this way can often be debugged more easily than scripts executed using Selenium's "getEval" command. Beware that JS exceptions thrown in these script tags aren't managed by Selenium, so you should probably wrap your script in try/catch blocks if there is any chance that the script will throw an exception. 'script' is the JavaScript snippet to run """ self.do_command("runScript", [script,]) def add_location_strategy(self,strategyName,functionDefinition): """ Defines a new function for Selenium to locate elements on the page. For example, if you define the strategy "foo", and someone runs click("foo=blah"), we'll run your function, passing you the string "blah", and click on the element that your function returns, or throw an "Element not found" error if your function returns null. We'll pass three arguments to your function: * locator: the string the user passed in * inWindow: the currently selected window * inDocument: the currently selected document The function must return null if the element can't be found. 'strategyName' is the name of the strategy to define; this should use only letters [a-zA-Z] with no spaces or other punctuation. 'functionDefinition' is a string defining the body of a function in JavaScript. For example: ``return inDocument.getElementById(locator);`` """ self.do_command("addLocationStrategy", [strategyName,functionDefinition,]) def capture_entire_page_screenshot(self,filename,kwargs): """ Saves the entire contents of the current window canvas to a PNG file. Contrast this with the captureScreenshot command, which captures the contents of the OS viewport (i.e. whatever is currently being displayed on the monitor), and is implemented in the RC only. Currently this only works in Firefox when running in chrome mode, and in IE non-HTA using the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly borrowed from the Screengrab! Firefox extension. Please see http://www.screengrab.org and http://snapsie.sourceforge.net/ for details. 'filename' is the path to the file to persist the screenshot as. No filename extension will be appended by default. Directories will not be created if they do not exist, and an exception will be thrown, possibly by native code. 'kwargs' is a kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD" Currently valid options: * background the background CSS for the HTML document. This may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas dimension to fail and a black background is exposed (possibly obscuring black text). """ self.do_command("captureEntirePageScreenshot", [filename,kwargs,]) def rollup(self,rollupName,kwargs): """ Executes a command rollup, which is a series of commands with a unique name, and optionally arguments that control the generation of the set of commands. If any one of the rolled-up commands fails, the rollup is considered to have failed. Rollups may also contain nested rollups. 'rollupName' is the name of the rollup command 'kwargs' is keyword arguments string that influences how the rollup expands into commands """ self.do_command("rollup", [rollupName,kwargs,]) def add_script(self,scriptContent,scriptTagId): """ Loads script content into a new script tag in the Selenium document. This differs from the runScript command in that runScript adds the script tag to the document of the AUT, not the Selenium document. The following entities in the script content are replaced by the characters they represent: &lt; &gt; &amp; The corresponding remove command is removeScript. 'scriptContent' is the Javascript content of the script to add 'scriptTagId' is (optional) the id of the new script tag. If specified, and an element with this id already exists, this operation will fail. """ self.do_command("addScript", [scriptContent,scriptTagId,]) def remove_script(self,scriptTagId): """ Removes a script tag from the Selenium document identified by the given id. Does nothing if the referenced tag doesn't exist. 'scriptTagId' is the id of the script element to remove. """ self.do_command("removeScript", [scriptTagId,]) def use_xpath_library(self,libraryName): """ Allows choice of one of the available libraries. 'libraryName' is name of the desired library Only the following three can be chosen: * "ajaxslt" - Google's library * "javascript-xpath" - Cybozu Labs' faster library * "default" - The default library. Currently the default library is "ajaxslt" . If libraryName isn't one of these three, then no change will be made. """ self.do_command("useXpathLibrary", [libraryName,]) def set_context(self,context): """ Writes a message to the status bar and adds a note to the browser-side log. 'context' is the message to be sent to the browser """ self.do_command("setContext", [context,]) def attach_file(self,fieldLocator,fileLocator): """ Sets a file input (upload) field to the file listed in fileLocator 'fieldLocator' is an element locator 'fileLocator' is a URL pointing to the specified file. Before the file can be set in the input field (fieldLocator), Selenium RC may need to transfer the file to the local machine before attaching the file in a web page form. This is common in selenium grid configurations where the RC server driving the browser is not the same machine that started the test. Supported Browsers: Firefox ("\*chrome") only. """ self.do_command("attachFile", [fieldLocator,fileLocator,]) def capture_screenshot(self,filename): """ Captures a PNG screenshot to the specified file. 'filename' is the absolute path to the file to be written, e.g. "c:\blah\screenshot.png" """ self.do_command("captureScreenshot", [filename,]) def capture_screenshot_to_string(self): """ Capture a PNG screenshot. It then returns the file as a base 64 encoded string. """ return self.get_string("captureScreenshotToString", []) def captureNetworkTraffic(self, type): """ Returns the network traffic seen by the browser, including headers, AJAX requests, status codes, and timings. When this function is called, the traffic log is cleared, so the returned content is only the traffic seen since the last call. 'type' is The type of data to return the network traffic as. Valid values are: json, xml, or plain. """ return self.get_string("captureNetworkTraffic", [type,]) def capture_network_traffic(self, type): return self.captureNetworkTraffic(type) def addCustomRequestHeader(self, key, value): """ Tells the Selenium server to add the specificed key and value as a custom outgoing request header. This only works if the browser is configured to use the built in Selenium proxy. 'key' the header name. 'value' the header value. """ return self.do_command("addCustomRequestHeader", [key,value,]) def add_custom_request_header(self, key, value): return self.addCustomRequestHeader(key, value) def capture_entire_page_screenshot_to_string(self,kwargs): """ Downloads a screenshot of the browser current window canvas to a based 64 encoded PNG file. The \ *entire* windows canvas is captured, including parts rendered outside of the current view port. Currently this only works in Mozilla and when running in chrome mode. 'kwargs' is A kwargs string that modifies the way the screenshot is captured. Example: "background=#CCFFDD". This may be useful to set for capturing screenshots of less-than-ideal layouts, for example where absolute positioning causes the calculation of the canvas dimension to fail and a black background is exposed (possibly obscuring black text). """ return self.get_string("captureEntirePageScreenshotToString", [kwargs,]) def shut_down_selenium_server(self): """ Kills the running Selenium Server and all browser sessions. After you run this command, you will no longer be able to send commands to the server; you can't remotely start the server once it has been stopped. Normally you should prefer to run the "stop" command, which terminates the current browser session, rather than shutting down the entire server. """ self.do_command("shutDownSeleniumServer", []) def retrieve_last_remote_control_logs(self): """ Retrieve the last messages logged on a specific remote control. Useful for error reports, especially when running multiple remote controls in a distributed environment. The maximum number of log messages that can be retrieve is configured on remote control startup. """ return self.get_string("retrieveLastRemoteControlLogs", []) def key_down_native(self,keycode): """ Simulates a user pressing a key (without releasing it yet) by sending a native operating system keystroke. This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular element, focus on the element first before running this command. 'keycode' is an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes! """ self.do_command("keyDownNative", [keycode,]) def key_up_native(self,keycode): """ Simulates a user releasing a key by sending a native operating system keystroke. This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular element, focus on the element first before running this command. 'keycode' is an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes! """ self.do_command("keyUpNative", [keycode,]) def key_press_native(self,keycode): """ Simulates a user pressing and releasing a key by sending a native operating system keystroke. This function uses the java.awt.Robot class to send a keystroke; this more accurately simulates typing a key on the keyboard. It does not honor settings from the shiftKeyDown, controlKeyDown, altKeyDown and metaKeyDown commands, and does not target any particular HTML element. To send a keystroke to a particular element, focus on the element first before running this command. 'keycode' is an integer keycode number corresponding to a java.awt.event.KeyEvent; note that Java keycodes are NOT the same thing as JavaScript keycodes! """ self.do_command("keyPressNative", [keycode,])
nattee/cafe-grader-web
refs/heads/master
lib/assets/Lib/_dummy_thread.py
14
"""Drop-in replacement for the thread module. Meant to be used as a brain-dead substitute so that threaded code does not need to be rewritten for when the thread module is not present. Suggested usage is:: try: import _thread except ImportError: import _dummy_thread as _thread """ # Exports only things specified by thread documentation; # skipping obsolete synonyms allocate(), start_new(), exit_thread(). __all__ = ['error', 'start_new_thread', 'exit', 'get_ident', 'allocate_lock', 'interrupt_main', 'LockType'] # A dummy value TIMEOUT_MAX = 2**31 # NOTE: this module can be imported early in the extension building process, # and so top level imports of other modules should be avoided. Instead, all # imports are done when needed on a function-by-function basis. Since threads # are disabled, the import lock should not be an issue anyway (??). error = RuntimeError def start_new_thread(function, args, kwargs={}): """Dummy implementation of _thread.start_new_thread(). Compatibility is maintained by making sure that ``args`` is a tuple and ``kwargs`` is a dictionary. If an exception is raised and it is SystemExit (which can be done by _thread.exit()) it is caught and nothing is done; all other exceptions are printed out by using traceback.print_exc(). If the executed function calls interrupt_main the KeyboardInterrupt will be raised when the function returns. """ if type(args) != type(tuple()): raise TypeError("2nd arg must be a tuple") if type(kwargs) != type(dict()): raise TypeError("3rd arg must be a dict") global _main _main = False try: function(*args, **kwargs) except SystemExit: pass except: import traceback traceback.print_exc() _main = True global _interrupt if _interrupt: _interrupt = False raise KeyboardInterrupt def exit(): """Dummy implementation of _thread.exit().""" raise SystemExit def get_ident(): """Dummy implementation of _thread.get_ident(). Since this module should only be used when _threadmodule is not available, it is safe to assume that the current process is the only thread. Thus a constant can be safely returned. """ return -1 def allocate_lock(): """Dummy implementation of _thread.allocate_lock().""" return LockType() def stack_size(size=None): """Dummy implementation of _thread.stack_size().""" if size is not None: raise error("setting thread stack size not supported") return 0 class LockType(object): """Class implementing dummy implementation of _thread.LockType. Compatibility is maintained by maintaining self.locked_status which is a boolean that stores the state of the lock. Pickling of the lock, though, should not be done since if the _thread module is then used with an unpickled ``lock()`` from here problems could occur from this class not having atomic methods. """ def __init__(self): self.locked_status = False def acquire(self, waitflag=None, timeout=-1): """Dummy implementation of acquire(). For blocking calls, self.locked_status is automatically set to True and returned appropriately based on value of ``waitflag``. If it is non-blocking, then the value is actually checked and not set if it is already acquired. This is all done so that threading.Condition's assert statements aren't triggered and throw a little fit. """ if waitflag is None or waitflag: self.locked_status = True return True else: if not self.locked_status: self.locked_status = True return True else: if timeout > 0: import time time.sleep(timeout) return False __enter__ = acquire def __exit__(self, typ, val, tb): self.release() def release(self): """Release the dummy lock.""" # XXX Perhaps shouldn't actually bother to test? Could lead # to problems for complex, threaded code. if not self.locked_status: raise error self.locked_status = False return True def locked(self): return self.locked_status # Used to signal that interrupt_main was called in a "thread" _interrupt = False # True when not executing in a "thread" _main = True def interrupt_main(): """Set _interrupt flag to True to have start_new_thread raise KeyboardInterrupt upon exiting.""" if _main: raise KeyboardInterrupt else: global _interrupt _interrupt = True
hmcmooc/muddx-platform
refs/heads/master
cms/djangoapps/contentstore/management/commands/course_id_clash.py
29
""" Script for finding all courses whose org/name pairs == other courses when ignoring case """ from django.core.management.base import BaseCommand from xmodule.modulestore.django import modulestore # # To run from command line: ./manage.py cms --settings dev course_id_clash # class Command(BaseCommand): """ Script for finding all courses whose org/name pairs == other courses when ignoring case """ help = 'List all courses ids which may collide when ignoring case' def handle(self, *args, **options): mstore = modulestore() if hasattr(mstore, 'collection'): map_fn = ''' function () { emit(this._id.org.toLowerCase()+this._id.course.toLowerCase(), {target: this._id}); } ''' reduce_fn = ''' function (idpair, matches) { var result = {target: []}; matches.forEach(function (match) { result.target.push(match.target); }); return result; } ''' finalize = ''' function(key, reduced) { if (Array.isArray(reduced.target)) { return reduced; } else {return null;} } ''' results = mstore.collection.map_reduce( map_fn, reduce_fn, {'inline': True}, query={'_id.category': 'course'}, finalize=finalize ) results = results.get('results') for entry in results: if entry.get('value') is not None: print '{:-^40}'.format(entry.get('_id')) for course_id in entry.get('value').get('target'): print ' {}/{}/{}'.format(course_id.get('org'), course_id.get('course'), course_id.get('name'))
pelson/numpy
refs/heads/master
numpy/f2py/use_rules.py
48
#!/usr/bin/env python """ Build 'use others module data' mechanism for f2py2e. Unfinished. Copyright 2000 Pearu Peterson all rights reserved, Pearu Peterson <pearu@ioc.ee> Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2000/09/10 12:35:43 $ Pearu Peterson """ __version__ = "$Revision: 1.3 $"[10:-1] f2py_version='See `f2py -v`' import pprint import sys errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint from auxfuncs import * ############## usemodule_rules={ 'body':""" #begintitle# static char doc_#apiname#[] = \"\\\nVariable wrapper signature:\\n\\ \t #name# = get_#name#()\\n\\ Arguments:\\n\\ #docstr#\"; extern F_MODFUNC(#usemodulename#,#USEMODULENAME#,#realname#,#REALNAME#); static PyObject *#apiname#(PyObject *capi_self, PyObject *capi_args) { /*#decl#*/ \tif (!PyArg_ParseTuple(capi_args, \"\")) goto capi_fail; printf(\"c: %d\\n\",F_MODFUNC(#usemodulename#,#USEMODULENAME#,#realname#,#REALNAME#)); \treturn Py_BuildValue(\"\"); capi_fail: \treturn NULL; } """, 'method':'\t{\"get_#name#\",#apiname#,METH_VARARGS|METH_KEYWORDS,doc_#apiname#},', 'need':['F_MODFUNC'] } ################ def buildusevars(m,r): ret={} outmess('\t\tBuilding use variable hooks for module "%s" (feature only for F90/F95)...\n'%(m['name'])) varsmap={} revmap={} if 'map' in r: for k in r['map'].keys(): if r['map'][k] in revmap: outmess('\t\t\tVariable "%s<=%s" is already mapped by "%s". Skipping.\n'%(r['map'][k],k,revmap[r['map'][k]])) else: revmap[r['map'][k]]=k if 'only' in r and r['only']: for v in r['map'].keys(): if r['map'][v] in m['vars']: if revmap[r['map'][v]]==v: varsmap[v]=r['map'][v] else: outmess('\t\t\tIgnoring map "%s=>%s". See above.\n'%(v,r['map'][v])) else: outmess('\t\t\tNo definition for variable "%s=>%s". Skipping.\n'%(v,r['map'][v])) else: for v in m['vars'].keys(): if v in revmap: varsmap[v]=revmap[v] else: varsmap[v]=v for v in varsmap.keys(): ret=dictappend(ret,buildusevar(v,varsmap[v],m['vars'],m['name'])) return ret def buildusevar(name,realname,vars,usemodulename): outmess('\t\t\tConstructing wrapper function for variable "%s=>%s"...\n'%(name,realname)) ret={} vrd={'name':name, 'realname':realname, 'REALNAME':realname.upper(), 'usemodulename':usemodulename, 'USEMODULENAME':usemodulename.upper(), 'texname':name.replace('_','\\_'), 'begintitle':gentitle('%s=>%s'%(name,realname)), 'endtitle':gentitle('end of %s=>%s'%(name,realname)), 'apiname':'#modulename#_use_%s_from_%s'%(realname,usemodulename) } nummap={0:'Ro',1:'Ri',2:'Rii',3:'Riii',4:'Riv',5:'Rv',6:'Rvi',7:'Rvii',8:'Rviii',9:'Rix'} vrd['texnamename']=name for i in nummap.keys(): vrd['texnamename']=vrd['texnamename'].replace(`i`,nummap[i]) if hasnote(vars[realname]): vrd['note']=vars[realname]['note'] rd=dictappend({},vrd) var=vars[realname] print name,realname,vars[realname] ret=applyrules(usemodule_rules,rd) return ret
shaneob/django_tutorial_blog_ng
refs/heads/master
blogengine/views.py
1
from django.shortcuts import render from django.views.generic import ListView from blogengine.models import Category, Post, Tag from django.contrib.syndication.views import Feed # Create your views here. class CategoryListView(ListView): def get_queryset(self): slug = self.kwargs['slug'] try: category = Category.objects.get(slug=slug) return Post.objects.filter(category=category) except Category.DoesNotExist: return Post.objects.none() class TagListView(ListView): def get_queryset(self): slug = self.kwargs['slug'] try: tag = Tag.objects.get(slug=slug) return tag.post_set.all() except Tag.DoesNotExist: return Post.objects.none() class PostsFeed(Feed): title = "RSS feed - posts" link = "feeds/posts/" description = "RSS feed - blog posts" def items(self): return Post.objects.order_by('-pub_date') def item_title(self, item): return item.title def item_description(self, item): return item.text
ToqueWillot/M2DAC
refs/heads/master
RDFIA/codesTME3-4/learning/libsvm/python/svmutil.py
13
#!/usr/bin/env python from svm import * def svm_read_problem(data_file_name): """ svm_read_problem(data_file_name) -> [y, x] Read LIBSVM-format data from data_file_name and return labels y and data instances x. """ prob_y = [] prob_x = [] for line in open(data_file_name): line = line.split(None, 1) # In case an instance with all zero features if len(line) == 1: line += [''] label, features = line xi = {} for e in features.split(): ind, val = e.split(":") xi[int(ind)] = float(val) prob_y += [float(label)] prob_x += [xi] return (prob_y, prob_x) def svm_load_model(model_file_name): """ svm_load_model(model_file_name) -> model Load a LIBSVM model from model_file_name and return. """ model = libsvm.svm_load_model(model_file_name) if not model: print("can't open model file %s" % model_file_name) return None model = toPyModel(model) return model def svm_save_model(model_file_name, model): """ svm_save_model(model_file_name, model) -> None Save a LIBSVM model to the file model_file_name. """ libsvm.svm_save_model(model_file_name, model) def evaluations(ty, pv): """ evaluations(ty, pv) -> (ACC, MSE, SCC) Calculate accuracy, mean squared error and squared correlation coefficient using the true values (ty) and predicted values (pv). """ if len(ty) != len(pv): raise ValueError("len(ty) must equal to len(pv)") total_correct = total_error = 0 sumv = sumy = sumvv = sumyy = sumvy = 0 for v, y in zip(pv, ty): if y == v: total_correct += 1 total_error += (v-y)*(v-y) sumv += v sumy += y sumvv += v*v sumyy += y*y sumvy += v*y l = len(ty) ACC = 100.0*total_correct/l MSE = total_error/l try: SCC = ((l*sumvy-sumv*sumy)*(l*sumvy-sumv*sumy))/((l*sumvv-sumv*sumv)*(l*sumyy-sumy*sumy)) except: SCC = float('nan') return (ACC, MSE, SCC) def svm_train(arg1, arg2=None, arg3=None): """ svm_train(y, x [, 'options']) -> model | ACC | MSE svm_train(prob, [, 'options']) -> model | ACC | MSE svm_train(prob, param) -> model | ACC| MSE Train an SVM model from data (y, x) or an svm_problem prob using 'options' or an svm_parameter param. If '-v' is specified in 'options' (i.e., cross validation) either accuracy (ACC) or mean-squared error (MSE) is returned. 'options': -s svm_type : set type of SVM (default 0) 0 -- C-SVC 1 -- nu-SVC 2 -- one-class SVM 3 -- epsilon-SVR 4 -- nu-SVR -t kernel_type : set type of kernel function (default 2) 0 -- linear: u'*v 1 -- polynomial: (gamma*u'*v + coef0)^degree 2 -- radial basis function: exp(-gamma*|u-v|^2) 3 -- sigmoid: tanh(gamma*u'*v + coef0) 4 -- precomputed kernel (kernel values in training_set_file) -d degree : set degree in kernel function (default 3) -g gamma : set gamma in kernel function (default 1/num_features) -r coef0 : set coef0 in kernel function (default 0) -c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1) -n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5) -p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1) -m cachesize : set cache memory size in MB (default 100) -e epsilon : set tolerance of termination criterion (default 0.001) -h shrinking : whether to use the shrinking heuristics, 0 or 1 (default 1) -b probability_estimates : whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0) -wi weight : set the parameter C of class i to weight*C, for C-SVC (default 1) -v n: n-fold cross validation mode -q : quiet mode (no outputs) """ prob, param = None, None if isinstance(arg1, (list, tuple)): assert isinstance(arg2, (list, tuple)) y, x, options = arg1, arg2, arg3 prob = svm_problem(y, x) param = svm_parameter(options) elif isinstance(arg1, svm_problem): prob = arg1 if isinstance(arg2, svm_parameter): param = arg2 else: param = svm_parameter(arg2) if prob == None or param == None: raise TypeError("Wrong types for the arguments") if param.kernel_type == PRECOMPUTED: for xi in prob.x_space: idx, val = xi[0].index, xi[0].value if xi[0].index != 0: raise ValueError('Wrong input format: first column must be 0:sample_serial_number') if val <= 0 or val > prob.n: raise ValueError('Wrong input format: sample_serial_number out of range') if param.gamma == 0 and prob.n > 0: param.gamma = 1.0 / prob.n libsvm.svm_set_print_string_function(param.print_func) err_msg = libsvm.svm_check_parameter(prob, param) if err_msg: raise ValueError('Error: %s' % err_msg) if param.cross_validation: l, nr_fold = prob.l, param.nr_fold target = (c_double * l)() libsvm.svm_cross_validation(prob, param, nr_fold, target) ACC, MSE, SCC = evaluations(prob.y[:l], target[:l]) if param.svm_type in [EPSILON_SVR, NU_SVR]: print("Cross Validation Mean squared error = %g" % MSE) print("Cross Validation Squared correlation coefficient = %g" % SCC) return MSE else: print("Cross Validation Accuracy = %g%%" % ACC) return ACC else: m = libsvm.svm_train(prob, param) m = toPyModel(m) # If prob is destroyed, data including SVs pointed by m can remain. m.x_space = prob.x_space return m def svm_predict(y, x, m, options=""): """ svm_predict(y, x, m [, "options"]) -> (p_labels, p_acc, p_vals) Predict data (y, x) with the SVM model m. "options": -b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); for one-class SVM only 0 is supported. The return tuple contains p_labels: a list of predicted labels p_acc: a tuple including accuracy (for classification), mean-squared error, and squared correlation coefficient (for regression). p_vals: a list of decision values or probability estimates (if '-b 1' is specified). If k is the number of classes, for decision values, each element includes results of predicting k(k-1)/2 binary-class SVMs. For probabilities, each element contains k values indicating the probability that the testing instance is in each class. Note that the order of classes here is the same as 'model.label' field in the model structure. """ predict_probability = 0 argv = options.split() i = 0 while i < len(argv): if argv[i] == '-b': i += 1 predict_probability = int(argv[i]) else: raise ValueError("Wrong options") i+=1 svm_type = m.get_svm_type() is_prob_model = m.is_probability_model() nr_class = m.get_nr_class() pred_labels = [] pred_values = [] if predict_probability: if not is_prob_model: raise ValueError("Model does not support probabiliy estimates") if svm_type in [NU_SVR, EPSILON_SVR]: print("Prob. model for test data: target value = predicted value + z,\n" "z: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma=%g" % m.get_svr_probability()); nr_class = 0 prob_estimates = (c_double * nr_class)() for xi in x: xi, idx = gen_svm_nodearray(xi) label = libsvm.svm_predict_probability(m, xi, prob_estimates) values = prob_estimates[:nr_class] pred_labels += [label] pred_values += [values] else: if is_prob_model: print("Model supports probability estimates, but disabled in predicton.") if svm_type in (ONE_CLASS, EPSILON_SVR, NU_SVC): nr_classifier = 1 else: nr_classifier = nr_class*(nr_class-1)//2 dec_values = (c_double * nr_classifier)() for xi in x: xi, idx = gen_svm_nodearray(xi) label = libsvm.svm_predict_values(m, xi, dec_values) if(nr_class == 1): values = [1] else: values = dec_values[:nr_classifier] pred_labels += [label] pred_values += [values] ACC, MSE, SCC = evaluations(y, pred_labels) l = len(y) if svm_type in [EPSILON_SVR, NU_SVR]: print("Mean squared error = %g (regression)" % MSE) print("Squared correlation coefficient = %g (regression)" % SCC) else: print("Accuracy = %g%% (%d/%d) (classification)" % (ACC, int(l*ACC/100), l)) return pred_labels, (ACC, MSE, SCC), pred_values
m0re4u/SmartLight
refs/heads/master
client/modules/always_on.py
1
def light_on(config): return True, True, True if __name__ == '__main__': import yaml with open('../config.yml') as f: config = yaml.load(f) print(light_on(config))
ibmjstart/bluemix-python-eve-sample
refs/heads/master
macreduce/tests/eve_docs_tests.py
2
#!/usr/bin/env python """Contains the Unit Tests for the REST Resources. Contains the Unit Tests for exercising all provided API Endpoints for the Python Eve REST Server """ import requests __author__ = "Sanjay Joshi" __copyright__ = "Copyright 2016 IBM" __credits__ = ["Sanjay Joshi"] __license__ = "Apache 2.0" __version__ = "1.0" __maintainer__ = "Sanjay Joshi" __email__ = "joshisa@us.ibm.com" __status__ = "Demo" ROOT_TEST_URL = 'http://localhost:5005' DOC_PATH = '/docs' def test_base_eve_docs_no_content_type_response(): """ Read Base EVE DOCS URL without Content Type""" url = ''.join([ROOT_TEST_URL, DOC_PATH]) headers = {} r = requests.get(url, headers=headers) assert r.status_code == requests.codes.ok # 200
retrogradeorbit/Pigo
refs/heads/master
pigo/gfx/Tex.py
1
from Texture import Texture import weakref class Tex: """A Tex is a window into a small part of a Texture. Successive Tex's can spell out an animation for a sprite to follow. Or a tex could have its offsets moved slowly over time to create special scaling and scrolling effects. """ def __init__(self, texture, x=0, y=0, width=None, height=None): #this is a weak ref so when our parent texture dies, we signal it here by setting to None #in this way each Tex is tied to a texture. Different textures shareing the same Tex behavoir? #make them different Tex()s self.texture=weakref.ref(texture, lambda x: self.ClearTexture()) self.x=x self.y=y self.width=width self.height=height if width==None: self.width=self.texture().originalwidth if height==None: self.height=self.texture().originalheight def __str__(self): return "%s, %s, %s, %s, %s"%(str(self.texture()),str(self.x),str(self.y),str(self.width),str(self.height)) def ClearTexture(self): self.texture=None # texture co-ordinates def GetU0(self): return float(self.x) / self.texture().width def GetU1(self): return float(self.x + self.width) / self.texture().width def GetV0(self): return float(self.y) / self.texture().height def GetV1(self): return float(self.y + self.height) / self.texture().height def GetExtents(self): return ( self.GetU0(), self.GetV0(), self.GetU1(), self.GetV1() )
samuto/Honeybee
refs/heads/master
src/Honeybee_open Pollination.py
1
# Open Pollination Website # # Honeybee: A Plugin for Environmental Analysis (GPL) started by Mostapha Sadeghipour Roudsari # # This file is part of Honeybee. # # Copyright (c) 2013-2015, Mostapha Sadeghipour Roudsari <Sadeghipour@gmail.com> # Honeybee 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. # # Honeybee 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 Honeybee; If not, see <http://www.gnu.org/licenses/>. # # @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+> """ Use this component to open the Pollination page - Provided by Honeybee 0.0.57 Args: _download: Set Boolean to True to open the Pollination page """ ghenv.Component.Name = "Honeybee_open Pollination" ghenv.Component.NickName = 'OpenPollination' ghenv.Component.Message = 'VER 0.0.57\nJUL_06_2015' ghenv.Component.Category = "Honeybee" ghenv.Component.SubCategory = "12 | WIP" #compatibleHBVersion = VER 0.0.56\nFEB_01_2015 try: ghenv.Component.AdditionalHelpFromDocStrings = "1" except: pass import webbrowser as wb import Grasshopper.Kernel as gh if _open: url = 'http://mostapharoudsari.github.io/Honeybee/Pollination' wb.open(url,2,True) print 'Vviiiiiiiizzzzz!' else: msg = 'Set open to true...' ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, msg) print msg
shot/hadoop-source-reading
refs/heads/master
src/contrib/hod/testing/testHodCleanup.py
182
#Licensed to the Apache Software Foundation (ASF) under one #or more contributor license agreements. See the NOTICE file #distributed with this work for additional information #regarding copyright ownership. The ASF licenses this file #to you under the Apache License, Version 2.0 (the #"License"); you may not use this file except in compliance #with the License. You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 #Unless required by applicable law or agreed to in writing, software #distributed under the License is distributed on an "AS IS" BASIS, #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #See the License for the specific language governing permissions and #limitations under the License. import unittest, os, sys, re, threading, time myDirectory = os.path.realpath(sys.argv[0]) rootDirectory = re.sub("/testing/.*", "", myDirectory) sys.path.append(rootDirectory) from testing.lib import BaseTestSuite from hodlib.HodRing.hodRing import MRSystemDirectoryManager, createMRSystemDirectoryManager from hodlib.Common.threads import simpleCommand excludes = [] # duplicating temporarily until HADOOP-2848 is committed. class MyMockLogger: def __init__(self): self.__logLines = {} def info(self, message): self.__logLines[message] = 'info' def critical(self, message): self.__logLines[message] = 'critical' def warn(self, message): self.__logLines[message] = 'warn' def debug(self, message): # don't track debug lines. pass # verify a certain message has been logged at the defined level of severity. def hasMessage(self, message, level): if not self.__logLines.has_key(message): return False return self.__logLines[message] == level class test_MRSystemDirectoryManager(unittest.TestCase): def setUp(self): self.log = MyMockLogger() def testCleanupArgsString(self): sysDirMgr = MRSystemDirectoryManager(1234, '/user/hod/mapredsystem/hoduser.123.abc.com', \ 'def.com:5678', '/usr/bin/hadoop', self.log) str = sysDirMgr.toCleanupArgs() self.assertTrue(" --jt-pid 1234 --mr-sys-dir /user/hod/mapredsystem/hoduser.123.abc.com --fs-name def.com:5678 --hadoop-path /usr/bin/hadoop ", str) def testCreateMRSysDirInvalidParams(self): # test that no mr system directory manager is created if required keys are not present # this case will test scenarios of non jobtracker daemons. keys = [ 'jt-pid', 'mr-sys-dir', 'fs-name', 'hadoop-path' ] map = { 'jt-pid' : 1234, 'mr-sys-dir' : '/user/hod/mapredsystem/hoduser.def.com', 'fs-name' : 'ghi.com:1234', 'hadoop-path' : '/usr/bin/hadoop' } for key in keys: val = map[key] map[key] = None self.assertEquals(createMRSystemDirectoryManager(map, self.log), None) map[key] = val def testUnresponsiveJobTracker(self): # simulate an unresponsive job tracker, by giving a command that runs longer than the retries # verify that the program returns with the right error message. sc = simpleCommand("sleep", "sleep 300") sc.start() pid = sc.getPid() while pid is None: pid = sc.getPid() sysDirMgr = MRSystemDirectoryManager(pid, '/user/yhemanth/mapredsystem/hoduser.123.abc.com', \ 'def.com:5678', '/usr/bin/hadoop', self.log, retries=3) sysDirMgr.removeMRSystemDirectory() self.log.hasMessage("Job Tracker did not exit even after a minute. Not going to try and cleanup the system directory", 'warn') sc.kill() sc.wait() sc.join() class HodCleanupTestSuite(BaseTestSuite): def __init__(self): # suite setup BaseTestSuite.__init__(self, __name__, excludes) pass def cleanUp(self): # suite tearDown pass def RunHodCleanupTests(): # modulename_suite suite = HodCleanupTestSuite() testResult = suite.runTests() suite.cleanUp() return testResult if __name__ == "__main__": RunHodCleanupTests()
sam-m888/addons-source
refs/heads/master
SetPrivacyTool/SetPrivacyTool.gpr.py
1
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2019 Matthias Kemmer <matt.familienforschung@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 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. # register(TOOL, id = 'SetPrivacyTool', name = _("Set Privacy Tool"), description = _("Set all objects of the last <number> of years private."), version = '1.0.2', gramps_target_version = "5.1", status = STABLE, fname = 'SetPrivacyTool.py', authors = ["Matthias Kemmer"], authors_email = ["matt.familienforschung@gmail.com"], category = TOOL_DBPROC, toolclass = 'SetPrivacyWindow', optionclass = 'SetPrivacyOptions', tool_modes = [TOOL_MODE_GUI], )
bbende/nifi
refs/heads/master
nifi-nar-bundles/nifi-scripting-bundle/nifi-scripting-processors/src/test/resources/jython/test_update_attribute.py
37
#! /usr/bin/python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import sys import traceback from org.apache.nifi.processor import Processor from org.apache.nifi.processor import Relationship from org.apache.nifi.components import PropertyDescriptor from org.apache.nifi.processor.util import StandardValidators class UpdateAttributes(Processor) : __rel_success = Relationship.Builder().description("Success").name("success").build() def __init__(self) : pass def initialize(self, context) : pass def getRelationships(self) : return set([self.__rel_success]) def validate(self, context) : pass def getPropertyDescriptors(self) : descriptor = PropertyDescriptor.Builder().name("for-attributes").addValidator(StandardValidators.NON_EMPTY_VALIDATOR).build() return [descriptor] def onPropertyModified(self, descriptor, newValue, oldValue) : pass def onTrigger(self, context, sessionFactory) : session = sessionFactory.createSession() try : # ensure there is work to do flowfile = session.get() if flowfile is None : return # extract some attribute values fromPropertyValue = context.getProperty("for-attributes").getValue() fromAttributeValue = flowfile.getAttribute("for-attributes") # set an attribute flowfile = session.putAttribute(flowfile, "from-property", fromPropertyValue) flowfile = session.putAttribute(flowfile, "from-attribute", fromAttributeValue) # transfer session.transfer(flowfile, self.__rel_success) session.commit() except : print sys.exc_info()[0] print "Exception in TestReader:" print '-' * 60 traceback.print_exc(file=sys.stdout) print '-' * 60 session.rollback(true) raise processor = UpdateAttributes()
ShinyROM/android_external_chromium_org
refs/heads/master
chrome/common/extensions/docs/server2/local_renderer.py
26
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from render_servlet import RenderServlet from server_instance import ServerInstance from servlet import Request class _LocalRenderServletDelegate(object): def CreateServerInstance(self): return ServerInstance.ForLocal() class LocalRenderer(object): '''Renders pages fetched from the local file system. ''' @staticmethod def Render(path): assert not '\\' in path return RenderServlet(Request.ForTest(path), _LocalRenderServletDelegate()).Get()
Manojkumar91/odoo_inresto
refs/heads/master
addons/l10n_hn/__init__.py
1
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (c) 2009-2010 Salvatore J. Trimarchi <salvatore@trimarchi.co.cc> # (http://salvatoreweb.co.cc) # # 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/>. # ##############################################################################
lepricon49/headphones
refs/heads/master
lib/requests/packages/chardet/eucjpprober.py
2918
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is mozilla.org code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # 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 St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### import sys from . import constants from .mbcharsetprober import MultiByteCharSetProber from .codingstatemachine import CodingStateMachine from .chardistribution import EUCJPDistributionAnalysis from .jpcntx import EUCJPContextAnalysis from .mbcssm import EUCJPSMModel class EUCJPProber(MultiByteCharSetProber): def __init__(self): MultiByteCharSetProber.__init__(self) self._mCodingSM = CodingStateMachine(EUCJPSMModel) self._mDistributionAnalyzer = EUCJPDistributionAnalysis() self._mContextAnalyzer = EUCJPContextAnalysis() self.reset() def reset(self): MultiByteCharSetProber.reset(self) self._mContextAnalyzer.reset() def get_charset_name(self): return "EUC-JP" def feed(self, aBuf): aLen = len(aBuf) for i in range(0, aLen): # PY3K: aBuf is a byte array, so aBuf[i] is an int, not a byte codingState = self._mCodingSM.next_state(aBuf[i]) if codingState == constants.eError: if constants._debug: sys.stderr.write(self.get_charset_name() + ' prober hit error at byte ' + str(i) + '\n') self._mState = constants.eNotMe break elif codingState == constants.eItsMe: self._mState = constants.eFoundIt break elif codingState == constants.eStart: charLen = self._mCodingSM.get_current_charlen() if i == 0: self._mLastChar[1] = aBuf[0] self._mContextAnalyzer.feed(self._mLastChar, charLen) self._mDistributionAnalyzer.feed(self._mLastChar, charLen) else: self._mContextAnalyzer.feed(aBuf[i - 1:i + 1], charLen) self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], charLen) self._mLastChar[0] = aBuf[aLen - 1] if self.get_state() == constants.eDetecting: if (self._mContextAnalyzer.got_enough_data() and (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): self._mState = constants.eFoundIt return self.get_state() def get_confidence(self): contxtCf = self._mContextAnalyzer.get_confidence() distribCf = self._mDistributionAnalyzer.get_confidence() return max(contxtCf, distribCf)
ThiagoGarciaAlves/intellij-community
refs/heads/master
python/lib/Lib/site-packages/django/contrib/sessions/backends/__init__.py
12133432
paulproteus/oppia-test-3
refs/heads/master
apps/widget/__init__.py
12133432
redhat-openstack/horizon
refs/heads/mitaka-patches
openstack_dashboard/contrib/developer/theme_preview/views.py
20
# Copyright 2015 Cisco Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django.utils.translation import ugettext_lazy as _ from horizon import views class IndexView(views.HorizonTemplateView): template_name = 'developer/theme_preview/index.html' page_title = _("Bootstrap Theme Preview")
javaos74/neutron
refs/heads/master
neutron/agent/linux/iptables_manager.py
17
# Copyright 2012 Locaweb. # 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. # # based on # https://github.com/openstack/nova/blob/master/nova/network/linux_net.py """Implements iptables rules using linux utilities.""" import collections import contextlib import os import re import sys from oslo_concurrency import lockutils from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils import six from neutron.agent.common import config from neutron.agent.linux import iptables_comments as ic from neutron.agent.linux import utils as linux_utils from neutron.common import exceptions as n_exc from neutron.common import utils from neutron.i18n import _LE, _LW LOG = logging.getLogger(__name__) config.register_iptables_opts(cfg.CONF) # NOTE(vish): Iptables supports chain names of up to 28 characters, and we # add up to 12 characters to binary_name which is used as a prefix, # so we limit it to 16 characters. # (max_chain_name_length - len('-POSTROUTING') == 16) def get_binary_name(): """Grab the name of the binary we're running in.""" return os.path.basename(sys.argv[0])[:16].replace(' ', '_') binary_name = get_binary_name() # A length of a chain name must be less than or equal to 11 characters. # <max length of iptables chain name> - (<binary_name> + '-') = 28-(16+1) = 11 MAX_CHAIN_LEN_WRAP = 11 MAX_CHAIN_LEN_NOWRAP = 28 # Number of iptables rules to print before and after a rule that causes a # a failure during iptables-restore IPTABLES_ERROR_LINES_OF_CONTEXT = 5 def comment_rule(rule, comment): if not cfg.CONF.AGENT.comment_iptables_rules or not comment: return rule # iptables-save outputs the comment before the jump so we need to match # that order so _find_last_entry works try: start_of_jump = rule.index(' -j ') except ValueError: return '%s -m comment --comment "%s"' % (rule, comment) return ' '.join([rule[0:start_of_jump], '-m comment --comment "%s"' % comment, rule[start_of_jump + 1:]]) def get_chain_name(chain_name, wrap=True): if wrap: return chain_name[:MAX_CHAIN_LEN_WRAP] else: return chain_name[:MAX_CHAIN_LEN_NOWRAP] class IptablesRule(object): """An iptables rule. You shouldn't need to use this class directly, it's only used by IptablesManager. """ def __init__(self, chain, rule, wrap=True, top=False, binary_name=binary_name, tag=None, comment=None): self.chain = get_chain_name(chain, wrap) self.rule = rule self.wrap = wrap self.top = top self.wrap_name = binary_name[:16] self.tag = tag self.comment = comment def __eq__(self, other): return ((self.chain == other.chain) and (self.rule == other.rule) and (self.top == other.top) and (self.wrap == other.wrap)) def __ne__(self, other): return not self == other def __str__(self): if self.wrap: chain = '%s-%s' % (self.wrap_name, self.chain) else: chain = self.chain return comment_rule('-A %s %s' % (chain, self.rule), self.comment) class IptablesTable(object): """An iptables table.""" def __init__(self, binary_name=binary_name): self.rules = [] self.remove_rules = [] self.chains = set() self.unwrapped_chains = set() self.remove_chains = set() self.wrap_name = binary_name[:16] def add_chain(self, name, wrap=True): """Adds a named chain to the table. The chain name is wrapped to be unique for the component creating it, so different components of Nova can safely create identically named chains without interfering with one another. At the moment, its wrapped name is <binary name>-<chain name>, so if neutron-openvswitch-agent creates a chain named 'OUTPUT', it'll actually end up being named 'neutron-openvswi-OUTPUT'. """ name = get_chain_name(name, wrap) if wrap: self.chains.add(name) else: self.unwrapped_chains.add(name) def _select_chain_set(self, wrap): if wrap: return self.chains else: return self.unwrapped_chains def remove_chain(self, name, wrap=True): """Remove named chain. This removal "cascades". All rule in the chain are removed, as are all rules in other chains that jump to it. If the chain is not found, this is merely logged. """ name = get_chain_name(name, wrap) chain_set = self._select_chain_set(wrap) if name not in chain_set: LOG.debug('Attempted to remove chain %s which does not exist', name) return chain_set.remove(name) if not wrap: # non-wrapped chains and rules need to be dealt with specially, # so we keep a list of them to be iterated over in apply() self.remove_chains.add(name) # first, add rules to remove that have a matching chain name self.remove_rules += [r for r in self.rules if r.chain == name] # next, remove rules from list that have a matching chain name self.rules = [r for r in self.rules if r.chain != name] if not wrap: jump_snippet = '-j %s' % name # next, add rules to remove that have a matching jump chain self.remove_rules += [r for r in self.rules if jump_snippet in r.rule] else: jump_snippet = '-j %s-%s' % (self.wrap_name, name) # finally, remove rules from list that have a matching jump chain self.rules = [r for r in self.rules if jump_snippet not in r.rule] def add_rule(self, chain, rule, wrap=True, top=False, tag=None, comment=None): """Add a rule to the table. This is just like what you'd feed to iptables, just without the '-A <chain name>' bit at the start. However, if you need to jump to one of your wrapped chains, prepend its name with a '$' which will ensure the wrapping is applied correctly. """ chain = get_chain_name(chain, wrap) if wrap and chain not in self.chains: raise LookupError(_('Unknown chain: %r') % chain) if '$' in rule: rule = ' '.join( self._wrap_target_chain(e, wrap) for e in rule.split(' ')) self.rules.append(IptablesRule(chain, rule, wrap, top, self.wrap_name, tag, comment)) def _wrap_target_chain(self, s, wrap): if s.startswith('$'): s = ('%s-%s' % (self.wrap_name, get_chain_name(s[1:], wrap))) return s def remove_rule(self, chain, rule, wrap=True, top=False, comment=None): """Remove a rule from a chain. Note: The rule must be exactly identical to the one that was added. You cannot switch arguments around like you can with the iptables CLI tool. """ chain = get_chain_name(chain, wrap) try: if '$' in rule: rule = ' '.join( self._wrap_target_chain(e, wrap) for e in rule.split(' ')) self.rules.remove(IptablesRule(chain, rule, wrap, top, self.wrap_name, comment=comment)) if not wrap: self.remove_rules.append(IptablesRule(chain, rule, wrap, top, self.wrap_name, comment=comment)) except ValueError: LOG.warn(_LW('Tried to remove rule that was not there:' ' %(chain)r %(rule)r %(wrap)r %(top)r'), {'chain': chain, 'rule': rule, 'top': top, 'wrap': wrap}) def _get_chain_rules(self, chain, wrap): chain = get_chain_name(chain, wrap) return [rule for rule in self.rules if rule.chain == chain and rule.wrap == wrap] def empty_chain(self, chain, wrap=True): """Remove all rules from a chain.""" chained_rules = self._get_chain_rules(chain, wrap) for rule in chained_rules: self.rules.remove(rule) def clear_rules_by_tag(self, tag): if not tag: return rules = [rule for rule in self.rules if rule.tag == tag] for rule in rules: self.rules.remove(rule) class IptablesManager(object): """Wrapper for iptables. See IptablesTable for some usage docs A number of chains are set up to begin with. First, neutron-filter-top. It's added at the top of FORWARD and OUTPUT. Its name is not wrapped, so it's shared between the various neutron workers. It's intended for rules that need to live at the top of the FORWARD and OUTPUT chains. It's in both the ipv4 and ipv6 set of tables. For ipv4 and ipv6, the built-in INPUT, OUTPUT, and FORWARD filter chains are wrapped, meaning that the "real" INPUT chain has a rule that jumps to the wrapped INPUT chain, etc. Additionally, there's a wrapped chain named "local" which is jumped to from neutron-filter-top. For ipv4, the built-in PREROUTING, OUTPUT, and POSTROUTING nat chains are wrapped in the same was as the built-in filter chains. Additionally, there's a snat chain that is applied after the POSTROUTING chain. """ def __init__(self, _execute=None, state_less=False, use_ipv6=False, namespace=None, binary_name=binary_name): if _execute: self.execute = _execute else: self.execute = linux_utils.execute self.use_ipv6 = use_ipv6 self.namespace = namespace self.iptables_apply_deferred = False self.wrap_name = binary_name[:16] self.ipv4 = {'filter': IptablesTable(binary_name=self.wrap_name)} self.ipv6 = {'filter': IptablesTable(binary_name=self.wrap_name)} # Add a neutron-filter-top chain. It's intended to be shared # among the various neutron components. It sits at the very top # of FORWARD and OUTPUT. for tables in [self.ipv4, self.ipv6]: tables['filter'].add_chain('neutron-filter-top', wrap=False) tables['filter'].add_rule('FORWARD', '-j neutron-filter-top', wrap=False, top=True) tables['filter'].add_rule('OUTPUT', '-j neutron-filter-top', wrap=False, top=True) tables['filter'].add_chain('local') tables['filter'].add_rule('neutron-filter-top', '-j $local', wrap=False) # Wrap the built-in chains builtin_chains = {4: {'filter': ['INPUT', 'OUTPUT', 'FORWARD']}, 6: {'filter': ['INPUT', 'OUTPUT', 'FORWARD']}} if not state_less: self.ipv4.update( {'mangle': IptablesTable(binary_name=self.wrap_name)}) builtin_chains[4].update( {'mangle': ['PREROUTING', 'INPUT', 'FORWARD', 'OUTPUT', 'POSTROUTING']}) self.ipv4.update( {'nat': IptablesTable(binary_name=self.wrap_name)}) builtin_chains[4].update({'nat': ['PREROUTING', 'OUTPUT', 'POSTROUTING']}) self.ipv4.update({'raw': IptablesTable(binary_name=self.wrap_name)}) builtin_chains[4].update({'raw': ['PREROUTING', 'OUTPUT']}) self.ipv6.update({'raw': IptablesTable(binary_name=self.wrap_name)}) builtin_chains[6].update({'raw': ['PREROUTING', 'OUTPUT']}) for ip_version in builtin_chains: if ip_version == 4: tables = self.ipv4 elif ip_version == 6: tables = self.ipv6 for table, chains in six.iteritems(builtin_chains[ip_version]): for chain in chains: tables[table].add_chain(chain) tables[table].add_rule(chain, '-j $%s' % (chain), wrap=False) if not state_less: # Add a neutron-postrouting-bottom chain. It's intended to be # shared among the various neutron components. We set it as the # last chain of POSTROUTING chain. self.ipv4['nat'].add_chain('neutron-postrouting-bottom', wrap=False) self.ipv4['nat'].add_rule('POSTROUTING', '-j neutron-postrouting-bottom', wrap=False) # We add a snat chain to the shared neutron-postrouting-bottom # chain so that it's applied last. self.ipv4['nat'].add_chain('snat') self.ipv4['nat'].add_rule('neutron-postrouting-bottom', '-j $snat', wrap=False, comment=ic.SNAT_OUT) # And then we add a float-snat chain and jump to first thing in # the snat chain. self.ipv4['nat'].add_chain('float-snat') self.ipv4['nat'].add_rule('snat', '-j $float-snat') # Add a mark chain to mangle PREROUTING chain. It is used to # identify ingress packets from a certain interface. self.ipv4['mangle'].add_chain('mark') self.ipv4['mangle'].add_rule('PREROUTING', '-j $mark') def get_chain(self, table, chain, ip_version=4, wrap=True): try: requested_table = {4: self.ipv4, 6: self.ipv6}[ip_version][table] except KeyError: return [] return requested_table._get_chain_rules(chain, wrap) def is_chain_empty(self, table, chain, ip_version=4, wrap=True): return not self.get_chain(table, chain, ip_version, wrap) @contextlib.contextmanager def defer_apply(self): """Defer apply context.""" self.defer_apply_on() try: yield finally: try: self.defer_apply_off() except Exception: msg = _LE('Failure applying iptables rules') LOG.exception(msg) raise n_exc.IpTablesApplyException(msg) def defer_apply_on(self): self.iptables_apply_deferred = True def defer_apply_off(self): self.iptables_apply_deferred = False self._apply() def apply(self): if self.iptables_apply_deferred: return self._apply() def _apply(self): lock_name = 'iptables' if self.namespace: lock_name += '-' + self.namespace with lockutils.lock(lock_name, utils.SYNCHRONIZED_PREFIX, True): return self._apply_synchronized() def get_rules_for_table(self, table): """Runs iptables-save on a table and returns the results.""" args = ['iptables-save', '-t', table] if self.namespace: args = ['ip', 'netns', 'exec', self.namespace] + args return self.execute(args, run_as_root=True).split('\n') def _apply_synchronized(self): """Apply the current in-memory set of iptables rules. This will blow away any rules left over from previous runs of the same component of Nova, and replace them with our current set of rules. This happens atomically, thanks to iptables-restore. """ s = [('iptables', self.ipv4)] if self.use_ipv6: s += [('ip6tables', self.ipv6)] for cmd, tables in s: args = ['%s-save' % (cmd,), '-c'] if self.namespace: args = ['ip', 'netns', 'exec', self.namespace] + args all_tables = self.execute(args, run_as_root=True) all_lines = all_tables.split('\n') # Traverse tables in sorted order for predictable dump output for table_name in sorted(tables): table = tables[table_name] start, end = self._find_table(all_lines, table_name) all_lines[start:end] = self._modify_rules( all_lines[start:end], table, table_name) args = ['%s-restore' % (cmd,), '-c'] if self.namespace: args = ['ip', 'netns', 'exec', self.namespace] + args try: self.execute(args, process_input='\n'.join(all_lines), run_as_root=True) except RuntimeError as r_error: with excutils.save_and_reraise_exception(): try: line_no = int(re.search( 'iptables-restore: line ([0-9]+?) failed', str(r_error)).group(1)) context = IPTABLES_ERROR_LINES_OF_CONTEXT log_start = max(0, line_no - context) log_end = line_no + context except AttributeError: # line error wasn't found, print all lines instead log_start = 0 log_end = len(all_lines) log_lines = ('%7d. %s' % (idx, l) for idx, l in enumerate( all_lines[log_start:log_end], log_start + 1) ) LOG.error(_LE("IPTablesManager.apply failed to apply the " "following set of iptables rules:\n%s"), '\n'.join(log_lines)) LOG.debug("IPTablesManager.apply completed with success") def _find_table(self, lines, table_name): if len(lines) < 3: # length only <2 when fake iptables return (0, 0) try: start = lines.index('*%s' % table_name) - 1 except ValueError: # Couldn't find table_name LOG.debug('Unable to find table %s', table_name) return (0, 0) end = lines[start:].index('COMMIT') + start + 2 return (start, end) def _find_rules_index(self, lines): seen_chains = False rules_index = 0 for rules_index, rule in enumerate(lines): if not seen_chains: if rule.startswith(':'): seen_chains = True else: if not rule.startswith(':'): break if not seen_chains: rules_index = 2 return rules_index def _find_last_entry(self, filter_map, match_str): # find last matching entry try: return filter_map[match_str][-1] except KeyError: pass def _modify_rules(self, current_lines, table, table_name): # Chains are stored as sets to avoid duplicates. # Sort the output chains here to make their order predictable. unwrapped_chains = sorted(table.unwrapped_chains) chains = sorted(table.chains) remove_chains = table.remove_chains rules = table.rules remove_rules = table.remove_rules if not current_lines: fake_table = ['# Generated by iptables_manager', '*' + table_name, 'COMMIT', '# Completed by iptables_manager'] current_lines = fake_table # Fill old_filter with any chains or rules we might have added, # they could have a [packet:byte] count we want to preserve. # Fill new_filter with any chains or rules without our name in them. old_filter, new_filter = [], [] for line in current_lines: (old_filter if self.wrap_name in line else new_filter).append(line.strip()) old_filter_map = make_filter_map(old_filter) new_filter_map = make_filter_map(new_filter) rules_index = self._find_rules_index(new_filter) all_chains = [':%s' % name for name in unwrapped_chains] all_chains += [':%s-%s' % (self.wrap_name, name) for name in chains] # Iterate through all the chains, trying to find an existing # match. our_chains = [] for chain in all_chains: chain_str = str(chain).strip() old = self._find_last_entry(old_filter_map, chain_str) if not old: dup = self._find_last_entry(new_filter_map, chain_str) new_filter = [s for s in new_filter if chain_str not in s.strip()] # if no old or duplicates, use original chain if old or dup: chain_str = str(old or dup) else: # add-on the [packet:bytes] chain_str += ' - [0:0]' our_chains += [chain_str] # Iterate through all the rules, trying to find an existing # match. our_rules = [] bot_rules = [] for rule in rules: rule_str = str(rule).strip() # Further down, we weed out duplicates from the bottom of the # list, so here we remove the dupes ahead of time. old = self._find_last_entry(old_filter_map, rule_str) if not old: dup = self._find_last_entry(new_filter_map, rule_str) new_filter = [s for s in new_filter if rule_str not in s.strip()] # if no old or duplicates, use original rule if old or dup: rule_str = str(old or dup) # backup one index so we write the array correctly if not old: rules_index -= 1 else: # add-on the [packet:bytes] rule_str = '[0:0] ' + rule_str if rule.top: # rule.top == True means we want this rule to be at the top. our_rules += [rule_str] else: bot_rules += [rule_str] our_rules += bot_rules new_filter[rules_index:rules_index] = our_rules new_filter[rules_index:rules_index] = our_chains def _strip_packets_bytes(line): # strip any [packet:byte] counts at start or end of lines if line.startswith(':'): # it's a chain, for example, ":neutron-billing - [0:0]" line = line.split(':')[1] line = line.split(' - [', 1)[0] elif line.startswith('['): # it's a rule, for example, "[0:0] -A neutron-billing..." line = line.split('] ', 1)[1] line = line.strip() return line seen_chains = set() def _weed_out_duplicate_chains(line): # ignore [packet:byte] counts at end of lines if line.startswith(':'): line = _strip_packets_bytes(line) if line in seen_chains: return False else: seen_chains.add(line) # Leave it alone return True seen_rules = set() def _weed_out_duplicate_rules(line): if line.startswith('['): line = _strip_packets_bytes(line) if line in seen_rules: return False else: seen_rules.add(line) # Leave it alone return True def _weed_out_removes(line): # We need to find exact matches here if line.startswith(':'): line = _strip_packets_bytes(line) for chain in remove_chains: if chain == line: remove_chains.remove(chain) return False elif line.startswith('['): line = _strip_packets_bytes(line) for rule in remove_rules: rule_str = _strip_packets_bytes(str(rule)) if rule_str == line: remove_rules.remove(rule) return False # Leave it alone return True # We filter duplicates. Go through the chains and rules, letting # the *last* occurrence take precedence since it could have a # non-zero [packet:byte] count we want to preserve. We also filter # out anything in the "remove" list. new_filter.reverse() new_filter = [line for line in new_filter if _weed_out_duplicate_chains(line) and _weed_out_duplicate_rules(line) and _weed_out_removes(line)] new_filter.reverse() # flush lists, just in case we didn't find something remove_chains.clear() for rule in remove_rules: remove_rules.remove(rule) return new_filter def _get_traffic_counters_cmd_tables(self, chain, wrap=True): name = get_chain_name(chain, wrap) cmd_tables = [('iptables', key) for key, table in self.ipv4.items() if name in table._select_chain_set(wrap)] if self.use_ipv6: cmd_tables += [('ip6tables', key) for key, table in self.ipv6.items() if name in table._select_chain_set(wrap)] return cmd_tables def get_traffic_counters(self, chain, wrap=True, zero=False): """Return the sum of the traffic counters of all rules of a chain.""" cmd_tables = self._get_traffic_counters_cmd_tables(chain, wrap) if not cmd_tables: LOG.warn(_LW('Attempted to get traffic counters of chain %s which ' 'does not exist'), chain) return name = get_chain_name(chain, wrap) acc = {'pkts': 0, 'bytes': 0} for cmd, table in cmd_tables: args = [cmd, '-t', table, '-L', name, '-n', '-v', '-x'] if zero: args.append('-Z') if self.namespace: args = ['ip', 'netns', 'exec', self.namespace] + args current_table = self.execute(args, run_as_root=True) current_lines = current_table.split('\n') for line in current_lines[2:]: if not line: break data = line.split() if (len(data) < 2 or not data[0].isdigit() or not data[1].isdigit()): break acc['pkts'] += int(data[0]) acc['bytes'] += int(data[1]) return acc def make_filter_map(filter_list): filter_map = collections.defaultdict(list) for data in filter_list: # strip any [packet:byte] counts at start or end of lines, # for example, chains look like ":neutron-foo - [0:0]" # and rules look like "[0:0] -A neutron-foo..." if data.startswith('['): key = data.rpartition('] ')[2] elif data.endswith(']'): key = data.rsplit(' [', 1)[0] if key.endswith(' -'): key = key[:-2] else: # things like COMMIT, *filter, and *nat land here continue filter_map[key].append(data) # regular IP(v6) entries are translated into /32s or /128s so we # include a lookup without the CIDR here to match as well for cidr in ('/32', '/128'): if cidr in key: alt_key = key.replace(cidr, '') filter_map[alt_key].append(data) # return a regular dict so readers don't accidentally add entries return dict(filter_map)
neumerance/deploy
refs/heads/master
.venv/lib/python2.7/site-packages/cinderclient/tests/v2/test_types.py
3
# Copyright (c) 2013 OpenStack, LLC. # # 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 cinderclient.v2 import volume_types from cinderclient.tests import utils from cinderclient.tests.v2 import fakes cs = fakes.FakeClient() class TypesTest(utils.TestCase): def test_list_types(self): tl = cs.volume_types.list() cs.assert_called('GET', '/types') for t in tl: self.assertTrue(isinstance(t, volume_types.VolumeType)) def test_create(self): t = cs.volume_types.create('test-type-3') cs.assert_called('POST', '/types') self.assertTrue(isinstance(t, volume_types.VolumeType)) def test_set_key(self): t = cs.volume_types.get(1) t.set_keys({'k': 'v'}) cs.assert_called('POST', '/types/1/extra_specs', {'extra_specs': {'k': 'v'}}) def test_unsset_keys(self): t = cs.volume_types.get(1) t.unset_keys(['k']) cs.assert_called('DELETE', '/types/1/extra_specs/k') def test_delete(self): cs.volume_types.delete(1) cs.assert_called('DELETE', '/types/1')
liangwang/m5
refs/heads/master
ext/ply/test/lex_token3.py
174
# lex_token3.py # # tokens is right type, but is missing a token for one rule import sys if ".." not in sys.path: sys.path.insert(0,"..") import ply.lex as lex tokens = [ "PLUS", "NUMBER", ] t_PLUS = r'\+' t_MINUS = r'-' t_NUMBER = r'\d+' def t_error(t): pass lex.lex()
sinkuri256/python-for-android
refs/heads/master
python-build/python-libs/gdata/src/gdata/Crypto/Util/number.py
232
# # number.py : Number-theoretic functions # # Part of the Python Cryptography Toolkit # # Distribute and use freely; there are no restrictions on further # dissemination and usage except those imposed by the laws of your # country of residence. This software is provided "as is" without # warranty of fitness for use or suitability for any purpose, express # or implied. Use at your own risk or not at all. # __revision__ = "$Id: number.py,v 1.13 2003/04/04 18:21:07 akuchling Exp $" bignum = long try: from Crypto.PublicKey import _fastmath except ImportError: _fastmath = None # Commented out and replaced with faster versions below ## def long2str(n): ## s='' ## while n>0: ## s=chr(n & 255)+s ## n=n>>8 ## return s ## import types ## def str2long(s): ## if type(s)!=types.StringType: return s # Integers will be left alone ## return reduce(lambda x,y : x*256+ord(y), s, 0L) def size (N): """size(N:long) : int Returns the size of the number N in bits. """ bits, power = 0,1L while N >= power: bits += 1 power = power << 1 return bits def getRandomNumber(N, randfunc): """getRandomNumber(N:int, randfunc:callable):long Return an N-bit random number.""" S = randfunc(N/8) odd_bits = N % 8 if odd_bits != 0: char = ord(randfunc(1)) >> (8-odd_bits) S = chr(char) + S value = bytes_to_long(S) value |= 2L ** (N-1) # Ensure high bit is set assert size(value) >= N return value def GCD(x,y): """GCD(x:long, y:long): long Return the GCD of x and y. """ x = abs(x) ; y = abs(y) while x > 0: x, y = y % x, x return y def inverse(u, v): """inverse(u:long, u:long):long Return the inverse of u mod v. """ u3, v3 = long(u), long(v) u1, v1 = 1L, 0L while v3 > 0: q=u3 / v3 u1, v1 = v1, u1 - v1*q u3, v3 = v3, u3 - v3*q while u1<0: u1 = u1 + v return u1 # Given a number of bits to generate and a random generation function, # find a prime number of the appropriate size. def getPrime(N, randfunc): """getPrime(N:int, randfunc:callable):long Return a random N-bit prime number. """ number=getRandomNumber(N, randfunc) | 1 while (not isPrime(number)): number=number+2 return number def isPrime(N): """isPrime(N:long):bool Return true if N is prime. """ if N == 1: return 0 if N in sieve: return 1 for i in sieve: if (N % i)==0: return 0 # Use the accelerator if available if _fastmath is not None: return _fastmath.isPrime(N) # Compute the highest bit that's set in N N1 = N - 1L n = 1L while (n<N): n=n<<1L n = n >> 1L # Rabin-Miller test for c in sieve[:7]: a=long(c) ; d=1L ; t=n while (t): # Iterate over the bits in N1 x=(d*d) % N if x==1L and d!=1L and d!=N1: return 0 # Square root of 1 found if N1 & t: d=(x*a) % N else: d=x t = t >> 1L if d!=1L: return 0 return 1 # Small primes used for checking primality; these are all the primes # less than 256. This should be enough to eliminate most of the odd # numbers before needing to do a Rabin-Miller test at all. sieve=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251] # Improved conversion functions contributed by Barry Warsaw, after # careful benchmarking import struct def long_to_bytes(n, blocksize=0): """long_to_bytes(n:long, blocksize:int) : string Convert a long integer to a byte string. If optional blocksize is given and greater than zero, pad the front of the byte string with binary zeros so that the length is a multiple of blocksize. """ # after much testing, this algorithm was deemed to be the fastest s = '' n = long(n) pack = struct.pack while n > 0: s = pack('>I', n & 0xffffffffL) + s n = n >> 32 # strip off leading zeros for i in range(len(s)): if s[i] != '\000': break else: # only happens when n == 0 s = '\000' i = 0 s = s[i:] # add back some pad bytes. this could be done more efficiently w.r.t. the # de-padding being done above, but sigh... if blocksize > 0 and len(s) % blocksize: s = (blocksize - len(s) % blocksize) * '\000' + s return s def bytes_to_long(s): """bytes_to_long(string) : long Convert a byte string to a long integer. This is (essentially) the inverse of long_to_bytes(). """ acc = 0L unpack = struct.unpack length = len(s) if length % 4: extra = (4 - length % 4) s = '\000' * extra + s length = length + extra for i in range(0, length, 4): acc = (acc << 32) + unpack('>I', s[i:i+4])[0] return acc # For backwards compatibility... import warnings def long2str(n, blocksize=0): warnings.warn("long2str() has been replaced by long_to_bytes()") return long_to_bytes(n, blocksize) def str2long(s): warnings.warn("str2long() has been replaced by bytes_to_long()") return bytes_to_long(s)
shashisp/blumix-webpy
refs/heads/master
app/applications/welcome/languages/fr-ca.py
163
# coding: utf8 { '!langcode!': 'fr-ca', '!langname!': 'Français (Canadien)', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résultats d\'un JOIN', '%s %%{row} deleted': '%s rangées supprimées', '%s %%{row} updated': '%s rangées mises à jour', '%s selected': '%s sélectionné', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', 'about': 'à propos', 'About': 'À propos', 'Access Control': "Contrôle d'accès", 'Administrative Interface': 'Administrative Interface', 'Administrative interface': "Interface d'administration", 'Ajax Recipes': 'Recettes Ajax', 'appadmin is disabled because insecure channel': "appadmin est désactivée parce que le canal n'est pas sécurisé", 'Are you sure you want to delete this object?': 'Êtes-vous sûr de vouloir supprimer cet objet?', 'Authentication': 'Authentification', 'Available Databases and Tables': 'Bases de données et tables disponibles', 'Buy this book': 'Acheter ce livre', 'cache': 'cache', 'Cache': 'Cache', 'Cache Keys': 'Cache Keys', 'Cannot be empty': 'Ne peut pas être vide', 'change password': 'changer le mot de passe', 'Check to delete': 'Cliquez pour supprimer', 'Check to delete:': 'Cliquez pour supprimer:', 'Clear CACHE?': 'Clear CACHE?', 'Clear DISK': 'Clear DISK', 'Clear RAM': 'Clear RAM', 'Client IP': 'IP client', 'Community': 'Communauté', 'Components and Plugins': 'Components and Plugins', 'Controller': 'Contrôleur', 'Copyright': "Droit d'auteur", 'Current request': 'Demande actuelle', 'Current response': 'Réponse actuelle', 'Current session': 'Session en cours', 'customize me!': 'personnalisez-moi!', 'data uploaded': 'données téléchargées', 'Database': 'base de données', 'Database %s select': 'base de données %s select', 'db': 'db', 'DB Model': 'Modèle DB', 'Delete:': 'Supprimer:', 'Demo': 'Démo', 'Deployment Recipes': 'Recettes de déploiement ', 'Description': 'Descriptif', 'design': 'design', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk Cleared', 'Documentation': 'Documentation', "Don't know what to do?": "Don't know what to do?", 'done!': 'fait!', 'Download': 'Téléchargement', 'E-mail': 'Courriel', 'Edit': 'Éditer', 'Edit current record': "Modifier l'enregistrement courant", 'edit profile': 'modifier le profil', 'Edit This App': 'Modifier cette application', 'Email and SMS': 'Email and SMS', 'enter an integer between %(min)g and %(max)g': 'entrer un entier compris entre %(min)g et %(max)g', 'Errors': 'Erreurs', 'export as csv file': 'exporter sous forme de fichier csv', 'FAQ': 'faq', 'First name': 'Prénom', 'Forms and Validators': 'Formulaires et Validateurs', 'Free Applications': 'Applications gratuites', 'Function disabled': 'Fonction désactivée', 'Group %(group_id)s created': '%(group_id)s groupe créé', 'Group ID': 'Groupe ID', 'Group uniquely assigned to user %(id)s': "Groupe unique attribué à l'utilisateur %(id)s", 'Groups': 'Groupes', 'Hello World': 'Bonjour le monde', 'Home': 'Accueil', 'How did you get here?': 'How did you get here?', 'import': 'import', 'Import/Export': 'Importer/Exporter', 'Index': 'Index', 'insert new': 'insérer un nouveau', 'insert new %s': 'insérer un nouveau %s', 'Internal State': 'État interne', 'Introduction': 'Présentation', 'Invalid email': 'Courriel invalide', 'Invalid Query': 'Requête Invalide', 'invalid request': 'requête invalide', 'Key': 'Key', 'Last name': 'Nom', 'Layout': 'Mise en page', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'layouts', 'Live chat': 'Clavardage en direct', 'Live Chat': 'Live Chat', 'Logged in': 'Connecté', 'login': 'connectez-vous', 'Login': 'Connectez-vous', 'logout': 'déconnectez-vous', 'lost password': 'mot de passe perdu', 'Lost Password': 'Mot de passe perdu', 'lost password?': 'mot de passe perdu?', 'Main Menu': 'Menu principal', 'Manage Cache': 'Manage Cache', 'Menu Model': 'Menu modèle', 'My Sites': 'My Sites', 'Name': 'Nom', 'New Record': 'Nouvel enregistrement', 'new record inserted': 'nouvel enregistrement inséré', 'next 100 rows': '100 prochaines lignes', 'No databases in this application': "Cette application n'a pas de bases de données", 'Online examples': 'Exemples en ligne', 'or import from csv file': "ou importer d'un fichier CSV", 'Origin': 'Origine', 'Other Plugins': 'Other Plugins', 'Other Recipes': 'Autres recettes', 'Overview': 'Présentation', 'password': 'mot de passe', 'Password': 'Mot de passe', "Password fields don't match": 'Les mots de passe ne correspondent pas', 'please input your password again': "S'il vous plaît entrer votre mot de passe", 'Plugins': 'Plugiciels', 'Powered by': 'Alimenté par', 'Preface': 'Préface', 'previous 100 rows': '100 lignes précédentes', 'profile': 'profile', 'Python': 'Python', 'Query:': 'Requête:', 'Quick Examples': 'Examples Rapides', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Cleared', 'Readme': 'Lisez-moi', 'Recipes': 'Recettes', 'Record': 'enregistrement', 'Record %(id)s created': 'Record %(id)s created', 'Record %(id)s updated': 'Record %(id)s updated', 'Record Created': 'Record Created', 'record does not exist': "l'archive n'existe pas", 'Record ID': "ID d'enregistrement", 'Record id': "id d'enregistrement", 'Record Updated': 'Record Updated', 'Register': "S'inscrire", 'register': "s'inscrire", 'Registration key': "Clé d'enregistrement", 'Registration successful': 'Inscription réussie', 'Remember me (for 30 days)': 'Se souvenir de moi (pendant 30 jours)', 'Request reset password': 'Demande de réinitialiser le mot clé', 'Reset Password key': 'Réinitialiser le mot clé', 'Resources': 'Ressources', 'Role': 'Rôle', 'Rows in Table': 'Lignes du tableau', 'Rows selected': 'Lignes sélectionnées', 'Semantic': 'Sémantique', 'Services': 'Services', 'Size of cache:': 'Size of cache:', 'state': 'état', 'Statistics': 'Statistics', 'Stylesheet': 'Feuille de style', 'submit': 'submit', 'Submit': 'Soumettre', 'Support': 'Soutien', 'Sure you want to delete this object?': 'Êtes-vous sûr de vouloir supprimer cet objet?', 'Table': 'tableau', 'Table name': 'Nom du tableau', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La "query" est une condition comme "db.table1.champ1==\'valeur\'". Quelque chose comme "db.table1.champ1==db.table2.champ2" résulte en un JOIN SQL.', 'The Core': 'Le noyau', 'The output of the file is a dictionary that was rendered by the view %s': 'La sortie de ce fichier est un dictionnaire qui été restitué par la vue %s', 'The Views': 'Les Vues', 'This App': 'Cette Appli', 'This is a copy of the scaffolding application': "Ceci est une copie de l'application échafaudage", 'Time in Cache (h:m:s)': 'Time in Cache (h:m:s)', 'Timestamp': 'Horodatage', 'Twitter': 'Twitter', 'unable to parse csv file': "incapable d'analyser le fichier cvs", 'Update:': 'Mise à jour:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Employez (...)&(...) pour AND, (...)|(...) pour OR, and ~(...) pour NOT pour construire des requêtes plus complexes.', 'User %(id)s Logged-in': 'Utilisateur %(id)s connecté', 'User %(id)s Registered': 'Utilisateur %(id)s enregistré', 'User ID': 'ID utilisateur', 'User Voice': 'User Voice', 'value already in database or empty': 'valeur déjà dans la base ou vide', 'Verify Password': 'Vérifiez le mot de passe', 'Videos': 'Vidéos', 'View': 'Présentation', 'Web2py': 'Web2py', 'Welcome': 'Bienvenu', 'Welcome %s': 'Bienvenue %s', 'Welcome to web2py': 'Bienvenue à web2py', 'Welcome to web2py!': 'Welcome to web2py!', 'Which called the function %s located in the file %s': 'Qui a appelé la fonction %s se trouvant dans le fichier %s', 'You are successfully running web2py': 'Vous roulez avec succès web2py', 'You can modify this application and adapt it to your needs': "Vous pouvez modifier cette application et l'adapter à vos besoins", 'You visited the url %s': "Vous avez visité l'URL %s", }
joachimmetz/plaso
refs/heads/main
tests/parsers/cookie_plugins/ganalytics.py
3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Google Analytics cookies.""" import unittest from plaso.lib import definitions from plaso.parsers.cookie_plugins import ganalytics # pylint: disable=unused-import from plaso.parsers.sqlite_plugins import chrome_cookies from plaso.parsers.sqlite_plugins import firefox_cookies from tests.parsers.sqlite_plugins import test_lib as sqlite_plugins_test_lib class GoogleAnalyticsPluginTest(sqlite_plugins_test_lib.SQLitePluginTestCase): """Tests for the Google Analytics plugin.""" def _GetAnalyticsCookieEvents(self, storage_writer): """Retrieves the analytics cookie events. Returns: list[EventObject]: analytics cookie events. """ cookies = [] for event in storage_writer.GetEvents(): event_data = self._GetEventDataOfEvent(storage_writer, event) if event_data.data_type.startswith('cookie:google:analytics'): cookies.append(event) return cookies def testParsingFirefox29CookieDatabase(self): """Tests the Process function on a Firefox 29 cookie database file.""" plugin = firefox_cookies.FirefoxCookiePlugin() storage_writer = self._ParseDatabaseFileWithPlugin( ['firefox_cookies.sqlite'], plugin) events = self._GetAnalyticsCookieEvents(storage_writer) self.assertEqual(len(events), 25) self.assertEqual(storage_writer.number_of_extraction_warnings, 0) self.assertEqual(storage_writer.number_of_recovery_warnings, 0) expected_event_values = { 'cookie_name': '__utmz', 'data_type': 'cookie:google:analytics:utmz', 'date_time': '2013-10-30 21:56:06', 'domain_hash': '137167072', 'sessions': 1, 'sources': 1, 'url': 'http://ads.aha.is/', 'utmccn': '(referral)', 'utmcct': ( '/frettir/erlent/2013/10/30/maelt_med_kerfisbundnum_hydingum/'), 'utmcmd': 'referral', 'utmcsr': 'mbl.is'} self.CheckEventValues(storage_writer, events[14], expected_event_values) def testParsingChromeCookieDatabase(self): """Test the process function on a Chrome cookie database.""" plugin = chrome_cookies.Chrome17CookiePlugin() storage_writer = self._ParseDatabaseFileWithPlugin(['cookies.db'], plugin) events = self._GetAnalyticsCookieEvents(storage_writer) # The cookie database contains 560 entries in total. Out of them # there are 75 events created by the Google Analytics plugin. self.assertEqual(len(events), 75) self.assertEqual(storage_writer.number_of_extraction_warnings, 0) self.assertEqual(storage_writer.number_of_recovery_warnings, 0) # Check few "random" events to verify. # Check an UTMZ Google Analytics event. expected_event_values = { 'cookie_name': '__utmz', 'data_type': 'cookie:google:analytics:utmz', 'domain_hash': '68898382', 'sessions': 1, 'sources': 1, 'url': 'http://imdb.com/', 'utmccn': '(organic)', 'utmctr': 'enders game', 'utmcmd': 'organic', 'utmcsr': 'google'} self.CheckEventValues(storage_writer, events[39], expected_event_values) # Check the UTMA Google Analytics event. expected_event_values = { 'cookie_name': '__utma', 'data_type': 'cookie:google:analytics:utma', 'date_time': '2012-03-22 01:55:29', 'domain_hash': '151488169', 'sessions': 2, 'timestamp_desc': 'Analytics Previous Time', 'url': 'http://assets.tumblr.com/', 'visitor_id': '1827102436'} self.CheckEventValues(storage_writer, events[41], expected_event_values) # Check the UTMB Google Analytics event. expected_event_values = { 'cookie_name': '__utmb', 'data_type': 'cookie:google:analytics:utmb', 'date_time': '2012-03-22 01:48:30', 'domain_hash': '154523900', 'pages_viewed': 1, 'timestamp_desc': definitions.TIME_DESCRIPTION_LAST_VISITED, 'url': 'http://upressonline.com/'} self.CheckEventValues(storage_writer, events[34], expected_event_values) if __name__ == '__main__': unittest.main()
jiangyy/oiutils
refs/heads/master
oi/compile/compile.py
2
import argparse, tempfile, os, shutil # compile should generate "a.exe" on the same directory def compile_cmd(options, src): ext = src.split('.')[-1] # cpp opt = ' '.join(options) if ext == 'cpp': return 'g++ %s -o a.exe %s' % (opt, src) elif ext == 'c': return 'gcc %s -o a.exe %s' % (opt, src) elif ext == 'pas': return 'fpc %s -oa.exe %s' % (opt, src) else: return '' def oi_compile(args): try: if len(args) == 0: args = ['-h'] parser = argparse.ArgumentParser(description = 'compile a source file.') parser.add_argument('-o', help = 'output file', default = 'a.exe') parser.add_argument('file', help = 'source code file', nargs = 1) parser.add_argument('--optimized', help = 'using optimized compiling', default = False, action = "store_true") options = vars(parser.parse_args(args)) opt = [] if options['optimized']: opt.append('-O2') fname = options.get('file')[0] # xyz/src/a.cpp dest = options.get('o') src = os.path.basename(fname) # a.cpp tmpdir = tempfile.mkdtemp() # /tmp/abc123 shutil.copy(fname, tmpdir) cwd = os.getcwd() os.chdir(tmpdir) os.system('%s' % (compile_cmd(opt, src)) ) os.chdir(cwd) exe = os.path.join(tmpdir, 'a.exe') shutil.copy(exe, dest) except: pass
geerlingguy/ansible-for-devops
refs/heads/master
dynamic-inventory/custom/inventory.py
1
#!/usr/bin/env python3 ''' Example custom dynamic inventory script for Ansible, in Python. ''' import os import sys import argparse import json class ExampleInventory(object): def __init__(self): self.inventory = {} self.read_cli_args() # Called with `--list`. if self.args.list: self.inventory = self.example_inventory() # Called with `--host [hostname]`. elif self.args.host: # Not implemented, since we return _meta info `--list`. self.inventory = self.empty_inventory() # If no groups or vars are present, return empty inventory. else: self.inventory = self.empty_inventory() print(json.dumps(self.inventory)); # Example inventory for testing. def example_inventory(self): return { 'group': { 'hosts': ['192.168.28.71', '192.168.28.72'], 'vars': { 'ansible_user': 'vagrant', 'ansible_ssh_private_key_file': '~/.vagrant.d/insecure_private_key', 'ansible_python_interpreter': '/usr/bin/python3', 'example_variable': 'value' } }, '_meta': { 'hostvars': { '192.168.28.71': { 'host_specific_var': 'foo' }, '192.168.28.72': { 'host_specific_var': 'bar' } } } } # Empty inventory for testing. def empty_inventory(self): return {'_meta': {'hostvars': {}}} # Read the command line args passed to the script. def read_cli_args(self): parser = argparse.ArgumentParser() parser.add_argument('--list', action = 'store_true') parser.add_argument('--host', action = 'store') self.args = parser.parse_args() # Get the inventory. ExampleInventory()
zhenzhai/edx-platform
refs/heads/master
cms/djangoapps/contentstore/views/tests/test_entrance_exam.py
38
""" Test module for Entrance Exams AJAX callback handler workflows """ import json from mock import patch from django.conf import settings from django.contrib.auth.models import User from django.test.client import RequestFactory from contentstore.tests.utils import AjaxEnabledTestClient, CourseTestCase from contentstore.utils import reverse_url from contentstore.views.entrance_exam import create_entrance_exam, update_entrance_exam, delete_entrance_exam,\ add_entrance_exam_milestone, remove_entrance_exam_milestone_reference from contentstore.views.helpers import GRADER_TYPES from models.settings.course_grading import CourseGradingModel from models.settings.course_metadata import CourseMetadata from opaque_keys.edx.keys import UsageKey from student.tests.factories import UserFactory from util import milestones_helpers from xmodule.modulestore.django import modulestore from contentstore.views.helpers import create_xblock from milestones.tests.utils import MilestonesTestCaseMixin @patch.dict(settings.FEATURES, {'ENTRANCE_EXAMS': True}) class EntranceExamHandlerTests(CourseTestCase, MilestonesTestCaseMixin): """ Base test class for create, save, and delete """ def setUp(self): """ Shared scaffolding for individual test runs """ super(EntranceExamHandlerTests, self).setUp() self.course_key = self.course.id self.usage_key = self.course.location self.course_url = '/course/{}'.format(unicode(self.course.id)) self.exam_url = '/course/{}/entrance_exam/'.format(unicode(self.course.id)) self.milestone_relationship_types = milestones_helpers.get_milestone_relationship_types() def test_entrance_exam_milestone_addition(self): """ Unit Test: test addition of entrance exam milestone content """ parent_locator = unicode(self.course.location) created_block = create_xblock( parent_locator=parent_locator, user=self.user, category='chapter', display_name=('Entrance Exam'), is_entrance_exam=True ) add_entrance_exam_milestone(self.course.id, created_block) content_milestones = milestones_helpers.get_course_content_milestones( unicode(self.course.id), unicode(created_block.location), self.milestone_relationship_types['FULFILLS'] ) self.assertTrue(len(content_milestones)) self.assertEqual(len(milestones_helpers.get_course_milestones(self.course.id)), 1) def test_entrance_exam_milestone_removal(self): """ Unit Test: test removal of entrance exam milestone content """ parent_locator = unicode(self.course.location) created_block = create_xblock( parent_locator=parent_locator, user=self.user, category='chapter', display_name=('Entrance Exam'), is_entrance_exam=True ) add_entrance_exam_milestone(self.course.id, created_block) content_milestones = milestones_helpers.get_course_content_milestones( unicode(self.course.id), unicode(created_block.location), self.milestone_relationship_types['FULFILLS'] ) self.assertEqual(len(content_milestones), 1) user = UserFactory() request = RequestFactory().request() request.user = user remove_entrance_exam_milestone_reference(request, self.course.id) content_milestones = milestones_helpers.get_course_content_milestones( unicode(self.course.id), unicode(created_block.location), self.milestone_relationship_types['FULFILLS'] ) self.assertEqual(len(content_milestones), 0) def test_contentstore_views_entrance_exam_post(self): """ Unit Test: test_contentstore_views_entrance_exam_post """ resp = self.client.post(self.exam_url, {}, http_accept='application/json') self.assertEqual(resp.status_code, 201) resp = self.client.get(self.exam_url) self.assertEqual(resp.status_code, 200) # Reload the test course now that the exam module has been added self.course = modulestore().get_course(self.course.id) metadata = CourseMetadata.fetch_all(self.course) self.assertTrue(metadata['entrance_exam_enabled']) self.assertIsNotNone(metadata['entrance_exam_minimum_score_pct']) self.assertIsNotNone(metadata['entrance_exam_id']['value']) self.assertTrue(len(milestones_helpers.get_course_milestones(unicode(self.course.id)))) content_milestones = milestones_helpers.get_course_content_milestones( unicode(self.course.id), metadata['entrance_exam_id']['value'], self.milestone_relationship_types['FULFILLS'] ) self.assertTrue(len(content_milestones)) def test_contentstore_views_entrance_exam_post_new_sequential_confirm_grader(self): """ Unit Test: test_contentstore_views_entrance_exam_post """ resp = self.client.post(self.exam_url, {}, http_accept='application/json') self.assertEqual(resp.status_code, 201) resp = self.client.get(self.exam_url) self.assertEqual(resp.status_code, 200) # Reload the test course now that the exam module has been added self.course = modulestore().get_course(self.course.id) # Add a new child sequential to the exam module # Confirm that the grader type is 'Entrance Exam' chapter_locator_string = json.loads(resp.content).get('locator') # chapter_locator = UsageKey.from_string(chapter_locator_string) seq_data = { 'category': "sequential", 'display_name': "Entrance Exam Subsection", 'parent_locator': chapter_locator_string, } resp = self.client.ajax_post(reverse_url('xblock_handler'), seq_data) seq_locator_string = json.loads(resp.content).get('locator') seq_locator = UsageKey.from_string(seq_locator_string) section_grader_type = CourseGradingModel.get_section_grader_type(seq_locator) self.assertEqual(GRADER_TYPES['ENTRANCE_EXAM'], section_grader_type['graderType']) def test_contentstore_views_entrance_exam_get(self): """ Unit Test: test_contentstore_views_entrance_exam_get """ resp = self.client.post( self.exam_url, {'entrance_exam_minimum_score_pct': settings.ENTRANCE_EXAM_MIN_SCORE_PCT}, http_accept='application/json' ) self.assertEqual(resp.status_code, 201) resp = self.client.get(self.exam_url) self.assertEqual(resp.status_code, 200) def test_contentstore_views_entrance_exam_delete(self): """ Unit Test: test_contentstore_views_entrance_exam_delete """ resp = self.client.post(self.exam_url, {}, http_accept='application/json') self.assertEqual(resp.status_code, 201) resp = self.client.get(self.exam_url) self.assertEqual(resp.status_code, 200) resp = self.client.delete(self.exam_url) self.assertEqual(resp.status_code, 204) resp = self.client.get(self.exam_url) self.assertEqual(resp.status_code, 404) user = User.objects.create( username='test_user', email='test_user@edx.org', is_active=True, ) user.set_password('test') user.save() milestones = milestones_helpers.get_course_milestones(unicode(self.course_key)) self.assertEqual(len(milestones), 1) milestone_key = '{}.{}'.format(milestones[0]['namespace'], milestones[0]['name']) paths = milestones_helpers.get_course_milestones_fulfillment_paths( unicode(self.course_key), milestones_helpers.serialize_user(user) ) # What we have now is a course milestone requirement and no valid fulfillment # paths for the specified user. The LMS is going to have to ignore this situation, # because we can't confidently prevent it from occuring at some point in the future. # milestone_key_1 = self.assertEqual(len(paths[milestone_key]), 0) # Re-adding an entrance exam to the course should fix the missing link # It wipes out any old entrance exam artifacts and inserts a new exam course chapter/module resp = self.client.post(self.exam_url, {}, http_accept='application/json') self.assertEqual(resp.status_code, 201) resp = self.client.get(self.exam_url) self.assertEqual(resp.status_code, 200) # Confirm that we have only one Entrance Exam grader after re-adding the exam (validates SOL-475) graders = CourseGradingModel.fetch(self.course_key).graders count = 0 for grader in graders: if grader['type'] == GRADER_TYPES['ENTRANCE_EXAM']: count += 1 self.assertEqual(count, 1) def test_contentstore_views_entrance_exam_delete_bogus_course(self): """ Unit Test: test_contentstore_views_entrance_exam_delete_bogus_course """ resp = self.client.delete('/course/bad/course/key/entrance_exam') self.assertEqual(resp.status_code, 400) def test_contentstore_views_entrance_exam_get_bogus_course(self): """ Unit Test: test_contentstore_views_entrance_exam_get_bogus_course """ resp = self.client.get('/course/bad/course/key/entrance_exam') self.assertEqual(resp.status_code, 400) def test_contentstore_views_entrance_exam_get_bogus_exam(self): """ Unit Test: test_contentstore_views_entrance_exam_get_bogus_exam """ resp = self.client.post( self.exam_url, {'entrance_exam_minimum_score_pct': '50'}, http_accept='application/json' ) self.assertEqual(resp.status_code, 201) resp = self.client.get(self.exam_url) self.assertEqual(resp.status_code, 200) self.course = modulestore().get_course(self.course.id) # Should raise an ItemNotFoundError and return a 404 updated_metadata = {'entrance_exam_id': 'i4x://org.4/course_4/chapter/ed7c4c6a4d68409998e2c8554c4629d1'} CourseMetadata.update_from_dict( updated_metadata, self.course, self.user, ) self.course = modulestore().get_course(self.course.id) resp = self.client.get(self.exam_url) self.assertEqual(resp.status_code, 404) # Should raise an InvalidKeyError and return a 404 updated_metadata = {'entrance_exam_id': '123afsdfsad90f87'} CourseMetadata.update_from_dict( updated_metadata, self.course, self.user, ) self.course = modulestore().get_course(self.course.id) resp = self.client.get(self.exam_url) self.assertEqual(resp.status_code, 404) def test_contentstore_views_entrance_exam_post_bogus_course(self): """ Unit Test: test_contentstore_views_entrance_exam_post_bogus_course """ resp = self.client.post( '/course/bad/course/key/entrance_exam', {}, http_accept='application/json' ) self.assertEqual(resp.status_code, 400) def test_contentstore_views_entrance_exam_post_invalid_http_accept(self): """ Unit Test: test_contentstore_views_entrance_exam_post_invalid_http_accept """ resp = self.client.post( '/course/bad/course/key/entrance_exam', {}, http_accept='text/html' ) self.assertEqual(resp.status_code, 400) def test_contentstore_views_entrance_exam_get_invalid_user(self): """ Unit Test: test_contentstore_views_entrance_exam_get_invalid_user """ user = User.objects.create( username='test_user', email='test_user@edx.org', is_active=True, ) user.set_password('test') user.save() self.client = AjaxEnabledTestClient() self.client.login(username='test_user', password='test') resp = self.client.get(self.exam_url) self.assertEqual(resp.status_code, 403) def test_contentstore_views_entrance_exam_unsupported_method(self): """ Unit Test: test_contentstore_views_entrance_exam_unsupported_method """ resp = self.client.put(self.exam_url) self.assertEqual(resp.status_code, 405) def test_entrance_exam_view_direct_missing_score_setting(self): """ Unit Test: test_entrance_exam_view_direct_missing_score_setting """ user = UserFactory() user.is_staff = True request = RequestFactory() request.user = user resp = create_entrance_exam(request, self.course.id, None) self.assertEqual(resp.status_code, 201) @patch.dict('django.conf.settings.FEATURES', {'ENTRANCE_EXAMS': False}) def test_entrance_exam_feature_flag_gating(self): user = UserFactory() user.is_staff = True request = RequestFactory() request.user = user resp = self.client.get(self.exam_url) self.assertEqual(resp.status_code, 400) resp = create_entrance_exam(request, self.course.id, None) self.assertEqual(resp.status_code, 400) resp = delete_entrance_exam(request, self.course.id) self.assertEqual(resp.status_code, 400) # No return, so we'll just ensure no exception is thrown update_entrance_exam(request, self.course.id, {})
andrius-preimantas/partner-contact
refs/heads/8.0
partner_address_street3/tests/__init__.py
34
# -*- coding: utf-8 -*- ############################################################################## # # Author: Nicolas Bessi # Copyright 2014 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import test_street_3
leo23/seafile
refs/heads/master
python/seafile/__init__.py
25
from rpcclient import SeafileRpcClient as RpcClient from rpcclient import SeafileThreadedRpcClient as ThreadedRpcClient from rpcclient import MonitorRpcClient as MonitorRpcClient from rpcclient import SeafServerRpcClient as ServerRpcClient from rpcclient import SeafServerThreadedRpcClient as ServerThreadedRpcClient class TaskType(object): DOWNLOAD = 0 UPLOAD = 1
gchp/django
refs/heads/master
django/template/loaders/locmem.py
464
""" Wrapper for loading templates from a plain Python dict. """ import warnings from django.template import Origin, TemplateDoesNotExist from django.utils.deprecation import RemovedInDjango20Warning from .base import Loader as BaseLoader class Loader(BaseLoader): def __init__(self, engine, templates_dict): self.templates_dict = templates_dict super(Loader, self).__init__(engine) def get_contents(self, origin): try: return self.templates_dict[origin.name] except KeyError: raise TemplateDoesNotExist(origin) def get_template_sources(self, template_name): yield Origin( name=template_name, template_name=template_name, loader=self, ) def load_template_source(self, template_name, template_dirs=None): warnings.warn( 'The load_template_sources() method is deprecated. Use ' 'get_template() or get_contents() instead.', RemovedInDjango20Warning, ) try: return self.templates_dict[template_name], template_name except KeyError: raise TemplateDoesNotExist(template_name)
blackbliss/callme
refs/heads/master
flask/lib/python2.7/site-packages/pip/commands/search.py
344
import sys import textwrap import pip.download from pip.basecommand import Command, SUCCESS from pip.util import get_terminal_size from pip.log import logger from pip.backwardcompat import xmlrpclib, reduce, cmp from pip.exceptions import CommandError from pip.status_codes import NO_MATCHES_FOUND from pip._vendor import pkg_resources from distutils.version import StrictVersion, LooseVersion class SearchCommand(Command): """Search for PyPI packages whose name or summary contains <query>.""" name = 'search' usage = """ %prog [options] <query>""" summary = 'Search PyPI for packages.' def __init__(self, *args, **kw): super(SearchCommand, self).__init__(*args, **kw) self.cmd_opts.add_option( '--index', dest='index', metavar='URL', default='https://pypi.python.org/pypi', help='Base URL of Python Package Index (default %default)') self.parser.insert_option_group(0, self.cmd_opts) def run(self, options, args): if not args: raise CommandError('Missing required argument (search query).') query = args index_url = options.index pypi_hits = self.search(query, index_url) hits = transform_hits(pypi_hits) terminal_width = None if sys.stdout.isatty(): terminal_width = get_terminal_size()[0] print_results(hits, terminal_width=terminal_width) if pypi_hits: return SUCCESS return NO_MATCHES_FOUND def search(self, query, index_url): pypi = xmlrpclib.ServerProxy(index_url) hits = pypi.search({'name': query, 'summary': query}, 'or') return hits def transform_hits(hits): """ The list from pypi is really a list of versions. We want a list of packages with the list of versions stored inline. This converts the list from pypi into one we can use. """ packages = {} for hit in hits: name = hit['name'] summary = hit['summary'] version = hit['version'] score = hit['_pypi_ordering'] if score is None: score = 0 if name not in packages.keys(): packages[name] = {'name': name, 'summary': summary, 'versions': [version], 'score': score} else: packages[name]['versions'].append(version) # if this is the highest version, replace summary and score if version == highest_version(packages[name]['versions']): packages[name]['summary'] = summary packages[name]['score'] = score # each record has a unique name now, so we will convert the dict into a list sorted by score package_list = sorted(packages.values(), key=lambda x: x['score'], reverse=True) return package_list def print_results(hits, name_column_width=25, terminal_width=None): installed_packages = [p.project_name for p in pkg_resources.working_set] for hit in hits: name = hit['name'] summary = hit['summary'] or '' if terminal_width is not None: # wrap and indent summary to fit terminal summary = textwrap.wrap(summary, terminal_width - name_column_width - 5) summary = ('\n' + ' ' * (name_column_width + 3)).join(summary) line = '%s - %s' % (name.ljust(name_column_width), summary) try: logger.notify(line) if name in installed_packages: dist = pkg_resources.get_distribution(name) logger.indent += 2 try: latest = highest_version(hit['versions']) if dist.version == latest: logger.notify('INSTALLED: %s (latest)' % dist.version) else: logger.notify('INSTALLED: %s' % dist.version) logger.notify('LATEST: %s' % latest) finally: logger.indent -= 2 except UnicodeEncodeError: pass def compare_versions(version1, version2): try: return cmp(StrictVersion(version1), StrictVersion(version2)) # in case of abnormal version number, fall back to LooseVersion except ValueError: pass try: return cmp(LooseVersion(version1), LooseVersion(version2)) except TypeError: # certain LooseVersion comparions raise due to unorderable types, # fallback to string comparison return cmp([str(v) for v in LooseVersion(version1).version], [str(v) for v in LooseVersion(version2).version]) def highest_version(versions): return reduce((lambda v1, v2: compare_versions(v1, v2) == 1 and v1 or v2), versions)
steakknife/ldns
refs/heads/master
contrib/python/examples/ldns-keygen.py
8
#!/usr/bin/python # # This example shows how to generate public/private key pair # import ldns algorithm = ldns.LDNS_SIGN_DSA bits = 512 ldns.ldns_init_random(open("/dev/urandom","rb"), (bits+7)//8) domain = ldns.ldns_dname("example.") #generate a new key key = ldns.ldns_key.new_frm_algorithm(algorithm, bits); print key #set owner key.set_pubkey_owner(domain) #create the public from the ldns_key pubkey = key.key_to_rr() #previous command is equivalent to # pubkey = ldns.ldns_key2rr(key) print pubkey #calculate and set the keytag key.set_keytag(ldns.ldns_calc_keytag(pubkey)) #build the DS record ds = ldns.ldns_key_rr2ds(pubkey, ldns.LDNS_SHA1) print ds owner, tag = pubkey.owner(), key.keytag() #write public key to .key file fw = open("key-%s-%d.key" % (owner,tag), "wb") pubkey.print_to_file(fw) #write private key to .priv file fw = open("key-%s-%d.private" % (owner,tag), "wb") key.print_to_file(fw) #write DS to .ds file fw = open("key-%s-%d.ds" % (owner,tag), "wb") ds.print_to_file(fw)
mkrupcale/ansible
refs/heads/devel
lib/ansible/modules/cloud/amazon/ec2_vpc_nacl.py
11
#!/usr/bin/python # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'committer', 'version': '1.0'} DOCUMENTATION = ''' module: ec2_vpc_nacl short_description: create and delete Network ACLs. description: - Read the AWS documentation for Network ACLS U(http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_ACLs.html) version_added: "2.2" options: name: description: - Tagged name identifying a network ACL. required: true vpc_id: description: - VPC id of the requesting VPC. required: true subnets: description: - The list of subnets that should be associated with the network ACL. - Must be specified as a list - Each subnet can be specified as subnet ID, or its tagged name. required: false egress: description: - A list of rules for outgoing traffic. - Each rule must be specified as a list. required: false ingress: description: - List of rules for incoming traffic. - Each rule must be specified as a list. required: false tags: description: - Dictionary of tags to look for and apply when creating a network ACL. required: false state: description: - Creates or modifies an existing NACL - Deletes a NACL and reassociates subnets to the default NACL required: false choices: ['present', 'absent'] default: present author: Mike Mochan(@mmochan) extends_documentation_fragment: aws requirements: [ botocore, boto3, json ] ''' EXAMPLES = ''' # Complete example to create and delete a network ACL # that allows SSH, HTTP and ICMP in, and all traffic out. - name: "Create and associate production DMZ network ACL with DMZ subnets" ec2_vpc_nacl: vpc_id: vpc-12345678 name: prod-dmz-nacl region: ap-southeast-2 subnets: ['prod-dmz-1', 'prod-dmz-2'] tags: CostCode: CC1234 Project: phoenix Description: production DMZ ingress: [ # rule no, protocol, allow/deny, cidr, icmp_code, icmp_type, # port from, port to [100, 'tcp', 'allow', '0.0.0.0/0', null, null, 22, 22], [200, 'tcp', 'allow', '0.0.0.0/0', null, null, 80, 80], [300, 'icmp', 'allow', '0.0.0.0/0', 0, 8], ] egress: [ [100, 'all', 'allow', '0.0.0.0/0', null, null, null, null] ] state: 'present' - name: "Remove the ingress and egress rules - defaults to deny all" ec2_vpc_nacl: vpc_id: vpc-12345678 name: prod-dmz-nacl region: ap-southeast-2 subnets: - prod-dmz-1 - prod-dmz-2 tags: CostCode: CC1234 Project: phoenix Description: production DMZ state: present - name: "Remove the NACL subnet associations and tags" ec2_vpc_nacl: vpc_id: 'vpc-12345678' name: prod-dmz-nacl region: ap-southeast-2 state: present - name: "Delete nacl and subnet associations" ec2_vpc_nacl: vpc_id: vpc-12345678 name: prod-dmz-nacl state: absent ''' RETURN = ''' task: description: The result of the create, or delete action. returned: success type: dictionary ''' try: import botocore import boto3 HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import boto3_conn, ec2_argument_spec, get_aws_connection_info # Common fields for the default rule that is contained within every VPC NACL. DEFAULT_RULE_FIELDS = { 'RuleNumber': 32767, 'RuleAction': 'deny', 'CidrBlock': '0.0.0.0/0', 'Protocol': '-1' } DEFAULT_INGRESS = dict(DEFAULT_RULE_FIELDS.items() + [('Egress', False)]) DEFAULT_EGRESS = dict(DEFAULT_RULE_FIELDS.items() + [('Egress', True)]) # VPC-supported IANA protocol numbers # http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml PROTOCOL_NUMBERS = {'all': -1, 'icmp': 1, 'tcp': 6, 'udp': 17, } #Utility methods def icmp_present(entry): if len(entry) == 6 and entry[1] == 'icmp' or entry[1] == 1: return True def load_tags(module): tags = [] if module.params.get('tags'): for name, value in module.params.get('tags').iteritems(): tags.append({'Key': name, 'Value': str(value)}) tags.append({'Key': "Name", 'Value': module.params.get('name')}) else: tags.append({'Key': "Name", 'Value': module.params.get('name')}) return tags def subnets_removed(nacl_id, subnets, client, module): results = find_acl_by_id(nacl_id, client, module) associations = results['NetworkAcls'][0]['Associations'] subnet_ids = [assoc['SubnetId'] for assoc in associations] return [subnet for subnet in subnet_ids if subnet not in subnets] def subnets_added(nacl_id, subnets, client, module): results = find_acl_by_id(nacl_id, client, module) associations = results['NetworkAcls'][0]['Associations'] subnet_ids = [assoc['SubnetId'] for assoc in associations] return [subnet for subnet in subnets if subnet not in subnet_ids] def subnets_changed(nacl, client, module): changed = False vpc_id = module.params.get('vpc_id') nacl_id = nacl['NetworkAcls'][0]['NetworkAclId'] subnets = subnets_to_associate(nacl, client, module) if not subnets: default_nacl_id = find_default_vpc_nacl(vpc_id, client, module)[0] subnets = find_subnet_ids_by_nacl_id(nacl_id, client, module) if subnets: replace_network_acl_association(default_nacl_id, subnets, client, module) changed = True return changed changed = False return changed subs_added = subnets_added(nacl_id, subnets, client, module) if subs_added: replace_network_acl_association(nacl_id, subs_added, client, module) changed = True subs_removed = subnets_removed(nacl_id, subnets, client, module) if subs_removed: default_nacl_id = find_default_vpc_nacl(vpc_id, client, module)[0] replace_network_acl_association(default_nacl_id, subs_removed, client, module) changed = True return changed def nacls_changed(nacl, client, module): changed = False params = dict() params['egress'] = module.params.get('egress') params['ingress'] = module.params.get('ingress') nacl_id = nacl['NetworkAcls'][0]['NetworkAclId'] nacl = describe_network_acl(client, module) entries = nacl['NetworkAcls'][0]['Entries'] tmp_egress = [entry for entry in entries if entry['Egress'] is True and DEFAULT_EGRESS !=entry] tmp_ingress = [entry for entry in entries if entry['Egress'] is False] egress = [rule for rule in tmp_egress if DEFAULT_EGRESS != rule] ingress = [rule for rule in tmp_ingress if DEFAULT_INGRESS != rule] if rules_changed(egress, params['egress'], True, nacl_id, client, module): changed = True if rules_changed(ingress, params['ingress'], False, nacl_id, client, module): changed = True return changed def tags_changed(nacl_id, client, module): changed = False tags = dict() if module.params.get('tags'): tags = module.params.get('tags') tags['Name'] = module.params.get('name') nacl = find_acl_by_id(nacl_id, client, module) if nacl['NetworkAcls']: nacl_values = [t.values() for t in nacl['NetworkAcls'][0]['Tags']] nacl_tags = [item for sublist in nacl_values for item in sublist] tag_values = [[key, str(value)] for key, value in tags.iteritems()] tags = [item for sublist in tag_values for item in sublist] if sorted(nacl_tags) == sorted(tags): changed = False return changed else: delete_tags(nacl_id, client, module) create_tags(nacl_id, client, module) changed = True return changed return changed def rules_changed(aws_rules, param_rules, Egress, nacl_id, client, module): changed = False rules = list() for entry in param_rules: rules.append(process_rule_entry(entry, Egress)) if rules == aws_rules: return changed else: removed_rules = [x for x in aws_rules if x not in rules] if removed_rules: params = dict() for rule in removed_rules: params['NetworkAclId'] = nacl_id params['RuleNumber'] = rule['RuleNumber'] params['Egress'] = Egress delete_network_acl_entry(params, client, module) changed = True added_rules = [x for x in rules if x not in aws_rules] if added_rules: for rule in added_rules: rule['NetworkAclId'] = nacl_id create_network_acl_entry(rule, client, module) changed = True return changed def process_rule_entry(entry, Egress): params = dict() params['RuleNumber'] = entry[0] params['Protocol'] = str(PROTOCOL_NUMBERS[entry[1]]) params['RuleAction'] = entry[2] params['Egress'] = Egress params['CidrBlock'] = entry[3] if icmp_present(entry): params['IcmpTypeCode'] = {"Type": int(entry[4]), "Code": int(entry[5])} else: if entry[6] or entry[7]: params['PortRange'] = {"From": entry[6], 'To': entry[7]} return params def restore_default_associations(assoc_ids, default_nacl_id, client, module): if assoc_ids: params = dict() params['NetworkAclId'] = default_nacl_id[0] for assoc_id in assoc_ids: params['AssociationId'] = assoc_id restore_default_acl_association(params, client, module) return True def construct_acl_entries(nacl, client, module): for entry in module.params.get('ingress'): params = process_rule_entry(entry, Egress=False) params['NetworkAclId'] = nacl['NetworkAcl']['NetworkAclId'] create_network_acl_entry(params, client, module) for rule in module.params.get('egress'): params = process_rule_entry(rule, Egress=True) params['NetworkAclId'] = nacl['NetworkAcl']['NetworkAclId'] create_network_acl_entry(params, client, module) ## Module invocations def setup_network_acl(client, module): changed = False nacl = describe_network_acl(client, module) if not nacl['NetworkAcls']: nacl = create_network_acl(module.params.get('vpc_id'), client, module) nacl_id = nacl['NetworkAcl']['NetworkAclId'] create_tags(nacl_id, client, module) subnets = subnets_to_associate(nacl, client, module) replace_network_acl_association(nacl_id, subnets, client, module) construct_acl_entries(nacl, client, module) changed = True return(changed, nacl['NetworkAcl']['NetworkAclId']) else: changed = False nacl_id = nacl['NetworkAcls'][0]['NetworkAclId'] subnet_result = subnets_changed(nacl, client, module) nacl_result = nacls_changed(nacl, client, module) tag_result = tags_changed(nacl_id, client, module) if subnet_result is True or nacl_result is True or tag_result is True: changed = True return(changed, nacl_id) return (changed, nacl_id) def remove_network_acl(client, module): changed = False result = dict() vpc_id = module.params.get('vpc_id') nacl = describe_network_acl(client, module) if nacl['NetworkAcls']: nacl_id = nacl['NetworkAcls'][0]['NetworkAclId'] associations = nacl['NetworkAcls'][0]['Associations'] assoc_ids = [a['NetworkAclAssociationId'] for a in associations] default_nacl_id = find_default_vpc_nacl(vpc_id, client, module) if not default_nacl_id: result = {vpc_id: "Default NACL ID not found - Check the VPC ID"} return changed, result if restore_default_associations(assoc_ids, default_nacl_id, client, module): delete_network_acl(nacl_id, client, module) changed = True result[nacl_id] = "Successfully deleted" return changed, result if not assoc_ids: delete_network_acl(nacl_id, client, module) changed = True result[nacl_id] = "Successfully deleted" return changed, result return changed, result #Boto3 client methods def create_network_acl(vpc_id, client, module): try: nacl = client.create_network_acl(VpcId=vpc_id) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) return nacl def create_network_acl_entry(params, client, module): try: result = client.create_network_acl_entry(**params) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) return result def create_tags(nacl_id, client, module): try: delete_tags(nacl_id, client, module) client.create_tags(Resources=[nacl_id], Tags=load_tags(module)) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) def delete_network_acl(nacl_id, client, module): try: client.delete_network_acl(NetworkAclId=nacl_id) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) def delete_network_acl_entry(params, client, module): try: client.delete_network_acl_entry(**params) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) def delete_tags(nacl_id, client, module): try: client.delete_tags(Resources=[nacl_id]) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) def describe_acl_associations(subnets, client, module): if not subnets: return [] try: results = client.describe_network_acls(Filters=[ {'Name': 'association.subnet-id', 'Values': subnets} ]) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) associations = results['NetworkAcls'][0]['Associations'] return [a['NetworkAclAssociationId'] for a in associations if a['SubnetId'] in subnets] def describe_network_acl(client, module): try: nacl = client.describe_network_acls(Filters=[ {'Name': 'tag:Name', 'Values': [module.params.get('name')]} ]) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) return nacl def find_acl_by_id(nacl_id, client, module): try: return client.describe_network_acls(NetworkAclIds=[nacl_id]) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) def find_default_vpc_nacl(vpc_id, client, module): try: response = client.describe_network_acls(Filters=[ {'Name': 'vpc-id', 'Values': [vpc_id]}]) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) nacls = response['NetworkAcls'] return [n['NetworkAclId'] for n in nacls if n['IsDefault'] == True] def find_subnet_ids_by_nacl_id(nacl_id, client, module): try: results = client.describe_network_acls(Filters=[ {'Name': 'association.network-acl-id', 'Values': [nacl_id]} ]) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) if results['NetworkAcls']: associations = results['NetworkAcls'][0]['Associations'] return [s['SubnetId'] for s in associations if s['SubnetId']] else: return [] def replace_network_acl_association(nacl_id, subnets, client, module): params = dict() params['NetworkAclId'] = nacl_id for association in describe_acl_associations(subnets, client, module): params['AssociationId'] = association try: client.replace_network_acl_association(**params) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) def replace_network_acl_entry(entries, Egress, nacl_id, client, module): params = dict() for entry in entries: params = entry params['NetworkAclId'] = nacl_id try: client.replace_network_acl_entry(**params) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) def restore_default_acl_association(params, client, module): try: client.replace_network_acl_association(**params) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) def subnets_to_associate(nacl, client, module): params = list(module.params.get('subnets')) if not params: return [] if params[0].startswith("subnet-"): try: subnets = client.describe_subnets(Filters=[ {'Name': 'subnet-id', 'Values': params}]) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) else: try: subnets = client.describe_subnets(Filters=[ {'Name': 'tag:Name', 'Values': params}]) except botocore.exceptions.ClientError as e: module.fail_json(msg=str(e)) return [s['SubnetId'] for s in subnets['Subnets'] if s['SubnetId']] def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( vpc_id=dict(required=True), name=dict(required=True), subnets=dict(required=False, type='list', default=list()), tags=dict(required=False, type='dict'), ingress=dict(required=False, type='list', default=list()), egress=dict(required=False, type='list', default=list(),), state=dict(default='present', choices=['present', 'absent']), ), ) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO3: module.fail_json(msg='json, botocore and boto3 are required.') state = module.params.get('state').lower() try: region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) client = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs) except botocore.exceptions.NoCredentialsError as e: module.fail_json(msg="Can't authorize connection - %s" % str(e)) invocations = { "present": setup_network_acl, "absent": remove_network_acl } (changed, results) = invocations[state](client, module) module.exit_json(changed=changed, nacl_id=results) if __name__ == '__main__': main()
SeedScientific/luigi
refs/heads/master
luigi/rpc.py
10
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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. # """ Implementation of the REST interface between the workers and the server. rpc.py implements the client side of it, server.py implements the server side. See :doc:`/central_scheduler` for more info. """ import json import logging import socket import time from luigi.six.moves.urllib.parse import urlencode from luigi.six.moves.urllib.request import Request, urlopen from luigi.six.moves.urllib.error import URLError from luigi import configuration from luigi.scheduler import PENDING, Scheduler logger = logging.getLogger('luigi-interface') # TODO: 'interface'? class RPCError(Exception): def __init__(self, message, sub_exception=None): super(RPCError, self).__init__(message) self.sub_exception = sub_exception class RemoteScheduler(Scheduler): """ Scheduler proxy object. Talks to a RemoteSchedulerResponder. """ def __init__(self, host='localhost', port=8082, connect_timeout=None, url_prefix=''): self._host = host self._port = port self._url_prefix = url_prefix config = configuration.get_config() if connect_timeout is None: connect_timeout = config.getfloat('core', 'rpc-connect-timeout', 10.0) self._connect_timeout = connect_timeout def _wait(self): time.sleep(30) def _fetch(self, url, body, log_exceptions=True, attempts=3): full_url = 'http://{host}:{port:d}{prefix}{url}'.format( host=self._host, port=self._port, prefix=self._url_prefix, url=url) last_exception = None attempt = 0 while attempt < attempts: attempt += 1 if last_exception: logger.info("Retrying...") self._wait() # wait for a bit and retry try: response = urlopen(full_url, body, self._connect_timeout) break except (URLError, socket.timeout) as e: last_exception = e if log_exceptions: logger.exception("Failed connecting to remote scheduler %r", self._host) continue else: raise RPCError( "Errors (%d attempts) when connecting to remote scheduler %r" % (attempts, self._host), last_exception ) return response.read().decode('utf-8') def _request(self, url, data, log_exceptions=True, attempts=3): data = {'data': json.dumps(data)} body = urlencode(data).encode('utf-8') page = self._fetch(url, body, log_exceptions, attempts) result = json.loads(page) return result["response"] def ping(self, worker): # just one attemtps, keep-alive thread will keep trying anyway self._request('/api/ping', {'worker': worker}, attempts=1) def add_task(self, worker, task_id, status=PENDING, runnable=True, deps=None, new_deps=None, expl=None, resources=None, priority=0, family='', module=None, params=None, assistant=False): self._request('/api/add_task', { 'task_id': task_id, 'worker': worker, 'status': status, 'runnable': runnable, 'deps': deps, 'new_deps': new_deps, 'expl': expl, 'resources': resources, 'priority': priority, 'family': family, 'module': module, 'params': params, 'assistant': assistant, }) def get_work(self, worker, host=None, assistant=False): return self._request( '/api/get_work', {'worker': worker, 'host': host, 'assistant': assistant}, log_exceptions=False, attempts=1) def graph(self): return self._request('/api/graph', {}) def dep_graph(self, task_id): return self._request('/api/dep_graph', {'task_id': task_id}) def inverse_dep_graph(self, task_id): return self._request('/api/inverse_dep_graph', {'task_id': task_id}) def task_list(self, status, upstream_status, search=None): return self._request('/api/task_list', { 'search': search, 'status': status, 'upstream_status': upstream_status, }) def worker_list(self): return self._request('/api/worker_list', {}) def task_search(self, task_str): return self._request('/api/task_search', {'task_str': task_str}) def fetch_error(self, task_id): return self._request('/api/fetch_error', {'task_id': task_id}) def add_worker(self, worker, info): return self._request('/api/add_worker', {'worker': worker, 'info': info}) def update_resources(self, **resources): return self._request('/api/update_resources', resources) def prune(self): return self._request('/api/prune', {}) def re_enable_task(self, task_id): return self._request('/api/re_enable_task', {'task_id': task_id})
atagar/ReviewBoard
refs/heads/master
reviewboard/scmtools/sshutils.py
3
import logging import os import urlparse from django.utils.translation import ugettext_lazy as _ import paramiko from reviewboard.scmtools.errors import AuthenticationError, \ BadHostKeyError, SCMError, \ UnknownHostKeyError, \ UnsupportedSSHKeyError # A list of known SSH URL schemes. ssh_uri_schemes = ["ssh", "sftp"] urlparse.uses_netloc.extend(ssh_uri_schemes) _ssh_dir = None class RaiseUnknownHostKeyPolicy(paramiko.MissingHostKeyPolicy): """A Paramiko policy that raises UnknownHostKeyError for missing keys.""" def missing_host_key(self, client, hostname, key): raise UnknownHostKeyError(hostname, key) class MakeSSHDirError(IOError): def __init__(self, dirname): IOError.__init__(_("Unable to create directory %(dirname)s, which is " "needed for the SSH host keys. Create this " "directory, set the web server's user as the " "the owner, and make it writable only by that " "user.") % { 'dirname': dirname, }) def humanize_key(key): """Returns a human-readable key as a series of hex characters.""" return ':'.join(["%02x" % ord(c) for c in key.get_fingerprint()]) def set_ssh_dir(path): """Sets the SSH directory to use. This is mostly intended for unit tests. """ global _ssh_dir _ssh_dir = path def get_ssh_dir(local_site_name=None, ssh_dir_name=None): """Returns the path to the SSH directory on the system. By default, this will attempt to find either a .ssh or ssh directory. If ``ssh_dir_name`` is specified, the search will be skipped, and we'll use that name instead. """ global _ssh_dir path = _ssh_dir if not _ssh_dir or ssh_dir_name: path = os.path.expanduser('~') if not ssh_dir_name: ssh_dir_name = '.ssh' for name in ('.ssh', 'ssh'): if os.path.exists(os.path.join(path, name)): ssh_dir_name = name break path = os.path.join(path, ssh_dir_name) if not ssh_dir_name: _ssh_dir = path if local_site_name: return os.path.join(path, local_site_name) else: return path def get_host_keys_filename(local_site_name=None): """Returns the path to the known host keys file.""" return os.path.join(get_ssh_dir(local_site_name), 'known_hosts') def get_user_key(local_site_name=None): """Returns the keypair of the user running Review Board. This will be an instance of :py:mod:`paramiko.PKey`, representing a DSS or RSA key, as long as one exists. Otherwise, it may return None. """ keyfiles = [] for cls, filename in ((paramiko.RSAKey, 'id_rsa'), (paramiko.DSSKey, 'id_dsa')): # Paramiko looks in ~/.ssh and ~/ssh, depending on the platform, # so check both. for sshdir in ('.ssh', 'ssh'): path = os.path.join(get_ssh_dir(local_site_name, sshdir), filename) if os.path.isfile(path): keyfiles.append((cls, path)) for cls, keyfile in keyfiles: try: return cls.from_private_key_file(keyfile) except paramiko.SSHException, e: logging.error('SSH: Unknown error accessing local key file %s: %s' % (keyfile, e)) except paramiko.PasswordRequiredException, e: logging.error('SSH: Unable to access password protected key file ' '%s: %s' % (keyfile, e)) except IOError, e: logging.error('SSH: Error reading local key file %s: %s' % (keyfile, e)) return None def get_public_key(key): """Returns the public key portion of an SSH key. This will be formatted for display. """ public_key = '' if key: base64 = key.get_base64() # TODO: Move this wrapping logic into a common templatetag. for i in range(0, len(base64), 64): public_key += base64[i:i + 64] + '\n' return public_key def is_key_authorized(key): """Returns whether or not a public key is currently authorized.""" authorized = False public_key = key.get_base64() try: filename = os.path.join(get_ssh_dir(), 'authorized_keys') fp = open(filename, 'r') for line in fp.xreadlines(): try: authorized_key = line.split()[1] except ValueError: continue except IndexError: continue if authorized_key == public_key: authorized = True break fp.close() except IOError: pass return authorized def ensure_ssh_dir(local_site_name=None): """Ensures the existance of the .ssh directory. If the directory doesn't exist, it will be created. The full path to the directory will be returned. Callers are expected to handle any exceptions. This may raise IOError for any problems in creating the directory. """ sshdir = get_ssh_dir(local_site_name) if local_site_name: # The parent will be the .ssh dir. parent = os.path.dirname(sshdir) if not os.path.exists(parent): try: os.mkdir(parent, 0700) except OSError: raise MakeSSHDirError(parent) if not os.path.exists(sshdir): try: os.mkdir(sshdir, 0700) except OSError: raise MakeSSHDirError(sshdir) return sshdir def generate_user_key(local_site_name=None): """Generates a new RSA keypair for the user running Review Board. This will store the new key in :file:`$HOME/.ssh/id_rsa` and return the resulting key as an instance of :py:mod:`paramiko.RSAKey`. If a key already exists in the id_rsa file, it's returned instead. Callers are expected to handle any exceptions. This may raise IOError for any problems in writing the key file, or paramiko.SSHException for any other problems. """ sshdir = ensure_ssh_dir(local_site_name) filename = os.path.join(sshdir, 'id_rsa') if os.path.isfile(filename): return get_user_key(local_site_name) key = paramiko.RSAKey.generate(2048) key.write_private_key_file(filename) return key def import_user_key(keyfile, local_site_name=None): """Imports an uploaded key file into Review Board. ``keyfile`` is expected to be an ``UploadedFile`` or a paramiko ``KeyFile``. If this is a valid key file, it will be saved in :file:`$HOME/.ssh/`` and the resulting key as an instance of :py:mod:`paramiko.RSAKey` will be returned. If a key of this name already exists, it will be overwritten. Callers are expected to handle any exceptions. This may raise IOError for any problems in writing the key file, or paramiko.SSHException for any other problems. This will raise UnsupportedSSHKeyError if the uploaded key is not a supported type. """ sshdir = ensure_ssh_dir(local_site_name) # Try to find out what key this is. for cls, filename in ((paramiko.RSAKey, 'id_rsa'), (paramiko.DSSKey, 'id_dsa')): try: key = None if not isinstance(keyfile, paramiko.PKey): keyfile.seek(0) key = cls.from_private_key(keyfile) elif isinstance(keyfile, cls): key = keyfile except paramiko.SSHException: # We don't have more detailed info than this, but most # likely, it's not a valid key. Skip to the next. continue if key: key.write_private_key_file(os.path.join(sshdir, filename)) return key raise UnsupportedSSHKeyError() def is_ssh_uri(url): """Returns whether or not a URL represents an SSH connection.""" return urlparse.urlparse(url)[0] in ssh_uri_schemes def get_ssh_client(local_site_name=None): """Returns a new paramiko.SSHClient with all known host keys added.""" client = paramiko.SSHClient() filename = get_host_keys_filename(local_site_name) if os.path.exists(filename): client.load_host_keys(filename) return client def add_host_key(hostname, key, local_site_name=None): """Adds a host key to the known hosts file.""" ensure_ssh_dir(local_site_name) filename = get_host_keys_filename(local_site_name) try: fp = open(filename, 'a') fp.write('%s %s %s\n' % (hostname, key.get_name(), key.get_base64())) fp.close() except IOError, e: raise IOError( _('Unable to write host keys file %(filename)s: %(error)s') % { 'filename': filename, 'error': e, }) def replace_host_key(hostname, old_key, new_key, local_site_name=None): """Replaces a host key in the known hosts file with another. This is used for replacing host keys that have changed. """ filename = get_host_keys_filename(local_site_name) if not os.path.exists(filename): add_host_key(hostname, new_key, local_site_name) return try: fp = open(filename, 'r') lines = fp.readlines() fp.close() old_key_base64 = old_key.get_base64() except IOError, e: raise IOError( _('Unable to read host keys file %(filename)s: %(error)s') % { 'filename': filename, 'error': e, }) try: fp = open(filename, 'w') for line in lines: parts = line.strip().split(" ") if parts[-1] == old_key_base64: parts[-1] = new_key.get_base64() fp.write(' '.join(parts) + '\n') fp.close() except IOError, e: raise IOError( _('Unable to write host keys file %(filename)s: %(error)s') % { 'filename': filename, 'error': e, }) def check_host(hostname, username=None, password=None, local_site_name=None): """ Checks if we can connect to a host with a known key. This will raise an exception if we cannot connect to the host. The exception will be one of BadHostKeyError, UnknownHostKeyError, or SCMError. """ from django.conf import settings client = get_ssh_client(local_site_name) client.set_missing_host_key_policy(RaiseUnknownHostKeyPolicy()) kwargs = {} # We normally want to notify on unknown host keys, but not when running # unit tests. if getattr(settings, 'RUNNING_TEST', False): client.set_missing_host_key_policy(paramiko.WarningPolicy()) kwargs['allow_agent'] = False try: client.connect(hostname, username=username, password=password, pkey=get_user_key(local_site_name), **kwargs) except paramiko.BadHostKeyException, e: raise BadHostKeyError(e.hostname, e.key, e.expected_key) except paramiko.AuthenticationException, e: # Some AuthenticationException instances have allowed_types set, # and some don't. allowed_types = getattr(e, 'allowed_types', []) if 'publickey' in allowed_types: key = get_user_key(local_site_name) else: key = None raise AuthenticationError(allowed_types=allowed_types, user_key=key) except paramiko.SSHException, e: if str(e) == 'No authentication methods available': raise AuthenticationError else: raise SCMError(unicode(e)) def register_rbssh(envvar): """Registers rbssh in an environment variable. This is a convenience method for making sure that rbssh is set properly in the environment for different tools. In some cases, we need to specifically place it in the system environment using ``os.putenv``, while in others (Mercurial, Bazaar), we need to place it in ``os.environ``. """ os.putenv(envvar, 'rbssh') os.environ[envvar] = 'rbssh'
lgscofield/odoo
refs/heads/8.0
addons/website/tests/__init__.py
396
# -*- coding: utf-8 -*- import test_converter import test_crawl import test_ui import test_views
martinspeleo/PaTOCalc
refs/heads/master
PaTOCalc/calc/migrations/0006_forminstance_form_generator.py
1
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-31 09:26 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('calc', '0005_auto_20160130_1549'), ] operations = [ migrations.AddField( model_name='forminstance', name='form_generator', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='calc.FormGenerator'), preserve_default=False, ), ]
indashnet/InDashNet.Open.UN2000
refs/heads/master
android/external/chromium_org/tools/perf/measurements/smoothness.py
23
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from metrics import loading from metrics import smoothness from metrics.gpu_rendering_stats import GpuRenderingStats from telemetry.page import page_measurement class DidNotScrollException(page_measurement.MeasurementFailure): def __init__(self): super(DidNotScrollException, self).__init__('Page did not scroll') class MissingDisplayFrameRate(page_measurement.MeasurementFailure): def __init__(self, name): super(MissingDisplayFrameRate, self).__init__( 'Missing display frame rate metrics: ' + name) class Smoothness(page_measurement.PageMeasurement): def __init__(self): super(Smoothness, self).__init__('smoothness') self.force_enable_threaded_compositing = False self.use_gpu_benchmarking_extension = True self._metrics = None def AddCommandLineOptions(self, parser): parser.add_option('--report-all-results', dest='report_all_results', action='store_true', help='Reports all data collected, not just FPS') def CustomizeBrowserOptions(self, options): if self.use_gpu_benchmarking_extension: options.extra_browser_args.append('--enable-gpu-benchmarking') if self.force_enable_threaded_compositing: options.extra_browser_args.append('--enable-threaded-compositing') def CanRunForPage(self, page): return hasattr(page, 'smoothness') def WillRunAction(self, page, tab, action): if tab.browser.platform.IsRawDisplayFrameRateSupported(): tab.browser.platform.StartRawDisplayFrameRateMeasurement() self._metrics = smoothness.SmoothnessMetrics(tab) if action.CanBeBound(): self._metrics.BindToAction(action) else: self._metrics.Start() def DidRunAction(self, page, tab, action): if tab.browser.platform.IsRawDisplayFrameRateSupported(): tab.browser.platform.StopRawDisplayFrameRateMeasurement() if not action.CanBeBound(): self._metrics.Stop() def MeasurePage(self, page, tab, results): rendering_stats_deltas = self._metrics.deltas if not (rendering_stats_deltas['numFramesSentToScreen'] > 0): raise DidNotScrollException() loading.LoadingMetric().AddResults(tab, results) smoothness.CalcFirstPaintTimeResults(results, tab) benchmark_stats = GpuRenderingStats(rendering_stats_deltas) smoothness.CalcResults(benchmark_stats, results) if self.options.report_all_results: for k, v in rendering_stats_deltas.iteritems(): results.Add(k, '', v) if tab.browser.platform.IsRawDisplayFrameRateSupported(): for r in tab.browser.platform.GetRawDisplayFrameRateMeasurements(): if r.value is None: raise MissingDisplayFrameRate(r.name) results.Add(r.name, r.unit, r.value)
tomas-mazak/taipan
refs/heads/master
taipan/tegakigtk/chartable.py
1
# -*- coding: utf-8 -*- # Copyright (C) 2009 The Tegaki project contributors # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 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. # Contributors to this file: # - Mathieu Blondel import gtk from gtk import gdk import gobject import pango import math import time from tegaki.character import * class CharTable(gtk.Widget): """ A nifty character table. A port of Takuro Ashie's TomoeCharTable to pygtk. """ LAYOUT_SINGLE_HORIZONTAL = 0 LAYOUT_SINGLE_VERTICAL = 1 LAYOUT_HORIZONTAL = 2 LAYOUT_VERTICAL = 3 DEFAULT_FONT_SCALE = 2.0 #pango.SCALE_XX_LARGE __gsignals__ = { "character_selected" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_PYOBJECT]) } def __init__(self): gtk.Widget.__init__(self) self._pixmap = None self._padding = 2 self._selected = None self._prelighted = None self._layout = self.LAYOUT_SINGLE_HORIZONTAL self._h_adj = None self._v_adj = None self.clear() self.connect("motion_notify_event", self.motion_notify_event) # Events... def do_realize(self): """ Called when the widget should create all of its windowing resources. We will create our gtk.gdk.Window. """ # Set an internal flag telling that we're realized self.set_flags(self.flags() | gtk.REALIZED) # Create a new gdk.Window which we can draw on. # Also say that we want to receive exposure events # and button click and button press events self.window = gdk.Window(self.get_parent_window(), x=self.allocation.x, y=self.allocation.y, width=self.allocation.width, height=self.allocation.height, window_type=gdk.WINDOW_CHILD, wclass=gdk.INPUT_OUTPUT, visual=self.get_visual(), colormap=self.get_colormap(), event_mask=gdk.EXPOSURE_MASK | gdk.BUTTON_PRESS_MASK | gdk.BUTTON_RELEASE_MASK | gdk.POINTER_MOTION_MASK | gdk.POINTER_MOTION_HINT_MASK | gdk.ENTER_NOTIFY_MASK | gdk.LEAVE_NOTIFY_MASK) # Associate the gdk.Window with ourselves, Gtk+ needs a reference # between the widget and the gdk window self.window.set_user_data(self) # Attach the style to the gdk.Window, a style contains colors and # GC contextes used for drawing self.style.attach(self.window) # The default color of the background should be what # the style (theme engine) tells us. self.style.set_background(self.window, gtk.STATE_NORMAL) self.window.move_resize(*self.allocation) # Font font_desc = self.style.font_desc.copy() size = font_desc.get_size() font_desc.set_size(int(size * self.DEFAULT_FONT_SCALE)) self.modify_font(font_desc) def do_unrealize(self): """ The do_unrealized method is responsible for freeing the GDK resources De-associate the window we created in do_realize with ourselves """ self.window.destroy() def do_size_request(self, requisition): """ The do_size_request method Gtk+ is called on a widget to ask it the widget how large it wishes to be. It's not guaranteed that gtk+ will actually give this size to the widget. """ self.ensure_style() context = self.get_pango_context() metrics = context.get_metrics(self.style.font_desc, context.get_language()) # width char_width = metrics.get_approximate_char_width() digit_width = metrics.get_approximate_digit_width() char_pixels = pango.PIXELS(int(max(char_width, digit_width) * self.DEFAULT_FONT_SCALE)) requisition.width = char_pixels + self._padding * 2 # height ascent = metrics.get_ascent() descent = metrics.get_descent() requisition.height = pango.PIXELS(ascent + descent) + self._padding * 2 def do_size_allocate(self, allocation): """ The do_size_allocate is called when the actual size is known and the widget is told how much space could actually be allocated.""" self.allocation = allocation self.width = self.allocation.width self.height = self.allocation.height if self.flags() & gtk.REALIZED: self.window.move_resize(*allocation) self._pixmap = gdk.Pixmap(self.window, self.width, self.height) self.draw() def do_expose_event(self, event): """ This is where the widget must draw itself. """ retval = False if self.flags() & gtk.REALIZED and not self._pixmap: self._pixmap = gdk.Pixmap(self.window, self.allocation.width, self.allocation.height) self._adjust_adjustments() self.draw() if self._pixmap: self.window.draw_drawable(self.style.fg_gc[self.state], self._pixmap, event.area.x, event.area.y, event.area.x, event.area.y, event.area.width, event.area.height) return retval def motion_notify_event(self, widget, event): retval = False if event.is_hint: x, y, state = event.window.get_pointer() else: x = event.x y = event.y state = event.state prev_prelighted = self._prelighted self._prelighted = self._get_char_id_from_coordinates(x, y) if prev_prelighted != self._prelighted: self.draw() return retval def do_button_press_event(self, event): retval = False prev_selected = self._selected self._selected = self._get_char_id_from_coordinates(event.x, event.y) if prev_selected != self._selected: self.draw() if self._selected >= 0: self.emit("character_selected", event) return retval def do_button_release_event(self, event): return False def get_max_char_size(self): context = self.get_pango_context() metrics = context.get_metrics(self.style.font_desc, context.get_language()) # width char_width = metrics.get_approximate_char_width() digit_width = metrics.get_approximate_digit_width() max_char_width = pango.PIXELS(int(max(char_width, digit_width) * self.DEFAULT_FONT_SCALE)) # height ascent = metrics.get_ascent() descent = metrics.get_descent() max_char_height = pango.PIXELS(int((ascent + descent) * self.DEFAULT_FONT_SCALE)) return (max_char_width, max_char_height) def _get_char_frame_size(self): sizes = [layout.get_pixel_size() for layout in self._layouts] if len(sizes) > 0: inner_width = max([size[0] for size in sizes]) inner_height = max([size[1] for size in sizes]) else: inner_width, inner_height = self.get_max_char_size() outer_width = inner_width + 2 * self._padding outer_height = inner_height + 2 * self._padding return [inner_width, inner_height, outer_width, outer_height] def _get_char_id_from_coordinates(self, x, y): inner_width, inner_height, outer_width, outer_height = \ self._get_char_frame_size() h_offset = 0; v_offset = 0 if self._h_adj: h_offset = h_adj.get_value() if self._v_adj: v_offset = v_adj.get_value() # Calculate columns for horizontal layout cols = self.allocation.width / outer_width if cols <= 0: cols = 1 # Calculate rows for vertical layout rows = self.allocation.height / outer_height if rows <= 0: rows = 1 for i in range(len(self._layouts)): if self._layout == self.LAYOUT_SINGLE_HORIZONTAL: area_x = outer_width * i - h_offset if x >= area_x and x < area_x + outer_width: return i elif self._layout == self.LAYOUT_SINGLE_VERTICAL: area_y = outer_height * i - v_offset if y >= area_y and y < area_y + outer_height: return i elif self._layout == self.LAYOUT_HORIZONTAL: area_x = outer_width * (i % cols) - h_offset area_y = outer_height * (i / cols) - v_offset if x >= area_x and x < area_x + outer_width and \ y >= area_y and y < area_y + outer_height: return i elif self._layout == self.LAYOUT_VERTICAL: area_x = outer_width * (i / rows) - h_offset area_y = outer_height * (i % rows) - v_offset if x >= area_x and x < area_x + outer_width and \ y >= area_y and y < area_y + outer_height: return i return None def _adjust_adjustments(self): pass def draw(self): if not self._pixmap: return inner_width, inner_height, outer_width, outer_height = \ self._get_char_frame_size() y_pos = (self.allocation.height - inner_height) / 2 x_pos = (self.allocation.width - inner_width) / 2 cols = self.allocation.width / outer_width if cols <= 0: cols = 1 rows = self.allocation.height / outer_height if rows <= 0: rows = 1 h_offset = 0; v_offset = 0 if self._h_adj: h_offset = h_adj.get_value() if self._v_adj: v_offset = v_adj.get_value() # Fill background self._pixmap.draw_rectangle(self.style.white_gc, True, 0, 0, self.allocation.width, self.allocation.height) # Draw characters for i in range(len(self._layouts)): layout = self._layouts[i] selected = i == self._selected char_width, char_height = layout.get_pixel_size() if self._layout == self.LAYOUT_SINGLE_HORIZONTAL: outer_x = outer_width * i - h_offset outer_y = 0 outer_height = self.allocation.height inner_x = outer_x + (outer_width - char_width) / 2 inner_y = y_pos if outer_x + outer_width < 0: continue if outer_x + outer_width > self.allocation.width: break elif self._layout == self.LAYOUT_SINGLE_VERTICAL: outer_x = 0 outer_y = outer_height * i - v_offset outer_width = self.allocation.width inner_x = x_pos inner_y = outer_y + (outer_height - char_height) / 2 if outer_y + outer_height < 0: continue if outer_y + outer_height > self.allocation.height: break elif self._layout == self.LAYOUT_HORIZONTAL: outer_x = outer_width * (i % cols) - h_offset outer_y = outer_height * (i / cols) - v_offset inner_x = outer_x + (outer_width - char_width) / 2 inner_y = outer_y + (outer_height - char_height) / 2 if outer_y + outer_height < 0: continue if outer_y + outer_height > self.allocation.height: break elif self._layout == self.LAYOUT_VERTICAL: outer_x = outer_width * (i / rows) - h_offset outer_y = outer_height * (i % rows) - v_offset inner_x = outer_x + (outer_width - char_width) / 2 inner_y = outer_y + (outer_height - char_height) / 2 if outer_x + outer_width < 0: continue if outer_x + outer_width > self.allocation.width: break if selected: outer_gc = self.style.bg_gc[gtk.STATE_SELECTED] inner_gc = self.style.white_gc else: outer_gc = self.style.white_gc inner_gc = self.style.black_gc self._pixmap.draw_rectangle(outer_gc, True, outer_x, outer_y, outer_width, outer_height) self._pixmap.draw_layout(inner_gc, inner_x, inner_y, layout) if i == self._prelighted: # FIXME: doesn't seem to work self.style.paint_shadow(self.window, gtk.STATE_PRELIGHT, gtk.SHADOW_OUT, None, None, None, outer_x, outer_y, outer_width, outer_height) self.window.draw_drawable(self.style.fg_gc[self.state], self._pixmap, 0, 0, 0, 0, self.allocation.width, self.allocation.height) def set_characters(self, characters): self._layouts = [] for character in characters: self._layouts.append(self.create_pango_layout(character)) self.draw() self._characters = characters def get_characters(self): return self._characters def get_selected(self): return self._selected def unselect(self): self._selected = None self.draw() def clear(self): self._selected = None self._prelighted = None self.set_characters([]) def set_layout(self, layout): self._layout = layout gobject.type_register(CharTable) if __name__ == "__main__": import sys window = gtk.Window() chartable = CharTable() chartable.set_characters(["あ", "い","う", "え", "お", "か", "き", "く", "け", "こ", "さ", "し", "す", "せ", "そ"]) try: layout = int(sys.argv[1]) if layout > 3: layout = 0 except IndexError: layout = 0 chartable.set_layout(layout) def on_selected(widget, event): print "char_selected", chartable.get_selected() print "ev button", event.button print "ev time", event.time chartable.connect("character-selected", on_selected) window.add(chartable) window.show_all() gtk.main()
dkodnik/Ant
refs/heads/master
addons/purchase_requisition/report/__init__.py
64
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import requisition # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
julien6387/supvisors
refs/heads/master
supvisors/tests/test_options.py
2
#!/usr/bin/python # -*- coding: utf-8 -*- # ====================================================================== # Copyright 2017 Julien LE CLEACH # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ====================================================================== import sys import unittest from socket import gethostname from unittest.mock import patch from supervisor.options import ServerOptions from supvisors.tests.configurations import * class SupvisorsOptionsTest(unittest.TestCase): """ Test case for the SupvisorsOptions class of the options module. """ def test_creation(self): """ Test the values set at construction. """ from supvisors.options import SupvisorsOptions opt = SupvisorsOptions() # all attributes are None self.assertIsNone(opt.address_list) self.assertIsNone(opt.rules_file) self.assertIsNone(opt.internal_port) self.assertIsNone(opt.event_port) self.assertIsNone(opt.auto_fence) self.assertIsNone(opt.synchro_timeout) self.assertIsNone(opt.force_synchro_if) self.assertIsNone(opt.conciliation_strategy) self.assertIsNone(opt.starting_strategy) self.assertIsNone(opt.stats_periods) self.assertIsNone(opt.stats_histo) self.assertIsNone(opt.stats_irix_mode) self.assertIsNone(opt.logfile) self.assertIsNone(opt.logfile_maxbytes) self.assertIsNone(opt.logfile_backups) self.assertIsNone(opt.loglevel) def test_str(self): """ Test the string output. """ from supvisors.options import SupvisorsOptions opt = SupvisorsOptions() self.assertEqual('address_list=None rules_file=None ' 'internal_port=None event_port=None auto_fence=None ' 'synchro_timeout=None force_synchro_if=None conciliation_strategy=None ' 'starting_strategy=None stats_periods=None stats_histo=None ' 'stats_irix_mode=None logfile=None logfile_maxbytes=None ' 'logfile_backups=None loglevel=None', str(opt)) class SupvisorsServerOptionsTest(unittest.TestCase): """ Test case for the SupvisorsServerOptionsTest class of the options module. """ common_error_message = 'invalid value for {}' def test_port_num(self): """ Test the conversion into to a port number. """ from supvisors.options import SupvisorsServerOptions error_message = self.common_error_message.format('port') # test invalid values with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_port_num('-1') with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_port_num('0') with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_port_num('65536') # test valid values self.assertEqual(1, SupvisorsServerOptions.to_port_num('1')) self.assertEqual(65535, SupvisorsServerOptions.to_port_num('65535')) def test_timeout(self): """ Test the conversion of a string to a timeout value. """ from supvisors.options import SupvisorsServerOptions error_message = self.common_error_message.format('synchro_timeout') # test invalid values with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_timeout('-1') with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_timeout('0') with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_timeout('14') with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_timeout('1201') # test valid values self.assertEqual(15, SupvisorsServerOptions.to_timeout('15')) self.assertEqual(1200, SupvisorsServerOptions.to_timeout('1200')) def test_conciliation_strategy(self): """ Test the conversion of a string to a conciliation strategy. """ from supvisors.options import SupvisorsServerOptions from supvisors.ttypes import ConciliationStrategies error_message = self.common_error_message.format('conciliation_strategy') # test invalid values with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_conciliation_strategy('123456') with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_conciliation_strategy('dummy') with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_conciliation_strategy('user') # test valid values self.assertEqual(ConciliationStrategies.SENICIDE, SupvisorsServerOptions.to_conciliation_strategy('SENICIDE')) self.assertEqual(ConciliationStrategies.INFANTICIDE, SupvisorsServerOptions.to_conciliation_strategy('INFANTICIDE')) self.assertEqual(ConciliationStrategies.USER, SupvisorsServerOptions.to_conciliation_strategy('USER')) self.assertEqual(ConciliationStrategies.STOP, SupvisorsServerOptions.to_conciliation_strategy('STOP')) self.assertEqual(ConciliationStrategies.RESTART, SupvisorsServerOptions.to_conciliation_strategy('RESTART')) def test_starting_strategy(self): """ Test the conversion of a string to a starting strategy. """ from supvisors.options import SupvisorsServerOptions from supvisors.ttypes import StartingStrategies error_message = self.common_error_message.format('starting_strategy') # test invalid values with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_starting_strategy('123456') with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_starting_strategy('dummy') with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_starting_strategy('config') # test valid values self.assertEqual(StartingStrategies.CONFIG, SupvisorsServerOptions.to_starting_strategy('CONFIG')) self.assertEqual(StartingStrategies.LESS_LOADED, SupvisorsServerOptions.to_starting_strategy('LESS_LOADED')) self.assertEqual(StartingStrategies.MOST_LOADED, SupvisorsServerOptions.to_starting_strategy('MOST_LOADED')) def test_periods(self): """ Test the conversion of a string to a list of periods. """ from supvisors.options import SupvisorsServerOptions error_message = self.common_error_message.format('stats_periods') # test invalid values with self.assertRaisesRegex(ValueError, 'unexpected number of stats_periods'): SupvisorsServerOptions.to_periods([]) with self.assertRaisesRegex(ValueError, 'unexpected number of stats_periods'): SupvisorsServerOptions.to_periods(['1', '2', '3', '4']) with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_periods(['4', '3600']) with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_periods(['5', '3601']) with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_periods(['6', '3599']) # test valid values self.assertEqual([5], SupvisorsServerOptions.to_periods(['5'])) self.assertEqual([60, 3600], SupvisorsServerOptions.to_periods(['60', '3600'])) self.assertEqual([120, 720, 1800], SupvisorsServerOptions.to_periods(['120', '720', '1800'])) def test_histo(self): """ Test the conversion of a string to a history depth. """ from supvisors.options import SupvisorsServerOptions error_message = self.common_error_message.format('stats_histo') # test invalid values with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_histo('-1') with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_histo('9') with self.assertRaisesRegex(ValueError, error_message): SupvisorsServerOptions.to_histo('1501') # test valid values self.assertEqual(10, SupvisorsServerOptions.to_histo('10')) self.assertEqual(1500, SupvisorsServerOptions.to_histo('1500')) def test_incorrect_supvisors(self): """ Test that exception is raised when the supvisors section is missing. """ with self.assertRaises(ValueError): self.create_server(NoSupvisors) def test_program_numbers(self): """ Test that the internal numbers of homogeneous programs are stored. """ server = self.create_server(ProgramConfiguration) self.assertDictEqual({'dummy': 0, 'dummy_0': 0, 'dummy_1': 1, 'dummy_2': 2, 'dumber_10': 0, 'dumber_11': 1}, server.supvisors_options.procnumbers) def test_default_options(self): """ Test the default values of options with empty Supvisors configuration. """ from supervisor.datatypes import Automatic from supvisors.ttypes import ConciliationStrategies, StartingStrategies server = self.create_server(DefaultOptionConfiguration) opt = server.supvisors_options self.assertListEqual([gethostname()], opt.address_list) self.assertIsNone(opt.rules_file) self.assertEqual(65001, opt.internal_port) self.assertEqual(65002, opt.event_port) self.assertFalse(opt.auto_fence) self.assertEqual(15, opt.synchro_timeout) self.assertEqual([], opt.force_synchro_if) self.assertEqual(ConciliationStrategies.USER, opt.conciliation_strategy) self.assertEqual(StartingStrategies.CONFIG, opt.starting_strategy) self.assertListEqual([10], opt.stats_periods) self.assertEqual(200, opt.stats_histo) self.assertFalse(opt.stats_irix_mode) self.assertEqual(Automatic, opt.logfile) self.assertEqual(50 * 1024 * 1024, opt.logfile_maxbytes) self.assertEqual(10, opt.logfile_backups) self.assertEqual(20, opt.loglevel) def test_defined_options(self): """ Test the values of options with defined Supvisors configuration. """ from supvisors.ttypes import ConciliationStrategies, StartingStrategies server = self.create_server(DefinedOptionConfiguration) opt = server.supvisors_options self.assertEqual(['cliche01', 'cliche03', 'cliche02'], opt.address_list) self.assertEqual('my_movies.xml', opt.rules_file) self.assertEqual(60001, opt.internal_port) self.assertEqual(60002, opt.event_port) self.assertTrue(opt.auto_fence) self.assertEqual(20, opt.synchro_timeout) self.assertEqual(['cliche01', 'cliche03'], opt.force_synchro_if) self.assertEqual(ConciliationStrategies.SENICIDE, opt.conciliation_strategy) self.assertEqual(StartingStrategies.MOST_LOADED, opt.starting_strategy) self.assertListEqual([5, 60, 600], opt.stats_periods) self.assertEqual(100, opt.stats_histo) self.assertTrue(opt.stats_irix_mode) self.assertEqual('/tmp/supvisors.log', opt.logfile) self.assertEqual(50 * 1024, opt.logfile_maxbytes) self.assertEqual(5, opt.logfile_backups) self.assertEqual(40, opt.loglevel) @patch.object(ServerOptions, 'default_configfile', return_value='supervisord.conf') @patch.object(ServerOptions, 'exists', return_value=True) @patch.object(ServerOptions, 'usage', side_effect=ValueError) def create_server(self, *args, **keywargs): """ Create a SupvisorsServerOptions instance using patches on Supervisor source code. This is required because the unit test does not include existing files. """ from supvisors.options import SupvisorsServerOptions server = SupvisorsServerOptions() # this flag is required for supervisor to cope with unittest arguments server.positional_args_allowed = 1 # remove pytest cov options with patch.object(sys, 'argv', [sys.argv[0]]): with patch.object(ServerOptions, 'open', return_value=args[0]): server.realize() return server def test_suite(): return unittest.findTestCases(sys.modules[__name__]) if __name__ == '__main__': unittest.main(defaultTest='test_suite')
gdub/django
refs/heads/master
django/contrib/gis/geos/__init__.py
89
""" The GeoDjango GEOS module. Please consult the GeoDjango documentation for more details: https://docs.djangoproject.com/en/dev/ref/contrib/gis/geos/ """ from .collections import ( # NOQA GeometryCollection, MultiLineString, MultiPoint, MultiPolygon, ) from .error import GEOSException, GEOSIndexError # NOQA from .factory import fromfile, fromstr # NOQA from .geometry import GEOSGeometry, hex_regex, wkt_regex # NOQA from .io import WKBReader, WKBWriter, WKTReader, WKTWriter # NOQA from .libgeos import geos_version, geos_version_info # NOQA from .linestring import LinearRing, LineString # NOQA from .point import Point # NOQA from .polygon import Polygon # NOQA try: geos_version_info() HAS_GEOS = True except ImportError: HAS_GEOS = False
mohierf/mod-webui
refs/heads/develop
module/submodules/helpdesk.py
2
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from shinken.log import logger from .metamodule import MetaModule class HelpdeskMetaModule(MetaModule): # Only those functions are enough for an helpdesk module ... _functions = ['get_ui_helpdesk_configuration'] _custom_log = "You should configure the module 'glpi-helpdesk' in webui2.cfg " \ "file to get helpdesk information." def __init__(self, modules, app): """ Because it wouldn't make sense to use many submodules in this MetaModule, we only use the first one in the list of modules. """ super(HelpdeskMetaModule, self).__init__(modules=modules, app=app) self.app = app self.module = None if modules: if len(modules) > 1: logger.warning('[WebUI] Too much helpdesk modules declared (%s > 1). Using %s.', len(modules), modules[0]) self.module = modules[0] def is_available(self): return self.module is not None def get_external_ui_link(self, ticket_page=False, default=None): if self.is_available(): return self.module.get_external_ui_link(ticket_page) or default return default def get_ui_session(self, default=None): if self.is_available(): return self.module.get_ui_session() or default return default def get_ui_ticket(self, ticket_id, default=None): if self.is_available(): return self.module.get_ui_ticket(ticket_id) or default return default def get_ui_tickets(self, name=None, status=None, count=50, list_only=True, session=None, default=None): if self.is_available(): return self.module.get_ui_tickets(name, status, count, list_only, session) or default return default def get_ui_helpdesk_configuration(self, default=None): if self.is_available(): return self.module.get_ui_helpdesk_configuration() or default return default def get_ui_types(self, default=None): if self.is_available(): hd_configuration = self.module.get_ui_helpdesk_configuration() if 'types' in hd_configuration: return hd_configuration['types'] or default return default def get_ui_categories(self, default=None): if self.is_available(): hd_configuration = self.module.get_ui_helpdesk_configuration() if 'categories' in hd_configuration: return hd_configuration['categories'] or default return default def get_ui_templates(self, default=None): if self.is_available(): hd_configuration = self.module.get_ui_helpdesk_configuration() if 'templates' in hd_configuration: return hd_configuration['templates'] or default return default def set_ui_ticket(self, parameters, default=None): """ Request to create a new ticket """ if self.is_available(): return self.module.set_ui_ticket(parameters) or default return default def set_ui_ticket_followup(self, parameters, default=None): """ Request to create a new follow-up for a ticket """ if self.is_available(): return self.module.set_ui_ticket_followup(parameters) or default return default
lbrtcoin/albertcoin
refs/heads/master
qa/rpc-tests/test_framework/mininode.py
8
#!/usr/bin/env python3 # Copyright (c) 2010 ArtForz -- public domain half-a-node # Copyright (c) 2012 Jeff Garzik # Copyright (c) 2010-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # mininode.py - Bitcoin P2P network half-a-node # # This python code was modified from ArtForz' public domain half-a-node, as # found in the mini-node branch of http://github.com/jgarzik/pynode. # # NodeConn: an object which manages p2p connectivity to a bitcoin node # NodeConnCB: a base class that describes the interface for receiving # callbacks with network messages from a NodeConn # CBlock, CTransaction, CBlockHeader, CTxIn, CTxOut, etc....: # data structures that should map to corresponding structures in # bitcoin/primitives # msg_block, msg_tx, msg_headers, etc.: # data structures that represent network messages # ser_*, deser_*: functions that handle serialization/deserialization import struct import socket import asyncore import time import sys import random from .util import hex_str_to_bytes, bytes_to_hex_str from io import BytesIO from codecs import encode import hashlib from threading import RLock from threading import Thread import logging import copy import litecoin_scrypt from test_framework.siphash import siphash256 BIP0031_VERSION = 60000 MY_VERSION = 80014 # past bip-31 for ping/pong MY_SUBVERSION = b"/python-mininode-tester:0.0.3/" MAX_INV_SZ = 50000 MAX_BLOCK_SIZE = 1000000 COIN = 100000000 # 1 btc in satoshis NODE_NETWORK = (1 << 0) NODE_GETUTXO = (1 << 1) NODE_BLOOM = (1 << 2) NODE_WITNESS = (1 << 3) # Keep our own socket map for asyncore, so that we can track disconnects # ourselves (to workaround an issue with closing an asyncore socket when # using select) mininode_socket_map = dict() # One lock for synchronizing all data access between the networking thread (see # NetworkThread below) and the thread running the test logic. For simplicity, # NodeConn acquires this lock whenever delivering a message to to a NodeConnCB, # and whenever adding anything to the send buffer (in send_message()). This # lock should be acquired in the thread running the test logic to synchronize # access to any data shared with the NodeConnCB or NodeConn. mininode_lock = RLock() # Serialization/deserialization tools def sha256(s): return hashlib.new('sha256', s).digest() def ripemd160(s): return hashlib.new('ripemd160', s).digest() def hash256(s): return sha256(sha256(s)) def ser_compact_size(l): r = b"" if l < 253: r = struct.pack("B", l) elif l < 0x10000: r = struct.pack("<BH", 253, l) elif l < 0x100000000: r = struct.pack("<BI", 254, l) else: r = struct.pack("<BQ", 255, l) return r def deser_compact_size(f): nit = struct.unpack("<B", f.read(1))[0] if nit == 253: nit = struct.unpack("<H", f.read(2))[0] elif nit == 254: nit = struct.unpack("<I", f.read(4))[0] elif nit == 255: nit = struct.unpack("<Q", f.read(8))[0] return nit def deser_string(f): nit = deser_compact_size(f) return f.read(nit) def ser_string(s): return ser_compact_size(len(s)) + s def deser_uint256(f): r = 0 for i in range(8): t = struct.unpack("<I", f.read(4))[0] r += t << (i * 32) return r def ser_uint256(u): rs = b"" for i in range(8): rs += struct.pack("<I", u & 0xFFFFFFFF) u >>= 32 return rs def uint256_from_str(s): r = 0 t = struct.unpack("<IIIIIIII", s[:32]) for i in range(8): r += t[i] << (i * 32) return r def uint256_from_compact(c): nbytes = (c >> 24) & 0xFF v = (c & 0xFFFFFF) << (8 * (nbytes - 3)) return v def deser_vector(f, c): nit = deser_compact_size(f) r = [] for i in range(nit): t = c() t.deserialize(f) r.append(t) return r # ser_function_name: Allow for an alternate serialization function on the # entries in the vector (we use this for serializing the vector of transactions # for a witness block). def ser_vector(l, ser_function_name=None): r = ser_compact_size(len(l)) for i in l: if ser_function_name: r += getattr(i, ser_function_name)() else: r += i.serialize() return r def deser_uint256_vector(f): nit = deser_compact_size(f) r = [] for i in range(nit): t = deser_uint256(f) r.append(t) return r def ser_uint256_vector(l): r = ser_compact_size(len(l)) for i in l: r += ser_uint256(i) return r def deser_string_vector(f): nit = deser_compact_size(f) r = [] for i in range(nit): t = deser_string(f) r.append(t) return r def ser_string_vector(l): r = ser_compact_size(len(l)) for sv in l: r += ser_string(sv) return r def deser_int_vector(f): nit = deser_compact_size(f) r = [] for i in range(nit): t = struct.unpack("<i", f.read(4))[0] r.append(t) return r def ser_int_vector(l): r = ser_compact_size(len(l)) for i in l: r += struct.pack("<i", i) return r # Deserialize from a hex string representation (eg from RPC) def FromHex(obj, hex_string): obj.deserialize(BytesIO(hex_str_to_bytes(hex_string))) return obj # Convert a binary-serializable object to hex (eg for submission via RPC) def ToHex(obj): return bytes_to_hex_str(obj.serialize()) # Objects that map to bitcoind objects, which can be serialized/deserialized class CAddress(object): def __init__(self): self.nServices = 1 self.pchReserved = b"\x00" * 10 + b"\xff" * 2 self.ip = "0.0.0.0" self.port = 0 def deserialize(self, f): self.nServices = struct.unpack("<Q", f.read(8))[0] self.pchReserved = f.read(12) self.ip = socket.inet_ntoa(f.read(4)) self.port = struct.unpack(">H", f.read(2))[0] def serialize(self): r = b"" r += struct.pack("<Q", self.nServices) r += self.pchReserved r += socket.inet_aton(self.ip) r += struct.pack(">H", self.port) return r def __repr__(self): return "CAddress(nServices=%i ip=%s port=%i)" % (self.nServices, self.ip, self.port) MSG_WITNESS_FLAG = 1<<30 class CInv(object): typemap = { 0: "Error", 1: "TX", 2: "Block", 1|MSG_WITNESS_FLAG: "WitnessTx", 2|MSG_WITNESS_FLAG : "WitnessBlock", 4: "CompactBlock" } def __init__(self, t=0, h=0): self.type = t self.hash = h def deserialize(self, f): self.type = struct.unpack("<i", f.read(4))[0] self.hash = deser_uint256(f) def serialize(self): r = b"" r += struct.pack("<i", self.type) r += ser_uint256(self.hash) return r def __repr__(self): return "CInv(type=%s hash=%064x)" \ % (self.typemap[self.type], self.hash) class CBlockLocator(object): def __init__(self): self.nVersion = MY_VERSION self.vHave = [] def deserialize(self, f): self.nVersion = struct.unpack("<i", f.read(4))[0] self.vHave = deser_uint256_vector(f) def serialize(self): r = b"" r += struct.pack("<i", self.nVersion) r += ser_uint256_vector(self.vHave) return r def __repr__(self): return "CBlockLocator(nVersion=%i vHave=%s)" \ % (self.nVersion, repr(self.vHave)) class COutPoint(object): def __init__(self, hash=0, n=0): self.hash = hash self.n = n def deserialize(self, f): self.hash = deser_uint256(f) self.n = struct.unpack("<I", f.read(4))[0] def serialize(self): r = b"" r += ser_uint256(self.hash) r += struct.pack("<I", self.n) return r def __repr__(self): return "COutPoint(hash=%064x n=%i)" % (self.hash, self.n) class CTxIn(object): def __init__(self, outpoint=None, scriptSig=b"", nSequence=0): if outpoint is None: self.prevout = COutPoint() else: self.prevout = outpoint self.scriptSig = scriptSig self.nSequence = nSequence def deserialize(self, f): self.prevout = COutPoint() self.prevout.deserialize(f) self.scriptSig = deser_string(f) self.nSequence = struct.unpack("<I", f.read(4))[0] def serialize(self): r = b"" r += self.prevout.serialize() r += ser_string(self.scriptSig) r += struct.pack("<I", self.nSequence) return r def __repr__(self): return "CTxIn(prevout=%s scriptSig=%s nSequence=%i)" \ % (repr(self.prevout), bytes_to_hex_str(self.scriptSig), self.nSequence) class CTxOut(object): def __init__(self, nValue=0, scriptPubKey=b""): self.nValue = nValue self.scriptPubKey = scriptPubKey def deserialize(self, f): self.nValue = struct.unpack("<q", f.read(8))[0] self.scriptPubKey = deser_string(f) def serialize(self): r = b"" r += struct.pack("<q", self.nValue) r += ser_string(self.scriptPubKey) return r def __repr__(self): return "CTxOut(nValue=%i.%08i scriptPubKey=%s)" \ % (self.nValue // COIN, self.nValue % COIN, bytes_to_hex_str(self.scriptPubKey)) class CScriptWitness(object): def __init__(self): # stack is a vector of strings self.stack = [] def __repr__(self): return "CScriptWitness(%s)" % \ (",".join([bytes_to_hex_str(x) for x in self.stack])) def is_null(self): if self.stack: return False return True class CTxInWitness(object): def __init__(self): self.scriptWitness = CScriptWitness() def deserialize(self, f): self.scriptWitness.stack = deser_string_vector(f) def serialize(self): return ser_string_vector(self.scriptWitness.stack) def __repr__(self): return repr(self.scriptWitness) def is_null(self): return self.scriptWitness.is_null() class CTxWitness(object): def __init__(self): self.vtxinwit = [] def deserialize(self, f): for i in range(len(self.vtxinwit)): self.vtxinwit[i].deserialize(f) def serialize(self): r = b"" # This is different than the usual vector serialization -- # we omit the length of the vector, which is required to be # the same length as the transaction's vin vector. for x in self.vtxinwit: r += x.serialize() return r def __repr__(self): return "CTxWitness(%s)" % \ (';'.join([repr(x) for x in self.vtxinwit])) def is_null(self): for x in self.vtxinwit: if not x.is_null(): return False return True class CTransaction(object): def __init__(self, tx=None): if tx is None: self.nVersion = 1 self.vin = [] self.vout = [] self.wit = CTxWitness() self.nLockTime = 0 self.sha256 = None self.hash = None else: self.nVersion = tx.nVersion self.vin = copy.deepcopy(tx.vin) self.vout = copy.deepcopy(tx.vout) self.nLockTime = tx.nLockTime self.sha256 = tx.sha256 self.hash = tx.hash self.wit = copy.deepcopy(tx.wit) def deserialize(self, f): self.nVersion = struct.unpack("<i", f.read(4))[0] self.vin = deser_vector(f, CTxIn) flags = 0 if len(self.vin) == 0: flags = struct.unpack("<B", f.read(1))[0] # Not sure why flags can't be zero, but this # matches the implementation in bitcoind if (flags != 0): self.vin = deser_vector(f, CTxIn) self.vout = deser_vector(f, CTxOut) else: self.vout = deser_vector(f, CTxOut) if flags != 0: self.wit.vtxinwit = [CTxInWitness() for i in range(len(self.vin))] self.wit.deserialize(f) self.nLockTime = struct.unpack("<I", f.read(4))[0] self.sha256 = None self.hash = None def serialize_without_witness(self): r = b"" r += struct.pack("<i", self.nVersion) r += ser_vector(self.vin) r += ser_vector(self.vout) r += struct.pack("<I", self.nLockTime) return r # Only serialize with witness when explicitly called for def serialize_with_witness(self): flags = 0 if not self.wit.is_null(): flags |= 1 r = b"" r += struct.pack("<i", self.nVersion) if flags: dummy = [] r += ser_vector(dummy) r += struct.pack("<B", flags) r += ser_vector(self.vin) r += ser_vector(self.vout) if flags & 1: if (len(self.wit.vtxinwit) != len(self.vin)): # vtxinwit must have the same length as vin self.wit.vtxinwit = self.wit.vtxinwit[:len(self.vin)] for i in range(len(self.wit.vtxinwit), len(self.vin)): self.wit.vtxinwit.append(CTxInWitness()) r += self.wit.serialize() r += struct.pack("<I", self.nLockTime) return r # Regular serialization is without witness -- must explicitly # call serialize_with_witness to include witness data. def serialize(self): return self.serialize_without_witness() # Recalculate the txid (transaction hash without witness) def rehash(self): self.sha256 = None self.calc_sha256() # We will only cache the serialization without witness in # self.sha256 and self.hash -- those are expected to be the txid. def calc_sha256(self, with_witness=False): if with_witness: # Don't cache the result, just return it return uint256_from_str(hash256(self.serialize_with_witness())) if self.sha256 is None: self.sha256 = uint256_from_str(hash256(self.serialize_without_witness())) self.hash = encode(hash256(self.serialize())[::-1], 'hex_codec').decode('ascii') def is_valid(self): self.calc_sha256() for tout in self.vout: if tout.nValue < 0 or tout.nValue > 84000000 * COIN: return False return True def __repr__(self): return "CTransaction(nVersion=%i vin=%s vout=%s wit=%s nLockTime=%i)" \ % (self.nVersion, repr(self.vin), repr(self.vout), repr(self.wit), self.nLockTime) class CBlockHeader(object): def __init__(self, header=None): if header is None: self.set_null() else: self.nVersion = header.nVersion self.hashPrevBlock = header.hashPrevBlock self.hashMerkleRoot = header.hashMerkleRoot self.nTime = header.nTime self.nBits = header.nBits self.nNonce = header.nNonce self.sha256 = header.sha256 self.hash = header.hash self.scrypt256 = header.scrypt256 self.calc_sha256() def set_null(self): self.nVersion = 1 self.hashPrevBlock = 0 self.hashMerkleRoot = 0 self.nTime = 0 self.nBits = 0 self.nNonce = 0 self.sha256 = None self.hash = None self.scrypt256 = None def deserialize(self, f): self.nVersion = struct.unpack("<i", f.read(4))[0] self.hashPrevBlock = deser_uint256(f) self.hashMerkleRoot = deser_uint256(f) self.nTime = struct.unpack("<I", f.read(4))[0] self.nBits = struct.unpack("<I", f.read(4))[0] self.nNonce = struct.unpack("<I", f.read(4))[0] self.sha256 = None self.hash = None self.scrypt256 = None def serialize(self): r = b"" r += struct.pack("<i", self.nVersion) r += ser_uint256(self.hashPrevBlock) r += ser_uint256(self.hashMerkleRoot) r += struct.pack("<I", self.nTime) r += struct.pack("<I", self.nBits) r += struct.pack("<I", self.nNonce) return r def calc_sha256(self): if self.sha256 is None: r = b"" r += struct.pack("<i", self.nVersion) r += ser_uint256(self.hashPrevBlock) r += ser_uint256(self.hashMerkleRoot) r += struct.pack("<I", self.nTime) r += struct.pack("<I", self.nBits) r += struct.pack("<I", self.nNonce) self.sha256 = uint256_from_str(hash256(r)) self.hash = encode(hash256(r)[::-1], 'hex_codec').decode('ascii') self.scrypt256 = uint256_from_str(litecoin_scrypt.getPoWHash(r)) def rehash(self): self.sha256 = None self.scrypt256 = None self.calc_sha256() return self.sha256 def __repr__(self): return "CBlockHeader(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x)" \ % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot, time.ctime(self.nTime), self.nBits, self.nNonce) class CBlock(CBlockHeader): def __init__(self, header=None): super(CBlock, self).__init__(header) self.vtx = [] def deserialize(self, f): super(CBlock, self).deserialize(f) self.vtx = deser_vector(f, CTransaction) def serialize(self, with_witness=False): r = b"" r += super(CBlock, self).serialize() if with_witness: r += ser_vector(self.vtx, "serialize_with_witness") else: r += ser_vector(self.vtx) return r # Calculate the merkle root given a vector of transaction hashes def get_merkle_root(self, hashes): while len(hashes) > 1: newhashes = [] for i in range(0, len(hashes), 2): i2 = min(i+1, len(hashes)-1) newhashes.append(hash256(hashes[i] + hashes[i2])) hashes = newhashes return uint256_from_str(hashes[0]) def calc_merkle_root(self): hashes = [] for tx in self.vtx: tx.calc_sha256() hashes.append(ser_uint256(tx.sha256)) return self.get_merkle_root(hashes) def calc_witness_merkle_root(self): # For witness root purposes, the hash of the # coinbase, with witness, is defined to be 0...0 hashes = [ser_uint256(0)] for tx in self.vtx[1:]: # Calculate the hashes with witness data hashes.append(ser_uint256(tx.calc_sha256(True))) return self.get_merkle_root(hashes) def is_valid(self): self.calc_sha256() target = uint256_from_compact(self.nBits) if self.scrypt256 > target: return False for tx in self.vtx: if not tx.is_valid(): return False if self.calc_merkle_root() != self.hashMerkleRoot: return False return True def solve(self): self.rehash() target = uint256_from_compact(self.nBits) while self.scrypt256 > target: self.nNonce += 1 self.rehash() def __repr__(self): return "CBlock(nVersion=%i hashPrevBlock=%064x hashMerkleRoot=%064x nTime=%s nBits=%08x nNonce=%08x vtx=%s)" \ % (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot, time.ctime(self.nTime), self.nBits, self.nNonce, repr(self.vtx)) class CUnsignedAlert(object): def __init__(self): self.nVersion = 1 self.nRelayUntil = 0 self.nExpiration = 0 self.nID = 0 self.nCancel = 0 self.setCancel = [] self.nMinVer = 0 self.nMaxVer = 0 self.setSubVer = [] self.nPriority = 0 self.strComment = b"" self.strStatusBar = b"" self.strReserved = b"" def deserialize(self, f): self.nVersion = struct.unpack("<i", f.read(4))[0] self.nRelayUntil = struct.unpack("<q", f.read(8))[0] self.nExpiration = struct.unpack("<q", f.read(8))[0] self.nID = struct.unpack("<i", f.read(4))[0] self.nCancel = struct.unpack("<i", f.read(4))[0] self.setCancel = deser_int_vector(f) self.nMinVer = struct.unpack("<i", f.read(4))[0] self.nMaxVer = struct.unpack("<i", f.read(4))[0] self.setSubVer = deser_string_vector(f) self.nPriority = struct.unpack("<i", f.read(4))[0] self.strComment = deser_string(f) self.strStatusBar = deser_string(f) self.strReserved = deser_string(f) def serialize(self): r = b"" r += struct.pack("<i", self.nVersion) r += struct.pack("<q", self.nRelayUntil) r += struct.pack("<q", self.nExpiration) r += struct.pack("<i", self.nID) r += struct.pack("<i", self.nCancel) r += ser_int_vector(self.setCancel) r += struct.pack("<i", self.nMinVer) r += struct.pack("<i", self.nMaxVer) r += ser_string_vector(self.setSubVer) r += struct.pack("<i", self.nPriority) r += ser_string(self.strComment) r += ser_string(self.strStatusBar) r += ser_string(self.strReserved) return r def __repr__(self): return "CUnsignedAlert(nVersion %d, nRelayUntil %d, nExpiration %d, nID %d, nCancel %d, nMinVer %d, nMaxVer %d, nPriority %d, strComment %s, strStatusBar %s, strReserved %s)" \ % (self.nVersion, self.nRelayUntil, self.nExpiration, self.nID, self.nCancel, self.nMinVer, self.nMaxVer, self.nPriority, self.strComment, self.strStatusBar, self.strReserved) class CAlert(object): def __init__(self): self.vchMsg = b"" self.vchSig = b"" def deserialize(self, f): self.vchMsg = deser_string(f) self.vchSig = deser_string(f) def serialize(self): r = b"" r += ser_string(self.vchMsg) r += ser_string(self.vchSig) return r def __repr__(self): return "CAlert(vchMsg.sz %d, vchSig.sz %d)" \ % (len(self.vchMsg), len(self.vchSig)) class PrefilledTransaction(object): def __init__(self, index=0, tx = None): self.index = index self.tx = tx def deserialize(self, f): self.index = deser_compact_size(f) self.tx = CTransaction() self.tx.deserialize(f) def serialize(self, with_witness=False): r = b"" r += ser_compact_size(self.index) if with_witness: r += self.tx.serialize_with_witness() else: r += self.tx.serialize_without_witness() return r def serialize_with_witness(self): return self.serialize(with_witness=True) def __repr__(self): return "PrefilledTransaction(index=%d, tx=%s)" % (self.index, repr(self.tx)) # This is what we send on the wire, in a cmpctblock message. class P2PHeaderAndShortIDs(object): def __init__(self): self.header = CBlockHeader() self.nonce = 0 self.shortids_length = 0 self.shortids = [] self.prefilled_txn_length = 0 self.prefilled_txn = [] def deserialize(self, f): self.header.deserialize(f) self.nonce = struct.unpack("<Q", f.read(8))[0] self.shortids_length = deser_compact_size(f) for i in range(self.shortids_length): # shortids are defined to be 6 bytes in the spec, so append # two zero bytes and read it in as an 8-byte number self.shortids.append(struct.unpack("<Q", f.read(6) + b'\x00\x00')[0]) self.prefilled_txn = deser_vector(f, PrefilledTransaction) self.prefilled_txn_length = len(self.prefilled_txn) # When using version 2 compact blocks, we must serialize with_witness. def serialize(self, with_witness=False): r = b"" r += self.header.serialize() r += struct.pack("<Q", self.nonce) r += ser_compact_size(self.shortids_length) for x in self.shortids: # We only want the first 6 bytes r += struct.pack("<Q", x)[0:6] if with_witness: r += ser_vector(self.prefilled_txn, "serialize_with_witness") else: r += ser_vector(self.prefilled_txn) return r def __repr__(self): return "P2PHeaderAndShortIDs(header=%s, nonce=%d, shortids_length=%d, shortids=%s, prefilled_txn_length=%d, prefilledtxn=%s" % (repr(self.header), self.nonce, self.shortids_length, repr(self.shortids), self.prefilled_txn_length, repr(self.prefilled_txn)) # P2P version of the above that will use witness serialization (for compact # block version 2) class P2PHeaderAndShortWitnessIDs(P2PHeaderAndShortIDs): def serialize(self): return super(P2PHeaderAndShortWitnessIDs, self).serialize(with_witness=True) # Calculate the BIP 152-compact blocks shortid for a given transaction hash def calculate_shortid(k0, k1, tx_hash): expected_shortid = siphash256(k0, k1, tx_hash) expected_shortid &= 0x0000ffffffffffff return expected_shortid # This version gets rid of the array lengths, and reinterprets the differential # encoding into indices that can be used for lookup. class HeaderAndShortIDs(object): def __init__(self, p2pheaders_and_shortids = None): self.header = CBlockHeader() self.nonce = 0 self.shortids = [] self.prefilled_txn = [] self.use_witness = False if p2pheaders_and_shortids != None: self.header = p2pheaders_and_shortids.header self.nonce = p2pheaders_and_shortids.nonce self.shortids = p2pheaders_and_shortids.shortids last_index = -1 for x in p2pheaders_and_shortids.prefilled_txn: self.prefilled_txn.append(PrefilledTransaction(x.index + last_index + 1, x.tx)) last_index = self.prefilled_txn[-1].index def to_p2p(self): if self.use_witness: ret = P2PHeaderAndShortWitnessIDs() else: ret = P2PHeaderAndShortIDs() ret.header = self.header ret.nonce = self.nonce ret.shortids_length = len(self.shortids) ret.shortids = self.shortids ret.prefilled_txn_length = len(self.prefilled_txn) ret.prefilled_txn = [] last_index = -1 for x in self.prefilled_txn: ret.prefilled_txn.append(PrefilledTransaction(x.index - last_index - 1, x.tx)) last_index = x.index return ret def get_siphash_keys(self): header_nonce = self.header.serialize() header_nonce += struct.pack("<Q", self.nonce) hash_header_nonce_as_str = sha256(header_nonce) key0 = struct.unpack("<Q", hash_header_nonce_as_str[0:8])[0] key1 = struct.unpack("<Q", hash_header_nonce_as_str[8:16])[0] return [ key0, key1 ] # Version 2 compact blocks use wtxid in shortids (rather than txid) def initialize_from_block(self, block, nonce=0, prefill_list = [0], use_witness = False): self.header = CBlockHeader(block) self.nonce = nonce self.prefilled_txn = [ PrefilledTransaction(i, block.vtx[i]) for i in prefill_list ] self.shortids = [] self.use_witness = use_witness [k0, k1] = self.get_siphash_keys() for i in range(len(block.vtx)): if i not in prefill_list: tx_hash = block.vtx[i].sha256 if use_witness: tx_hash = block.vtx[i].calc_sha256(with_witness=True) self.shortids.append(calculate_shortid(k0, k1, tx_hash)) def __repr__(self): return "HeaderAndShortIDs(header=%s, nonce=%d, shortids=%s, prefilledtxn=%s" % (repr(self.header), self.nonce, repr(self.shortids), repr(self.prefilled_txn)) class BlockTransactionsRequest(object): def __init__(self, blockhash=0, indexes = None): self.blockhash = blockhash self.indexes = indexes if indexes != None else [] def deserialize(self, f): self.blockhash = deser_uint256(f) indexes_length = deser_compact_size(f) for i in range(indexes_length): self.indexes.append(deser_compact_size(f)) def serialize(self): r = b"" r += ser_uint256(self.blockhash) r += ser_compact_size(len(self.indexes)) for x in self.indexes: r += ser_compact_size(x) return r # helper to set the differentially encoded indexes from absolute ones def from_absolute(self, absolute_indexes): self.indexes = [] last_index = -1 for x in absolute_indexes: self.indexes.append(x-last_index-1) last_index = x def to_absolute(self): absolute_indexes = [] last_index = -1 for x in self.indexes: absolute_indexes.append(x+last_index+1) last_index = absolute_indexes[-1] return absolute_indexes def __repr__(self): return "BlockTransactionsRequest(hash=%064x indexes=%s)" % (self.blockhash, repr(self.indexes)) class BlockTransactions(object): def __init__(self, blockhash=0, transactions = None): self.blockhash = blockhash self.transactions = transactions if transactions != None else [] def deserialize(self, f): self.blockhash = deser_uint256(f) self.transactions = deser_vector(f, CTransaction) def serialize(self, with_witness=False): r = b"" r += ser_uint256(self.blockhash) if with_witness: r += ser_vector(self.transactions, "serialize_with_witness") else: r += ser_vector(self.transactions) return r def __repr__(self): return "BlockTransactions(hash=%064x transactions=%s)" % (self.blockhash, repr(self.transactions)) # Objects that correspond to messages on the wire class msg_version(object): command = b"version" def __init__(self): self.nVersion = MY_VERSION self.nServices = 1 self.nTime = int(time.time()) self.addrTo = CAddress() self.addrFrom = CAddress() self.nNonce = random.getrandbits(64) self.strSubVer = MY_SUBVERSION self.nStartingHeight = -1 def deserialize(self, f): self.nVersion = struct.unpack("<i", f.read(4))[0] if self.nVersion == 10300: self.nVersion = 300 self.nServices = struct.unpack("<Q", f.read(8))[0] self.nTime = struct.unpack("<q", f.read(8))[0] self.addrTo = CAddress() self.addrTo.deserialize(f) if self.nVersion >= 106: self.addrFrom = CAddress() self.addrFrom.deserialize(f) self.nNonce = struct.unpack("<Q", f.read(8))[0] self.strSubVer = deser_string(f) if self.nVersion >= 209: self.nStartingHeight = struct.unpack("<i", f.read(4))[0] else: self.nStartingHeight = None else: self.addrFrom = None self.nNonce = None self.strSubVer = None self.nStartingHeight = None def serialize(self): r = b"" r += struct.pack("<i", self.nVersion) r += struct.pack("<Q", self.nServices) r += struct.pack("<q", self.nTime) r += self.addrTo.serialize() r += self.addrFrom.serialize() r += struct.pack("<Q", self.nNonce) r += ser_string(self.strSubVer) r += struct.pack("<i", self.nStartingHeight) return r def __repr__(self): return 'msg_version(nVersion=%i nServices=%i nTime=%s addrTo=%s addrFrom=%s nNonce=0x%016X strSubVer=%s nStartingHeight=%i)' \ % (self.nVersion, self.nServices, time.ctime(self.nTime), repr(self.addrTo), repr(self.addrFrom), self.nNonce, self.strSubVer, self.nStartingHeight) class msg_verack(object): command = b"verack" def __init__(self): pass def deserialize(self, f): pass def serialize(self): return b"" def __repr__(self): return "msg_verack()" class msg_addr(object): command = b"addr" def __init__(self): self.addrs = [] def deserialize(self, f): self.addrs = deser_vector(f, CAddress) def serialize(self): return ser_vector(self.addrs) def __repr__(self): return "msg_addr(addrs=%s)" % (repr(self.addrs)) class msg_alert(object): command = b"alert" def __init__(self): self.alert = CAlert() def deserialize(self, f): self.alert = CAlert() self.alert.deserialize(f) def serialize(self): r = b"" r += self.alert.serialize() return r def __repr__(self): return "msg_alert(alert=%s)" % (repr(self.alert), ) class msg_inv(object): command = b"inv" def __init__(self, inv=None): if inv is None: self.inv = [] else: self.inv = inv def deserialize(self, f): self.inv = deser_vector(f, CInv) def serialize(self): return ser_vector(self.inv) def __repr__(self): return "msg_inv(inv=%s)" % (repr(self.inv)) class msg_getdata(object): command = b"getdata" def __init__(self, inv=None): self.inv = inv if inv != None else [] def deserialize(self, f): self.inv = deser_vector(f, CInv) def serialize(self): return ser_vector(self.inv) def __repr__(self): return "msg_getdata(inv=%s)" % (repr(self.inv)) class msg_getblocks(object): command = b"getblocks" def __init__(self): self.locator = CBlockLocator() self.hashstop = 0 def deserialize(self, f): self.locator = CBlockLocator() self.locator.deserialize(f) self.hashstop = deser_uint256(f) def serialize(self): r = b"" r += self.locator.serialize() r += ser_uint256(self.hashstop) return r def __repr__(self): return "msg_getblocks(locator=%s hashstop=%064x)" \ % (repr(self.locator), self.hashstop) class msg_tx(object): command = b"tx" def __init__(self, tx=CTransaction()): self.tx = tx def deserialize(self, f): self.tx.deserialize(f) def serialize(self): return self.tx.serialize_without_witness() def __repr__(self): return "msg_tx(tx=%s)" % (repr(self.tx)) class msg_witness_tx(msg_tx): def serialize(self): return self.tx.serialize_with_witness() class msg_block(object): command = b"block" def __init__(self, block=None): if block is None: self.block = CBlock() else: self.block = block def deserialize(self, f): self.block.deserialize(f) def serialize(self): return self.block.serialize() def __repr__(self): return "msg_block(block=%s)" % (repr(self.block)) # for cases where a user needs tighter control over what is sent over the wire # note that the user must supply the name of the command, and the data class msg_generic(object): def __init__(self, command, data=None): self.command = command self.data = data def serialize(self): return self.data def __repr__(self): return "msg_generic()" class msg_witness_block(msg_block): def serialize(self): r = self.block.serialize(with_witness=True) return r class msg_getaddr(object): command = b"getaddr" def __init__(self): pass def deserialize(self, f): pass def serialize(self): return b"" def __repr__(self): return "msg_getaddr()" class msg_ping_prebip31(object): command = b"ping" def __init__(self): pass def deserialize(self, f): pass def serialize(self): return b"" def __repr__(self): return "msg_ping() (pre-bip31)" class msg_ping(object): command = b"ping" def __init__(self, nonce=0): self.nonce = nonce def deserialize(self, f): self.nonce = struct.unpack("<Q", f.read(8))[0] def serialize(self): r = b"" r += struct.pack("<Q", self.nonce) return r def __repr__(self): return "msg_ping(nonce=%08x)" % self.nonce class msg_pong(object): command = b"pong" def __init__(self, nonce=0): self.nonce = nonce def deserialize(self, f): self.nonce = struct.unpack("<Q", f.read(8))[0] def serialize(self): r = b"" r += struct.pack("<Q", self.nonce) return r def __repr__(self): return "msg_pong(nonce=%08x)" % self.nonce class msg_mempool(object): command = b"mempool" def __init__(self): pass def deserialize(self, f): pass def serialize(self): return b"" def __repr__(self): return "msg_mempool()" class msg_sendheaders(object): command = b"sendheaders" def __init__(self): pass def deserialize(self, f): pass def serialize(self): return b"" def __repr__(self): return "msg_sendheaders()" # getheaders message has # number of entries # vector of hashes # hash_stop (hash of last desired block header, 0 to get as many as possible) class msg_getheaders(object): command = b"getheaders" def __init__(self): self.locator = CBlockLocator() self.hashstop = 0 def deserialize(self, f): self.locator = CBlockLocator() self.locator.deserialize(f) self.hashstop = deser_uint256(f) def serialize(self): r = b"" r += self.locator.serialize() r += ser_uint256(self.hashstop) return r def __repr__(self): return "msg_getheaders(locator=%s, stop=%064x)" \ % (repr(self.locator), self.hashstop) # headers message has # <count> <vector of block headers> class msg_headers(object): command = b"headers" def __init__(self): self.headers = [] def deserialize(self, f): # comment in bitcoind indicates these should be deserialized as blocks blocks = deser_vector(f, CBlock) for x in blocks: self.headers.append(CBlockHeader(x)) def serialize(self): blocks = [CBlock(x) for x in self.headers] return ser_vector(blocks) def __repr__(self): return "msg_headers(headers=%s)" % repr(self.headers) class msg_reject(object): command = b"reject" REJECT_MALFORMED = 1 def __init__(self): self.message = b"" self.code = 0 self.reason = b"" self.data = 0 def deserialize(self, f): self.message = deser_string(f) self.code = struct.unpack("<B", f.read(1))[0] self.reason = deser_string(f) if (self.code != self.REJECT_MALFORMED and (self.message == b"block" or self.message == b"tx")): self.data = deser_uint256(f) def serialize(self): r = ser_string(self.message) r += struct.pack("<B", self.code) r += ser_string(self.reason) if (self.code != self.REJECT_MALFORMED and (self.message == b"block" or self.message == b"tx")): r += ser_uint256(self.data) return r def __repr__(self): return "msg_reject: %s %d %s [%064x]" \ % (self.message, self.code, self.reason, self.data) # Helper function def wait_until(predicate, *, attempts=float('inf'), timeout=float('inf')): attempt = 0 elapsed = 0 while attempt < attempts and elapsed < timeout: with mininode_lock: if predicate(): return True attempt += 1 elapsed += 0.05 time.sleep(0.05) return False class msg_feefilter(object): command = b"feefilter" def __init__(self, feerate=0): self.feerate = feerate def deserialize(self, f): self.feerate = struct.unpack("<Q", f.read(8))[0] def serialize(self): r = b"" r += struct.pack("<Q", self.feerate) return r def __repr__(self): return "msg_feefilter(feerate=%08x)" % self.feerate class msg_sendcmpct(object): command = b"sendcmpct" def __init__(self): self.announce = False self.version = 1 def deserialize(self, f): self.announce = struct.unpack("<?", f.read(1))[0] self.version = struct.unpack("<Q", f.read(8))[0] def serialize(self): r = b"" r += struct.pack("<?", self.announce) r += struct.pack("<Q", self.version) return r def __repr__(self): return "msg_sendcmpct(announce=%s, version=%lu)" % (self.announce, self.version) class msg_cmpctblock(object): command = b"cmpctblock" def __init__(self, header_and_shortids = None): self.header_and_shortids = header_and_shortids def deserialize(self, f): self.header_and_shortids = P2PHeaderAndShortIDs() self.header_and_shortids.deserialize(f) def serialize(self): r = b"" r += self.header_and_shortids.serialize() return r def __repr__(self): return "msg_cmpctblock(HeaderAndShortIDs=%s)" % repr(self.header_and_shortids) class msg_getblocktxn(object): command = b"getblocktxn" def __init__(self): self.block_txn_request = None def deserialize(self, f): self.block_txn_request = BlockTransactionsRequest() self.block_txn_request.deserialize(f) def serialize(self): r = b"" r += self.block_txn_request.serialize() return r def __repr__(self): return "msg_getblocktxn(block_txn_request=%s)" % (repr(self.block_txn_request)) class msg_blocktxn(object): command = b"blocktxn" def __init__(self): self.block_transactions = BlockTransactions() def deserialize(self, f): self.block_transactions.deserialize(f) def serialize(self): r = b"" r += self.block_transactions.serialize() return r def __repr__(self): return "msg_blocktxn(block_transactions=%s)" % (repr(self.block_transactions)) class msg_witness_blocktxn(msg_blocktxn): def serialize(self): r = b"" r += self.block_transactions.serialize(with_witness=True) return r # This is what a callback should look like for NodeConn # Reimplement the on_* functions to provide handling for events class NodeConnCB(object): def __init__(self): self.verack_received = False # deliver_sleep_time is helpful for debugging race conditions in p2p # tests; it causes message delivery to sleep for the specified time # before acquiring the global lock and delivering the next message. self.deliver_sleep_time = None # Remember the services our peer has advertised self.peer_services = None def set_deliver_sleep_time(self, value): with mininode_lock: self.deliver_sleep_time = value def get_deliver_sleep_time(self): with mininode_lock: return self.deliver_sleep_time # Spin until verack message is received from the node. # Tests may want to use this as a signal that the test can begin. # This can be called from the testing thread, so it needs to acquire the # global lock. def wait_for_verack(self): while True: with mininode_lock: if self.verack_received: return time.sleep(0.05) def deliver(self, conn, message): deliver_sleep = self.get_deliver_sleep_time() if deliver_sleep is not None: time.sleep(deliver_sleep) with mininode_lock: try: getattr(self, 'on_' + message.command.decode('ascii'))(conn, message) except: print("ERROR delivering %s (%s)" % (repr(message), sys.exc_info()[0])) def on_version(self, conn, message): if message.nVersion >= 209: conn.send_message(msg_verack()) conn.ver_send = min(MY_VERSION, message.nVersion) if message.nVersion < 209: conn.ver_recv = conn.ver_send conn.nServices = message.nServices def on_verack(self, conn, message): conn.ver_recv = conn.ver_send self.verack_received = True def on_inv(self, conn, message): want = msg_getdata() for i in message.inv: if i.type != 0: want.inv.append(i) if len(want.inv): conn.send_message(want) def on_addr(self, conn, message): pass def on_alert(self, conn, message): pass def on_getdata(self, conn, message): pass def on_getblocks(self, conn, message): pass def on_tx(self, conn, message): pass def on_block(self, conn, message): pass def on_getaddr(self, conn, message): pass def on_headers(self, conn, message): pass def on_getheaders(self, conn, message): pass def on_ping(self, conn, message): if conn.ver_send > BIP0031_VERSION: conn.send_message(msg_pong(message.nonce)) def on_reject(self, conn, message): pass def on_close(self, conn): pass def on_mempool(self, conn): pass def on_pong(self, conn, message): pass def on_feefilter(self, conn, message): pass def on_sendheaders(self, conn, message): pass def on_sendcmpct(self, conn, message): pass def on_cmpctblock(self, conn, message): pass def on_getblocktxn(self, conn, message): pass def on_blocktxn(self, conn, message): pass # More useful callbacks and functions for NodeConnCB's which have a single NodeConn class SingleNodeConnCB(NodeConnCB): def __init__(self): NodeConnCB.__init__(self) self.connection = None self.ping_counter = 1 self.last_pong = msg_pong() def add_connection(self, conn): self.connection = conn # Wrapper for the NodeConn's send_message function def send_message(self, message): self.connection.send_message(message) def send_and_ping(self, message): self.send_message(message) self.sync_with_ping() def on_pong(self, conn, message): self.last_pong = message # Sync up with the node def sync_with_ping(self, timeout=30): def received_pong(): return (self.last_pong.nonce == self.ping_counter) self.send_message(msg_ping(nonce=self.ping_counter)) success = wait_until(received_pong, timeout=timeout) self.ping_counter += 1 return success # The actual NodeConn class # This class provides an interface for a p2p connection to a specified node class NodeConn(asyncore.dispatcher): messagemap = { b"version": msg_version, b"verack": msg_verack, b"addr": msg_addr, b"alert": msg_alert, b"inv": msg_inv, b"getdata": msg_getdata, b"getblocks": msg_getblocks, b"tx": msg_tx, b"block": msg_block, b"getaddr": msg_getaddr, b"ping": msg_ping, b"pong": msg_pong, b"headers": msg_headers, b"getheaders": msg_getheaders, b"reject": msg_reject, b"mempool": msg_mempool, b"feefilter": msg_feefilter, b"sendheaders": msg_sendheaders, b"sendcmpct": msg_sendcmpct, b"cmpctblock": msg_cmpctblock, b"getblocktxn": msg_getblocktxn, b"blocktxn": msg_blocktxn } MAGIC_BYTES = { "mainnet": b"\xfb\xc0\xb6\xdb", # mainnet "testnet3": b"\xfc\xc1\xb7\xdc", # testnet3 "regtest": b"\xfa\xbf\xb5\xda", # regtest } def __init__(self, dstaddr, dstport, rpc, callback, net="regtest", services=NODE_NETWORK): asyncore.dispatcher.__init__(self, map=mininode_socket_map) self.log = logging.getLogger("NodeConn(%s:%d)" % (dstaddr, dstport)) self.dstaddr = dstaddr self.dstport = dstport self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.sendbuf = b"" self.recvbuf = b"" self.ver_send = 209 self.ver_recv = 209 self.last_sent = 0 self.state = "connecting" self.network = net self.cb = callback self.disconnect = False self.nServices = 0 # stuff version msg into sendbuf vt = msg_version() vt.nServices = services vt.addrTo.ip = self.dstaddr vt.addrTo.port = self.dstport vt.addrFrom.ip = "0.0.0.0" vt.addrFrom.port = 0 self.send_message(vt, True) print('MiniNode: Connecting to Litecoin Node IP # ' + dstaddr + ':' \ + str(dstport)) try: self.connect((dstaddr, dstport)) except: self.handle_close() self.rpc = rpc def show_debug_msg(self, msg): self.log.debug(msg) def handle_connect(self): self.show_debug_msg("MiniNode: Connected & Listening: \n") self.state = "connected" def handle_close(self): self.show_debug_msg("MiniNode: Closing Connection to %s:%d... " % (self.dstaddr, self.dstport)) self.state = "closed" self.recvbuf = b"" self.sendbuf = b"" try: self.close() except: pass self.cb.on_close(self) def handle_read(self): try: t = self.recv(8192) if len(t) > 0: self.recvbuf += t self.got_data() except: pass def readable(self): return True def writable(self): with mininode_lock: length = len(self.sendbuf) return (length > 0) def handle_write(self): with mininode_lock: try: sent = self.send(self.sendbuf) except: self.handle_close() return self.sendbuf = self.sendbuf[sent:] def got_data(self): try: while True: if len(self.recvbuf) < 4: return if self.recvbuf[:4] != self.MAGIC_BYTES[self.network]: raise ValueError("got garbage %s" % repr(self.recvbuf)) if self.ver_recv < 209: if len(self.recvbuf) < 4 + 12 + 4: return command = self.recvbuf[4:4+12].split(b"\x00", 1)[0] msglen = struct.unpack("<i", self.recvbuf[4+12:4+12+4])[0] checksum = None if len(self.recvbuf) < 4 + 12 + 4 + msglen: return msg = self.recvbuf[4+12+4:4+12+4+msglen] self.recvbuf = self.recvbuf[4+12+4+msglen:] else: if len(self.recvbuf) < 4 + 12 + 4 + 4: return command = self.recvbuf[4:4+12].split(b"\x00", 1)[0] msglen = struct.unpack("<i", self.recvbuf[4+12:4+12+4])[0] checksum = self.recvbuf[4+12+4:4+12+4+4] if len(self.recvbuf) < 4 + 12 + 4 + 4 + msglen: return msg = self.recvbuf[4+12+4+4:4+12+4+4+msglen] th = sha256(msg) h = sha256(th) if checksum != h[:4]: raise ValueError("got bad checksum " + repr(self.recvbuf)) self.recvbuf = self.recvbuf[4+12+4+4+msglen:] if command in self.messagemap: f = BytesIO(msg) t = self.messagemap[command]() t.deserialize(f) self.got_message(t) else: self.show_debug_msg("Unknown command: '" + command + "' " + repr(msg)) except Exception as e: print('got_data:', repr(e)) # import traceback # traceback.print_tb(sys.exc_info()[2]) def send_message(self, message, pushbuf=False): if self.state != "connected" and not pushbuf: raise IOError('Not connected, no pushbuf') self.show_debug_msg("Send %s" % repr(message)) command = message.command data = message.serialize() tmsg = self.MAGIC_BYTES[self.network] tmsg += command tmsg += b"\x00" * (12 - len(command)) tmsg += struct.pack("<I", len(data)) if self.ver_send >= 209: th = sha256(data) h = sha256(th) tmsg += h[:4] tmsg += data with mininode_lock: self.sendbuf += tmsg self.last_sent = time.time() def got_message(self, message): if message.command == b"version": if message.nVersion <= BIP0031_VERSION: self.messagemap[b'ping'] = msg_ping_prebip31 if self.last_sent + 30 * 60 < time.time(): self.send_message(self.messagemap[b'ping']()) self.show_debug_msg("Recv %s" % repr(message)) self.cb.deliver(self, message) def disconnect_node(self): self.disconnect = True class NetworkThread(Thread): def run(self): while mininode_socket_map: # We check for whether to disconnect outside of the asyncore # loop to workaround the behavior of asyncore when using # select disconnected = [] for fd, obj in mininode_socket_map.items(): if obj.disconnect: disconnected.append(obj) [ obj.handle_close() for obj in disconnected ] asyncore.loop(0.1, use_poll=True, map=mininode_socket_map, count=1) # An exception we can raise if we detect a potential disconnect # (p2p or rpc) before the test is complete class EarlyDisconnectError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
TomConlin/dipper
refs/heads/master
tests/test_ucscbands.py
2
#!/usr/bin/env python3 import unittest import logging from tests.test_source import SourceTestCase from dipper.sources.UCSCBands import UCSCBands logging.basicConfig(level=logging.WARNING) logger = logging.getLogger(__name__) class UCSCBandsTestCase(SourceTestCase): def setUp(self): self.source = UCSCBands('rdf_graph', True) self.source.settestonly(True) self._setDirToSource() return def tearDown(self): self.source = None return # TODO add some specific tests to make sure we are hitting # all parts of the code # @unittest.skip('test not yet defined') # def test_ucscbandstest(self): # logger.info("A UCSCBands-specific test") # # return if __name__ == '__main__': unittest.main()
dgilman/echobot
refs/heads/master
echobot/__init__.py
1
from .hipchat import HipchatClient from .irc import IRCClient from .server import EchoBotServer
wzhfy/spark
refs/heads/master
examples/src/main/python/als.py
27
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ This is an example implementation of ALS for learning how to use Spark. Please refer to pyspark.ml.recommendation.ALS for more conventional use. This example requires numpy (http://www.numpy.org/) """ import sys import numpy as np from numpy.random import rand from numpy import matrix from pyspark.sql import SparkSession LAMBDA = 0.01 # regularization np.random.seed(42) def rmse(R, ms, us): diff = R - ms * us.T return np.sqrt(np.sum(np.power(diff, 2)) / (M * U)) def update(i, mat, ratings): uu = mat.shape[0] ff = mat.shape[1] XtX = mat.T * mat Xty = mat.T * ratings[i, :].T for j in range(ff): XtX[j, j] += LAMBDA * uu return np.linalg.solve(XtX, Xty) if __name__ == "__main__": """ Usage: als [M] [U] [F] [iterations] [partitions]" """ print("""WARN: This is a naive implementation of ALS and is given as an example. Please use pyspark.ml.recommendation.ALS for more conventional use.""", file=sys.stderr) spark = SparkSession\ .builder\ .appName("PythonALS")\ .getOrCreate() sc = spark.sparkContext M = int(sys.argv[1]) if len(sys.argv) > 1 else 100 U = int(sys.argv[2]) if len(sys.argv) > 2 else 500 F = int(sys.argv[3]) if len(sys.argv) > 3 else 10 ITERATIONS = int(sys.argv[4]) if len(sys.argv) > 4 else 5 partitions = int(sys.argv[5]) if len(sys.argv) > 5 else 2 print("Running ALS with M=%d, U=%d, F=%d, iters=%d, partitions=%d\n" % (M, U, F, ITERATIONS, partitions)) R = matrix(rand(M, F)) * matrix(rand(U, F).T) ms = matrix(rand(M, F)) us = matrix(rand(U, F)) Rb = sc.broadcast(R) msb = sc.broadcast(ms) usb = sc.broadcast(us) for i in range(ITERATIONS): ms = sc.parallelize(range(M), partitions) \ .map(lambda x: update(x, usb.value, Rb.value)) \ .collect() # collect() returns a list, so array ends up being # a 3-d array, we take the first 2 dims for the matrix ms = matrix(np.array(ms)[:, :, 0]) msb = sc.broadcast(ms) us = sc.parallelize(range(U), partitions) \ .map(lambda x: update(x, msb.value, Rb.value.T)) \ .collect() us = matrix(np.array(us)[:, :, 0]) usb = sc.broadcast(us) error = rmse(R, ms, us) print("Iteration %d:" % i) print("\nRMSE: %5.4f\n" % error) spark.stop()
nvoron23/socialite
refs/heads/master
jython/Lib/test/test_itertools.py
10
import unittest from test import test_support from itertools import * from weakref import proxy import sys import operator import random def onearg(x): 'Test function of one argument' return 2*x def errfunc(*args): 'Test function that raises an error' raise ValueError def gen3(): 'Non-restartable source sequence' for i in (0, 1, 2): yield i def isEven(x): 'Test predicate' return x%2==0 def isOdd(x): 'Test predicate' return x%2==1 class StopNow: 'Class emulating an empty iterable.' def __iter__(self): return self def next(self): raise StopIteration def take(n, seq): 'Convenience function for partially consuming a long of infinite iterable' return list(islice(seq, n)) class TestBasicOps(unittest.TestCase): def test_chain(self): self.assertEqual(list(chain('abc', 'def')), list('abcdef')) self.assertEqual(list(chain('abc')), list('abc')) self.assertEqual(list(chain('')), []) self.assertEqual(take(4, chain('abc', 'def')), list('abcd')) self.assertRaises(TypeError, chain, 2, 3) def test_count(self): self.assertEqual(zip('abc',count()), [('a', 0), ('b', 1), ('c', 2)]) self.assertEqual(zip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)]) self.assertEqual(take(2, zip('abc',count(3))), [('a', 3), ('b', 4)]) self.assertRaises(TypeError, count, 2, 3) self.assertRaises(TypeError, count, 'a') c = count(sys.maxint-2) # verify that rollover doesn't crash c.next(); c.next(); c.next(); c.next(); c.next() c = count(3) self.assertEqual(repr(c), 'count(3)') c.next() self.assertEqual(repr(c), 'count(4)') def test_cycle(self): self.assertEqual(take(10, cycle('abc')), list('abcabcabca')) self.assertEqual(list(cycle('')), []) self.assertRaises(TypeError, cycle) self.assertRaises(TypeError, cycle, 5) self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0]) def test_groupby(self): # Check whether it accepts arguments correctly self.assertEqual([], list(groupby([]))) self.assertEqual([], list(groupby([], key=id))) self.assertRaises(TypeError, list, groupby('abc', [])) self.assertRaises(TypeError, groupby, None) self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10) # Check normal input s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22), (2,15,22), (3,16,23), (3,17,23)] dup = [] for k, g in groupby(s, lambda r:r[0]): for elem in g: self.assertEqual(k, elem[0]) dup.append(elem) self.assertEqual(s, dup) # Check nested case dup = [] for k, g in groupby(s, lambda r:r[0]): for ik, ig in groupby(g, lambda r:r[2]): for elem in ig: self.assertEqual(k, elem[0]) self.assertEqual(ik, elem[2]) dup.append(elem) self.assertEqual(s, dup) # Check case where inner iterator is not used keys = [k for k, g in groupby(s, lambda r:r[0])] expectedkeys = set([r[0] for r in s]) self.assertEqual(set(keys), expectedkeys) self.assertEqual(len(keys), len(expectedkeys)) # Exercise pipes and filters style s = 'abracadabra' # sort s | uniq r = [k for k, g in groupby(sorted(s))] self.assertEqual(r, ['a', 'b', 'c', 'd', 'r']) # sort s | uniq -d r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))] self.assertEqual(r, ['a', 'b', 'r']) # sort s | uniq -c r = [(len(list(g)), k) for k, g in groupby(sorted(s))] self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')]) # sort s | uniq -c | sort -rn | head -3 r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3] self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')]) # iter.next failure class ExpectedError(Exception): pass def delayed_raise(n=0): for i in range(n): yield 'yo' raise ExpectedError def gulp(iterable, keyp=None, func=list): return [func(g) for k, g in groupby(iterable, keyp)] # iter.next failure on outer object self.assertRaises(ExpectedError, gulp, delayed_raise(0)) # iter.next failure on inner object #self.assertRaises(ExpectedError, gulp, delayed_raise(1)) # __cmp__ failure class DummyCmp: def __cmp__(self, dst): raise ExpectedError s = [DummyCmp(), DummyCmp(), None] # __cmp__ failure on outer object #self.assertRaises(ExpectedError, gulp, s, func=id) # __cmp__ failure on inner object #self.assertRaises(ExpectedError, gulp, s) # keyfunc failure def keyfunc(obj): if keyfunc.skip > 0: keyfunc.skip -= 1 return obj else: raise ExpectedError # keyfunc failure on outer object keyfunc.skip = 0 self.assertRaises(ExpectedError, gulp, [None], keyfunc) keyfunc.skip = 1 self.assertRaises(ExpectedError, gulp, [None, None], keyfunc) def test_ifilter(self): self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4]) self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2]) self.assertEqual(take(4, ifilter(isEven, count())), [0,2,4,6]) self.assertRaises(TypeError, ifilter) self.assertRaises(TypeError, ifilter, lambda x:x) self.assertRaises(TypeError, ifilter, lambda x:x, range(6), 7) self.assertRaises(TypeError, ifilter, isEven, 3) self.assertRaises(TypeError, ifilter(range(6), range(6)).next) def test_ifilterfalse(self): self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5]) self.assertEqual(list(ifilterfalse(None, [0,1,0,2,0])), [0,0,0]) self.assertEqual(take(4, ifilterfalse(isEven, count())), [1,3,5,7]) self.assertRaises(TypeError, ifilterfalse) self.assertRaises(TypeError, ifilterfalse, lambda x:x) self.assertRaises(TypeError, ifilterfalse, lambda x:x, range(6), 7) self.assertRaises(TypeError, ifilterfalse, isEven, 3) self.assertRaises(TypeError, ifilterfalse(range(6), range(6)).next) def test_izip(self): ans = [(x,y) for x, y in izip('abc',count())] self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)]) self.assertEqual(list(izip('abc', range(6))), zip('abc', range(6))) self.assertEqual(list(izip('abcdef', range(3))), zip('abcdef', range(3))) self.assertEqual(take(3,izip('abcdef', count())), zip('abcdef', range(3))) self.assertEqual(list(izip('abcdef')), zip('abcdef')) self.assertEqual(list(izip()), zip()) self.assertRaises(TypeError, izip, 3) self.assertRaises(TypeError, izip, range(3), 3) # Check tuple re-use (implementation detail) self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')], zip('abc', 'def')) self.assertEqual([pair for pair in izip('abc', 'def')], zip('abc', 'def')) # Does not apply to Jython - no tuple reuse # ids = map(id, izip('abc', 'def')) # self.assertEqual(min(ids), max(ids)) ids = map(id, list(izip('abc', 'def'))) self.assertEqual(len(dict.fromkeys(ids)), len(ids)) def test_repeat(self): self.assertEqual(zip(xrange(3),repeat('a')), [(0, 'a'), (1, 'a'), (2, 'a')]) self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a']) self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a']) self.assertEqual(list(repeat('a', 0)), []) self.assertEqual(list(repeat('a', -3)), []) self.assertRaises(TypeError, repeat) self.assertRaises(TypeError, repeat, None, 3, 4) self.assertRaises(TypeError, repeat, None, 'a') r = repeat(1+0j) self.assertEqual(repr(r), 'repeat((1+0j))') r = repeat(1+0j, 5) self.assertEqual(repr(r), 'repeat((1+0j), 5)') list(r) self.assertEqual(repr(r), 'repeat((1+0j), 0)') def test_imap(self): self.assertEqual(list(imap(operator.pow, range(3), range(1,7))), [0**1, 1**2, 2**3]) self.assertEqual(list(imap(None, 'abc', range(5))), [('a',0),('b',1),('c',2)]) self.assertEqual(list(imap(None, 'abc', count())), [('a',0),('b',1),('c',2)]) self.assertEqual(take(2,imap(None, 'abc', count())), [('a',0),('b',1)]) self.assertEqual(list(imap(operator.pow, [])), []) self.assertRaises(TypeError, imap) self.assertRaises(TypeError, imap, operator.neg) self.assertRaises(TypeError, imap(10, range(5)).next) self.assertRaises(ValueError, imap(errfunc, [4], [5]).next) self.assertRaises(TypeError, imap(onearg, [4], [5]).next) def test_starmap(self): self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))), [0**1, 1**2, 2**3]) self.assertEqual(take(3, starmap(operator.pow, izip(count(), count(1)))), [0**1, 1**2, 2**3]) self.assertEqual(list(starmap(operator.pow, [])), []) self.assertRaises(TypeError, list, starmap(operator.pow, [[4,5]])) self.assertRaises(TypeError, starmap) self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, starmap(10, [(4,5)]).next) self.assertRaises(ValueError, starmap(errfunc, [(4,5)]).next) self.assertRaises(TypeError, starmap(onearg, [(4,5)]).next) def test_islice(self): for args in [ # islice(args) should agree with range(args) (10, 20, 3), (10, 3, 20), (10, 20), (10, 3), (20,) ]: self.assertEqual(list(islice(xrange(100), *args)), range(*args)) for args, tgtargs in [ # Stop when seqn is exhausted ((10, 110, 3), ((10, 100, 3))), ((10, 110), ((10, 100))), ((110,), (100,)) ]: self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs)) # Test stop=None self.assertEqual(list(islice(xrange(10), None)), range(10)) self.assertEqual(list(islice(xrange(10), None, None)), range(10)) self.assertEqual(list(islice(xrange(10), None, None, None)), range(10)) self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10)) self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2)) # Test number of items consumed SF #1171417 it = iter(range(10)) self.assertEqual(list(islice(it, 3)), range(3)) self.assertEqual(list(it), range(3, 10)) # Test invalid arguments self.assertRaises(TypeError, islice, xrange(10)) self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4) self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1) self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1) self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1) self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0) self.assertRaises(ValueError, islice, xrange(10), 'a') self.assertRaises(ValueError, islice, xrange(10), 'a', 1) self.assertRaises(ValueError, islice, xrange(10), 1, 'a') self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1) self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1) self.assertEqual(len(list(islice(count(), 1, 10, sys.maxint))), 1) def test_takewhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] underten = lambda x: x<10 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5]) self.assertEqual(list(takewhile(underten, [])), []) self.assertRaises(TypeError, takewhile) self.assertRaises(TypeError, takewhile, operator.pow) self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, takewhile(10, [(4,5)]).next) self.assertRaises(ValueError, takewhile(errfunc, [(4,5)]).next) t = takewhile(bool, [1, 1, 1, 0, 0, 0]) self.assertEqual(list(t), [1, 1, 1]) self.assertRaises(StopIteration, t.next) def test_dropwhile(self): data = [1, 3, 5, 20, 2, 4, 6, 8] underten = lambda x: x<10 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8]) self.assertEqual(list(dropwhile(underten, [])), []) self.assertRaises(TypeError, dropwhile) self.assertRaises(TypeError, dropwhile, operator.pow) self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra') self.assertRaises(TypeError, dropwhile(10, [(4,5)]).next) self.assertRaises(ValueError, dropwhile(errfunc, [(4,5)]).next) def test_tee(self): n = 200 def irange(n): for i in xrange(n): yield i a, b = tee([]) # test empty iterator self.assertEqual(list(a), []) self.assertEqual(list(b), []) a, b = tee(irange(n)) # test 100% interleaved self.assertEqual(zip(a,b), zip(range(n),range(n))) a, b = tee(irange(n)) # test 0% interleaved self.assertEqual(list(a), range(n)) self.assertEqual(list(b), range(n)) a, b = tee(irange(n)) # test dealloc of leading iterator for i in xrange(100): self.assertEqual(a.next(), i) del a self.assertEqual(list(b), range(n)) a, b = tee(irange(n)) # test dealloc of trailing iterator for i in xrange(100): self.assertEqual(a.next(), i) del b self.assertEqual(list(a), range(100, n)) for j in xrange(5): # test randomly interleaved order = [0]*n + [1]*n random.shuffle(order) lists = ([], []) its = tee(irange(n)) for i in order: value = its[i].next() lists[i].append(value) self.assertEqual(lists[0], range(n)) self.assertEqual(lists[1], range(n)) # test argument format checking self.assertRaises(TypeError, tee) self.assertRaises(TypeError, tee, 3) self.assertRaises(TypeError, tee, [1,2], 'x') self.assertRaises(TypeError, tee, [1,2], 3, 'x') # tee object should be instantiable a, b = tee('abc') c = type(a)('def') self.assertEqual(list(c), list('def')) # test long-lagged and multi-way split a, b, c = tee(xrange(2000), 3) for i in xrange(100): self.assertEqual(a.next(), i) self.assertEqual(list(b), range(2000)) self.assertEqual([c.next(), c.next()], range(2)) self.assertEqual(list(a), range(100,2000)) self.assertEqual(list(c), range(2,2000)) # test values of n self.assertRaises(TypeError, tee, 'abc', 'invalid') self.assertRaises(ValueError, tee, [], -1) for n in xrange(5): result = tee('abc', n) self.assertEqual(type(result), tuple) self.assertEqual(len(result), n) self.assertEqual(map(list, result), [list('abc')]*n) # tee pass-through to copyable iterator a, b = tee('abc') c, d = tee(a) # JYTHON TODO: we do not currently implement copy # self.assert_(a is c) # test tee_new t1, t2 = tee('abc') tnew = type(t1) self.assertRaises(TypeError, tnew) self.assertRaises(TypeError, tnew, 10) t3 = tnew(t1) # JYTHON: this tests that copy is transitive #self.assert_(list(t1) == list(t2) == list(t3) == list('abc')) self.assert_(list(t3) == list(t2) == list('abc')) # test that tee objects are weak referencable a, b = tee(xrange(10)) p = proxy(a) self.assertEqual(getattr(p, '__class__'), type(b)) del a # JYTHON: this depends on `a` actually going out of scope; we # would have to play with GC to make it so # self.assertRaises(ReferenceError, getattr, p, '__class__') def test_StopIteration(self): self.assertRaises(StopIteration, izip().next) for f in (chain, cycle, izip, groupby): self.assertRaises(StopIteration, f([]).next) self.assertRaises(StopIteration, f(StopNow()).next) self.assertRaises(StopIteration, islice([], None).next) self.assertRaises(StopIteration, islice(StopNow(), None).next) p, q = tee([]) self.assertRaises(StopIteration, p.next) self.assertRaises(StopIteration, q.next) p, q = tee(StopNow()) self.assertRaises(StopIteration, p.next) self.assertRaises(StopIteration, q.next) self.assertRaises(StopIteration, repeat(None, 0).next) for f in (ifilter, ifilterfalse, imap, takewhile, dropwhile, starmap): self.assertRaises(StopIteration, f(lambda x:x, []).next) self.assertRaises(StopIteration, f(lambda x:x, StopNow()).next) class TestGC(unittest.TestCase): def makecycle(self, iterator, container): container.append(iterator) iterator.next() del container, iterator def test_chain(self): a = [] self.makecycle(chain(a), a) def test_cycle(self): a = [] self.makecycle(cycle([a]*2), a) def test_dropwhile(self): a = [] self.makecycle(dropwhile(bool, [0, a, a]), a) def test_groupby(self): a = [] self.makecycle(groupby([a]*2, lambda x:x), a) def test_ifilter(self): a = [] self.makecycle(ifilter(lambda x:True, [a]*2), a) def test_ifilterfalse(self): a = [] self.makecycle(ifilterfalse(lambda x:False, a), a) def test_izip(self): a = [] self.makecycle(izip([a]*2, [a]*3), a) def test_imap(self): a = [] self.makecycle(imap(lambda x:x, [a]*2), a) def test_islice(self): a = [] self.makecycle(islice([a]*2, None), a) def test_repeat(self): a = [] self.makecycle(repeat(a), a) def test_starmap(self): a = [] self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a) def test_takewhile(self): a = [] self.makecycle(takewhile(bool, [1, 0, a, a]), a) def R(seqn): 'Regular generator' for i in seqn: yield i class G: 'Sequence using __getitem__' def __init__(self, seqn): self.seqn = seqn def __getitem__(self, i): return self.seqn[i] class I: 'Sequence using iterator protocol' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __iter__(self): return self def next(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 return v class Ig: 'Sequence using iterator protocol defined with a generator' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __iter__(self): for val in self.seqn: yield val class X: 'Missing __getitem__ and __iter__' def __init__(self, seqn): self.seqn = seqn self.i = 0 def next(self): if self.i >= len(self.seqn): raise StopIteration v = self.seqn[self.i] self.i += 1 return v class N: 'Iterator missing next()' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __iter__(self): return self class E: 'Test propagation of exceptions' def __init__(self, seqn): self.seqn = seqn self.i = 0 def __iter__(self): return self def next(self): 3 // 0 class S: 'Test immediate stop' def __init__(self, seqn): pass def __iter__(self): return self def next(self): raise StopIteration def L(seqn): 'Test multiple tiers of iterators' return chain(imap(lambda x:x, R(Ig(G(seqn))))) class TestVariousIteratorArgs(unittest.TestCase): def test_chain(self): for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(chain(g(s))), list(g(s))) self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s))) self.assertRaises(TypeError, chain, X(s)) self.assertRaises(TypeError, list, chain(N(s))) self.assertRaises(ZeroDivisionError, list, chain(E(s))) def test_cycle(self): for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for g in (G, I, Ig, S, L, R): tgtlen = len(s) * 3 expected = list(g(s))*3 actual = list(islice(cycle(g(s)), tgtlen)) self.assertEqual(actual, expected) self.assertRaises(TypeError, cycle, X(s)) self.assertRaises(TypeError, list, cycle(N(s))) self.assertRaises(ZeroDivisionError, list, cycle(E(s))) def test_groupby(self): for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)): for g in (G, I, Ig, S, L, R): self.assertEqual([k for k, sb in groupby(g(s))], list(g(s))) self.assertRaises(TypeError, groupby, X(s)) self.assertRaises(TypeError, list, groupby(N(s))) self.assertRaises(ZeroDivisionError, list, groupby(E(s))) def test_ifilter(self): for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(ifilter(isEven, g(s))), filter(isEven, g(s))) self.assertRaises(TypeError, ifilter, isEven, X(s)) self.assertRaises(TypeError, list, ifilter(isEven, N(s))) self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s))) def test_ifilterfalse(self): for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(ifilterfalse(isEven, g(s))), filter(isOdd, g(s))) self.assertRaises(TypeError, ifilterfalse, isEven, X(s)) self.assertRaises(TypeError, list, ifilterfalse(isEven, N(s))) self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s))) def test_izip(self): for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(izip(g(s))), zip(g(s))) self.assertEqual(list(izip(g(s), g(s))), zip(g(s), g(s))) self.assertRaises(TypeError, izip, X(s)) self.assertRaises(TypeError, list, izip(N(s))) self.assertRaises(ZeroDivisionError, list, izip(E(s))) def test_imap(self): for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(imap(onearg, g(s))), map(onearg, g(s))) self.assertEqual(list(imap(operator.pow, g(s), g(s))), map(operator.pow, g(s), g(s))) self.assertRaises(TypeError, imap, onearg, X(s)) self.assertRaises(TypeError, list, imap(onearg, N(s))) self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s))) def test_islice(self): for s in ("12345", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for g in (G, I, Ig, S, L, R): self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2]) self.assertRaises(TypeError, islice, X(s), 10) self.assertRaises(TypeError, list, islice(N(s), 10)) self.assertRaises(ZeroDivisionError, list, islice(E(s), 10)) def test_starmap(self): for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)): for g in (G, I, Ig, S, L, R): ss = zip(s, s) self.assertEqual(list(starmap(operator.pow, g(ss))), map(operator.pow, g(s), g(s))) self.assertRaises(TypeError, starmap, operator.pow, X(ss)) self.assertRaises(TypeError, list, starmap(operator.pow, N(ss))) self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss))) def test_takewhile(self): for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)): for g in (G, I, Ig, S, L, R): tgt = [] for elem in g(s): if not isEven(elem): break tgt.append(elem) self.assertEqual(list(takewhile(isEven, g(s))), tgt) self.assertRaises(TypeError, takewhile, isEven, X(s)) self.assertRaises(TypeError, list, takewhile(isEven, N(s))) self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s))) def test_dropwhile(self): for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)): for g in (G, I, Ig, S, L, R): tgt = [] for elem in g(s): if not tgt and isOdd(elem): continue tgt.append(elem) self.assertEqual(list(dropwhile(isOdd, g(s))), tgt) self.assertRaises(TypeError, dropwhile, isOdd, X(s)) self.assertRaises(TypeError, list, dropwhile(isOdd, N(s))) self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s))) def test_tee(self): for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for g in (G, I, Ig, S, L, R): it1, it2 = tee(g(s)) self.assertEqual(list(it1), list(g(s))) self.assertEqual(list(it2), list(g(s))) self.assertRaises(TypeError, tee, X(s)) self.assertRaises(TypeError, list, tee(N(s))[0]) self.assertRaises(ZeroDivisionError, list, tee(E(s))[0]) class LengthTransparency(unittest.TestCase): def test_repeat(self): from test.test_iterlen import len self.assertEqual(len(repeat(None, 50)), 50) self.assertRaises(TypeError, len, repeat(None)) class RegressionTests(unittest.TestCase): def test_sf_793826(self): # Fix Armin Rigo's successful efforts to wreak havoc def mutatingtuple(tuple1, f, tuple2): # this builds a tuple t which is a copy of tuple1, # then calls f(t), then mutates t to be equal to tuple2 # (needs len(tuple1) == len(tuple2)). def g(value, first=[1]): if first: del first[:] f(z.next()) return value items = list(tuple2) items[1:1] = list(tuple1) gen = imap(g, items) z = izip(*[gen]*len(tuple1)) z.next() def f(t): global T T = t first[:] = list(T) first = [] mutatingtuple((1,2,3), f, (4,5,6)) second = list(T) self.assertEqual(first, second) def test_sf_950057(self): # Make sure that chain() and cycle() catch exceptions immediately # rather than when shifting between input sources def gen1(): hist.append(0) yield 1 hist.append(1) raise AssertionError hist.append(2) def gen2(x): hist.append(3) yield 2 hist.append(4) if x: raise StopIteration hist = [] self.assertRaises(AssertionError, list, chain(gen1(), gen2(False))) self.assertEqual(hist, [0,1]) hist = [] self.assertRaises(AssertionError, list, chain(gen1(), gen2(True))) self.assertEqual(hist, [0,1]) hist = [] self.assertRaises(AssertionError, list, cycle(gen1())) self.assertEqual(hist, [0,1]) libreftest = """ Doctest for examples in the library reference: libitertools.tex >>> amounts = [120.15, 764.05, 823.14] >>> for checknum, amount in izip(count(1200), amounts): ... print 'Check %d is for $%.2f' % (checknum, amount) ... Check 1200 is for $120.15 Check 1201 is for $764.05 Check 1202 is for $823.14 >>> import operator >>> for cube in imap(operator.pow, xrange(1,4), repeat(3)): ... print cube ... 1 8 27 >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele'] >>> for name in islice(reportlines, 3, None, 2): ... print name.title() ... Alex Laura Martin Walter Samuele # >>> from operator import itemgetter # >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) # >>> di = sorted(sorted(d.iteritems()), key=itemgetter(1)) # >>> for k, g in groupby(di, itemgetter(1)): # ... print k, map(itemgetter(0), g) # ... # 1 ['a', 'c', 'e'] # 2 ['b', 'd', 'f'] # 3 ['g'] # Find runs of consecutive numbers using groupby. The key to the solution # is differencing with a range so that consecutive numbers all appear in # same group. #>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] # >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x): # ... print map(operator.itemgetter(1), g) # ... # [1] # [4, 5, 6] # [10] # [15, 16, 17, 18] # [22] # [25, 26, 27, 28] >>> def take(n, seq): ... return list(islice(seq, n)) >>> def enumerate(iterable): ... return izip(count(), iterable) >>> def tabulate(function): ... "Return function(0), function(1), ..." ... return imap(function, count()) >>> def iteritems(mapping): ... return izip(mapping.iterkeys(), mapping.itervalues()) >>> def nth(iterable, n): ... "Returns the nth item" ... return list(islice(iterable, n, n+1)) >>> def all(seq, pred=None): ... "Returns True if pred(x) is true for every element in the iterable" ... for elem in ifilterfalse(pred, seq): ... return False ... return True >>> def any(seq, pred=None): ... "Returns True if pred(x) is true for at least one element in the iterable" ... for elem in ifilter(pred, seq): ... return True ... return False >>> def no(seq, pred=None): ... "Returns True if pred(x) is false for every element in the iterable" ... for elem in ifilter(pred, seq): ... return False ... return True >>> def quantify(seq, pred=None): ... "Count how many times the predicate is true in the sequence" ... return sum(imap(pred, seq)) >>> def padnone(seq): ... "Returns the sequence elements and then returns None indefinitely" ... return chain(seq, repeat(None)) >>> def ncycles(seq, n): ... "Returns the sequence elements n times" ... return chain(*repeat(seq, n)) >>> def dotproduct(vec1, vec2): ... return sum(imap(operator.mul, vec1, vec2)) >>> def flatten(listOfLists): ... return list(chain(*listOfLists)) >>> def repeatfunc(func, times=None, *args): ... "Repeat calls to func with specified arguments." ... " Example: repeatfunc(random.random)" ... if times is None: ... return starmap(func, repeat(args)) ... else: ... return starmap(func, repeat(args, times)) >>> def pairwise(iterable): ... "s -> (s0,s1), (s1,s2), (s2, s3), ..." ... a, b = tee(iterable) ... try: ... b.next() ... except StopIteration: ... pass ... return izip(a, b) This is not part of the examples but it tests to make sure the definitions perform as purported. >>> take(10, count()) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(enumerate('abc')) [(0, 'a'), (1, 'b'), (2, 'c')] >>> list(islice(tabulate(lambda x: 2*x), 4)) [0, 2, 4, 6] >>> nth('abcde', 3) ['d'] >>> all([2, 4, 6, 8], lambda x: x%2==0) True >>> all([2, 3, 6, 8], lambda x: x%2==0) False >>> any([2, 4, 6, 8], lambda x: x%2==0) True >>> any([1, 3, 5, 9], lambda x: x%2==0,) False >>> no([1, 3, 5, 9], lambda x: x%2==0) True >>> no([1, 2, 5, 9], lambda x: x%2==0) False >>> quantify(xrange(99), lambda x: x%2==0) 50 >>> a = [[1, 2, 3], [4, 5, 6]] >>> flatten(a) [1, 2, 3, 4, 5, 6] >>> list(repeatfunc(pow, 5, 2, 3)) [8, 8, 8, 8, 8] >>> import random >>> take(5, imap(int, repeatfunc(random.random))) [0, 0, 0, 0, 0] >>> list(pairwise('abcd')) [('a', 'b'), ('b', 'c'), ('c', 'd')] >>> list(pairwise([])) [] >>> list(pairwise('a')) [] >>> list(islice(padnone('abc'), 0, 6)) ['a', 'b', 'c', None, None, None] >>> list(ncycles('abc', 3)) ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'] >>> dotproduct([1,2,3], [4,5,6]) 32 """ __test__ = {'libreftest' : libreftest} def test_main(verbose=None): test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC, RegressionTests, LengthTransparency) test_support.run_unittest(*test_classes) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): import gc counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() print counts # doctest the examples in the library reference test_support.run_doctest(sys.modules[__name__], verbose) if __name__ == "__main__": test_main(verbose=True)
dbhirko/ansible-modules-extras
refs/heads/devel
windows/__init__.py
12133432
sbalde/edx-platform
refs/heads/master
cms/lib/__init__.py
12133432
haldean/toolpath
refs/heads/master
include/re2/re2/unicode.py
119
# Copyright 2008 The RE2 Authors. All Rights Reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. """Parser for Unicode data files (as distributed by unicode.org).""" import os import re import urllib2 # Directory or URL where Unicode tables reside. _UNICODE_DIR = "http://www.unicode.org/Public/6.3.0/ucd" # Largest valid Unicode code value. _RUNE_MAX = 0x10FFFF class Error(Exception): """Unicode error base class.""" class InputError(Error): """Unicode input error class. Raised on invalid input.""" def _UInt(s): """Converts string to Unicode code point ('263A' => 0x263a). Args: s: string to convert Returns: Unicode code point Raises: InputError: the string is not a valid Unicode value. """ try: v = int(s, 16) except ValueError: v = -1 if len(s) < 4 or len(s) > 6 or v < 0 or v > _RUNE_MAX: raise InputError("invalid Unicode value %s" % (s,)) return v def _URange(s): """Converts string to Unicode range. '0001..0003' => [1, 2, 3]. '0001' => [1]. Args: s: string to convert Returns: Unicode range Raises: InputError: the string is not a valid Unicode range. """ a = s.split("..") if len(a) == 1: return [_UInt(a[0])] if len(a) == 2: lo = _UInt(a[0]) hi = _UInt(a[1]) if lo < hi: return range(lo, hi + 1) raise InputError("invalid Unicode range %s" % (s,)) def _UStr(v): """Converts Unicode code point to hex string. 0x263a => '0x263A'. Args: v: code point to convert Returns: Unicode string Raises: InputError: the argument is not a valid Unicode value. """ if v < 0 or v > _RUNE_MAX: raise InputError("invalid Unicode value %s" % (v,)) return "0x%04X" % (v,) def _ParseContinue(s): """Parses a Unicode continuation field. These are of the form '<Name, First>' or '<Name, Last>'. Instead of giving an explicit range in a single table entry, some Unicode tables use two entries, one for the first code value in the range and one for the last. The first entry's description is '<Name, First>' instead of 'Name' and the second is '<Name, Last>'. '<Name, First>' => ('Name', 'First') '<Name, Last>' => ('Name', 'Last') 'Anything else' => ('Anything else', None) Args: s: continuation field string Returns: pair: name and ('First', 'Last', or None) """ match = re.match("<(.*), (First|Last)>", s) if match is not None: return match.groups() return (s, None) def ReadUnicodeTable(filename, nfields, doline): """Generic Unicode table text file reader. The reader takes care of stripping out comments and also parsing the two different ways that the Unicode tables specify code ranges (using the .. notation and splitting the range across multiple lines). Each non-comment line in the table is expected to have the given number of fields. The first field is known to be the Unicode value and the second field its description. The reader calls doline(codes, fields) for each entry in the table. If fn raises an exception, the reader prints that exception, prefixed with the file name and line number, and continues processing the file. When done with the file, the reader re-raises the first exception encountered during the file. Arguments: filename: the Unicode data file to read, or a file-like object. nfields: the number of expected fields per line in that file. doline: the function to call for each table entry. Raises: InputError: nfields is invalid (must be >= 2). """ if nfields < 2: raise InputError("invalid number of fields %d" % (nfields,)) if type(filename) == str: if filename.startswith("http://"): fil = urllib2.urlopen(filename) else: fil = open(filename, "r") else: fil = filename first = None # first code in multiline range expect_last = None # tag expected for "Last" line in multiline range lineno = 0 # current line number for line in fil: lineno += 1 try: # Chop # comments and white space; ignore empty lines. sharp = line.find("#") if sharp >= 0: line = line[:sharp] line = line.strip() if not line: continue # Split fields on ";", chop more white space. # Must have the expected number of fields. fields = [s.strip() for s in line.split(";")] if len(fields) != nfields: raise InputError("wrong number of fields %d %d - %s" % (len(fields), nfields, line)) # The Unicode text files have two different ways # to list a Unicode range. Either the first field is # itself a range (0000..FFFF), or the range is split # across two lines, with the second field noting # the continuation. codes = _URange(fields[0]) (name, cont) = _ParseContinue(fields[1]) if expect_last is not None: # If the last line gave the First code in a range, # this one had better give the Last one. if (len(codes) != 1 or codes[0] <= first or cont != "Last" or name != expect_last): raise InputError("expected Last line for %s" % (expect_last,)) codes = range(first, codes[0] + 1) first = None expect_last = None fields[0] = "%04X..%04X" % (codes[0], codes[-1]) fields[1] = name elif cont == "First": # Otherwise, if this is the First code in a range, # remember it and go to the next line. if len(codes) != 1: raise InputError("bad First line: range given") expect_last = name first = codes[0] continue doline(codes, fields) except Exception, e: print "%s:%d: %s" % (filename, lineno, e) raise if expect_last is not None: raise InputError("expected Last line for %s; got EOF" % (expect_last,)) def CaseGroups(unicode_dir=_UNICODE_DIR): """Returns list of Unicode code groups equivalent under case folding. Each group is a sorted list of code points, and the list of groups is sorted by first code point in the group. Args: unicode_dir: Unicode data directory Returns: list of Unicode code groups """ # Dict mapping lowercase code point to fold-equivalent group. togroup = {} def DoLine(codes, fields): """Process single CaseFolding.txt line, updating togroup.""" (_, foldtype, lower, _) = fields if foldtype not in ("C", "S"): return lower = _UInt(lower) togroup.setdefault(lower, [lower]).extend(codes) ReadUnicodeTable(unicode_dir+"/CaseFolding.txt", 4, DoLine) groups = togroup.values() for g in groups: g.sort() groups.sort() return togroup, groups def Scripts(unicode_dir=_UNICODE_DIR): """Returns dict mapping script names to code lists. Args: unicode_dir: Unicode data directory Returns: dict mapping script names to code lists """ scripts = {} def DoLine(codes, fields): """Process single Scripts.txt line, updating scripts.""" (_, name) = fields scripts.setdefault(name, []).extend(codes) ReadUnicodeTable(unicode_dir+"/Scripts.txt", 2, DoLine) return scripts def Categories(unicode_dir=_UNICODE_DIR): """Returns dict mapping category names to code lists. Args: unicode_dir: Unicode data directory Returns: dict mapping category names to code lists """ categories = {} def DoLine(codes, fields): """Process single UnicodeData.txt line, updating categories.""" category = fields[2] categories.setdefault(category, []).extend(codes) # Add codes from Lu into L, etc. if len(category) > 1: short = category[0] categories.setdefault(short, []).extend(codes) ReadUnicodeTable(unicode_dir+"/UnicodeData.txt", 15, DoLine) return categories
hcsturix74/django
refs/heads/master
tests/syndication_tests/urls.py
236
from django.conf.urls import url from . import feeds urlpatterns = [ url(r'^syndication/rss2/$', feeds.TestRss2Feed()), url(r'^syndication/rss2/guid_ispermalink_true/$', feeds.TestRss2FeedWithGuidIsPermaLinkTrue()), url(r'^syndication/rss2/guid_ispermalink_false/$', feeds.TestRss2FeedWithGuidIsPermaLinkFalse()), url(r'^syndication/rss091/$', feeds.TestRss091Feed()), url(r'^syndication/no_pubdate/$', feeds.TestNoPubdateFeed()), url(r'^syndication/atom/$', feeds.TestAtomFeed()), url(r'^syndication/latest/$', feeds.TestLatestFeed()), url(r'^syndication/custom/$', feeds.TestCustomFeed()), url(r'^syndication/naive-dates/$', feeds.NaiveDatesFeed()), url(r'^syndication/aware-dates/$', feeds.TZAwareDatesFeed()), url(r'^syndication/feedurl/$', feeds.TestFeedUrlFeed()), url(r'^syndication/articles/$', feeds.ArticlesFeed()), url(r'^syndication/template/$', feeds.TemplateFeed()), url(r'^syndication/template_context/$', feeds.TemplateContextFeed()), ]
haoyunfeix/crosswalk-test-suite
refs/heads/master
apptools/apptools-android-tests/apptools/manifest_package_id.py
24
#!/usr/bin/env python # # Copyright (c) 2015 Intel Corporation. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of works must retain the original copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the original 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 Intel Corporation nor the names of its contributors # may be used to endorse or promote products derived from this work without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION 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. # # Authors: # Liu, Yun <yunx.liu@intel.com> import unittest import os import comm from xml.etree import ElementTree import json class TestCrosswalkApptoolsFunctions(unittest.TestCase): def test_update_packageID(self): comm.setUp() comm.create(self) os.chdir('org.xwalk.test') jsonfile = open(comm.ConstPath + "/../tools/org.xwalk.test/app/manifest.json", "r") jsons = jsonfile.read() jsonfile.close() jsonDict = json.loads(jsons) jsonDict["xwalk_package_id"] = "org.test.foo" json.dump(jsonDict, open(comm.ConstPath + "/../tools/org.xwalk.test/app/manifest.json", "w")) buildcmd = comm.HOST_PREFIX + comm.PackTools + "crosswalk-app build" return_code = os.system(buildcmd) comm.clear("org.xwalk.test") self.assertNotEquals(return_code, 0) if __name__ == '__main__': unittest.main()
udoyen/pythonlearning
refs/heads/master
1-35/ex15-1.py
1
# Ask user for name of file to read content print "Enter the name of file to read" # Assign user input to variable filename = raw_input('> ') # Open file for reading and assign to variable 'myfile' myfile = open(filename) # Print name of file print "Here's your file %r:" % filename # Read file content and print to screen print myfile.read() myfile.close() # Ask for filename again print "Type the filename again:" # Assign user input to variable txt = raw_input('> ') # Open file for reading and assign to variable 'myfile' dfile = open(txt) # Read file content and print to screen print dfile.read() dfile.close()
Xaxetrov/OSCAR
refs/heads/master
oscar/meta_action/train_unit.py
1
from oscar.util.selection import * def train_unit(obs, building_id, action_train_id): command_center = find_position(obs, building_id) return [actions.FunctionCall(SELECT_POINT, [NEW_SELECTION, command_center]), actions.FunctionCall(action_train_id, [NOT_QUEUED])]
bdero/edx-platform
refs/heads/master
common/djangoapps/contentserver/__init__.py
12133432
h4ck3rm1k3/pip
refs/heads/develop
tests/data/packages/LocalEnvironMarker/localenvironmarker/__init__.py
12133432
402231466/40223146
refs/heads/master
static/Brython3.1.1-20150328-091302/Lib/site-packages/turtle.py
619
import math from javascript import console from browser import document, html import _svg _CFG = {"width" : 0.5, # Screen "height" : 0.75, "canvwidth" : 400, "canvheight": 300, "leftright": None, "topbottom": None, "mode": "standard", # TurtleScreen "colormode": 1.0, "delay": 10, "undobuffersize": 1000, # RawTurtle "shape": "classic", "pencolor" : "black", "fillcolor" : "black", "resizemode" : "noresize", "visible" : True, "language": "english", # docstrings "exampleturtle": "turtle", "examplescreen": "screen", "title": "Python Turtle Graphics", "using_IDLE": False } class Vec2D(tuple): """A 2 dimensional vector class, used as a helper class for implementing turtle graphics. May be useful for turtle graphics programs also. Derived from tuple, so a vector is a tuple! Provides (for a, b vectors, k number): a+b vector addition a-b vector subtraction a*b inner product k*a and a*k multiplication with scalar |a| absolute value of a a.rotate(angle) rotation """ def __new__(cls, x, y): return tuple.__new__(cls, (x, y)) def __add__(self, other): return Vec2D(self[0]+other[0], self[1]+other[1]) def __mul__(self, other): if isinstance(other, Vec2D): return self[0]*other[0]+ self[1]*other[1] return Vec2D(self[0]*other, self[1]*other) def __rmul__(self, other): if isinstance(other, int) or isinstance(other, float): return Vec2D(self[0]*other, self[1]*other) def __sub__(self, other): return Vec2D(self[0]-other[0], self[1]-other[1]) def __neg__(self): return Vec2D(-self[0], -self[1]) def __abs__(self): return (self[0]**2 + self[1]**2)**0.5 def rotate(self, angle): """rotate self counterclockwise by angle """ perp = Vec2D(-self[1], self[0]) angle = angle * math.pi / 180.0 c, s = math.cos(angle), math.sin(angle) return Vec2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s) def __getnewargs__(self): return (self[0], self[1]) def __repr__(self): return "(%.2f,%.2f)" % self ############################################################################## ### From here up to line : Tkinter - Interface for turtle.py ### ### May be replaced by an interface to some different graphics toolkit ### ############################################################################## class _Root: """Root class for Screen based on Tkinter.""" def setupcanvas(self, width, height, cwidth, cheight): self._svg=_svg.svg(Id="mycanvas", width=cwidth, height=cheight) self._canvas=_svg.g(transform="translate(%d,%d)" % (cwidth//2, cheight//2)) self._svg <= self._canvas def end(self): def set_svg(): #have to do this to get animate to work... document['container'].html=document['container'].html if "mycanvas" not in document: document["container"] <= self._svg from browser import timer #need this for chrome so that first few draw commands are viewed properly. timer.set_timeout(set_svg, 1) def _getcanvas(self): return self._canvas def win_width(self): return self._canvas.width def win_height(self): return self._canvas.height class TurtleScreenBase: """Provide the basic graphics functionality. Interface between Tkinter and turtle.py. To port turtle.py to some different graphics toolkit a corresponding TurtleScreenBase class has to be implemented. """ #@staticmethod #def _blankimage(): # """return a blank image object # """ # pass #@staticmethod #def _image(filename): # """return an image object containing the # imagedata from a gif-file named filename. # """ # pass def __init__(self, cv): self.cv = cv self._previous_turtle_attributes={} self._draw_pos=0 self.canvwidth = cv.width self.canvheight = cv.height self.xscale = self.yscale = 1.0 def _createpoly(self): """Create an invisible polygon item on canvas self.cv) """ #console.log("_createpoly") pass def _drawpoly(self, polyitem, coordlist, fill=None, outline=None, width=None, top=False): """Configure polygonitem polyitem according to provided arguments: coordlist is sequence of coordinates fill is filling color outline is outline color top is a boolean value, which specifies if polyitem will be put on top of the canvas' displaylist so it will not be covered by other items. """ #console.log("_drawpoly") pass def _drawline(self, lineitem, coordlist=None, fill=None, width=None, top=False): """Configure lineitem according to provided arguments: coordlist is sequence of coordinates fill is drawing color width is width of drawn line. top is a boolean value, which specifies if polyitem will be put on top of the canvas' displaylist so it will not be covered by other items. """ #console.log("_drawline") #if not isinstance(lineitem, Turtle): # return if coordlist is not None: _x0, _y0=coordlist[0] _x1, _y1=coordlist[1] _dist=math.sqrt( (_x0-_x1)*(_x0-_x1) + (_y0-_y1)*(_y0-_y1) ) _dur="%4.2fs" % (0.01*_dist) if _dur == '0.00s': _dur='0.1s' #_dur="%ss" % 1 self._draw_pos+=1 _shape=["%s,%s" % (_x, _y) for _x,_y in lineitem.get_shapepoly()] if 0: #if lineitem.isvisible(): if lineitem in self._previous_turtle_attributes: _previous=self._previous_turtle_attributes[lineitem] if _previous.heading() != lineitem.heading(): #if self._turtle_heading[lineitem] != lineitem.heading(): _rotate=_previous.heading() _turtle=_svg.polygon(points=" ".join(_shape), transform="rotate(%s)" % (_rotate-90), style={'stroke': fill, 'fill': fill, 'stroke-width': width, 'display': 'none'}) # we need to rotate our turtle.. _turtle <= _svg.animateTransform( Id="animateLine%s" % self._draw_pos, attributeName="transform", type="rotate", attributeType="XML", From=_rotate - 90, to=lineitem.heading() -90, dur=_dur, begin="animateLine%s.end" % (self._draw_pos-1)) _turtle <= _svg.set(attributeName="display", attributeType="CSS", to="block", begin="animateLine%s.begin" % self._draw_pos, end="animateLine%s.end" % self._draw_pos) #_turtle <= _svg.animateMotion(From="%s,%s" % (_x0*self.xscale, _y0*self.yscale), # to="%s,%s" % (_x0*self.xscale, _y0*self.yscale), # begin="animateLine%s.begin" % self._draw_pos, # end="animateLine%s.end" % self._draw_pos) #_turtle <= _svg.animate(attributeName="fill", # From=_previous.fill, to=fill, dur=_dur, # begin="animateLine%s.begin" % self._draw_pos) self._draw_pos+=1 self._canvas <= _turtle _line= _svg.line(x1=_x0*self.xscale, y1=_y0*self.yscale, x2=_x0*self.xscale, y2=_y0*self.yscale, style={'stroke': fill, 'stroke-width': width}) _an1=_svg.animate(Id="animateLine%s" % self._draw_pos, attributeName="x2", attributeType="XML", From=_x0*self.xscale, to=_x1*self.xscale, dur=_dur, fill='freeze') _an2=_svg.animate(attributeName="y2", attributeType="XML", begin="animateLine%s.begin" % self._draw_pos, From=_y0*self.xscale, to=_y1*self.xscale, dur=_dur, fill='freeze') # draw turtle if lineitem.isvisible(): _turtle=_svg.polygon(points=" ".join(_shape), transform="rotate(%s)" % (lineitem.heading() - 90), style={'stroke': fill, 'fill': fill, 'stroke-width': width, 'display': 'none'}) _turtle <= _svg.animateMotion(From="%s,%s" % (_x0*self.xscale, _y0*self.yscale), to="%s,%s" % (_x1*self.xscale, _y1*self.yscale), dur=_dur, begin="animateLine%s.begin" % self._draw_pos) _turtle <= _svg.set(attributeName="display", attributeType="CSS", to="block", begin="animateLine%s.begin" % self._draw_pos, end="animateLine%s.end" % self._draw_pos) self._canvas <= _turtle self._previous_turtle_attributes[lineitem]=lineitem if self._draw_pos == 1: _an1.setAttribute('begin', "0s") else: _an1.setAttribute('begin', "animateLine%s.end" % (self._draw_pos-1)) _line <= _an1 _line <= _an2 self._canvas <= _line def _delete(self, item): """Delete graphics item from canvas. If item is"all" delete all graphics items. """ pass def _update(self): """Redraw graphics items on canvas """ pass def _delay(self, delay): """Delay subsequent canvas actions for delay ms.""" pass def _iscolorstring(self, color): """Check if the string color is a legal Tkinter color string. """ return True #fix me #try: # rgb = self.cv.winfo_rgb(color) # ok = True #except TK.TclError: # ok = False #return ok def _bgcolor(self, color=None): """Set canvas' backgroundcolor if color is not None, else return backgroundcolor.""" if color is not None: self.cv.style.backgroundColor=color else: return self.cv.style.backgroundColor def _write(self, pos, txt, align, font, pencolor): """Write txt at pos in canvas with specified font and color. Return text item and x-coord of right bottom corner of text's bounding box.""" self._draw_pos+=1 _text= _svg.text(txt, x=pos[0], y=pos[1], fill=pencolor, style={'display': 'none'}) _text <= _svg.animate(Id="animateLine%s" % self._draw_pos, attributeName="display", attributeType="CSS", From="block", to="block", dur="1s", fill='freeze', begin="animateLine%s.end" % (self._draw_pos-1)) self._canvas <= _text return Vec2D(pos[0]+50, pos[1]+50) #fix me ## def _dot(self, pos, size, color): ## """may be implemented for some other graphics toolkit""" def _createimage(self, image): """Create and return image item on canvas. """ pass def _drawimage(self, item, pos, image): """Configure image item as to draw image object at position (x,y) on canvas) """ pass def _setbgpic(self, item, image): """Configure image item as to draw image object at center of canvas. Set item to the first item in the displaylist, so it will be drawn below any other item .""" pass def _type(self, item): """Return 'line' or 'polygon' or 'image' depending on type of item. """ pass def _resize(self, canvwidth=None, canvheight=None, bg=None): """Resize the canvas the turtles are drawing on. Does not alter the drawing window. """ self.cv.style.width=canvwidth self.cv.style.height=canvheight if bg is not None: self.cv.style.backgroundColor=bg def _window_size(self): """ Return the width and height of the turtle window. """ #for now just return canvas width/height return self.cv.width, self.cv.height def mainloop(self): """Starts event loop - calling Tkinter's mainloop function. No argument. Must be last statement in a turtle graphics program. Must NOT be used if a script is run from within IDLE in -n mode (No subprocess) - for interactive use of turtle graphics. Example (for a TurtleScreen instance named screen): >>> screen.mainloop() """ pass def textinput(self, title, prompt): """Pop up a dialog window for input of a string. Arguments: title is the title of the dialog window, prompt is a text mostly describing what information to input. Return the string input If the dialog is canceled, return None. Example (for a TurtleScreen instance named screen): >>> screen.textinput("NIM", "Name of first player:") """ pass def numinput(self, title, prompt, default=None, minval=None, maxval=None): """Pop up a dialog window for input of a number. Arguments: title is the title of the dialog window, prompt is a text mostly describing what numerical information to input. default: default value minval: minimum value for imput maxval: maximum value for input The number input must be in the range minval .. maxval if these are given. If not, a hint is issued and the dialog remains open for correction. Return the number input. If the dialog is canceled, return None. Example (for a TurtleScreen instance named screen): >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000) """ pass ############################################################################## ### End of Tkinter - interface ### ############################################################################## class Terminator (Exception): """Will be raised in TurtleScreen.update, if _RUNNING becomes False. This stops execution of a turtle graphics script. Main purpose: use in the Demo-Viewer turtle.Demo.py. """ pass class TurtleGraphicsError(Exception): """Some TurtleGraphics Error """ pass class Shape: """Data structure modeling shapes. attribute _type is one of "polygon", "image", "compound" attribute _data is - depending on _type a poygon-tuple, an image or a list constructed using the addcomponent method. """ def __init__(self, type_, data=None): self._type = type_ if type_ == "polygon": if isinstance(data, list): data = tuple(data) elif type_ == "image": if isinstance(data, str): if data.lower().endswith(".gif") and isfile(data): data = TurtleScreen._image(data) # else data assumed to be Photoimage elif type_ == "compound": data = [] else: raise TurtleGraphicsError("There is no shape type %s" % type_) self._data = data def addcomponent(self, poly, fill, outline=None): """Add component to a shape of type compound. Arguments: poly is a polygon, i. e. a tuple of number pairs. fill is the fillcolor of the component, outline is the outline color of the component. call (for a Shapeobject namend s): -- s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue") Example: >>> poly = ((0,0),(10,-5),(0,10),(-10,-5)) >>> s = Shape("compound") >>> s.addcomponent(poly, "red", "blue") >>> # .. add more components and then use register_shape() """ if self._type != "compound": raise TurtleGraphicsError("Cannot add component to %s Shape" % self._type) if outline is None: outline = fill self._data.append([poly, fill, outline]) class TurtleScreen(TurtleScreenBase): """Provides screen oriented methods like setbg etc. Only relies upon the methods of TurtleScreenBase and NOT upon components of the underlying graphics toolkit - which is Tkinter in this case. """ _RUNNING = True def __init__(self, cv, mode=_CFG["mode"], colormode=_CFG["colormode"], delay=_CFG["delay"]): self._shapes = { "arrow" : Shape("polygon", ((-10,0), (10,0), (0,10))), "turtle" : Shape("polygon", ((0,16), (-2,14), (-1,10), (-4,7), (-7,9), (-9,8), (-6,5), (-7,1), (-5,-3), (-8,-6), (-6,-8), (-4,-5), (0,-7), (4,-5), (6,-8), (8,-6), (5,-3), (7,1), (6,5), (9,8), (7,9), (4,7), (1,10), (2,14))), "circle" : Shape("polygon", ((10,0), (9.51,3.09), (8.09,5.88), (5.88,8.09), (3.09,9.51), (0,10), (-3.09,9.51), (-5.88,8.09), (-8.09,5.88), (-9.51,3.09), (-10,0), (-9.51,-3.09), (-8.09,-5.88), (-5.88,-8.09), (-3.09,-9.51), (-0.00,-10.00), (3.09,-9.51), (5.88,-8.09), (8.09,-5.88), (9.51,-3.09))), "square" : Shape("polygon", ((10,-10), (10,10), (-10,10), (-10,-10))), "triangle" : Shape("polygon", ((10,-5.77), (0,11.55), (-10,-5.77))), "classic": Shape("polygon", ((0,0),(-5,-9),(0,-7),(5,-9))), "blank" : Shape("image", None) #self._blankimage()) } self._bgpics = {"nopic" : ""} TurtleScreenBase.__init__(self, cv) self._mode = mode self._delayvalue = delay self._colormode = _CFG["colormode"] self._keys = [] self.clear() def clear(self): """Delete all drawings and all turtles from the TurtleScreen. No argument. Reset empty TurtleScreen to its initial state: white background, no backgroundimage, no eventbindings and tracing on. Example (for a TurtleScreen instance named screen): >>> screen.clear() Note: this method is not available as function. """ self._delayvalue = _CFG["delay"] self._colormode = _CFG["colormode"] self._delete("all") self._bgpic = self._createimage("") self._bgpicname = "nopic" self._tracing = 1 self._updatecounter = 0 self._turtles = [] self.bgcolor("white") #for btn in 1, 2, 3: # self.onclick(None, btn) #self.onkeypress(None) #for key in self._keys[:]: # self.onkey(None, key) # self.onkeypress(None, key) Turtle._pen = None def mode(self, mode=None): """Set turtle-mode ('standard', 'logo' or 'world') and perform reset. Optional argument: mode -- on of the strings 'standard', 'logo' or 'world' Mode 'standard' is compatible with turtle.py. Mode 'logo' is compatible with most Logo-Turtle-Graphics. Mode 'world' uses userdefined 'worldcoordinates'. *Attention*: in this mode angles appear distorted if x/y unit-ratio doesn't equal 1. If mode is not given, return the current mode. Mode Initial turtle heading positive angles ------------|-------------------------|------------------- 'standard' to the right (east) counterclockwise 'logo' upward (north) clockwise Examples: >>> mode('logo') # resets turtle heading to north >>> mode() 'logo' """ if mode is None: return self._mode mode = mode.lower() if mode not in ["standard", "logo", "world"]: raise TurtleGraphicsError("No turtle-graphics-mode %s" % mode) self._mode = mode if mode in ["standard", "logo"]: self._setscrollregion(-self.canvwidth//2, -self.canvheight//2, self.canvwidth//2, self.canvheight//2) self.xscale = self.yscale = 1.0 self.reset() def setworldcoordinates(self, llx, lly, urx, ury): """Set up a user defined coordinate-system. Arguments: llx -- a number, x-coordinate of lower left corner of canvas lly -- a number, y-coordinate of lower left corner of canvas urx -- a number, x-coordinate of upper right corner of canvas ury -- a number, y-coordinate of upper right corner of canvas Set up user coodinat-system and switch to mode 'world' if necessary. This performs a screen.reset. If mode 'world' is already active, all drawings are redrawn according to the new coordinates. But ATTENTION: in user-defined coordinatesystems angles may appear distorted. (see Screen.mode()) Example (for a TurtleScreen instance named screen): >>> screen.setworldcoordinates(-10,-0.5,50,1.5) >>> for _ in range(36): ... left(10) ... forward(0.5) """ if self.mode() != "world": self.mode("world") xspan = float(urx - llx) yspan = float(ury - lly) wx, wy = self._window_size() self.screensize(wx-20, wy-20) oldxscale, oldyscale = self.xscale, self.yscale self.xscale = self.canvwidth / xspan self.yscale = self.canvheight / yspan srx1 = llx * self.xscale sry1 = -ury * self.yscale srx2 = self.canvwidth + srx1 sry2 = self.canvheight + sry1 self._setscrollregion(srx1, sry1, srx2, sry2) self._rescale(self.xscale/oldxscale, self.yscale/oldyscale) #self.update() def register_shape(self, name, shape=None): """Adds a turtle shape to TurtleScreen's shapelist. Arguments: (1) name is the name of a gif-file and shape is None. Installs the corresponding image shape. !! Image-shapes DO NOT rotate when turning the turtle, !! so they do not display the heading of the turtle! (2) name is an arbitrary string and shape is a tuple of pairs of coordinates. Installs the corresponding polygon shape (3) name is an arbitrary string and shape is a (compound) Shape object. Installs the corresponding compound shape. To use a shape, you have to issue the command shape(shapename). call: register_shape("turtle.gif") --or: register_shape("tri", ((0,0), (10,10), (-10,10))) Example (for a TurtleScreen instance named screen): >>> screen.register_shape("triangle", ((5,-3),(0,5),(-5,-3))) """ if shape is None: # image if name.lower().endswith(".gif"): shape = Shape("image", self._image(name)) else: raise TurtleGraphicsError("Bad arguments for register_shape.\n" + "Use help(register_shape)" ) elif isinstance(shape, tuple): shape = Shape("polygon", shape) ## else shape assumed to be Shape-instance self._shapes[name] = shape def _colorstr(self, color): """Return color string corresponding to args. Argument may be a string or a tuple of three numbers corresponding to actual colormode, i.e. in the range 0<=n<=colormode. If the argument doesn't represent a color, an error is raised. """ if len(color) == 1: color = color[0] if isinstance(color, str): if self._iscolorstring(color) or color == "": return color else: raise TurtleGraphicsError("bad color string: %s" % str(color)) try: r, g, b = color except: raise TurtleGraphicsError("bad color arguments: %s" % str(color)) if self._colormode == 1.0: r, g, b = [round(255.0*x) for x in (r, g, b)] if not ((0 <= r <= 255) and (0 <= g <= 255) and (0 <= b <= 255)): raise TurtleGraphicsError("bad color sequence: %s" % str(color)) return "#%02x%02x%02x" % (r, g, b) def _color(self, cstr): if not cstr.startswith("#"): return cstr if len(cstr) == 7: cl = [int(cstr[i:i+2], 16) for i in (1, 3, 5)] elif len(cstr) == 4: cl = [16*int(cstr[h], 16) for h in cstr[1:]] else: raise TurtleGraphicsError("bad colorstring: %s" % cstr) return tuple([c * self._colormode/255 for c in cl]) def colormode(self, cmode=None): """Return the colormode or set it to 1.0 or 255. Optional argument: cmode -- one of the values 1.0 or 255 r, g, b values of colortriples have to be in range 0..cmode. Example (for a TurtleScreen instance named screen): >>> screen.colormode() 1.0 >>> screen.colormode(255) >>> pencolor(240,160,80) """ if cmode is None: return self._colormode if cmode == 1.0: self._colormode = float(cmode) elif cmode == 255: self._colormode = int(cmode) def reset(self): """Reset all Turtles on the Screen to their initial state. No argument. Example (for a TurtleScreen instance named screen): >>> screen.reset() """ for turtle in self._turtles: turtle._setmode(self._mode) turtle.reset() def turtles(self): """Return the list of turtles on the screen. Example (for a TurtleScreen instance named screen): >>> screen.turtles() [<turtle.Turtle object at 0x00E11FB0>] """ return self._turtles def bgcolor(self, *args): """Set or return backgroundcolor of the TurtleScreen. Arguments (if given): a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers. Example (for a TurtleScreen instance named screen): >>> screen.bgcolor("orange") >>> screen.bgcolor() 'orange' >>> screen.bgcolor(0.5,0,0.5) >>> screen.bgcolor() '#800080' """ if args: color = self._colorstr(args) else: color = None color = self._bgcolor(color) if color is not None: color = self._color(color) return color def tracer(self, n=None, delay=None): """Turns turtle animation on/off and set delay for update drawings. Optional arguments: n -- nonnegative integer delay -- nonnegative integer If n is given, only each n-th regular screen update is really performed. (Can be used to accelerate the drawing of complex graphics.) Second arguments sets delay value (see RawTurtle.delay()) Example (for a TurtleScreen instance named screen): >>> screen.tracer(8, 25) >>> dist = 2 >>> for i in range(200): ... fd(dist) ... rt(90) ... dist += 2 """ if n is None: return self._tracing self._tracing = int(n) self._updatecounter = 0 if delay is not None: self._delayvalue = int(delay) if self._tracing: self.update() def delay(self, delay=None): """ Return or set the drawing delay in milliseconds. Optional argument: delay -- positive integer Example (for a TurtleScreen instance named screen): >>> screen.delay(15) >>> screen.delay() 15 """ if delay is None: return self._delayvalue self._delayvalue = int(delay) def _incrementudc(self): """Increment update counter.""" if not TurtleScreen._RUNNING: TurtleScreen._RUNNNING = True raise Terminator if self._tracing > 0: self._updatecounter += 1 self._updatecounter %= self._tracing def update(self): """Perform a TurtleScreen update. """ return tracing = self._tracing self._tracing = True for t in self.turtles(): #t._update_data() t._drawturtle() self._tracing = tracing self._update() def window_width(self): """ Return the width of the turtle window. Example (for a TurtleScreen instance named screen): >>> screen.window_width() 640 """ return self._window_size()[0] def window_height(self): """ Return the height of the turtle window. Example (for a TurtleScreen instance named screen): >>> screen.window_height() 480 """ return self._window_size()[1] def getcanvas(self): """Return the Canvas of this TurtleScreen. No argument. Example (for a Screen instance named screen): >>> cv = screen.getcanvas() >>> cv <turtle.ScrolledCanvas instance at 0x010742D8> """ return self.cv def getshapes(self): """Return a list of names of all currently available turtle shapes. No argument. Example (for a TurtleScreen instance named screen): >>> screen.getshapes() ['arrow', 'blank', 'circle', ... , 'turtle'] """ return sorted(self._shapes.keys()) def onclick(self, fun, btn=1, add=None): """Bind fun to mouse-click event on canvas. Arguments: fun -- a function with two arguments, the coordinates of the clicked point on the canvas. num -- the number of the mouse-button, defaults to 1 Example (for a TurtleScreen instance named screen) >>> screen.onclick(goto) >>> # Subsequently clicking into the TurtleScreen will >>> # make the turtle move to the clicked point. >>> screen.onclick(None) """ self._onscreenclick(fun, btn, add) def onkey(self, fun, key): """Bind fun to key-release event of key. Arguments: fun -- a function with no arguments key -- a string: key (e.g. "a") or key-symbol (e.g. "space") In order to be able to register key-events, TurtleScreen must have focus. (See method listen.) Example (for a TurtleScreen instance named screen): >>> def f(): ... fd(50) ... lt(60) ... >>> screen.onkey(f, "Up") >>> screen.listen() Subsequently the turtle can be moved by repeatedly pressing the up-arrow key, consequently drawing a hexagon """ if fun is None: if key in self._keys: self._keys.remove(key) elif key not in self._keys: self._keys.append(key) self._onkeyrelease(fun, key) def onkeypress(self, fun, key=None): """Bind fun to key-press event of key if key is given, or to any key-press-event if no key is given. Arguments: fun -- a function with no arguments key -- a string: key (e.g. "a") or key-symbol (e.g. "space") In order to be able to register key-events, TurtleScreen must have focus. (See method listen.) Example (for a TurtleScreen instance named screen and a Turtle instance named turtle): >>> def f(): ... fd(50) ... lt(60) ... >>> screen.onkeypress(f, "Up") >>> screen.listen() Subsequently the turtle can be moved by repeatedly pressing the up-arrow key, or by keeping pressed the up-arrow key. consequently drawing a hexagon. """ if fun is None: if key in self._keys: self._keys.remove(key) elif key is not None and key not in self._keys: self._keys.append(key) self._onkeypress(fun, key) def listen(self, xdummy=None, ydummy=None): """Set focus on TurtleScreen (in order to collect key-events) No arguments. Dummy arguments are provided in order to be able to pass listen to the onclick method. Example (for a TurtleScreen instance named screen): >>> screen.listen() """ self._listen() def ontimer(self, fun, t=0): """Install a timer, which calls fun after t milliseconds. Arguments: fun -- a function with no arguments. t -- a number >= 0 Example (for a TurtleScreen instance named screen): >>> running = True >>> def f(): ... if running: ... fd(50) ... lt(60) ... screen.ontimer(f, 250) ... >>> f() # makes the turtle marching around >>> running = False """ self._ontimer(fun, t) def bgpic(self, picname=None): """Set background image or return name of current backgroundimage. Optional argument: picname -- a string, name of a gif-file or "nopic". If picname is a filename, set the corresponding image as background. If picname is "nopic", delete backgroundimage, if present. If picname is None, return the filename of the current backgroundimage. Example (for a TurtleScreen instance named screen): >>> screen.bgpic() 'nopic' >>> screen.bgpic("landscape.gif") >>> screen.bgpic() 'landscape.gif' """ if picname is None: return self._bgpicname if picname not in self._bgpics: self._bgpics[picname] = self._image(picname) self._setbgpic(self._bgpic, self._bgpics[picname]) self._bgpicname = picname def screensize(self, canvwidth=None, canvheight=None, bg=None): """Resize the canvas the turtles are drawing on. Optional arguments: canvwidth -- positive integer, new width of canvas in pixels canvheight -- positive integer, new height of canvas in pixels bg -- colorstring or color-tuple, new backgroundcolor If no arguments are given, return current (canvaswidth, canvasheight) Do not alter the drawing window. To observe hidden parts of the canvas use the scrollbars. (Can make visible those parts of a drawing, which were outside the canvas before!) Example (for a Turtle instance named turtle): >>> turtle.screensize(2000,1500) >>> # e.g. to search for an erroneously escaped turtle ;-) """ return self._resize(canvwidth, canvheight, bg) onscreenclick = onclick resetscreen = reset clearscreen = clear addshape = register_shape onkeyrelease = onkey class TNavigator: """Navigation part of the RawTurtle. Implements methods for turtle movement. """ START_ORIENTATION = { "standard": Vec2D(1.0, 0.0), "world" : Vec2D(1.0, 0.0), "logo" : Vec2D(0.0, 1.0) } DEFAULT_MODE = "standard" DEFAULT_ANGLEOFFSET = 0 DEFAULT_ANGLEORIENT = 1 def __init__(self, mode=DEFAULT_MODE): self._angleOffset = self.DEFAULT_ANGLEOFFSET self._angleOrient = self.DEFAULT_ANGLEORIENT self._mode = mode self.undobuffer = None self.degrees() self._mode = None self._setmode(mode) TNavigator.reset(self) def reset(self): """reset turtle to its initial values Will be overwritten by parent class """ self._position = Vec2D(0.0, 0.0) self._orient = TNavigator.START_ORIENTATION[self._mode] def _setmode(self, mode=None): """Set turtle-mode to 'standard', 'world' or 'logo'. """ if mode is None: return self._mode if mode not in ["standard", "logo", "world"]: return self._mode = mode if mode in ["standard", "world"]: self._angleOffset = 0 self._angleOrient = 1 else: # mode == "logo": self._angleOffset = self._fullcircle/4. self._angleOrient = -1 def _setDegreesPerAU(self, fullcircle): """Helper function for degrees() and radians()""" self._fullcircle = fullcircle self._degreesPerAU = 360/fullcircle if self._mode == "standard": self._angleOffset = 0 else: self._angleOffset = fullcircle/4. def degrees(self, fullcircle=360.0): """ Set angle measurement units to degrees. Optional argument: fullcircle - a number Set angle measurement units, i. e. set number of 'degrees' for a full circle. Dafault value is 360 degrees. Example (for a Turtle instance named turtle): >>> turtle.left(90) >>> turtle.heading() 90 Change angle measurement unit to grad (also known as gon, grade, or gradian and equals 1/100-th of the right angle.) >>> turtle.degrees(400.0) >>> turtle.heading() 100 """ self._setDegreesPerAU(fullcircle) def radians(self): """ Set the angle measurement units to radians. No arguments. Example (for a Turtle instance named turtle): >>> turtle.heading() 90 >>> turtle.radians() >>> turtle.heading() 1.5707963267948966 """ self._setDegreesPerAU(2*math.pi) def _go(self, distance): """move turtle forward by specified distance""" #console.log('_go') ende = self._position + self._orient * distance self._goto(ende) def _rotate(self, angle): """Turn turtle counterclockwise by specified angle if angle > 0.""" #console.log('_rotate') angle *= self._degreesPerAU self._orient = self._orient.rotate(angle) def _goto(self, end): """move turtle to position end.""" #console.log('_goto') self._position = end def forward(self, distance): """Move the turtle forward by the specified distance. Aliases: forward | fd Argument: distance -- a number (integer or float) Move the turtle forward by the specified distance, in the direction the turtle is headed. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00) """ self._go(distance) def back(self, distance): """Move the turtle backward by distance. Aliases: back | backward | bk Argument: distance -- a number Move the turtle backward by distance ,opposite to the direction the turtle is headed. Do not change the turtle's heading. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00, 0.00) """ self._go(-distance) def right(self, angle): """Turn turtle right by angle units. Aliases: right | rt Argument: angle -- a number (integer or float) Turn turtle right by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on mode. (See this.) Example (for a Turtle instance named turtle): >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.0 """ self._rotate(-angle) def left(self, angle): """Turn turtle left by angle units. Aliases: left | lt Argument: angle -- a number (integer or float) Turn turtle left by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on mode. (See this.) Example (for a Turtle instance named turtle): >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.0 """ self._rotate(angle) def pos(self): """Return the turtle's current location (x,y), as a Vec2D-vector. Aliases: pos | position No arguments. Example (for a Turtle instance named turtle): >>> turtle.pos() (0.00, 240.00) """ return self._position def xcor(self): """ Return the turtle's x coordinate. No arguments. Example (for a Turtle instance named turtle): >>> reset() >>> turtle.left(60) >>> turtle.forward(100) >>> print turtle.xcor() 50.0 """ return self._position[0] def ycor(self): """ Return the turtle's y coordinate --- No arguments. Example (for a Turtle instance named turtle): >>> reset() >>> turtle.left(60) >>> turtle.forward(100) >>> print turtle.ycor() 86.6025403784 """ return self._position[1] def goto(self, x, y=None): """Move turtle to an absolute position. Aliases: setpos | setposition | goto: Arguments: x -- a number or a pair/vector of numbers y -- a number None call: goto(x, y) # two coordinates --or: goto((x, y)) # a pair (tuple) of coordinates --or: goto(vec) # e.g. as returned by pos() Move turtle to an absolute position. If the pen is down, a line will be drawn. The turtle's orientation does not change. Example (for a Turtle instance named turtle): >>> tp = turtle.pos() >>> tp (0.00, 0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00) """ if y is None: self._goto(Vec2D(*x)) else: self._goto(Vec2D(x, y)) def home(self): """Move turtle to the origin - coordinates (0,0). No arguments. Move turtle to the origin - coordinates (0,0) and set its heading to its start-orientation (which depends on mode). Example (for a Turtle instance named turtle): >>> turtle.home() """ self.goto(0, 0) self.setheading(0) def setx(self, x): """Set the turtle's first coordinate to x Argument: x -- a number (integer or float) Set the turtle's first coordinate to x, leave second coordinate unchanged. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 240.00) >>> turtle.setx(10) >>> turtle.position() (10.00, 240.00) """ self._goto(Vec2D(x, self._position[1])) def sety(self, y): """Set the turtle's second coordinate to y Argument: y -- a number (integer or float) Set the turtle's first coordinate to x, second coordinate remains unchanged. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00, -10.00) """ self._goto(Vec2D(self._position[0], y)) def distance(self, x, y=None): """Return the distance from the turtle to (x,y) in turtle step units. Arguments: x -- a number or a pair/vector of numbers or a turtle instance y -- a number None None call: distance(x, y) # two coordinates --or: distance((x, y)) # a pair (tuple) of coordinates --or: distance(vec) # e.g. as returned by pos() --or: distance(mypen) # where mypen is another turtle Example (for a Turtle instance named turtle): >>> turtle.pos() (0.00, 0.00) >>> turtle.distance(30,40) 50.0 >>> pen = Turtle() >>> pen.forward(77) >>> turtle.distance(pen) 77.0 """ if y is not None: pos = Vec2D(x, y) if isinstance(x, Vec2D): pos = x elif isinstance(x, tuple): pos = Vec2D(*x) elif isinstance(x, TNavigator): pos = x._position return abs(pos - self._position) def towards(self, x, y=None): """Return the angle of the line from the turtle's position to (x, y). Arguments: x -- a number or a pair/vector of numbers or a turtle instance y -- a number None None call: distance(x, y) # two coordinates --or: distance((x, y)) # a pair (tuple) of coordinates --or: distance(vec) # e.g. as returned by pos() --or: distance(mypen) # where mypen is another turtle Return the angle, between the line from turtle-position to position specified by x, y and the turtle's start orientation. (Depends on modes - "standard" or "logo") Example (for a Turtle instance named turtle): >>> turtle.pos() (10.00, 10.00) >>> turtle.towards(0,0) 225.0 """ if y is not None: pos = Vec2D(x, y) if isinstance(x, Vec2D): pos = x elif isinstance(x, tuple): pos = Vec2D(*x) elif isinstance(x, TNavigator): pos = x._position x, y = pos - self._position result = round(math.atan2(y, x)*180.0/math.pi, 10) % 360.0 result /= self._degreesPerAU return (self._angleOffset + self._angleOrient*result) % self._fullcircle def heading(self): """ Return the turtle's current heading. No arguments. Example (for a Turtle instance named turtle): >>> turtle.left(67) >>> turtle.heading() 67.0 """ x, y = self._orient result = round(math.atan2(y, x)*180.0/math.pi, 10) % 360.0 result /= self._degreesPerAU return (self._angleOffset + self._angleOrient*result) % self._fullcircle def setheading(self, to_angle): """Set the orientation of the turtle to to_angle. Aliases: setheading | seth Argument: to_angle -- a number (integer or float) Set the orientation of the turtle to to_angle. Here are some common directions in degrees: standard - mode: logo-mode: -------------------|-------------------- 0 - east 0 - north 90 - north 90 - east 180 - west 180 - south 270 - south 270 - west Example (for a Turtle instance named turtle): >>> turtle.setheading(90) >>> turtle.heading() 90 """ angle = (to_angle - self.heading())*self._angleOrient full = self._fullcircle angle = (angle+full/2.)%full - full/2. self._rotate(angle) def circle(self, radius, extent = None, steps = None): """ Draw a circle with given radius. Arguments: radius -- a number extent (optional) -- a number steps (optional) -- an integer Draw a circle with given radius. The center is radius units left of the turtle; extent - an angle - determines which part of the circle is drawn. If extent is not given, draw the entire circle. If extent is not a full circle, one endpoint of the arc is the current pen position. Draw the arc in counterclockwise direction if radius is positive, otherwise in clockwise direction. Finally the direction of the turtle is changed by the amount of extent. As the circle is approximated by an inscribed regular polygon, steps determines the number of steps to use. If not given, it will be calculated automatically. Maybe used to draw regular polygons. call: circle(radius) # full circle --or: circle(radius, extent) # arc --or: circle(radius, extent, steps) --or: circle(radius, steps=6) # 6-sided polygon Example (for a Turtle instance named turtle): >>> turtle.circle(50) >>> turtle.circle(120, 180) # semicircle """ if self.undobuffer: self.undobuffer.push(["seq"]) self.undobuffer.cumulate = True speed = self.speed() if extent is None: extent = self._fullcircle if steps is None: frac = abs(extent)/self._fullcircle steps = 1+int(min(11+abs(radius)/6.0, 59.0)*frac) w = 1.0 * extent / steps w2 = 0.5 * w l = 2.0 * radius * math.sin(w2*math.pi/180.0*self._degreesPerAU) if radius < 0: l, w, w2 = -l, -w, -w2 tr = self._tracer() dl = self._delay() if speed == 0: self._tracer(0, 0) else: self.speed(0) self._rotate(w2) for i in range(steps): self.speed(speed) self._go(l) self.speed(0) self._rotate(w) self._rotate(-w2) if speed == 0: self._tracer(tr, dl) self.speed(speed) if self.undobuffer: self.undobuffer.cumulate = False ## three dummy methods to be implemented by child class: def speed(self, s=0): """dummy method - to be overwritten by child class""" def _tracer(self, a=None, b=None): """dummy method - to be overwritten by child class""" def _delay(self, n=None): """dummy method - to be overwritten by child class""" fd = forward bk = back backward = back rt = right lt = left position = pos setpos = goto setposition = goto seth = setheading class TPen: """Drawing part of the RawTurtle. Implements drawing properties. """ def __init__(self, resizemode=_CFG["resizemode"]): self._resizemode = resizemode # or "user" or "noresize" self.undobuffer = None TPen._reset(self) def _reset(self, pencolor=_CFG["pencolor"], fillcolor=_CFG["fillcolor"]): self._pensize = 1 self._shown = True self._pencolor = pencolor self._fillcolor = fillcolor self._drawing = True self._speed = 3 self._stretchfactor = (1., 1.) self._shearfactor = 0. self._tilt = 0. self._shapetrafo = (1., 0., 0., 1.) self._outlinewidth = 1 def resizemode(self, rmode=None): """Set resizemode to one of the values: "auto", "user", "noresize". (Optional) Argument: rmode -- one of the strings "auto", "user", "noresize" Different resizemodes have the following effects: - "auto" adapts the appearance of the turtle corresponding to the value of pensize. - "user" adapts the appearance of the turtle according to the values of stretchfactor and outlinewidth (outline), which are set by shapesize() - "noresize" no adaption of the turtle's appearance takes place. If no argument is given, return current resizemode. resizemode("user") is called by a call of shapesize with arguments. Examples (for a Turtle instance named turtle): >>> turtle.resizemode("noresize") >>> turtle.resizemode() 'noresize' """ if rmode is None: return self._resizemode rmode = rmode.lower() if rmode in ["auto", "user", "noresize"]: self.pen(resizemode=rmode) def pensize(self, width=None): """Set or return the line thickness. Aliases: pensize | width Argument: width -- positive number Set the line thickness to width or return it. If resizemode is set to "auto" and turtleshape is a polygon, that polygon is drawn with the same line thickness. If no argument is given, current pensize is returned. Example (for a Turtle instance named turtle): >>> turtle.pensize() 1 >>> turtle.pensize(10) # from here on lines of width 10 are drawn """ if width is None: return self._pensize self.pen(pensize=width) def penup(self): """Pull the pen up -- no drawing when moving. Aliases: penup | pu | up No argument Example (for a Turtle instance named turtle): >>> turtle.penup() """ if not self._drawing: return self.pen(pendown=False) def pendown(self): """Pull the pen down -- drawing when moving. Aliases: pendown | pd | down No argument. Example (for a Turtle instance named turtle): >>> turtle.pendown() """ if self._drawing: return self.pen(pendown=True) def isdown(self): """Return True if pen is down, False if it's up. No argument. Example (for a Turtle instance named turtle): >>> turtle.penup() >>> turtle.isdown() False >>> turtle.pendown() >>> turtle.isdown() True """ return self._drawing def speed(self, speed=None): """ Return or set the turtle's speed. Optional argument: speed -- an integer in the range 0..10 or a speedstring (see below) Set the turtle's speed to an integer value in the range 0 .. 10. If no argument is given: return current speed. If input is a number greater than 10 or smaller than 0.5, speed is set to 0. Speedstrings are mapped to speedvalues in the following way: 'fastest' : 0 'fast' : 10 'normal' : 6 'slow' : 3 'slowest' : 1 speeds from 1 to 10 enforce increasingly faster animation of line drawing and turtle turning. Attention: speed = 0 : *no* animation takes place. forward/back makes turtle jump and likewise left/right make the turtle turn instantly. Example (for a Turtle instance named turtle): >>> turtle.speed(3) """ speeds = {'fastest':0, 'fast':10, 'normal':6, 'slow':3, 'slowest':1 } if speed is None: return self._speed if speed in speeds: speed = speeds[speed] elif 0.5 < speed < 10.5: speed = int(round(speed)) else: speed = 0 self.pen(speed=speed) def color(self, *args): """Return or set the pencolor and fillcolor. Arguments: Several input formats are allowed. They use 0, 1, 2, or 3 arguments as follows: color() Return the current pencolor and the current fillcolor as a pair of color specification strings as are returned by pencolor and fillcolor. color(colorstring), color((r,g,b)), color(r,g,b) inputs as in pencolor, set both, fillcolor and pencolor, to the given value. color(colorstring1, colorstring2), color((r1,g1,b1), (r2,g2,b2)) equivalent to pencolor(colorstring1) and fillcolor(colorstring2) and analogously, if the other input format is used. If turtleshape is a polygon, outline and interior of that polygon is drawn with the newly set colors. For mor info see: pencolor, fillcolor Example (for a Turtle instance named turtle): >>> turtle.color('red', 'green') >>> turtle.color() ('red', 'green') >>> colormode(255) >>> color((40, 80, 120), (160, 200, 240)) >>> color() ('#285078', '#a0c8f0') """ if args: l = len(args) if l == 1: pcolor = fcolor = args[0] elif l == 2: pcolor, fcolor = args elif l == 3: pcolor = fcolor = args pcolor = self._colorstr(pcolor) fcolor = self._colorstr(fcolor) self.pen(pencolor=pcolor, fillcolor=fcolor) else: return self._color(self._pencolor), self._color(self._fillcolor) def pencolor(self, *args): """ Return or set the pencolor. Arguments: Four input formats are allowed: - pencolor() Return the current pencolor as color specification string, possibly in hex-number format (see example). May be used as input to another color/pencolor/fillcolor call. - pencolor(colorstring) s is a Tk color specification string, such as "red" or "yellow" - pencolor((r, g, b)) *a tuple* of r, g, and b, which represent, an RGB color, and each of r, g, and b are in the range 0..colormode, where colormode is either 1.0 or 255 - pencolor(r, g, b) r, g, and b represent an RGB color, and each of r, g, and b are in the range 0..colormode If turtleshape is a polygon, the outline of that polygon is drawn with the newly set pencolor. Example (for a Turtle instance named turtle): >>> turtle.pencolor('brown') >>> tup = (0.2, 0.8, 0.55) >>> turtle.pencolor(tup) >>> turtle.pencolor() '#33cc8c' """ if args: color = self._colorstr(args) if color == self._pencolor: return self.pen(pencolor=color) else: return self._color(self._pencolor) def fillcolor(self, *args): """ Return or set the fillcolor. Arguments: Four input formats are allowed: - fillcolor() Return the current fillcolor as color specification string, possibly in hex-number format (see example). May be used as input to another color/pencolor/fillcolor call. - fillcolor(colorstring) s is a Tk color specification string, such as "red" or "yellow" - fillcolor((r, g, b)) *a tuple* of r, g, and b, which represent, an RGB color, and each of r, g, and b are in the range 0..colormode, where colormode is either 1.0 or 255 - fillcolor(r, g, b) r, g, and b represent an RGB color, and each of r, g, and b are in the range 0..colormode If turtleshape is a polygon, the interior of that polygon is drawn with the newly set fillcolor. Example (for a Turtle instance named turtle): >>> turtle.fillcolor('violet') >>> col = turtle.pencolor() >>> turtle.fillcolor(col) >>> turtle.fillcolor(0, .5, 0) """ if args: color = self._colorstr(args) if color == self._fillcolor: return self.pen(fillcolor=color) else: return self._color(self._fillcolor) def showturtle(self): """Makes the turtle visible. Aliases: showturtle | st No argument. Example (for a Turtle instance named turtle): >>> turtle.hideturtle() >>> turtle.showturtle() """ self.pen(shown=True) def hideturtle(self): """Makes the turtle invisible. Aliases: hideturtle | ht No argument. It's a good idea to do this while you're in the middle of a complicated drawing, because hiding the turtle speeds up the drawing observably. Example (for a Turtle instance named turtle): >>> turtle.hideturtle() """ self.pen(shown=False) def isvisible(self): """Return True if the Turtle is shown, False if it's hidden. No argument. Example (for a Turtle instance named turtle): >>> turtle.hideturtle() >>> print turtle.isvisible(): False """ return self._shown def pen(self, pen=None, **pendict): """Return or set the pen's attributes. Arguments: pen -- a dictionary with some or all of the below listed keys. **pendict -- one or more keyword-arguments with the below listed keys as keywords. Return or set the pen's attributes in a 'pen-dictionary' with the following key/value pairs: "shown" : True/False "pendown" : True/False "pencolor" : color-string or color-tuple "fillcolor" : color-string or color-tuple "pensize" : positive number "speed" : number in range 0..10 "resizemode" : "auto" or "user" or "noresize" "stretchfactor": (positive number, positive number) "shearfactor": number "outline" : positive number "tilt" : number This dictionary can be used as argument for a subsequent pen()-call to restore the former pen-state. Moreover one or more of these attributes can be provided as keyword-arguments. This can be used to set several pen attributes in one statement. Examples (for a Turtle instance named turtle): >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10) >>> turtle.pen() {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1, 'pencolor': 'red', 'pendown': True, 'fillcolor': 'black', 'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0} >>> penstate=turtle.pen() >>> turtle.color("yellow","") >>> turtle.penup() >>> turtle.pen() {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1, 'pencolor': 'yellow', 'pendown': False, 'fillcolor': '', 'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0} >>> p.pen(penstate, fillcolor="green") >>> p.pen() {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1, 'pencolor': 'red', 'pendown': True, 'fillcolor': 'green', 'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0} """ _pd = {"shown" : self._shown, "pendown" : self._drawing, "pencolor" : self._pencolor, "fillcolor" : self._fillcolor, "pensize" : self._pensize, "speed" : self._speed, "resizemode" : self._resizemode, "stretchfactor" : self._stretchfactor, "shearfactor" : self._shearfactor, "outline" : self._outlinewidth, "tilt" : self._tilt } #console.log('pen') if not (pen or pendict): return _pd if isinstance(pen, dict): p = pen else: p = {} p.update(pendict) _p_buf = {} for key in p: _p_buf[key] = _pd[key] if self.undobuffer: self.undobuffer.push(("pen", _p_buf)) newLine = False if "pendown" in p: if self._drawing != p["pendown"]: newLine = True if "pencolor" in p: if isinstance(p["pencolor"], tuple): p["pencolor"] = self._colorstr((p["pencolor"],)) if self._pencolor != p["pencolor"]: newLine = True if "pensize" in p: if self._pensize != p["pensize"]: newLine = True if newLine: self._newLine() if "pendown" in p: self._drawing = p["pendown"] if "pencolor" in p: self._pencolor = p["pencolor"] if "pensize" in p: self._pensize = p["pensize"] if "fillcolor" in p: if isinstance(p["fillcolor"], tuple): p["fillcolor"] = self._colorstr((p["fillcolor"],)) self._fillcolor = p["fillcolor"] if "speed" in p: self._speed = p["speed"] if "resizemode" in p: self._resizemode = p["resizemode"] if "stretchfactor" in p: sf = p["stretchfactor"] if isinstance(sf, (int, float)): sf = (sf, sf) self._stretchfactor = sf if "shearfactor" in p: self._shearfactor = p["shearfactor"] if "outline" in p: self._outlinewidth = p["outline"] if "shown" in p: self._shown = p["shown"] if "tilt" in p: self._tilt = p["tilt"] if "stretchfactor" in p or "tilt" in p or "shearfactor" in p: scx, scy = self._stretchfactor shf = self._shearfactor sa, ca = math.sin(self._tilt), math.cos(self._tilt) self._shapetrafo = ( scx*ca, scy*(shf*ca + sa), -scx*sa, scy*(ca - shf*sa)) self._update() ## three dummy methods to be implemented by child class: def _newLine(self, usePos = True): """dummy method - to be overwritten by child class""" def _update(self, count=True, forced=False): """dummy method - to be overwritten by child class""" def _color(self, args): """dummy method - to be overwritten by child class""" def _colorstr(self, args): """dummy method - to be overwritten by child class""" width = pensize up = penup pu = penup pd = pendown down = pendown st = showturtle ht = hideturtle class _TurtleImage: """Helper class: Datatype to store Turtle attributes """ def __init__(self, screen, shapeIndex): self.screen = screen self._type = None self._setshape(shapeIndex) def _setshape(self, shapeIndex): #console.log("_setshape", self._type) screen = self.screen self.shapeIndex = shapeIndex if self._type == "polygon" == screen._shapes[shapeIndex]._type: return if self._type == "image" == screen._shapes[shapeIndex]._type: return if self._type in ["image", "polygon"]: screen._delete(self._item) elif self._type == "compound": for item in self._item: screen._delete(item) self._type = screen._shapes[shapeIndex]._type return #console.log(self._type) if self._type == "polygon": self._item = screen._createpoly() elif self._type == "image": self._item = screen._createimage(screen._shapes["blank"]._data) elif self._type == "compound": self._item = [screen._createpoly() for item in screen._shapes[shapeIndex]._data] #console.log(self._item) class RawTurtle(TPen, TNavigator): """Animation part of the RawTurtle. Puts RawTurtle upon a TurtleScreen and provides tools for its animation. """ screens = [] def __init__(self, canvas=None, shape=_CFG["shape"], undobuffersize=_CFG["undobuffersize"], visible=_CFG["visible"]): if isinstance(canvas, _Screen): self.screen = canvas elif isinstance(canvas, TurtleScreen): if canvas not in RawTurtle.screens: RawTurtle.screens.append(canvas) self.screen = canvas #elif isinstance(canvas, (ScrolledCanvas, Canvas)): # for screen in RawTurtle.screens: # if screen.cv == canvas: # self.screen = screen # break # else: # self.screen = TurtleScreen(canvas) # RawTurtle.screens.append(self.screen) else: raise TurtleGraphicsError("bad canvas argument %s" % canvas) screen = self.screen TNavigator.__init__(self, screen.mode()) TPen.__init__(self) screen._turtles.append(self) #self.drawingLineItem = screen._createline() self.turtle = _TurtleImage(screen, shape) self._poly = None self._creatingPoly = False self._fillitem = self._fillpath = None self._shown = visible self._hidden_from_screen = False #self.currentLineItem = screen._createline() self.currentLine = [self._position] #self.items = [] #[self.currentLineItem] self.stampItems = [] self._undobuffersize = undobuffersize self.undobuffer = None #Tbuffer(undobuffersize) #self._update() def reset(self): """Delete the turtle's drawings and restore its default values. No argument. Delete the turtle's drawings from the screen, re-center the turtle and set variables to the default values. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00,-22.00) >>> turtle.heading() 100.0 >>> turtle.reset() >>> turtle.position() (0.00,0.00) >>> turtle.heading() 0.0 """ TNavigator.reset(self) TPen._reset(self) self._clear() self._drawturtle() #self._update() def setundobuffer(self, size): """Set or disable undobuffer. Argument: size -- an integer or None If size is an integer an empty undobuffer of given size is installed. Size gives the maximum number of turtle-actions that can be undone by the undo() function. If size is None, no undobuffer is present. Example (for a Turtle instance named turtle): >>> turtle.setundobuffer(42) """ if size is None: self.undobuffer = None else: self.undobuffer = Tbuffer(size) def undobufferentries(self): """Return count of entries in the undobuffer. No argument. Example (for a Turtle instance named turtle): >>> while undobufferentries(): ... undo() """ if self.undobuffer is None: return 0 return self.undobuffer.nr_of_items() def _clear(self): """Delete all of pen's drawings""" self._fillitem = self._fillpath = None #for item in self.items: # self.screen._delete(item) #self.currentLineItem = #self.screen._createline() self.currentLine = [] if self._drawing: self.currentLine.append(self._position) #self.items = [self.currentLineItem] self.clearstamps() #self.setundobuffer(self._undobuffersize) def clear(self): """Delete the turtle's drawings from the screen. Do not move turtle. No arguments. Delete the turtle's drawings from the screen. Do not move turtle. State and position of the turtle as well as drawings of other turtles are not affected. Examples (for a Turtle instance named turtle): >>> turtle.clear() """ self._clear() #self._update() #def _update_data(self): # self.screen._incrementudc() # if self.screen._updatecounter != 0: # return # if len(self.currentLine)>1: # self.screen._drawline(self.currentLineItem, self.currentLine, # self._pencolor, self._pensize) def _update(self): """Perform a Turtle-data update. """ return screen = self.screen if screen._tracing == 0: return elif screen._tracing == 1: #self._update_data() self._drawturtle() #screen._update() # TurtleScreenBase #screen._delay(screen._delayvalue) # TurtleScreenBase else: #self._update_data() if screen._updatecounter == 0: for t in screen.turtles(): t._drawturtle() #screen._update() def _tracer(self, flag=None, delay=None): """Turns turtle animation on/off and set delay for update drawings. Optional arguments: n -- nonnegative integer delay -- nonnegative integer If n is given, only each n-th regular screen update is really performed. (Can be used to accelerate the drawing of complex graphics.) Second arguments sets delay value (see RawTurtle.delay()) Example (for a Turtle instance named turtle): >>> turtle.tracer(8, 25) >>> dist = 2 >>> for i in range(200): ... turtle.fd(dist) ... turtle.rt(90) ... dist += 2 """ return self.screen.tracer(flag, delay) def _color(self, args): return self.screen._color(args) def _colorstr(self, args): return self.screen._colorstr(args) def _cc(self, args): """Convert colortriples to hexstrings. """ if isinstance(args, str): return args try: r, g, b = args except: raise TurtleGraphicsError("bad color arguments: %s" % str(args)) if self.screen._colormode == 1.0: r, g, b = [round(255.0*x) for x in (r, g, b)] if not ((0 <= r <= 255) and (0 <= g <= 255) and (0 <= b <= 255)): raise TurtleGraphicsError("bad color sequence: %s" % str(args)) return "#%02x%02x%02x" % (r, g, b) def shape(self, name=None): """Set turtle shape to shape with given name / return current shapename. Optional argument: name -- a string, which is a valid shapename Set turtle shape to shape with given name or, if name is not given, return name of current shape. Shape with name must exist in the TurtleScreen's shape dictionary. Initially there are the following polygon shapes: 'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'. To learn about how to deal with shapes see Screen-method register_shape. Example (for a Turtle instance named turtle): >>> turtle.shape() 'arrow' >>> turtle.shape("turtle") >>> turtle.shape() 'turtle' """ if name is None: return self.turtle.shapeIndex if not name in self.screen.getshapes(): raise TurtleGraphicsError("There is no shape named %s" % name) self.turtle._setshape(name) #self._update() def shapesize(self, stretch_wid=None, stretch_len=None, outline=None): """Set/return turtle's stretchfactors/outline. Set resizemode to "user". Optional arguments: stretch_wid : positive number stretch_len : positive number outline : positive number Return or set the pen's attributes x/y-stretchfactors and/or outline. Set resizemode to "user". If and only if resizemode is set to "user", the turtle will be displayed stretched according to its stretchfactors: stretch_wid is stretchfactor perpendicular to orientation stretch_len is stretchfactor in direction of turtles orientation. outline determines the width of the shapes's outline. Examples (for a Turtle instance named turtle): >>> turtle.resizemode("user") >>> turtle.shapesize(5, 5, 12) >>> turtle.shapesize(outline=8) """ if stretch_wid is stretch_len is outline is None: stretch_wid, stretch_len = self._stretchfactor return stretch_wid, stretch_len, self._outlinewidth if stretch_wid == 0 or stretch_len == 0: raise TurtleGraphicsError("stretch_wid/stretch_len must not be zero") if stretch_wid is not None: if stretch_len is None: stretchfactor = stretch_wid, stretch_wid else: stretchfactor = stretch_wid, stretch_len elif stretch_len is not None: stretchfactor = self._stretchfactor[0], stretch_len else: stretchfactor = self._stretchfactor if outline is None: outline = self._outlinewidth self.pen(resizemode="user", stretchfactor=stretchfactor, outline=outline) def shearfactor(self, shear=None): """Set or return the current shearfactor. Optional argument: shear -- number, tangent of the shear angle Shear the turtleshape according to the given shearfactor shear, which is the tangent of the shear angle. DO NOT change the turtle's heading (direction of movement). If shear is not given: return the current shearfactor, i. e. the tangent of the shear angle, by which lines parallel to the heading of the turtle are sheared. Examples (for a Turtle instance named turtle): >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.shearfactor(0.5) >>> turtle.shearfactor() >>> 0.5 """ if shear is None: return self._shearfactor self.pen(resizemode="user", shearfactor=shear) def settiltangle(self, angle): """Rotate the turtleshape to point in the specified direction Argument: angle -- number Rotate the turtleshape to point in the direction specified by angle, regardless of its current tilt-angle. DO NOT change the turtle's heading (direction of movement). Examples (for a Turtle instance named turtle): >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.settiltangle(45) >>> stamp() >>> turtle.fd(50) >>> turtle.settiltangle(-45) >>> stamp() >>> turtle.fd(50) """ tilt = -angle * self._degreesPerAU * self._angleOrient tilt = (tilt * math.pi / 180.0) % (2*math.pi) self.pen(resizemode="user", tilt=tilt) def tiltangle(self, angle=None): """Set or return the current tilt-angle. Optional argument: angle -- number Rotate the turtleshape to point in the direction specified by angle, regardless of its current tilt-angle. DO NOT change the turtle's heading (direction of movement). If angle is not given: return the current tilt-angle, i. e. the angle between the orientation of the turtleshape and the heading of the turtle (its direction of movement). Deprecated since Python 3.1 Examples (for a Turtle instance named turtle): >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.tilt(45) >>> turtle.tiltangle() """ if angle is None: tilt = -self._tilt * (180.0/math.pi) * self._angleOrient return (tilt / self._degreesPerAU) % self._fullcircle else: self.settiltangle(angle) def tilt(self, angle): """Rotate the turtleshape by angle. Argument: angle - a number Rotate the turtleshape by angle from its current tilt-angle, but do NOT change the turtle's heading (direction of movement). Examples (for a Turtle instance named turtle): >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.tilt(30) >>> turtle.fd(50) >>> turtle.tilt(30) >>> turtle.fd(50) """ self.settiltangle(angle + self.tiltangle()) def shapetransform(self, t11=None, t12=None, t21=None, t22=None): """Set or return the current transformation matrix of the turtle shape. Optional arguments: t11, t12, t21, t22 -- numbers. If none of the matrix elements are given, return the transformation matrix. Otherwise set the given elements and transform the turtleshape according to the matrix consisting of first row t11, t12 and second row t21, 22. Modify stretchfactor, shearfactor and tiltangle according to the given matrix. Examples (for a Turtle instance named turtle): >>> turtle.shape("square") >>> turtle.shapesize(4,2) >>> turtle.shearfactor(-0.5) >>> turtle.shapetransform() (4.0, -1.0, -0.0, 2.0) """ #console.log("shapetransform") if t11 is t12 is t21 is t22 is None: return self._shapetrafo m11, m12, m21, m22 = self._shapetrafo if t11 is not None: m11 = t11 if t12 is not None: m12 = t12 if t21 is not None: m21 = t21 if t22 is not None: m22 = t22 if t11 * t22 - t12 * t21 == 0: raise TurtleGraphicsError("Bad shape transform matrix: must not be singular") self._shapetrafo = (m11, m12, m21, m22) alfa = math.atan2(-m21, m11) % (2 * math.pi) sa, ca = math.sin(alfa), math.cos(alfa) a11, a12, a21, a22 = (ca*m11 - sa*m21, ca*m12 - sa*m22, sa*m11 + ca*m21, sa*m12 + ca*m22) self._stretchfactor = a11, a22 self._shearfactor = a12/a22 self._tilt = alfa self._update() def _polytrafo(self, poly): """Computes transformed polygon shapes from a shape according to current position and heading. """ screen = self.screen p0, p1 = self._position e0, e1 = self._orient e = Vec2D(e0, e1 * screen.yscale / screen.xscale) e0, e1 = (1.0 / abs(e)) * e return [(p0+(e1*x+e0*y)/screen.xscale, p1+(-e0*x+e1*y)/screen.yscale) for (x, y) in poly] def get_shapepoly(self): """Return the current shape polygon as tuple of coordinate pairs. No argument. Examples (for a Turtle instance named turtle): >>> turtle.shape("square") >>> turtle.shapetransform(4, -1, 0, 2) >>> turtle.get_shapepoly() ((50, -20), (30, 20), (-50, 20), (-30, -20)) """ shape = self.screen._shapes[self.turtle.shapeIndex] if shape._type == "polygon": return self._getshapepoly(shape._data, shape._type == "compound") # else return None def _getshapepoly(self, polygon, compound=False): """Calculate transformed shape polygon according to resizemode and shapetransform. """ if self._resizemode == "user" or compound: t11, t12, t21, t22 = self._shapetrafo elif self._resizemode == "auto": l = max(1, self._pensize/5.0) t11, t12, t21, t22 = l, 0, 0, l elif self._resizemode == "noresize": return polygon return tuple([(t11*x + t12*y, t21*x + t22*y) for (x, y) in polygon]) def _drawturtle(self): """Manages the correct rendering of the turtle with respect to its shape, resizemode, stretch and tilt etc.""" return ############################## stamp stuff ############################### def stamp(self): """Stamp a copy of the turtleshape onto the canvas and return its id. No argument. Stamp a copy of the turtle shape onto the canvas at the current turtle position. Return a stamp_id for that stamp, which can be used to delete it by calling clearstamp(stamp_id). Example (for a Turtle instance named turtle): >>> turtle.color("blue") >>> turtle.stamp() 13 >>> turtle.fd(50) """ screen = self.screen shape = screen._shapes[self.turtle.shapeIndex] ttype = shape._type tshape = shape._data if ttype == "polygon": stitem = screen._createpoly() if self._resizemode == "noresize": w = 1 elif self._resizemode == "auto": w = self._pensize else: w =self._outlinewidth shape = self._polytrafo(self._getshapepoly(tshape)) fc, oc = self._fillcolor, self._pencolor screen._drawpoly(stitem, shape, fill=fc, outline=oc, width=w, top=True) elif ttype == "image": stitem = screen._createimage("") screen._drawimage(stitem, self._position, tshape) elif ttype == "compound": stitem = [] for element in tshape: item = screen._createpoly() stitem.append(item) stitem = tuple(stitem) for item, (poly, fc, oc) in zip(stitem, tshape): poly = self._polytrafo(self._getshapepoly(poly, True)) screen._drawpoly(item, poly, fill=self._cc(fc), outline=self._cc(oc), width=self._outlinewidth, top=True) self.stampItems.append(stitem) self.undobuffer.push(("stamp", stitem)) return stitem def _clearstamp(self, stampid): """does the work for clearstamp() and clearstamps() """ if stampid in self.stampItems: if isinstance(stampid, tuple): for subitem in stampid: self.screen._delete(subitem) else: self.screen._delete(stampid) self.stampItems.remove(stampid) # Delete stampitem from undobuffer if necessary # if clearstamp is called directly. item = ("stamp", stampid) buf = self.undobuffer if item not in buf.buffer: return index = buf.buffer.index(item) buf.buffer.remove(item) if index <= buf.ptr: buf.ptr = (buf.ptr - 1) % buf.bufsize buf.buffer.insert((buf.ptr+1)%buf.bufsize, [None]) def clearstamp(self, stampid): """Delete stamp with given stampid Argument: stampid - an integer, must be return value of previous stamp() call. Example (for a Turtle instance named turtle): >>> turtle.color("blue") >>> astamp = turtle.stamp() >>> turtle.fd(50) >>> turtle.clearstamp(astamp) """ self._clearstamp(stampid) self._update() def clearstamps(self, n=None): """Delete all or first/last n of turtle's stamps. Optional argument: n -- an integer If n is None, delete all of pen's stamps, else if n > 0 delete first n stamps else if n < 0 delete last n stamps. Example (for a Turtle instance named turtle): >>> for i in range(8): ... turtle.stamp(); turtle.fd(30) ... >>> turtle.clearstamps(2) >>> turtle.clearstamps(-2) >>> turtle.clearstamps() """ if n is None: toDelete = self.stampItems[:] elif n >= 0: toDelete = self.stampItems[:n] else: toDelete = self.stampItems[n:] for item in toDelete: self._clearstamp(item) self._update() def _goto(self, end): """Move the pen to the point end, thereby drawing a line if pen is down. All other methods for turtle movement depend on this one. """ if self._speed and self.screen._tracing == 1: if self._drawing: #console.log('%s:%s:%s:%s:%s' % (self, start, end, self._pencolor, # self._pensize)) self.screen._drawline(self, #please remove me eventually (self._position, end), self._pencolor, self._pensize, False) if isinstance(self._fillpath, list): self._fillpath.append(end) ###### vererbung!!!!!!!!!!!!!!!!!!!!!! self._position = end def _rotate(self, angle): """Turns pen clockwise by angle. """ #console.log('_rotate') if self.undobuffer: self.undobuffer.push(("rot", angle, self._degreesPerAU)) angle *= self._degreesPerAU neworient = self._orient.rotate(angle) tracing = self.screen._tracing self._orient = neworient #self._update() def _newLine(self, usePos=True): """Closes current line item and starts a new one. Remark: if current line became too long, animation performance (via _drawline) slowed down considerably. """ #console.log('_newLine') return def filling(self): """Return fillstate (True if filling, False else). No argument. Example (for a Turtle instance named turtle): >>> turtle.begin_fill() >>> if turtle.filling(): ... turtle.pensize(5) ... else: ... turtle.pensize(3) """ return isinstance(self._fillpath, list) def begin_fill(self): """Called just before drawing a shape to be filled. No argument. Example (for a Turtle instance named turtle): >>> turtle.color("black", "red") >>> turtle.begin_fill() >>> turtle.circle(60) >>> turtle.end_fill() """ if not self.filling(): self._fillitem = self.screen._createpoly() #self.items.append(self._fillitem) self._fillpath = [self._position] #self._newLine() if self.undobuffer: self.undobuffer.push(("beginfill", self._fillitem)) #self._update() def end_fill(self): """Fill the shape drawn after the call begin_fill(). No argument. Example (for a Turtle instance named turtle): >>> turtle.color("black", "red") >>> turtle.begin_fill() >>> turtle.circle(60) >>> turtle.end_fill() """ if self.filling(): if len(self._fillpath) > 2: self.screen._drawpoly(self._fillitem, self._fillpath, fill=self._fillcolor) if self.undobuffer: self.undobuffer.push(("dofill", self._fillitem)) self._fillitem = self._fillpath = None self._update() def dot(self, size=None, *color): """Draw a dot with diameter size, using color. Optional arguments: size -- an integer >= 1 (if given) color -- a colorstring or a numeric color tuple Draw a circular dot with diameter size, using color. If size is not given, the maximum of pensize+4 and 2*pensize is used. Example (for a Turtle instance named turtle): >>> turtle.dot() >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50) """ if not color: if isinstance(size, (str, tuple)): color = self._colorstr(size) size = self._pensize + max(self._pensize, 4) else: color = self._pencolor if not size: size = self._pensize + max(self._pensize, 4) else: if size is None: size = self._pensize + max(self._pensize, 4) color = self._colorstr(color) if hasattr(self.screen, "_dot"): item = self.screen._dot(self._position, size, color) #self.items.append(item) if self.undobuffer: self.undobuffer.push(("dot", item)) else: pen = self.pen() if self.undobuffer: self.undobuffer.push(["seq"]) self.undobuffer.cumulate = True try: if self.resizemode() == 'auto': self.ht() self.pendown() self.pensize(size) self.pencolor(color) self.forward(0) finally: self.pen(pen) if self.undobuffer: self.undobuffer.cumulate = False def _write(self, txt, align, font): """Performs the writing for write() """ item, end = self.screen._write(self._position, txt, align, font, self._pencolor) #self.items.append(item) if self.undobuffer: self.undobuffer.push(("wri", item)) return end def write(self, arg, move=False, align="left", font=("Arial", 8, "normal")): """Write text at the current turtle position. Arguments: arg -- info, which is to be written to the TurtleScreen move (optional) -- True/False align (optional) -- one of the strings "left", "center" or right" font (optional) -- a triple (fontname, fontsize, fonttype) Write text - the string representation of arg - at the current turtle position according to align ("left", "center" or right") and with the given font. If move is True, the pen is moved to the bottom-right corner of the text. By default, move is False. Example (for a Turtle instance named turtle): >>> turtle.write('Home = ', True, align="center") >>> turtle.write((0,0), True) """ if self.undobuffer: self.undobuffer.push(["seq"]) self.undobuffer.cumulate = True end = self._write(str(arg), align.lower(), font) if move: x, y = self.pos() self.setpos(end, y) if self.undobuffer: self.undobuffer.cumulate = False def begin_poly(self): """Start recording the vertices of a polygon. No argument. Start recording the vertices of a polygon. Current turtle position is first point of polygon. Example (for a Turtle instance named turtle): >>> turtle.begin_poly() """ self._poly = [self._position] self._creatingPoly = True def end_poly(self): """Stop recording the vertices of a polygon. No argument. Stop recording the vertices of a polygon. Current turtle position is last point of polygon. This will be connected with the first point. Example (for a Turtle instance named turtle): >>> turtle.end_poly() """ self._creatingPoly = False def get_poly(self): """Return the lastly recorded polygon. No argument. Example (for a Turtle instance named turtle): >>> p = turtle.get_poly() >>> turtle.register_shape("myFavouriteShape", p) """ ## check if there is any poly? if self._poly is not None: return tuple(self._poly) def getscreen(self): """Return the TurtleScreen object, the turtle is drawing on. No argument. Return the TurtleScreen object, the turtle is drawing on. So TurtleScreen-methods can be called for that object. Example (for a Turtle instance named turtle): >>> ts = turtle.getscreen() >>> ts <turtle.TurtleScreen object at 0x0106B770> >>> ts.bgcolor("pink") """ return self.screen def getturtle(self): """Return the Turtleobject itself. No argument. Only reasonable use: as a function to return the 'anonymous turtle': Example: >>> pet = getturtle() >>> pet.fd(50) >>> pet <turtle.Turtle object at 0x0187D810> >>> turtles() [<turtle.Turtle object at 0x0187D810>] """ return self getpen = getturtle ################################################################ ### screen oriented methods recurring to methods of TurtleScreen ################################################################ def _delay(self, delay=None): """Set delay value which determines speed of turtle animation. """ return self.screen.delay(delay) turtlesize = shapesize RawPen = RawTurtle ### Screen - Singleton ######################## def Screen(): """Return the singleton screen object. If none exists at the moment, create a new one and return it, else return the existing one.""" if Turtle._screen is None: Turtle._screen = _Screen() return Turtle._screen class _Screen(TurtleScreen): _root = None _canvas = None _title = _CFG["title"] def __init__(self): # XXX there is no need for this code to be conditional, # as there will be only a single _Screen instance, anyway # XXX actually, the turtle demo is injecting root window, # so perhaps the conditional creation of a root should be # preserved (perhaps by passing it as an optional parameter) if _Screen._root is None: _Screen._root = self._root = _Root() #self._root.title(_Screen._title) #self._root.ondestroy(self._destroy) if _Screen._canvas is None: width = _CFG["width"] height = _CFG["height"] canvwidth = _CFG["canvwidth"] canvheight = _CFG["canvheight"] leftright = _CFG["leftright"] topbottom = _CFG["topbottom"] self._root.setupcanvas(width, height, canvwidth, canvheight) _Screen._canvas = self._root._getcanvas() TurtleScreen.__init__(self, _Screen._canvas) self.setup(width, height, leftright, topbottom) def end(self): self._root.end() def setup(self, width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"]): """ Set the size and position of the main window. Arguments: width: as integer a size in pixels, as float a fraction of the screen. Default is 50% of screen. height: as integer the height in pixels, as float a fraction of the screen. Default is 75% of screen. startx: if positive, starting position in pixels from the left edge of the screen, if negative from the right edge Default, startx=None is to center window horizontally. starty: if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge Default, starty=None is to center window vertically. Examples (for a Screen instance named screen): >>> screen.setup (width=200, height=200, startx=0, starty=0) sets window to 200x200 pixels, in upper left of screen >>> screen.setup(width=.75, height=0.5, startx=None, starty=None) sets window to 75% of screen by 50% of screen and centers """ if not hasattr(self._root, "set_geometry"): return sw = self._root.win_width() sh = self._root.win_height() if isinstance(width, float) and 0 <= width <= 1: width = sw*width if startx is None: startx = (sw - width) / 2 if isinstance(height, float) and 0 <= height <= 1: height = sh*height if starty is None: starty = (sh - height) / 2 self._root.set_geometry(width, height, startx, starty) self.update() class Turtle(RawTurtle): """RawTurtle auto-creating (scrolled) canvas. When a Turtle object is created or a function derived from some Turtle method is called a TurtleScreen object is automatically created. """ _pen = None _screen = None def __init__(self, shape=_CFG["shape"], undobuffersize=_CFG["undobuffersize"], visible=_CFG["visible"]): if Turtle._screen is None: Turtle._screen = Screen() RawTurtle.__init__(self, Turtle._screen, shape=shape, undobuffersize=undobuffersize, visible=visible) Pen = Turtle def _getpen(): """Create the 'anonymous' turtle if not already present.""" if Turtle._pen is None: Turtle._pen = Turtle() return Turtle._pen def _getscreen(): """Create a TurtleScreen if not already present.""" if Turtle._screen is None: Turtle._screen = Screen() return Turtle._screen if __name__ == "__main__": def switchpen(): if isdown(): pu() else: pd() def demo1(): """Demo of old turtle.py - module""" reset() tracer(True) up() backward(100) down() # draw 3 squares; the last filled width(3) for i in range(3): if i == 2: begin_fill() for _ in range(4): forward(20) left(90) if i == 2: color("maroon") end_fill() up() forward(30) down() width(1) color("black") # move out of the way tracer(False) up() right(90) forward(100) right(90) forward(100) right(180) down() # some text write("startstart", 1) write("start", 1) color("red") # staircase for i in range(5): forward(20) left(90) forward(20) right(90) # filled staircase tracer(True) begin_fill() for i in range(5): forward(20) left(90) forward(20) right(90) end_fill() # more text def demo2(): """Demo of some new features.""" speed(1) st() pensize(3) setheading(towards(0, 0)) radius = distance(0, 0)/2.0 rt(90) for _ in range(18): switchpen() circle(radius, 10) write("wait a moment...") while undobufferentries(): undo() reset() lt(90) colormode(255) laenge = 10 pencolor("green") pensize(3) lt(180) for i in range(-2, 16): if i > 0: begin_fill() fillcolor(255-15*i, 0, 15*i) for _ in range(3): fd(laenge) lt(120) end_fill() laenge += 10 lt(15) speed((speed()+1)%12) #end_fill() lt(120) pu() fd(70) rt(30) pd() color("red","yellow") speed(0) begin_fill() for _ in range(4): circle(50, 90) rt(90) fd(30) rt(90) end_fill() lt(90) pu() fd(30) pd() shape("turtle") tri = getturtle() tri.resizemode("auto") turtle = Turtle() turtle.resizemode("auto") turtle.shape("turtle") turtle.reset() turtle.left(90) turtle.speed(0) turtle.up() turtle.goto(280, 40) turtle.lt(30) turtle.down() turtle.speed(6) turtle.color("blue","orange") turtle.pensize(2) tri.speed(6) setheading(towards(turtle)) count = 1 while tri.distance(turtle) > 4: turtle.fd(3.5) turtle.lt(0.6) tri.setheading(tri.towards(turtle)) tri.fd(4) if count % 20 == 0: turtle.stamp() tri.stamp() switchpen() count += 1 tri.write("CAUGHT! ", font=("Arial", 16, "bold"), align="right") tri.pencolor("black") tri.pencolor("red") def baba(xdummy, ydummy): clearscreen() bye() time.sleep(2) while undobufferentries(): tri.undo() turtle.undo() tri.fd(50) tri.write(" Click me!", font = ("Courier", 12, "bold") ) tri.onclick(baba, 1) demo1() demo2() exitonclick()
blackzw/openwrt_sdk_dev1
refs/heads/master
staging_dir/host/lib/python2.7/idlelib/ZoomHeight.py
150
# Sample extension: zoom a window to maximum height import re import sys from idlelib import macosxSupport class ZoomHeight: menudefs = [ ('windows', [ ('_Zoom Height', '<<zoom-height>>'), ]) ] def __init__(self, editwin): self.editwin = editwin def zoom_height_event(self, event): top = self.editwin.top zoom_height(top) def zoom_height(top): geom = top.wm_geometry() m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom) if not m: top.bell() return width, height, x, y = map(int, m.groups()) newheight = top.winfo_screenheight() if sys.platform == 'win32': newy = 0 newheight = newheight - 72 elif macosxSupport.runningAsOSXApp(): # The '88' below is a magic number that avoids placing the bottom # of the window below the panel on my machine. I don't know how # to calculate the correct value for this with tkinter. newy = 22 newheight = newheight - newy - 88 else: #newy = 24 newy = 0 #newheight = newheight - 96 newheight = newheight - 88 if height >= newheight: newgeom = "" else: newgeom = "%dx%d+%d+%d" % (width, newheight, x, newy) top.wm_geometry(newgeom)
mattcaldwell/django-denorm
refs/heads/master
denorm/migrations/__init__.py
12133432
UXE/local-edx
refs/heads/master
lms/urls.py
2
from django.conf import settings from django.conf.urls import patterns, include, url from ratelimitbackend import admin from django.conf.urls.static import static import django.contrib.auth.views from microsite_configuration import microsite # Uncomment the next two lines to enable the admin: if settings.DEBUG or settings.FEATURES.get('ENABLE_DJANGO_ADMIN_SITE'): admin.autodiscover() urlpatterns = ('', # nopep8 # certificate view url(r'^update_certificate$', 'certificates.views.update_certificate'), url(r'^request_certificate$', 'certificates.views.request_certificate'), url(r'^$', 'branding.views.index', name="root"), # Main marketing page, or redirect to courseware url(r'^dashboard$', 'student.views.dashboard', name="dashboard"), url(r'^login_ajax$', 'student.views.login_user', name="login"), url(r'^login_ajax/(?P<error>[^/]*)$', 'student.views.login_user'), url(r'^login$', 'student.views.signin_user', name="signin_user"), url(r'^register$', 'student.views.register_user', name="register_user"), url(r'^admin_dashboard$', 'dashboard.views.dashboard'), url(r'^change_email$', 'student.views.change_email_request', name="change_email"), url(r'^email_confirm/(?P<key>[^/]*)$', 'student.views.confirm_email_change'), url(r'^change_name$', 'student.views.change_name_request', name="change_name"), url(r'^accept_name_change$', 'student.views.accept_name_change'), url(r'^reject_name_change$', 'student.views.reject_name_change'), url(r'^pending_name_changes$', 'student.views.pending_name_changes'), url(r'^event$', 'track.views.user_track'), url(r'^segmentio/event$', 'track.views.segmentio.segmentio_event'), url(r'^t/(?P<template>[^/]*)$', 'static_template_view.views.index'), # TODO: Is this used anymore? What is STATIC_GRAB? url(r'^accounts/login$', 'student.views.accounts_login', name="accounts_login"), url(r'^accounts/manage_user_standing', 'student.views.manage_user_standing', name='manage_user_standing'), url(r'^accounts/disable_account_ajax$', 'student.views.disable_account_ajax', name="disable_account_ajax"), url(r'^logout$', 'student.views.logout_user', name='logout'), url(r'^create_account$', 'student.views.create_account', name='create_account'), url(r'^activate/(?P<key>[^/]*)$', 'student.views.activate_account', name="activate"), url(r'^password_reset/$', 'student.views.password_reset', name='password_reset'), ## Obsolete Django views for password resets ## TODO: Replace with Mako-ized views url(r'^password_change/$', django.contrib.auth.views.password_change, name='auth_password_change'), url(r'^password_change_done/$', django.contrib.auth.views.password_change_done, name='auth_password_change_done'), url(r'^password_reset_confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'student.views.password_reset_confirm_wrapper', name='auth_password_reset_confirm'), url(r'^password_reset_complete/$', django.contrib.auth.views.password_reset_complete, name='auth_password_reset_complete'), url(r'^password_reset_done/$', django.contrib.auth.views.password_reset_done, name='auth_password_reset_done'), url(r'^heartbeat$', include('heartbeat.urls')), url(r'^user_api/', include('openedx.core.djangoapps.user_api.urls')), url(r'^notifier_api/', include('notifier_api.urls')), url(r'^lang_pref/', include('lang_pref.urls')), url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^embargo$', 'student.views.embargo', name="embargo"), # Feedback Form endpoint url(r'^submit_feedback$', 'util.views.submit_feedback'), # Enrollment API RESTful endpoints url(r'^enrollment/v0/', include('enrollment.urls')), ) if settings.FEATURES["ENABLE_MOBILE_REST_API"]: urlpatterns += ( url(r'^api/mobile/v0.5/', include('mobile_api.urls')), # Video Abstraction Layer used to allow video teams to manage video assets # independently of courseware. https://github.com/edx/edx-val url(r'^api/val/v0/', include('edxval.urls')), ) # if settings.FEATURES.get("MULTIPLE_ENROLLMENT_ROLES"): urlpatterns += ( url(r'^verify_student/', include('verify_student.urls')), url(r'^course_modes/', include('course_modes.urls')), ) js_info_dict = { 'domain': 'djangojs', # We need to explicitly include external Django apps that are not in LOCALE_PATHS. 'packages': ('openassessment',), } urlpatterns += ( # Serve catalog of localized strings to be rendered by Javascript url(r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict), ) # sysadmin dashboard, to see what courses are loaded, to delete & load courses if settings.FEATURES["ENABLE_SYSADMIN_DASHBOARD"]: urlpatterns += ( url(r'^sysadmin/', include('dashboard.sysadmin_urls')), ) urlpatterns += ( url(r'^support/', include('dashboard.support_urls')), ) #Semi-static views (these need to be rendered and have the login bar, but don't change) urlpatterns += ( url(r'^404$', 'static_template_view.views.render', {'template': '404.html'}, name="404"), ) # Favicon favicon_path = microsite.get_value('favicon_path', settings.FAVICON_PATH) urlpatterns += (( r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': settings.STATIC_URL + favicon_path} ),) # Semi-static views only used by edX, not by themes if not settings.FEATURES["USE_CUSTOM_THEME"]: urlpatterns += ( url(r'^blog$', 'static_template_view.views.render', {'template': 'blog.html'}, name="blog"), url(r'^contact$', 'static_template_view.views.render', {'template': 'contact.html'}, name="contact"), url(r'^donate$', 'static_template_view.views.render', {'template': 'donate.html'}, name="donate"), url(r'^faq$', 'static_template_view.views.render', {'template': 'faq.html'}, name="faq"), url(r'^help$', 'static_template_view.views.render', {'template': 'help.html'}, name="help_edx"), url(r'^jobs$', 'static_template_view.views.render', {'template': 'jobs.html'}, name="jobs"), url(r'^news$', 'static_template_view.views.render', {'template': 'news.html'}, name="news"), url(r'^press$', 'static_template_view.views.render', {'template': 'press.html'}, name="press"), url(r'^media-kit$', 'static_template_view.views.render', {'template': 'media-kit.html'}, name="media-kit"), # TODO: (bridger) The copyright has been removed until it is updated for edX # url(r'^copyright$', 'static_template_view.views.render', # {'template': 'copyright.html'}, name="copyright"), # Press releases url(r'^press/([_a-zA-Z0-9-]+)$', 'static_template_view.views.render_press_release', name='press_release'), ) # Only enable URLs for those marketing links actually enabled in the # settings. Disable URLs by marking them as None. for key, value in settings.MKTG_URL_LINK_MAP.items(): # Skip disabled URLs if value is None: continue # These urls are enabled separately if key == "ROOT" or key == "COURSES": continue # Make the assumptions that the templates are all in the same dir # and that they all match the name of the key (plus extension) template = "%s.html" % key.lower() # To allow theme templates to inherit from default templates, # prepend a standard prefix if settings.FEATURES["USE_CUSTOM_THEME"]: template = "theme-" + template # Make the assumption that the URL we want is the lowercased # version of the map key urlpatterns += (url(r'^%s$' % key.lower(), 'static_template_view.views.render', {'template': template}, name=value),) # Multicourse wiki (Note: wiki urls must be above the courseware ones because of # the custom tab catch-all) if settings.WIKI_ENABLED: from wiki.urls import get_pattern as wiki_pattern from django_notify.urls import get_pattern as notify_pattern urlpatterns += ( # First we include views from course_wiki that we use to override the default views. # They come first in the urlpatterns so they get resolved first url('^wiki/create-root/$', 'course_wiki.views.root_create', name='root_create'), url(r'^wiki/', include(wiki_pattern())), url(r'^notify/', include(notify_pattern())), # These urls are for viewing the wiki in the context of a course. They should # never be returned by a reverse() so they come after the other url patterns url(r'^courses/{}/course_wiki/?$'.format(settings.COURSE_ID_PATTERN), 'course_wiki.views.course_wiki_redirect', name="course_wiki"), url(r'^courses/{}/wiki/'.format(settings.COURSE_KEY_REGEX), include(wiki_pattern())), ) if settings.COURSEWARE_ENABLED: urlpatterns += ( url(r'^courses/{}/jump_to/(?P<location>.*)$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.jump_to', name="jump_to"), url(r'^courses/{}/jump_to_id/(?P<module_id>.*)$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.jump_to_id', name="jump_to_id"), url(r'^courses/{course_key}/xblock/{usage_key}/handler/(?P<handler>[^/]*)(?:/(?P<suffix>.*))?$'.format(course_key=settings.COURSE_ID_PATTERN, usage_key=settings.USAGE_ID_PATTERN), 'courseware.module_render.handle_xblock_callback', name='xblock_handler'), url(r'^courses/{course_key}/xblock/{usage_key}/handler_noauth/(?P<handler>[^/]*)(?:/(?P<suffix>.*))?$'.format(course_key=settings.COURSE_ID_PATTERN, usage_key=settings.USAGE_ID_PATTERN), 'courseware.module_render.handle_xblock_callback_noauth', name='xblock_handler_noauth'), url(r'xblock/resource/(?P<block_type>[^/]+)/(?P<uri>.*)$', 'courseware.module_render.xblock_resource', name='xblock_resource_url'), # Software Licenses # TODO: for now, this is the endpoint of an ajax replay # service that retrieve and assigns license numbers for # software assigned to a course. The numbers have to be loaded # into the database. url(r'^software-licenses$', 'licenses.views.user_software_license', name="user_software_license"), url(r'^courses/{}/xqueue/(?P<userid>[^/]*)/(?P<mod_id>.*?)/(?P<dispatch>[^/]*)$'.format(settings.COURSE_ID_PATTERN), 'courseware.module_render.xqueue_callback', name='xqueue_callback'), url(r'^change_setting$', 'student.views.change_setting', name='change_setting'), # TODO: These views need to be updated before they work url(r'^calculate$', 'util.views.calculate'), # TODO: We should probably remove the circuit package. I believe it was only used in the old way of saving wiki circuits for the wiki # url(r'^edit_circuit/(?P<circuit>[^/]*)$', 'circuit.views.edit_circuit'), # url(r'^save_circuit/(?P<circuit>[^/]*)$', 'circuit.views.save_circuit'), url(r'^courses/?$', 'branding.views.courses', name="courses"), url(r'^change_enrollment$', 'student.views.change_enrollment', name="change_enrollment"), url(r'^change_email_settings$', 'student.views.change_email_settings', name="change_email_settings"), #About the course url(r'^courses/{}/about$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.course_about', name="about_course"), #View for mktg site (kept for backwards compatibility TODO - remove before merge to master) url(r'^courses/{}/mktg-about$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.mktg_course_about', name="mktg_about_course"), #View for mktg site url(r'^mktg/{}/?$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.mktg_course_about', name="mktg_about_course"), #Inside the course url(r'^courses/{}/$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.course_info', name="course_root"), url(r'^courses/{}/info$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.course_info', name="info"), url(r'^courses/{}/syllabus$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.syllabus', name="syllabus"), # TODO arjun remove when custom tabs in place, see courseware/courses.py #Survey associated with a course url(r'^courses/{}/survey$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.course_survey', name="course_survey"), url(r'^courses/{}/book/(?P<book_index>\d+)/$'.format(settings.COURSE_ID_PATTERN), 'staticbook.views.index', name="book"), url(r'^courses/{}/book/(?P<book_index>\d+)/(?P<page>\d+)$'.format(settings.COURSE_ID_PATTERN), 'staticbook.views.index', name="book"), url(r'^courses/{}/pdfbook/(?P<book_index>\d+)/$'.format(settings.COURSE_ID_PATTERN), 'staticbook.views.pdf_index', name="pdf_book"), url(r'^courses/{}/pdfbook/(?P<book_index>\d+)/(?P<page>\d+)$'.format(settings.COURSE_ID_PATTERN), 'staticbook.views.pdf_index', name="pdf_book"), url(r'^courses/{}/pdfbook/(?P<book_index>\d+)/chapter/(?P<chapter>\d+)/$'.format(settings.COURSE_ID_PATTERN), 'staticbook.views.pdf_index', name="pdf_book"), url(r'^courses/{}/pdfbook/(?P<book_index>\d+)/chapter/(?P<chapter>\d+)/(?P<page>\d+)$'.format(settings.COURSE_ID_PATTERN), 'staticbook.views.pdf_index', name="pdf_book"), url(r'^courses/{}/htmlbook/(?P<book_index>\d+)/$'.format(settings.COURSE_ID_PATTERN), 'staticbook.views.html_index', name="html_book"), url(r'^courses/{}/htmlbook/(?P<book_index>\d+)/chapter/(?P<chapter>\d+)/$'.format(settings.COURSE_ID_PATTERN), 'staticbook.views.html_index', name="html_book"), url(r'^courses/{}/courseware/?$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.index', name="courseware"), url(r'^courses/{}/courseware/(?P<chapter>[^/]*)/$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.index', name="courseware_chapter"), url(r'^courses/{}/courseware/(?P<chapter>[^/]*)/(?P<section>[^/]*)/$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.index', name="courseware_section"), url(r'^courses/{}/courseware/(?P<chapter>[^/]*)/(?P<section>[^/]*)/(?P<position>[^/]*)/?$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.index', name="courseware_position"), url(r'^courses/{}/progress$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.progress', name="progress"), # Takes optional student_id for instructor use--shows profile as that student sees it. url(r'^courses/{}/progress/(?P<student_id>[^/]*)/$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.progress', name="student_progress"), # For the instructor url(r'^courses/{}/instructor$'.format(settings.COURSE_ID_PATTERN), 'instructor.views.instructor_dashboard.instructor_dashboard_2', name="instructor_dashboard"), url(r'^courses/{}/set_course_mode_price$'.format(settings.COURSE_ID_PATTERN), 'instructor.views.instructor_dashboard.set_course_mode_price', name="set_course_mode_price"), url(r'^courses/{}/instructor/api/'.format(settings.COURSE_ID_PATTERN), include('instructor.views.api_urls')), url(r'^courses/{}/remove_coupon$'.format(settings.COURSE_ID_PATTERN), 'instructor.views.coupons.remove_coupon', name="remove_coupon"), url(r'^courses/{}/add_coupon$'.format(settings.COURSE_ID_PATTERN), 'instructor.views.coupons.add_coupon', name="add_coupon"), url(r'^courses/{}/update_coupon$'.format(settings.COURSE_ID_PATTERN), 'instructor.views.coupons.update_coupon', name="update_coupon"), url(r'^courses/{}/get_coupon_info$'.format(settings.COURSE_ID_PATTERN), 'instructor.views.coupons.get_coupon_info', name="get_coupon_info"), # see ENABLE_INSTRUCTOR_LEGACY_DASHBOARD section for legacy dash urls # Open Ended grading views url(r'^courses/{}/staff_grading$'.format(settings.COURSE_ID_PATTERN), 'open_ended_grading.views.staff_grading', name='staff_grading'), url(r'^courses/{}/staff_grading/get_next$'.format(settings.COURSE_ID_PATTERN), 'open_ended_grading.staff_grading_service.get_next', name='staff_grading_get_next'), url(r'^courses/{}/staff_grading/save_grade$'.format(settings.COURSE_ID_PATTERN), 'open_ended_grading.staff_grading_service.save_grade', name='staff_grading_save_grade'), url(r'^courses/{}/staff_grading/get_problem_list$'.format(settings.COURSE_ID_PATTERN), 'open_ended_grading.staff_grading_service.get_problem_list', name='staff_grading_get_problem_list'), # Open Ended problem list url(r'^courses/{}/open_ended_problems$'.format(settings.COURSE_ID_PATTERN), 'open_ended_grading.views.student_problem_list', name='open_ended_problems'), # Open Ended flagged problem list url(r'^courses/{}/open_ended_flagged_problems$'.format(settings.COURSE_ID_PATTERN), 'open_ended_grading.views.flagged_problem_list', name='open_ended_flagged_problems'), url(r'^courses/{}/open_ended_flagged_problems/take_action_on_flags$'.format(settings.COURSE_ID_PATTERN), 'open_ended_grading.views.take_action_on_flags', name='open_ended_flagged_problems_take_action'), # Cohorts management url(r'^courses/{}/cohorts$'.format(settings.COURSE_KEY_PATTERN), 'openedx.core.djangoapps.course_groups.views.list_cohorts', name="cohorts"), url(r'^courses/{}/cohorts/add$'.format(settings.COURSE_KEY_PATTERN), 'openedx.core.djangoapps.course_groups.views.add_cohort', name="add_cohort"), url(r'^courses/{}/cohorts/(?P<cohort_id>[0-9]+)$'.format(settings.COURSE_KEY_PATTERN), 'openedx.core.djangoapps.course_groups.views.users_in_cohort', name="list_cohort"), url(r'^courses/{}/cohorts/(?P<cohort_id>[0-9]+)/add$'.format(settings.COURSE_KEY_PATTERN), 'openedx.core.djangoapps.course_groups.views.add_users_to_cohort', name="add_to_cohort"), url(r'^courses/{}/cohorts/(?P<cohort_id>[0-9]+)/delete$'.format(settings.COURSE_KEY_PATTERN), 'openedx.core.djangoapps.course_groups.views.remove_user_from_cohort', name="remove_from_cohort"), url(r'^courses/{}/cohorts/debug$'.format(settings.COURSE_KEY_PATTERN), 'openedx.core.djangoapps.course_groups.views.debug_cohort_mgmt', name="debug_cohort_mgmt"), # Open Ended Notifications url(r'^courses/{}/open_ended_notifications$'.format(settings.COURSE_ID_PATTERN), 'open_ended_grading.views.combined_notifications', name='open_ended_notifications'), url(r'^courses/{}/peer_grading$'.format(settings.COURSE_ID_PATTERN), 'open_ended_grading.views.peer_grading', name='peer_grading'), url(r'^courses/{}/notes$'.format(settings.COURSE_ID_PATTERN), 'notes.views.notes', name='notes'), url(r'^courses/{}/notes/'.format(settings.COURSE_ID_PATTERN), include('notes.urls')), # LTI endpoints listing url(r'^courses/{}/lti_rest_endpoints/'.format(settings.COURSE_ID_PATTERN), 'courseware.views.get_course_lti_endpoints', name='lti_rest_endpoints'), # Student account and profile url(r'^account/', include('student_account.urls')), url(r'^profile/', include('student_profile.urls')), ) # allow course staff to change to student view of courseware if settings.FEATURES.get('ENABLE_MASQUERADE'): urlpatterns += ( url(r'^masquerade/(?P<marg>.*)$', 'courseware.masquerade.handle_ajax', name="masquerade-switch"), ) # discussion forums live within courseware, so courseware must be enabled first if settings.FEATURES.get('ENABLE_DISCUSSION_SERVICE'): urlpatterns += ( url(r'^courses/{}/discussion/'.format(settings.COURSE_ID_PATTERN), include('django_comment_client.urls')), url(r'^notification_prefs/enable/', 'notification_prefs.views.ajax_enable'), url(r'^notification_prefs/disable/', 'notification_prefs.views.ajax_disable'), url(r'^notification_prefs/status/', 'notification_prefs.views.ajax_status'), url(r'^notification_prefs/unsubscribe/(?P<token>[a-zA-Z0-9-_=]+)/', 'notification_prefs.views.set_subscription', {'subscribe': False}, name="unsubscribe_forum_update"), url(r'^notification_prefs/resubscribe/(?P<token>[a-zA-Z0-9-_=]+)/', 'notification_prefs.views.set_subscription', {'subscribe': True}, name="resubscribe_forum_update"), ) urlpatterns += ( # This MUST be the last view in the courseware--it's a catch-all for custom tabs. url(r'^courses/{}/(?P<tab_slug>[^/]+)/$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.static_tab', name="static_tab"), ) if settings.FEATURES.get('ENABLE_STUDENT_HISTORY_VIEW'): urlpatterns += ( url(r'^courses/{}/submission_history/(?P<student_username>[^/]*)/(?P<location>.*?)$'.format(settings.COURSE_ID_PATTERN), 'courseware.views.submission_history', name='submission_history'), ) if settings.COURSEWARE_ENABLED and settings.FEATURES.get('ENABLE_INSTRUCTOR_LEGACY_DASHBOARD'): urlpatterns += ( url(r'^courses/{}/legacy_instructor_dash$'.format(settings.COURSE_ID_PATTERN), 'instructor.views.legacy.instructor_dashboard', name="instructor_dashboard_legacy"), ) if settings.FEATURES.get('CLASS_DASHBOARD'): urlpatterns += ( url(r'^class_dashboard/', include('class_dashboard.urls')), ) if settings.DEBUG or settings.FEATURES.get('ENABLE_DJANGO_ADMIN_SITE'): ## Jasmine and admin urlpatterns += (url(r'^admin/', include(admin.site.urls)),) if settings.FEATURES.get('AUTH_USE_OPENID'): urlpatterns += ( url(r'^openid/login/$', 'django_openid_auth.views.login_begin', name='openid-login'), url(r'^openid/complete/$', 'external_auth.views.openid_login_complete', name='openid-complete'), url(r'^openid/logo.gif$', 'django_openid_auth.views.logo', name='openid-logo'), ) if settings.FEATURES.get('AUTH_USE_SHIB'): urlpatterns += ( url(r'^shib-login/$', 'external_auth.views.shib_login', name='shib-login'), ) if settings.FEATURES.get('AUTH_USE_CAS'): urlpatterns += ( url(r'^cas-auth/login/$', 'external_auth.views.cas_login', name="cas-login"), url(r'^cas-auth/logout/$', 'django_cas.views.logout', {'next_page': '/'}, name="cas-logout"), ) if settings.FEATURES.get('RESTRICT_ENROLL_BY_REG_METHOD'): urlpatterns += ( url(r'^course_specific_login/{}/$'.format(settings.COURSE_ID_PATTERN), 'external_auth.views.course_specific_login', name='course-specific-login'), url(r'^course_specific_register/{}/$'.format(settings.COURSE_ID_PATTERN), 'external_auth.views.course_specific_register', name='course-specific-register'), ) # Shopping cart urlpatterns += ( url(r'^shoppingcart/', include('shoppingcart.urls')), ) # Survey Djangoapp urlpatterns += ( url(r'^survey/', include('survey.urls')), ) if settings.FEATURES.get('AUTH_USE_OPENID_PROVIDER'): urlpatterns += ( url(r'^openid/provider/login/$', 'external_auth.views.provider_login', name='openid-provider-login'), url(r'^openid/provider/login/(?:.+)$', 'external_auth.views.provider_identity', name='openid-provider-login-identity'), url(r'^openid/provider/identity/$', 'external_auth.views.provider_identity', name='openid-provider-identity'), url(r'^openid/provider/xrds/$', 'external_auth.views.provider_xrds', name='openid-provider-xrds') ) if settings.FEATURES.get('ENABLE_OAUTH2_PROVIDER'): urlpatterns += ( url(r'^oauth2/', include('oauth2_provider.urls', namespace='oauth2')), ) if settings.FEATURES.get('ENABLE_LMS_MIGRATION'): urlpatterns += ( url(r'^migrate/modules$', 'lms_migration.migrate.manage_modulestores'), url(r'^migrate/reload/(?P<reload_dir>[^/]+)$', 'lms_migration.migrate.manage_modulestores'), url(r'^migrate/reload/(?P<reload_dir>[^/]+)/(?P<commit_id>[^/]+)$', 'lms_migration.migrate.manage_modulestores'), url(r'^gitreload$', 'lms_migration.migrate.gitreload'), url(r'^gitreload/(?P<reload_dir>[^/]+)$', 'lms_migration.migrate.gitreload'), ) if settings.FEATURES.get('ENABLE_SQL_TRACKING_LOGS'): urlpatterns += ( url(r'^event_logs$', 'track.views.view_tracking_log'), url(r'^event_logs/(?P<args>.+)$', 'track.views.view_tracking_log'), ) if settings.FEATURES.get('ENABLE_SERVICE_STATUS'): urlpatterns += ( url(r'^status/', include('service_status.urls')), ) if settings.FEATURES.get('ENABLE_INSTRUCTOR_BACKGROUND_TASKS'): urlpatterns += ( url(r'^instructor_task_status/$', 'instructor_task.views.instructor_task_status', name='instructor_task_status'), ) if settings.FEATURES.get('RUN_AS_ANALYTICS_SERVER_ENABLED'): urlpatterns += ( url(r'^edinsights_service/', include('edinsights.core.urls')), ) import edinsights.core.registry # FoldIt views urlpatterns += ( # The path is hardcoded into their app... url(r'^comm/foldit_ops', 'foldit.views.foldit_ops', name="foldit_ops"), ) if settings.FEATURES.get('ENABLE_DEBUG_RUN_PYTHON'): urlpatterns += ( url(r'^debug/run_python$', 'debug.views.run_python'), ) urlpatterns += ( url(r'^debug/show_parameters$', 'debug.views.show_parameters'), ) # Crowdsourced hinting instructor manager. if settings.FEATURES.get('ENABLE_HINTER_INSTRUCTOR_VIEW'): urlpatterns += ( url(r'^courses/{}/hint_manager$'.format(settings.COURSE_ID_PATTERN), 'instructor.hint_manager.hint_manager', name="hint_manager"), ) # enable automatic login if settings.FEATURES.get('AUTOMATIC_AUTH_FOR_TESTING'): urlpatterns += ( url(r'^auto_auth$', 'student.views.auto_auth'), ) # Third-party auth. if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH'): urlpatterns += ( url(r'', include('third_party_auth.urls')), url(r'^login_oauth_token/(?P<backend>[^/]+)/$', 'student.views.login_oauth_token'), ) urlpatterns = patterns(*urlpatterns) if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # in debug mode, allow any template to be rendered (most useful for UX reference templates) urlpatterns += url(r'^template/(?P<template>.+)$', 'debug.views.show_reference_template'), #Custom error pages handler404 = 'static_template_view.views.render_404' handler500 = 'static_template_view.views.render_500' # display error page templates, for testing purposes urlpatterns += ( url(r'404', handler404), url(r'500', handler500), )
350dotorg/Django
refs/heads/master
tests/regressiontests/custom_managers_regress/models.py
93
""" Regression tests for custom manager classes. """ from django.db import models class RestrictedManager(models.Manager): """ A manager that filters out non-public instances. """ def get_query_set(self): return super(RestrictedManager, self).get_query_set().filter(is_public=True) class RelatedModel(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class RestrictedModel(models.Model): name = models.CharField(max_length=50) is_public = models.BooleanField(default=False) related = models.ForeignKey(RelatedModel) objects = RestrictedManager() plain_manager = models.Manager() def __unicode__(self): return self.name class OneToOneRestrictedModel(models.Model): name = models.CharField(max_length=50) is_public = models.BooleanField(default=False) related = models.OneToOneField(RelatedModel) objects = RestrictedManager() plain_manager = models.Manager() def __unicode__(self): return self.name
jeff-alves/Tera
refs/heads/master
game/message/unused/C_USER_AIM_TO.py
1
from util.tipo import tipo class C_USER_AIM_TO(object): def __init__(self, tracker, time, direction, opcode, data): print(str(type(self)).split('.')[3]+'('+str(len(data))+'): '+ str(data.get_array_hex(1))[1:-1])
MrSurly/micropython-esp32
refs/heads/esp32
tests/basics/fun_error2.py
18
# test errors from bad function calls try: enumerate except: print("SKIP") raise SystemExit def test_exc(code, exc): try: exec(code) print("no exception") except exc: print("right exception") except: print("wrong exception") # function with keyword args not given a specific keyword arg test_exc("enumerate()", TypeError)
allthroughthenight/aces
refs/heads/master
web2py/gluon/packages/dal/tests/_adapt.py
10
import os DEFAULT_URI = os.getenv('DB', 'sqlite:memory') NOSQL = any([name in DEFAULT_URI for name in ("datastore", "mongodb", "imap")]) IS_IMAP = "imap" in DEFAULT_URI IS_GAE = "datastore" in DEFAULT_URI IS_MONGODB = "mongodb" in DEFAULT_URI IS_POSTGRESQL = 'postgres' in DEFAULT_URI IS_SQLITE = 'sqlite' in DEFAULT_URI IS_MSSQL = 'mssql' in DEFAULT_URI IS_MYSQL = 'mysql' in DEFAULT_URI def drop(table, cascade=None): if NOSQL and not (IS_MONGODB): # GAE drop/cleanup is not implemented db = table._db db[table]._common_filter = None db(table).delete() del db[table._tablename] del db.tables[db.tables.index(table._tablename)] db._remove_references_to(table) else: if cascade: table.drop(cascade) else: table.drop()
ampax/edx-platform-backup
refs/heads/live
common/test/acceptance/performance/test_lms_performance.py
62
""" Single page performance tests for LMS. """ from bok_choy.web_app_test import WebAppTest, with_cache from ..pages.lms.auto_auth import AutoAuthPage from ..pages.lms.courseware import CoursewarePage from ..pages.lms.dashboard import DashboardPage from ..pages.lms.course_info import CourseInfoPage from ..pages.lms.login import LoginPage from ..pages.lms.progress import ProgressPage from ..pages.common.logout import LogoutPage from ..fixtures.course import CourseFixture, XBlockFixtureDesc, CourseUpdateDesc from ..tests.helpers import UniqueCourseTest, load_data_str from nose.plugins.attrib import attr @attr(har_mode='explicit') class LmsPerformanceTest(UniqueCourseTest): """ Base class to capture LMS performance with HTTP Archives. """ username = 'test_student' email = 'student101@example.com' def setUp(self): """ Setup course """ super(LmsPerformanceTest, self).setUp() # Install a course with sections/problems, tabs, updates, and handouts course_fix = CourseFixture( self.course_info['org'], self.course_info['number'], self.course_info['run'], self.course_info['display_name'] ) course_fix.add_update(CourseUpdateDesc(date='January 29, 2014', content='Test course update1')) course_fix.add_update(CourseUpdateDesc(date='January 30, 2014', content='Test course update2')) course_fix.add_update(CourseUpdateDesc(date='January 31, 2014', content='Test course update3')) course_fix.add_children( XBlockFixtureDesc('chapter', 'Test Section 1').add_children( XBlockFixtureDesc('sequential', 'Test Subsection 1').add_children( XBlockFixtureDesc('problem', 'Test Problem 1', data=load_data_str('multiple_choice.xml')), XBlockFixtureDesc('problem', 'Test Problem 2', data=load_data_str('formula_problem.xml')), XBlockFixtureDesc('html', 'Test HTML', data="<html>Html child text</html>"), ) ), XBlockFixtureDesc('chapter', 'Test Section 2').add_children( XBlockFixtureDesc('sequential', 'Test Subsection 2').add_children( XBlockFixtureDesc('html', 'Html Child', data="<html>Html child text</html>") ) ), XBlockFixtureDesc('chapter', 'Test Section 3').add_children( XBlockFixtureDesc('sequential', 'Test Subsection 3').add_children( XBlockFixtureDesc('problem', 'Test Problem 3') ) ) ).install() AutoAuthPage(self.browser, username=self.username, email=self.email, course_id=self.course_id).visit() def _make_har_file(self, page): """ Visit page and make HAR file. """ har_name = '{page}_{course}'.format(page=type(page).__name__, course=self.course_info['number']) self.har_capturer.add_page(self.browser, har_name) page.visit() self.har_capturer.save_har(self.browser, har_name) @with_cache def test_visit_coursware(self): """ Produce a HAR for loading the Coursware page. """ courseware_page = CoursewarePage(self.browser, self.course_id) self._make_har_file(courseware_page) @with_cache def test_visit_dashboard(self): """ Produce a HAR for loading the Dashboard page. """ dashboard_page = DashboardPage(self.browser) self._make_har_file(dashboard_page) @with_cache def test_visit_course_info(self): """ Produce a HAR for loading the Course Info page. """ course_info_page = CourseInfoPage(self.browser, self.course_id) self._make_har_file(course_info_page) @with_cache def test_visit_login_page(self): """ Produce a HAR for loading the Login page. """ login_page = LoginPage(self.browser) # Logout previously logged in user to be able to see Login page. LogoutPage(self.browser).visit() self._make_har_file(login_page) @with_cache def test_visit_progress_page(self): """ Produce a HAR for loading the Progress page. """ progress_page = ProgressPage(self.browser, self.course_id) self._make_har_file(progress_page)
rockstor/rockstor-core
refs/heads/master
src/rockstor/system/network.py
2
""" Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. RockStor is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import json import logging import re from .exceptions import CommandException from .osi import run_command from .docker import dnets, docker_status, dnet_inspect NMCLI = "/usr/bin/nmcli" DEFAULT_MTU = 1500 logger = logging.getLogger(__name__) def val(s): fields = s.split(": ") if len(fields) < 2: return None v = fields[1].strip() if len(v) == 0 or v == "--": return None return v def get_dev_list(): """ Returns a list of connection devices as seen by Network Manager :return: list """ o, e, rc = run_command([NMCLI, "-t", "-f", "device", "device"]) return o def get_dev_config(dev_list): """ Takes a list of connection devices and returns a dictionary with each device's config as seens by Network Manager :param dev_list: list returned by get_dev_list() :return: dictionary """ dmap = {} for dev in dev_list: if len(dev.strip()) == 0: continue tmap = { "dtype": None, "mac": None, "mtu": None, "state": None, } try: o, e, r = run_command([NMCLI, "d", "show", dev]) except CommandException as e: # especially veth devices can vanish abruptly sometimes. if e.rc == 10: logger.exception(e) logger.debug("device: {} vanished. Discarding it".format(dev)) continue raise for l in o: if re.match("GENERAL.TYPE:", l) is not None: tmap["dtype"] = val(l) elif re.match("GENERAL.HWADDR:", l) is not None: tmap["mac"] = val(l) elif re.match("GENERAL.MTU:", l) is not None: tmap["mtu"] = val(l) elif re.match("GENERAL.STATE:", l) is not None: tmap["state"] = val(l) elif re.match("GENERAL.CONNECTION:", l) is not None: connection = val(l) if connection is not None: tmap["connection"] = connection dmap[dev] = tmap return dmap def get_con_list(): """ Returns a list of connections as seen by Network Manager. :return: list """ o, e, rc = run_command([NMCLI, "-t", "-f", "uuid", "c", "show",]) return o def get_con_config(con_list): """ Takes a list of connections and returns a dictionary with each connection's config as seens by Network Manager :param con_list: list returned by get_con_list() :return: dictionary """ cmap = {} def flatten(l): s = ",".join(l) if len(s) == 0: return None return s def parse_aux_addresses(dtmap): """ Parses auxilliary addresses of a docker network and returns a flat list. :param dtmap: :return: """ aux = dtmap["IPAM"]["Config"][0]["AuxiliaryAddresses"] aux_list = [] for k, v in aux.items(): aux_list.append("{}={}".format(k, v)) return flatten(aux_list) for uuid in con_list: if len(uuid.strip()) == 0: continue tmap = { "name": None, "state": None, "ipv4_method": None, "ipv4_addresses": [], "ipv4_gw": None, "ipv4_dns": [], "ipv4_dns_search": None, "ipv6_method": None, "ipv6_addresses": None, "ipv6_gw": None, "ipv6_dns": None, "ipv6_dns_search": None, } try: o, e, rc = run_command([NMCLI, "c", "show", uuid,]) except CommandException as e: # in case the connection disappears if e.rc == 10: logger.exception(e) logger.debug("connection: {} vanished. Discarding it".format(uuid)) continue raise e for l in o: if re.match("ipv4.method:", l) is not None: tmap["ipv4_method"] = val(l) elif re.match("connection.id:", l) is not None: tmap["name"] = val(l) elif re.match("GENERAL.STATE:", l) is not None: tmap["state"] = val(l) elif re.match("IP4.ADDRESS", l) is not None: tmap["ipv4_addresses"].append(val(l)) elif re.match("IP4.GATEWAY:", l) is not None: tmap["ipv4_gw"] = val(l) elif re.match("IP4.DNS", l) is not None: v = val(l) if v is not None: if v not in tmap["ipv4_dns"]: tmap["ipv4_dns"].append(v) elif re.match("ipv4.dns:", l) is not None: v = val(l) if v is not None: for ip in v.split(","): if ip not in tmap["ipv4_dns"]: tmap["ipv4_dns"].append(ip) elif re.match("ipv4.dns-search:", l) is not None: tmap["ipv4_dns_search"] = val(l) elif re.match("connection.type:", l) is not None: tmap["ctype"] = val(l) if tmap["ctype"] == "802-3-ethernet": tmap[tmap["ctype"]] = { "mac": None, "cloned_mac": None, "mtu": None, } elif tmap["ctype"] in ("team", "bond"): tmap[tmap["ctype"]] = {"config": None} elif tmap["ctype"] == "bridge": cid = tmap["name"] tmap[tmap["ctype"]] = { "docker_name": None, "aux_address": None, "dgateway": None, "host_binding": None, "icc": False, "internal": False, "ip_masquerade": False, "ip_range": None, "subnet": None, } # Get docker_name if docker_status(): # if (cid[0].startswith('br-')): # custom-type docker network if cid.startswith("br-"): # custom-type docker network docker_name = dname = dnets(cid[3:])[0] else: # default docker0 bridge network docker_name = cid dname = "bridge" # Fill custom information, if any. dtmap = dnet_inspect(dname) tmap[tmap["ctype"]]["docker_name"] = docker_name if dtmap["IPAM"]["Config"][0].get("AuxiliaryAddresses"): tmap[tmap["ctype"]]["aux_address"] = parse_aux_addresses( dtmap ) # In some case, DNET inspect does NOT return Gateway in Docker version 18.09.5, build e8ff056 # This is likely related to the following bug in which the 'Gateway' is not reported the first # time the docker daemon is started. Upon reload of docker daemon, it IS correctly reported. # https://github.com/moby/moby/issues/26799 if dtmap["IPAM"]["Config"][0].get("Gateway"): tmap[tmap["ctype"]]["dgateway"] = dtmap["IPAM"]["Config"][ 0 ]["Gateway"] if dtmap["Options"].get( "com.docker.network.bridge.host_binding_ipv4" ): tmap[tmap["ctype"]]["host_binding"] = dtmap["Options"][ "com.docker.network.bridge.host_binding_ipv4" ] if dtmap["Options"].get("com.docker.network.bridge.enable_icc"): tmap[tmap["ctype"]]["icc"] = dtmap["Options"][ "com.docker.network.bridge.enable_icc" ] tmap[tmap["ctype"]]["internal"] = dtmap["Internal"] if dtmap["Options"].get( "com.docker.network.bridge.ip_masquerade" ): tmap[tmap["ctype"]]["ip_masquerade"] = dtmap["Options"][ "com.docker.network.bridge.ip_masquerade" ] if dtmap["IPAM"]["Config"][0].get("IPRange"): tmap[tmap["ctype"]]["ip_range"] = dtmap["IPAM"]["Config"][ 0 ]["IPRange"] tmap[tmap["ctype"]]["subnet"] = dtmap["IPAM"]["Config"][0][ "Subnet" ] else: tmap[tmap["ctype"]] = {} elif re.match("connection.master:", l) is not None: # for team, bond and bridge type connections. master = val(l) if master is not None: tmap["master"] = master elif ( re.match("802-3-ethernet.mac-address:", l) is not None and tmap["ctype"] == "802-3-ethernet" ): tmap[tmap["ctype"]]["mac"] = val(l) elif ( re.match("802-3-ethernet.cloned-mac-address:", l) is not None and tmap["ctype"] == "802-3-ethernet" ): tmap[tmap["ctype"]]["cloned_mac"] = val(l) elif ( re.match("802-3-ethernet.mtu:", l) is not None and tmap["ctype"] == "802-3-ethernet" ): tmap[tmap["ctype"]]["mtu"] = val(l) elif re.match("team.config:", l) is not None and tmap["ctype"] == "team": tmap[tmap["ctype"]]["config"] = l.split("team.config:")[1].strip() elif re.match("bond.options:", l) is not None and tmap["ctype"] == "bond": options = l.split("bond.options:")[1].strip() options_l = options.split("=") # @todo: there may be more options. for now, we just care about # mode. tmap[tmap["ctype"]]["config"] = json.dumps({options_l[0]: options_l[1]}) tmap["ipv4_addresses"] = flatten(tmap["ipv4_addresses"]) tmap["ipv4_dns"] = flatten(tmap["ipv4_dns"]) cmap[uuid] = tmap return cmap def valid_connection(uuid): o, e, rc = run_command([NMCLI, "c", "show", uuid], throw=False) if rc != 0: return False return True def toggle_connection(uuid, switch): return run_command([NMCLI, "c", switch, uuid]) def delete_connection(uuid): if valid_connection(uuid): return run_command([NMCLI, "c", "delete", uuid]) def reload_connection(uuid): return run_command([NMCLI, "c", "reload", uuid]) def new_connection_helper( name, ipaddr, gateway, dns_servers, search_domains, mtu=DEFAULT_MTU ): manual = False if ipaddr is not None and len(ipaddr.strip()) > 0: manual = True run_command([NMCLI, "c", "mod", name, "ipv4.addresses", ipaddr]) if gateway is not None and len(gateway.strip()) > 0: run_command([NMCLI, "c", "mod", name, "ipv4.gateway", gateway]) if manual: run_command([NMCLI, "c", "mod", name, "ipv4.method", "manual"]) if dns_servers is not None and len(dns_servers.strip()) > 0: run_command([NMCLI, "c", "mod", name, "ipv4.dns", dns_servers]) if search_domains is not None and len(search_domains.strip()) > 0: run_command([NMCLI, "c", "mod", name, "ipv4.dns-search", search_domains]) if mtu != DEFAULT_MTU: # no need to set it if it's default value run_command([NMCLI, "c", "mod", name, "802-3-ethernet.mtu", mtu]) def new_ethernet_connection( name, ifname, ipaddr=None, gateway=None, dns_servers=None, search_domains=None, mtu=DEFAULT_MTU, ): run_command( [NMCLI, "c", "add", "type", "ethernet", "con-name", name, "ifname", ifname] ) new_connection_helper(name, ipaddr, gateway, dns_servers, search_domains, mtu=mtu) # @todo: probably better to get the uuid and reload with it instead of # name. reload_connection(name) def new_member_helper(name, members, mtype): for i in range(len(members)): mname = "%s-slave-%d" % (name, i) run_command( [ NMCLI, "c", "add", "type", mtype, "con-name", mname, "ifname", members[i], "master", name, ] ) for i in range(len(members)): mname = "%s-slave-%d" % (name, i) run_command([NMCLI, "c", "up", mname]) # keeping new_team_connection and new_bond_connection separate even though they # are very similar. We should consolidate after we are able to support all # common config parameters in both modes. def new_team_connection( name, config, members, ipaddr=None, gateway=None, dns_servers=None, search_domains=None, mtu=DEFAULT_MTU, ): run_command( [ NMCLI, "c", "add", "type", "team", "con-name", name, "ifname", name, "config", config, ] ) new_connection_helper(name, ipaddr, gateway, dns_servers, search_domains, mtu) new_member_helper(name, members, "team-slave") reload_connection(name) def new_bond_connection( name, mode, members, ipaddr=None, gateway=None, dns_servers=None, search_domains=None, ): run_command( [ NMCLI, "c", "add", "type", "bond", "con-name", name, "ifname", name, "mode", mode, ] ) new_connection_helper(name, ipaddr, gateway, dns_servers, search_domains) new_member_helper(name, members, "bond-slave") reload_connection(name)
lowfatcomputing/amforth
refs/heads/master
core/devices/atmega165pa/device.py
5
# Partname: ATmega165PA # generated automatically, do not edit MCUREGS = { 'TCCR0A': '&68', 'TCCR0A_FOC0A': '$80', 'TCCR0A_WGM00': '$40', 'TCCR0A_COM0A': '$30', 'TCCR0A_WGM01': '$08', 'TCCR0A_CS0': '$07', 'TCNT0': '&70', 'OCR0A': '&71', 'TIMSK0': '&110', 'TIMSK0_OCIE0A': '$02', 'TIMSK0_TOIE0': '$01', 'TIFR0': '&53', 'TIFR0_OCF0A': '$02', 'TIFR0_TOV0': '$01', 'GTCCR': '&67', 'GTCCR_TSM': '$80', 'GTCCR_PSR310': '$01', 'TCCR1A': '&128', 'TCCR1A_COM1A': '$C0', 'TCCR1A_COM1B': '$30', 'TCCR1A_WGM1': '$03', 'TCCR1B': '&129', 'TCCR1B_ICNC1': '$80', 'TCCR1B_ICES1': '$40', 'TCCR1B_WGM1': '$18', 'TCCR1B_CS1': '$07', 'TCCR1C': '&130', 'TCCR1C_FOC1A': '$80', 'TCCR1C_FOC1B': '$40', 'TCNT1': '&132', 'OCR1A': '&136', 'OCR1B': '&138', 'ICR1': '&134', 'TIMSK1': '&111', 'TIMSK1_ICIE1': '$20', 'TIMSK1_OCIE1B': '$04', 'TIMSK1_OCIE1A': '$02', 'TIMSK1_TOIE1': '$01', 'TIFR1': '&54', 'TIFR1_ICF1': '$20', 'TIFR1_OCF1B': '$04', 'TIFR1_OCF1A': '$02', 'TIFR1_TOV1': '$01', 'TCCR2A': '&176', 'TCCR2A_FOC2A': '$80', 'TCCR2A_WGM20': '$40', 'TCCR2A_COM2A': '$30', 'TCCR2A_WGM21': '$08', 'TCCR2A_CS2': '$07', 'TCNT2': '&178', 'OCR2A': '&179', 'TIMSK2': '&112', 'TIMSK2_OCIE2A': '$02', 'TIMSK2_TOIE2': '$01', 'TIFR2': '&55', 'TIFR2_OCF2A': '$02', 'TIFR2_TOV2': '$01', 'ASSR': '&182', 'ASSR_EXCLK': '$10', 'ASSR_AS2': '$08', 'ASSR_TCN2UB': '$04', 'ASSR_OCR2UB': '$02', 'ASSR_TCR2UB': '$01', 'WDTCR': '&96', 'WDTCR_WDCE': '$10', 'WDTCR_WDE': '$08', 'WDTCR_WDP': '$07', 'EEAR': '&65', 'EEDR': '&64', 'EECR': '&63', 'EECR_EERIE': '$08', 'EECR_EEMWE': '$04', 'EECR_EEWE': '$02', 'EECR_EERE': '$01', 'SPCR': '&76', 'SPCR_SPIE': '$80', 'SPCR_SPE': '$40', 'SPCR_DORD': '$20', 'SPCR_MSTR': '$10', 'SPCR_CPOL': '$08', 'SPCR_CPHA': '$04', 'SPCR_SPR': '$03', 'SPSR': '&77', 'SPSR_SPIF': '$80', 'SPSR_WCOL': '$40', 'SPSR_SPI2X': '$01', 'SPDR': '&78', 'PORTA': '&34', 'DDRA': '&33', 'PINA': '&32', 'PORTB': '&37', 'DDRB': '&36', 'PINB': '&35', 'PORTC': '&40', 'DDRC': '&39', 'PINC': '&38', 'PORTD': '&43', 'DDRD': '&42', 'PIND': '&41', 'ADCSRB': '&123', 'ADCSRB_ACME': '$40', 'ACSR': '&80', 'ACSR_ACD': '$80', 'ACSR_ACBG': '$40', 'ACSR_ACO': '$20', 'ACSR_ACI': '$10', 'ACSR_ACIE': '$08', 'ACSR_ACIC': '$04', 'ACSR_ACIS': '$03', 'DIDR1': '&127', 'DIDR1_AIN1D': '$02', 'DIDR1_AIN0D': '$01', 'PORTE': '&46', 'DDRE': '&45', 'PINE': '&44', 'PORTF': '&49', 'DDRF': '&48', 'PINF': '&47', 'PORTG': '&52', 'DDRG': '&51', 'PING': '&50', 'OCDR': '&81', 'MCUCR': '&85', 'MCUCR_JTD': '$80', 'MCUSR': '&84', 'MCUSR_JTRF': '$10', 'USIDR': '&186', 'USISR': '&185', 'USISR_USISIF': '$80', 'USISR_USIOIF': '$40', 'USISR_USIPF': '$20', 'USISR_USIDC': '$10', 'USISR_USICNT': '$0F', 'USICR': '&184', 'USICR_USISIE': '$80', 'USICR_USIOIE': '$40', 'USICR_USIWM': '$30', 'USICR_USICS': '$0C', 'USICR_USICLK': '$02', 'USICR_USITC': '$01', 'ADMUX': '&124', 'ADMUX_REFS': '$C0', 'ADMUX_ADLAR': '$20', 'ADMUX_MUX': '$1F', 'ADCSRA': '&122', 'ADCSRA_ADEN': '$80', 'ADCSRA_ADSC': '$40', 'ADCSRA_ADATE': '$20', 'ADCSRA_ADIF': '$10', 'ADCSRA_ADIE': '$08', 'ADCSRA_ADPS': '$07', 'ADC': '&120', 'DIDR0': '&126', 'DIDR0_ADC7D': '$80', 'DIDR0_ADC6D': '$40', 'DIDR0_ADC5D': '$20', 'DIDR0_ADC4D': '$10', 'DIDR0_ADC3D': '$08', 'DIDR0_ADC2D': '$04', 'DIDR0_ADC1D': '$02', 'DIDR0_ADC0D': '$01', 'SPMCSR': '&87', 'SPMCSR_SPMIE': '$80', 'SPMCSR_RWWSB': '$40', 'SPMCSR_RWWSRE': '$10', 'SPMCSR_BLBSET': '$08', 'SPMCSR_PGWRT': '$04', 'SPMCSR_PGERS': '$02', 'SPMCSR_SPMEN': '$01', 'UDR0': '&198', 'UCSR0A': '&192', 'UCSR0A_RXC0': '$80', 'UCSR0A_TXC0': '$40', 'UCSR0A_UDRE0': '$20', 'UCSR0A_FE0': '$10', 'UCSR0A_DOR0': '$08', 'UCSR0A_UPE0': '$04', 'UCSR0A_U2X0': '$02', 'UCSR0A_MPCM0': '$01', 'UCSR0B': '&193', 'UCSR0B_RXCIE0': '$80', 'UCSR0B_TXCIE0': '$40', 'UCSR0B_UDRIE0': '$20', 'UCSR0B_RXEN0': '$10', 'UCSR0B_TXEN0': '$08', 'UCSR0B_UCSZ02': '$04', 'UCSR0B_RXB80': '$02', 'UCSR0B_TXB80': '$01', 'UCSR0C': '&194', 'UCSR0C_UMSEL0': '$40', 'UCSR0C_UPM0': '$30', 'UCSR0C_USBS0': '$08', 'UCSR0C_UCSZ0': '$06', 'UCSR0C_UCPOL0': '$01', 'UBRR0': '&196', 'EICRA': '&105', 'EICRA_ISC01': '$02', 'EICRA_ISC00': '$01', 'EIMSK': '&61', 'EIMSK_PCIE': '$30', 'EIMSK_INT0': '$01', 'EIFR': '&60', 'EIFR_PCIF': '$30', 'EIFR_INTF0': '$01', 'PCMSK1': '&108', 'PCMSK1_PCINT': '$FF', 'PCMSK0': '&107', 'PCMSK0_PCINT': '$FF', 'SREG': '&95', 'SREG_I': '$80', 'SREG_T': '$40', 'SREG_H': '$20', 'SREG_S': '$10', 'SREG_V': '$08', 'SREG_N': '$04', 'SREG_Z': '$02', 'SREG_C': '$01', 'SP': '&93', 'OSCCAL': '&102', 'CLKPR': '&97', 'CLKPR_CLKPCE': '$80', 'CLKPR_CLKPS': '$0F', 'PRR': '&100', 'PRR_PRTIM1': '$08', 'PRR_PRSPI': '$04', 'PRR_PRUSART0': '$02', 'PRR_PRADC': '$01', 'SMCR': '&83', 'SMCR_SM': '$0E', 'SMCR_SE': '$01', 'GPIOR2': '&75', 'GPIOR1': '&74', 'GPIOR0': '&62', 'INT0Addr': '2', 'PCINT0Addr': '4', 'PCINT1Addr': '6', 'TIMER2_COMPAddr': '8', 'TIMER2_OVFAddr': '10', 'TIMER1_CAPTAddr': '12', 'TIMER1_COMPAAddr': '14', 'TIMER1_COMPBAddr': '16', 'TIMER1_OVFAddr': '18', 'TIMER0_COMPAddr': '20', 'TIMER0_OVFAddr': '22', 'SPI__STCAddr': '24', 'USART0__RXAddr': '26', 'USART0__UDREAddr': '28', 'USART0__TXAddr': '30', 'USI_STARTAddr': '32', 'USI_OVERFLOWAddr': '34', 'ANALOG_COMPAddr': '36', 'ADCAddr': '38', 'EE_READYAddr': '40', 'SPM_READYAddr': '42' }
topxiaoke/myedx
refs/heads/master
common/lib/xmodule/xmodule/foldit_module.py
56
import logging from lxml import etree from pkg_resources import resource_string from xmodule.editing_module import EditingDescriptor from xmodule.x_module import XModule from xmodule.xml_module import XmlDescriptor from xblock.fields import Scope, Integer, String from .fields import Date from .util.duedate import get_extended_due_date log = logging.getLogger(__name__) class FolditFields(object): # default to what Spring_7012x uses required_level_half_credit = Integer(default=3, scope=Scope.settings) required_sublevel_half_credit = Integer(default=5, scope=Scope.settings) required_level = Integer(default=4, scope=Scope.settings) required_sublevel = Integer(default=5, scope=Scope.settings) due = Date(help="Date that this problem is due by", scope=Scope.settings) extended_due = Date( help="Date that this problem is due by for a particular student. This " "can be set by an instructor, and will override the global due " "date if it is set to a date that is later than the global due " "date.", default=None, scope=Scope.user_state, ) show_basic_score = String(scope=Scope.settings, default='false') show_leaderboard = String(scope=Scope.settings, default='false') class FolditModule(FolditFields, XModule): css = {'scss': [resource_string(__name__, 'css/foldit/leaderboard.scss')]} def __init__(self, *args, **kwargs): """ Example: <foldit show_basic_score="true" required_level="4" required_sublevel="3" required_level_half_credit="2" required_sublevel_half_credit="3" show_leaderboard="false"/> """ super(FolditModule, self).__init__(*args, **kwargs) self.due_time = get_extended_due_date(self) def is_complete(self): """ Did the user get to the required level before the due date? """ # We normally don't want django dependencies in xmodule. foldit is # special. Import this late to avoid errors with things not yet being # initialized. from foldit.models import PuzzleComplete complete = PuzzleComplete.is_level_complete( self.system.anonymous_student_id, self.required_level, self.required_sublevel, self.due_time) return complete def is_half_complete(self): """ Did the user reach the required level for half credit? Ideally this would be more flexible than just 0, 0.5, or 1 credit. On the other hand, the xml attributes for specifying more specific cut-offs and partial grades can get more confusing. """ from foldit.models import PuzzleComplete complete = PuzzleComplete.is_level_complete( self.system.anonymous_student_id, self.required_level_half_credit, self.required_sublevel_half_credit, self.due_time) return complete def completed_puzzles(self): """ Return a list of puzzles that this user has completed, as an array of dicts: [ {'set': int, 'subset': int, 'created': datetime} ] The list is sorted by set, then subset """ from foldit.models import PuzzleComplete return sorted( PuzzleComplete.completed_puzzles(self.system.anonymous_student_id), key=lambda d: (d['set'], d['subset'])) def puzzle_leaders(self, n=10, courses=None): """ Returns a list of n pairs (user, score) corresponding to the top scores; the pairs are in descending order of score. """ from foldit.models import Score if courses is None: courses = [self.location.course_key] leaders = [(leader['username'], leader['score']) for leader in Score.get_tops_n(10, course_list=courses)] leaders.sort(key=lambda x: -x[1]) return leaders def get_html(self): """ Render the html for the module. """ goal_level = '{0}-{1}'.format( self.required_level, self.required_sublevel) showbasic = (self.show_basic_score.lower() == "true") showleader = (self.show_leaderboard.lower() == "true") context = { 'due': self.due, 'success': self.is_complete(), 'goal_level': goal_level, 'completed': self.completed_puzzles(), 'top_scores': self.puzzle_leaders(), 'show_basic': showbasic, 'show_leader': showleader, 'folditbasic': self.get_basicpuzzles_html(), 'folditchallenge': self.get_challenge_html() } return self.system.render_template('foldit.html', context) def get_basicpuzzles_html(self): """ Render html for the basic puzzle section. """ goal_level = '{0}-{1}'.format( self.required_level, self.required_sublevel) context = { 'due': self.due, 'success': self.is_complete(), 'goal_level': goal_level, 'completed': self.completed_puzzles(), } return self.system.render_template('folditbasic.html', context) def get_challenge_html(self): """ Render html for challenge (i.e., the leaderboard) """ context = { 'top_scores': self.puzzle_leaders()} return self.system.render_template('folditchallenge.html', context) def get_score(self): """ 0 if required_level_half_credit - required_sublevel_half_credit not reached. 0.5 if required_level_half_credit and required_sublevel_half_credit reached. 1 if requred_level and required_sublevel reached. """ if self.is_complete(): score = 1 elif self.is_half_complete(): score = 0.5 else: score = 0 return {'score': score, 'total': self.max_score()} def max_score(self): return 1 class FolditDescriptor(FolditFields, XmlDescriptor, EditingDescriptor): """ Module for adding Foldit problems to courses """ mako_template = "widgets/html-edit.html" module_class = FolditModule filename_extension = "xml" has_score = True js = {'coffee': [resource_string(__name__, 'js/src/html/edit.coffee')]} js_module_name = "HTMLEditingDescriptor" # The grade changes without any student interaction with the edx website, # so always need to actually check. always_recalculate_grades = True @classmethod def definition_from_xml(cls, xml_object, system): return {}, [] def definition_to_xml(self, resource_fs): xml_object = etree.Element('foldit') return xml_object
myd7349/DiveIntoPython3Practices
refs/heads/master
chapter_10_Refactoring/roman8.5.py
1
# -*- coding: utf-8 -*- # 2014-11-21T16:55+08:00 import re import unittest class OutOfRangeError(ValueError): pass class NotIntegerError(ValueError): pass class InvalidRomanNumeralError(ValueError): pass roman_numeral_map = (('M', 1000), ('CM', 900), ('D', 500), ('CD', 400), ('C', 100), ('XC', 90), ('L', 50), ('XL', 40), ('X', 10), ('IX', 9), ('V', 5), ('IV', 4), ('I', 1)) def to_roman(n): '''Convert integer to Roman numeral''' if not (0 < n < 4000): # a nice Pythonic shortcut: multiple comparisons at once # The unit test does not check the human-readable string that accompanies the exception # If you change your conditions, make sure to update your human-readable error strings # to match. The unittest framework won’t care, but it’ll make it difficult to do manual # debugging if your code is throwing incorrectly-described exceptions. raise OutOfRangeError('number out of range (must be 1...3999)') if not isinstance(n, int): raise NotIntegerError('non-integers can not be converted') result = '' for numeral, integer in roman_numeral_map: while n >= integer: result += numeral n -= integer return result roman_numeral_pattern = re.compile(''' ^ # beginning of string M{0,3} # thousands - 0 to 3 Ms (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 Cs), # or 500-800 (D, followed by 0 to 3 Cs) (XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 Xs), # or 50-80 (L, followed by 0 to 3 Xs) (IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 Is), # or 5-8 (V, followed by 0 to 3 Is) $ # end of string ''', re.VERBOSE) def from_roman(s): '''Convert Roman numeral to integer''' if not s: raise InvalidRomanNumeralError('Input can not be blank') if not roman_numeral_pattern.search(s): raise InvalidRomanNumeralError('Invalid Roman numeral: {0}'.format(s)) result = 0 index = 0 for numeral, integer in roman_numeral_map: while s[index:index+len(numeral)] == numeral: result += integer index += len(numeral) return result class KnownValues(unittest.TestCase): known_values = ((1, 'I'), (2, 'II'), (3, 'III'), (4, 'IV'), (5, 'V'), (6, 'VI'), (7, 'VII'), (8, 'VIII'), (9, 'IX'), (10, 'X'), (50, 'L'), (100, 'C'), (500, 'D'), (1000, 'M'), (31, 'XXXI'), (148, 'CXLVIII'), (294, 'CCXCIV'), (312, 'CCCXII'), (421, 'CDXXI'), (528, 'DXXVIII'), (621, 'DCXXI'), (782, 'DCCLXXXII'), (870, 'DCCCLXX'), (941, 'CMXLI'), (1043, 'MXLIII'), (1110, 'MCX'), (1226, 'MCCXXVI'), (1301, 'MCCCI'), (1485, 'MCDLXXXV'), (1509, 'MDIX'), (1607, 'MDCVII'), (1754, 'MDCCLIV'), (1832, 'MDCCCXXXII'), (1993, 'MCMXCIII'), (2074, 'MMLXXIV'), (2152, 'MMCLII'), (2212, 'MMCCXII'), (2343, 'MMCCCXLIII'), (2499, 'MMCDXCIX'), (2574, 'MMDLXXIV'), (2646, 'MMDCXLVI'), (2723, 'MMDCCXXIII'), (2892, 'MMDCCCXCII'), (2975, 'MMCMLXXV'), (3051, 'MMMLI'), (3185, 'MMMCLXXXV'), (3250, 'MMMCCL'), (3313, 'MMMCCCXIII'), (3408, 'MMMCDVIII'), (3501, 'MMMDI'), (3610, 'MMMDCX'), (3743, 'MMMDCCXLIII'), (3844, 'MMMDCCCXLIV'), (3888, 'MMMDCCCLXXXVIII'), (3940, 'MMMCMXL'), (3999, 'MMMCMXCIX')) def test_to_roman_known_values(self): '''to_roman should give known result with known input''' for integer, numeral in self.known_values: self.assertEqual(numeral, to_roman(integer)) # FAIL def test_from_roman_known_values(self): '''from_roman should give known result with known input''' for integer, numeral in self.known_values: self.assertEqual(integer, from_roman(numeral)) class RoundtripCheck(unittest.TestCase): # FAIL def test_roundtrip(self): '''from_roman(to_roman(n)) == n for all n''' for integer in range(1, 4000): self.assertEqual(from_roman(to_roman(integer)), integer) class ToRomanBadInput(unittest.TestCase): # PASS def test_too_large(self): '''to_roman should fail with large input''' # 3. The unittest.TestCase class provides the assertRaises method, # which takes the following arguments: the exception you’re expecting, # the function you’re testing, and the arguments you’re passing to that # function. (If the function you’re testing takes more than one argument, # pass them all to assertRaises, in order, and it will pass them right along # to the function you’re testing.) # assertRaises(exception, callable, *args, **kwds) # assertRaises(exception, msg=None) self.assertRaises(OutOfRangeError, to_roman, 4000) # PASS def test_zero(self): '''to_roman should fail with 0 input''' self.assertRaises(OutOfRangeError, to_roman, 0) # PASS def test_negative(self): '''to_roman should fail with negative input''' self.assertRaises(OutOfRangeError, to_roman, -1) # PASS def test_non_integer(self): '''to_roman should fail with non-integer input''' self.assertRaises(NotIntegerError, to_roman, 0.5) class FromRomanBadInput(unittest.TestCase): def test_too_many_repeated_numerals(self): '''from_roman should fail with too many repeated numerals''' for s in ('MMMM', 'DD', 'CCCC', 'LL', 'XXXX', 'VV', 'IIII'): self.assertRaises(InvalidRomanNumeralError, from_roman, s) def test_repeated_pairs(self): '''from_roman should fail with repated pairs of numerals''' for s in ('CMCM', 'CDCD', 'XCXC', 'XLXL', 'IXIX', 'IVIV'): self.assertRaises(InvalidRomanNumeralError, from_roman, s) def test_malformed_antecedents(self): '''from_roman should fail with malformed antecedents''' for s in ('IIMXCC', 'VX', 'DCM', 'CMM', 'IXIV', 'MCMC', 'XCX', 'IVI', 'LM', 'LD', 'LC'): self.assertRaises(InvalidRomanNumeralError, from_roman, s) # PASS def test_blank(self): '''from_roman should fail with blank string''' self.assertRaises(InvalidRomanNumeralError, from_roman, '') if __name__ == '__main__': # By default, unittest.main will call sys.exit after all tests, and in this case, # code after the invoking of unittest.main will be ignored. By passing False to # 'exit' keyword argument, we change this behavior. unittest.main(exit = False) # It is not enough to test that functions succeed when given good input; you must # also test that they fail when given bad input. And not just any sort of failure; # they must fail in the way you expect. try: print(to_roman(5000)) except OutOfRangeError: print('5000 is too large') # Along with testing numbers that are too large, # you need to test numbers that are too small. try: print('{!r}'.format(to_roman(0))) print('{!r}'.format(to_roman(-1))) except: pass # And more... try: print('{!r}'.format(to_roman(0.5))) print('{!r}'.format(to_roman(1.5))) except Exception as e: print(repr(e))
llange/pynag
refs/heads/master
pynag/Utils/importer.py
2
#!/usr/bin/env python # -*- coding: utf-8 -*- """ General Utilities from importing nagios objects. Currently .csv files are supported Either execute this script standalone from the command line or use it as a python library like so: >>> from pynag.Utils import importer >>> pynag_objects = importer.import_from_csv_file(filename='foo', seperator=',') # doctest: +SKIP >>> for i in pynag_objects: # doctest: +SKIP ... i.save() # doctest: +SKIP """ import optparse import os import pynag.Model # Default host is used when you try to add a service to a # Host that does not exist DEFAULT_HOST_ATTRIBUTES = { 'use': 'generic-host', 'check_command': 'check-host-alive', 'check_interval': '1', 'max_check_attempts': '3', 'retry_interval': '2', } options = optparse.OptionParser() options.add_option( '--destination_filename', dest='destination_filename', default=None, help='Destination file where objects will be saved', ) options.add_option( '--seperator', dest='seperator', default=',', help='Use this as seperator for columns (default: ,)', ) options.add_option( '--dry_run', dest='dry_run', default=False, action='store_true', help='If specified, only print object definitions to screen', ) options.add_option( '--object_type', dest='object_type', default=None, help='Assume this object type (e.g. "host") if its not specified in file' ) def parse_arguments(): """ Parse command line arguments """ (opts, args) = options.parse_args() return opts, args def main(): (opts, args) = parse_arguments() if not args: options.error("You must specify at least one .csv file as an argument") for i in args: if not os.path.isfile(i): options.error("Could not find file: %s" % i) pynag_objects = [] for i in args: tmp = import_from_csv_file(filename=i, seperator=opts.seperator, object_type=opts.object_type) pynag_objects += tmp if opts.dry_run: print len(pynag_objects) for i in pynag_objects: print i else: for i in pynag_objects: i.save(filename=opts.destination_filename) def dict_to_pynag_objects(dict_list, object_type=None): """Take a list of dictionaries, return a list of pynag.Model objects. Args: dict_list: List of dictionaries that represent pynag objects object_type: Use this object type as default, if it is not specified in dict_list Returns: List of pynag objects """ result = [] for i in dict_list: dictionary = i.copy() object_type = dictionary.pop("object_type", object_type) if not object_type: raise ValueError('One column needs to specify object type') Class = pynag.Model.string_to_class[object_type] pynag_object = Class(**dictionary) result.append(pynag_object) return result def parse_csv_file(filename, seperator=','): """ Parse filename and return a dict representing its contents """ with open(filename) as f: data = f.read() return parse_csv_string(data, seperator=seperator) def parse_csv_string(csv_string, seperator=','): """ Parse csv string and return a dict representing its contents """ result = [] lines = csv_string.splitlines() headers = None for line in lines: # Skip empty lines if not line: continue # If this is first line if not headers: headers = map(lambda x: x.strip(), line.split(seperator)) continue mydict = {} result.append(mydict) columns = map(lambda x: x.strip(), line.split(seperator)) for i, column in enumerate(columns): header = headers[i] mydict[header] = column return result def import_from_csv_file(filename, seperator=',', object_type=None): """ Parses filename and returns a list of pynag objects. Args: filename: Path to a file seperator: use this symbol to seperate columns in the file object_type: Assume this object_type if there is no object_type column """ dicts = parse_csv_file(filename=filename, seperator=seperator) pynag_objects = dict_to_pynag_objects(dicts, object_type=object_type) return pynag_objects if __name__ == '__main__': main()
jcoady9/python-for-android
refs/heads/master
python3-alpha/python3-src/Lib/distutils/tests/test_sdist.py
46
"""Tests for distutils.command.sdist.""" import os import tarfile import unittest import warnings import zipfile from os.path import join from textwrap import dedent from test.support import captured_stdout, check_warnings, run_unittest from distutils.command.sdist import sdist, show_formats from distutils.core import Distribution from distutils.tests.test_config import PyPIRCCommandTestCase from distutils.errors import DistutilsOptionError from distutils.spawn import find_executable from distutils.log import WARN from distutils.archive_util import ARCHIVE_FORMATS SETUP_PY = """ from distutils.core import setup import somecode setup(name='fake') """ MANIFEST = """\ # file GENERATED by distutils, do NOT edit README inroot.txt setup.py data%(sep)sdata.dt scripts%(sep)sscript.py some%(sep)sfile.txt some%(sep)sother_file.txt somecode%(sep)s__init__.py somecode%(sep)sdoc.dat somecode%(sep)sdoc.txt """ try: import zlib ZLIB_SUPPORT = True except ImportError: ZLIB_SUPPORT = False class SDistTestCase(PyPIRCCommandTestCase): def setUp(self): # PyPIRCCommandTestCase creates a temp dir already # and put it in self.tmp_dir super(SDistTestCase, self).setUp() # setting up an environment self.old_path = os.getcwd() os.mkdir(join(self.tmp_dir, 'somecode')) os.mkdir(join(self.tmp_dir, 'dist')) # a package, and a README self.write_file((self.tmp_dir, 'README'), 'xxx') self.write_file((self.tmp_dir, 'somecode', '__init__.py'), '#') self.write_file((self.tmp_dir, 'setup.py'), SETUP_PY) os.chdir(self.tmp_dir) def tearDown(self): # back to normal os.chdir(self.old_path) super(SDistTestCase, self).tearDown() def get_cmd(self, metadata=None): """Returns a cmd""" if metadata is None: metadata = {'name': 'fake', 'version': '1.0', 'url': 'xxx', 'author': 'xxx', 'author_email': 'xxx'} dist = Distribution(metadata) dist.script_name = 'setup.py' dist.packages = ['somecode'] dist.include_package_data = True cmd = sdist(dist) cmd.dist_dir = 'dist' def _warn(*args): pass cmd.warn = _warn return dist, cmd @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') def test_prune_file_list(self): # this test creates a package with some vcs dirs in it # and launch sdist to make sure they get pruned # on all systems # creating VCS directories with some files in them os.mkdir(join(self.tmp_dir, 'somecode', '.svn')) self.write_file((self.tmp_dir, 'somecode', '.svn', 'ok.py'), 'xxx') os.mkdir(join(self.tmp_dir, 'somecode', '.hg')) self.write_file((self.tmp_dir, 'somecode', '.hg', 'ok'), 'xxx') os.mkdir(join(self.tmp_dir, 'somecode', '.git')) self.write_file((self.tmp_dir, 'somecode', '.git', 'ok'), 'xxx') # now building a sdist dist, cmd = self.get_cmd() # zip is available universally # (tar might not be installed under win32) cmd.formats = ['zip'] cmd.ensure_finalized() cmd.run() # now let's check what we have dist_folder = join(self.tmp_dir, 'dist') files = os.listdir(dist_folder) self.assertEqual(files, ['fake-1.0.zip']) zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip')) try: content = zip_file.namelist() finally: zip_file.close() # making sure everything has been pruned correctly self.assertEqual(len(content), 4) @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') def test_make_distribution(self): # check if tar and gzip are installed if (find_executable('tar') is None or find_executable('gzip') is None): return # now building a sdist dist, cmd = self.get_cmd() # creating a gztar then a tar cmd.formats = ['gztar', 'tar'] cmd.ensure_finalized() cmd.run() # making sure we have two files dist_folder = join(self.tmp_dir, 'dist') result = os.listdir(dist_folder) result.sort() self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz'] ) os.remove(join(dist_folder, 'fake-1.0.tar')) os.remove(join(dist_folder, 'fake-1.0.tar.gz')) # now trying a tar then a gztar cmd.formats = ['tar', 'gztar'] cmd.ensure_finalized() cmd.run() result = os.listdir(dist_folder) result.sort() self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz']) @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') def test_add_defaults(self): # http://bugs.python.org/issue2279 # add_default should also include # data_files and package_data dist, cmd = self.get_cmd() # filling data_files by pointing files # in package_data dist.package_data = {'': ['*.cfg', '*.dat'], 'somecode': ['*.txt']} self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') self.write_file((self.tmp_dir, 'somecode', 'doc.dat'), '#') # adding some data in data_files data_dir = join(self.tmp_dir, 'data') os.mkdir(data_dir) self.write_file((data_dir, 'data.dt'), '#') some_dir = join(self.tmp_dir, 'some') os.mkdir(some_dir) self.write_file((self.tmp_dir, 'inroot.txt'), '#') self.write_file((some_dir, 'file.txt'), '#') self.write_file((some_dir, 'other_file.txt'), '#') dist.data_files = [('data', ['data/data.dt', 'inroot.txt', 'notexisting']), 'some/file.txt', 'some/other_file.txt'] # adding a script script_dir = join(self.tmp_dir, 'scripts') os.mkdir(script_dir) self.write_file((script_dir, 'script.py'), '#') dist.scripts = [join('scripts', 'script.py')] cmd.formats = ['zip'] cmd.use_defaults = True cmd.ensure_finalized() cmd.run() # now let's check what we have dist_folder = join(self.tmp_dir, 'dist') files = os.listdir(dist_folder) self.assertEqual(files, ['fake-1.0.zip']) zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip')) try: content = zip_file.namelist() finally: zip_file.close() # making sure everything was added self.assertEqual(len(content), 11) # checking the MANIFEST f = open(join(self.tmp_dir, 'MANIFEST')) try: manifest = f.read() self.assertEqual(manifest, MANIFEST % {'sep': os.sep}) finally: f.close() @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') def test_metadata_check_option(self): # testing the `medata-check` option dist, cmd = self.get_cmd(metadata={}) # this should raise some warnings ! # with the `check` subcommand cmd.ensure_finalized() cmd.run() warnings = self.get_logs(WARN) self.assertEqual(len(warnings), 2) # trying with a complete set of metadata self.clear_logs() dist, cmd = self.get_cmd() cmd.ensure_finalized() cmd.metadata_check = 0 cmd.run() warnings = self.get_logs(WARN) self.assertEqual(len(warnings), 0) def test_check_metadata_deprecated(self): # makes sure make_metadata is deprecated dist, cmd = self.get_cmd() with check_warnings() as w: warnings.simplefilter("always") cmd.check_metadata() self.assertEqual(len(w.warnings), 1) def test_show_formats(self): with captured_stdout() as stdout: show_formats() # the output should be a header line + one line per format num_formats = len(ARCHIVE_FORMATS.keys()) output = [line for line in stdout.getvalue().split('\n') if line.strip().startswith('--formats=')] self.assertEqual(len(output), num_formats) def test_finalize_options(self): dist, cmd = self.get_cmd() cmd.finalize_options() # default options set by finalize self.assertEqual(cmd.manifest, 'MANIFEST') self.assertEqual(cmd.template, 'MANIFEST.in') self.assertEqual(cmd.dist_dir, 'dist') # formats has to be a string splitable on (' ', ',') or # a stringlist cmd.formats = 1 self.assertRaises(DistutilsOptionError, cmd.finalize_options) cmd.formats = ['zip'] cmd.finalize_options() # formats has to be known cmd.formats = 'supazipa' self.assertRaises(DistutilsOptionError, cmd.finalize_options) @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') def test_get_file_list(self): # make sure MANIFEST is recalculated dist, cmd = self.get_cmd() # filling data_files by pointing files in package_data dist.package_data = {'somecode': ['*.txt']} self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#') cmd.ensure_finalized() cmd.run() f = open(cmd.manifest) try: manifest = [line.strip() for line in f.read().split('\n') if line.strip() != ''] finally: f.close() self.assertEqual(len(manifest), 5) # adding a file self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#') # make sure build_py is reinitialized, like a fresh run build_py = dist.get_command_obj('build_py') build_py.finalized = False build_py.ensure_finalized() cmd.run() f = open(cmd.manifest) try: manifest2 = [line.strip() for line in f.read().split('\n') if line.strip() != ''] finally: f.close() # do we have the new file in MANIFEST ? self.assertEqual(len(manifest2), 6) self.assertIn('doc2.txt', manifest2[-1]) @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') def test_manifest_marker(self): # check that autogenerated MANIFESTs have a marker dist, cmd = self.get_cmd() cmd.ensure_finalized() cmd.run() f = open(cmd.manifest) try: manifest = [line.strip() for line in f.read().split('\n') if line.strip() != ''] finally: f.close() self.assertEqual(manifest[0], '# file GENERATED by distutils, do NOT edit') @unittest.skipUnless(ZLIB_SUPPORT, "Need zlib support to run") def test_manifest_comments(self): # make sure comments don't cause exceptions or wrong includes contents = dedent("""\ # bad.py #bad.py good.py """) dist, cmd = self.get_cmd() cmd.ensure_finalized() self.write_file((self.tmp_dir, cmd.manifest), contents) self.write_file((self.tmp_dir, 'good.py'), '# pick me!') self.write_file((self.tmp_dir, 'bad.py'), "# don't pick me!") self.write_file((self.tmp_dir, '#bad.py'), "# don't pick me!") cmd.run() self.assertEqual(cmd.filelist.files, ['good.py']) @unittest.skipUnless(ZLIB_SUPPORT, 'Need zlib support to run') def test_manual_manifest(self): # check that a MANIFEST without a marker is left alone dist, cmd = self.get_cmd() cmd.formats = ['gztar'] cmd.ensure_finalized() self.write_file((self.tmp_dir, cmd.manifest), 'README.manual') self.write_file((self.tmp_dir, 'README.manual'), 'This project maintains its MANIFEST file itself.') cmd.run() self.assertEqual(cmd.filelist.files, ['README.manual']) f = open(cmd.manifest) try: manifest = [line.strip() for line in f.read().split('\n') if line.strip() != ''] finally: f.close() self.assertEqual(manifest, ['README.manual']) archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz') archive = tarfile.open(archive_name) try: filenames = [tarinfo.name for tarinfo in archive] finally: archive.close() self.assertEqual(sorted(filenames), ['fake-1.0', 'fake-1.0/PKG-INFO', 'fake-1.0/README.manual']) def test_suite(): return unittest.makeSuite(SDistTestCase) if __name__ == "__main__": run_unittest(test_suite())
tuxfux-hlp-notes/python-batches
refs/heads/master
archieves/batch-62/files/myenv/lib/python2.7/site-packages/pip/wheel.py
338
""" Support for installing and building the "wheel" binary package format. """ from __future__ import absolute_import import compileall import csv import errno import functools import hashlib import logging import os import os.path import re import shutil import stat import sys import tempfile import warnings from base64 import urlsafe_b64encode from email.parser import Parser from pip._vendor.six import StringIO import pip from pip.compat import expanduser from pip.download import path_to_url, unpack_url from pip.exceptions import ( InstallationError, InvalidWheelFilename, UnsupportedWheel) from pip.locations import distutils_scheme, PIP_DELETE_MARKER_FILENAME from pip import pep425tags from pip.utils import ( call_subprocess, ensure_dir, captured_stdout, rmtree, read_chunks, ) from pip.utils.ui import open_spinner from pip.utils.logging import indent_log from pip.utils.setuptools_build import SETUPTOOLS_SHIM from pip._vendor.distlib.scripts import ScriptMaker from pip._vendor import pkg_resources from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.six.moves import configparser wheel_ext = '.whl' VERSION_COMPATIBLE = (1, 0) logger = logging.getLogger(__name__) class WheelCache(object): """A cache of wheels for future installs.""" def __init__(self, cache_dir, format_control): """Create a wheel cache. :param cache_dir: The root of the cache. :param format_control: A pip.index.FormatControl object to limit binaries being read from the cache. """ self._cache_dir = expanduser(cache_dir) if cache_dir else None self._format_control = format_control def cached_wheel(self, link, package_name): return cached_wheel( self._cache_dir, link, self._format_control, package_name) def _cache_for_link(cache_dir, link): """ Return a directory to store cached wheels in for link. Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param cache_dir: The cache_dir being used by pip. :param link: The link of the sdist for which this will cache wheels. """ # We want to generate an url to use as our cache key, we don't want to just # re-use the URL because it might have other items in the fragment and we # don't care about those. key_parts = [link.url_without_fragment] if link.hash_name is not None and link.hash is not None: key_parts.append("=".join([link.hash_name, link.hash])) key_url = "#".join(key_parts) # Encode our key url with sha224, we'll use this because it has similar # security properties to sha256, but with a shorter total output (and thus # less secure). However the differences don't make a lot of difference for # our use case here. hashed = hashlib.sha224(key_url.encode()).hexdigest() # We want to nest the directories some to prevent having a ton of top level # directories where we might run out of sub directories on some FS. parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]] # Inside of the base location for cached wheels, expand our parts and join # them all together. return os.path.join(cache_dir, "wheels", *parts) def cached_wheel(cache_dir, link, format_control, package_name): if not cache_dir: return link if not link: return link if link.is_wheel: return link if not link.is_artifact: return link if not package_name: return link canonical_name = canonicalize_name(package_name) formats = pip.index.fmt_ctl_formats(format_control, canonical_name) if "binary" not in formats: return link root = _cache_for_link(cache_dir, link) try: wheel_names = os.listdir(root) except OSError as e: if e.errno in (errno.ENOENT, errno.ENOTDIR): return link raise candidates = [] for wheel_name in wheel_names: try: wheel = Wheel(wheel_name) except InvalidWheelFilename: continue if not wheel.supported(): # Built for a different python/arch/etc continue candidates.append((wheel.support_index_min(), wheel_name)) if not candidates: return link candidates.sort() path = os.path.join(root, candidates[0][1]) return pip.index.Link(path_to_url(path)) def rehash(path, algo='sha256', blocksize=1 << 20): """Return (hash, length) for path using hashlib.new(algo)""" h = hashlib.new(algo) length = 0 with open(path, 'rb') as f: for block in read_chunks(f, size=blocksize): length += len(block) h.update(block) digest = 'sha256=' + urlsafe_b64encode( h.digest() ).decode('latin1').rstrip('=') return (digest, length) def open_for_csv(name, mode): if sys.version_info[0] < 3: nl = {} bin = 'b' else: nl = {'newline': ''} bin = '' return open(name, mode + bin, **nl) def fix_script(path): """Replace #!python with #!/path/to/python Return True if file was changed.""" # XXX RECORD hashes will need to be updated if os.path.isfile(path): with open(path, 'rb') as script: firstline = script.readline() if not firstline.startswith(b'#!python'): return False exename = sys.executable.encode(sys.getfilesystemencoding()) firstline = b'#!' + exename + os.linesep.encode("ascii") rest = script.read() with open(path, 'wb') as script: script.write(firstline) script.write(rest) return True dist_info_re = re.compile(r"""^(?P<namever>(?P<name>.+?)(-(?P<ver>\d.+?))?) \.dist-info$""", re.VERBOSE) def root_is_purelib(name, wheeldir): """ Return True if the extracted wheel in wheeldir should go into purelib. """ name_folded = name.replace("-", "_") for item in os.listdir(wheeldir): match = dist_info_re.match(item) if match and match.group('name') == name_folded: with open(os.path.join(wheeldir, item, 'WHEEL')) as wheel: for line in wheel: line = line.lower().rstrip() if line == "root-is-purelib: true": return True return False def get_entrypoints(filename): if not os.path.exists(filename): return {}, {} # This is done because you can pass a string to entry_points wrappers which # means that they may or may not be valid INI files. The attempt here is to # strip leading and trailing whitespace in order to make them valid INI # files. with open(filename) as fp: data = StringIO() for line in fp: data.write(line.strip()) data.write("\n") data.seek(0) cp = configparser.RawConfigParser() cp.optionxform = lambda option: option cp.readfp(data) console = {} gui = {} if cp.has_section('console_scripts'): console = dict(cp.items('console_scripts')) if cp.has_section('gui_scripts'): gui = dict(cp.items('gui_scripts')) return console, gui def move_wheel_files(name, req, wheeldir, user=False, home=None, root=None, pycompile=True, scheme=None, isolated=False, prefix=None): """Install a wheel""" if not scheme: scheme = distutils_scheme( name, user=user, home=home, root=root, isolated=isolated, prefix=prefix, ) if root_is_purelib(name, wheeldir): lib_dir = scheme['purelib'] else: lib_dir = scheme['platlib'] info_dir = [] data_dirs = [] source = wheeldir.rstrip(os.path.sep) + os.path.sep # Record details of the files moved # installed = files copied from the wheel to the destination # changed = files changed while installing (scripts #! line typically) # generated = files newly generated during the install (script wrappers) installed = {} changed = set() generated = [] # Compile all of the pyc files that we're going to be installing if pycompile: with captured_stdout() as stdout: with warnings.catch_warnings(): warnings.filterwarnings('ignore') compileall.compile_dir(source, force=True, quiet=True) logger.debug(stdout.getvalue()) def normpath(src, p): return os.path.relpath(src, p).replace(os.path.sep, '/') def record_installed(srcfile, destfile, modified=False): """Map archive RECORD paths to installation RECORD paths.""" oldpath = normpath(srcfile, wheeldir) newpath = normpath(destfile, lib_dir) installed[oldpath] = newpath if modified: changed.add(destfile) def clobber(source, dest, is_base, fixer=None, filter=None): ensure_dir(dest) # common for the 'include' path for dir, subdirs, files in os.walk(source): basedir = dir[len(source):].lstrip(os.path.sep) destdir = os.path.join(dest, basedir) if is_base and basedir.split(os.path.sep, 1)[0].endswith('.data'): continue for s in subdirs: destsubdir = os.path.join(dest, basedir, s) if is_base and basedir == '' and destsubdir.endswith('.data'): data_dirs.append(s) continue elif (is_base and s.endswith('.dist-info') and canonicalize_name(s).startswith( canonicalize_name(req.name))): assert not info_dir, ('Multiple .dist-info directories: ' + destsubdir + ', ' + ', '.join(info_dir)) info_dir.append(destsubdir) for f in files: # Skip unwanted files if filter and filter(f): continue srcfile = os.path.join(dir, f) destfile = os.path.join(dest, basedir, f) # directory creation is lazy and after the file filtering above # to ensure we don't install empty dirs; empty dirs can't be # uninstalled. ensure_dir(destdir) # We use copyfile (not move, copy, or copy2) to be extra sure # that we are not moving directories over (copyfile fails for # directories) as well as to ensure that we are not copying # over any metadata because we want more control over what # metadata we actually copy over. shutil.copyfile(srcfile, destfile) # Copy over the metadata for the file, currently this only # includes the atime and mtime. st = os.stat(srcfile) if hasattr(os, "utime"): os.utime(destfile, (st.st_atime, st.st_mtime)) # If our file is executable, then make our destination file # executable. if os.access(srcfile, os.X_OK): st = os.stat(srcfile) permissions = ( st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH ) os.chmod(destfile, permissions) changed = False if fixer: changed = fixer(destfile) record_installed(srcfile, destfile, changed) clobber(source, lib_dir, True) assert info_dir, "%s .dist-info directory not found" % req # Get the defined entry points ep_file = os.path.join(info_dir[0], 'entry_points.txt') console, gui = get_entrypoints(ep_file) def is_entrypoint_wrapper(name): # EP, EP.exe and EP-script.py are scripts generated for # entry point EP by setuptools if name.lower().endswith('.exe'): matchname = name[:-4] elif name.lower().endswith('-script.py'): matchname = name[:-10] elif name.lower().endswith(".pya"): matchname = name[:-4] else: matchname = name # Ignore setuptools-generated scripts return (matchname in console or matchname in gui) for datadir in data_dirs: fixer = None filter = None for subdir in os.listdir(os.path.join(wheeldir, datadir)): fixer = None if subdir == 'scripts': fixer = fix_script filter = is_entrypoint_wrapper source = os.path.join(wheeldir, datadir, subdir) dest = scheme[subdir] clobber(source, dest, False, fixer=fixer, filter=filter) maker = ScriptMaker(None, scheme['scripts']) # Ensure old scripts are overwritten. # See https://github.com/pypa/pip/issues/1800 maker.clobber = True # Ensure we don't generate any variants for scripts because this is almost # never what somebody wants. # See https://bitbucket.org/pypa/distlib/issue/35/ maker.variants = set(('', )) # This is required because otherwise distlib creates scripts that are not # executable. # See https://bitbucket.org/pypa/distlib/issue/32/ maker.set_mode = True # Simplify the script and fix the fact that the default script swallows # every single stack trace. # See https://bitbucket.org/pypa/distlib/issue/34/ # See https://bitbucket.org/pypa/distlib/issue/33/ def _get_script_text(entry): if entry.suffix is None: raise InstallationError( "Invalid script entry point: %s for req: %s - A callable " "suffix is required. Cf https://packaging.python.org/en/" "latest/distributing.html#console-scripts for more " "information." % (entry, req) ) return maker.script_template % { "module": entry.prefix, "import_name": entry.suffix.split(".")[0], "func": entry.suffix, } maker._get_script_text = _get_script_text maker.script_template = """# -*- coding: utf-8 -*- import re import sys from %(module)s import %(import_name)s if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(%(func)s()) """ # Special case pip and setuptools to generate versioned wrappers # # The issue is that some projects (specifically, pip and setuptools) use # code in setup.py to create "versioned" entry points - pip2.7 on Python # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into # the wheel metadata at build time, and so if the wheel is installed with # a *different* version of Python the entry points will be wrong. The # correct fix for this is to enhance the metadata to be able to describe # such versioned entry points, but that won't happen till Metadata 2.0 is # available. # In the meantime, projects using versioned entry points will either have # incorrect versioned entry points, or they will not be able to distribute # "universal" wheels (i.e., they will need a wheel per Python version). # # Because setuptools and pip are bundled with _ensurepip and virtualenv, # we need to use universal wheels. So, as a stopgap until Metadata 2.0, we # override the versioned entry points in the wheel and generate the # correct ones. This code is purely a short-term measure until Metadata 2.0 # is available. # # To add the level of hack in this section of code, in order to support # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment # variable which will control which version scripts get installed. # # ENSUREPIP_OPTIONS=altinstall # - Only pipX.Y and easy_install-X.Y will be generated and installed # ENSUREPIP_OPTIONS=install # - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note # that this option is technically if ENSUREPIP_OPTIONS is set and is # not altinstall # DEFAULT # - The default behavior is to install pip, pipX, pipX.Y, easy_install # and easy_install-X.Y. pip_script = console.pop('pip', None) if pip_script: if "ENSUREPIP_OPTIONS" not in os.environ: spec = 'pip = ' + pip_script generated.extend(maker.make(spec)) if os.environ.get("ENSUREPIP_OPTIONS", "") != "altinstall": spec = 'pip%s = %s' % (sys.version[:1], pip_script) generated.extend(maker.make(spec)) spec = 'pip%s = %s' % (sys.version[:3], pip_script) generated.extend(maker.make(spec)) # Delete any other versioned pip entry points pip_ep = [k for k in console if re.match(r'pip(\d(\.\d)?)?$', k)] for k in pip_ep: del console[k] easy_install_script = console.pop('easy_install', None) if easy_install_script: if "ENSUREPIP_OPTIONS" not in os.environ: spec = 'easy_install = ' + easy_install_script generated.extend(maker.make(spec)) spec = 'easy_install-%s = %s' % (sys.version[:3], easy_install_script) generated.extend(maker.make(spec)) # Delete any other versioned easy_install entry points easy_install_ep = [ k for k in console if re.match(r'easy_install(-\d\.\d)?$', k) ] for k in easy_install_ep: del console[k] # Generate the console and GUI entry points specified in the wheel if len(console) > 0: generated.extend( maker.make_multiple(['%s = %s' % kv for kv in console.items()]) ) if len(gui) > 0: generated.extend( maker.make_multiple( ['%s = %s' % kv for kv in gui.items()], {'gui': True} ) ) # Record pip as the installer installer = os.path.join(info_dir[0], 'INSTALLER') temp_installer = os.path.join(info_dir[0], 'INSTALLER.pip') with open(temp_installer, 'wb') as installer_file: installer_file.write(b'pip\n') shutil.move(temp_installer, installer) generated.append(installer) # Record details of all files installed record = os.path.join(info_dir[0], 'RECORD') temp_record = os.path.join(info_dir[0], 'RECORD.pip') with open_for_csv(record, 'r') as record_in: with open_for_csv(temp_record, 'w+') as record_out: reader = csv.reader(record_in) writer = csv.writer(record_out) for row in reader: row[0] = installed.pop(row[0], row[0]) if row[0] in changed: row[1], row[2] = rehash(row[0]) writer.writerow(row) for f in generated: h, l = rehash(f) writer.writerow((normpath(f, lib_dir), h, l)) for f in installed: writer.writerow((installed[f], '', '')) shutil.move(temp_record, record) def _unique(fn): @functools.wraps(fn) def unique(*args, **kw): seen = set() for item in fn(*args, **kw): if item not in seen: seen.add(item) yield item return unique # TODO: this goes somewhere besides the wheel module @_unique def uninstallation_paths(dist): """ Yield all the uninstallation paths for dist based on RECORD-without-.pyc Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc in the same directory. UninstallPathSet.add() takes care of the __pycache__ .pyc. """ from pip.utils import FakeFile # circular import r = csv.reader(FakeFile(dist.get_metadata_lines('RECORD'))) for row in r: path = os.path.join(dist.location, row[0]) yield path if path.endswith('.py'): dn, fn = os.path.split(path) base = fn[:-3] path = os.path.join(dn, base + '.pyc') yield path def wheel_version(source_dir): """ Return the Wheel-Version of an extracted wheel, if possible. Otherwise, return False if we couldn't parse / extract it. """ try: dist = [d for d in pkg_resources.find_on_path(None, source_dir)][0] wheel_data = dist.get_metadata('WHEEL') wheel_data = Parser().parsestr(wheel_data) version = wheel_data['Wheel-Version'].strip() version = tuple(map(int, version.split('.'))) return version except: return False def check_compatibility(version, name): """ Raises errors or warns if called with an incompatible Wheel-Version. Pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given """ if not version: raise UnsupportedWheel( "%s is in an unsupported or invalid wheel" % name ) if version[0] > VERSION_COMPATIBLE[0]: raise UnsupportedWheel( "%s's Wheel-Version (%s) is not compatible with this version " "of pip" % (name, '.'.join(map(str, version))) ) elif version > VERSION_COMPATIBLE: logger.warning( 'Installing from a newer Wheel-Version (%s)', '.'.join(map(str, version)), ) class Wheel(object): """A wheel file""" # TODO: maybe move the install code into this class wheel_file_re = re.compile( r"""^(?P<namever>(?P<name>.+?)-(?P<ver>\d.*?)) ((-(?P<build>\d.*?))?-(?P<pyver>.+?)-(?P<abi>.+?)-(?P<plat>.+?) \.whl|\.dist-info)$""", re.VERBOSE ) def __init__(self, filename): """ :raises InvalidWheelFilename: when the filename is invalid for a wheel """ wheel_info = self.wheel_file_re.match(filename) if not wheel_info: raise InvalidWheelFilename( "%s is not a valid wheel filename." % filename ) self.filename = filename self.name = wheel_info.group('name').replace('_', '-') # we'll assume "_" means "-" due to wheel naming scheme # (https://github.com/pypa/pip/issues/1150) self.version = wheel_info.group('ver').replace('_', '-') self.pyversions = wheel_info.group('pyver').split('.') self.abis = wheel_info.group('abi').split('.') self.plats = wheel_info.group('plat').split('.') # All the tag combinations from this file self.file_tags = set( (x, y, z) for x in self.pyversions for y in self.abis for z in self.plats ) def support_index_min(self, tags=None): """ Return the lowest index that one of the wheel's file_tag combinations achieves in the supported_tags list e.g. if there are 8 supported tags, and one of the file tags is first in the list, then return 0. Returns None is the wheel is not supported. """ if tags is None: # for mock tags = pep425tags.supported_tags indexes = [tags.index(c) for c in self.file_tags if c in tags] return min(indexes) if indexes else None def supported(self, tags=None): """Is this wheel supported on this system?""" if tags is None: # for mock tags = pep425tags.supported_tags return bool(set(tags).intersection(self.file_tags)) class WheelBuilder(object): """Build wheels from a RequirementSet.""" def __init__(self, requirement_set, finder, build_options=None, global_options=None): self.requirement_set = requirement_set self.finder = finder self._cache_root = requirement_set._wheel_cache._cache_dir self._wheel_dir = requirement_set.wheel_download_dir self.build_options = build_options or [] self.global_options = global_options or [] def _build_one(self, req, output_dir, python_tag=None): """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ tempd = tempfile.mkdtemp('pip-wheel-') try: if self.__build_one(req, tempd, python_tag=python_tag): try: wheel_name = os.listdir(tempd)[0] wheel_path = os.path.join(output_dir, wheel_name) shutil.move(os.path.join(tempd, wheel_name), wheel_path) logger.info('Stored in directory: %s', output_dir) return wheel_path except: pass # Ignore return, we can't do anything else useful. self._clean_one(req) return None finally: rmtree(tempd) def _base_setup_args(self, req): return [ sys.executable, "-u", '-c', SETUPTOOLS_SHIM % req.setup_py ] + list(self.global_options) def __build_one(self, req, tempd, python_tag=None): base_args = self._base_setup_args(req) spin_message = 'Running setup.py bdist_wheel for %s' % (req.name,) with open_spinner(spin_message) as spinner: logger.debug('Destination directory: %s', tempd) wheel_args = base_args + ['bdist_wheel', '-d', tempd] \ + self.build_options if python_tag is not None: wheel_args += ["--python-tag", python_tag] try: call_subprocess(wheel_args, cwd=req.setup_py_dir, show_stdout=False, spinner=spinner) return True except: spinner.finish("error") logger.error('Failed building wheel for %s', req.name) return False def _clean_one(self, req): base_args = self._base_setup_args(req) logger.info('Running setup.py clean for %s', req.name) clean_args = base_args + ['clean', '--all'] try: call_subprocess(clean_args, cwd=req.source_dir, show_stdout=False) return True except: logger.error('Failed cleaning build dir for %s', req.name) return False def build(self, autobuilding=False): """Build wheels. :param unpack: If True, replace the sdist we built from with the newly built wheel, in preparation for installation. :return: True if all the wheels built correctly. """ assert self._wheel_dir or (autobuilding and self._cache_root) # unpack sdists and constructs req set self.requirement_set.prepare_files(self.finder) reqset = self.requirement_set.requirements.values() buildset = [] for req in reqset: if req.constraint: continue if req.is_wheel: if not autobuilding: logger.info( 'Skipping %s, due to already being wheel.', req.name) elif autobuilding and req.editable: pass elif autobuilding and req.link and not req.link.is_artifact: pass elif autobuilding and not req.source_dir: pass else: if autobuilding: link = req.link base, ext = link.splitext() if pip.index.egg_info_matches(base, None, link) is None: # Doesn't look like a package - don't autobuild a wheel # because we'll have no way to lookup the result sanely continue if "binary" not in pip.index.fmt_ctl_formats( self.finder.format_control, canonicalize_name(req.name)): logger.info( "Skipping bdist_wheel for %s, due to binaries " "being disabled for it.", req.name) continue buildset.append(req) if not buildset: return True # Build the wheels. logger.info( 'Building wheels for collected packages: %s', ', '.join([req.name for req in buildset]), ) with indent_log(): build_success, build_failure = [], [] for req in buildset: python_tag = None if autobuilding: python_tag = pep425tags.implementation_tag output_dir = _cache_for_link(self._cache_root, req.link) try: ensure_dir(output_dir) except OSError as e: logger.warning("Building wheel for %s failed: %s", req.name, e) build_failure.append(req) continue else: output_dir = self._wheel_dir wheel_file = self._build_one( req, output_dir, python_tag=python_tag, ) if wheel_file: build_success.append(req) if autobuilding: # XXX: This is mildly duplicative with prepare_files, # but not close enough to pull out to a single common # method. # The code below assumes temporary source dirs - # prevent it doing bad things. if req.source_dir and not os.path.exists(os.path.join( req.source_dir, PIP_DELETE_MARKER_FILENAME)): raise AssertionError( "bad source dir - missing marker") # Delete the source we built the wheel from req.remove_temporary_source() # set the build directory again - name is known from # the work prepare_files did. req.source_dir = req.build_location( self.requirement_set.build_dir) # Update the link for this. req.link = pip.index.Link( path_to_url(wheel_file)) assert req.link.is_wheel # extract the wheel into the dir unpack_url( req.link, req.source_dir, None, False, session=self.requirement_set.session) else: build_failure.append(req) # notify success/failure if build_success: logger.info( 'Successfully built %s', ' '.join([req.name for req in build_success]), ) if build_failure: logger.info( 'Failed to build %s', ' '.join([req.name for req in build_failure]), ) # Return True if all builds were successful return len(build_failure) == 0
NielsZeilemaker/incubator-airflow
refs/heads/master
airflow/hooks/hive_hooks.py
22
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function from builtins import zip from past.builtins import basestring import collections import unicodecsv as csv import itertools import logging import re import subprocess import time from tempfile import NamedTemporaryFile import hive_metastore from airflow.exceptions import AirflowException from airflow.hooks.base_hook import BaseHook from airflow.utils.helpers import as_flattened_list from airflow.utils.file import TemporaryDirectory from airflow import configuration import airflow.security.utils as utils HIVE_QUEUE_PRIORITIES = ['VERY_HIGH', 'HIGH', 'NORMAL', 'LOW', 'VERY_LOW'] class HiveCliHook(BaseHook): """Simple wrapper around the hive CLI. It also supports the ``beeline`` a lighter CLI that runs JDBC and is replacing the heavier traditional CLI. To enable ``beeline``, set the use_beeline param in the extra field of your connection as in ``{ "use_beeline": true }`` Note that you can also set default hive CLI parameters using the ``hive_cli_params`` to be used in your connection as in ``{"hive_cli_params": "-hiveconf mapred.job.tracker=some.jobtracker:444"}`` Parameters passed here can be overridden by run_cli's hive_conf param The extra connection parameter ``auth`` gets passed as in the ``jdbc`` connection string as is. :param mapred_queue: queue used by the Hadoop Scheduler (Capacity or Fair) :type mapred_queue: string :param mapred_queue_priority: priority within the job queue. Possible settings include: VERY_HIGH, HIGH, NORMAL, LOW, VERY_LOW :type mapred_queue_priority: string :param mapred_job_name: This name will appear in the jobtracker. This can make monitoring easier. :type mapred_job_name: string """ def __init__( self, hive_cli_conn_id="hive_cli_default", run_as=None, mapred_queue=None, mapred_queue_priority=None, mapred_job_name=None): conn = self.get_connection(hive_cli_conn_id) self.hive_cli_params = conn.extra_dejson.get('hive_cli_params', '') self.use_beeline = conn.extra_dejson.get('use_beeline', False) self.auth = conn.extra_dejson.get('auth', 'noSasl') self.conn = conn self.run_as = run_as if mapred_queue_priority: mapred_queue_priority = mapred_queue_priority.upper() if mapred_queue_priority not in HIVE_QUEUE_PRIORITIES: raise AirflowException( "Invalid Mapred Queue Priority. Valid values are: " "{}".format(', '.join(HIVE_QUEUE_PRIORITIES))) self.mapred_queue = mapred_queue self.mapred_queue_priority = mapred_queue_priority self.mapred_job_name = mapred_job_name def _prepare_cli_cmd(self): """ This function creates the command list from available information """ conn = self.conn hive_bin = 'hive' cmd_extra = [] if self.use_beeline: hive_bin = 'beeline' jdbc_url = "jdbc:hive2://{conn.host}:{conn.port}/{conn.schema}" if configuration.get('core', 'security') == 'kerberos': template = conn.extra_dejson.get( 'principal', "hive/_HOST@EXAMPLE.COM") if "_HOST" in template: template = utils.replace_hostname_pattern( utils.get_components(template)) proxy_user = "" # noqa if conn.extra_dejson.get('proxy_user') == "login" and conn.login: proxy_user = "hive.server2.proxy.user={0}".format(conn.login) elif conn.extra_dejson.get('proxy_user') == "owner" and self.run_as: proxy_user = "hive.server2.proxy.user={0}".format(self.run_as) jdbc_url += ";principal={template};{proxy_user}" elif self.auth: jdbc_url += ";auth=" + self.auth jdbc_url = jdbc_url.format(**locals()) cmd_extra += ['-u', jdbc_url] if conn.login: cmd_extra += ['-n', conn.login] if conn.password: cmd_extra += ['-p', conn.password] hive_params_list = self.hive_cli_params.split() return [hive_bin] + cmd_extra + hive_params_list def _prepare_hiveconf(self, d): """ This function prepares a list of hiveconf params from a dictionary of key value pairs. :param d: :type d: dict >>> hh = HiveCliHook() >>> hive_conf = {"hive.exec.dynamic.partition": "true", ... "hive.exec.dynamic.partition.mode": "nonstrict"} >>> hh._prepare_hiveconf(hive_conf) ["-hiveconf", "hive.exec.dynamic.partition=true",\ "-hiveconf", "hive.exec.dynamic.partition.mode=nonstrict"] """ if not d: return [] return as_flattened_list( itertools.izip( ["-hiveconf"] * len(d), ["{}={}".format(k, v) for k, v in d.items()] ) ) def run_cli(self, hql, schema=None, verbose=True, hive_conf=None): """ Run an hql statement using the hive cli. If hive_conf is specified it should be a dict and the entries will be set as key/value pairs in HiveConf :param hive_conf: if specified these key value pairs will be passed to hive as ``-hiveconf "key"="value"``. Note that they will be passed after the ``hive_cli_params`` and thus will override whatever values are specified in the database. :type hive_conf: dict >>> hh = HiveCliHook() >>> result = hh.run_cli("USE airflow;") >>> ("OK" in result) True """ conn = self.conn schema = schema or conn.schema if schema: hql = "USE {schema};\n{hql}".format(**locals()) with TemporaryDirectory(prefix='airflow_hiveop_') as tmp_dir: with NamedTemporaryFile(dir=tmp_dir) as f: f.write(hql.encode('UTF-8')) f.flush() hive_cmd = self._prepare_cli_cmd() hive_conf_params = self._prepare_hiveconf(hive_conf) if self.mapred_queue: hive_conf_params.extend( ['-hiveconf', 'mapreduce.job.queuename={}' .format(self.mapred_queue)]) if self.mapred_queue_priority: hive_conf_params.extend( ['-hiveconf', 'mapreduce.job.priority={}' .format(self.mapred_queue_priority)]) if self.mapred_job_name: hive_conf_params.extend( ['-hiveconf', 'mapred.job.name={}' .format(self.mapred_job_name)]) hive_cmd.extend(hive_conf_params) hive_cmd.extend(['-f', f.name]) if verbose: logging.info(" ".join(hive_cmd)) sp = subprocess.Popen( hive_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=tmp_dir) self.sp = sp stdout = '' while True: line = sp.stdout.readline() if not line: break stdout += line.decode('UTF-8') if verbose: logging.info(line.decode('UTF-8').strip()) sp.wait() if sp.returncode: raise AirflowException(stdout) return stdout def test_hql(self, hql): """ Test an hql statement using the hive cli and EXPLAIN """ create, insert, other = [], [], [] for query in hql.split(';'): # naive query_original = query query = query.lower().strip() if query.startswith('create table'): create.append(query_original) elif query.startswith(('set ', 'add jar ', 'create temporary function')): other.append(query_original) elif query.startswith('insert'): insert.append(query_original) other = ';'.join(other) for query_set in [create, insert]: for query in query_set: query_preview = ' '.join(query.split())[:50] logging.info("Testing HQL [{0} (...)]".format(query_preview)) if query_set == insert: query = other + '; explain ' + query else: query = 'explain ' + query try: self.run_cli(query, verbose=False) except AirflowException as e: message = e.args[0].split('\n')[-2] logging.info(message) error_loc = re.search('(\d+):(\d+)', message) if error_loc and error_loc.group(1).isdigit(): l = int(error_loc.group(1)) begin = max(l-2, 0) end = min(l+3, len(query.split('\n'))) context = '\n'.join(query.split('\n')[begin:end]) logging.info("Context :\n {0}".format(context)) else: logging.info("SUCCESS") def load_df( self, df, table, create=True, recreate=False, field_dict=None, delimiter=',', encoding='utf8', pandas_kwargs=None, **kwargs): """ Loads a pandas DataFrame into hive. Hive data types will be inferred if not passed but column names will not be sanitized. :param table: target Hive table, use dot notation to target a specific database :type table: str :param create: whether to create the table if it doesn't exist :type create: bool :param recreate: whether to drop and recreate the table at every execution :type recreate: bool :param field_dict: mapping from column name to hive data type :type field_dict: dict :param encoding: string encoding to use when writing DataFrame to file :type encoding: str :param pandas_kwargs: passed to DataFrame.to_csv :type pandas_kwargs: dict :param kwargs: passed to self.load_file """ def _infer_field_types_from_df(df): DTYPE_KIND_HIVE_TYPE = { 'b': 'BOOLEAN', # boolean 'i': 'BIGINT', # signed integer 'u': 'BIGINT', # unsigned integer 'f': 'DOUBLE', # floating-point 'c': 'STRING', # complex floating-point 'O': 'STRING', # object 'S': 'STRING', # (byte-)string 'U': 'STRING', # Unicode 'V': 'STRING' # void } return dict((col, DTYPE_KIND_HIVE_TYPE[dtype.kind]) for col, dtype in df.dtypes.iteritems()) if pandas_kwargs is None: pandas_kwargs = {} with TemporaryDirectory(prefix='airflow_hiveop_') as tmp_dir: with NamedTemporaryFile(dir=tmp_dir) as f: if field_dict is None and (create or recreate): field_dict = _infer_field_types_from_df(df) df.to_csv(f, sep=delimiter, **pandas_kwargs) return self.load_file(filepath=f.name, table=table, delimiter=delimiter, field_dict=field_dict, **kwargs) def load_file( self, filepath, table, delimiter=",", field_dict=None, create=True, overwrite=True, partition=None, recreate=False): """ Loads a local file into Hive Note that the table generated in Hive uses ``STORED AS textfile`` which isn't the most efficient serialization format. If a large amount of data is loaded and/or if the tables gets queried considerably, you may want to use this operator only to stage the data into a temporary table before loading it into its final destination using a ``HiveOperator``. :param table: target Hive table, use dot notation to target a specific database :type table: str :param create: whether to create the table if it doesn't exist :type create: bool :param recreate: whether to drop and recreate the table at every execution :type recreate: bool :param partition: target partition as a dict of partition columns and values :type partition: dict :param delimiter: field delimiter in the file :type delimiter: str """ hql = '' if recreate: hql += "DROP TABLE IF EXISTS {table};\n" if create or recreate: if field_dict is None: raise ValueError("Must provide a field dict when creating a table") fields = ",\n ".join( [k + ' ' + v for k, v in field_dict.items()]) hql += "CREATE TABLE IF NOT EXISTS {table} (\n{fields})\n" if partition: pfields = ",\n ".join( [p + " STRING" for p in partition]) hql += "PARTITIONED BY ({pfields})\n" hql += "ROW FORMAT DELIMITED\n" hql += "FIELDS TERMINATED BY '{delimiter}'\n" hql += "STORED AS textfile;" hql = hql.format(**locals()) logging.info(hql) self.run_cli(hql) hql = "LOAD DATA LOCAL INPATH '{filepath}' " if overwrite: hql += "OVERWRITE " hql += "INTO TABLE {table} " if partition: pvals = ", ".join( ["{0}='{1}'".format(k, v) for k, v in partition.items()]) hql += "PARTITION ({pvals});" hql = hql.format(**locals()) logging.info(hql) self.run_cli(hql) def kill(self): if hasattr(self, 'sp'): if self.sp.poll() is None: print("Killing the Hive job") self.sp.terminate() time.sleep(60) self.sp.kill() class HiveMetastoreHook(BaseHook): """ Wrapper to interact with the Hive Metastore""" def __init__(self, metastore_conn_id='metastore_default'): self.metastore_conn = self.get_connection(metastore_conn_id) self.metastore = self.get_metastore_client() def __getstate__(self): # This is for pickling to work despite the thirft hive client not # being pickable d = dict(self.__dict__) del d['metastore'] return d def __setstate__(self, d): self.__dict__.update(d) self.__dict__['metastore'] = self.get_metastore_client() def get_metastore_client(self): """ Returns a Hive thrift client. """ from thrift.transport import TSocket, TTransport from thrift.protocol import TBinaryProtocol from hive_service import ThriftHive ms = self.metastore_conn auth_mechanism = ms.extra_dejson.get('authMechanism', 'NOSASL') if configuration.get('core', 'security') == 'kerberos': auth_mechanism = ms.extra_dejson.get('authMechanism', 'GSSAPI') kerberos_service_name = ms.extra_dejson.get('kerberos_service_name', 'hive') socket = TSocket.TSocket(ms.host, ms.port) if configuration.get('core', 'security') == 'kerberos' and auth_mechanism == 'GSSAPI': try: import saslwrapper as sasl except ImportError: import sasl def sasl_factory(): sasl_client = sasl.Client() sasl_client.setAttr("host", ms.host) sasl_client.setAttr("service", kerberos_service_name) sasl_client.init() return sasl_client from thrift_sasl import TSaslClientTransport transport = TSaslClientTransport(sasl_factory, "GSSAPI", socket) else: transport = TTransport.TBufferedTransport(socket) protocol = TBinaryProtocol.TBinaryProtocol(transport) return ThriftHive.Client(protocol) def get_conn(self): return self.metastore def check_for_partition(self, schema, table, partition): """ Checks whether a partition exists :param schema: Name of hive schema (database) @table belongs to :type schema: string :param table: Name of hive table @partition belongs to :type schema: string :partition: Expression that matches the partitions to check for (eg `a = 'b' AND c = 'd'`) :type schema: string :rtype: boolean >>> hh = HiveMetastoreHook() >>> t = 'static_babynames_partitioned' >>> hh.check_for_partition('airflow', t, "ds='2015-01-01'") True """ self.metastore._oprot.trans.open() partitions = self.metastore.get_partitions_by_filter( schema, table, partition, 1) self.metastore._oprot.trans.close() if partitions: return True else: return False def check_for_named_partition(self, schema, table, partition_name): """ Checks whether a partition with a given name exists :param schema: Name of hive schema (database) @table belongs to :type schema: string :param table: Name of hive table @partition belongs to :type schema: string :partition: Name of the partitions to check for (eg `a=b/c=d`) :type schema: string :rtype: boolean >>> hh = HiveMetastoreHook() >>> t = 'static_babynames_partitioned' >>> hh.check_for_named_partition('airflow', t, "ds=2015-01-01") True >>> hh.check_for_named_partition('airflow', t, "ds=xxx") False """ self.metastore._oprot.trans.open() try: self.metastore.get_partition_by_name( schema, table, partition_name) return True except hive_metastore.ttypes.NoSuchObjectException: return False finally: self.metastore._oprot.trans.close() def get_table(self, table_name, db='default'): """Get a metastore table object >>> hh = HiveMetastoreHook() >>> t = hh.get_table(db='airflow', table_name='static_babynames') >>> t.tableName 'static_babynames' >>> [col.name for col in t.sd.cols] ['state', 'year', 'name', 'gender', 'num'] """ self.metastore._oprot.trans.open() if db == 'default' and '.' in table_name: db, table_name = table_name.split('.')[:2] table = self.metastore.get_table(dbname=db, tbl_name=table_name) self.metastore._oprot.trans.close() return table def get_tables(self, db, pattern='*'): """ Get a metastore table object """ self.metastore._oprot.trans.open() tables = self.metastore.get_tables(db_name=db, pattern=pattern) objs = self.metastore.get_table_objects_by_name(db, tables) self.metastore._oprot.trans.close() return objs def get_databases(self, pattern='*'): """ Get a metastore table object """ self.metastore._oprot.trans.open() dbs = self.metastore.get_databases(pattern) self.metastore._oprot.trans.close() return dbs def get_partitions( self, schema, table_name, filter=None): """ Returns a list of all partitions in a table. Works only for tables with less than 32767 (java short max val). For subpartitioned table, the number might easily exceed this. >>> hh = HiveMetastoreHook() >>> t = 'static_babynames_partitioned' >>> parts = hh.get_partitions(schema='airflow', table_name=t) >>> len(parts) 1 >>> parts [{'ds': '2015-01-01'}] """ self.metastore._oprot.trans.open() table = self.metastore.get_table(dbname=schema, tbl_name=table_name) if len(table.partitionKeys) == 0: raise AirflowException("The table isn't partitioned") else: if filter: parts = self.metastore.get_partitions_by_filter( db_name=schema, tbl_name=table_name, filter=filter, max_parts=32767) else: parts = self.metastore.get_partitions( db_name=schema, tbl_name=table_name, max_parts=32767) self.metastore._oprot.trans.close() pnames = [p.name for p in table.partitionKeys] return [dict(zip(pnames, p.values)) for p in parts] def max_partition(self, schema, table_name, field=None, filter=None): """ Returns the maximum value for all partitions in a table. Works only for tables that have a single partition key. For subpartitioned table, we recommend using signal tables. >>> hh = HiveMetastoreHook() >>> t = 'static_babynames_partitioned' >>> hh.max_partition(schema='airflow', table_name=t) '2015-01-01' """ parts = self.get_partitions(schema, table_name, filter) if not parts: return None elif len(parts[0]) == 1: field = list(parts[0].keys())[0] elif not field: raise AirflowException( "Please specify the field you want the max " "value for") return max([p[field] for p in parts]) def table_exists(self, table_name, db='default'): """ Check if table exists >>> hh = HiveMetastoreHook() >>> hh.table_exists(db='airflow', table_name='static_babynames') True >>> hh.table_exists(db='airflow', table_name='does_not_exist') False """ try: t = self.get_table(table_name, db) return True except Exception as e: return False class HiveServer2Hook(BaseHook): """ Wrapper around the impyla library Note that the default authMechanism is PLAIN, to override it you can specify it in the ``extra`` of your connection in the UI as in """ def __init__(self, hiveserver2_conn_id='hiveserver2_default'): self.hiveserver2_conn_id = hiveserver2_conn_id def get_conn(self, schema=None): db = self.get_connection(self.hiveserver2_conn_id) auth_mechanism = db.extra_dejson.get('authMechanism', 'PLAIN') kerberos_service_name = None if configuration.get('core', 'security') == 'kerberos': auth_mechanism = db.extra_dejson.get('authMechanism', 'GSSAPI') kerberos_service_name = db.extra_dejson.get('kerberos_service_name', 'hive') # impyla uses GSSAPI instead of KERBEROS as a auth_mechanism identifier if auth_mechanism == 'KERBEROS': logging.warning("Detected deprecated 'KERBEROS' for authMechanism for %s. Please use 'GSSAPI' instead", self.hiveserver2_conn_id) auth_mechanism = 'GSSAPI' from impala.dbapi import connect return connect( host=db.host, port=db.port, auth_mechanism=auth_mechanism, kerberos_service_name=kerberos_service_name, user=db.login, database=schema or db.schema or 'default') def get_results(self, hql, schema='default', arraysize=1000): from impala.error import ProgrammingError with self.get_conn(schema) as conn: if isinstance(hql, basestring): hql = [hql] results = { 'data': [], 'header': [], } cur = conn.cursor() for statement in hql: cur.execute(statement) records = [] try: # impala Lib raises when no results are returned # we're silencing here as some statements in the list # may be `SET` or DDL records = cur.fetchall() except ProgrammingError: logging.debug("get_results returned no records") if records: results = { 'data': records, 'header': cur.description, } return results def to_csv( self, hql, csv_filepath, schema='default', delimiter=',', lineterminator='\r\n', output_header=True, fetch_size=1000): schema = schema or 'default' with self.get_conn(schema) as conn: with conn.cursor() as cur: logging.info("Running query: " + hql) cur.execute(hql) schema = cur.description with open(csv_filepath, 'wb') as f: writer = csv.writer(f, delimiter=delimiter, lineterminator=lineterminator, encoding='utf-8') if output_header: writer.writerow([c[0] for c in cur.description]) i = 0 while True: rows = [row for row in cur.fetchmany(fetch_size) if row] if not rows: break writer.writerows(rows) i += len(rows) logging.info("Written {0} rows so far.".format(i)) logging.info("Done. Loaded a total of {0} rows.".format(i)) def get_records(self, hql, schema='default'): """ Get a set of records from a Hive query. >>> hh = HiveServer2Hook() >>> sql = "SELECT * FROM airflow.static_babynames LIMIT 100" >>> len(hh.get_records(sql)) 100 """ return self.get_results(hql, schema=schema)['data'] def get_pandas_df(self, hql, schema='default'): """ Get a pandas dataframe from a Hive query >>> hh = HiveServer2Hook() >>> sql = "SELECT * FROM airflow.static_babynames LIMIT 100" >>> df = hh.get_pandas_df(sql) >>> len(df.index) 100 """ import pandas as pd res = self.get_results(hql, schema=schema) df = pd.DataFrame(res['data']) df.columns = [c[0] for c in res['header']] return df
skuda/client-python
refs/heads/master
kubernetes/client/models/v1_container.py
1
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.6.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class V1Container(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, args=None, command=None, env=None, env_from=None, image=None, image_pull_policy=None, lifecycle=None, liveness_probe=None, name=None, ports=None, readiness_probe=None, resources=None, security_context=None, stdin=None, stdin_once=None, termination_message_path=None, termination_message_policy=None, tty=None, volume_mounts=None, working_dir=None): """ V1Container - 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 = { 'args': 'list[str]', 'command': 'list[str]', 'env': 'list[V1EnvVar]', 'env_from': 'list[V1EnvFromSource]', 'image': 'str', 'image_pull_policy': 'str', 'lifecycle': 'V1Lifecycle', 'liveness_probe': 'V1Probe', 'name': 'str', 'ports': 'list[V1ContainerPort]', 'readiness_probe': 'V1Probe', 'resources': 'V1ResourceRequirements', 'security_context': 'V1SecurityContext', 'stdin': 'bool', 'stdin_once': 'bool', 'termination_message_path': 'str', 'termination_message_policy': 'str', 'tty': 'bool', 'volume_mounts': 'list[V1VolumeMount]', 'working_dir': 'str' } self.attribute_map = { 'args': 'args', 'command': 'command', 'env': 'env', 'env_from': 'envFrom', 'image': 'image', 'image_pull_policy': 'imagePullPolicy', 'lifecycle': 'lifecycle', 'liveness_probe': 'livenessProbe', 'name': 'name', 'ports': 'ports', 'readiness_probe': 'readinessProbe', 'resources': 'resources', 'security_context': 'securityContext', 'stdin': 'stdin', 'stdin_once': 'stdinOnce', 'termination_message_path': 'terminationMessagePath', 'termination_message_policy': 'terminationMessagePolicy', 'tty': 'tty', 'volume_mounts': 'volumeMounts', 'working_dir': 'workingDir' } self._args = args self._command = command self._env = env self._env_from = env_from self._image = image self._image_pull_policy = image_pull_policy self._lifecycle = lifecycle self._liveness_probe = liveness_probe self._name = name self._ports = ports self._readiness_probe = readiness_probe self._resources = resources self._security_context = security_context self._stdin = stdin self._stdin_once = stdin_once self._termination_message_path = termination_message_path self._termination_message_policy = termination_message_policy self._tty = tty self._volume_mounts = volume_mounts self._working_dir = working_dir @property def args(self): """ Gets the args of this V1Container. Arguments to the entrypoint. The docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/containers#containers-and-commands :return: The args of this V1Container. :rtype: list[str] """ return self._args @args.setter def args(self, args): """ Sets the args of this V1Container. Arguments to the entrypoint. The docker image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/containers#containers-and-commands :param args: The args of this V1Container. :type: list[str] """ self._args = args @property def command(self): """ Gets the command of this V1Container. Entrypoint array. Not executed within a shell. The docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/containers#containers-and-commands :return: The command of this V1Container. :rtype: list[str] """ return self._command @command.setter def command(self, command): """ Sets the command of this V1Container. Entrypoint array. Not executed within a shell. The docker image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/containers#containers-and-commands :param command: The command of this V1Container. :type: list[str] """ self._command = command @property def env(self): """ Gets the env of this V1Container. List of environment variables to set in the container. Cannot be updated. :return: The env of this V1Container. :rtype: list[V1EnvVar] """ return self._env @env.setter def env(self, env): """ Sets the env of this V1Container. List of environment variables to set in the container. Cannot be updated. :param env: The env of this V1Container. :type: list[V1EnvVar] """ self._env = env @property def env_from(self): """ Gets the env_from of this V1Container. List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated. :return: The env_from of this V1Container. :rtype: list[V1EnvFromSource] """ return self._env_from @env_from.setter def env_from(self, env_from): """ Sets the env_from of this V1Container. List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated. :param env_from: The env_from of this V1Container. :type: list[V1EnvFromSource] """ self._env_from = env_from @property def image(self): """ Gets the image of this V1Container. Docker image name. More info: http://kubernetes.io/docs/user-guide/images :return: The image of this V1Container. :rtype: str """ return self._image @image.setter def image(self, image): """ Sets the image of this V1Container. Docker image name. More info: http://kubernetes.io/docs/user-guide/images :param image: The image of this V1Container. :type: str """ self._image = image @property def image_pull_policy(self): """ Gets the image_pull_policy of this V1Container. Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/images#updating-images :return: The image_pull_policy of this V1Container. :rtype: str """ return self._image_pull_policy @image_pull_policy.setter def image_pull_policy(self, image_pull_policy): """ Sets the image_pull_policy of this V1Container. Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/images#updating-images :param image_pull_policy: The image_pull_policy of this V1Container. :type: str """ self._image_pull_policy = image_pull_policy @property def lifecycle(self): """ Gets the lifecycle of this V1Container. Actions that the management system should take in response to container lifecycle events. Cannot be updated. :return: The lifecycle of this V1Container. :rtype: V1Lifecycle """ return self._lifecycle @lifecycle.setter def lifecycle(self, lifecycle): """ Sets the lifecycle of this V1Container. Actions that the management system should take in response to container lifecycle events. Cannot be updated. :param lifecycle: The lifecycle of this V1Container. :type: V1Lifecycle """ self._lifecycle = lifecycle @property def liveness_probe(self): """ Gets the liveness_probe of this V1Container. Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes :return: The liveness_probe of this V1Container. :rtype: V1Probe """ return self._liveness_probe @liveness_probe.setter def liveness_probe(self, liveness_probe): """ Sets the liveness_probe of this V1Container. Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes :param liveness_probe: The liveness_probe of this V1Container. :type: V1Probe """ self._liveness_probe = liveness_probe @property def name(self): """ Gets the name of this V1Container. Name of the container specified as a DNS_LABEL. Each container in a pod must have a unique name (DNS_LABEL). Cannot be updated. :return: The name of this V1Container. :rtype: str """ return self._name @name.setter def name(self, name): """ Sets the name of this V1Container. Name of the container specified as a DNS_LABEL. Each container in a pod must have a unique name (DNS_LABEL). Cannot be updated. :param name: The name of this V1Container. :type: str """ if name is None: raise ValueError("Invalid value for `name`, must not be `None`") self._name = name @property def ports(self): """ Gets the ports of this V1Container. List of ports to expose from the container. Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default \"0.0.0.0\" address inside a container will be accessible from the network. Cannot be updated. :return: The ports of this V1Container. :rtype: list[V1ContainerPort] """ return self._ports @ports.setter def ports(self, ports): """ Sets the ports of this V1Container. List of ports to expose from the container. Exposing a port here gives the system additional information about the network connections a container uses, but is primarily informational. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default \"0.0.0.0\" address inside a container will be accessible from the network. Cannot be updated. :param ports: The ports of this V1Container. :type: list[V1ContainerPort] """ self._ports = ports @property def readiness_probe(self): """ Gets the readiness_probe of this V1Container. Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes :return: The readiness_probe of this V1Container. :rtype: V1Probe """ return self._readiness_probe @readiness_probe.setter def readiness_probe(self, readiness_probe): """ Sets the readiness_probe of this V1Container. Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/pod-states#container-probes :param readiness_probe: The readiness_probe of this V1Container. :type: V1Probe """ self._readiness_probe = readiness_probe @property def resources(self): """ Gets the resources of this V1Container. Compute Resources required by this container. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#resources :return: The resources of this V1Container. :rtype: V1ResourceRequirements """ return self._resources @resources.setter def resources(self, resources): """ Sets the resources of this V1Container. Compute Resources required by this container. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/persistent-volumes#resources :param resources: The resources of this V1Container. :type: V1ResourceRequirements """ self._resources = resources @property def security_context(self): """ Gets the security_context of this V1Container. Security options the pod should run with. More info: http://releases.k8s.io/HEAD/docs/design/security_context.md :return: The security_context of this V1Container. :rtype: V1SecurityContext """ return self._security_context @security_context.setter def security_context(self, security_context): """ Sets the security_context of this V1Container. Security options the pod should run with. More info: http://releases.k8s.io/HEAD/docs/design/security_context.md :param security_context: The security_context of this V1Container. :type: V1SecurityContext """ self._security_context = security_context @property def stdin(self): """ Gets the stdin of this V1Container. Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false. :return: The stdin of this V1Container. :rtype: bool """ return self._stdin @stdin.setter def stdin(self, stdin): """ Sets the stdin of this V1Container. Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false. :param stdin: The stdin of this V1Container. :type: bool """ self._stdin = stdin @property def stdin_once(self): """ Gets the stdin_once of this V1Container. Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false :return: The stdin_once of this V1Container. :rtype: bool """ return self._stdin_once @stdin_once.setter def stdin_once(self, stdin_once): """ Sets the stdin_once of this V1Container. Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false :param stdin_once: The stdin_once of this V1Container. :type: bool """ self._stdin_once = stdin_once @property def termination_message_path(self): """ Gets the termination_message_path of this V1Container. Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated. :return: The termination_message_path of this V1Container. :rtype: str """ return self._termination_message_path @termination_message_path.setter def termination_message_path(self, termination_message_path): """ Sets the termination_message_path of this V1Container. Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated. :param termination_message_path: The termination_message_path of this V1Container. :type: str """ self._termination_message_path = termination_message_path @property def termination_message_policy(self): """ Gets the termination_message_policy of this V1Container. Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated. :return: The termination_message_policy of this V1Container. :rtype: str """ return self._termination_message_policy @termination_message_policy.setter def termination_message_policy(self, termination_message_policy): """ Sets the termination_message_policy of this V1Container. Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated. :param termination_message_policy: The termination_message_policy of this V1Container. :type: str """ self._termination_message_policy = termination_message_policy @property def tty(self): """ Gets the tty of this V1Container. Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false. :return: The tty of this V1Container. :rtype: bool """ return self._tty @tty.setter def tty(self, tty): """ Sets the tty of this V1Container. Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false. :param tty: The tty of this V1Container. :type: bool """ self._tty = tty @property def volume_mounts(self): """ Gets the volume_mounts of this V1Container. Pod volumes to mount into the container's filesystem. Cannot be updated. :return: The volume_mounts of this V1Container. :rtype: list[V1VolumeMount] """ return self._volume_mounts @volume_mounts.setter def volume_mounts(self, volume_mounts): """ Sets the volume_mounts of this V1Container. Pod volumes to mount into the container's filesystem. Cannot be updated. :param volume_mounts: The volume_mounts of this V1Container. :type: list[V1VolumeMount] """ self._volume_mounts = volume_mounts @property def working_dir(self): """ Gets the working_dir of this V1Container. Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated. :return: The working_dir of this V1Container. :rtype: str """ return self._working_dir @working_dir.setter def working_dir(self, working_dir): """ Sets the working_dir of this V1Container. Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated. :param working_dir: The working_dir of this V1Container. :type: str """ self._working_dir = working_dir 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() 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 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
simongoffin/website_version
refs/heads/Multi_fonctionnel
addons/account/wizard/account_move_bank_reconcile.py
385
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ class account_move_bank_reconcile(osv.osv_memory): """ Bank Reconciliation """ _name = "account.move.bank.reconcile" _description = "Move bank reconcile" _columns = { 'journal_id': fields.many2one('account.journal', 'Journal', required=True), } def action_open_window(self, cr, uid, ids, context=None): """ @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: account move bank reconcile’s ID or list of IDs @return: dictionary of Open account move line on given journal_id. """ if context is None: context = {} data = self.read(cr, uid, ids, context=context)[0] cr.execute('select default_credit_account_id \ from account_journal where id=%s', (data['journal_id'],)) account_id = cr.fetchone()[0] if not account_id: raise osv.except_osv(_('Error!'), _('You have to define \ the bank account\nin the journal definition for reconciliation.')) return { 'domain': "[('journal_id','=',%d), ('account_id','=',%d), ('state','<>','draft')]" % (data['journal_id'], account_id), 'name': _('Standard Encoding'), 'view_type': 'form', 'view_mode': 'tree,form', 'res_model': 'account.move.line', 'view_id': False, 'context': "{'journal_id': %d}" % (data['journal_id'],), 'type': 'ir.actions.act_window' } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
chhans/tor-automation
refs/heads/master
classifier.py
1
import numpy as np import math i_d = 0 i_u = 1 i_pbd = 2 i_pbu = 3 i_b = 4 i_ibt = 5 class Classifier: def __init__(self, label): self.label = label self.inter_burst_times = np.array([]) self.num_burst = np.array([]) self.per_burst_dn = np.array([]) self.per_burst_up = np.array([]) self.tot_cells_dn = np.array([]) self.tot_cells_up = np.array([]) self.tot_distances = np.array([]) self.per_burst_distances = np.array([]) def euclidianDist(self, dn_0, up_0, dn_1, up_1): return math.sqrt( (dn_0 - dn_1)**2 + (up_0 - up_1)**2 ) def trainIBT(self, ibt): self.inter_burst_times = np.append(self.inter_burst_times, ibt) def trainNumBursts(self, b): self.num_burst = np.append(self.num_burst, b) def trainPerBurstDistance(self): for i in range(len(self.per_burst_dn)-1): u0 = self.per_burst_up[-1] d0 = self.per_burst_dn[-1] u1 = self.per_burst_up[i] d1 = self.per_burst_dn[i] d = self.euclidianDist(d0, u0, d1, u1) self.per_burst_distances = np.append(self.per_burst_distances, d) def trainPerBurst(self, dn, up): self.per_burst_dn = np.append(self.per_burst_dn, dn) self.per_burst_up = np.append(self.per_burst_up, up) if len(self.per_burst_dn) > 1: self.trainPerBurstDistance() def trainTotalDistance(self): for i in range(len(self.tot_cells_dn)-1): u0 = self.tot_cells_up[-1] d0 = self.tot_cells_dn[-1] u1 = self.tot_cells_up[i] d1 = self.tot_cells_dn[i] d = self.euclidianDist(d0, u0, d1, u1) self.tot_distances = np.append(self.tot_distances, d) def trainTotalCells(self, dn, up): self.tot_cells_dn = np.append(self.tot_cells_dn, dn) self.tot_cells_up = np.append(self.tot_cells_up, up) if len(self.tot_cells_dn) > 1: self.trainTotalDistance() def train(self, metrics): # Average inter-burst time self.trainIBT(metrics[i_ibt]) # Number of bursts self.trainNumBursts(metrics[i_b]) # Number of cells per burst self.trainPerBurst(metrics[i_pbd], metrics[i_pbu]) # Total number of cells self.trainTotalCells(metrics[i_d], metrics[i_u]) def meanTotalDistance(self): return np.mean(self.tot_distances) def meanPerBurstDistance(self): return np.mean(self.per_burst_distances) def IBTVote(self, ibt): std = np.std(self.inter_burst_times) mean = np.mean(self.inter_burst_times) dist = abs(ibt - mean) perfect_match = dist == 0 and std == 0 limit = 4.0 if perfect_match: return 4.0 elif dist <= limit: return 1.0 else: return -1.0 def numBurstsVote(self, b): std = np.std(self.num_burst) mean = np.mean(self.num_burst) dist = abs(b - mean) perfect_match = dist <= 0.5 and std <= 0.5 limit = 5 if perfect_match: return 4.0 elif dist <= limit: return 1.0 else: return -1.0 def perBurstRatioVote(self, ratio): ratios = self.per_burst_dn/self.per_burst_up mean = np.mean(ratios) dist = abs(ratio - mean) limit = mean/3.5 if dist <= limit: return 1.0 else: return -1.0 def totalRatioVote(self, ratio): ratios = self.tot_cells_dn/self.tot_cells_up mean = np.mean(ratios) dist = abs(ratio - mean) limit = mean/1.8 if dist <= limit: return 1.0 else: return -1.0 def perBurstDistance(self, metrics): mean_dn = np.mean(self.per_burst_dn) mean_up = np.mean(self.per_burst_up) dn = metrics[i_pbd] up = metrics[i_pbu] return self.euclidianDist(dn, up, mean_dn, mean_up) def totalDistance(self, metrics): mean_dn = np.mean(self.tot_cells_dn) mean_up = np.mean(self.tot_cells_up) dn = metrics[i_d] up = metrics[i_u] return self.euclidianDist(dn, up, mean_dn, mean_up) def predict(self, metrics): vote = 0.0 # Average inter-burst time vote += self.IBTVote(metrics[i_ibt]) # Number of bursts vote += self.numBurstsVote(metrics[i_b]) # Cells per burst ratio vote += self.perBurstRatioVote(metrics[i_pbd]/float(metrics[i_pbu])) vote += self.totalRatioVote(metrics[i_d]/metrics[i_u]) return vote
legrosbuffle/or-tools
refs/heads/master
examples/tests/issue128.py
7
from ortools.constraint_solver import pywrapcp def test_v0(): print 'test_v0' solver = pywrapcp.Solver('') # we have two tasks of durations 4 and 7 task1 = solver.FixedDurationIntervalVar(0, 5, 4, False, "task1") task2 = solver.FixedDurationIntervalVar(0, 5, 7, False, "task2") tasks = [task1, task2] # to each task, a post task of duration 64 is attached postTask1 = solver.FixedDurationIntervalVar(4, 74 + 64, 64, False, "postTask1") postTask2 = solver.FixedDurationIntervalVar(4, 77 + 64, 64, False, "postTask2") postTasks = [postTask1, postTask2] solver.Add(postTask1.StartsAtEnd(task1)) solver.Add(postTask2.StartsAtEnd(task2)) # two resources are available for the post tasks. There are binary indicator # variables to determine which task uses which resource postTask1UsesRes1 = solver.IntVar(0, 1, "post task 1 using resource 1") postTask1UsesRes2 = solver.IntVar(0, 1, "post task 1 using resource 2") postTask2UsesRes1 = solver.IntVar(0, 1, "post task 2 using resource 1") postTask2UsesRes2 = solver.IntVar(0, 1, "post task 2 using resource 2") indicators = [postTask1UsesRes1, postTask1UsesRes2, postTask2UsesRes1, postTask2UsesRes2] # each post task needs exactly one resource solver.Add(postTask1UsesRes1 + postTask1UsesRes2 == 1) solver.Add(postTask2UsesRes1 + postTask2UsesRes2 == 1) # each resource cannot be used simultaneously by more than one post task solver.Add(solver.Cumulative(postTasks, [postTask1UsesRes1, postTask2UsesRes1], 1, "cumul1")) solver.Add(solver.Cumulative(postTasks, [postTask1UsesRes2, postTask2UsesRes2], 1, "cumul2")) # using constant demands instead, the correct solution is found # solver.Add(solver.Cumulative(postTasks, [0, 1], 1, "")) # solver.Add(solver.Cumulative(postTasks, [1, 0], 1, "")) # search setup and solving dbInterval = solver.Phase(tasks + postTasks, solver.INTERVAL_DEFAULT) dbInt = solver.Phase(indicators, solver.INT_VAR_DEFAULT, solver.INT_VALUE_DEFAULT) makespan = solver.Max([task1.EndExpr().Var(), task2.EndExpr().Var()]) optimize = solver.Optimize(False, makespan, 1) solution = solver.Assignment() solution.Add([t for t in (tasks + postTasks)]) solution.Add(indicators) collector = solver.LastSolutionCollector(solution) phase = solver.Compose([dbInt, dbInterval]) solver.Solve(phase, [collector, optimize]) if collector.SolutionCount() > 0: for i, task in enumerate(tasks): print("task {} runs from {} to {}".format( i, collector.StartValue(0, task), collector.EndValue(0, task))) for i, task in enumerate(postTasks): print("postTask {} starts at {}".format(i, collector.StartValue(0, task))) for indicator in indicators: print('{} -> {}'.format(indicator.Name(), collector.Value(0, indicator))) else: print 'No solution' def test_v1(): print 'test_v1' solver = pywrapcp.Solver('') # we have two tasks of durations 4 and 7 task1 = solver.FixedDurationIntervalVar(0, 5, 4, False, "task1") task2 = solver.FixedDurationIntervalVar(0, 5, 7, False, "task2") tasks = [task1, task2] # Create copies for each resource task1_r1 = solver.FixedDurationIntervalVar(0, 5, 4, True, "task1_1") task2_r1 = solver.FixedDurationIntervalVar(0, 5, 7, True, "task2_1") tasks_r1 = [task1_r1, task2_r1] task1_r2 = solver.FixedDurationIntervalVar(0, 5, 4, True, "task1_2") task2_r2 = solver.FixedDurationIntervalVar(0, 5, 7, True, "task2_2") tasks_r2 = [task1_r2, task2_r2] # to each task, a post task of duration 64 is attached postTask1 = solver.FixedDurationStartSyncedOnEndIntervalVar(task1, 64, 0) postTask2 = solver.FixedDurationStartSyncedOnEndIntervalVar(task2, 64, 0) postTasks = [postTask1, postTask2] # Create copies for each resource postTask1_r1 = solver.FixedDurationIntervalVar(4, 9, 64, True, "pTask1_1") postTask2_r1 = solver.FixedDurationIntervalVar(4, 11, 64, True, "pTask2_1") postTask1_r2 = solver.FixedDurationIntervalVar(4, 9, 64, True, "pTask1_2") postTask2_r2 = solver.FixedDurationIntervalVar(4, 11, 64, True, "pTask2_2") copies = [ task1_r1, task2_r1, task1_r2, task2_r2, postTask1_r1, postTask1_r2, postTask2_r1, postTask2_r2 ] # each resource cannot be used simultaneously by more than one post task solver.Add(solver.DisjunctiveConstraint( [task1_r1, task2_r1, postTask1_r1, postTask2_r1], "disj1")) solver.Add(solver.DisjunctiveConstraint( [task1_r2, task2_r2, postTask1_r2, postTask2_r2], "disj1")) # Only one resource available solver.Add(task1_r1.PerformedExpr() + task1_r2.PerformedExpr() == 1) solver.Add(task2_r1.PerformedExpr() + task2_r2.PerformedExpr() == 1) solver.Add(postTask1_r1.PerformedExpr() + postTask1_r2.PerformedExpr() == 1) solver.Add(postTask2_r1.PerformedExpr() + postTask2_r2.PerformedExpr() == 1) # Sync master task with copies solver.Add(solver.Cover([task1_r1, task1_r2], task1)) solver.Add(solver.Cover([task2_r1, task2_r2], task2)) solver.Add(solver.Cover([postTask1_r1, postTask1_r2], postTask1)) solver.Add(solver.Cover([postTask2_r1, postTask2_r2], postTask2)) # Indicators (no need to add both as they are constrained together) indicators = [ task1_r1.PerformedExpr(), task2_r1.PerformedExpr(), postTask1_r1.PerformedExpr(), postTask2_r1.PerformedExpr()] # search setup and solving dbInterval = solver.Phase(tasks + postTasks, solver.INTERVAL_DEFAULT) dbInt = solver.Phase( indicators, solver.INT_VAR_DEFAULT, solver.INT_VALUE_DEFAULT) makespan = solver.Max([task1.EndExpr(), task2.EndExpr()]) optimize = solver.Minimize(makespan, 1) solution = solver.Assignment() solution.Add(tasks) solution.Add(postTasks) solution.Add(copies) solution.AddObjective(makespan) collector = solver.LastSolutionCollector(solution) phase = solver.Compose([dbInt, dbInterval]) solver.Solve(phase, [collector, optimize]) if collector.SolutionCount() > 0: print 'solution with makespan', collector.ObjectiveValue(0) for task in tasks: print("task {} runs from {} to {}".format( task.Name(), collector.StartValue(0, task), collector.EndValue(0, task))) for task in postTasks: print("postTask {} starts at {}".format( task.Name(), collector.StartValue(0, task))) for task in copies: print task.Name(), collector.PerformedValue(0, task) else: print 'No solution' test_v0() test_v1()
VentureROM-L/android_external_skia
refs/heads/lollipop
tools/pyutils/gs_utils.py
66
#!/usr/bin/python """ Copyright 2014 Google Inc. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. Utilities for accessing Google Cloud Storage. TODO(epoger): move this into tools/utils for broader use? """ # System-level imports import os import posixpath import sys try: from apiclient.discovery import build as build_service except ImportError: print ('Missing google-api-python-client. Please install it; directions ' 'can be found at https://developers.google.com/api-client-library/' 'python/start/installation') raise # Local imports import url_utils def download_file(source_bucket, source_path, dest_path, create_subdirs_if_needed=False): """ Downloads a single file from Google Cloud Storage to local disk. Args: source_bucket: GCS bucket to download the file from source_path: full path (Posix-style) within that bucket dest_path: full path (local-OS-style) on local disk to copy the file to create_subdirs_if_needed: boolean; whether to create subdirectories as needed to create dest_path """ source_http_url = posixpath.join( 'http://storage.googleapis.com', source_bucket, source_path) url_utils.copy_contents(source_url=source_http_url, dest_path=dest_path, create_subdirs_if_needed=create_subdirs_if_needed) def list_bucket_contents(bucket, subdir=None): """ Returns files in the Google Cloud Storage bucket as a (dirs, files) tuple. Uses the API documented at https://developers.google.com/storage/docs/json_api/v1/objects/list Args: bucket: name of the Google Storage bucket subdir: directory within the bucket to list, or None for root directory """ # The GCS command relies on the subdir name (if any) ending with a slash. if subdir and not subdir.endswith('/'): subdir += '/' subdir_length = len(subdir) if subdir else 0 storage = build_service('storage', 'v1') command = storage.objects().list( bucket=bucket, delimiter='/', fields='items(name),prefixes', prefix=subdir) results = command.execute() # The GCS command returned two subdicts: # prefixes: the full path of every directory within subdir, with trailing '/' # items: property dict for each file object within subdir # (including 'name', which is full path of the object) dirs = [] for dir_fullpath in results.get('prefixes', []): dir_basename = dir_fullpath[subdir_length:] dirs.append(dir_basename[:-1]) # strip trailing slash files = [] for file_properties in results.get('items', []): file_fullpath = file_properties['name'] file_basename = file_fullpath[subdir_length:] files.append(file_basename) return (dirs, files)
pomegranited/edx-platform
refs/heads/master
cms/djangoapps/contentstore/features/course-outline.py
19
# pylint: disable=missing-docstring # pylint: disable=redefined-outer-name from lettuce import world, step from common import * from nose.tools import assert_true, assert_false from logging import getLogger logger = getLogger(__name__) @step(u'I have a course with no sections$') def have_a_course(step): world.clear_courses() course = world.CourseFactory.create() @step(u'I have a course with 1 section$') def have_a_course_with_1_section(step): world.clear_courses() course = world.CourseFactory.create() section = world.ItemFactory.create(parent_location=course.location) subsection1 = world.ItemFactory.create( parent_location=section.location, category='sequential', display_name='Subsection One',) @step(u'I have a course with multiple sections$') def have_a_course_with_two_sections(step): world.clear_courses() course = world.CourseFactory.create() section = world.ItemFactory.create(parent_location=course.location) subsection1 = world.ItemFactory.create( parent_location=section.location, category='sequential', display_name='Subsection One',) section2 = world.ItemFactory.create( parent_location=course.location, display_name='Section Two',) subsection2 = world.ItemFactory.create( parent_location=section2.location, category='sequential', display_name='Subsection Alpha',) subsection3 = world.ItemFactory.create( parent_location=section2.location, category='sequential', display_name='Subsection Beta',) @step(u'I navigate to the course outline page$') def navigate_to_the_course_outline_page(step): create_studio_user(is_staff=True) log_into_studio() course_locator = 'a.course-link' world.css_click(course_locator) @step(u'I navigate to the outline page of a course with multiple sections') def nav_to_the_outline_page_of_a_course_with_multiple_sections(step): step.given('I have a course with multiple sections') step.given('I navigate to the course outline page') @step(u'I add a section') def i_add_a_section(step): add_section() @step(u'I press the section delete icon') def i_press_the_section_delete_icon(step): delete_locator = 'section .outline-section > .section-header a.delete-button' world.css_click(delete_locator) @step(u'I will confirm all alerts') def i_confirm_all_alerts(step): confirm_locator = '.prompt .nav-actions button.action-primary' world.css_click(confirm_locator) @step(u'I see the "([^"]*) All Sections" link$') def i_see_the_collapse_expand_all_span(step, text): if text == "Collapse": span_locator = '.button-toggle-expand-collapse .collapse-all .label' elif text == "Expand": span_locator = '.button-toggle-expand-collapse .expand-all .label' assert_true(world.css_visible(span_locator)) @step(u'I do not see the "([^"]*) All Sections" link$') def i_do_not_see_the_collapse_expand_all_span(step, text): if text == "Collapse": span_locator = '.button-toggle-expand-collapse .collapse-all .label' elif text == "Expand": span_locator = '.button-toggle-expand-collapse .expand-all .label' assert_false(world.css_visible(span_locator)) @step(u'I click the "([^"]*) All Sections" link$') def i_click_the_collapse_expand_all_span(step, text): if text == "Collapse": span_locator = '.button-toggle-expand-collapse .collapse-all .label' elif text == "Expand": span_locator = '.button-toggle-expand-collapse .expand-all .label' assert_true(world.browser.is_element_present_by_css(span_locator)) world.css_click(span_locator) @step(u'I ([^"]*) the first section$') def i_collapse_expand_a_section(step, text): if text == "collapse": locator = 'section .outline-section .ui-toggle-expansion' elif text == "expand": locator = 'section .outline-section .ui-toggle-expansion' world.css_click(locator) @step(u'all sections are ([^"]*)$') def all_sections_are_collapsed_or_expanded(step, text): subsection_locator = 'div.subsection-list' subsections = world.css_find(subsection_locator) for index in range(len(subsections)): if text == "collapsed": assert_false(world.css_visible(subsection_locator, index=index)) elif text == "expanded": assert_true(world.css_visible(subsection_locator, index=index)) @step(u"I change an assignment's grading status") def change_grading_status(step): world.css_find('a.menu-toggle').click() world.css_find('.menu li').first.click()
bealdav/OpenUpgrade
refs/heads/8.0
addons/account_chart/__openerp__.py
119
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Template of Charts of Accounts', 'version': '1.1', 'category': 'Hidden/Dependency', 'description': """ Remove minimal account chart. ============================= Deactivates minimal chart of accounts. """, 'author': 'OpenERP SA', 'website': 'http://www.openerp.com', 'depends': ['account'], 'data': [], 'demo': [], 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agoose77/hivesystem
refs/heads/master
hiveguilib/PQt/__init__.py
1
from .PGenerator import PGenerator from .PTree import PTree from .PControllerGeneral import PControllerGeneral from .PControllerBlock import PControllerBlock from .PSpyderhive import PSpyderhive from .TypeCompleter import TypeCompleter from .AntennaFoldState import AntennaFoldState
motion2015/a3
refs/heads/a3
common/lib/sandbox-packages/eia.py
193
""" Standard resistor values. Commonly used for verifying electronic components in circuit classes are standard values, or conversely, for generating realistic component values in parameterized problems. For details, see: http://en.wikipedia.org/wiki/Electronic_color_code """ # pylint: disable=invalid-name # r is standard name for a resistor. We would like to use it as such. import math import numbers E6 = [10, 15, 22, 33, 47, 68] E12 = [10, 12, 15, 18, 22, 27, 33, 39, 47, 56, 68, 82] E24 = [10, 12, 15, 18, 22, 27, 33, 39, 47, 56, 68, 82, 11, 13, 16, 20, 24, 30, 36, 43, 51, 62, 75, 91] E48 = [100, 121, 147, 178, 215, 261, 316, 383, 464, 562, 681, 825, 105, 127, 154, 187, 226, 274, 332, 402, 487, 590, 715, 866, 110, 133, 162, 196, 237, 287, 348, 422, 511, 619, 750, 909, 115, 140, 169, 205, 249, 301, 365, 442, 536, 649, 787, 953] E96 = [100, 121, 147, 178, 215, 261, 316, 383, 464, 562, 681, 825, 102, 124, 150, 182, 221, 267, 324, 392, 475, 576, 698, 845, 105, 127, 154, 187, 226, 274, 332, 402, 487, 590, 715, 866, 107, 130, 158, 191, 232, 280, 340, 412, 499, 604, 732, 887, 110, 133, 162, 196, 237, 287, 348, 422, 511, 619, 750, 909, 113, 137, 165, 200, 243, 294, 357, 432, 523, 634, 768, 931, 115, 140, 169, 205, 249, 301, 365, 442, 536, 649, 787, 953, 118, 143, 174, 210, 255, 309, 374, 453, 549, 665, 806, 976] E192 = [100, 121, 147, 178, 215, 261, 316, 383, 464, 562, 681, 825, 101, 123, 149, 180, 218, 264, 320, 388, 470, 569, 690, 835, 102, 124, 150, 182, 221, 267, 324, 392, 475, 576, 698, 845, 104, 126, 152, 184, 223, 271, 328, 397, 481, 583, 706, 856, 105, 127, 154, 187, 226, 274, 332, 402, 487, 590, 715, 866, 106, 129, 156, 189, 229, 277, 336, 407, 493, 597, 723, 876, 107, 130, 158, 191, 232, 280, 340, 412, 499, 604, 732, 887, 109, 132, 160, 193, 234, 284, 344, 417, 505, 612, 741, 898, 110, 133, 162, 196, 237, 287, 348, 422, 511, 619, 750, 909, 111, 135, 164, 198, 240, 291, 352, 427, 517, 626, 759, 920, 113, 137, 165, 200, 243, 294, 357, 432, 523, 634, 768, 931, 114, 138, 167, 203, 246, 298, 361, 437, 530, 642, 777, 942, 115, 140, 169, 205, 249, 301, 365, 442, 536, 649, 787, 953, 117, 142, 172, 208, 252, 305, 370, 448, 542, 657, 796, 965, 118, 143, 174, 210, 255, 309, 374, 453, 549, 665, 806, 976, 120, 145, 176, 213, 258, 312, 379, 459, 556, 673, 816, 988] def iseia(r, valid_types=(E6, E12, E24)): ''' Check if a component is a valid EIA value. By default, check 5% component values ''' # Step 1: Discount things which are not numbers if not isinstance(r, numbers.Number) or \ r < 0 or \ math.isnan(r) or \ math.isinf(r): return False # Special case: 0 is an okay resistor if r == 0: return True # Step 2: Move into the range [100, 1000) while r < 100: r = r * 10 while r >= 1000: r = r / 10 # Step 3: Discount things which are not integers, and cast to int if abs(r - round(r)) > 0.01: return False r = int(round(r)) # Step 4: Check if we're a valid EIA value for type_list in valid_types: if r in type_list: return True if int(r / 10.) in type_list and (r % 10) == 0: return True return False if __name__ == '__main__': # Test cases. All of these should return True print iseia(100) # 100 ohm resistor is EIA print not iseia(101) # 101 is not print not iseia(100.3) # Floating point close to EIA is not EIA print iseia(100.001) # But within floating point error is print iseia(1e5) # We handle big numbers well print iseia(2200) # We handle middle-of-the-list well # We can handle 1% components correctly; 2.2k is EIA24, but not EIA48. print not iseia(2200, (E48, E96, E192)) print iseia(5490e2, (E48, E96, E192)) print iseia(2200) print not iseia(5490e2) print iseia(1e-5) # We handle little numbers well print not iseia("Hello") # Junk handled okay print not iseia(float('NaN')) print not iseia(-1) print not iseia(iseia) print not iseia(float('Inf')) print iseia(0) # Corner case. 0 is a standard resistor value.
pepeportela/edx-platform
refs/heads/master
lms/djangoapps/courseware/context_processor.py
6
""" This is the courseware context_processor module. This is meant to simplify the process of sending user preferences (espec. time_zone and pref-lang) to the templates without having to append every view file. """ import request_cache from openedx.core.djangoapps.user_api.errors import UserAPIInternalError, UserNotFound from openedx.core.djangoapps.user_api.preferences.api import get_user_preferences RETRIEVABLE_PREFERENCES = { 'user_timezone': 'time_zone', 'user_language': 'pref-lang' } CACHE_NAME = "context_processor.user_timezone_preferences" def user_timezone_locale_prefs(request): """ Checks if request has an authenticated user. If so, sends set (or none if unset) time_zone and language prefs. This interacts with the DateUtils to either display preferred or attempt to determine system/browser set time_zones and languages """ cached_value = request_cache.get_cache(CACHE_NAME) if not cached_value: user_prefs = { 'user_timezone': None, 'user_language': None, } if hasattr(request, 'user') and request.user.is_authenticated(): try: user_preferences = get_user_preferences(request.user) except (UserNotFound, UserAPIInternalError): cached_value.update(user_prefs) else: user_prefs = { key: user_preferences.get(pref_name, None) for key, pref_name in RETRIEVABLE_PREFERENCES.iteritems() } cached_value.update(user_prefs) return cached_value
GitHublong/hue
refs/heads/master
desktop/core/ext-py/Pygments-1.3.1/external/rst-directive.py
47
# -*- coding: utf-8 -*- """ The Pygments reStructuredText directive ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This fragment is a Docutils_ 0.5 directive that renders source code (to HTML only, currently) via Pygments. To use it, adjust the options below and copy the code into a module that you import on initialization. The code then automatically registers a ``sourcecode`` directive that you can use instead of normal code blocks like this:: .. sourcecode:: python My code goes here. If you want to have different code styles, e.g. one with line numbers and one without, add formatters with their names in the VARIANTS dict below. You can invoke them instead of the DEFAULT one by using a directive option:: .. sourcecode:: python :linenos: My code goes here. Look at the `directive documentation`_ to get all the gory details. .. _Docutils: http://docutils.sf.net/ .. _directive documentation: http://docutils.sourceforge.net/docs/howto/rst-directives.html :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ # Options # ~~~~~~~ # Set to True if you want inline CSS styles instead of classes INLINESTYLES = False from pygments.formatters import HtmlFormatter # The default formatter DEFAULT = HtmlFormatter(noclasses=INLINESTYLES) # Add name -> formatter pairs for every variant you want to use VARIANTS = { # 'linenos': HtmlFormatter(noclasses=INLINESTYLES, linenos=True), } from docutils import nodes from docutils.parsers.rst import directives, Directive from pygments import highlight from pygments.lexers import get_lexer_by_name, TextLexer class Pygments(Directive): """ Source code syntax hightlighting. """ required_arguments = 1 optional_arguments = 0 final_argument_whitespace = True option_spec = dict([(key, directives.flag) for key in VARIANTS]) has_content = True def run(self): self.assert_has_content() try: lexer = get_lexer_by_name(self.arguments[0]) except ValueError: # no lexer found - use the text one instead of an exception lexer = TextLexer() # take an arbitrary option if more than one is given formatter = self.options and VARIANTS[self.options.keys()[0]] or DEFAULT parsed = highlight(u'\n'.join(self.content), lexer, formatter) return [nodes.raw('', parsed, format='html')] directives.register_directive('sourcecode', Pygments)
googleapis/googleapis-gen
refs/heads/master
google/cloud/asset/v1p7beta1/asset-v1p7beta1-py/google/cloud/asset_v1p7beta1/services/asset_service/transports/grpc_asyncio.py
1
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import 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.api_core import operations_v1 # 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.cloud.asset_v1p7beta1.types import asset_service from google.longrunning import operations_pb2 # type: ignore from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .grpc import AssetServiceGrpcTransport class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): """gRPC AsyncIO backend transport for AssetService. Asset service definition. 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 = 'cloudasset.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 = 'cloudasset.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 applicatin 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 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 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] = {} self._operations_client = None 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 operations_client(self) -> operations_v1.OperationsAsyncClient: """Create the client designed to process long-running operations. This property caches on the instance; repeated calls return the same client. """ # Sanity check: Only create a new client if we do not already have one. if self._operations_client is None: self._operations_client = operations_v1.OperationsAsyncClient( self.grpc_channel ) # Return the client from cache. return self._operations_client @property def export_assets(self) -> Callable[ [asset_service.ExportAssetsRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the export assets method over gRPC. Exports assets with time and resource types to a given Cloud Storage location/BigQuery table. For Cloud Storage location destinations, the output format is newline-delimited JSON. Each line represents a [google.cloud.asset.v1p7beta1.Asset][google.cloud.asset.v1p7beta1.Asset] in the JSON format; for BigQuery table destinations, the output table stores the fields in asset proto as columns. This API implements the [google.longrunning.Operation][google.longrunning.Operation] API , which allows you to keep track of the export. We recommend intervals of at least 2 seconds with exponential retry to poll the export operation result. For regular-size resource parent, the export operation usually finishes within 5 minutes. Returns: Callable[[~.ExportAssetsRequest], Awaitable[~.Operation]]: 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 'export_assets' not in self._stubs: self._stubs['export_assets'] = self.grpc_channel.unary_unary( '/google.cloud.asset.v1p7beta1.AssetService/ExportAssets', request_serializer=asset_service.ExportAssetsRequest.serialize, response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs['export_assets'] __all__ = ( 'AssetServiceGrpcAsyncIOTransport', )
staujd02/Pi-RFID-Video-Player
refs/heads/master
source/guiComponents/tkinterImplementation.py
1
import Tkinter import tkinter class TkinterImplementation(object): def begin(self, wrappedIdleImage): self.root = tkinter.Tk() self.root.overrideredirect(True) self.root.geometry( "{0}x{1}+0+0".format(self.root.winfo_screenwidth(), self.root.winfo_screenheight())) self.root.config(background='black') self.panel = Tkinter.Label(self.root, image=wrappedIdleImage.getImage()) self.panel.config(background='black') self.panel.pack(side='bottom', fill='both', expand='yes') self.root.update() def update(self): self.root.update() def changeImage(self, image): self.panel.config(image=image) self.root.update()
VirtualMonitor/VirtualMonitor
refs/heads/master
src/VBox/Devices/Network/scripts/VBoxPortForwarding.py
10
#!/usr/bin/python """ Copyright (C) 2009-2012 Oracle Corporation This file is part of VirtualBox Open Source Edition (OSE), as available from http://www.virtualbox.org. This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation, in version 2 as it comes in the "COPYING" file of the VirtualBox OSE distribution. VirtualBox OSE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. """ ################################################################################# # This program is a port-forwarding configurator supposed to simplify # port-forwarding for NAT users # > python VBoxPortForwarding.py --vm winXP -a 1 -p TCP -l 8080 -g 80 -P www # generates sequence of API calls, equivalent to: # > VBoxManage setextradata "winXP" # "VBoxInternal/Devices/pcnet/0/LUN#0/Config/www/Protocol" TCP # > VBoxManage setextradata "winXP" # "VBoxInternal/Devices/pcnet/0/LUN#0/Config/www/GuestPort" 80 # > VBoxManage setextradata "winXP" # "VBoxInternal/Devices/pcnet/0/LUN#0/Config/www/HostPort" 8080 ################################################################################ import os,sys from vboxapi import VirtualBoxManager import optparse class OptionParser (optparse.OptionParser): def check_required(self, opt): option = self.get_option(opt) if option.type == "string" and getattr(self.values, option.dest) != None: return True if option.type == "int" and getattr(self.values, option.dest) != -1: return True return False def generate_profile_name(proto, host_port, guest_port): return proto + '_' + str(host_port) + '_' + str(guest_port) def main(argv): usage = "usage: %prog --vm winXP -a 1 -p TCP -l 8080 -g 80 -P www" parser = OptionParser(usage=usage) parser.add_option("-V", "--vm", action="store", dest="vmname", type="string", help="Name or UID of VM to operate on", default=None) parser.add_option("-P", "--profile", dest="profile", type="string", default=None) parser.add_option("-p", "--ip-proto", dest="proto", type="string", default=None) parser.add_option("-l", "--host-port", dest="host_port", type="int", default = -1) parser.add_option("-g", "--guest-port", dest="guest_port", type="int", default = -1) parser.add_option("-a", "--adapter", dest="adapter", type="int", default=-1) (options,args) = parser.parse_args(argv) if (not (parser.check_required("-V") or parser.check_required("-G"))): parser.error("please define --vm or --guid option") if (not parser.check_required("-p")): parser.error("please define -p or --ip-proto option") if (not parser.check_required("-l")): parser.error("please define -l or --host_port option") if (not parser.check_required("-g")): parser.error("please define -g or --guest_port option") if (not parser.check_required("-a")): parser.error("please define -a or --adapter option") man = VirtualBoxManager(None, None) vb = man.getVirtualBox() print "VirtualBox version: %s" % vb.version, print "r%s" % vb.revision vm = None try: if options.vmname != None: vm = vb.findMachine(options.vmname) elif options.vmname != None: vm = vb.getMachine(options.vmname) except: print "can't find VM by name or UID:",options.vmname del man return print "vm found: %s [%s]" % (vm.name, vm.id) session = man.openMachineSession(vm.id) vm = session.machine adapter = vm.getNetworkAdapter(options.adapter) if adapter.enabled == False: print "adapter(%d) is disabled" % adapter.slot del man return name = None if (adapter.adapterType == man.constants.NetworkAdapterType_Null): print "none adapter type detected" return -1 elif (adapter.adapterType == man.constants.NetworkAdapterType_Am79C970A): name = "pcnet" elif (adapter.adapterType == man.constants.NetworkAdapterType_Am79C973): name = "pcnet" elif (adapter.adapterType == man.constants.NetworkAdapterType_I82540EM): name = "e1000" elif (adapter.adapterType == man.constants.NetworkAdapterType_I82545EM): name = "e1000" elif (adapter.adapterType == man.constants.NetworkAdapterType_I82543GC): name = "e1000" print "adapter of '%s' type has been detected" % name profile_name = options.profile if profile_name == None: profile_name = generate_profile_name(options.proto.upper(), options.host_port, options.guest_port) config = "VBoxInternal/Devices/" + name + "/" config = config + str(adapter.slot) +"/LUN#0/Config/" + profile_name proto = config + "/Protocol" host_port = config + "/HostPort" guest_port = config + "/GuestPort" vm.setExtraData(proto, options.proto.upper()) vm.setExtraData(host_port, str(options.host_port)) vm.setExtraData(guest_port, str(options.guest_port)) vm.saveSettings() man.closeMachineSession(session) del man if __name__ == "__main__": main(sys.argv)
joebowen/LogMyRocket_API
refs/heads/master
LogMyRocket/libraries/sys_packages/docutils/docutils/parsers/rst/roles.py
108
# $Id: roles.py 7514 2012-09-14 14:27:12Z milde $ # Author: Edward Loper <edloper@gradient.cis.upenn.edu> # Copyright: This module has been placed in the public domain. """ This module defines standard interpreted text role functions, a registry for interpreted text roles, and an API for adding to and retrieving from the registry. The interface for interpreted role functions is as follows:: def role_fn(name, rawtext, text, lineno, inliner, options={}, content=[]): code... # Set function attributes for customization: role_fn.options = ... role_fn.content = ... Parameters: - ``name`` is the local name of the interpreted text role, the role name actually used in the document. - ``rawtext`` is a string containing the entire interpreted text construct. Return it as a ``problematic`` node linked to a system message if there is a problem. - ``text`` is the interpreted text content, with backslash escapes converted to nulls (``\x00``). - ``lineno`` is the line number where the interpreted text beings. - ``inliner`` is the Inliner object that called the role function. It defines the following useful attributes: ``reporter``, ``problematic``, ``memo``, ``parent``, ``document``. - ``options``: A dictionary of directive options for customization, to be interpreted by the role function. Used for additional attributes for the generated elements and other functionality. - ``content``: A list of strings, the directive content for customization ("role" directive). To be interpreted by the role function. Function attributes for customization, interpreted by the "role" directive: - ``options``: A dictionary, mapping known option names to conversion functions such as `int` or `float`. ``None`` or an empty dict implies no options to parse. Several directive option conversion functions are defined in the `directives` module. All role functions implicitly support the "class" option, unless disabled with an explicit ``{'class': None}``. - ``content``: A boolean; true if content is allowed. Client code must handle the case where content is required but not supplied (an empty content list will be supplied). Note that unlike directives, the "arguments" function attribute is not supported for role customization. Directive arguments are handled by the "role" directive itself. Interpreted role functions return a tuple of two values: - A list of nodes which will be inserted into the document tree at the point where the interpreted role was encountered (can be an empty list). - A list of system messages, which will be inserted into the document tree immediately after the end of the current inline block (can also be empty). """ __docformat__ = 'reStructuredText' from docutils import nodes, utils from docutils.parsers.rst import directives from docutils.parsers.rst.languages import en as _fallback_language_module from docutils.utils.code_analyzer import Lexer, LexerError DEFAULT_INTERPRETED_ROLE = 'title-reference' """ The canonical name of the default interpreted role. This role is used when no role is specified for a piece of interpreted text. """ _role_registry = {} """Mapping of canonical role names to role functions. Language-dependent role names are defined in the ``language`` subpackage.""" _roles = {} """Mapping of local or language-dependent interpreted text role names to role functions.""" def role(role_name, language_module, lineno, reporter): """ Locate and return a role function from its language-dependent name, along with a list of system messages. If the role is not found in the current language, check English. Return a 2-tuple: role function (``None`` if the named role cannot be found) and a list of system messages. """ normname = role_name.lower() messages = [] msg_text = [] if normname in _roles: return _roles[normname], messages if role_name: canonicalname = None try: canonicalname = language_module.roles[normname] except AttributeError, error: msg_text.append('Problem retrieving role entry from language ' 'module %r: %s.' % (language_module, error)) except KeyError: msg_text.append('No role entry for "%s" in module "%s".' % (role_name, language_module.__name__)) else: canonicalname = DEFAULT_INTERPRETED_ROLE # If we didn't find it, try English as a fallback. if not canonicalname: try: canonicalname = _fallback_language_module.roles[normname] msg_text.append('Using English fallback for role "%s".' % role_name) except KeyError: msg_text.append('Trying "%s" as canonical role name.' % role_name) # The canonical name should be an English name, but just in case: canonicalname = normname # Collect any messages that we generated. if msg_text: message = reporter.info('\n'.join(msg_text), line=lineno) messages.append(message) # Look the role up in the registry, and return it. if canonicalname in _role_registry: role_fn = _role_registry[canonicalname] register_local_role(normname, role_fn) return role_fn, messages else: return None, messages # Error message will be generated by caller. def register_canonical_role(name, role_fn): """ Register an interpreted text role by its canonical name. :Parameters: - `name`: The canonical name of the interpreted role. - `role_fn`: The role function. See the module docstring. """ set_implicit_options(role_fn) _role_registry[name] = role_fn def register_local_role(name, role_fn): """ Register an interpreted text role by its local or language-dependent name. :Parameters: - `name`: The local or language-dependent name of the interpreted role. - `role_fn`: The role function. See the module docstring. """ set_implicit_options(role_fn) _roles[name] = role_fn def set_implicit_options(role_fn): """ Add customization options to role functions, unless explicitly set or disabled. """ if not hasattr(role_fn, 'options') or role_fn.options is None: role_fn.options = {'class': directives.class_option} elif 'class' not in role_fn.options: role_fn.options['class'] = directives.class_option def register_generic_role(canonical_name, node_class): """For roles which simply wrap a given `node_class` around the text.""" role = GenericRole(canonical_name, node_class) register_canonical_role(canonical_name, role) class GenericRole: """ Generic interpreted text role, where the interpreted text is simply wrapped with the provided node class. """ def __init__(self, role_name, node_class): self.name = role_name self.node_class = node_class def __call__(self, role, rawtext, text, lineno, inliner, options={}, content=[]): set_classes(options) return [self.node_class(rawtext, utils.unescape(text), **options)], [] class CustomRole: """ Wrapper for custom interpreted text roles. """ def __init__(self, role_name, base_role, options={}, content=[]): self.name = role_name self.base_role = base_role self.options = None if hasattr(base_role, 'options'): self.options = base_role.options self.content = None if hasattr(base_role, 'content'): self.content = base_role.content self.supplied_options = options self.supplied_content = content def __call__(self, role, rawtext, text, lineno, inliner, options={}, content=[]): opts = self.supplied_options.copy() opts.update(options) cont = list(self.supplied_content) if cont and content: cont += '\n' cont.extend(content) return self.base_role(role, rawtext, text, lineno, inliner, options=opts, content=cont) def generic_custom_role(role, rawtext, text, lineno, inliner, options={}, content=[]): """""" # Once nested inline markup is implemented, this and other methods should # recursively call inliner.nested_parse(). set_classes(options) return [nodes.inline(rawtext, utils.unescape(text), **options)], [] generic_custom_role.options = {'class': directives.class_option} ###################################################################### # Define and register the standard roles: ###################################################################### register_generic_role('abbreviation', nodes.abbreviation) register_generic_role('acronym', nodes.acronym) register_generic_role('emphasis', nodes.emphasis) register_generic_role('literal', nodes.literal) register_generic_role('strong', nodes.strong) register_generic_role('subscript', nodes.subscript) register_generic_role('superscript', nodes.superscript) register_generic_role('title-reference', nodes.title_reference) def pep_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: pepnum = int(text) if pepnum < 0 or pepnum > 9999: raise ValueError except ValueError: msg = inliner.reporter.error( 'PEP number must be a number from 0 to 9999; "%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] # Base URL mainly used by inliner.pep_reference; so this is correct: ref = (inliner.document.settings.pep_base_url + inliner.document.settings.pep_file_url_template % pepnum) set_classes(options) return [nodes.reference(rawtext, 'PEP ' + utils.unescape(text), refuri=ref, **options)], [] register_canonical_role('pep-reference', pep_reference_role) def rfc_reference_role(role, rawtext, text, lineno, inliner, options={}, content=[]): try: rfcnum = int(text) if rfcnum <= 0: raise ValueError except ValueError: msg = inliner.reporter.error( 'RFC number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] # Base URL mainly used by inliner.rfc_reference, so this is correct: ref = inliner.document.settings.rfc_base_url + inliner.rfc_url % rfcnum set_classes(options) node = nodes.reference(rawtext, 'RFC ' + utils.unescape(text), refuri=ref, **options) return [node], [] register_canonical_role('rfc-reference', rfc_reference_role) def raw_role(role, rawtext, text, lineno, inliner, options={}, content=[]): if not inliner.document.settings.raw_enabled: msg = inliner.reporter.warning('raw (and derived) roles disabled') prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] if 'format' not in options: msg = inliner.reporter.error( 'No format (Writer name) is associated with this role: "%s".\n' 'The "raw" role cannot be used directly.\n' 'Instead, use the "role" directive to create a new role with ' 'an associated format.' % role, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] set_classes(options) node = nodes.raw(rawtext, utils.unescape(text, 1), **options) node.source, node.line = inliner.reporter.get_source_and_line(lineno) return [node], [] raw_role.options = {'format': directives.unchanged} register_canonical_role('raw', raw_role) def code_role(role, rawtext, text, lineno, inliner, options={}, content=[]): set_classes(options) language = options.get('language', '') classes = ['code'] if 'classes' in options: classes.extend(options['classes']) if language and language not in classes: classes.append(language) try: tokens = Lexer(utils.unescape(text, 1), language, inliner.document.settings.syntax_highlight) except LexerError, error: msg = inliner.reporter.warning(error) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] node = nodes.literal(rawtext, '', classes=classes) # analyze content and add nodes for every token for classes, value in tokens: # print (classes, value) if classes: node += nodes.inline(value, value, classes=classes) else: # insert as Text to decrease the verbosity of the output node += nodes.Text(value, value) return [node], [] code_role.options = {'class': directives.class_option, 'language': directives.unchanged} register_canonical_role('code', code_role) def math_role(role, rawtext, text, lineno, inliner, options={}, content=[]): i = rawtext.find('`') text = rawtext.split('`')[1] node = nodes.math(rawtext, text) return [node], [] register_canonical_role('math', math_role) ###################################################################### # Register roles that are currently unimplemented. ###################################################################### def unimplemented_role(role, rawtext, text, lineno, inliner, attributes={}): msg = inliner.reporter.error( 'Interpreted text role "%s" not implemented.' % role, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] register_canonical_role('index', unimplemented_role) register_canonical_role('named-reference', unimplemented_role) register_canonical_role('anonymous-reference', unimplemented_role) register_canonical_role('uri-reference', unimplemented_role) register_canonical_role('footnote-reference', unimplemented_role) register_canonical_role('citation-reference', unimplemented_role) register_canonical_role('substitution-reference', unimplemented_role) register_canonical_role('target', unimplemented_role) # This should remain unimplemented, for testing purposes: register_canonical_role('restructuredtext-unimplemented-role', unimplemented_role) def set_classes(options): """ Auxiliary function to set options['classes'] and delete options['class']. """ if 'class' in options: assert 'classes' not in options options['classes'] = options['class'] del options['class']
vladmm/intellij-community
refs/heads/master
python/testData/fillParagraph/string.py
83
p = "my new <caret>string blah blah blah ;j;dsjv sd;fj;dsjf;ds js;djgf ;jsg s;dgj; sjd;gj sd;gj ;sjg;j asdl j;sjdg; jasdgl j;sldjg ;jsd;gj "
SoftwareMaven/django
refs/heads/master
django/conf/locale/id/formats.py
504
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j N Y' DATETIME_FORMAT = "j N Y, G.i" TIME_FORMAT = 'G.i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd-m-Y' SHORT_DATETIME_FORMAT = 'd-m-Y G.i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d-%m-%y', '%d/%m/%y', # '25-10-09', 25/10/09' '%d-%m-%Y', '%d/%m/%Y', # '25-10-2009', 25/10/2009' '%d %b %Y', # '25 Oct 2006', '%d %B %Y', # '25 October 2006' ] TIME_INPUT_FORMATS = [ '%H.%M.%S', # '14.30.59' '%H.%M', # '14.30' ] DATETIME_INPUT_FORMATS = [ '%d-%m-%Y %H.%M.%S', # '25-10-2009 14.30.59' '%d-%m-%Y %H.%M.%S.%f', # '25-10-2009 14.30.59.000200' '%d-%m-%Y %H.%M', # '25-10-2009 14.30' '%d-%m-%Y', # '25-10-2009' '%d-%m-%y %H.%M.%S', # '25-10-09' 14.30.59' '%d-%m-%y %H.%M.%S.%f', # '25-10-09' 14.30.59.000200' '%d-%m-%y %H.%M', # '25-10-09' 14.30' '%d-%m-%y', # '25-10-09'' '%m/%d/%y %H.%M.%S', # '10/25/06 14.30.59' '%m/%d/%y %H.%M.%S.%f', # '10/25/06 14.30.59.000200' '%m/%d/%y %H.%M', # '10/25/06 14.30' '%m/%d/%y', # '10/25/06' '%m/%d/%Y %H.%M.%S', # '25/10/2009 14.30.59' '%m/%d/%Y %H.%M.%S.%f', # '25/10/2009 14.30.59.000200' '%m/%d/%Y %H.%M', # '25/10/2009 14.30' '%m/%d/%Y', # '10/25/2009' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
Poles/Poles
refs/heads/master
platforms/windows/JsonCpp/scons-local-2.3.0/SCons/Tool/f03.py
11
"""engine.SCons.Tool.f03 Tool-specific initialization for the generic Posix f03 Fortran compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/f03.py 2013/03/03 09:48:35 garyo" import SCons.Defaults import SCons.Tool import SCons.Util import fortran from SCons.Tool.FortranCommon import add_all_to_env, add_f03_to_env compilers = ['f03'] def generate(env): add_all_to_env(env) add_f03_to_env(env) fcomp = env.Detect(compilers) or 'f03' env['F03'] = fcomp env['SHF03'] = fcomp env['FORTRAN'] = fcomp env['SHFORTRAN'] = fcomp def exists(env): return env.Detect(compilers) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
karlnapf/shogun
refs/heads/develop
examples/undocumented/python/so_multiclass.py
4
#!/usr/bin/env python import numpy as np def gen_data(num_classes,num_samples,dim): np.random.seed(0) covs = np.array([[[0., -1. ], [2.5, .7]], [[3., -1.5], [1.2, .3]], [[ 2, 0 ], [ .0, 1.5 ]]]) X = np.r_[np.dot(np.random.randn(num_samples, dim), covs[0]) + np.array([0, 10]), np.dot(np.random.randn(num_samples, dim), covs[1]) + np.array([-10, -10]), np.dot(np.random.randn(num_samples, dim), covs[2]) + np.array([10, -10])]; Y = np.hstack((np.zeros(num_samples), np.ones(num_samples), 2*np.ones(num_samples))) return X, Y # Number of classes M = 3 # Number of samples of each class N = 50 # Dimension of the data dim = 2 traindat, label_traindat = gen_data(M,N,dim) parameter_list = [[traindat,label_traindat]] def so_multiclass (fm_train_real=traindat,label_train_multiclass=label_traindat): try: from shogun import RealFeatures from shogun import MulticlassModel, MulticlassSOLabels, PrimalMosekSOSVM, RealNumber except ImportError: print("Mosek not available") return labels = MulticlassSOLabels(label_train_multiclass) features = sg.features(fm_train_real.T) model = MulticlassModel(features, labels) sosvm = PrimalMosekSOSVM(model, labels) sosvm.train() out = sosvm.apply() count = 0 for i in xrange(out.get_num_labels()): yi_pred = RealNumber.obtain_from_generic(out.get_label(i)) if yi_pred.value == label_train_multiclass[i]: count = count + 1 print("Correct classification rate: %0.2f" % ( 100.0*count/out.get_num_labels() )) if __name__=='__main__': print('SO multiclass') so_multiclass(*parameter_list[0])
seandavi/seqtools
refs/heads/master
SDST/__init__.py
9480
#