docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Make all tests that should be run for the given object in the specified testcase Args: sdkobject: the sdk object testcase: the test case Returns: It returns a dictionary of all tests to run
def make_tests(self, sdkobject, testcase): tests = dict() attributes = sdkobject.get_attributes() for attribute in attributes: if attribute.local_name in self.IGNORED_ATTRIBUTES: continue for function_name, conditions in self._attributes_regist...
597,883
Create a test method for the sdkoject Args: testcase: the testcase to that should manage the method function_name: the name of the method in the testcase sdkobject: the object that should be tested attribute: the attribute information if neces...
def _create_test(self, testcase, function_name, sdkobject, attribute=None): func = getattr(testcase, function_name) object_name = sdkobject.rest_name # Name that will be displayed test_name = "" rep = dict() rep["object"] = object_name if attribute: ...
597,884
Write a file at the specific destination with the content. Args: destination (string): the destination location filename (string): the filename that will be written content (string): the content of the filename
def write(self, destination, filename, content): if not os.path.exists(destination): try: os.makedirs(destination) except: # The directory can be created while creating it. pass filepath = "%s/%s" % (destination, filename) f = o...
597,942
Write a file according to the template name Args: destination (string): the destination location filename (string): the filename that will be written template_name (string): the name of the template kwargs (dict): all attribute that will be pa...
def write(self, destination, filename, template_name, **kwargs): template = self.env.get_template(template_name) content = template.render(kwargs) super(TemplateFileWriter, self).write(destination=destination, filename=filename, content=content)
597,944
Write SDK session file Args: version (str): the version of the server
def _write_session(self): base_name = "%ssession" % self._product_accronym.lower() filename = "%s%s.py" % (self._class_prefix.lower(), base_name) override_content = self._extract_override_content(base_name) self.write(destination=self.output_directory, filename=filename, templa...
597,951
Write init file Args: filenames (dict): dict of filename and classes
def _write_init_models(self, filenames): self.write(destination=self.output_directory, filename="__init__.py", template_name="__init_model__.py.tpl", filenames=self._prepare_filenames(filenames), class_prefix=self._class_prefix, product_accronym...
597,952
Write fetcher init file Args: filenames (dict): dict of filename and classes
def _write_init_fetchers(self, filenames): destination = "%s%s" % (self.output_directory, self.fetchers_path) self.write(destination=destination, filename="__init__.py", template_name="__init_fetcher__.py.tpl", filenames=self._prepare_filenames(filenames, suffix='Fetcher'), ...
597,955
Initializes Courgette Args: url (string): the url of the server with its port username (string): the username to launch tests password (string): the password to connect to the server enterprise (string): the name of the enterprise to connect t...
def __init__(self, url, username, password, enterprise, apiversion, sdk_identifier, monolithe_config): self.url = url self.username = username self.password = password self.enterprise = enterprise self.apiversion = apiversion self.monolithe_config = monolithe_con...
597,959
Loads a new source (as a file) from ``source`` (a file path or URL) by killing the current ``omxplayer`` process and forking a new one. Args: source (string): Path to the file to play or URL
def load(self, source, pause=False): self._source = source self._load_source(source) if pause: time.sleep(0.5) # Wait for the DBus interface to be initialised self.pause()
597,983
Seek the video by `relative_position` seconds Args: relative_position (float): The position in seconds to seek to.
def seek(self, relative_position): self._player_interface.Seek(Int64(1000.0 * 1000 * relative_position)) self.seekEvent(self, relative_position)
597,988
Set the video to playback position to `position` seconds from the start of the video Args: position (float): The position in seconds.
def set_position(self, position): self._player_interface.SetPosition(ObjectPath("/not/used"), Int64(position * 1000.0 * 1000)) self.positionEvent(self, position)
597,989
Set the video position on the screen Args: x1 (int): Top left x coordinate (px) y1 (int): Top left y coordinate (px) x2 (int): Bottom right x coordinate (px) y2 (int): Bottom right y coordinate (px)
def set_video_pos(self, x1, y1, x2, y2): position = "%s %s %s %s" % (str(x1),str(y1),str(x2),str(y2)) self._player_interface.VideoPos(ObjectPath('/not/used'), String(position))
597,990
Define target for common output. Args: logger (bool | None | logging.Logger): Pass None to use `print()` to stdout instead of logging. Pass True to create a simple standard logger.
def set_pyftpsync_logger(logger=True): global _logger prev_logger = _logger if logger is True: logging.basicConfig(level=logging.INFO) _logger = logging.getLogger("pyftpsync") _logger.setLevel(logging.DEBUG) else: _logger = logger return prev_logger
598,970
Prompt for username and password. If a user name is passed, only prompt for a password. Args: url (str): hostname user (str, optional): Pass a valid name to skip prompting for a user name default_user (str, optional): Pass a valid name that is used as default whe...
def prompt_for_password(url, user=None, default_user=None): if user is None: default_user = default_user or getpass.getuser() while user is None: user = compat.console_input( "Enter username for {} [{}]: ".format(url, default_user) ) if user.s...
598,977
Factory that creates `_Target` objects from URLs. FTP targets must begin with the scheme ``ftp://`` or ``ftps://`` for TLS. Note: TLS is only supported on Python 2.7/3.2+. Args: url (str): extra_opts (dict, optional): Passed to Target constructor. Default: None. Returns: ...
def make_target(url, extra_opts=None): # debug = extra_opts.get("debug", 1) parts = compat.urlparse(url, allow_fragments=False) # scheme is case-insensitive according to https://tools.ietf.org/html/rfc3986 scheme = parts.scheme.lower() if scheme in ["ftp", "ftps"]: creds = parts.usernam...
598,985
Iterate over all target entries recursively. Args: pred (function, optional): Callback(:class:`ftpsync.resources._Resource`) should return `False` to ignore entry. Default: `None`. recursive (bool, optional): Pass `False` to generate top l...
def walk(self, pred=None, recursive=True): for entry in self.get_dir(): if pred and pred(entry) is False: continue yield entry if recursive: if isinstance(entry, DirectoryEntry): self.cwd(entry.name) ...
598,994
Open cur_dir/name for reading. Note: we read everything into a buffer that supports .read(). Args: name (str): file name, located in self.curdir Returns: file-like (must support read() method)
def open_readable(self, name): # print("FTP open_readable({})".format(name)) assert compat.is_native(name) out = SpooledTemporaryFile(max_size=self.MAX_SPOOL_MEM, mode="w+b") self.ftp.retrbinary( "RETR {}".format(name), out.write, FtpTarget.DEFAULT_BLOCKSIZE ...
599,022
Write file-like `fp_src` to cur_dir/name. Args: name (str): file name, located in self.curdir fp_src (file-like): must support read() method blocksize (int, optional): callback (function, optional): Called like `func(buf)` for every written...
def write_file(self, name, fp_src, blocksize=DEFAULT_BLOCKSIZE, callback=None): # print("FTP write_file({})".format(name), blocksize) assert compat.is_native(name) self.check_write(name) self.ftp.storbinary("STOR {}".format(name), fp_src, blocksize, callback)
599,023
Write cur_dir/name to file-like `fp_dest`. Args: name (str): file name, located in self.curdir fp_dest (file-like): must support write() method callback (function, optional): Called like `func(buf)` for every written chunk
def copy_to_file(self, name, fp_dest, callback=None): assert compat.is_native(name) def _write_to_file(data): # print("_write_to_file() {} bytes.".format(len(data))) fp_dest.write(data) if callback: callback(data) self.ftp....
599,024
Set the form fields for every key in the form_field_dict. Params: form_field_dict -- a dictionary created by get_form_field_dict parent_key -- the key for the previous key in the recursive call field_type -- used to determine what kind of field we are setting
def set_form_fields(self, form_field_dict, parent_key=None, field_type=None): for form_key, field_value in form_field_dict.items(): form_key = make_key(parent_key, form_key) if parent_key is not None else form_key if isinstance(field_value, tuple): set_list_clas...
599,060
Confirm that the geometry type is of type Polygon or MultiPolygon. Args: geometry (BaseGeometry): BaseGeometry instance (e.g. Polygon) Returns: bool
def is_valid_geometry(geometry): if isinstance(geometry, Polygon) or isinstance(geometry, MultiPolygon): return True else: return False
600,182
Get the OGR driver from the provided file extension. Args: file_extension (str): file extension Returns: osgeo.ogr.Driver Raises: ValueError: no driver is found
def get_ogr_driver(filepath): filename, file_extension = os.path.splitext(filepath) EXTENSION = file_extension[1:] ogr_driver_count = ogr.GetDriverCount() for idx in range(ogr_driver_count): driver = ogr.GetDriver(idx) driver_extension = driver.GetMetadataItem(str('DMD_EXTENSION'))...
600,183
Login with a username and password Arguments: user - username or email address password - the password for the account Keyword Arguments: token - meteor resume token callback - callback function containing error as first argument and login data
def login(self, user, password, token=None, callback=None): # TODO: keep the tokenExpires around so we know the next time # we need to authenticate # hash the password hashed = hashlib.sha256(password).hexdigest() # handle username or email address if '@' ...
600,222
Call a remote method Arguments: method - remote method name params - remote method parameters Keyword Arguments: callback - callback function containing return data
def call(self, method, params, callback=None): self._wait_for_connect() self.ddp_client.call(method, params, callback=callback)
600,226
Subscribe to a collection Arguments: name - the name of the publication params - the subscription parameters Keyword Arguments: callback - a function callback that returns an error (if exists)
def subscribe(self, name, params=[], callback=None): self._wait_for_connect() def subscribed(error, sub_id): if error: self._remove_sub_by_id(sub_id) if callback: callback(error.get('reason')) return if...
600,227
Unsubscribe from a collection Arguments: name - the name of the publication
def unsubscribe(self, name): self._wait_for_connect() if name not in self.subscriptions: raise MeteorClientException('No subscription for {}'.format(name)) self.ddp_client.unsubscribe(self.subscriptions[name]['id']) del self.subscriptions[name] self.emit('uns...
600,228
Find data in a collection Arguments: collection - collection to search Keyword Arguments: selector - the query (default returns all items in a collection)
def find(self, collection, selector={}): results = [] for _id, doc in self.collection_data.data.get(collection, {}).items(): doc.update({'_id': _id}) if selector == {}: results.append(doc) for key, value in selector.items(): if...
600,229
Return one item from a collection Arguments: collection - collection to search Keyword Arguments: selector - the query (default returns first item found)
def find_one(self, collection, selector={}): for _id, doc in self.collection_data.data.get(collection, {}).items(): doc.update({'_id': _id}) if selector == {}: return doc for key, value in selector.items(): if key in doc and doc[key] =...
600,230
Insert an item into a collection Arguments: collection - the collection to be modified doc - The document to insert. May not yet have an _id attribute, in which case Meteor will generate one for you. Keyword Arguments: callback - Optional. If present, called with an err...
def insert(self, collection, doc, callback=None): self.call("/" + collection + "/insert", [doc], callback=callback)
600,231
Insert an item into a collection Arguments: collection - the collection to be modified selector - specifies which documents to modify modifier - Specifies how to modify the documents Keyword Arguments: callback - Optional. If present, called with an error object as the ...
def update(self, collection, selector, modifier, callback=None): self.call("/" + collection + "/update", [selector, modifier], callback=callback)
600,232
Remove an item from a collection Arguments: collection - the collection to be modified selector - Specifies which documents to remove Keyword Arguments: callback - Optional. If present, called with an error object as its argument.
def remove(self, collection, selector, callback=None): self.call("/" + collection + "/remove", [selector], callback=callback)
600,233
Constructor Args: url: API url endpoint username: API username or real username password: API token or user password auth_header: API HTTP header
def __init__(self, url, username, password, auth_header=DEFAULT_AUTH_HEADER, cafile=None): self._url = url self._username = username self._password = password self._auth_header = auth_header self._cafile = cafile
600,442
Call remote API procedure Args: method: Procedure name kwargs: Procedure named arguments Returns: Procedure result Raises: urllib2.HTTPError: Any HTTP error (Python 2) urllib.error.HTTPError: Any HTTP error (Python 3)
def execute(self, method, **kwargs): payload = { 'id': 1, 'jsonrpc': '2.0', 'method': method, 'params': kwargs } credentials = base64.b64encode('{}:{}'.format(self._username, self._password).encode()) auth_header_prefix = 'Basic '...
600,447
Get active position for given position name. params: category - Category model to look for name - name of the position nofallback - if True than do not fall back to parent category if active position is not found for category
def get_active_position(self, category, name, nofallback=False): now = timezone.now() lookup = (Q(active_from__isnull=True) | Q(active_from__lte=now)) & \ (Q(active_till__isnull=True) | Q(active_till__gt=now)) while True: try: return self.ge...
600,937
Return a cached object. If the object does not exist in the cache, create it. Params: model - ContentType instance representing the model's class or the model class itself timeout - TTL for the item in cache, defaults to CACHE_TIMEOUT **kwargs - lookup parameters for content_type.get_object...
def get_cached_object(model, timeout=CACHE_TIMEOUT, **kwargs): if not isinstance(model, ContentType): model_ct = ContentType.objects.get_for_model(model) else: model_ct = model key = _get_key(KEY_PREFIX, model_ct, **kwargs) obj = cache.get(key) if obj is None: # if we ...
600,993
Return a list of objects with given PKs using cache. Params: pks - list of Primary Key values to look up or list of content_type_id, pk tuples model - ContentType instance representing the model's class or the model class itself timeout - TTL for the items in cache, defaults to CACHE_TIMEOU...
def get_cached_objects(pks, model=None, timeout=CACHE_TIMEOUT, missing=RAISE): if model is not None: if not isinstance(model, ContentType): model = ContentType.objects.get_for_model(model) pks = [(model, pk) for pk in pks] else: pks = [(ContentType.objects.get_for_id(ct_...
600,994
Construct an instance of TaskTracker Args: task_queue (multiprocessing.JoinableQueue): A queue of the input data. verbose (bool, optional): Set to False to disable verbose output.
def __init__(self, task_queue, verbose=True): multiprocessing.Process.__init__(self) self._task_queue = task_queue self.total_task = self._task_queue.qsize() self.current_state = None self.verbose = verbose
602,169
Initialize CrontabReader Args: cronfile: Path to cronfile Returns: None
def __init__(self, cronfile): options = Options() options.day_of_week_start_index_zero = False options.use_24hour_time_format = True with open(cronfile) as f: for line in f.readlines(): parsed_line = self.parse_cron_line(line) if parse...
602,557
Parses crontab line and returns only starting time string Args: line: crontab line Returns: Time part of cron line
def parse_cron_line(self, line): stripped = line.strip() if stripped and stripped.startswith('#') is False: rexres = self.rex.search(stripped) if rexres: return ' '.join(rexres.group(1).split()) return None
602,558
Initializes a new instance of the ExpressionParser class Args: expression: The cron expression string options: Parsing options
def __init__(self, expression, options): self._expression = expression self._options = options
602,572
Converts cron expression components into consistent, predictable formats. Args: expression_parts: A 7 part string array, one part for each component of the cron expression Returns: None
def normalize_expression(self, expression_parts): # convert ? to * only for DOM and DOW expression_parts[3] = expression_parts[3].replace("?", "*") expression_parts[5] = expression_parts[5].replace("?", "*") # convert 0/, 1/ to */ if expression_parts[0].startswith("0/")...
602,574
Generates a human readable string for the Cron Expression Args: expression: The cron expression string options: Options to control the output description Returns: The cron expression description
def get_description(expression, options=None): descripter = ExpressionDescriptor(expression, options) return descripter.get_description(DescriptionTypeEnum.FULL)
602,647
Initializes a new instance of the ExpressionDescriptorclass Args: expression: The cron expression string options: Options to control the output description Raises: WrongArgumentException: if kwarg is unknow
def __init__(self, expression, options=None, **kwargs): if options is None: options = Options() self._expression = expression self._options = options self._expression_parts = [] self._parsed = False # if kwargs in _options, overwrite it, if not raise...
602,648
Generates a human readable string for the Cron Expression Args: description_type: Which part(s) of the expression to describe Returns: The cron expression description Raises: Exception: if throw_exception_on_parse_error is True
def get_description(self, description_type=DescriptionTypeEnum.FULL): try: if self._parsed is False: parser = ExpressionParser(self._expression, self._options) self._expression_parts = parser.parse() self._parsed = True choices = ...
602,649
Returns segment description Args: expression: Segment to descript all_description: * get_single_item_description: 1 get_interval_description_format: 1/2 get_between_description_format: 1-2 get_description_format: format get_single_item_desc...
def get_segment_description( self, expression, all_description, get_single_item_description, get_interval_description_format, get_between_description_format, get_description_format ): description = None if expression is None or express...
602,659
Given time parts, will contruct a formatted time description Args: hour_expression: Hours part minute_expression: Minutes part second_expression: Seconds part Returns: Formatted time description
def format_time( self, hour_expression, minute_expression, second_expression='' ): hour = int(hour_expression) period = '' if self._options.use_24hour_time_format is False: period = " PM" if (hour >= 12) else " AM" if hour > 1...
602,661
Transforms the verbosity of the expression description by stripping verbosity from original description Args: description: The description to transform use_verbose_format: If True, will leave description as it, if False, will strip verbose parts second_expression: Seconds par...
def transform_verbosity(self, description, use_verbose_format): if use_verbose_format is False: description = description.replace( _(", every minute"), '') description = description.replace(_(", every hour"), '') description = description.replace(_(",...
602,662
Transforms the case of the expression description, based on options Args: description: The description to transform case_type: The casing type that controls the output casing second_expression: Seconds part Returns: The transformed description with proper ...
def transform_case(self, description, case_type): if case_type == CasingTypeEnum.Sentence: description = "{}{}".format( description[0].upper(), description[1:]) elif case_type == CasingTypeEnum.Title: description = description.title() ...
602,663
Returns localized day name by its CRON number Args: day_number: Number of a day Returns: Day corresponding to day_number Raises: IndexError: When day_number is not found
def number_to_day(self, day_number): return [ calendar.day_name[6], calendar.day_name[0], calendar.day_name[1], calendar.day_name[2], calendar.day_name[3], calendar.day_name[4], calendar.day_name[5] ][day_number...
602,664
Pure-python Murmur2 implementation. Based on java client, see org.apache.kafka.common.utils.Utils.murmur2 https://github.com/apache/kafka/blob/0.8.2/clients/src/main/java/org/apache/kafka/common/utils/Utils.java#L244 Args: byte_array: bytearray - Raises TypeError otherwise Returns: MurmurHash2...
def pure_murmur2(byte_array, seed=0x9747b28c): # Ensure byte_array arg is a bytearray if not isinstance(byte_array, bytearray): raise TypeError("Type: %r of 'byte_array' arg must be 'bytearray'", type(byte_array)) length = len(byte_array) # 'm' and 'r' are mixing co...
602,688
Callback invoked when the AMQP connection is ready (when self.ready fires). This API is not meant for users. Args: res: This is an unused argument that provides compatibility with Pika versions lower than 1.0.0.
def connectionReady(self, res=None): self._channel = yield self._allocate_channel() if _pika_version < pkg_resources.parse_version("1.0.0b1"): extra_args = dict(all_channels=True) else: extra_args = dict(global_qos=True) yield self._channel.basic_qos( ...
603,531
Cancel the consumer for a queue. Args: queue (str): The name of the queue the consumer is subscribed to. Returns: defer.Deferred: A Deferred that fires when the consumer is canceled, or None if the consumer was already canceled. Wrap the call in ...
def cancel(self, queue): try: consumer = self._consumers[queue] yield consumer.channel.basic_cancel(consumer_tag=consumer.tag) except pika.exceptions.AMQPChannelError: # Consumers are tied to channels, so if this channel is dead the # consumer sho...
603,543
Retrieve the message class associated with the schema name. If no match is found, the default schema is returned and a warning is logged. Args: schema_name (six.text_type): The name of the :class:`Message` sub-class; this is typically the Python path. Returns: Message: A sub-c...
def get_class(schema_name): global _registry_loaded if not _registry_loaded: load_message_classes() try: return _schema_name_to_class[schema_name] except KeyError: _log.warning( 'The schema "%s" is not in the schema registry! Either install ' "the pa...
603,547
Construct a Message instance given the routing key, the properties and the body received from the AMQP broker. Args: routing_key (str): The AMQP routing key (will become the message topic) properties (pika.BasicProperties): the AMQP properties body (bytes): The encoded message body ...
def get_message(routing_key, properties, body): if properties.headers is None: _log.error( "Message (body=%r) arrived without headers. " "A publisher is misbehaving!", body, ) properties.headers = {} try: MessageClass = get_class(properties.headers["...
603,550
Serialize messages to a JSON formatted str Args: messages (list): The list of messages to serialize. Each message in the messages is subclass of Messge. Returns: str: Serialized messages. Raises: TypeError: If at least one message is not instance of Message class or su...
def dumps(messages): serialized_messages = [] try: for message in messages: message_dict = message._dump() serialized_messages.append(message_dict) except AttributeError: _log.error("Improper object for messages serialization.") raise TypeError("Message h...
603,551
Deserialize messages from a JSON formatted str Args: serialized_messages (JSON str): Returns: list: Deserialized message objects. Raises: ValidationError: If deserialized message validation failed. KeyError: If serialized_messages aren't properly serialized. ValueE...
def loads(serialized_messages): try: messages_dicts = json.loads(serialized_messages) except ValueError: _log.error("Loading serialized messages failed.") raise messages = [] for message_dict in messages_dicts: try: headers = message_dict["headers"] ...
603,552
Two messages of the same class with the same topic, headers, and body are equal. The "sent-at" header is excluded from the equality check as this is set automatically and is dependent on when the object is created. Args: other (object): The object to check for equality. Re...
def __eq__(self, other): if not isinstance(other, self.__class__): return False headers = self._headers.copy() other_headers = other._headers.copy() try: del headers["sent-at"] except KeyError: pass try: del other_...
603,558
Turns a callback that is potentially a class into a callable object. Args: callback (object): An object that might be a class, method, or function. if the object is a class, this creates an instance of it. Raises: ValueError: If an instance can't be created or it isn't a callable objec...
def _check_callback(callback): # If the callback is a class, create an instance of it first if inspect.isclass(callback): callback_object = callback() if not callable(callback_object): raise ValueError( "Callback must be a class that implements __call__ or a func...
603,578
Register a new consumer. This consumer will be configured for every protocol this factory produces so it will be reconfigured on network failures. If a connection is already active, the consumer will be added to it. Args: callback (callable): The callback to invoke when a m...
def consume(self, callback, queue): self.consumers[queue] = callback if self._client_ready.called: return self.client.consume(callback, queue)
603,589
Create a new factory for protocol objects. Any exchanges, queues, or bindings provided here will be declared and set up each time a new protocol instance is created. In other words, each time a new connection is set up to the broker, it will start with the declaration of these objects. ...
def __init__(self, parameters, confirms=True): self.confirms = confirms self.protocol = FedoraMessagingProtocolV2 self._parameters = parameters # Used to implement the when_connected API self._client_deferred = defer.Deferred() self._client = None self._c...
603,592
Cancel a consumer that was previously started with consume. Args: consumer (list of fedora_messaging.api.Consumer): The consumers to cancel.
def cancel(self, consumers): for consumer in consumers: del self._consumers[consumer.queue] protocol = yield self.when_connected() yield protocol.cancel(consumer)
603,597
Produce a Twisted SSL context object from a pika connection parameter object. This is necessary as Twisted manages the connection, not Pika. Args: parameters (pika.ConnectionParameters): The connection parameters built from the fedora_messaging configuration.
def _ssl_context_factory(parameters): client_cert = None ca_cert = None key = config.conf["tls"]["keyfile"] cert = config.conf["tls"]["certfile"] ca_file = config.conf["tls"]["ca_cert"] if ca_file: with open(ca_file, "rb") as fd: # Open it in binary mode since otherwise ...
603,614
Configure the pika connection parameters for TLS based on the configuration. This modifies the object provided to it. This accounts for whether or not the new API based on the standard library's SSLContext is available for pika. Args: parameters (pika.ConnectionParameters): The connection para...
def _configure_tls_parameters(parameters): cert = config.conf["tls"]["certfile"] key = config.conf["tls"]["keyfile"] if cert and key: _log.info( "Authenticating with server using x509 (certfile: %s, keyfile: %s)", cert, key, ) parameters.crede...
603,620
Called when the server acknowledges a cancel request. Args: cancel_frame (pika.spec.Basic.CancelOk): The cancelok frame from the server.
def _on_cancelok(self, cancel_frame): _log.info("Consumer canceled; returning all unprocessed messages to the queue") self._channel.basic_nack(delivery_tag=0, multiple=True, requeue=True)
603,626
Callback used when a channel is opened. This registers all the channel callbacks. Args: channel (pika.channel.Channel): The channel that successfully opened.
def _on_channel_open(self, channel): channel.add_on_close_callback(self._on_channel_close) channel.add_on_cancel_callback(self._on_cancel) channel.basic_qos(callback=self._on_qosok, **config.conf["qos"])
603,627
Callback invoked when the server acknowledges the QoS settings. Asserts or creates the exchanges and queues exist. Args: qosok_frame (pika.spec.Basic.Qos): The frame send from the server.
def _on_qosok(self, qosok_frame): for name, args in self._exchanges.items(): self._channel.exchange_declare( exchange=name, exchange_type=args["type"], durable=args["durable"], auto_delete=args["auto_delete"], a...
603,628
Callback invoked when the channel is closed. Args: channel (pika.channel.Channel): The channel that got closed. reply_code_or_reason (int|Exception): The reason why the channel was closed. In older versions of pika, this is the AMQP code. reply_text (str): Th...
def _on_channel_close(self, channel, reply_code_or_reason, reply_text=None): if isinstance(reply_code_or_reason, pika_errs.ChannelClosed): reply_code = reply_code_or_reason.reply_code reply_text = reply_code_or_reason.reply_text elif isinstance(reply_code_or_reason, int)...
603,629
Callback invoked when the connection is successfully established. Args: connection (pika.connection.SelectConnection): The newly-estabilished connection.
def _on_connection_open(self, connection): _log.info("Successfully opened connection to %s", connection.params.host) self._channel = connection.channel(on_open_callback=self._on_channel_open)
603,630
Callback invoked when a previously-opened connection is closed. Args: connection (pika.connection.SelectConnection): The connection that was just closed. reply_code_or_reason (int|Exception): The reason why the channel was closed. In older versions of pik...
def _on_connection_close(self, connection, reply_code_or_reason, reply_text=None): self._channel = None if isinstance(reply_code_or_reason, pika_errs.ConnectionClosed): reply_code = reply_code_or_reason.reply_code reply_text = reply_code_or_reason.reply_text eli...
603,631
Callback invoked when the connection failed to be established. Args: connection (pika.connection.SelectConnection): The connection that failed to open. error_message (str): The reason the connection couldn't be opened.
def _on_connection_error(self, connection, error_message): self._channel = None if isinstance(error_message, pika_errs.AMQPConnectionError): error_message = repr(error_message.args[0]) _log.error(error_message) self.call_later(1, self.reconnect)
603,632
Callback invoked when a queue is successfully declared. Args: frame (pika.frame.Method): The message sent from the server.
def _on_queue_declareok(self, frame): _log.info("Successfully declared the %s queue", frame.method.queue) for binding in self._bindings: if binding["queue"] == frame.method.queue: for key in binding["routing_keys"]: _log.info( ...
603,633
Schedule a one-shot timeout given delay seconds. This method is only useful for compatibility with older versions of pika. Args: delay (float): Non-negative number of seconds from now until expiration callback (method): The callback method, having the signature ...
def call_later(self, delay, callback): if hasattr(self._connection.ioloop, "call_later"): self._connection.ioloop.call_later(delay, callback) else: self._connection.ioloop.add_timeout(delay, callback)
603,634
Get the avatar URL from the email's From header. Args: from_header (str): The email's From header. May contain the sender's full name. Returns: str: The URL to that sender's avatar.
def get_avatar(from_header, size=64, default="retro"): params = OrderedDict([("s", size), ("d", default)]) query = parse.urlencode(params) address = email.utils.parseaddr(from_header)[1] value_hash = sha256(address.encode("utf-8")).hexdigest() return "https://seccdn.libravatar.org/avatar/{}?{}"...
603,639
Get the contents of a file listing the requirements. Args: requirements_file (str): The path to the requirements file, relative to this file. Returns: list: the list of requirements, or an empty list if ``requirements_file`` could not be opened or...
def get_requirements(requirements_file="requirements.txt"): with open(requirements_file) as fd: lines = fd.readlines() dependencies = [] for line in lines: maybe_dep = line.strip() if maybe_dep.startswith("#"): # Skip pure comment lines continue i...
603,641
Get the avatar URL of the provided Fedora username. The URL is returned from the Libravatar service. Args: username (str): The username to get the avatar of. size (int): Size of the avatar in pixels (it's a square). default (str): Default avatar to return if not found. Returns: ...
def user_avatar_url(username, size=64, default="retro"): openid = "http://{}.id.fedoraproject.org/".format(username) return libravatar_url(openid=openid, size=size, default=default)
603,642
Look up an account on the blockchain. Sample output: Args: address: (str) address to lookup ( in format 'AXjaFSP23Jkbe6Pk9pPGT6NBDs1HVdqaXK') id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: ...
def get_account(self, address, id=None, endpoint=None): return self._call_endpoint(GET_ACCOUNT_STATE, params=[address], id=id, endpoint=endpoint)
603,793
Get the current height of the blockchain Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
def get_height(self, id=None, endpoint=None): return self._call_endpoint(GET_BLOCK_COUNT, id=id, endpoint=endpoint)
603,794
Get an asset by its hash Args: asset_hash: (str) asset to lookup, example would be 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b' id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Retu...
def get_asset(self, asset_hash, id=None, endpoint=None): return self._call_endpoint(GET_ASSET_STATE, params=[asset_hash], id=id, endpoint=endpoint)
603,795
Get balance by asset hash Args: asset_hash: (str) asset to lookup, example would be 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b' id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Ret...
def get_balance(self, asset_hash, id=None, endpoint=None): return self._call_endpoint(GET_BALANCE, params=[asset_hash], id=id, endpoint=endpoint)
603,796
Get the hash of the highest block Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
def get_best_blockhash(self, id=None, endpoint=None): return self._call_endpoint(GET_BEST_BLOCK_HASH, id=id, endpoint=endpoint)
603,797
Look up a block by the height or hash of the block. Args: height_or_hash: (int or str) either the height of the desired block or its hash in the form '1e67372c158a4cfbb17b9ad3aaae77001a4247a00318e354c62e53b56af4006f' id: (int, optional) id to use for response tracking endpoin...
def get_block(self, height_or_hash, id=None, endpoint=None): return self._call_endpoint(GET_BLOCK, params=[height_or_hash, 1], id=id, endpoint=endpoint)
603,798
Get hash of a block by its height Args: height: (int) height of the block to lookup id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountere...
def get_block_hash(self, height, id=None, endpoint=None): return self._call_endpoint(GET_BLOCK_HASH, params=[height], id=id, endpoint=endpoint)
603,799
Get the corresponding block header information according to the specified script hash. Args: block_hash: (str) the block scripthash (e.g. 'a5508c9b6ed0fc09a531a62bc0b3efcb6b8a9250abaf72ab8e9591294c1f6957') id: (int, optional) id to use for response tracking endpoint: (RPCEndp...
def get_block_header(self, block_hash, id=None, endpoint=None): return self._call_endpoint(GET_BLOCK_HEADER, params=[block_hash, 1], id=id, endpoint=endpoint)
603,800
Get the system fee of a block by height. This is used in calculating gas claims Args: height: (int) height of the block to lookup id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: js...
def get_block_sysfee(self, height, id=None, endpoint=None): return self._call_endpoint(GET_BLOCK_SYS_FEE, params=[height], id=id, endpoint=endpoint)
603,801
Gets the number of nodes connected to the endpoint Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
def get_connection_count(self, id=None, endpoint=None): return self._call_endpoint(GET_CONNECTION_COUNT, id=id, endpoint=endpoint)
603,802
Get a contract state object by its hash Args: contract_hash: (str) the hash of the contract to lookup, for example 'd7678dd97c000be3f33e9362e673101bac4ca654' id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use ...
def get_contract_state(self, contract_hash, id=None, endpoint=None): return self._call_endpoint(GET_CONTRACT_STATE, params=[contract_hash], id=id, endpoint=endpoint)
603,803
Returns the tx that are in the memorypool of the endpoint Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
def get_raw_mempool(self, id=None, endpoint=None): return self._call_endpoint(GET_RAW_MEMPOOL, id=id, endpoint=endpoint)
603,804
Look up a transaction by hash. Args: tx_hash: (str) hash in the form '58c634f81fbd4ae2733d7e3930a9849021840fc19dc6af064d6f2812a333f91d' id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: ...
def get_transaction(self, tx_hash, id=None, endpoint=None): return self._call_endpoint(GET_RAW_TRANSACTION, params=[tx_hash, 1], id=id, endpoint=endpoint)
603,805
Returns a storage item of a specified contract Args: contract_hash: (str) hash of the contract to lookup, for example 'd7678dd97c000be3f33e9362e673101bac4ca654' storage_key: (str) storage key to lookup, for example 'totalSupply' id: (int, optional) id to use for response trac...
def get_storage(self, contract_hash, storage_key, id=None, endpoint=None): result = self._call_endpoint(GET_STORAGE, params=[contract_hash, binascii.hexlify(storage_key.encode('utf-8')).decode('utf-8')], id=id, endpoint=endpoint) try: return bytearray(binascii.unhexlify(result.enco...
603,806
Invokes a script that has been assembled Args: script: (str) a hexlified string of a contract invocation script, example '00c10b746f74616c537570706c796754a64cac1b1073e662933ef3e30b007cd98d67d7' id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, option...
def invoke_script(self, script, id=None, endpoint=None): return self._call_endpoint(INVOKE_SCRIPT, params=[script], id=id, endpoint=endpoint)
603,810
Submits a serialized tx to the network Args: serialized_tx: (str) a hexlified string of a transaction id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: bool: whether the tx was accepte...
def send_raw_tx(self, serialized_tx, id=None, endpoint=None): return self._call_endpoint(SEND_TX, params=[serialized_tx], id=id, endpoint=endpoint)
603,811
returns whether or not addr string is valid Args: address: (str) address to lookup ( in format 'AXjaFSP23Jkbe6Pk9pPGT6NBDs1HVdqaXK') id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: ...
def validate_addr(self, address, id=None, endpoint=None): return self._call_endpoint(VALIDATE_ADDR, params=[address], id=id, endpoint=endpoint)
603,812
Get the current peers of a remote node Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
def get_peers(self, id=None, endpoint=None): return self._call_endpoint(GET_PEERS, id=id, endpoint=endpoint)
603,813
Returns the current NEO consensus nodes information and voting status. Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
def get_validators(self, id=None, endpoint=None): return self._call_endpoint(GET_VALIDATORS, id=id, endpoint=endpoint)
603,814
Get the current version of the endpoint. Note: Not all endpoints currently implement this method Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the e...
def get_version(self, id=None, endpoint=None): return self._call_endpoint(GET_VERSION, id=id, endpoint=endpoint)
603,815
Create new address Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
def get_new_address(self, id=None, endpoint=None): return self._call_endpoint(GET_NEW_ADDRESS, id=id, endpoint=endpoint)
603,816
Get the current wallet index height. Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
def get_wallet_height(self, id=None, endpoint=None): return self._call_endpoint(GET_WALLET_HEIGHT, id=id, endpoint=endpoint)
603,817
Lists all the addresses in the current wallet. Args: id: (int, optional) id to use for response tracking endpoint: (RPCEndpoint, optional) endpoint to specify to use Returns: json object of the result or the error encountered in the RPC call
def list_address(self, id=None, endpoint=None): return self._call_endpoint(LIST_ADDRESS, id=id, endpoint=endpoint)
603,818
Instantiate a model class according to import path args: name: class import path like `user.User` return: model instance
def instance(cls, name): if not cls._instance.get(name): model_name = name.split('.') ins_name = '.'.join( ['models', model_name[0], 'model', model_name[1]]) cls._instance[name] = cls.import_model(ins_name)() return cls._instance[name]
605,866
r""" Instantiates an instance of MesoPy. Arguments: ---------- token: string, mandatory Your API token that authenticates you for requests against MesoWest.mes Returns: -------- None. Raises: ------- None.
def __init__(self, token): r self.base_url = 'http://api.mesowest.net/v2/' self.token = token self.geo_criteria = ['stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa', 'nwsfirezone', 'gacc', 'subgacc']
606,266