_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q20300
_Paragraph.runs
train
def runs(self): """ Immutable sequence of |_Run| objects corresponding to the runs in this paragraph. """ return tuple(_Run(r, self) for r in self._element.r_lst)
python
{ "resource": "" }
q20301
BaseShape.click_action
train
def click_action(self): """|ActionSetting| instance providing access to click behaviors. Click behaviors are hyperlink-like behaviors including jumping to a hyperlink (web page) or to another slide in the presentation. The click action is that defined on the overall shape, not a run of ...
python
{ "resource": "" }
q20302
_BaseShapes._next_shape_id
train
def _next_shape_id(self): """Return a unique shape id suitable for use with a new shape. The returned id is 1 greater than the maximum shape id used so far. In practice, the minimum id is 2 because the spTree element is always assigned id="1". """ # ---presence of cached...
python
{ "resource": "" }
q20303
_BaseGroupShapes.add_connector
train
def add_connector(self, connector_type, begin_x, begin_y, end_x, end_y): """Add a newly created connector shape to the end of this shape tree. *connector_type* is a member of the :ref:`MsoConnectorType` enumeration and the end-point values are specified as EMU values. The returned conne...
python
{ "resource": "" }
q20304
_BaseGroupShapes.add_group_shape
train
def add_group_shape(self, shapes=[]): """Return a |GroupShape| object newly appended to this shape tree. The group shape is empty and must be populated with shapes using methods on its shape tree, available on its `.shapes` property. The position and extents of the group shape are deter...
python
{ "resource": "" }
q20305
_BaseGroupShapes.add_shape
train
def add_shape(self, autoshape_type_id, left, top, width, height): """Return new |Shape| object appended to this shape tree. *autoshape_type_id* is a member of :ref:`MsoAutoShapeType` e.g. ``MSO_SHAPE.RECTANGLE`` specifying the type of shape to be added. The remaining arguments specify t...
python
{ "resource": "" }
q20306
_BaseGroupShapes.add_textbox
train
def add_textbox(self, left, top, width, height): """Return newly added text box shape appended to this shape tree. The text box is of the specified size, located at the specified position on the slide. """ sp = self._add_textbox_sp(left, top, width, height) self._recalcu...
python
{ "resource": "" }
q20307
_BaseGroupShapes.build_freeform
train
def build_freeform(self, start_x=0, start_y=0, scale=1.0): """Return |FreeformBuilder| object to specify a freeform shape. The optional *start_x* and *start_y* arguments specify the starting pen position in local coordinates. They will be rounded to the nearest integer before use and ea...
python
{ "resource": "" }
q20308
SlideShapes.title
train
def title(self): """ The title placeholder shape on the slide or |None| if the slide has no title placeholder. """ for elm in self._spTree.iter_ph_elms(): if elm.ph_idx == 0: return self._shape_factory(elm) return None
python
{ "resource": "" }
q20309
_MoviePicElementCreator._poster_frame_rId
train
def _poster_frame_rId(self): """Return the rId of relationship to poster frame image. The poster frame is the image used to represent the video before it's played. """ _, poster_frame_rId = self._slide_part.get_or_add_image_part( self._poster_frame_image_file ...
python
{ "resource": "" }
q20310
_MoviePicElementCreator._video_part_rIds
train
def _video_part_rIds(self): """Return the rIds for relationships to media part for video. This is where the media part and its relationships to the slide are actually created. """ media_rId, video_rId = self._slide_part.get_or_add_video_media_part( self._video ...
python
{ "resource": "" }
q20311
Shape.shape_type
train
def shape_type(self): """ Unique integer identifying the type of this shape, like ``MSO_SHAPE_TYPE.TEXT_BOX``. """ if self.is_placeholder: return MSO_SHAPE_TYPE.PLACEHOLDER if self._sp.has_custom_geometry: return MSO_SHAPE_TYPE.FREEFORM if ...
python
{ "resource": "" }
q20312
Package.next_media_partname
train
def next_media_partname(self, ext): """Return |PackURI| instance for next available media partname. Partname is first available, starting at sequence number 1. Empty sequence numbers are reused. *ext* is used as the extension on the returned partname. """ def first_avail...
python
{ "resource": "" }
q20313
_ImageParts._find_by_sha1
train
def _find_by_sha1(self, sha1): """ Return an |ImagePart| object belonging to this package or |None| if no matching image part is found. The image part is identified by the SHA1 hash digest of the image binary it contains. """ for image_part in self: # ---skip ...
python
{ "resource": "" }
q20314
NotesMasterPart.create_default
train
def create_default(cls, package): """ Create and return a default notes master part, including creating the new theme it requires. """ notes_master_part = cls._new(package) theme_part = cls._new_theme_part(package) notes_master_part.relate_to(theme_part, RT.THEME)...
python
{ "resource": "" }
q20315
NotesMasterPart._new_theme_part
train
def _new_theme_part(cls, package): """ Create and return a default theme part suitable for use with a notes master. """ partname = package.next_partname('/ppt/theme/theme%d.xml') content_type = CT.OFC_THEME theme = CT_OfficeStyleSheet.new_default() return ...
python
{ "resource": "" }
q20316
SlidePart.get_or_add_video_media_part
train
def get_or_add_video_media_part(self, video): """Return rIds for media and video relationships to media part. A new |MediaPart| object is created if it does not already exist (such as would occur if the same video appeared more than once in a presentation). Two relationships to the med...
python
{ "resource": "" }
q20317
SlidePart.notes_slide
train
def notes_slide(self): """ The |NotesSlide| instance associated with this slide. If the slide does not have a notes slide, a new one is created. The same single instance is returned on each call. """ try: notes_slide_part = self.part_related_by(RT.NOTES_SLIDE)...
python
{ "resource": "" }
q20318
SlidePart._add_notes_slide_part
train
def _add_notes_slide_part(self): """ Return a newly created |NotesSlidePart| object related to this slide part. Caller is responsible for ensuring this slide doesn't already have a notes slide part. """ notes_slide_part = NotesSlidePart.new(self.package, self) sel...
python
{ "resource": "" }
q20319
_BaseWorkbookWriter.xlsx_blob
train
def xlsx_blob(self): """ Return the byte stream of an Excel file formatted as chart data for the category chart specified in the chart data object. """ xlsx_file = BytesIO() with self._open_worksheet(xlsx_file) as (workbook, worksheet): self._populate_workshee...
python
{ "resource": "" }
q20320
CategoryWorkbookWriter._series_col_letter
train
def _series_col_letter(self, series): """ The letter of the Excel worksheet column in which the data for a series appears. """ column_number = 1 + series.categories.depth + series.index return self._column_reference(column_number)
python
{ "resource": "" }
q20321
_BasePlot.data_labels
train
def data_labels(self): """ |DataLabels| instance providing properties and methods on the collection of data labels associated with this plot. """ dLbls = self._element.dLbls if dLbls is None: raise ValueError( 'plot has no data labels, set has_...
python
{ "resource": "" }
q20322
Chart.font
train
def font(self): """Font object controlling text format defaults for this chart.""" defRPr = ( self._chartSpace .get_or_add_txPr() .p_lst[0] .get_or_add_pPr() .get_or_add_defRPr() ) return Font(defRPr)
python
{ "resource": "" }
q20323
Chart.legend
train
def legend(self): """ A |Legend| object providing access to the properties of the legend for this chart. """ legend_elm = self._chartSpace.chart.legend if legend_elm is None: return None return Legend(legend_elm)
python
{ "resource": "" }
q20324
Chart.value_axis
train
def value_axis(self): """ The |ValueAxis| object providing access to properties of the value axis of this chart. Raises |ValueError| if the chart has no value axis. """ valAx_lst = self._chartSpace.valAx_lst if not valAx_lst: raise ValueError('chart ha...
python
{ "resource": "" }
q20325
CT_TextBodyProperties.autofit
train
def autofit(self): """ The autofit setting for the text frame, a member of the ``MSO_AUTO_SIZE`` enumeration. """ if self.noAutofit is not None: return MSO_AUTO_SIZE.NONE if self.normAutofit is not None: return MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE ...
python
{ "resource": "" }
q20326
Categories.depth
train
def depth(self): """ The number of hierarchy levels in this category graph. Returns 0 if it contains no categories. """ categories = self._categories if not categories: return 0 first_depth = categories[0].depth for category in categories[1:]: ...
python
{ "resource": "" }
q20327
Category.depth
train
def depth(self): """ The number of hierarchy levels rooted at this category node. Returns 1 if this category has no sub-categories. """ sub_categories = self._sub_categories if not sub_categories: return 1 first_depth = sub_categories[0].depth ...
python
{ "resource": "" }
q20328
Category.leaf_count
train
def leaf_count(self): """ The number of leaf category nodes under this category. Returns 1 if this category has no sub-categories. """ if not self._sub_categories: return 1 return sum(category.leaf_count for category in self._sub_categories)
python
{ "resource": "" }
q20329
CT_SlideIdList._next_id
train
def _next_id(self): """ Return the next available slide ID as an int. Valid slide IDs start at 256. The next integer value greater than the max value in use is chosen, which minimizes that chance of reusing the id of a deleted slide. """ id_str_lst = self.xpath('....
python
{ "resource": "" }
q20330
_default_pptx_path
train
def _default_pptx_path(): """ Return the path to the built-in default .pptx package. """ _thisdir = os.path.split(__file__)[0] return os.path.join(_thisdir, 'templates', 'default.pptx')
python
{ "resource": "" }
q20331
API.__get_url
train
def __get_url(self, endpoint): """ Get URL for requests """ url = self.url api = "wc-api" if url.endswith("/") is False: url = "%s/" % url if self.wp_api: api = "wp-json" return "%s%s/%s/%s" % (url, api, self.version, endpoint)
python
{ "resource": "" }
q20332
API.__get_oauth_url
train
def __get_oauth_url(self, url, method, **kwargs): """ Generate oAuth1.0a URL """ oauth = OAuth( url=url, consumer_key=self.consumer_key, consumer_secret=self.consumer_secret, version=self.version, method=method, oauth_timestamp=kwar...
python
{ "resource": "" }
q20333
OAuth.get_oauth_url
train
def get_oauth_url(self): """ Returns the URL with OAuth params """ params = OrderedDict() if "?" in self.url: url = self.url[:self.url.find("?")] for key, value in parse_qsl(urlparse(self.url).query): params[key] = value else: url = se...
python
{ "resource": "" }
q20334
OAuth.generate_oauth_signature
train
def generate_oauth_signature(self, params, url): """ Generate OAuth Signature """ if "oauth_signature" in params.keys(): del params["oauth_signature"] base_request_uri = quote(url, "") params = self.sorted_params(params) params = self.normalize_parameters(params) ...
python
{ "resource": "" }
q20335
OAuth.generate_nonce
train
def generate_nonce(): """ Generate nonce number """ nonce = ''.join([str(randint(0, 9)) for i in range(8)]) return HMAC( nonce.encode(), "secret".encode(), sha1 ).hexdigest()
python
{ "resource": "" }
q20336
print_ldamodel_distribution
train
def print_ldamodel_distribution(distrib, row_labels, val_labels, top_n=10): """ Print `n_top` top values from a LDA model's distribution `distrib`. Can be used for topic-word distributions and document-topic distributions. """ df_values = top_n_from_distribution(distrib, top_n=top_n, row_labels=row...
python
{ "resource": "" }
q20337
print_ldamodel_topic_words
train
def print_ldamodel_topic_words(topic_word_distrib, vocab, n_top=10, row_labels=DEFAULT_TOPIC_NAME_FMT): """Print `n_top` values from a LDA model's topic-word distributions.""" print_ldamodel_distribution(topic_word_distrib, row_labels=row_labels, val_labels=vocab, top_n=n_top)
python
{ "resource": "" }
q20338
print_ldamodel_doc_topics
train
def print_ldamodel_doc_topics(doc_topic_distrib, doc_labels, n_top=3, val_labels=DEFAULT_TOPIC_NAME_FMT): """Print `n_top` values from a LDA model's document-topic distributions.""" print_ldamodel_distribution(doc_topic_distrib, row_labels=doc_labels, val_labels=val_labels, top_n...
python
{ "resource": "" }
q20339
save_ldamodel_to_pickle
train
def save_ldamodel_to_pickle(picklefile, model, vocab, doc_labels, dtm=None, **kwargs): """Save a LDA model as pickle file.""" pickle_data({'model': model, 'vocab': vocab, 'doc_labels': doc_labels, 'dtm': dtm}, picklefile)
python
{ "resource": "" }
q20340
plot_heatmap
train
def plot_heatmap(fig, ax, data, xaxislabel=None, yaxislabel=None, xticklabels=None, yticklabels=None, title=None, grid=True, values_in_cells=True, round_values_in_cells=2, legend=False, fontsize_axislabel=None, ...
python
{ "resource": "" }
q20341
get_term_proportions
train
def get_term_proportions(dtm): """ Return the term proportions given the document-term matrix `dtm` """ unnorm = get_term_frequencies(dtm) if unnorm.sum() == 0: raise ValueError('`dtm` does not contain any tokens (is all-zero)') else: return unnorm / unnorm.sum()
python
{ "resource": "" }
q20342
TMPreproc._setup_workers
train
def _setup_workers(self, initial_states=None): """ Create worker processes and queues. Distribute the work evenly across worker processes. Optionally send initial states defined in list `initial_states` to each worker process. """ if initial_states is not None: requir...
python
{ "resource": "" }
q20343
_words_by_score
train
def _words_by_score(words, score, least_to_most, n=None): """ Order a vector of `words` by a `score`, either `least_to_most` or reverse. Optionally return only the top `n` results. """ if words.shape != score.shape: raise ValueError('`words` and `score` must have the same shape') if n i...
python
{ "resource": "" }
q20344
_words_by_salience_score
train
def _words_by_salience_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None, least_to_most=False): """Return words in `vocab` ordered by saliency score.""" saliency = get_word_saliency(topic_word_distrib, doc_topic_distrib, doc_lengths) return _words_by_score(vocab, saliency, least_to_mos...
python
{ "resource": "" }
q20345
_words_by_distinctiveness_score
train
def _words_by_distinctiveness_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None, least_to_most=False): """Return words in `vocab` ordered by distinctiveness score.""" p_t = get_marginal_topic_distrib(doc_topic_distrib, doc_lengths) distinct = get_wor...
python
{ "resource": "" }
q20346
pickle_data
train
def pickle_data(data, picklefile): """Helper function to pickle `data` in `picklefile`.""" with open(picklefile, 'wb') as f: pickle.dump(data, f, protocol=2)
python
{ "resource": "" }
q20347
unpickle_file
train
def unpickle_file(picklefile, **kwargs): """Helper function to unpickle data from `picklefile`.""" with open(picklefile, 'rb') as f: return pickle.load(f, **kwargs)
python
{ "resource": "" }
q20348
dyndoc_insert
train
def dyndoc_insert(src): """docstring_insert - a decorator to insert API-docparts dynamically.""" # manipulating docstrings this way is tricky due to indentation # the JSON needs leading whitespace to be interpreted correctly import json import re def mkblock(d, flag=0): # response, pret...
python
{ "resource": "" }
q20349
endpoint
train
def endpoint(url, method="GET", expected_status=200): """endpoint - decorator to manipulate the REST-service endpoint. The endpoint decorator sets the endpoint and the method for the class to access the REST-service. """ def dec(obj): obj.ENDPOINT = url obj.METHOD = method o...
python
{ "resource": "" }
q20350
abstractclass
train
def abstractclass(cls): """abstractclass - class decorator. make sure the class is abstract and cannot be used on it's own. @abstractclass class A(object): def __init__(self, *args, **kwargs): # logic pass class B(A): pass a = A() # results in an Ass...
python
{ "resource": "" }
q20351
granularity_to_time
train
def granularity_to_time(s): """convert a named granularity into seconds. get value in seconds for named granularities: M1, M5 ... H1 etc. >>> print(granularity_to_time("M5")) 300 """ mfact = { 'S': 1, 'M': 60, 'H': 3600, 'D': 86400, 'W': 604800, } ...
python
{ "resource": "" }
q20352
get_classes
train
def get_classes(modName): """return a list of all classes in a module.""" classNames = [] for name, obj in inspect.getmembers(sys.modules[modName]): if inspect.isclass(obj): classNames.append(name) return classNames
python
{ "resource": "" }
q20353
InstrumentsCandlesFactory
train
def InstrumentsCandlesFactory(instrument, params=None): """InstrumentsCandlesFactory - generate InstrumentCandles requests. InstrumentsCandlesFactory is used to retrieve historical data by automatically generating consecutive requests when the OANDA limit of *count* records is exceeded. This is kn...
python
{ "resource": "" }
q20354
API.request
train
def request(self, endpoint): """Perform a request for the APIRequest instance 'endpoint'. Parameters ---------- endpoint : APIRequest The endpoint parameter contains an instance of an APIRequest containing the endpoint, method and optionally other parameters ...
python
{ "resource": "" }
q20355
make_definition_classes
train
def make_definition_classes(mod): """Dynamically create the definition classes from module 'mod'.""" rootpath = "oandapyV20" PTH = "{}.definitions.{}".format(rootpath, mod) M = import_module(PTH) __ALL__ = [] # construct the __all__ variable for cls, cldef in M.definitions.items(): or...
python
{ "resource": "" }
q20356
_fix_integrity_error
train
def _fix_integrity_error(f): """Ensure raising of IntegrityError on unique constraint violations. In earlier versions of hdbcli it doesn't raise the hdbcli.dbapi.IntegrityError exception for unique constraint violations. To support also older versions of hdbcli this decorator inspects the raised except...
python
{ "resource": "" }
q20357
pp_xml
train
def pp_xml(body): """Pretty print format some XML so it's readable.""" pretty = xml.dom.minidom.parseString(body) return pretty.toprettyxml(indent=" ")
python
{ "resource": "" }
q20358
Client.power_on
train
def power_on(self): """Power on the box.""" payload = amt.wsman.power_state_request(self.uri, "on") return self.post(payload, CIM_PowerManagementService)
python
{ "resource": "" }
q20359
Client.set_next_boot
train
def set_next_boot(self, boot_device): """Sets the machine to boot to boot_device on its next reboot Will default back to normal boot list on the reboot that follows. """ payload = amt.wsman.change_boot_order_request(self.uri, boot_device) self.post(payload) payload = am...
python
{ "resource": "" }
q20360
dumps
train
def dumps(obj, **kwargs): """Serialize ``obj`` to a JSON5-formatted ``str``.""" t = type(obj) if obj is True: return u'true' elif obj is False: return u'false' elif obj == None: return u'null' elif t == type('') or t == type(u''): single = "'" in obj doub...
python
{ "resource": "" }
q20361
Connection.destroy
train
def destroy(self): """Close the connection, and close any associated CBS authentication session. """ try: self.lock() _logger.debug("Unlocked connection %r to close.", self.container_id) self._close() finally: self.release() ...
python
{ "resource": "" }
q20362
Connection.work
train
def work(self): """Perform a single Connection iteration.""" try: raise self._error except TypeError: pass except Exception as e: _logger.warning("%r", e) raise try: self.lock() self._conn.do_work() e...
python
{ "resource": "" }
q20363
MessageSender._detach_received
train
def _detach_received(self, error): """Callback called when a link DETACH frame is received. This callback will process the received DETACH error to determine if the link is recoverable or whether it should be shutdown. :param error: The error information from the detach frame. ...
python
{ "resource": "" }
q20364
MessageSender.get_state
train
def get_state(self): """Get the state of the MessageSender and its underlying Link. :rtype: ~uamqp.constants.MessageSenderState """ try: raise self._error except TypeError: pass except Exception as e: _logger.warning("%r", e) ...
python
{ "resource": "" }
q20365
AMQPClientAsync.open_async
train
async def open_async(self, connection=None): """Asynchronously open the client. The client can create a new Connection or an existing Connection can be passed in. This existing Connection may have an existing CBS authentication Session, which will be used for this client as well. Otherwi...
python
{ "resource": "" }
q20366
AMQPClientAsync.close_async
train
async def close_async(self): """Close the client asynchronously. This includes closing the Session and CBS authentication layer as well as the Connection. If the client was opened using an external Connection, this will be left intact. """ if self.message_handler: ...
python
{ "resource": "" }
q20367
AMQPClientAsync.do_work_async
train
async def do_work_async(self): """Run a single connection iteration asynchronously. This will return `True` if the connection is still open and ready to be used for further work, or `False` if it needs to be shut down. :rtype: bool :raises: TimeoutError or ~uamqp.errors....
python
{ "resource": "" }
q20368
SendClientAsync.send_message_async
train
async def send_message_async(self, messages, close_on_done=False): """Send a single message or batched message asynchronously. :param messages: A message to send. This can either be a single instance of ~uamqp.message.Message, or multiple messages wrapped in an instance of ~uamqp.mess...
python
{ "resource": "" }
q20369
SendClientAsync.send_all_messages_async
train
async def send_all_messages_async(self, close_on_done=True): """Send all pending messages in the queue asynchronously. This will return a list of the send result of all the pending messages so it can be determined if any messages failed to send. This function will open the client if it i...
python
{ "resource": "" }
q20370
ReceiveClientAsync._client_ready_async
train
async def _client_ready_async(self): """Determine whether the client is ready to start receiving messages. To be ready, the connection must be open and authentication complete, The Session, Link and MessageReceiver must be open and in non-errored states. :rtype: bool :ra...
python
{ "resource": "" }
q20371
ReceiveClientAsync.receive_message_batch_async
train
async def receive_message_batch_async(self, max_batch_size=None, on_message_received=None, timeout=0): """Receive a batch of messages asynchronously. This method will return as soon as some messages are available rather than waiting to achieve a specific batch size, and therefore the number of m...
python
{ "resource": "" }
q20372
ReceiveClientAsync.receive_messages_iter_async
train
def receive_messages_iter_async(self, on_message_received=None): """Receive messages by asynchronous generator. Messages returned in the generator have already been accepted - if you wish to add logic to accept or reject messages based on custom criteria, pass in a callback. If the rece...
python
{ "resource": "" }
q20373
create_sas_token
train
def create_sas_token(key_name, shared_access_key, scope, expiry=timedelta(hours=1)): """Create a SAS token. :param key_name: The username/key name/policy name for the token. :type key_name: bytes :param shared_access_key: The shared access key to generate the token from. :type shared_access_key: by...
python
{ "resource": "" }
q20374
_convert_py_number
train
def _convert_py_number(value): """Convert a Python integer value into equivalent C object. Will attempt to use the smallest possible conversion, starting with int, then long then double. """ try: return c_uamqp.int_value(value) except OverflowError: pass try: return c...
python
{ "resource": "" }
q20375
ConnectionAsync.work_async
train
async def work_async(self): """Perform a single Connection iteration asynchronously.""" try: raise self._error except TypeError: pass except Exception as e: _logger.warning("%r", e) raise try: await self.lock_async() ...
python
{ "resource": "" }
q20376
ConnectionAsync.destroy_async
train
async def destroy_async(self): """Close the connection asynchronously, and close any associated CBS authentication session. """ try: await self.lock_async() _logger.debug("Unlocked connection %r to close.", self.container_id) await self._close_async() ...
python
{ "resource": "" }
q20377
AMQPAuth.set_tlsio
train
def set_tlsio(self, hostname, port, http_proxy): """Setup the default underlying TLS IO layer. On Windows this is Schannel, on Linux and MacOS this is OpenSSL. :param hostname: The endpoint hostname. :type hostname: bytes :param port: The TLS port. :type port: int ...
python
{ "resource": "" }
q20378
AMQPAuth.close
train
def close(self): """Close the authentication layer and cleanup all the authentication wrapper objects. """ self.sasl.mechanism.destroy() self.sasl_client.get_client().destroy() self._underlying_xio.destroy()
python
{ "resource": "" }
q20379
Message.decode_from_bytes
train
def decode_from_bytes(cls, data): """Decode an AMQP message from a bytearray. The returned message will not have a delivery context and therefore will be considered to be in an "already settled" state. :param data: The AMQP wire-encoded bytes to decode. :type data: bytes or byte...
python
{ "resource": "" }
q20380
Message._parse_message
train
def _parse_message(self, message): """Parse a message received from an AMQP service. :param message: The received C message. :type message: uamqp.c_uamqp.cMessage """ _logger.debug("Parsing received message %r.", self.delivery_no) self._message = message body_typ...
python
{ "resource": "" }
q20381
Message.get_message_encoded_size
train
def get_message_encoded_size(self): """Pre-emptively get the size of the message once it has been encoded to go over the wire so we can raise an error if the message will be rejected for being to large. This method is not available for messages that have been received. :rtype: ...
python
{ "resource": "" }
q20382
Message.encode_message
train
def encode_message(self): """Encode message to AMQP wire-encoded bytearray. :rtype: bytearray """ if not self._message: raise ValueError("No message data to encode.") cloned_data = self._message.clone() self._populate_message_attributes(cloned_data) e...
python
{ "resource": "" }
q20383
Message.gather
train
def gather(self): """Return all the messages represented by this object. This will always be a list of a single message. :rtype: list[~uamqp.message.Message] """ if self.state in constants.RECEIVE_STATES: raise TypeError("Only new messages can be gathered.") ...
python
{ "resource": "" }
q20384
Message.get_message
train
def get_message(self): """Get the underlying C message from this object. :rtype: uamqp.c_uamqp.cMessage """ if not self._message: return None self._populate_message_attributes(self._message) return self._message
python
{ "resource": "" }
q20385
Message.accept
train
def accept(self): """Send a response disposition to the service to indicate that a received message has been accepted. If the client is running in PeekLock mode, the service will wait on this disposition. Otherwise it will be ignored. Returns `True` is message was accepted, or `False` if...
python
{ "resource": "" }
q20386
Message.reject
train
def reject(self, condition=None, description=None): """Send a response disposition to the service to indicate that a received message has been rejected. If the client is running in PeekLock mode, the service will wait on this disposition. Otherwise it will be ignored. A rejected message ...
python
{ "resource": "" }
q20387
Message.release
train
def release(self): """Send a response disposition to the service to indicate that a received message has been released. If the client is running in PeekLock mode, the service will wait on this disposition. Otherwise it will be ignored. A released message will not incremenet the messages ...
python
{ "resource": "" }
q20388
Message.modify
train
def modify(self, failed, deliverable, annotations=None): """Send a response disposition to the service to indicate that a received message has been modified. If the client is running in PeekLock mode, the service will wait on this disposition. Otherwise it will be ignored. Returns `True`...
python
{ "resource": "" }
q20389
BatchMessage._create_batch_message
train
def _create_batch_message(self): """Create a ~uamqp.message.Message for a value supplied by the data generator. Applies all properties and annotations to the message. :rtype: ~uamqp.message.Message """ return Message(body=[], properties=self.properties, ...
python
{ "resource": "" }
q20390
BatchMessage._multi_message_generator
train
def _multi_message_generator(self): """Generate multiple ~uamqp.message.Message objects from a single data stream that in total may exceed the maximum individual message size. Data will be continuously added to a single message until that message reaches a max allowable size, at which po...
python
{ "resource": "" }
q20391
BatchMessage.gather
train
def gather(self): """Return all the messages represented by this object. This will convert the batch data into individual Message objects, which may be one or more if multi_messages is set to `True`. :rtype: list[~uamqp.message.Message] """ if self._multi_messages: ...
python
{ "resource": "" }
q20392
DataBody.append
train
def append(self, data): """Append a section to the body. :param data: The data to append. :type data: str or bytes """ if isinstance(data, six.text_type): self._message.add_body_data(data.encode(self._encoding)) elif isinstance(data, six.binary_type): ...
python
{ "resource": "" }
q20393
ValueBody.set
train
def set(self, value): """Set a value as the message body. This can be any Python data type and it will be automatically encoded into an AMQP type. If a specific AMQP type is required, a `types.AMQPType` can be used. :param data: The data to send in the body. :type data: ...
python
{ "resource": "" }
q20394
CBSAuthMixin.create_authenticator
train
def create_authenticator(self, connection, debug=False, **kwargs): """Create the AMQP session and the CBS channel with which to negotiate the token. :param connection: The underlying AMQP connection on which to create the session. :type connection: ~uamqp.connection.Connection ...
python
{ "resource": "" }
q20395
CBSAuthMixin.close_authenticator
train
def close_authenticator(self): """Close the CBS auth channel and session.""" _logger.info("Shutting down CBS session on connection: %r.", self._connection.container_id) try: _logger.debug("Unlocked CBS to close on connection: %r.", self._connection.container_id) self._cbs...
python
{ "resource": "" }
q20396
SASTokenAuth.update_token
train
def update_token(self): """If a username and password are present - attempt to use them to request a fresh SAS token. """ if not self.username or not self.password: raise errors.TokenExpired("Unable to refresh token - no username or password.") encoded_uri = compat.qu...
python
{ "resource": "" }
q20397
SASTokenAuth.from_shared_access_key
train
def from_shared_access_key( cls, uri, key_name, shared_access_key, expiry=None, port=constants.DEFAULT_AMQPS_PORT, timeout=10, retry_policy=TokenRetryPolicy(), verify=None, http_proxy=None, ...
python
{ "resource": "" }
q20398
MessageReceiver._state_changed
train
def _state_changed(self, previous_state, new_state): """Callback called whenever the underlying Receiver undergoes a change of state. This function wraps the states as Enums to prepare for calling the public callback. :param previous_state: The previous Receiver state. :type pre...
python
{ "resource": "" }
q20399
MessageReceiver._settle_message
train
def _settle_message(self, message_number, response): """Send a settle dispostition for a received message. :param message_number: The delivery number of the message to settle. :type message_number: int :response: The type of disposition to respond with, e.g. whether th...
python
{ "resource": "" }