code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class Describe_BaseSortRowsByValueHelper: <NEW_LINE> <INDENT> def it_provides_the_order( self, SortByValueCollator_, _rows_dimension_prop_, _element_values_prop_, _subtotal_values_prop_, _empty_row_idxs_prop_, ): <NEW_LINE> <INDENT> _BaseSortRowsByValueHelper(None, None)._order <NEW_LINE> SortByValueCollator_.display_order.assert_called_once_with( _rows_dimension_prop_(), _element_values_prop_(), _subtotal_values_prop_(), _empty_row_idxs_prop_(), ) <NEW_LINE> <DEDENT> def but_it_falls_back_to_payload_order_on_value_error( self, request, dimensions_, _element_values_prop_, _subtotal_values_prop_, _empty_row_idxs_prop_, SortByValueCollator_, ): <NEW_LINE> <INDENT> _element_values_prop_.return_value = None <NEW_LINE> _subtotal_values_prop_.return_value = None <NEW_LINE> _empty_row_idxs_prop_.return_value = (4, 2) <NEW_LINE> SortByValueCollator_.display_order.side_effect = ValueError <NEW_LINE> PayloadOrderCollator_ = class_mock( request, "cr.cube.matrix.assembler.PayloadOrderCollator" ) <NEW_LINE> PayloadOrderCollator_.display_order.return_value = (1, 2, 3, 4) <NEW_LINE> order_helper = _BaseSortRowsByValueHelper(dimensions_, None) <NEW_LINE> order = order_helper._order <NEW_LINE> PayloadOrderCollator_.display_order.assert_called_once_with( dimensions_[0], (4, 2) ) <NEW_LINE> assert order == (1, 2, 3, 4) <NEW_LINE> <DEDENT> @pytest.fixture <NEW_LINE> def dimensions_(self, request): <NEW_LINE> <INDENT> return (instance_mock(request, Dimension), instance_mock(request, Dimension)) <NEW_LINE> <DEDENT> @pytest.fixture <NEW_LINE> def _element_values_prop_(self, request): <NEW_LINE> <INDENT> return property_mock(request, _BaseSortRowsByValueHelper, "_element_values") <NEW_LINE> <DEDENT> @pytest.fixture <NEW_LINE> def _empty_row_idxs_prop_(self, request): <NEW_LINE> <INDENT> return property_mock(request, _BaseSortRowsByValueHelper, "_empty_row_idxs") <NEW_LINE> <DEDENT> @pytest.fixture <NEW_LINE> def _rows_dimension_prop_(self, request): <NEW_LINE> <INDENT> return property_mock(request, _BaseSortRowsByValueHelper, "_rows_dimension") <NEW_LINE> <DEDENT> @pytest.fixture <NEW_LINE> def SortByValueCollator_(self, request): <NEW_LINE> <INDENT> return class_mock(request, "cr.cube.matrix.assembler.SortByValueCollator") <NEW_LINE> <DEDENT> @pytest.fixture <NEW_LINE> def _subtotal_values_prop_(self, request): <NEW_LINE> <INDENT> return property_mock(request, _BaseSortRowsByValueHelper, "_subtotal_values")
Unit test suite for `cr.cube.matrix.assembler._BaseSortRowsByValueHelper`.
62598fa9b7558d5895463592
class MainPane (object): <NEW_LINE> <INDENT> __metaclass__ = ABCMeta <NEW_LINE> def __init__ (self, parent, auiManager, application): <NEW_LINE> <INDENT> self._parent = parent <NEW_LINE> self._auiManager = auiManager <NEW_LINE> self._application = application <NEW_LINE> self._panel = self._createPanel() <NEW_LINE> self._config = self._createConfig() <NEW_LINE> pane = self._createPane() <NEW_LINE> self._auiManager.AddPane(self._panel, pane) <NEW_LINE> <DEDENT> def _savePaneInfo (self, param, paneInfo): <NEW_LINE> <INDENT> string_info = self._auiManager.SavePaneInfo (paneInfo) <NEW_LINE> param.value = string_info <NEW_LINE> <DEDENT> def _loadPaneInfo (self, param): <NEW_LINE> <INDENT> string_info = param.value <NEW_LINE> if len (string_info) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> pane = wx.aui.AuiPaneInfo() <NEW_LINE> try: <NEW_LINE> <INDENT> self._auiManager.LoadPaneInfo (string_info, pane) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> return pane <NEW_LINE> <DEDENT> def loadPaneSize (self): <NEW_LINE> <INDENT> self.pane.BestSize ((self.config.width.value, self.config.height.value)) <NEW_LINE> <DEDENT> def show (self): <NEW_LINE> <INDENT> self.pane.Show() <NEW_LINE> <DEDENT> def hide (self): <NEW_LINE> <INDENT> self.pane.Hide() <NEW_LINE> <DEDENT> def isShown (self): <NEW_LINE> <INDENT> return self.pane.IsShown() <NEW_LINE> <DEDENT> def close (self): <NEW_LINE> <INDENT> self.panel.Close() <NEW_LINE> <DEDENT> def saveParams (self): <NEW_LINE> <INDENT> self._savePaneInfo (self.config.pane, self._auiManager.GetPane (self.panel)) <NEW_LINE> self.config.width.value = self.panel.GetSizeTuple()[0] <NEW_LINE> self.config.height.value = self.panel.GetSizeTuple()[1] <NEW_LINE> <DEDENT> @abstractproperty <NEW_LINE> def caption (self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def _createPanel(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def _createConfig (self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @property <NEW_LINE> def panel (self): <NEW_LINE> <INDENT> return self._panel <NEW_LINE> <DEDENT> @property <NEW_LINE> def config (self): <NEW_LINE> <INDENT> return self._config <NEW_LINE> <DEDENT> @property <NEW_LINE> def parent (self): <NEW_LINE> <INDENT> return self._parent <NEW_LINE> <DEDENT> @property <NEW_LINE> def application (self): <NEW_LINE> <INDENT> return self._application <NEW_LINE> <DEDENT> @property <NEW_LINE> def pane (self): <NEW_LINE> <INDENT> return self._auiManager.GetPane (self.panel)
Базовый класс для хранения основных панелей главного окна
62598fa95166f23b2e24333b
class BluetoothPlugin(interface.PlistPlugin): <NEW_LINE> <INDENT> NAME = 'macosx_bluetooth' <NEW_LINE> DATA_FORMAT = 'Bluetooth plist file' <NEW_LINE> PLIST_PATH_FILTERS = frozenset([ interface.PlistPathFilter('com.apple.bluetooth.plist')]) <NEW_LINE> PLIST_KEYS = frozenset(['DeviceCache', 'PairedDevices']) <NEW_LINE> def GetEntries(self, parser_mediator, match=None, **unused_kwargs): <NEW_LINE> <INDENT> device_cache = match.get('DeviceCache', {}) <NEW_LINE> for device, value in device_cache.items(): <NEW_LINE> <INDENT> name = value.get('Name', '') <NEW_LINE> if name: <NEW_LINE> <INDENT> name = ''.join(('Name:', name)) <NEW_LINE> <DEDENT> event_data = plist_event.PlistTimeEventData() <NEW_LINE> event_data.root = '/DeviceCache' <NEW_LINE> datetime_value = value.get('LastInquiryUpdate', None) <NEW_LINE> if datetime_value: <NEW_LINE> <INDENT> event_data.desc = ' '.join( filter(None, ('Bluetooth Discovery', name))) <NEW_LINE> event_data.key = '{0:s}/LastInquiryUpdate'.format(device) <NEW_LINE> date_time = dfdatetime_time_elements.TimeElementsInMicroseconds() <NEW_LINE> date_time.CopyFromDatetime(datetime_value) <NEW_LINE> event = time_events.DateTimeValuesEvent( date_time, definitions.TIME_DESCRIPTION_WRITTEN) <NEW_LINE> parser_mediator.ProduceEventWithEventData(event, event_data) <NEW_LINE> if device in match.get('PairedDevices', []): <NEW_LINE> <INDENT> event_data.desc = 'Paired:True {0:s}'.format(name) <NEW_LINE> event_data.key = device <NEW_LINE> date_time = dfdatetime_time_elements.TimeElementsInMicroseconds() <NEW_LINE> date_time.CopyFromDatetime(datetime_value) <NEW_LINE> event = time_events.DateTimeValuesEvent( date_time, definitions.TIME_DESCRIPTION_WRITTEN) <NEW_LINE> parser_mediator.ProduceEventWithEventData(event, event_data) <NEW_LINE> <DEDENT> <DEDENT> datetime_value = value.get('LastNameUpdate', None) <NEW_LINE> if datetime_value: <NEW_LINE> <INDENT> event_data.desc = ' '.join(filter(None, ('Device Name Set', name))) <NEW_LINE> event_data.key = '{0:s}/LastNameUpdate'.format(device) <NEW_LINE> date_time = dfdatetime_time_elements.TimeElementsInMicroseconds() <NEW_LINE> date_time.CopyFromDatetime(datetime_value) <NEW_LINE> event = time_events.DateTimeValuesEvent( date_time, definitions.TIME_DESCRIPTION_WRITTEN) <NEW_LINE> parser_mediator.ProduceEventWithEventData(event, event_data) <NEW_LINE> <DEDENT> datetime_value = value.get('LastServicesUpdate', None) <NEW_LINE> if datetime_value: <NEW_LINE> <INDENT> event_data.desc = ' '.join(filter(None, ('Services Updated', name))) <NEW_LINE> event_data.key = '{0:s}/LastServicesUpdate'.format(device) <NEW_LINE> date_time = dfdatetime_time_elements.TimeElementsInMicroseconds() <NEW_LINE> date_time.CopyFromDatetime(datetime_value) <NEW_LINE> event = time_events.DateTimeValuesEvent( date_time, definitions.TIME_DESCRIPTION_WRITTEN) <NEW_LINE> parser_mediator.ProduceEventWithEventData(event, event_data)
Plist parser plugin for Bluetooth plist files. Additional details about the fields. LastInquiryUpdate: Device connected via Bluetooth Discovery. Updated when a device is detected in discovery mode. E.g. BT headphone power on. Pairing is not required for a device to be discovered and cached. LastNameUpdate: When the human name was last set. Usually done only once during initial setup. LastServicesUpdate: Time set when device was polled to determine what it is. Usually done at setup or manually requested via advanced menu.
62598fa94e4d562566372388
class DeleteSchemaView(LoginRequiredMixin, View): <NEW_LINE> <INDENT> def post(self, request, schema_id): <NEW_LINE> <INDENT> if request.is_ajax(): <NEW_LINE> <INDENT> schema = Schema.objects.filter(id=schema_id, owner=request.user) <NEW_LINE> schema.delete() <NEW_LINE> return JsonResponse({'succsess': schema_id}, status=200)
Responsible for delete schemas. Receive a POST AJAX request and delete schema in database and send json data to front end.
62598fa9aad79263cf42e737
class DevelopmentConfig(Config): <NEW_LINE> <INDENT> DEBUG = True
Application development configurations
62598fa9f7d966606f747f48
class AboutDialog(QtGui.QDialog): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> QtGui.QDialog.__init__(self) <NEW_LINE> self.ui = Ui_FreeseerAbout() <NEW_LINE> self.ui.setupUi(self) <NEW_LINE> self.ui.aboutInfo.setText(ABOUT_INFO)
About dialog class for displaying app information.
62598fa9442bda511e95c3ba
class CliResolver(Resolver): <NEW_LINE> <INDENT> def resolve(self, param: inspect.Parameter) -> typing.Optional[typing.Tuple[str, typing.Callable]]: <NEW_LINE> <INDENT> key = 'param:%s' % param.name <NEW_LINE> func = self.command_line_argument <NEW_LINE> return (key, func) <NEW_LINE> <DEDENT> def command_line_argument(self, name: ParamName, kwargs: KeywordArgs) -> typing.Any: <NEW_LINE> <INDENT> return kwargs[name]
Handles resolving parameters for running with the command line.
62598fa92ae34c7f260ab045
class HPBasicCode(): <NEW_LINE> <INDENT> def __init__(self,file_path=None,**options): <NEW_LINE> <INDENT> if file_path is None: <NEW_LINE> <INDENT> print("Please Do Not Write Any More HP Basic Code!!") <NEW_LINE> raise <NEW_LINE> <DEDENT> self.path=file_path <NEW_LINE> self.code=[] <NEW_LINE> in_file=open(self.path,'r') <NEW_LINE> for line in in_file: <NEW_LINE> <INDENT> self.code.append(line) <NEW_LINE> <DEDENT> defaults={} <NEW_LINE> self.options={} <NEW_LINE> for key,value in defaults.iteritems(): <NEW_LINE> <INDENT> self.options[key]=value <NEW_LINE> <DEDENT> for key,value in options.iteritems(): <NEW_LINE> <INDENT> self.options[key]=value
This Class Serves a container for HPBasic Code that has been converted to DOS Compatible ASCII.
62598fa97d847024c075c327
class Ksztalt(QWidget): <NEW_LINE> <INDENT> prost = QRect(1, 1, 101, 101) <NEW_LINE> punkty = QPolygon([ QPoint(1, 101), QPoint(51, 1), QPoint(101, 101)]) <NEW_LINE> def __init__(self, parent, ksztalt=Ksztalty.Rect): <NEW_LINE> <INDENT> super(Ksztalt, self).__init__(parent) <NEW_LINE> self.ksztalt = ksztalt <NEW_LINE> self.kolorO = QColor(0, 0, 0) <NEW_LINE> self.kolorW = QColor(155, 255, 255) <NEW_LINE> <DEDENT> def paintEvent(self, e): <NEW_LINE> <INDENT> qp = QPainter() <NEW_LINE> qp.begin(self) <NEW_LINE> self.rysujFigury(e, qp) <NEW_LINE> qp.end() <NEW_LINE> <DEDENT> def rysujFigury(self, e, qp): <NEW_LINE> <INDENT> qp.setPen(self.kolorO) <NEW_LINE> qp.setBrush(self.kolorW) <NEW_LINE> qp.setRenderHint(QPainter.Antialiasing) <NEW_LINE> if self.ksztalt == Ksztalty.Rect: <NEW_LINE> <INDENT> qp.drawRect(self.prost) <NEW_LINE> <DEDENT> elif self.ksztalt == Ksztalty.Ellipse: <NEW_LINE> <INDENT> qp.drawEllipse(self.prost) <NEW_LINE> <DEDENT> elif self.ksztalt == Ksztalty.Polygon: <NEW_LINE> <INDENT> qp.drawPolygon(self.punkty) <NEW_LINE> <DEDENT> elif self.ksztalt == Ksztalty.Line: <NEW_LINE> <INDENT> qp.drawLine(self.prost.topLeft(), self.prost.bottomRight()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> qp.drawRect(self.prost) <NEW_LINE> <DEDENT> <DEDENT> def sizeHint(self): <NEW_LINE> <INDENT> return QSize(102, 102) <NEW_LINE> <DEDENT> def minimumSizeHint(self): <NEW_LINE> <INDENT> return QSize(102, 102) <NEW_LINE> <DEDENT> def ustawKsztalt(self, ksztalt): <NEW_LINE> <INDENT> self.ksztalt = ksztalt <NEW_LINE> self.update() <NEW_LINE> <DEDENT> def ustawKolorW(self, r=0, g=0, b=0): <NEW_LINE> <INDENT> self.kolorW = QColor(r, g, b) <NEW_LINE> self.update()
Klasa definiująca widget do rysowania kształtów
62598fa9cb5e8a47e493c12a
class WriteRackNestedSerializer(object): <NEW_LINE> <INDENT> def __init__(self, name=None, facility_id=None): <NEW_LINE> <INDENT> self.swagger_types = { 'name': 'str', 'facility_id': 'str' } <NEW_LINE> self.attribute_map = { 'name': 'name', 'facility_id': 'facility_id' } <NEW_LINE> self._name = name <NEW_LINE> self._facility_id = facility_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @name.setter <NEW_LINE> def name(self, name): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def facility_id(self): <NEW_LINE> <INDENT> return self._facility_id <NEW_LINE> <DEDENT> @facility_id.setter <NEW_LINE> def facility_id(self, facility_id): <NEW_LINE> <INDENT> self._facility_id = facility_id <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fa926068e7796d4c8b8
class And(Condition): <NEW_LINE> <INDENT> def __init__(self, exprs): <NEW_LINE> <INDENT> self.exprs = exprs <NEW_LINE> <DEDENT> def loss(self, args): <NEW_LINE> <INDENT> losses = [exp.loss(args) for exp in self.exprs] <NEW_LINE> return reduce(lambda a, b: a + b, losses) <NEW_LINE> <DEDENT> def satisfy(self, args): <NEW_LINE> <INDENT> ret = None <NEW_LINE> for exp in self.exprs: <NEW_LINE> <INDENT> sat = exp.satisfy(args) <NEW_LINE> if not isinstance(sat, (np.ndarray, np.generic)): <NEW_LINE> <INDENT> sat = sat.cpu().numpy() <NEW_LINE> <DEDENT> if ret is None: <NEW_LINE> <INDENT> ret = sat.copy() <NEW_LINE> <DEDENT> ret = ret * sat <NEW_LINE> <DEDENT> return ret
E_1 & E_2 & ... E_k
62598fa94e4d562566372389
class Response(object): <NEW_LINE> <INDENT> def __init__(self, response): <NEW_LINE> <INDENT> if response.content: <NEW_LINE> <INDENT> self.data = response.json() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data = {}
Basic container for response dictionary :param requests.Response response: Response for call via requests lib
62598fa9d268445f26639b35
class Drone(Zergling): <NEW_LINE> <INDENT> def __init__(self, player): <NEW_LINE> <INDENT> Zergling.__init__(self, player) <NEW_LINE> self.name = 'drone' <NEW_LINE> self.hp = 45 <NEW_LINE> self.taken_supplies = 1 <NEW_LINE> player.busy_supply += self.taken_supplies - 0.5 <NEW_LINE> <DEDENT> def build(self, structure): <NEW_LINE> <INDENT> if (self.owner.is_enough_minerals(structure) and self.owner.is_enough_gas(structure)): <NEW_LINE> <INDENT> self.owner.spend_resources(structure) <NEW_LINE> self.death() <NEW_LINE> return structure <NEW_LINE> <DEDENT> <DEDENT> def mine_minerals(self): <NEW_LINE> <INDENT> self.owner.minerals += 25 <NEW_LINE> <DEDENT> def extracting_gas(self, ): <NEW_LINE> <INDENT> self.owner.gas += 8
Changing drone's characteristics
62598fa9a8ecb03325871174
class Test(unittest.TestCase): <NEW_LINE> <INDENT> data = [ ('waterbottle', 'erbottlewat', True), ('water','', False) ('foo', 'bar', False), ('foo', 'foofoo', False) ] <NEW_LINE> def test_string_rotation(self): <NEW_LINE> <INDENT> for [s1, s2, expected] in self.data: <NEW_LINE> <INDENT> actual = string_rotation(s1, s2) <NEW_LINE> self.assertEqual(actual, expected)
Test Cases
62598fa9f548e778e596b509
class sqlitelib(object): <NEW_LINE> <INDENT> def __init__(self, dbfile): <NEW_LINE> <INDENT> self.dbfile = dbfile <NEW_LINE> self.conn = self.connect() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> self.conn = sqlite3.connect(self.dbfile, isolation_level=None) <NEW_LINE> self.conn.row_factory = self.dict_factory <NEW_LINE> return self.conn <NEW_LINE> <DEDENT> def execute(self, sql, parameters=None): <NEW_LINE> <INDENT> if not parameters: <NEW_LINE> <INDENT> c = self.conn.execute(sql) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> c = self.conn.execute(sql, parameters) <NEW_LINE> <DEDENT> data = c.fetchall() <NEW_LINE> return data <NEW_LINE> <DEDENT> def executemany(self, sql, parameters): <NEW_LINE> <INDENT> c = self.conn.executemany(sql, parameters) <NEW_LINE> data = c.fetchall() <NEW_LINE> return data <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> self.conn.close() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.conn.close() <NEW_LINE> <DEDENT> def dict_factory(self, cursor, row): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for idx, col in enumerate(cursor.description): <NEW_LINE> <INDENT> d[col[0]] = row[idx] <NEW_LINE> <DEDENT> return d
wrapper for sqlite3 providing some convenience functions. Autocommit is on by default, and query results are lists of dicts.
62598fa91f037a2d8b9e4051
class Member(object): <NEW_LINE> <INDENT> def __init__(self, soup): <NEW_LINE> <INDENT> self.soup = soup <NEW_LINE> self.name = self.soup.get('name') <NEW_LINE> self.wn = self.soup.get('wn') <NEW_LINE> self.grouping = self.soup.get('grouping') <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<Member %s %s %s>" % (self.name, self.wn, self.grouping)
Represents a single member of a VerbClass, with associated name, WordNet category and PropBank grouping.
62598fa966656f66f7d5a355
class NoProxy(Proxy): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(NoProxy, self).__init__(None) <NEW_LINE> self._proxy_socket = None <NEW_LINE> <DEDENT> def _connect(self, destination): <NEW_LINE> <INDENT> self._proxy_socket = self._init_connection(destination.address, destination.port) <NEW_LINE> <DEDENT> def is_connected(self): <NEW_LINE> <INDENT> return self._proxy_socket is not None <NEW_LINE> <DEDENT> def _send(self, payload): <NEW_LINE> <INDENT> self._proxy_socket.send(payload.get_bytes()) <NEW_LINE> <DEDENT> def _receive(self): <NEW_LINE> <INDENT> received_bytes = self._read_until_empty(self._proxy_socket) <NEW_LINE> return NoProtocol(received_bytes) <NEW_LINE> <DEDENT> def _close(self): <NEW_LINE> <INDENT> self._proxy_socket.close() <NEW_LINE> self._proxy_socket = None <NEW_LINE> <DEDENT> def copy(self): <NEW_LINE> <INDENT> return NoProxy()
A proxy which is actually no proxy? That's right! The NoProxy class extends from the Proxy class but is actually no proxy but a direct connection. It's used when the program does not make use of a proxy. This method makes the implementation of AttackMethods easier by 'abstracting' away the connection. This approach prevents if-else like connection structures like the following one: if isinstance(myProxy, Proxy): myProxy.send(myProtocol) elif isinstance(myProxy, socket) myProxy.send(myProtocol.get_bytes()) Not all methods are documented because they are already documented in the Proxy class.
62598fa93539df3088ecc217
class TestCompareXLSXFiles(ExcelComparisonTest): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.set_filename('chart_blank03.xlsx') <NEW_LINE> <DEDENT> def test_create_file(self): <NEW_LINE> <INDENT> workbook = Workbook(self.got_filename) <NEW_LINE> worksheet = workbook.add_worksheet() <NEW_LINE> chart = workbook.add_chart({'type': 'line'}) <NEW_LINE> chart.axis_ids = [44253568, 44269952] <NEW_LINE> data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] <NEW_LINE> worksheet.write_column('A1', data[0]) <NEW_LINE> worksheet.write_column('B1', data[1]) <NEW_LINE> worksheet.write_column('C1', data[2]) <NEW_LINE> chart.add_series({'values': '=Sheet1!$A$1:$A$5'}) <NEW_LINE> chart.add_series({'values': '=Sheet1!$B$1:$B$5'}) <NEW_LINE> chart.add_series({'values': '=Sheet1!$C$1:$C$5'}) <NEW_LINE> chart.show_blanks_as('span') <NEW_LINE> worksheet.insert_chart('E9', chart) <NEW_LINE> workbook.close() <NEW_LINE> self.assertExcelEqual()
Test file created by XlsxWriter against a file created by Excel.
62598fa97d43ff24874273b4
class get_Image_with_Tag_args(object): <NEW_LINE> <INDENT> def __init__( self, openstack_id=None, ): <NEW_LINE> <INDENT> self.openstack_id = openstack_id <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if ( iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None ): <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.openstack_id = ( iprot.readString().decode("utf-8", errors="replace") if sys.version_info[0] == 2 else iprot.readString() ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write( oprot._fast_encode(self, [self.__class__, self.thrift_spec]) ) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin("get_Image_with_Tag_args") <NEW_LINE> if self.openstack_id is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin("openstack_id", TType.STRING, 1) <NEW_LINE> oprot.writeString( self.openstack_id.encode("utf-8") if sys.version_info[0] == 2 else self.openstack_id ) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = [f"{key}={value!r}" for key, value in self.__dict__.items()] <NEW_LINE> return f"{self.__class__.__name__}({', '.join(L)})" <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other)
Attributes: - openstack_id
62598fa966673b3332c3032f
class Settings(models.Model): <NEW_LINE> <INDENT> site = models.ForeignKey(Site, unique=True) <NEW_LINE> site_name = models.CharField(max_length=50, editable=False) <NEW_LINE> author_name = models.CharField(_('author name'), max_length=255, blank=True, null=True) <NEW_LINE> copyright = models.CharField(_('copyright'), max_length=255, blank=True, null=True) <NEW_LINE> about = models.TextField(_('about'), help_text=_('Accepts RAW html. By default, appears in right rail.'), blank=True, null=True) <NEW_LINE> twitter_url = models.URLField(_('twitter url'), verify_exists=False, blank=True, null=True) <NEW_LINE> rss_url = models.URLField(_('rss url'), verify_exists=False, blank=True, null=True, help_text=_('The location of your RSS feed. Often used to wire up feedburner.')) <NEW_LINE> email_subscribe_url = models.URLField(_('subscribe via email url'), verify_exists=False, blank=True, null=True) <NEW_LINE> page_size = models.PositiveIntegerField(_('page size'), default=20) <NEW_LINE> ping_google = models.BooleanField(_('ping google'), default=False) <NEW_LINE> disqus_shortname = models.CharField(_('disqus shortname'), max_length=255, blank=True, null=True) <NEW_LINE> meta_keywords = models.TextField(_('meta keywords'), blank=True, null=True) <NEW_LINE> meta_description = models.TextField(_('meta description'), blank=True, null=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _('settings') <NEW_LINE> verbose_name_plural = _('settings') <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return "%s-settings" % self.site.name <NEW_LINE> <DEDENT> def delete(self, *args, **kwargs): <NEW_LINE> <INDENT> if settings.SITE_ID != self.site.id: <NEW_LINE> <INDENT> super(Settings, self).delete(*args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.site_name = self.site.name <NEW_LINE> super(Settings, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_current(): <NEW_LINE> <INDENT> site = Site.objects.get_current() <NEW_LINE> key = create_cache_key(Settings, field='site__id', field_value=site.id) <NEW_LINE> blog_settings = cache.get(key, None) <NEW_LINE> if blog_settings is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> blog_settings = Settings.objects.get(site=site) <NEW_LINE> cache.add(key, blog_settings) <NEW_LINE> <DEDENT> except Settings.DoesNotExist: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> return blog_settings
Global settings for the blog. The class name is plural because "Setting" singular implies one and this is a collection of settings. Possible: dynamic settings could be designed at some point to allow the user to add settings as they wish.
62598fa9090684286d59368e
class MissingTagError(UnicodeException, E.KeyError): <NEW_LINE> <INDENT> pass
The requested tag at the specified address does not exist.
62598fa91b99ca400228f4e2
class QuerySplitterError(Exception): <NEW_LINE> <INDENT> pass
Top-level error type.
62598fa9baa26c4b54d4f216
class SOptionsOfResult(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.__root = Tk() <NEW_LINE> self.__root.title('Результаты') <NEW_LINE> self.__root.geometry('340x200') <NEW_LINE> self.__root.resizable(width=False, height=False) <NEW_LINE> self.__root.protocol('WM_DELETE_WINDOW', self.close) <NEW_LINE> CenterOnScreen(self.__root, size=[340,200]) <NEW_LINE> self.__root.focus_force() <NEW_LINE> btm = Button(self.__root, text='Просмотр результатов') <NEW_LINE> btm.place(x=20, y=20, width=300, height=40) <NEW_LINE> btm.bind('<Button-1>', self.event_btn_1) <NEW_LINE> btm = Button(self.__root, text='Сравнение результатов') <NEW_LINE> btm.place(x=20, y=70, width=300, height=40) <NEW_LINE> btm.bind('<Button-1>', self.event_btn_2) <NEW_LINE> btm = Button(self.__root, text='Назад') <NEW_LINE> btm.place(x=20, y=140, width=300, height=40) <NEW_LINE> btm.bind('<Button-1>', self.event_btn_3) <NEW_LINE> pass <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> ManagerOfScreens.active_screen = SMain <NEW_LINE> self.__root.destroy() <NEW_LINE> pass <NEW_LINE> <DEDENT> def event_btn_1(self, event): <NEW_LINE> <INDENT> ManagerOfScreens.active_screen = SViewResults <NEW_LINE> self.__root.destroy() <NEW_LINE> print('btn_1') <NEW_LINE> pass <NEW_LINE> <DEDENT> def event_btn_2(self, event): <NEW_LINE> <INDENT> ManagerOfScreens.active_screen = SComparisonResults <NEW_LINE> self.__root.destroy() <NEW_LINE> print('btn_1') <NEW_LINE> pass <NEW_LINE> <DEDENT> def event_btn_3(self, event): <NEW_LINE> <INDENT> self.close() <NEW_LINE> pass <NEW_LINE> <DEDENT> pass
Экран опций результатов
62598fa97d847024c075c328
class HeadingRule(Rule): <NEW_LINE> <INDENT> type = 'heading' <NEW_LINE> def condition(self, block): <NEW_LINE> <INDENT> return not '\n' in block and len(block) <= 70 and not block[-1] == ':'
标题占一行,最多 70 个字符,并且不以冒号结尾。
62598fa9a8370b77170f0340
class RegisterHandler(base.APIBaseHandler, MailMixin): <NEW_LINE> <INDENT> @gen.coroutine <NEW_LINE> def post(self): <NEW_LINE> <INDENT> form = forms.RegisterForm(self.json_args, locale_code=self.locale.code) <NEW_LINE> if form.validate(): <NEW_LINE> <INDENT> user = self.create_user(form) <NEW_LINE> yield self.send_confirm_mail(user) <NEW_LINE> self.set_status(201) <NEW_LINE> self.finish(json.dumps({ 'auth': self.get_auth(user.id.hex).decode('utf8'), })) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.validation_error(form) <NEW_LINE> <DEDENT> <DEDENT> @base.db_success_or_500 <NEW_LINE> def create_user(self, form): <NEW_LINE> <INDENT> avatar_num = random.randint(1, 3) <NEW_LINE> avatar_name = "avatar{}.png".format(avatar_num) <NEW_LINE> admin = models.User.query.filter_by(number=0).first() <NEW_LINE> avatar = admin.images.filter_by(filename=avatar_name).first() <NEW_LINE> number = self.session.query(func.max(models.User.number)).first()[0] + 1 <NEW_LINE> user = models.User(email=form.email.data, name=form.name.data, avatar=avatar, number=number) <NEW_LINE> user.set_password(form.password.data) <NEW_LINE> self.session.add(user) <NEW_LINE> self.session.flush() <NEW_LINE> cover = self.create_collection() <NEW_LINE> user.cover_collection = cover <NEW_LINE> self.session.add(user) <NEW_LINE> return user <NEW_LINE> <DEDENT> @base.db_success_or_500 <NEW_LINE> def create_collection(self): <NEW_LINE> <INDENT> collection = models.Collection( name='cover' ) <NEW_LINE> self.session.add(collection) <NEW_LINE> return collection
URL: /register Allowed methods: POST
62598fa94e4d56256637238a
class PrefixStorage(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._mapping = {} <NEW_LINE> self._sizes = [] <NEW_LINE> <DEDENT> def __setitem__(self, key, value): <NEW_LINE> <INDENT> ln = len(key) <NEW_LINE> if ln not in self._sizes: <NEW_LINE> <INDENT> self._sizes.append(ln) <NEW_LINE> self._sizes.sort() <NEW_LINE> self._sizes.reverse() <NEW_LINE> <DEDENT> self._mapping[key] = value <NEW_LINE> <DEDENT> def getByPrefix(self, key, default=None): <NEW_LINE> <INDENT> for ln in self._sizes: <NEW_LINE> <INDENT> k = key[:ln] <NEW_LINE> if k in self._mapping: <NEW_LINE> <INDENT> return self._mapping[k] <NEW_LINE> <DEDENT> <DEDENT> return default
Storage for store information about prefixes. >>> s = PrefixStorage() First we save information for some prefixes: >>> s["123"] = "123 domain" >>> s["12"] = "12 domain" Then we can retrieve prefix information by full key (longest prefix always win): >>> s.getByPrefix("123456") '123 domain' >>> s.getByPrefix("12456") '12 domain' If no prefix has been found then getByPrefix() returns default value: >>> s.getByPrefix("13456", "None") 'None'
62598fa9236d856c2adc93ef
class ReflexAgent(Agent): <NEW_LINE> <INDENT> def getAction(self, gameState): <NEW_LINE> <INDENT> legalMoves = gameState.getLegalActions() <NEW_LINE> scores = [self.evaluationFunction(gameState, action) for action in legalMoves] <NEW_LINE> bestScore = max(scores) <NEW_LINE> bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] <NEW_LINE> chosenIndex = random.choice(bestIndices) <NEW_LINE> "Add more of your code here if you want to" <NEW_LINE> return legalMoves[chosenIndex] <NEW_LINE> <DEDENT> def evaluationFunction(self, currentGameState, action): <NEW_LINE> <INDENT> successorGameState = currentGameState.generatePacmanSuccessor(action) <NEW_LINE> newPos = successorGameState.getPacmanPosition() <NEW_LINE> newFood = successorGameState.getFood() <NEW_LINE> newGhostStates = successorGameState.getGhostStates() <NEW_LINE> newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> def disToNearestGhost(pacmanPos, ghosts): <NEW_LINE> <INDENT> return min([manhattanDistance(pacmanPos, gPos) for gPos in ghosts]) <NEW_LINE> <DEDENT> def nearestFood(pacmanPos, food): <NEW_LINE> <INDENT> return min(manhattanDistance(pacmanPos, fPos) for fPos in food.asList()) <NEW_LINE> <DEDENT> x, y = newPos <NEW_LINE> if disToNearestGhost(newPos, successorGameState.getGhostPositions()) < 3: <NEW_LINE> <INDENT> return -10 <NEW_LINE> <DEDENT> if currentGameState.hasFood(x, y): <NEW_LINE> <INDENT> return 10 <NEW_LINE> <DEDENT> return (1/nearestFood(newPos, newFood)) - (1/disToNearestGhost(newPos, successorGameState.getGhostPositions()))
A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers.
62598fa938b623060ffa8ffd
class Filter(Node): <NEW_LINE> <INDENT> def run(self, data, func, **kwargs): <NEW_LINE> <INDENT> if func(self, data): <NEW_LINE> <INDENT> self.push(data)
A node that only pushes if some condition is met
62598fa9379a373c97d98f77
class CoffeedocDocumenter(Documenter): <NEW_LINE> <INDENT> priority = 20 <NEW_LINE> domain = 'coffee' <NEW_LINE> @classmethod <NEW_LINE> def can_document_member(cls, member, membername, isattr, parent): <NEW_LINE> <INDENT> return isinstance(member, StubObject) and member.type == cls.documents_type <NEW_LINE> <DEDENT> def parse_name(self): <NEW_LINE> <INDENT> self.fullname = self.name <NEW_LINE> self.modname, path = self.name.split(MOD_SEP) <NEW_LINE> self.real_modname = self.modname <NEW_LINE> self.objpath = path.split('.') <NEW_LINE> self.args = None <NEW_LINE> self.retann = None <NEW_LINE> return True <NEW_LINE> <DEDENT> def format_name(self): <NEW_LINE> <INDENT> return self.modname + MOD_SEP + '.'.join(self.objpath) <NEW_LINE> <DEDENT> def get_object_members(self, want_all=False): <NEW_LINE> <INDENT> members = [] <NEW_LINE> for type in self.sub_member_keys: <NEW_LINE> <INDENT> for obj in self.object[type]: <NEW_LINE> <INDENT> members.append((obj['name'], StubObject(type, obj))) <NEW_LINE> <DEDENT> <DEDENT> return False, members <NEW_LINE> <DEDENT> @property <NEW_LINE> def coffeedoc_module(self): <NEW_LINE> <INDENT> filename = self.modname + '.coffee' <NEW_LINE> return self._load_module(filename) <NEW_LINE> <DEDENT> def _load_module(self, filename): <NEW_LINE> <INDENT> modules = self.env.temp_data.setdefault('coffee:coffeedoc-output', {}) <NEW_LINE> if filename in modules: <NEW_LINE> <INDENT> return modules[filename] <NEW_LINE> <DEDENT> basedir = self.env.config.coffee_src_dir <NEW_LINE> parser = self.env.config.coffee_src_parser or 'commonjs' <NEW_LINE> gencmd = ['coffeedoc', '--stdout', '--renderer', 'json', '--parser', parser, filename] <NEW_LINE> docgen = Popen(gencmd, cwd=basedir, stdout=PIPE) <NEW_LINE> (stdout, stderr) = docgen.communicate() <NEW_LINE> data = json.loads(stdout)[0] <NEW_LINE> data['path'] = data['path'].replace(basedir + '/', '') <NEW_LINE> data['name'] = data['path'].replace('.coffee', MOD_SEP) <NEW_LINE> modules[filename] = StubObject('module', data) <NEW_LINE> return modules[filename] <NEW_LINE> <DEDENT> def import_object(self): <NEW_LINE> <INDENT> raise NotImplemented("")
Base class for documenters that use the output of ``coffeedoc``
62598fa9aad79263cf42e739
class CatmainURLTileProcessor(TileProcessor): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> TileProcessor.__init__(self) <NEW_LINE> <DEDENT> def setup(self, parameters): <NEW_LINE> <INDENT> self.parameters = parameters <NEW_LINE> <DEDENT> def process(self, file_path, x_index, y_index, z_index, t_index=0): <NEW_LINE> <INDENT> CATMAID_URL = self.parameters["url"] <NEW_LINE> FORMAT = self.parameters["filetype"] <NEW_LINE> if z_index + self.parameters["z_offset"] < 0: <NEW_LINE> <INDENT> data = np.zeros((self.parameters["x_tile"], self.parameters["y_tile"]), dtype=np.int32, order="C") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cnt = 0 <NEW_LINE> while cnt < 5: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> url = CATMAID_URL + str(z_index) + '/' + str(y_index) + '/' + str(x_index) + "." + FORMAT <NEW_LINE> r = req.get(url) <NEW_LINE> if r.status_code == 403: <NEW_LINE> <INDENT> print("=== \nRequest Err:{} \n{} \nreplacing with Zeros".format(r.status_code, url)) <NEW_LINE> data = np.zeros((self.parameters["x_tile"], self.parameters["y_tile"]), dtype=np.int32, order="C") <NEW_LINE> <DEDENT> elif r.status_code == 200: <NEW_LINE> <INDENT> data = Image.open(BytesIO(r.content)) <NEW_LINE> data = np.asarray(data, np.uint32) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("=== \nRequest Err:{}; attempting again".format(r.status_code)) <NEW_LINE> print(url) <NEW_LINE> raise Exception <NEW_LINE> <DEDENT> break <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> if cnt > 5: <NEW_LINE> <INDENT> raise err <NEW_LINE> <DEDENT> cnt += 1 <NEW_LINE> time.sleep(10) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> upload_img = Image.fromarray(np.squeeze(data)) <NEW_LINE> output = six.BytesIO() <NEW_LINE> upload_img.save(output, format="TIFF") <NEW_LINE> return output
A Tile processor for a single image file identified by z index
62598fa9925a0f43d25e7fa4
class CriticalSection(object): <NEW_LINE> <INDENT> def __init__(self, keys, fail_hard=False, timeout=60): <NEW_LINE> <INDENT> self.keys = keys <NEW_LINE> self.locks = [] <NEW_LINE> self.fail_hard = fail_hard <NEW_LINE> self.timeout = timeout <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> client = get_redis_client() <NEW_LINE> for key in self.keys: <NEW_LINE> <INDENT> lock = client.lock(key, timeout=self.timeout) <NEW_LINE> self.locks.append(lock) <NEW_LINE> <DEDENT> for lock in self.locks: <NEW_LINE> <INDENT> lock.acquire(blocking=True) <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> if self.fail_hard: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> for lock in self.locks: <NEW_LINE> <INDENT> release_lock(lock, True)
An object to facilitate the use of locking in critical sections where you can't use CouchDocLockableMixIn (i.e., in cases where you don't necessarily want or need a document to be created). Sample usage: with CriticalSection(["my-update-key"]): ...do processing keys - a list of strings representing the keys of the locks to acquire; when using multiple keys, make sure to consider key order to prevent deadlock and be mindful of the duration of the task(s) using these keys in relation to the lock timeout fail_hard - if True, exceptions are raised when locks can't be acquired timeout - the number of seconds before each lock times out
62598fa94c3428357761a21f
class BOT_533: <NEW_LINE> <INDENT> pass
Menacing Nimbus
62598fa9aad79263cf42e73a
class BaseProductVersionSerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> content_title = serializers.SerializerMethodField() <NEW_LINE> readable_id = serializers.SerializerMethodField() <NEW_LINE> price = serializers.SerializerMethodField() <NEW_LINE> def get_content_title(self, instance): <NEW_LINE> <INDENT> return instance.product.content_object.title <NEW_LINE> <DEDENT> def get_readable_id(self, instance): <NEW_LINE> <INDENT> return instance.product.content_object.text_id <NEW_LINE> <DEDENT> def get_price(self, instance): <NEW_LINE> <INDENT> return str(instance.price) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> fields = ["price", "content_title", "readable_id"] <NEW_LINE> model = models.ProductVersion
ProductVersion serializer for fetching summary info for receipts
62598fa94428ac0f6e658489
class IPDFPeekConfiguration(Interface): <NEW_LINE> <INDENT> preview_toggle = schema.Bool( title=_(u'Preview Toggle'), description=_( u'Display PDFPeek image previews in default content views.'), required=True, default=True ) <NEW_LINE> eventhandler_toggle = schema.Bool( title=_(u'Event Handler Toggle'), description=_(u'Enable the default PDFPeek event handler.'), required=True, default=True ) <NEW_LINE> preview_length = schema.Int( title=_(u'Preview Length'), description=_(u'Control PDFPeek Image Preview Length.'), required=True, default=512, ) <NEW_LINE> preview_width = schema.Int( title=_(u'Preview Width'), description=_(u'Control PDFPeek Image Preview Width.'), required=True, default=512, ) <NEW_LINE> thumbnail_length = schema.Int( title=_(u'Thumbnail Length'), description=_(u'Control PDFPeek Image Thumbnail Length.'), required=True, default=128, ) <NEW_LINE> thumbnail_width = schema.Int( title=_(u'Thumbnail Width'), description=_(u'Control PDFPeek Image Thumbnail Width.'), required=True, default=128, ) <NEW_LINE> page_limit = schema.Int( title=_(u'Limit pages'), description=_(u'Limit preview and thumbnail generation to maximum ' u'amount of pages. 0 means all no limit.'), default=0, required=True, )
interface describing the pdfpeek control panel.
62598fa92ae34c7f260ab047
class SelectLoop(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._r_list = set() <NEW_LINE> self._w_list = set() <NEW_LINE> self._x_list = set() <NEW_LINE> <DEDENT> def poll(self, timeout): <NEW_LINE> <INDENT> r, w, x = select.select( self._r_list, self._w_list, self._x_list, timeout) <NEW_LINE> result = defaultdict(lambda: POLLNULL) <NEW_LINE> for f_list in [(r, POLLIN), (w, POLLOUT), (x, POLLERR)]: <NEW_LINE> <INDENT> for fd in f_list[0]: <NEW_LINE> <INDENT> result[fd] = result[fd] | f_list[1] <NEW_LINE> <DEDENT> <DEDENT> return result.items() <NEW_LINE> <DEDENT> def add_fd(self, fd, mode): <NEW_LINE> <INDENT> if mode & POLLIN: <NEW_LINE> <INDENT> self._r_list.add(fd) <NEW_LINE> <DEDENT> if mode & POLLOUT: <NEW_LINE> <INDENT> self._w_list.add(fd) <NEW_LINE> <DEDENT> if mode & POLLERR: <NEW_LINE> <INDENT> self._x_list.add(fd) <NEW_LINE> <DEDENT> <DEDENT> def remove_fd(self, fd): <NEW_LINE> <INDENT> if fd in self._r_list: <NEW_LINE> <INDENT> self._r_list.remove(fd) <NEW_LINE> <DEDENT> if fd in self._w_list: <NEW_LINE> <INDENT> self._w_list.remove(fd) <NEW_LINE> <DEDENT> if fd in self._x_list: <NEW_LINE> <INDENT> self._x_list.remove(fd) <NEW_LINE> <DEDENT> <DEDENT> def edit_fd(self, fd, mode): <NEW_LINE> <INDENT> self.remove_fd(fd) <NEW_LINE> self.add_fd(fd, mode)
SelectLoop Methods: * __init__() * pool() * add_fd() * remove_fd() * modify_fd()
62598fa9e1aae11d1e7ce7d6
class UserData: <NEW_LINE> <INDENT> def __init__(self, userdatafile): <NEW_LINE> <INDENT> self.userdatafile = userdatafile <NEW_LINE> <DEDENT> def read_user_info(self, userdatafile): <NEW_LINE> <INDENT> self.userdatas = [] <NEW_LINE> datafile = open(userdatafile) <NEW_LINE> reader = csv.reader(datafile) <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> self.userdatas.append(row) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def insurance(self, income): <NEW_LINE> <INDENT> return float(income * config.rate) <NEW_LINE> <DEDENT> def tax_rate(self, income): <NEW_LINE> <INDENT> if income <= 1500: <NEW_LINE> <INDENT> rate = 0.03 <NEW_LINE> <DEDENT> elif income <= 4500: <NEW_LINE> <INDENT> rate = 0.1 <NEW_LINE> <DEDENT> elif income <= 9000: <NEW_LINE> <INDENT> rate = 0.2 <NEW_LINE> <DEDENT> elif income <= 35000: <NEW_LINE> <INDENT> rate = 0.25 <NEW_LINE> <DEDENT> elif income <= 55000: <NEW_LINE> <INDENT> rate = 0.3 <NEW_LINE> <DEDENT> elif income <= 80000: <NEW_LINE> <INDENT> rate = 0.35 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rate = 0.45 <NEW_LINE> <DEDENT> return rate <NEW_LINE> <DEDENT> def calculator(self, income): <NEW_LINE> <INDENT> annuity = float(config.basic(income)) <NEW_LINE> out = [] <NEW_LINE> if float(income) > 3500.00: <NEW_LINE> <INDENT> taxable_income = (float(income) - float(annuity) - 3500.00) <NEW_LINE> taxrate = self.tax_rate(taxable_income) <NEW_LINE> deduction = deductions[taxrate] <NEW_LINE> tax = taxable_income * taxrate - deduction <NEW_LINE> after = float(income) - float(tax) - float(annuity) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tax = 0.00 <NEW_LINE> after = float(income) - annuity <NEW_LINE> <DEDENT> for i in [annuity, tax, after]: <NEW_LINE> <INDENT> out.append('{:.2f}'.format(i)) <NEW_LINE> <DEDENT> return out <NEW_LINE> <DEDENT> def full(self): <NEW_LINE> <INDENT> datas = [] <NEW_LINE> pool = Pool(processes=3) <NEW_LINE> for p in userdata.userdatas: <NEW_LINE> <INDENT> for j in pool.apply(self.calculator, ((p[1]),)): <NEW_LINE> <INDENT> p.append(j) <NEW_LINE> <DEDENT> datas.append(p) <NEW_LINE> <DEDENT> return datas <NEW_LINE> <DEDENT> def dumptofile(self, outputfile): <NEW_LINE> <INDENT> contents = Process(target=self.full) <NEW_LINE> contents.start() <NEW_LINE> contents.join() <NEW_LINE> queue.put(contents) <NEW_LINE> out_file = open(outputfile, 'w', newline='') <NEW_LINE> outwriter = csv.writer(out_file) <NEW_LINE> for row in queue.get(contents): <NEW_LINE> <INDENT> outwriter.writerow(row) <NEW_LINE> <DEDENT> out_file.close()
read userdate and output new userdata file
62598fa921bff66bcd722bcc
class Fixture(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def populate(): <NEW_LINE> <INDENT> pass
Class contains populate method as static method Is used by django-swagger-utils as a management command
62598fa945492302aabfc437
class ToTensor(object): <NEW_LINE> <INDENT> def __init__(self, sample_rate=16000, augment=False, tempo_range=(0.85, 1.15), gain_range=(-6, 8)): <NEW_LINE> <INDENT> self.sample_rate = sample_rate <NEW_LINE> self.augment = augment <NEW_LINE> self.tempo_range = tempo_range <NEW_LINE> self.gain_range = gain_range <NEW_LINE> <DEDENT> def _load(self, path): <NEW_LINE> <INDENT> if isinstance(path, bytes): <NEW_LINE> <INDENT> data, sample_rate = sf.read(io.ByteIO(path)) <NEW_LINE> return torch.from_numpy(data).float(), sample_rate <NEW_LINE> <DEDENT> return torchaudio.load(path) <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> if not self.augment: <NEW_LINE> <INDENT> y, sample_rate = self._load(x) <NEW_LINE> assert sample_rate == self.sample_rate <NEW_LINE> return y.squeeze() <NEW_LINE> <DEDENT> low_tempo, high_tempo = self.tempo_range <NEW_LINE> tempo_value = np.random.uniform(low=low_tempo, high=high_tempo) <NEW_LINE> low_gain, high_gain = self.gain_range <NEW_LINE> gain_value = np.random.uniform(low=low_gain, high=high_gain) <NEW_LINE> audio = self._augment_audio_with_sox( x, sample_rate=self.sample_rate, tempo=tempo_value, gain=gain_value) <NEW_LINE> return audio <NEW_LINE> <DEDENT> def _augment_audio_with_sox(self, x, sample_rate, tempo, gain): <NEW_LINE> <INDENT> if isinstance(x, bytes): <NEW_LINE> <INDENT> with NamedTemporaryFile( suffix='.wav', delete=False) as original_file: <NEW_LINE> <INDENT> path = original_file.name <NEW_LINE> data, sample_rate = self._load(x) <NEW_LINE> sf.write(original_file.name, data.numpy(), sample_rate) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> path = x <NEW_LINE> <DEDENT> with NamedTemporaryFile(suffix=".wav") as augmented_file: <NEW_LINE> <INDENT> augmented_filename = augmented_file.name <NEW_LINE> sox_augment_params = [ "tempo", "{:.3f}".format(tempo), "gain", "{:.3f}".format(gain) ] <NEW_LINE> sox_params = "sox \"{}\" -r {} -c 1 -b 16 -e si {} {} >/dev/null 2>&1".format( path, sample_rate, augmented_filename, " ".join(sox_augment_params)) <NEW_LINE> ret_code = subprocess.call(sox_params, shell=True) <NEW_LINE> if ret_code < 0: <NEW_LINE> <INDENT> raise RuntimeError( 'sox was terminated by signal {}'.format(ret_code)) <NEW_LINE> <DEDENT> y, sample_rate = torchaudio.load(augmented_filename) <NEW_LINE> assert sample_rate == self.sample_rate <NEW_LINE> if isinstance(x, bytes): <NEW_LINE> <INDENT> os.unlink(path) <NEW_LINE> <DEDENT> return y.squeeze() <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ('{}(sample_rate={}, augment={}, tempo_range={}, ' 'gain_range={})').format(self.__class__.__name__, self.sample_rate, self.augment, self.tempo_range, self.gain_range)
Picks tempo and gain uniformly, applies it to the utterance by using sox utility. Args: sample_rate (int): the desired sample rate augment (bool): if `True`, will add random jitter and gain tempo_prob (float): probability of tempo jitter being applied to sample tempo_range (list, int): list with (tempo_min, tempo_max) gain_prob (float): probability of gain being added to sample gain_range (float): gain level in dB Returns: the augmented utterance.
62598fa98e7ae83300ee9008
class CTD_ANON_7 (pyxb.binding.basis.complexTypeDefinition): <NEW_LINE> <INDENT> _TypeDefinition = None <NEW_LINE> _ContentTypeTag = pyxb.binding.basis.complexTypeDefinition._CT_ELEMENT_ONLY <NEW_LINE> _Abstract = False <NEW_LINE> _ExpandedName = None <NEW_LINE> _XSDLocation = pyxb.utils.utility.Location('/tmp/tmpJ5bTzwxsds/PacBioCollectionMetadata.xsd', 352, 5) <NEW_LINE> _ElementMap = {} <NEW_LINE> _AttributeMap = {} <NEW_LINE> __TraceSamplingFactor = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'TraceSamplingFactor'), 'TraceSamplingFactor', '__httppacificbiosciences_comPacBioCollectionMetadata_xsd_CTD_ANON_7_httppacificbiosciences_comPacBioCollectionMetadata_xsdTraceSamplingFactor', False, pyxb.utils.utility.Location('/tmp/tmpJ5bTzwxsds/PacBioCollectionMetadata.xsd', 354, 7), ) <NEW_LINE> TraceSamplingFactor = property(__TraceSamplingFactor.value, __TraceSamplingFactor.set, None, 'Percentage of traces to sample. ') <NEW_LINE> __FullPulseFile = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'FullPulseFile'), 'FullPulseFile', '__httppacificbiosciences_comPacBioCollectionMetadata_xsd_CTD_ANON_7_httppacificbiosciences_comPacBioCollectionMetadata_xsdFullPulseFile', False, pyxb.utils.utility.Location('/tmp/tmpJ5bTzwxsds/PacBioCollectionMetadata.xsd', 359, 7), ) <NEW_LINE> FullPulseFile = property(__FullPulseFile.value, __FullPulseFile.set, None, 'Whether full or sampled pulse file is transferred if requested. ') <NEW_LINE> _ElementMap.update({ __TraceSamplingFactor.name() : __TraceSamplingFactor, __FullPulseFile.name() : __FullPulseFile }) <NEW_LINE> _AttributeMap.update({ })
Tag to indicate that the trace file will be sampled.
62598fa9a8ecb03325871176
class Pbkdf1_Test(TestCase): <NEW_LINE> <INDENT> descriptionPrefix = "passlib.crypto.digest.pbkdf1" <NEW_LINE> pbkdf1_tests = [ (b'password', hb('78578E5A5D63CB06'), 1000, 16, 'sha1', hb('dc19847e05c64d2faf10ebfb4a3d2a20')), (b'password', b'salt', 1000, 0, 'md5', b''), (b'password', b'salt', 1000, 1, 'md5', hb('84')), (b'password', b'salt', 1000, 8, 'md5', hb('8475c6a8531a5d27')), (b'password', b'salt', 1000, 16, 'md5', hb('8475c6a8531a5d27e386cd496457812c')), (b'password', b'salt', 1000, None, 'md5', hb('8475c6a8531a5d27e386cd496457812c')), (b'password', b'salt', 1000, None, 'sha1', hb('4a8fd48e426ed081b535be5769892fa396293efb')), ] <NEW_LINE> if not JYTHON: <NEW_LINE> <INDENT> pbkdf1_tests.append( (b'password', b'salt', 1000, None, 'md4', hb('f7f2e91100a8f96190f2dd177cb26453')) ) <NEW_LINE> <DEDENT> def test_known(self): <NEW_LINE> <INDENT> from passlib.crypto.digest import pbkdf1 <NEW_LINE> for secret, salt, rounds, keylen, digest, correct in self.pbkdf1_tests: <NEW_LINE> <INDENT> result = pbkdf1(digest, secret, salt, rounds, keylen) <NEW_LINE> self.assertEqual(result, correct) <NEW_LINE> <DEDENT> <DEDENT> def test_border(self): <NEW_LINE> <INDENT> from passlib.crypto.digest import pbkdf1 <NEW_LINE> def helper(secret=b'secret', salt=b'salt', rounds=1, keylen=1, hash='md5'): <NEW_LINE> <INDENT> return pbkdf1(hash, secret, salt, rounds, keylen) <NEW_LINE> <DEDENT> helper() <NEW_LINE> self.assertRaises(TypeError, helper, secret=1) <NEW_LINE> self.assertRaises(TypeError, helper, salt=1) <NEW_LINE> self.assertRaises(ValueError, helper, hash='missing') <NEW_LINE> self.assertRaises(ValueError, helper, rounds=0) <NEW_LINE> self.assertRaises(TypeError, helper, rounds='1') <NEW_LINE> self.assertRaises(ValueError, helper, keylen=-1) <NEW_LINE> self.assertRaises(ValueError, helper, keylen=17, hash='md5') <NEW_LINE> self.assertRaises(TypeError, helper, keylen='1')
test kdf helpers
62598fa95fcc89381b2660ff
class XmlSystemStatus(ElementWrapper): <NEW_LINE> <INDENT> def filter(self, joins): <NEW_LINE> <INDENT> value = self.get_xml_attr('value', unicode, None) <NEW_LINE> query = None <NEW_LINE> if value: <NEW_LINE> <INDENT> query = System.status == value <NEW_LINE> <DEDENT> return (joins, query)
Pick a system with the correct system status.
62598fa91f037a2d8b9e4053
class DysonInvalidCredential(DysonException): <NEW_LINE> <INDENT> pass
Requesents invalid mqtt credential.
62598fa9a79ad16197769fcb
class ArModeSonar(ArMode): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> this = _AriaPy.new_ArModeSonar(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> __swig_destroy__ = _AriaPy.delete_ArModeSonar <NEW_LINE> __del__ = lambda self : None; <NEW_LINE> def activate(self): <NEW_LINE> <INDENT> return _AriaPy.ArModeSonar_activate(self) <NEW_LINE> <DEDENT> def deactivate(self): <NEW_LINE> <INDENT> return _AriaPy.ArModeSonar_deactivate(self) <NEW_LINE> <DEDENT> def userTask(self): <NEW_LINE> <INDENT> return _AriaPy.ArModeSonar_userTask(self) <NEW_LINE> <DEDENT> def help(self): <NEW_LINE> <INDENT> return _AriaPy.ArModeSonar_help(self) <NEW_LINE> <DEDENT> def allSonar(self): <NEW_LINE> <INDENT> return _AriaPy.ArModeSonar_allSonar(self) <NEW_LINE> <DEDENT> def firstSonar(self): <NEW_LINE> <INDENT> return _AriaPy.ArModeSonar_firstSonar(self) <NEW_LINE> <DEDENT> def secondSonar(self): <NEW_LINE> <INDENT> return _AriaPy.ArModeSonar_secondSonar(self) <NEW_LINE> <DEDENT> def thirdSonar(self): <NEW_LINE> <INDENT> return _AriaPy.ArModeSonar_thirdSonar(self) <NEW_LINE> <DEDENT> def fourthSonar(self): <NEW_LINE> <INDENT> return _AriaPy.ArModeSonar_fourthSonar(self)
Proxy of C++ ArModeSonar class
62598fa92c8b7c6e89bd372c
class AjaxSetMemberAllAccounts(AjaxAllAccountsViewBase): <NEW_LINE> <INDENT> def init_counter(self): <NEW_LINE> <INDENT> self.group_msg.title = "Надання права доступу групі акаунтів" <NEW_LINE> self.group_msg.type = msgType.Group <NEW_LINE> self.group_msg.message = "" <NEW_LINE> self.counter = OrderedDict() <NEW_LINE> self.counter["встановлено" ] = 0 <NEW_LINE> self.counter["доступ вже є" ] = 0 <NEW_LINE> self.counter["відхилені" ] = 0 <NEW_LINE> self.counter["непідтверджені"] = 0 <NEW_LINE> <DEDENT> @method_decorator(permission_required('koopsite.activate_account', raise_exception=True)) <NEW_LINE> def dispatch(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return self.group_handler(request) <NEW_LINE> <DEDENT> def processing(self, user, profile, msg): <NEW_LINE> <INDENT> if has_group(user, 'members'): <NEW_LINE> <INDENT> msg.title = user.username <NEW_LINE> msg.type = msgType.NoChange <NEW_LINE> msg.message = "Акаунт вже має ці права доступу!" <NEW_LINE> self.counter["доступ вже є"] += 1 <NEW_LINE> <DEDENT> elif profile and profile.is_recognized == False: <NEW_LINE> <INDENT> msg.title = user.username <NEW_LINE> msg.type = msgType.Error <NEW_LINE> msg.message = "Відхилений Акаунт не може отримати права доступу!" <NEW_LINE> self.counter["відхилені"] += 1 <NEW_LINE> <DEDENT> elif (not profile) or (profile and profile.is_recognized == None): <NEW_LINE> <INDENT> msg.title = user.username <NEW_LINE> msg.type = msgType.Error <NEW_LINE> msg.message = "Непідтверджений Акаунт не може отримати права доступу!" <NEW_LINE> self.counter["непідтверджені"] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> add_group(user, 'members') <NEW_LINE> user.save() <NEW_LINE> msg.title = user.username <NEW_LINE> msg.type = msgType.Change <NEW_LINE> msg.message = "Права доступу встановлено!" <NEW_LINE> self.counter["встановлено"] += 1 <NEW_LINE> e_msg_body = "Ваш акаунт на сайті отримав права доступу " "члена кооперативу." <NEW_LINE> self.send_e_mail(user, e_msg_body) <NEW_LINE> <DEDENT> return user, msg
Приєднання до групи members всіх акаунтів з фільтрованого списку.
62598fa97d43ff24874273b5
class Bootstrap(Role): <NEW_LINE> <INDENT> def __init__(self, node, peers, execute_fn, replica_cls=Replica, acceptor_cls=Acceptor, leader_cls=Leader, commander_cls=Commander, scout_cls=Scout): <NEW_LINE> <INDENT> super(Bootstrap, self).__init__(node) <NEW_LINE> self.execute_fn = execute_fn <NEW_LINE> self.peers = peers <NEW_LINE> self.peers_cycle = itertools.cycle(peers) <NEW_LINE> self.replica_cls = replica_cls <NEW_LINE> self.acceptor_cls = acceptor_cls <NEW_LINE> self.leader_cls = leader_cls <NEW_LINE> self.commander_cls = commander_cls <NEW_LINE> self.scout_cls = scout_cls <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> self.join() <NEW_LINE> <DEDENT> def join(self): <NEW_LINE> <INDENT> self.node.send([next(self.peers_cycle)], Join()) <NEW_LINE> self.set_timer(JOIN_RETRANSMIT, self.join) <NEW_LINE> <DEDENT> def do_welcome(self, sender, state, slot, decisions): <NEW_LINE> <INDENT> self.acceptor_cls(self.node) <NEW_LINE> self.replica_cls(self.node, execute_fn=self.execute_fn, peers=self.peers, state=state, slot=slot, decisions=decisions) <NEW_LINE> self.leader_cls(self.node, peers=self.peers, commander_cls=self.commander_cls, scout_cls=self.scout_cls).start() <NEW_LINE> self.stop()
introduce a new node to an existing cluster
62598fa910dbd63aa1c70b19
class Spider(): <NEW_LINE> <INDENT> url = "https://www.panda.tv/cate/lol" <NEW_LINE> root_pattern = '<div class="video-info">([\s\S]*?)</div>' <NEW_LINE> name_pattern = '</i>([\s\S]*?)</span>' <NEW_LINE> number_pattern = '<span class="video-number">([\s\S]*?)</span>' <NEW_LINE> def __fetch_content(self): <NEW_LINE> <INDENT> r = request.urlopen(Spider.url) <NEW_LINE> htmls = r.read() <NEW_LINE> htmls = str(htmls,encoding='utf-8') <NEW_LINE> return htmls <NEW_LINE> <DEDENT> def __analysis(self,htmls): <NEW_LINE> <INDENT> root_html = re.findall(Spider.root_pattern,htmls) <NEW_LINE> anchors = [] <NEW_LINE> for html in root_html: <NEW_LINE> <INDENT> name = re.findall(Spider.name_pattern,html) <NEW_LINE> number = re.findall(Spider.number_pattern,html) <NEW_LINE> anchor = {'name':name,'number':number} <NEW_LINE> anchors.append(anchor) <NEW_LINE> <DEDENT> return anchors <NEW_LINE> <DEDENT> def __refine(self,anchors): <NEW_LINE> <INDENT> l = lambda anchor: { 'name':anchor['name'][0].strip(), 'number':anchor['number'][0].strip() } <NEW_LINE> return map(l,anchors) <NEW_LINE> <DEDENT> def __sort(self,anchors): <NEW_LINE> <INDENT> anchors = sorted(anchors,key=self.__sort_seed,reverse=True) <NEW_LINE> return anchors <NEW_LINE> <DEDENT> def __sort_seed(self,anchor): <NEW_LINE> <INDENT> r = re.findall('\d+',anchor['number']) <NEW_LINE> number = int(r[0]) <NEW_LINE> if '万' in anchor['number']: <NEW_LINE> <INDENT> number *= 10000 <NEW_LINE> if len(r) == 2: <NEW_LINE> <INDENT> number += int(r[1]) * 1000 <NEW_LINE> <DEDENT> <DEDENT> return number <NEW_LINE> <DEDENT> def __show(self,anchors): <NEW_LINE> <INDENT> for rank in range(0,len(anchors)): <NEW_LINE> <INDENT> print('rank '+ str(rank+1)+ ' : '+anchors[rank]['name']+ ' : '+anchors[rank]['number']) <NEW_LINE> <DEDENT> <DEDENT> def go(self): <NEW_LINE> <INDENT> htmls = self.__fetch_content() <NEW_LINE> anchors = self.__analysis(htmls) <NEW_LINE> anchors = list(self.__refine(anchors)) <NEW_LINE> anchors = self.__sort(anchors) <NEW_LINE> self.__show(anchors)
This is a class
62598fa930dc7b766599f7b3
class LdapSyncJobStatusJson(object): <NEW_LINE> <INDENT> swagger_types = { 'in_progress': 'bool', 'clusters': 'list[ClusterLdapSyncInfoJson]' } <NEW_LINE> attribute_map = { 'in_progress': 'inProgress', 'clusters': 'clusters' } <NEW_LINE> def __init__(self, in_progress=None, clusters=None): <NEW_LINE> <INDENT> self._in_progress = None <NEW_LINE> self._clusters = None <NEW_LINE> self.discriminator = None <NEW_LINE> if in_progress is not None: <NEW_LINE> <INDENT> self.in_progress = in_progress <NEW_LINE> <DEDENT> if clusters is not None: <NEW_LINE> <INDENT> self.clusters = clusters <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def in_progress(self): <NEW_LINE> <INDENT> return self._in_progress <NEW_LINE> <DEDENT> @in_progress.setter <NEW_LINE> def in_progress(self, in_progress): <NEW_LINE> <INDENT> self._in_progress = in_progress <NEW_LINE> <DEDENT> @property <NEW_LINE> def clusters(self): <NEW_LINE> <INDENT> return self._clusters <NEW_LINE> <DEDENT> @clusters.setter <NEW_LINE> def clusters(self, clusters): <NEW_LINE> <INDENT> self._clusters = clusters <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(LdapSyncJobStatusJson, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, LdapSyncJobStatusJson): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598fa97d847024c075c32a
class ModbusConnectedRequestHandler(ModbusBaseRequestHandler): <NEW_LINE> <INDENT> def handle(self): <NEW_LINE> <INDENT> while self.running: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = self.request.recv(1024) <NEW_LINE> if not data: self.running = False <NEW_LINE> if _logger.isEnabledFor(logging.DEBUG): <NEW_LINE> <INDENT> _logger.debug(' '.join([hex(byte2int(x)) for x in data])) <NEW_LINE> <DEDENT> self.framer.processIncomingPacket(data, self.execute) <NEW_LINE> <DEDENT> except socket.timeout as msg: <NEW_LINE> <INDENT> if _logger.isEnabledFor(logging.DEBUG): <NEW_LINE> <INDENT> _logger.debug("Socket timeout occurred %s", msg) <NEW_LINE> <DEDENT> pass <NEW_LINE> <DEDENT> except socket.error as msg: <NEW_LINE> <INDENT> _logger.error("Socket error occurred %s" % msg) <NEW_LINE> self.running = False <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> _logger.error("Socket exception occurred %s" % traceback.format_exc() ) <NEW_LINE> self.running = False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def send(self, message): <NEW_LINE> <INDENT> if message.should_respond: <NEW_LINE> <INDENT> pdu = self.framer.buildPacket(message) <NEW_LINE> if _logger.isEnabledFor(logging.DEBUG): <NEW_LINE> <INDENT> _logger.debug('send: %s' % b2a_hex(pdu)) <NEW_LINE> <DEDENT> return self.request.send(pdu)
Implements the modbus server protocol This uses the socketserver.BaseRequestHandler to implement the client handler for a connected protocol (TCP).
62598fa9a8370b77170f0342
class UserView(object): <NEW_LINE> <INDENT> def __init__(self, app, user): <NEW_LINE> <INDENT> self.app = app <NEW_LINE> self.user = user <NEW_LINE> <DEDENT> @property <NEW_LINE> def image_thumb(self): <NEW_LINE> <INDENT> u = self.user <NEW_LINE> uf = self.app.url_for <NEW_LINE> if u.image is not None and u.image!="": <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> asset = self.app.module_map.uploader.get(u.image).variants['thumb'] <NEW_LINE> return uf("asset", asset_id = self.app.module_map.uploader.get(u.image).variants['thumb']._id) <NEW_LINE> <DEDENT> except AssetNotFound: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return uf("static", filename="img/anon50x50.png")
adapter for a user object to provide additional data such as profile image etc.
62598fa923849d37ff85101b
class ZWaveProtectionView(HomeAssistantView): <NEW_LINE> <INDENT> url = r"/api/zwave/protection/{node_id:\d+}" <NEW_LINE> name = "api:zwave:protection" <NEW_LINE> async def get(self, request, node_id): <NEW_LINE> <INDENT> nodeid = int(node_id) <NEW_LINE> hass = request.app["hass"] <NEW_LINE> network = hass.data.get(const.DATA_NETWORK) <NEW_LINE> def _fetch_protection(): <NEW_LINE> <INDENT> node = network.nodes.get(nodeid) <NEW_LINE> if node is None: <NEW_LINE> <INDENT> return self.json_message("Node not found", HTTP_NOT_FOUND) <NEW_LINE> <DEDENT> protection_options = {} <NEW_LINE> if not node.has_command_class(const.COMMAND_CLASS_PROTECTION): <NEW_LINE> <INDENT> return self.json(protection_options) <NEW_LINE> <DEDENT> protections = node.get_protections() <NEW_LINE> protection_options = { "value_id": f"{list(protections)[0]:d}", "selected": node.get_protection_item(list(protections)[0]), "options": node.get_protection_items(list(protections)[0]), } <NEW_LINE> return self.json(protection_options) <NEW_LINE> <DEDENT> return await hass.async_add_executor_job(_fetch_protection) <NEW_LINE> <DEDENT> async def post(self, request, node_id): <NEW_LINE> <INDENT> nodeid = int(node_id) <NEW_LINE> hass = request.app["hass"] <NEW_LINE> network = hass.data.get(const.DATA_NETWORK) <NEW_LINE> protection_data = await request.json() <NEW_LINE> def _set_protection(): <NEW_LINE> <INDENT> node = network.nodes.get(nodeid) <NEW_LINE> selection = protection_data["selection"] <NEW_LINE> value_id = int(protection_data[const.ATTR_VALUE_ID]) <NEW_LINE> if node is None: <NEW_LINE> <INDENT> return self.json_message("Node not found", HTTP_NOT_FOUND) <NEW_LINE> <DEDENT> if not node.has_command_class(const.COMMAND_CLASS_PROTECTION): <NEW_LINE> <INDENT> return self.json_message( "No protection commandclass on this node", HTTP_NOT_FOUND ) <NEW_LINE> <DEDENT> state = node.set_protection(value_id, selection) <NEW_LINE> if not state: <NEW_LINE> <INDENT> return self.json_message( "Protection setting did not complete", HTTP_ACCEPTED ) <NEW_LINE> <DEDENT> return self.json_message("Protection setting succsessfully set", HTTP_OK) <NEW_LINE> <DEDENT> return await hass.async_add_executor_job(_set_protection)
View for the protection commandclass of a node.
62598faaf548e778e596b50b
class StatsGroupTopInviter(TLObject): <NEW_LINE> <INDENT> __slots__: List[str] = ["user_id", "invitations"] <NEW_LINE> ID = 0x31962a4c <NEW_LINE> QUALNAME = "types.StatsGroupTopInviter" <NEW_LINE> def __init__(self, *, user_id: int, invitations: int) -> None: <NEW_LINE> <INDENT> self.user_id = user_id <NEW_LINE> self.invitations = invitations <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read(data: BytesIO, *args: Any) -> "StatsGroupTopInviter": <NEW_LINE> <INDENT> user_id = Int.read(data) <NEW_LINE> invitations = Int.read(data) <NEW_LINE> return StatsGroupTopInviter(user_id=user_id, invitations=invitations) <NEW_LINE> <DEDENT> def write(self) -> bytes: <NEW_LINE> <INDENT> data = BytesIO() <NEW_LINE> data.write(Int(self.ID, False)) <NEW_LINE> data.write(Int(self.user_id)) <NEW_LINE> data.write(Int(self.invitations)) <NEW_LINE> return data.getvalue()
This object is a constructor of the base type :obj:`~pyrogram.raw.base.StatsGroupTopInviter`. Details: - Layer: ``122`` - ID: ``0x31962a4c`` Parameters: user_id: ``int`` ``32-bit`` invitations: ``int`` ``32-bit``
62598faa44b2445a339b6923
class DefaultValueFormatInvalid(SettingValueFormatInvalid, DefaultValueError): <NEW_LINE> <INDENT> pass
As SettingValueFormatInvalid, but specifically for a default value.
62598faa379a373c97d98f79
class TestUpdateStories(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testUpdateStories(self): <NEW_LINE> <INDENT> pass
UpdateStories unit test stubs
62598faae76e3b2f99fd899d
class IPageVersion(IPageContentVersion): <NEW_LINE> <INDENT> pass
A page version
62598faad486a94d0ba2bf35
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): <NEW_LINE> <INDENT> VERSION = 1 <NEW_LINE> async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> FlowResult: <NEW_LINE> <INDENT> if user_input is None: <NEW_LINE> <INDENT> return self.async_show_form(step_id="user", data_schema=USER_DATA_SCHEMA) <NEW_LINE> <DEDENT> errors = {} <NEW_LINE> try: <NEW_LINE> <INDENT> info = await validate_input(self.hass, user_input) <NEW_LINE> <DEDENT> except InvalidAuth: <NEW_LINE> <INDENT> errors["base"] = "invalid_auth" <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> _LOGGER.exception("Unexpected exception") <NEW_LINE> errors["base"] = "unknown" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> await self.async_set_unique_id(info["user_id"]) <NEW_LINE> self._abort_if_unique_id_configured() <NEW_LINE> return self.async_create_entry(title=info["title"], data=user_input) <NEW_LINE> <DEDENT> return self.async_show_form( step_id="user", data_schema=USER_DATA_SCHEMA, errors=errors ) <NEW_LINE> <DEDENT> async def async_step_reauth(self, _: dict[str, Any]) -> FlowResult: <NEW_LINE> <INDENT> return await self.async_step_reauth_confirm() <NEW_LINE> <DEDENT> async def async_step_reauth_confirm( self, user_input: dict[str, Any] = None ) -> FlowResult: <NEW_LINE> <INDENT> errors = {} <NEW_LINE> if user_input is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> info = await validate_input(self.hass, user_input) <NEW_LINE> <DEDENT> except InvalidAuth: <NEW_LINE> <INDENT> errors["base"] = "invalid_auth" <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> _LOGGER.exception("Unexpected exception") <NEW_LINE> errors["base"] = "unknown" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> existing_entry = await self.async_set_unique_id(info["user_id"]) <NEW_LINE> if existing_entry: <NEW_LINE> <INDENT> await self.hass.config_entries.async_reload(existing_entry.entry_id) <NEW_LINE> return self.async_abort(reason="reauth_successful") <NEW_LINE> <DEDENT> return self.async_abort(reason="reauth_failed_existing") <NEW_LINE> <DEDENT> <DEDENT> return self.async_show_form( step_id="reauth_confirm", data_schema=USER_DATA_SCHEMA, errors=errors, )
Handle a config flow for tractive.
62598faa32920d7e50bc5fbc
class ComputerWeekly(JobSite): <NEW_LINE> <INDENT> def __init__(self, job): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.site = "Computer Weekly" <NEW_LINE> job_details = job.find_all('div', class_='col-xs-7') <NEW_LINE> self.title = job.find('a').text <NEW_LINE> self.recruiter = job_details[2].p.text <NEW_LINE> self.applied = job_details[1].p.text.split(' ')[0] <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fetch_jobs(cls, html_file): <NEW_LINE> <INDENT> html_source = BeautifulSoup(html_file, JobSite._html_parser) <NEW_LINE> return html_source.find_all('div', class_='col-xs-12 col-sm-9')
Computer Weekly job site.
62598faa7c178a314d78d404
class Champion : <NEW_LINE> <INDENT> count = 0 <NEW_LINE> def __init__(self, key, name, title) : <NEW_LINE> <INDENT> self.key = key <NEW_LINE> self.name = name <NEW_LINE> self.title = title <NEW_LINE> Champion.count += 1 <NEW_LINE> <DEDENT> def return_name(self) : <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def return_key(self) : <NEW_LINE> <INDENT> return self.key <NEW_LINE> <DEDENT> def return_title(self) : <NEW_LINE> <INDENT> return self.title
Base Class for Champions
62598faaaad79263cf42e73c
class ScaXmlTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_load_xml(self): <NEW_LINE> <INDENT> sca_xml = ScaXml() <NEW_LINE> events = sca_xml.get_event_list() <NEW_LINE> assert not [] == events <NEW_LINE> event = next((event for event in events if event.name == "MOVE HOT CODE TO COLD AREA"), None) <NEW_LINE> assert event is not None <NEW_LINE> expected_problem = "Invariant or infrequently executed code " "found within a loop." <NEW_LINE> expected_solution = "\n\tMove the flagged code outside the loop." <NEW_LINE> self.assertEqual(expected_problem, event.get_problem()) <NEW_LINE> self.assertEqual(expected_solution, event.get_solution()) <NEW_LINE> event = next((event for event in events if event.name == "BLA"), None) <NEW_LINE> assert event is None
Class to run tests from sca xml
62598faaac7a0e7691f72471
class Landsat(object): <NEW_LINE> <INDENT> def __init__(self, parts): <NEW_LINE> <INDENT> self.parts = list(parts) <NEW_LINE> self.labels = ['sensor', 'satellite'] <NEW_LINE> self.lut = [{'C': 'OLI_TIRS', 'O': 'OLI', 'E': 'ETM+', 'T': 'TM', 'M': 'MSS' }, {'07': 'Landsat7', '08': 'Landsat8', }, ] <NEW_LINE> <DEDENT> def metadata(self): <NEW_LINE> <INDENT> parts_copy = deepcopy(self.parts) <NEW_LINE> tile_numbers = parts_copy.pop(3) <NEW_LINE> d = {'wrs_path': tile_numbers[:3], 'wrs_row': tile_numbers[3:], 'acquisition_date': datetime.strptime(parts_copy.pop(3), '%Y%m%d'), 'production_date': datetime.strptime(parts_copy.pop(3), '%Y%m%d'), "collection_number": parts_copy.pop(3), "collection_category": parts_copy.pop(3), "processing_level": parts_copy.pop(-1)} <NEW_LINE> for idx, item in enumerate(self.lut): <NEW_LINE> <INDENT> d.update({self.labels[idx]: self.lut[idx][parts_copy.pop(0)]}) <NEW_LINE> <DEDENT> return d <NEW_LINE> <DEDENT> def stac_item(self, vrt): <NEW_LINE> <INDENT> metadata = self.metadata() <NEW_LINE> stac_item = stac.Item(vrt) <NEW_LINE> stac_item['properties'] = metadata <NEW_LINE> stac_item['assets'] = {'raw': {'href': vrt.filename}} <NEW_LINE> item_path = '${wrs_path}/${wrs_row}/${acquisition_date}' <NEW_LINE> satstac_item = satstac.Item(stac_item) <NEW_LINE> return satstac_item
https://landsat.usgs.gov/landsat-collections
62598faa4f6381625f199472
class VisibleDeprecationWarning(UserWarning): <NEW_LINE> <INDENT> pass
Warning issued by jupyter_client 5.2.4 about future deprecations in tornado
62598faa8e7ae83300ee9009
class InEdgeView(OutEdgeView): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> view = InEdgeDataView <NEW_LINE> def __init__(self, G): <NEW_LINE> <INDENT> pred = G._pred if hasattr(G, "pred") else G._adj <NEW_LINE> self.nbunch_iter = G.nbunch_iter <NEW_LINE> self._adjdict = pred <NEW_LINE> self._nodes_nbrs = pred.items <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> for n, nbrs in self._nodes_nbrs(): <NEW_LINE> <INDENT> for nbr in nbrs: <NEW_LINE> <INDENT> yield (nbr, n) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __contains__(self, e): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> u, v = e <NEW_LINE> return u in self._adjdict[v] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, e): <NEW_LINE> <INDENT> u, v = e <NEW_LINE> return self._adjdict[v][u]
A EdgeView class for inward edges of a DiGraph
62598faa8c0ade5d55dc3645
class FormError(ApiFailed): <NEW_LINE> <INDENT> code = 400 <NEW_LINE> errcode = 4007
表单格式错误
62598faa56b00c62f0fb281c
class AcmiFileReader: <NEW_LINE> <INDENT> _codec = 'utf-8-sig' <NEW_LINE> def __init__(self, fh): <NEW_LINE> <INDENT> self.fh = fh <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> line = self.fh.readline().decode(AcmiFileReader._codec) <NEW_LINE> if len(line) == 0: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> while line.strip().endswith('\\'): <NEW_LINE> <INDENT> line = line.strip()[:-1] + '\n' + self.fh.readline().decode(AcmiFileReader._codec) <NEW_LINE> <DEDENT> return line
Stream reading class that correctly line escaped acmi files.
62598faa21bff66bcd722bce
class CompanyEditView(generic.UpdateView): <NEW_LINE> <INDENT> model = Company <NEW_LINE> form_class = CompanyForm
Company edit view.
62598faa8e7ae83300ee900a
class StrictModeError(PanzerError): <NEW_LINE> <INDENT> pass
An error on `---strict` mode that causes panzer to exit - On `--strict` mode: exception raised if any error of level 'ERROR' or above is logged - Without `--strict` mode: exception never raised
62598faa45492302aabfc439
class SubscriberEditTest(SubscriberBaseTest): <NEW_LINE> <INDENT> def test_get(self): <NEW_LINE> <INDENT> response = self.client.get('/dashboard/subscribers/%s/edit' % self.subscriber_imsi) <NEW_LINE> self.assertEqual(200, response.status_code)
Testing endagaweb.views.dashboard.SubscriberEdit.
62598faaa8ecb03325871178
class PoolTrackTagOverlay(obj.ProfileModification): <NEW_LINE> <INDENT> conditions = {'os': lambda x: x == 'windows'} <NEW_LINE> def modification(self, profile): <NEW_LINE> <INDENT> profile.merge_overlay({ '_POOL_TRACKER_TABLE': [ None, { 'Key': [ None, ['String', dict(length = 4)]] }], })
Overlays for pool trackers
62598faaa17c0f6771d5c19d
class Mailbox(object): <NEW_LINE> <INDENT> def __init__(self, parent_api, boxtype='inbox', page='1', sort='unread'): <NEW_LINE> <INDENT> self.parent_api = parent_api <NEW_LINE> self.boxtype = boxtype <NEW_LINE> self.current_page = page <NEW_LINE> self.total_pages = None <NEW_LINE> self.sort = sort <NEW_LINE> self.messages = None <NEW_LINE> <DEDENT> def set_mbox_data(self, mbox_resp): <NEW_LINE> <INDENT> self.current_page = mbox_resp['currentPage'] <NEW_LINE> self.total_pages = mbox_resp['pages'] <NEW_LINE> self.messages = [MailboxMessage(self.parent_api, m) for m in mbox_resp['messages']] <NEW_LINE> <DEDENT> def update_mbox_data(self): <NEW_LINE> <INDENT> response = self.parent_api.request(action='inbox', type=self.boxtype, page=self.current_page, sort=self.sort) <NEW_LINE> self.set_mbox_data(response) <NEW_LINE> <DEDENT> def next_page(self): <NEW_LINE> <INDENT> if not self.total_pages: <NEW_LINE> <INDENT> raise ValueError("call update_mbox_data() first") <NEW_LINE> <DEDENT> total_pages = int(self.total_pages) <NEW_LINE> cur_page = int(self.current_page) <NEW_LINE> if cur_page < total_pages: <NEW_LINE> <INDENT> return Mailbox(self.parent_api, self.boxtype, str(cur_page + 1), self.sort) <NEW_LINE> <DEDENT> raise ValueError("Already at page %d/%d" % (cur_page, total_pages)) <NEW_LINE> <DEDENT> def prev_page(self): <NEW_LINE> <INDENT> if not self.total_pages: <NEW_LINE> <INDENT> raise ValueError("call update_mbox_data() first") <NEW_LINE> <DEDENT> total_pages = int(self.total_pages) <NEW_LINE> cur_page = int(self.current_page) <NEW_LINE> if cur_page > 1: <NEW_LINE> <INDENT> return Mailbox(self.parent_api, self.boxtype, str(cur_page - 1), self.sort) <NEW_LINE> <DEDENT> raise ValueError("Already at page %d/%d" % (cur_page, total_pages)) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Mailbox: %s %s Page %s/%s" % (self.boxtype, self.sort, self.current_page, self.total_pages)
This class represents the logged in user's inbox/sentbox
62598faad7e4931a7ef3bffe
class KeyedPool(object): <NEW_LINE> <INDENT> def __init__(self, factory, disposer): <NEW_LINE> <INDENT> self.factory = factory <NEW_LINE> self.disposer = disposer <NEW_LINE> self._value_to_key = {} <NEW_LINE> def make_pool(key): <NEW_LINE> <INDENT> def factory(): <NEW_LINE> <INDENT> return self.factory(key) <NEW_LINE> <DEDENT> return Pool(factory, self.disposer) <NEW_LINE> <DEDENT> self._pools = KeyedDefaultdict(make_pool) <NEW_LINE> <DEDENT> def add(self, key, value): <NEW_LINE> <INDENT> pool = self._pools[key] <NEW_LINE> pool.add(value) <NEW_LINE> <DEDENT> def acquire(self, key): <NEW_LINE> <INDENT> pool = self._pools[key] <NEW_LINE> d = pool.acquire() <NEW_LINE> def success(v): <NEW_LINE> <INDENT> self._value_to_key[v] = key <NEW_LINE> return v <NEW_LINE> <DEDENT> d.addCallback(success) <NEW_LINE> return d <NEW_LINE> <DEDENT> def release(self, v): <NEW_LINE> <INDENT> key = self._value_to_key.pop(v) <NEW_LINE> pool = self._pools[key] <NEW_LINE> return pool.release(v) <NEW_LINE> <DEDENT> def dispose(self, v): <NEW_LINE> <INDENT> key = self._value_to_key.pop(v) <NEW_LINE> pool = self._pools[key] <NEW_LINE> return pool.dispose(v) <NEW_LINE> <DEDENT> def dispose_all_of_key(self, key, force=False): <NEW_LINE> <INDENT> if key not in self._pools: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> pool = self._pools[key] <NEW_LINE> return pool.dispose_all(force) <NEW_LINE> <DEDENT> def dispose_all(self): <NEW_LINE> <INDENT> ds = [pool.dispose_all() for pool in self._pools.values()] <NEW_LINE> return defer.DeferredList(ds, fireOnOneErrback=True)
Async object pool that uses a factory to create objects as needed. There is one pool per key.
62598faa67a9b606de545f34
class ANSIFormatterMixin(object): <NEW_LINE> <INDENT> def format(self, record): <NEW_LINE> <INDENT> msg = super(ANSIFormatterMixin, self).format(record) <NEW_LINE> return format_ansi(msg)
A log formatter mixin that inserts ANSI color.
62598faadd821e528d6d8e9e
class PostUpdateView(AutoPermissionRequiredMixin, UpdateView): <NEW_LINE> <INDENT> model = Post <NEW_LINE> form_class = PostEditForm <NEW_LINE> template_name = "blog/edit_post.html" <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> context["posts"] = self.model.objects.get_without_removed().order_by("-pk") <NEW_LINE> context["title"] = "Edit Post" <NEW_LINE> context["side_title"] = "Post List" <NEW_LINE> return context
PostUpdateView View to update a Post Args: AutoPermissionRequiredMixin ([type]): Tests if the User has the permission to do that UpdateView ([type]): [description] Returns: [type]: [description]
62598faad486a94d0ba2bf36
class LokiOptions_Default_Resources_Statefulset(Data): <NEW_LINE> <INDENT> def is_enabled(self) -> bool: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def get_value(self) -> Any: <NEW_LINE> <INDENT> return { 'requests': { 'cpu': '100m', 'memory': '128Mi' }, 'limits': { 'cpu': '200m', 'memory': '256Mi' }, }
Default option value for: ```kubernetes.resources.statefulset```
62598faa71ff763f4b5e76d7
class GCSLog(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> remote_conn_id = configuration.get('core', 'REMOTE_LOG_CONN_ID') <NEW_LINE> self.use_gcloud = False <NEW_LINE> try: <NEW_LINE> <INDENT> from airflow.contrib.hooks import GCSHook <NEW_LINE> self.hook = GCSHook(remote_conn_id) <NEW_LINE> self.use_gcloud = True <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from airflow.contrib.hooks import GoogleCloudStorageHook <NEW_LINE> self.hook = GoogleCloudStorageHook( scope='https://www.googleapis.com/auth/devstorage.read_write', google_cloud_storage_conn_id=remote_conn_id) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.hook = None <NEW_LINE> logging.error( 'Could not create a GCSHook with connection id "{}". ' 'Please make sure that either airflow[gcloud] or ' 'airflow[gcp_api] is installed and the GCS connection ' 'exists.'.format(remote_conn_id)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def read(self, remote_log_location, return_error=False): <NEW_LINE> <INDENT> if self.hook: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.use_gcloud: <NEW_LINE> <INDENT> gcs_blob = self.hook.get_blob(remote_log_location) <NEW_LINE> if gcs_blob: <NEW_LINE> <INDENT> return gcs_blob.download_as_string().decode() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> bkt, blob = self.parse_gcs_url(remote_log_location) <NEW_LINE> return self.hook.download(bkt, blob).decode() <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> err = 'Could not read logs from {}'.format(remote_log_location) <NEW_LINE> logging.error(err) <NEW_LINE> return err if return_error else '' <NEW_LINE> <DEDENT> def write(self, log, remote_log_location, append=False): <NEW_LINE> <INDENT> if self.hook: <NEW_LINE> <INDENT> if append: <NEW_LINE> <INDENT> old_log = self.read(remote_log_location) <NEW_LINE> log = old_log + '\n' + log <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if self.use_gcloud: <NEW_LINE> <INDENT> self.hook.upload_from_string( log, blob=remote_log_location, replace=True) <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bkt, blob = self.parse_gcs_url(remote_log_location) <NEW_LINE> from tempfile import NamedTemporaryFile <NEW_LINE> with NamedTemporaryFile(mode='w+') as tmpfile: <NEW_LINE> <INDENT> tmpfile.write(log) <NEW_LINE> tmpfile.flush() <NEW_LINE> self.hook.upload(bkt, blob, tmpfile.name) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> logging.error('Could not write logs to {}'.format(remote_log_location)) <NEW_LINE> <DEDENT> def parse_gcs_url(self, gsurl): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from urllib.parse import urlparse <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> from urlparse import urlparse <NEW_LINE> <DEDENT> parsed_url = urlparse(gsurl) <NEW_LINE> if not parsed_url.netloc: <NEW_LINE> <INDENT> raise AirflowException('Please provide a bucket name') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bucket = parsed_url.netloc <NEW_LINE> blob = parsed_url.path.strip('/') <NEW_LINE> return (bucket, blob)
Utility class for reading and writing logs in GCS. Requires either airflow[gcloud] or airflow[gcp_api] and setting the REMOTE_BASE_LOG_FOLDER and REMOTE_LOG_CONN_ID configuration options in airflow.cfg.
62598faa0c0af96317c562eb
class QLearningAgent(ReinforcementAgent): <NEW_LINE> <INDENT> def __init__(self, **args): <NEW_LINE> <INDENT> ReinforcementAgent.__init__(self, **args) <NEW_LINE> self.qvalues = util.Counter() <NEW_LINE> <DEDENT> def getQValue(self, state, action): <NEW_LINE> <INDENT> return self.qvalues[(state, action)] <NEW_LINE> <DEDENT> def computeValueFromQValues(self, state): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(state) <NEW_LINE> if not legalActions: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> max = -10000000 <NEW_LINE> for act in legalActions: <NEW_LINE> <INDENT> qvalue = self.getQValue(state, act) <NEW_LINE> if qvalue > max: <NEW_LINE> <INDENT> max = qvalue <NEW_LINE> <DEDENT> <DEDENT> return max <NEW_LINE> <DEDENT> def computeActionFromQValues(self, state): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(state) <NEW_LINE> if not legalActions: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> action = None <NEW_LINE> max = -10000000 <NEW_LINE> for act in legalActions: <NEW_LINE> <INDENT> qvalue = self.getQValue(state, act) <NEW_LINE> if qvalue > max: <NEW_LINE> <INDENT> max = qvalue <NEW_LINE> action = act <NEW_LINE> <DEDENT> <DEDENT> return action <NEW_LINE> <DEDENT> def getAction(self, state): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(state) <NEW_LINE> action = None <NEW_LINE> if util.flipCoin(self.epsilon): <NEW_LINE> <INDENT> action = random.choice(legalActions) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> action = self.getPolicy(state) <NEW_LINE> <DEDENT> return action <NEW_LINE> <DEDENT> def update(self, state, action, nextState, reward): <NEW_LINE> <INDENT> discount = self.discount <NEW_LINE> alpha = self.alpha <NEW_LINE> qvalue = self.getQValue(state, action) <NEW_LINE> value = self.getValue(nextState) <NEW_LINE> n_value = alpha * (reward + (discount * value)) + ((1-alpha) * qvalue) <NEW_LINE> self.qvalues[(state, action)] = n_value <NEW_LINE> <DEDENT> def getPolicy(self, state): <NEW_LINE> <INDENT> return self.computeActionFromQValues(state) <NEW_LINE> <DEDENT> def getValue(self, state): <NEW_LINE> <INDENT> return self.computeValueFromQValues(state)
Q-Learning Agent Functions you should fill in: - computeValueFromQValues - computeActionFromQValues - getQValue - getAction - update Instance variables you have access to - self.epsilon (exploration prob) - self.alpha (learning rate) - self.discount (discount rate) Functions you should use - self.getLegalActions(state) which returns legal actions for a state
62598faa498bea3a75a57a86
class MappingUsersRulesRuleOptions(object): <NEW_LINE> <INDENT> swagger_types = { '_break': 'bool', 'default_user': 'MappingUsersRulesRuleUser2', 'group': 'bool', 'groups': 'bool', 'user': 'bool' } <NEW_LINE> attribute_map = { '_break': 'break', 'default_user': 'default_user', 'group': 'group', 'groups': 'groups', 'user': 'user' } <NEW_LINE> def __init__(self, _break=None, default_user=None, group=None, groups=None, user=None): <NEW_LINE> <INDENT> self.__break = None <NEW_LINE> self._default_user = None <NEW_LINE> self._group = None <NEW_LINE> self._groups = None <NEW_LINE> self._user = None <NEW_LINE> self.discriminator = None <NEW_LINE> if _break is not None: <NEW_LINE> <INDENT> self._break = _break <NEW_LINE> <DEDENT> if default_user is not None: <NEW_LINE> <INDENT> self.default_user = default_user <NEW_LINE> <DEDENT> if group is not None: <NEW_LINE> <INDENT> self.group = group <NEW_LINE> <DEDENT> if groups is not None: <NEW_LINE> <INDENT> self.groups = groups <NEW_LINE> <DEDENT> if user is not None: <NEW_LINE> <INDENT> self.user = user <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def _break(self): <NEW_LINE> <INDENT> return self.__break <NEW_LINE> <DEDENT> @_break.setter <NEW_LINE> def _break(self, _break): <NEW_LINE> <INDENT> self.__break = _break <NEW_LINE> <DEDENT> @property <NEW_LINE> def default_user(self): <NEW_LINE> <INDENT> return self._default_user <NEW_LINE> <DEDENT> @default_user.setter <NEW_LINE> def default_user(self, default_user): <NEW_LINE> <INDENT> self._default_user = default_user <NEW_LINE> <DEDENT> @property <NEW_LINE> def group(self): <NEW_LINE> <INDENT> return self._group <NEW_LINE> <DEDENT> @group.setter <NEW_LINE> def group(self, group): <NEW_LINE> <INDENT> self._group = group <NEW_LINE> <DEDENT> @property <NEW_LINE> def groups(self): <NEW_LINE> <INDENT> return self._groups <NEW_LINE> <DEDENT> @groups.setter <NEW_LINE> def groups(self, groups): <NEW_LINE> <INDENT> self._groups = groups <NEW_LINE> <DEDENT> @property <NEW_LINE> def user(self): <NEW_LINE> <INDENT> return self._user <NEW_LINE> <DEDENT> @user.setter <NEW_LINE> def user(self, user): <NEW_LINE> <INDENT> self._user = user <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, MappingUsersRulesRuleOptions): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
62598faa4f88993c371f04be
class TestUndbm(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def test_undbm_1(self): <NEW_LINE> <INDENT> self.assertTrue(np.allclose([undbm(53.015)], [100.054125892], rtol=1e-05, atol=1e-08)) <NEW_LINE> <DEDENT> def test_undbm_2(self): <NEW_LINE> <INDENT> self.assertTrue(np.allclose([undbm(3, 100)], [0.44668359215], rtol=1e-05, atol=1e-08)) <NEW_LINE> <DEDENT> def test_undbm_3(self): <NEW_LINE> <INDENT> self.assertTrue(np.isscalar(undbm(3, 100)))
Test class for undbm()
62598faa0a50d4780f705346
class I_cpseq_w_w_B(Instruction_w_w_B): <NEW_LINE> <INDENT> name = 'cpseq' <NEW_LINE> mask = 0xFF83F0 <NEW_LINE> code = 0xE78000 <NEW_LINE> feat = idaapi.CF_USE1 | idaapi.CF_USE2
CPSEQ{.B} Wb, Wn
62598faa7d847024c075c32c
class CharacterTable(): <NEW_LINE> <INDENT> def __init__(self, chars, maxlen): <NEW_LINE> <INDENT> self.chars = sorted(set(chars)) <NEW_LINE> self.char_index = dict((c, i) for i, c in enumerate(self.chars)) <NEW_LINE> self.index_char = dict((i, c) for i, c in enumerate(self.chars)) <NEW_LINE> self.maxlen = maxlen <NEW_LINE> <DEDENT> def encode(self, C, maxlen): <NEW_LINE> <INDENT> X = np.zeros((maxlen, len(self.chars))) <NEW_LINE> for i, c in enumerate(C): <NEW_LINE> <INDENT> X[i, self.char_index[c]] = 1 <NEW_LINE> <DEDENT> return X <NEW_LINE> <DEDENT> def decode(self, X, calc_argmax=True): <NEW_LINE> <INDENT> if calc_argmax: <NEW_LINE> <INDENT> X = X.argmax(axis=-1) <NEW_LINE> <DEDENT> return ''.join(self.index_char[x] for x in X)
encode: 将一个str转化为一个n维数组 decode: 将一个n为数组转化为一个str 输入输出分别为 character_table = [' ', '+', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 如果一个question = [' 123+23'] 那个改question对应的数组就是(7,12): 同样expected最大是一个四位数[' 146']: 那么ans对应的数组就是[4,12]
62598faa23849d37ff85101d
class UserNotFound(APIException): <NEW_LINE> <INDENT> status_code = 404 <NEW_LINE> default_detail = 'Sorry the user with the id dosen\'t exist' <NEW_LINE> default_code = "user_not_found"
User exists. This exception provide a good custom error message, when a user is not found.
62598faa5166f23b2e243341
class DB(object): <NEW_LINE> <INDENT> supported_databases = [DATABASE_MYSQL, DATABASE_SQLITE] <NEW_LINE> database_type_to_connection = { DATABASE_MYSQL: MySQLConnection, } <NEW_LINE> def __init__(self, database_type, db_name=None, username=None, password=None, host='localhost', port=3306, unix_socket=None): <NEW_LINE> <INDENT> if database_type not in self.supported_databases: <NEW_LINE> <INDENT> raise BeeSQLError('database_type: {} not supported'.format(database_type)) <NEW_LINE> <DEDENT> self.database_type = database_type <NEW_LINE> self.db_name = db_name <NEW_LINE> self.username = username <NEW_LINE> self.password = password <NEW_LINE> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.unix_socket = unix_socket <NEW_LINE> <DEDENT> def query(self, table=None, table_alias=None): <NEW_LINE> <INDENT> if not self.db_name: <NEW_LINE> <INDENT> raise BeeSQLError('No database chosen') <NEW_LINE> <DEDENT> if self.database_type == DATABASE_MYSQL: <NEW_LINE> <INDENT> _query = MySQLQuery(self, table, table_alias) <NEW_LINE> return _query <NEW_LINE> <DEDENT> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<DB {}:{}'.format(self.database_type, self.db_name) <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> Connection = self.database_type_to_connection[self.database_type] <NEW_LINE> conn = Connection(username=self.username, password=self.password, db=self.db_name, host=self.host, port=self.port, unix_socket=self.unix_socket) <NEW_LINE> return conn <NEW_LINE> <DEDENT> def use(self, db_name): <NEW_LINE> <INDENT> self.db_name = db_name <NEW_LINE> return self <NEW_LINE> <DEDENT> def auth(self, username, password): <NEW_LINE> <INDENT> self.username = username <NEW_LINE> self.password = password <NEW_LINE> return self <NEW_LINE> <DEDENT> def escape(self, item): <NEW_LINE> <INDENT> if self.database_type == DATABASE_MYSQL: <NEW_LINE> <INDENT> str_item = str(item) <NEW_LINE> return pymysql.escape_string(str_item) <NEW_LINE> <DEDENT> return item
Database connection
62598faa76e4537e8c3ef516
class Recognizer(Configurable): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Configurable.__init__(self) <NEW_LINE> Configurable.load(self)
Fake :class:`Recognizer <Camera>` class. Just to simulate configs
62598faa3cc13d1c6d4656d5
class CLRSSFeed(object): <NEW_LINE> <INDENT> def __init__(self, city_url, make, model): <NEW_LINE> <INDENT> self.city_url = city_url <NEW_LINE> self.make = make <NEW_LINE> self.model = model <NEW_LINE> self.rss_url = f"{self.city_url}/search/mcy?format=rss&query={self.make.lower()}+{self.model.lower()}*" <NEW_LINE> self.posting_urls = []
Creat object to hold RSS Feed information for a given search location.
62598faae5267d203ee6b873
class ProsegurAlarm(alarm.AlarmControlPanelEntity): <NEW_LINE> <INDENT> def __init__(self, contract: str, auth: Auth) -> None: <NEW_LINE> <INDENT> self._changed_by = None <NEW_LINE> self._installation = None <NEW_LINE> self.contract = contract <NEW_LINE> self._auth = auth <NEW_LINE> self._attr_name = f"contract {self.contract}" <NEW_LINE> self._attr_unique_id = self.contract <NEW_LINE> self._attr_supported_features = SUPPORT_ALARM_ARM_AWAY | SUPPORT_ALARM_ARM_HOME <NEW_LINE> <DEDENT> async def async_update(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self._installation = await Installation.retrieve(self._auth) <NEW_LINE> <DEDENT> except ConnectionError as err: <NEW_LINE> <INDENT> _LOGGER.error(err) <NEW_LINE> self._attr_available = False <NEW_LINE> return <NEW_LINE> <DEDENT> self._attr_state = STATE_MAPPING.get(self._installation.status) <NEW_LINE> self._attr_available = True <NEW_LINE> <DEDENT> async def async_alarm_disarm(self, code=None): <NEW_LINE> <INDENT> await self._installation.disarm(self._auth) <NEW_LINE> <DEDENT> async def async_alarm_arm_home(self, code=None): <NEW_LINE> <INDENT> await self._installation.arm_partially(self._auth) <NEW_LINE> <DEDENT> async def async_alarm_arm_away(self, code=None): <NEW_LINE> <INDENT> await self._installation.arm(self._auth)
Representation of a Prosegur alarm status.
62598faa379a373c97d98f7b
@public.add <NEW_LINE> class Table: <NEW_LINE> <INDENT> columns = [] <NEW_LINE> data = [] <NEW_LINE> def __init__(self, columns, data): <NEW_LINE> <INDENT> self.columns = list(columns) <NEW_LINE> self.data = list(data) <NEW_LINE> <DEDENT> def get_headers(self): <NEW_LINE> <INDENT> return self.columns <NEW_LINE> <DEDENT> def get_alignments(self): <NEW_LINE> <INDENT> values = [] <NEW_LINE> for column in self.columns: <NEW_LINE> <INDENT> align = getattr(column, "align", "left") <NEW_LINE> value = dict(left="-", center=":-:", right="-:").get(align, "-") <NEW_LINE> values.append(value) <NEW_LINE> <DEDENT> return values <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> return self.data <NEW_LINE> <DEDENT> def render(self): <NEW_LINE> <INDENT> if not self.get_data(): <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> return "\n".join([ "|".join(self.get_headers()), "|".join(self.get_alignments()), ] + list(map(lambda r: " |".join(r), self.get_data()))) <NEW_LINE> <DEDENT> def save(self, path): <NEW_LINE> <INDENT> dirname = os.path.dirname(path) <NEW_LINE> if not dirname and not os.path.exists(dirname): <NEW_LINE> <INDENT> os.makedirs(dirname) <NEW_LINE> <DEDENT> open(path, "w").write(str(self)) <NEW_LINE> <DEDENT> def __bool__(self): <NEW_LINE> <INDENT> return len(self.get_data()) > 0 <NEW_LINE> <DEDENT> def __nonzero__(self): <NEW_LINE> <INDENT> return self.__bool__() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.render() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.__str__()
table class. attrs: `columns`, `data`
62598faa460517430c432011
class ExtractURLpartsTests(TestCase): <NEW_LINE> <INDENT> def test_types(self): <NEW_LINE> <INDENT> url_scheme, server_name, server_port, path_info, script_name = _extractURLparts(requestMock(b"/f\xc3\xb6\xc3\xb6")) <NEW_LINE> self.assertIsInstance(url_scheme, unicode) <NEW_LINE> self.assertIsInstance(server_name, unicode) <NEW_LINE> self.assertIsInstance(server_port, int) <NEW_LINE> self.assertIsInstance(path_info, unicode) <NEW_LINE> self.assertIsInstance(script_name, unicode) <NEW_LINE> <DEDENT> def assertDecodingFailure(self, exception, part): <NEW_LINE> <INDENT> self.assertEqual(1, len(exception.errors)) <NEW_LINE> actualPart, actualFail = exception.errors[0] <NEW_LINE> self.assertEqual(part, actualPart) <NEW_LINE> self.assertIsInstance(actualFail.value, UnicodeDecodeError) <NEW_LINE> <DEDENT> def test_failServerName(self): <NEW_LINE> <INDENT> request = requestMock(b"/foo") <NEW_LINE> request.getRequestHostname = lambda: b"f\xc3\xc3\xb6" <NEW_LINE> e = self.assertRaises(_URLDecodeError, _extractURLparts, request) <NEW_LINE> self.assertDecodingFailure(e, "SERVER_NAME") <NEW_LINE> <DEDENT> def test_failPathInfo(self): <NEW_LINE> <INDENT> request = requestMock(b"/f\xc3\xc3\xb6") <NEW_LINE> e = self.assertRaises(_URLDecodeError, _extractURLparts, request) <NEW_LINE> self.assertDecodingFailure(e, "PATH_INFO") <NEW_LINE> <DEDENT> def test_failScriptName(self): <NEW_LINE> <INDENT> request = requestMock(b"/foo") <NEW_LINE> request.prepath = [b"f\xc3\xc3\xb6"] <NEW_LINE> e = self.assertRaises(_URLDecodeError, _extractURLparts, request) <NEW_LINE> self.assertDecodingFailure(e, "SCRIPT_NAME") <NEW_LINE> <DEDENT> def test_failAll(self): <NEW_LINE> <INDENT> request = requestMock(b"/f\xc3\xc3\xb6") <NEW_LINE> request.prepath = [b"f\xc3\xc3\xb6"] <NEW_LINE> request.getRequestHostname = lambda: b"f\xc3\xc3\xb6" <NEW_LINE> e = self.assertRaises(_URLDecodeError, _extractURLparts, request) <NEW_LINE> self.assertEqual( set(["SERVER_NAME", "PATH_INFO", "SCRIPT_NAME"]), set(part for part, _ in e.errors) )
Tests for L{klein.resource._extractURLparts}.
62598faafff4ab517ebcd74e
class LtmMonitorSmb(LtmMonitorSmbSchema): <NEW_LINE> <INDENT> cli_command = "/mgmt/tm/ltm/monitor/smb" <NEW_LINE> def rest(self): <NEW_LINE> <INDENT> response = self.device.get(self.cli_command) <NEW_LINE> response_json = response.json() <NEW_LINE> if not response_json: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> return response_json
To F5 resource for /mgmt/tm/ltm/monitor/smb
62598faa3617ad0b5ee060bd
class Translator(gtapi.TranslateService): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Translator, self).__init__() <NEW_LINE> self.lock = threading.Lock() <NEW_LINE> <DEDENT> def trans_details(self, source_lang, target_lang, value): <NEW_LINE> <INDENT> response = super(Translator, self).trans_details(source_lang, target_lang, value) <NEW_LINE> result = u'' <NEW_LINE> if response: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sentence = response.get(u'sentences', [])[0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> sentence = {} <NEW_LINE> <DEDENT> details = response.get(u'dict', []) <NEW_LINE> result = u'\n'.join([ sentence.get(u'orig', u''), sentence.get(u'trans', u''), u'', u'Translit: {0}'.format(sentence.get(u'translit', u'')), ]) <NEW_LINE> for form in details: <NEW_LINE> <INDENT> result = u'\n'.join([ result, u'', u'{0} | {1}'.format(form.get(u'base_form', u''), form.get(u'pos', u'')), ]) <NEW_LINE> for entry in form.get(u'entry', []): <NEW_LINE> <INDENT> result = u' '.join([ result, u'\n', u' {0}: '.format(entry.get(u'word', u'')), u', '.join(entry.get(u'reverse_translation', [])), u'[{0}]'.format(int(entry.get(u'score', 0.0) * 10000)), ]) <NEW_LINE> <DEDENT> result = u'\n'.join([result, u'', u' Phrases:']) <NEW_LINE> for term in form.get(u'terms', []): <NEW_LINE> <INDENT> result = u'\n '.join([result, term]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return result
Customization of :class:`google_translate_api.TranslateService` mainly for output formatting.
62598faaa219f33f346c6780
class RegisterView(CreateView): <NEW_LINE> <INDENT> template_name = 'accounts/register.html' <NEW_LINE> form_class = RegisterForm <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> logout(self.request) <NEW_LINE> form_class = self.get_form_class() <NEW_LINE> form = self.get_form(form_class) <NEW_LINE> context = { 'form': form, } <NEW_LINE> return render(request, self.template_name, context) <NEW_LINE> <DEDENT> def form_valid(self, form): <NEW_LINE> <INDENT> form.save() <NEW_LINE> username = self.request.POST['username'] <NEW_LINE> password = self.request.POST['password1'] <NEW_LINE> user = authenticate(username=username, password=password) <NEW_LINE> if user is not None: <NEW_LINE> <INDENT> login(self.request, user) <NEW_LINE> user_profile = UserProfile.objects.create(user_name=user) <NEW_LINE> user_profile.save() <NEW_LINE> print(user_profile) <NEW_LINE> messages.success(self.request, f'Congratulations {username}! Your account has been created.') <NEW_LINE> return redirect('update_user_profile', pk=user.id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return redirect('index')
Register view template, render form. If form valid, try to authenticate user and redirect to User Profile
62598faa2ae34c7f260ab04b
class HuberParameter(Model): <NEW_LINE> <INDENT> def __init__(self, epsilon=None, max_iter=None, alpha=None, tol=None): <NEW_LINE> <INDENT> self.openapi_types = { 'epsilon': 'float', 'max_iter': 'int', 'alpha': 'float', 'tol': 'float' } <NEW_LINE> self.attribute_map = { 'epsilon': 'epsilon', 'max_iter': 'max_iter', 'alpha': 'alpha', 'tol': 'tol' } <NEW_LINE> self._epsilon = epsilon <NEW_LINE> self._max_iter = max_iter <NEW_LINE> self._alpha = alpha <NEW_LINE> self._tol = tol <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_dict(cls, dikt) -> 'HuberParameter': <NEW_LINE> <INDENT> return util.deserialize_model(dikt, cls) <NEW_LINE> <DEDENT> @property <NEW_LINE> def epsilon(self): <NEW_LINE> <INDENT> return self._epsilon <NEW_LINE> <DEDENT> @epsilon.setter <NEW_LINE> def epsilon(self, epsilon): <NEW_LINE> <INDENT> self._epsilon = epsilon <NEW_LINE> <DEDENT> @property <NEW_LINE> def max_iter(self): <NEW_LINE> <INDENT> return self._max_iter <NEW_LINE> <DEDENT> @max_iter.setter <NEW_LINE> def max_iter(self, max_iter): <NEW_LINE> <INDENT> self._max_iter = max_iter <NEW_LINE> <DEDENT> @property <NEW_LINE> def alpha(self): <NEW_LINE> <INDENT> return self._alpha <NEW_LINE> <DEDENT> @alpha.setter <NEW_LINE> def alpha(self, alpha): <NEW_LINE> <INDENT> self._alpha = alpha <NEW_LINE> <DEDENT> @property <NEW_LINE> def tol(self): <NEW_LINE> <INDENT> return self._tol <NEW_LINE> <DEDENT> @tol.setter <NEW_LINE> def tol(self, tol): <NEW_LINE> <INDENT> self._tol = tol
NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually.
62598faae5267d203ee6b874
class DescribeAlarmsRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Offset = None <NEW_LINE> self.Limit = None <NEW_LINE> self.Status = None <NEW_LINE> self.BeginTime = None <NEW_LINE> self.EndTime = None <NEW_LINE> self.ObjName = None <NEW_LINE> self.SortBy = None <NEW_LINE> self.SortType = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Offset = params.get("Offset") <NEW_LINE> self.Limit = params.get("Limit") <NEW_LINE> self.Status = params.get("Status") <NEW_LINE> self.BeginTime = params.get("BeginTime") <NEW_LINE> self.EndTime = params.get("EndTime") <NEW_LINE> self.ObjName = params.get("ObjName") <NEW_LINE> self.SortBy = params.get("SortBy") <NEW_LINE> self.SortType = params.get("SortType")
DescribeAlarms请求参数结构体
62598faad7e4931a7ef3c000
class Customer_LevelForm(forms.Form): <NEW_LINE> <INDENT> level = forms.ChoiceField(choices=level_choices, initial=2) <NEW_LINE> name = forms.CharField(max_length=20)
客户水平
62598faa4428ac0f6e65848e
class Watchable(TutorialObject): <NEW_LINE> <INDENT> def at_object_creation(self): <NEW_LINE> <INDENT> self.cmdset.add_default(CmdSetWatchable, permanent=True) <NEW_LINE> self.watch_reward = 1 <NEW_LINE> <DEDENT> def at_watch(self): <NEW_LINE> <INDENT> return self.watch_reward
A watchable object. All that is special about it is that it has the "watch" command available on it.
62598faa2ae34c7f260ab04c
class InvokeCACTIP(Invoke): <NEW_LINE> <INDENT> def __init__(self, output_dir, cfg_dir=None, log_dir=None, cacti_path=None): <NEW_LINE> <INDENT> super().__init__(output_dir, cfg_dir=cfg_dir, log_dir=log_dir, cacti_path=cacti_path) <NEW_LINE> self.cfg_cls = config.ConfigCACTIP <NEW_LINE> self.res_cls = result_parser.ResultParserCACTIP
Environment class to invoke CACTI-P.
62598faaa8370b77170f0346
class Message(AttrDict): <NEW_LINE> <INDENT> def __init__(self, folder, message_id, data): <NEW_LINE> <INDENT> assert is_sha1(message_id), 'Message id not a SHA1 hash' <NEW_LINE> self.folder = folder <NEW_LINE> self.id = message_id <NEW_LINE> super(AttrDict, self).__init__(data) <NEW_LINE> self['startTime'] = gmtime(int(self['startTime']) / 1000) <NEW_LINE> self['displayStartDateTime'] = datetime.strptime(self['displayStartDateTime'], '%m/%d/%y %I:%M %p') <NEW_LINE> self['displayStartTime'] = self['displayStartDateTime'].time() <NEW_LINE> <DEDENT> def delete(self, trash=1): <NEW_LINE> <INDENT> self.folder.voice.__messages_post('delete', self.id, trash=trash) <NEW_LINE> <DEDENT> def star(self, star=1): <NEW_LINE> <INDENT> self.folder.voice.__messages_post('star', self.id, star=star) <NEW_LINE> <DEDENT> def mark(self, read=1): <NEW_LINE> <INDENT> self.folder.voice.__messages_post('mark', self.id, read=read) <NEW_LINE> <DEDENT> def download(self, adir=None): <NEW_LINE> <INDENT> return self.folder.voice.download(self, adir) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.id <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Message #%s (%s)>' % (self.id, self.phoneNumber)
Wrapper for all call/sms message instances stored in Google Voice Attributes are: * id: SHA1 identifier * isTrash: bool * displayStartDateTime: datetime * star: bool * isSpam: bool * startTime: gmtime * labels: list * displayStartTime: time * children: str * note: str * isRead: bool * displayNumber: str * relativeStartTime: str * phoneNumber: str * type: int
62598faabaa26c4b54d4f21c
class Name(PhotosBaseElement): <NEW_LINE> <INDENT> _tag = 'name'
The Google Photo `Name' element
62598faa0a50d4780f705348
class QAPair(): <NEW_LINE> <INDENT> def __init__(self, question, answers): <NEW_LINE> <INDENT> self.question = question <NEW_LINE> self.answers = answers
Stores a question and a list of acceptable answers.
62598faa5166f23b2e243343
class MixinHorizontal: <NEW_LINE> <INDENT> def _add_label(self): <NEW_LINE> <INDENT> Label(self, text=self._name, bg=self._color, bd=0).pack(side=LEFT) <NEW_LINE> <DEDENT> def _add_entry(self): <NEW_LINE> <INDENT> self._entry = Entry(self, width=7, validate='key') <NEW_LINE> self._entry.pack(side=LEFT, fill=X) <NEW_LINE> self._entry.config(textvariable=self._value_var)
Override _add_label and _add_entry methods to provide a horizontal arrangement instead of vertical.
62598faa236d856c2adc93f2
class AlertName(EtcString): <NEW_LINE> <INDENT> pass
Update the parent's alert name
62598faa7b25080760ed7418
class UndoableDelete(object): <NEW_LINE> <INDENT> def __init__(self, text_buffer, start_iter, end_iter): <NEW_LINE> <INDENT> self.text = str(text_buffer.get_text(start_iter, end_iter, True)) <NEW_LINE> self.start = start_iter.get_offset() <NEW_LINE> self.end = end_iter.get_offset() <NEW_LINE> insert_iter = text_buffer.get_iter_at_mark(text_buffer.get_insert()) <NEW_LINE> if insert_iter.get_offset() <= self.start: <NEW_LINE> <INDENT> self.delete_key_used = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.delete_key_used = False <NEW_LINE> <DEDENT> if self.end - self.start > 1 or self.text in ("\r", "\n", " "): <NEW_LINE> <INDENT> self.mergeable = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.mergeable = True <NEW_LINE> <DEDENT> self.tags = None
something that has been deleted from our textbuffer
62598faae5267d203ee6b875
class Interaction(object): <NEW_LINE> <INDENT> def interact(self, view): <NEW_LINE> <INDENT> pass
TEMPLATE CLASS for Interactions. An Interaction is a sequence of displayables and prompts that display on a View in order. Interactions are created by Stories, but are not necessarily able to reference their creator. This class's single method returns instructions of some sort that tell the Story how to produce its next Interaction, or update its internal state if it has dynamic data.
62598faa8da39b475be0314f