code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def paged_object_to_list(paged_object): ''' Extract all pages within a paged object as a list of dictionaries ''' paged_return = [] while True: try: page = next(paged_object) paged_return.append(page.as_dict()) except CloudError: raise exce...
Extract all pages within a paged object as a list of dictionaries
def replace_name(file_path, new_name): ''' Change the file name in a path but keep the extension ''' if not file_path: raise Exception("File path cannot be empty") elif not new_name: raise Exception("New name cannot be empty") dirname = os.path.dirname(file_path) ...
Change the file name in a path but keep the extension
def proj4_to_epsg(projection): """Attempts to convert a PROJ4 projection object to an EPSG code and returns None if conversion fails""" def make_definition(value): return {x.strip().lower() for x in value.split('+') if x} # Use the EPSG in the definition if available match = EPSG_RE.search(pro...
Attempts to convert a PROJ4 projection object to an EPSG code and returns None if conversion fails
def call_action(self, service_name, action_name, **kwargs): """Executes the given action. Raise a KeyError on unkown actions.""" action = self.services[service_name].actions[action_name] return action.execute(**kwargs)
Executes the given action. Raise a KeyError on unkown actions.
def unpack(self, buff, offset=0): """Unpack the buffer into a OxmTLV. Args: buff (bytes): The binary data to be unpacked. offset (int): If we need to shift the beginning of the data. """ super().unpack(buff, offset) # Recover field from field_and_hasmask...
Unpack the buffer into a OxmTLV. Args: buff (bytes): The binary data to be unpacked. offset (int): If we need to shift the beginning of the data.
def _set_route_target_evpn(self, v, load=False): """ Setter method for route_target_evpn, mapped from YANG variable /vrf/address_family/ipv6/unicast/route_target_container_ipv6/route_target_evpn (list) If this variable is read-only (config: false) in the source YANG file, then _set_route_target_evpn is ...
Setter method for route_target_evpn, mapped from YANG variable /vrf/address_family/ipv6/unicast/route_target_container_ipv6/route_target_evpn (list) If this variable is read-only (config: false) in the source YANG file, then _set_route_target_evpn is considered as a private method. Backends looking to popul...
def complete_reminder(self, reminder_id, complete_dict): """ Completes a reminder :param complete_dict: the complete dict with the template id :param reminder_id: the reminder id :return: Response """ return self._create_put_request( resource=REMINDER...
Completes a reminder :param complete_dict: the complete dict with the template id :param reminder_id: the reminder id :return: Response
def _generate_new_address(self, creator=None) -> str: """Generates a new address for the global state. :return: """ if creator: # TODO: Use nounce return "0x" + str(mk_contract_address(creator, 0).hex()) while True: address = "0x" + "".join([s...
Generates a new address for the global state. :return:
def insert(self, context): """ Deploy application. :param resort.engine.execution.Context context: Current execution context. """ module_file = open(context.resolve(self.__path), "rb") data = { "name": self.__name } if self.__context_root is not None: data["contextroot"] = self.__cont...
Deploy application. :param resort.engine.execution.Context context: Current execution context.
def _resolve_api_id(self): ''' returns an Api Id that matches the given api_name and the hardcoded _Swagger.AWS_API_DESCRIPTION as the api description ''' apis = __salt__['boto_apigateway.describe_apis'](name=self.rest_api_name, ...
returns an Api Id that matches the given api_name and the hardcoded _Swagger.AWS_API_DESCRIPTION as the api description
def share_network(network_id, usernames, read_only, share,**kwargs): """ Share a network with a list of users, identified by their usernames. The read_only flag ('Y' or 'N') must be set to 'Y' to allow write access or sharing. The share flat ('Y' or 'N') must be set to 'Y' to allow...
Share a network with a list of users, identified by their usernames. The read_only flag ('Y' or 'N') must be set to 'Y' to allow write access or sharing. The share flat ('Y' or 'N') must be set to 'Y' to allow the project to be shared with other users
def add_mismatch(self, entity, *traits): """ Add a mismatching entity to the index. We do this by simply adding the mismatch to the index. :param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by` :param list traits: a list of hashable tr...
Add a mismatching entity to the index. We do this by simply adding the mismatch to the index. :param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by` :param list traits: a list of hashable traits to index the entity with
def resume(self): """ resume the execution """ if self.get_state() != Target.TARGET_HALTED: logging.debug('cannot resume: target not halted') return self.notify(Notification(event=Target.EVENT_PRE_RUN, source=self, data=Target.RUN_TYPE_RESUME)) sel...
resume the execution
def set_context(self, data): """Load Context with data""" for key in data: setattr(self.local_context, key, data[key])
Load Context with data
def order_by(self, field, orientation='ASC'): """ Indica los campos y el criterio de ordenamiento """ if isinstance(field, list): self.raw_order_by.append(field) else: self.raw_order_by.append([field, orientation]) return self
Indica los campos y el criterio de ordenamiento
def QueueQueryAndOwn(self, queue, lease_seconds, limit, timestamp): """Returns a list of Tasks leased for a certain time. Args: queue: The queue to query from. lease_seconds: The tasks will be leased for this long. limit: Number of values to fetch. timestamp: Range of times for consider...
Returns a list of Tasks leased for a certain time. Args: queue: The queue to query from. lease_seconds: The tasks will be leased for this long. limit: Number of values to fetch. timestamp: Range of times for consideration. Returns: A list of GrrMessage() objects leased.
def _raise_on_mode(self, mode): """ Checks that the provided query mode is one of the accepted values. If not, raises a :obj:`ValueError`. """ valid_modes = [ 'random_sample', 'random_sample_per_pix', 'samples', 'median', ...
Checks that the provided query mode is one of the accepted values. If not, raises a :obj:`ValueError`.
def getStats(self): """ Parse the file using dedicated reader and collect fields stats. Never called if user of :class:`~.FileRecordStream` does not invoke :meth:`~.FileRecordStream.getStats` method. :returns: a dictionary of stats. In the current implementation, min and max fie...
Parse the file using dedicated reader and collect fields stats. Never called if user of :class:`~.FileRecordStream` does not invoke :meth:`~.FileRecordStream.getStats` method. :returns: a dictionary of stats. In the current implementation, min and max fields are supported. Example of th...
def do_classdesc(self, parent=None, ident=0): """ Handles a TC_CLASSDESC opcode :param parent: :param ident: Log indentation level :return: A JavaClass object """ # TC_CLASSDESC className serialVersionUID newHandle classDescInfo # classDescInfo: #...
Handles a TC_CLASSDESC opcode :param parent: :param ident: Log indentation level :return: A JavaClass object
def update_cursor(self, dc, grid, row, col): """Whites out the old cursor and draws the new one""" old_row, old_col = self.old_cursor_row_col bgcolor = get_color(config["background_color"]) self._draw_cursor(dc, grid, old_row, old_col, pen=wx.Pen(bgcolor), br...
Whites out the old cursor and draws the new one
def element_type(self): """ Returns the pointed-to type. When the type is not a pointer, raises exception. """ if not self.is_pointer: raise ValueError("Type {} is not a pointer".format(self)) return TypeRef(ffi.lib.LLVMPY_GetElementType(self))
Returns the pointed-to type. When the type is not a pointer, raises exception.
def Clamond(Re, eD, fast=False): r'''Calculates Darcy friction factor using a solution accurate to almost machine precision. Recommended very strongly. For details of the algorithm, see [1]_. Parameters ---------- Re : float Reynolds number, [-] eD : float Relative roug...
r'''Calculates Darcy friction factor using a solution accurate to almost machine precision. Recommended very strongly. For details of the algorithm, see [1]_. Parameters ---------- Re : float Reynolds number, [-] eD : float Relative roughness, [-] fast : bool, optional ...
def _execute(self, api_command, *, timeout=None): """Execute the command.""" if api_command.observe: self._observe(api_command) return method = api_command.method path = api_command.path data = api_command.data parse_json = api_command.parse_json...
Execute the command.
def _init_unique_sets(self): """Initialise sets used for uniqueness checking.""" ks = dict() for t in self._unique_checks: key = t[0] ks[key] = set() # empty set return ks
Initialise sets used for uniqueness checking.
def update(self, _attributes=None, **attributes): """ Perform an update on all the related models. :param attributes: The attributes :type attributes: dict :rtype: int """ if _attributes is not None: attributes.update(_attributes) if self._r...
Perform an update on all the related models. :param attributes: The attributes :type attributes: dict :rtype: int
def read_history_file(self, filename=None): u'''Load a readline history file.''' if filename is None: filename = self.history_filename try: for line in open(filename, u'r'): self.add_history(lineobj.ReadLineTextBuffer(ensure_unicode(line.rstrip())))...
u'''Load a readline history file.
def get_documents(self, subtypes=None, refresh=False): """Return list of author's publications using ScopusSearch, which fit a specified set of document subtypes. """ search = ScopusSearch('au-id({})'.format(self.identifier), refresh) if subtypes: return [p for p in s...
Return list of author's publications using ScopusSearch, which fit a specified set of document subtypes.
def create_styles(title,defaults=None,mappings=None,host=cytoscape_host,port=cytoscape_port): """ Creates a new visual style :param title: title of the visual style :param defaults: a list of dictionaries for each visualProperty :param mappings: a list of dictionaries for each visualProperty ...
Creates a new visual style :param title: title of the visual style :param defaults: a list of dictionaries for each visualProperty :param mappings: a list of dictionaries for each visualProperty :param host: cytoscape host address, default=cytoscape_host :param port: cytoscape port, default=123...
def search_variant_sets(self, dataset_id): """ Returns an iterator over the VariantSets fulfilling the specified conditions from the specified Dataset. :param str dataset_id: The ID of the :class:`ga4gh.protocol.Dataset` of interest. :return: An iterator over the :cl...
Returns an iterator over the VariantSets fulfilling the specified conditions from the specified Dataset. :param str dataset_id: The ID of the :class:`ga4gh.protocol.Dataset` of interest. :return: An iterator over the :class:`ga4gh.protocol.VariantSet` objects defined by ...
def verify(self, obj): """Verify that the object conforms to this verifier's schema Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the dictionary, a ValidationError is thrown with at least the reaso...
Verify that the object conforms to this verifier's schema Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the dictionary, a ValidationError is thrown with at least the reason key set indicating ...
def _tls_auth_encrypt(self, s): """ Return the TLSCiphertext.fragment for AEAD ciphers, i.e. the whole GenericAEADCipher. Also, the additional data is computed right here. """ write_seq_num = struct.pack("!Q", self.tls_session.wcs.seq_num) self.tls_session.wcs.seq_num += ...
Return the TLSCiphertext.fragment for AEAD ciphers, i.e. the whole GenericAEADCipher. Also, the additional data is computed right here.
def pvlan_host_association(self, **kwargs): """Set interface PVLAN association. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet, etc) name (str): Name of interface. (1/0/5, 1/0/10, etc) pri_vlan (str): The primary PVLAN. ...
Set interface PVLAN association. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet, etc) name (str): Name of interface. (1/0/5, 1/0/10, etc) pri_vlan (str): The primary PVLAN. sec_vlan (str): The secondary PVLAN. ...
def _make_image_description(self, datasets, **kwargs): """ generate image description for mitiff. Satellite: NOAA 18 Date and Time: 06:58 31/05-2016 SatDir: 0 Channels: 6 In this file: 1-VIS0.63 2-VIS0.86 3(3B)-IR3.7 4-IR10.8 5-IR11.5 6(3A)-VIS1.6 Xsize...
generate image description for mitiff. Satellite: NOAA 18 Date and Time: 06:58 31/05-2016 SatDir: 0 Channels: 6 In this file: 1-VIS0.63 2-VIS0.86 3(3B)-IR3.7 4-IR10.8 5-IR11.5 6(3A)-VIS1.6 Xsize: 4720 Ysize: 5544 Map projection: Stereographic ...
def main(args): """Launch the appropriate builder.""" grr_config.CONFIG.AddContext(contexts.CLIENT_BUILD_CONTEXT) if args.subparser_name == "generate_client_config": # We don't need a full init to just build a config. GetClientConfig(args.client_config_output) return # TODO(user): Find out if add...
Launch the appropriate builder.
def _setup_axes(cls, axes, info_axis=None, stat_axis=None, aliases=None, slicers=None, axes_are_reversed=False, build_axes=True, ns=None, docs=None): """Provide axes setup for the major PandasObjects. Parameters ---------- axes : the names of the ...
Provide axes setup for the major PandasObjects. Parameters ---------- axes : the names of the axes in order (lowest to highest) info_axis_num : the axis of the selector dimension (int) stat_axis_num : the number of axis for the default stats (int) aliases : other names f...
def parent(self): """ Get the parent of the element @rtype: WebElementWrapper @return: Parent of webelementwrapper on which this was invoked """ def parent_element(): """ Wrapper to retrieve parent element """ return...
Get the parent of the element @rtype: WebElementWrapper @return: Parent of webelementwrapper on which this was invoked
def record(self): """ Record PyAudio stream into StringIO output This coroutine keeps stream open; the stream is closed in stop() """ while True: frames = [] self.stream.start_stream() for i in range(self.num_frames): data = s...
Record PyAudio stream into StringIO output This coroutine keeps stream open; the stream is closed in stop()
def argmin(self, axis=None, skipna=True, *args, **kwargs): """ Returns the indices of the minimum values along an axis. See `numpy.ndarray.argmin` for more information on the `axis` parameter. See Also -------- numpy.ndarray.argmin """ nv.validat...
Returns the indices of the minimum values along an axis. See `numpy.ndarray.argmin` for more information on the `axis` parameter. See Also -------- numpy.ndarray.argmin
def next_event(self): """Simulates the queue forward one event. Use :meth:`.simulate` instead. Returns ------- out : :class:`.Agent` (sometimes) If the next event is a departure then the departing agent is returned, otherwise nothing is returned. ...
Simulates the queue forward one event. Use :meth:`.simulate` instead. Returns ------- out : :class:`.Agent` (sometimes) If the next event is a departure then the departing agent is returned, otherwise nothing is returned. See Also -------- ...
def generate_bigip_uri(base_uri, partition, name, sub_path, suffix, **kwargs): '''(str, str, str) --> str This function checks the supplied elements to see if each conforms to the specification for the appropriate part of the URI. These validations are conducted by the helper function _validate_uri_par...
(str, str, str) --> str This function checks the supplied elements to see if each conforms to the specification for the appropriate part of the URI. These validations are conducted by the helper function _validate_uri_parts. After validation the parts are assembled into a valid BigIP REST URI strin...
def makeUserLoginMethod(username, password, locale=None): '''Return a function that will call the vim.SessionManager.Login() method with the given parameters. The result of this function can be passed as the "loginMethod" to a SessionOrientedStub constructor.''' def _doLogin(soapStub): ...
Return a function that will call the vim.SessionManager.Login() method with the given parameters. The result of this function can be passed as the "loginMethod" to a SessionOrientedStub constructor.
def router_function(fn): # type: (Callable) -> Callable """Raise a runtime error if on Win32 systems. Decorator. Decorator for functions that interact with the router for the Linux implementation of the ADS library. Unlike the Windows implementation which uses a separate router daemon, th...
Raise a runtime error if on Win32 systems. Decorator. Decorator for functions that interact with the router for the Linux implementation of the ADS library. Unlike the Windows implementation which uses a separate router daemon, the Linux library manages AMS routing in-process. As such, routing mu...
def _get_content_type(self, file): """ Return content type of file. If file does not have a content type, make a guess. """ if file.mimetype: return file.mimetype # get file extension _, extension = os.path.splitext(file.name) extension = exte...
Return content type of file. If file does not have a content type, make a guess.
def _encode_text(name, value, dummy0, dummy1): """Encode a python unicode (python 2.x) / str (python 3.x).""" value = _utf_8_encode(value)[0] return b"\x02" + name + _PACK_INT(len(value) + 1) + value + b"\x00"
Encode a python unicode (python 2.x) / str (python 3.x).
def get_passenger_queue_stats(self): """ Execute passenger-stats, parse its output, returnand requests in queue """ queue_stats = { "top_level_queue_size": 0.0, "passenger_queue_size": 0.0, } command = [self.config["passenger_status_bin"]] ...
Execute passenger-stats, parse its output, returnand requests in queue
def SetProtocol(self, protocol): """Sets the protocol that will be used to query Viper. Args: protocol (str): protocol to use to query Viper. Either 'http' or 'https'. Raises: ValueError: If an invalid protocol is selected. """ protocol = protocol.lower().strip() if protocol not in...
Sets the protocol that will be used to query Viper. Args: protocol (str): protocol to use to query Viper. Either 'http' or 'https'. Raises: ValueError: If an invalid protocol is selected.
def reset(self, hard=False): '''reset the card dispense, either soft or hard based on boolean 2nd arg''' if hard: self.sendcommand(Vendapin.RESET, 1, 0x01) time.sleep(2) else: self.sendcommand(Vendapin.RESET) time.sleep(2) # parse the r...
reset the card dispense, either soft or hard based on boolean 2nd arg
def _configure_key_pair(config): """Configure SSH access, using an existing key pair if possible. Creates a project-wide ssh key that can be used to access all the instances unless explicitly prohibited by instance config. The ssh-keys created by ray are of format: [USERNAME]:ssh-rsa [KEY_VALUE...
Configure SSH access, using an existing key pair if possible. Creates a project-wide ssh key that can be used to access all the instances unless explicitly prohibited by instance config. The ssh-keys created by ray are of format: [USERNAME]:ssh-rsa [KEY_VALUE] [USERNAME] where: [USERNAM...
def _set_mpls_interface(self, v, load=False): """ Setter method for mpls_interface, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface (list) If this variable is read-only (config: false) in the source YANG file, then _set_mpls_interface is considered as a private met...
Setter method for mpls_interface, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface (list) If this variable is read-only (config: false) in the source YANG file, then _set_mpls_interface is considered as a private method. Backends looking to populate this variable should ...
def render_document(template_name, data_name, output_name): """ Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file. Parameters ========== template_name : String Exact ...
Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file. Parameters ========== template_name : String Exact name of the MarkDown template file from the aide_document/templates fold...
def create_asset(json): """Create :class:`.resources.Asset` from JSON. :param json: JSON dict. :return: Asset instance. """ result = Asset(json['sys']) file_dict = json['fields']['file'] result.fields = json['fields'] result.url = file_dict['url'] ...
Create :class:`.resources.Asset` from JSON. :param json: JSON dict. :return: Asset instance.
def _field_sort_name(cls, name): """Get a sort key for a field name that determines the order fields should be written in. Fields names are kept unchanged, unless they are instances of :class:`DateItemField`, in which case `year`, `month`, and `day` are replaced by `date0`, `dat...
Get a sort key for a field name that determines the order fields should be written in. Fields names are kept unchanged, unless they are instances of :class:`DateItemField`, in which case `year`, `month`, and `day` are replaced by `date0`, `date1`, and `date2`, respectively, to m...
def parse_atoms(self): '''All ATOM lines are parsed even though only one per residue needs to be parsed. The reason for parsing all the lines is just to sanity-checks that the ATOMs within one residue are consistent with each other.''' atom_site_header_tag = self.main_tag.getElementsByTagNam...
All ATOM lines are parsed even though only one per residue needs to be parsed. The reason for parsing all the lines is just to sanity-checks that the ATOMs within one residue are consistent with each other.
def t_whitespace(self, s): r'\s+' self.add_token('SPACE', s) self.pos += len(s) pass
r'\s+
def init_publisher(app): """Calling this with your flask app as argument is required for the publisher decorator to work. """ @app.context_processor def inject_links(): return { 'websub_self_url': stack.top.websub_self_url, 'websub_hub_url': stack.top.websub_hub_url,...
Calling this with your flask app as argument is required for the publisher decorator to work.
def __tomo_linear_inv(freqs, ops, weights=None, trace=None): """ Reconstruct a matrix through linear inversion. Args: freqs (list[float]): list of observed frequences. ops (list[np.array]): list of corresponding projectors. weights (list[float] or array_like): weights to...
Reconstruct a matrix through linear inversion. Args: freqs (list[float]): list of observed frequences. ops (list[np.array]): list of corresponding projectors. weights (list[float] or array_like): weights to be used for weighted fitting. trace (float or None): trace of re...
def find_branches(self, labels=False, unique=False): """Recursively constructs a list of pointers of the tree's structure Args: labels (bool): If True, returned lists consist of node labels. If False (default), lists consist of node poin...
Recursively constructs a list of pointers of the tree's structure Args: labels (bool): If True, returned lists consist of node labels. If False (default), lists consist of node pointers. This option is mostly intended for ...
def __update_html(self, html): """ Updates the View with given html content. :param html: Html content. :type html: unicode """ if platform.system() in ("Windows", "Microsoft"): html = re.sub(r"((?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+)", ...
Updates the View with given html content. :param html: Html content. :type html: unicode
def _future_command_unlocked(self, cmd): """Run command as a coroutine and return a future. Args: loop (BackgroundEventLoop): The loop that we should attach the future too. cmd (list): The command and arguments that we wish to call. Returns: ...
Run command as a coroutine and return a future. Args: loop (BackgroundEventLoop): The loop that we should attach the future too. cmd (list): The command and arguments that we wish to call. Returns: asyncio.Future: An awaitable future with the result ...
def register (self, target): """ Registers a new virtual target. Checks if there's already registered target, with the same name, type, project and subvariant properties, and also with the same sources and equal action. If such target is found it is retured and 'target' is not registered...
Registers a new virtual target. Checks if there's already registered target, with the same name, type, project and subvariant properties, and also with the same sources and equal action. If such target is found it is retured and 'target' is not registered. Otherwise, 'target' is regi...
def _list_store_resources(self, request, head_id, filter_ids, resource_fetcher, block_xform): """Builds a list of blocks or resources derived from blocks, handling multiple possible filter requests: - filtered by a set of ids - filtered by head block...
Builds a list of blocks or resources derived from blocks, handling multiple possible filter requests: - filtered by a set of ids - filtered by head block - filtered by both id and head block - not filtered (all current resources) Note: This me...
def post(self, action, data=None, headers=None): """Makes a GET request """ return self.request(make_url(self.endpoint, action), method='POST', data=data, headers=headers)
Makes a GET request
def setColor(self, key, value): """ Sets the color value for the inputed color. :param key | <unicode> value | <QtGui.QColor> """ key = nativestring(key).capitalize() self._colorSet.setColor(key, value) # ...
Sets the color value for the inputed color. :param key | <unicode> value | <QtGui.QColor>
def matches(self, client, event_data): """True if all filters are matching.""" for f in self.filters: if not f(client, event_data): return False return True
True if all filters are matching.
def invalidate(self): """ Invalidate access tokens with a client/access token pair Returns: dict: Empty or error dict """ endpoint = '/invalidate' payload = { 'accessToken': self.access_token, 'clientToken': self.client_token, ...
Invalidate access tokens with a client/access token pair Returns: dict: Empty or error dict
def _update_camera_pos(self): """ Set the camera position and orientation""" # transform will be updated several times; do not update camera # transform until we are done. ch_em = self.events.transform_change with ch_em.blocker(self._update_transform): tr = self.tran...
Set the camera position and orientation
def resolve_and_call(self, func, extra_env=None): """ Resolve function arguments and call them, possibily filling from the environment """ kwargs = self.resolve_parameters(func, extra_env=extra_env) return func(**kwargs)
Resolve function arguments and call them, possibily filling from the environment
def _expand_numparse(disable_numparse, column_count): """ Return a list of bools of length `column_count` which indicates whether number parsing should be used on each column. If `disable_numparse` is a list of indices, each of those indices are False, and everything else is True. If `disable_nu...
Return a list of bools of length `column_count` which indicates whether number parsing should be used on each column. If `disable_numparse` is a list of indices, each of those indices are False, and everything else is True. If `disable_numparse` is a bool, then the returned list is all the same.
def byaxis(self): """Return the subspace defined along one or several dimensions. Examples -------- Indexing with integers or slices: >>> space = odl.rn((2, 3, 4)) >>> space.byaxis[0] rn(2) >>> space.byaxis[1:] rn((3, 4)) Lists can be us...
Return the subspace defined along one or several dimensions. Examples -------- Indexing with integers or slices: >>> space = odl.rn((2, 3, 4)) >>> space.byaxis[0] rn(2) >>> space.byaxis[1:] rn((3, 4)) Lists can be used to stack spaces arbitraril...
def lock_status(self, resource_id, parent_id=None, account_id=None): """Get the lock status for a given resource. for security groups, parent id is their vpc. """ account_id = self.get_account_id(account_id) params = parent_id and {'parent_id': parent_id} or None return ...
Get the lock status for a given resource. for security groups, parent id is their vpc.
def find_children(self): """Take a tree and set the children according to the parents. Takes a tree structure which lists the parents of each vertex and computes the children for each vertex and places them in.""" for i in range(len(self.vertices)): self.vertices[i].children...
Take a tree and set the children according to the parents. Takes a tree structure which lists the parents of each vertex and computes the children for each vertex and places them in.
def remove(self, *members): """ Removes @members from the set -> #int the number of members that were removed from the set """ if self.serialized: members = list(map(self._dumps, members)) return self._client.srem(self.key_prefix, *members)
Removes @members from the set -> #int the number of members that were removed from the set
def eth_getBlockByNumber(self, block=BLOCK_TAG_LATEST, tx_objects=True): """TODO: documentation https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblockbynumber TESTED """ block = validate_block(block) return self._call("eth_getBlockByNumber", [block, tx_objects])
TODO: documentation https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblockbynumber TESTED
def list(self, pattern='*'): """Returns a list of metric descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"compute*"``, ``"*cpu/load_??m"``. Returns: A list of Metri...
Returns a list of metric descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"compute*"``, ``"*cpu/load_??m"``. Returns: A list of MetricDescriptor objects that match the f...
def _raw(cls, vertices, edges, out_edges, in_edges, head, tail): """ Private constructor for direct construction of an ObjectGraph from its attributes. vertices is the collection of vertices out_edges and in_edges map vertices to lists of edges head and tail map edges to...
Private constructor for direct construction of an ObjectGraph from its attributes. vertices is the collection of vertices out_edges and in_edges map vertices to lists of edges head and tail map edges to objects.
def i18n(msg, event=None, lang='en', domain='backend'): """Gettext function wrapper to return a message in a specified language by domain To use internationalization (i18n) on your messages, import it as '_' and use as usual. Do not forget to supply the client's language setting.""" if event is not No...
Gettext function wrapper to return a message in a specified language by domain To use internationalization (i18n) on your messages, import it as '_' and use as usual. Do not forget to supply the client's language setting.
def ring_coding(array): """ Produces matplotlib Path codes for exterior and interior rings of a polygon geometry. """ # The codes will be all "LINETO" commands, except for "MOVETO"s at the # beginning of each subpath n = len(array) codes = np.ones(n, dtype=Path.code_type) * Path.LINETO ...
Produces matplotlib Path codes for exterior and interior rings of a polygon geometry.
def write_utf(self, s): """Writes a UTF-8 string of a given length to the packet""" utfstr = s.encode('utf-8') length = len(utfstr) if length > 64: raise NamePartTooLongException self.write_byte(length) self.write_string(utfstr, length)
Writes a UTF-8 string of a given length to the packet
def preprocess_async(train_dataset, output_dir, eval_dataset=None, checkpoint=None, cloud=None): """Preprocess data. Produce output that can be used by training efficiently. Args: train_dataset: training data source to preprocess. Can be CsvDataset or BigQueryDataSet. If eval_dataset is None, the pipel...
Preprocess data. Produce output that can be used by training efficiently. Args: train_dataset: training data source to preprocess. Can be CsvDataset or BigQueryDataSet. If eval_dataset is None, the pipeline will randomly split train_dataset into train/eval set with 7:3 ratio. output_dir: The ...
def save_figures(block, block_vars, gallery_conf): """Save all open figures of the example code-block. Parameters ---------- block : tuple A tuple containing the (label, content, line_number) of the block. block_vars : dict Dict of block variables. gallery_conf : dict Co...
Save all open figures of the example code-block. Parameters ---------- block : tuple A tuple containing the (label, content, line_number) of the block. block_vars : dict Dict of block variables. gallery_conf : dict Contains the configuration of Sphinx-Gallery Returns ...
def get_points_and_weights(w_func=lambda x : np.ones(x.shape), left=-1.0, right=1.0, num_points=5, n=4096): """Quadratude points and weights for a weighting function. Points and weights for approximating the integral I = \int_left^right f(x) w(x) dx given the weighting function w(x) using the...
Quadratude points and weights for a weighting function. Points and weights for approximating the integral I = \int_left^right f(x) w(x) dx given the weighting function w(x) using the approximation I ~ w_i f(x_i) Args: w_func: The weighting function w(x). Must be a function that ta...
def submit_form(self, form, submit=None, **kwargs): """Submit a form. :param Form form: Filled-out form object :param Submit submit: Optional `Submit` to click, if form includes multiple submits :param kwargs: Keyword arguments to `Session::send` """ # Get H...
Submit a form. :param Form form: Filled-out form object :param Submit submit: Optional `Submit` to click, if form includes multiple submits :param kwargs: Keyword arguments to `Session::send`
def predict_proba(self, X): """Return the output of the module's forward method as a numpy array. If the module's forward method returns multiple outputs as a tuple, it is assumed that the first output contains the relevant information and the other values are ignored. If all ...
Return the output of the module's forward method as a numpy array. If the module's forward method returns multiple outputs as a tuple, it is assumed that the first output contains the relevant information and the other values are ignored. If all values are relevant, consider usi...
def get_method_serializers(self, http_method): """Get request method serializers + default media type. Grab serializers from ``method_serializers`` if defined, otherwise returns the default serializers. Uses GET serializers for HEAD requests if no HEAD serializers were specified. ...
Get request method serializers + default media type. Grab serializers from ``method_serializers`` if defined, otherwise returns the default serializers. Uses GET serializers for HEAD requests if no HEAD serializers were specified. The method also determines the default media type. ...
def get_protocol_version(protocol=None, target=None): """ Return a suitable pickle protocol version for a given target. Arguments: target: The internals description of the targeted python version. If this is ``None`` the specification of the currently running python version ...
Return a suitable pickle protocol version for a given target. Arguments: target: The internals description of the targeted python version. If this is ``None`` the specification of the currently running python version will be used. protocol(None or int): The requested protoco...
def get_free_region(self, width, height): """Get a free region of given size and allocate it Parameters ---------- width : int Width of region to allocate height : int Height of region to allocate Returns ------- bounds : tuple | ...
Get a free region of given size and allocate it Parameters ---------- width : int Width of region to allocate height : int Height of region to allocate Returns ------- bounds : tuple | None A newly allocated region as (x, y, w...
def parse_version(version: str) -> tuple: """Parse a string formatted X[.Y.Z] version number into a tuple >>> parse_version('10.2.3') (10, 2, 3) >>> parse_version('12') (12, 0, 0) """ if not version: return None parts = version.split('.') missing = 3 - len(parts) return...
Parse a string formatted X[.Y.Z] version number into a tuple >>> parse_version('10.2.3') (10, 2, 3) >>> parse_version('12') (12, 0, 0)
def prepare(self, cache): """Prepare to run next shot.""" if cache is not None: np.copyto(self.qubits, cache) else: self.qubits.fill(0.0) self.qubits[0] = 1.0 self.cregs = [0] * self.n_qubits
Prepare to run next shot.
def conditional_accept(self): """Accepts the inputs if all values are valid and congruent. i.e. Valid datafile and frequency range within the given calibration dataset.""" if self.ui.calfileRadio.isChecked() and str(self.ui.calChoiceCmbbx.currentText()) == '': self.ui.noneRadio.setCh...
Accepts the inputs if all values are valid and congruent. i.e. Valid datafile and frequency range within the given calibration dataset.
def _set_fetcher_options(self, base): """ When easy_install is about to run bdist_egg on a source dist, that source dist might have 'setup_requires' directives, requiring additional fetching. Ensure the fetcher options given to easy_install are available to that command as well. ...
When easy_install is about to run bdist_egg on a source dist, that source dist might have 'setup_requires' directives, requiring additional fetching. Ensure the fetcher options given to easy_install are available to that command as well.
def validate_key(request, group=None, perm=None, keytype=None): """ Validate the given key """ def update_last_access(): if KEY_LAST_USED_UPDATE: request.key.save() if request.user.is_authenticated() and is_valid_consumer(request): if not group and not perm and not k...
Validate the given key
def receive(self, msg): """ Returns a (receiver, msg) pair, where receiver is `None` if no route for the message was found, or otherwise an object with a `receive` method that can accept that `msg`. """ x = self.routing while not isinstance(x, ActionList): ...
Returns a (receiver, msg) pair, where receiver is `None` if no route for the message was found, or otherwise an object with a `receive` method that can accept that `msg`.
def _ecc_encode_compressed_point(private_key): """Encodes a compressed elliptic curve point as described in SEC-1 v2 section 2.3.3 http://www.secg.org/sec1-v2.pdf :param private_key: Private key from which to extract point data :type private_key: cryptography.hazmat.primitives.asymmetric.ec...
Encodes a compressed elliptic curve point as described in SEC-1 v2 section 2.3.3 http://www.secg.org/sec1-v2.pdf :param private_key: Private key from which to extract point data :type private_key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey :returns: Encoded compres...
def default_multivariate_normal_fn(dtype, shape, name, trainable, add_variable_fn): """Creates multivariate standard `Normal` distribution. Args: dtype: Type of parameter's event. shape: Python `list`-like representing the parameter's event shape. name: Python `str` n...
Creates multivariate standard `Normal` distribution. Args: dtype: Type of parameter's event. shape: Python `list`-like representing the parameter's event shape. name: Python `str` name prepended to any created (or existing) `tf.Variable`s. trainable: Python `bool` indicating all created `tf.Var...
def check_rights(self, resources, request=None): """ Check rights for resources. :return bool: True if operation is success else HTTP_403_FORBIDDEN """ if not self.auth: return True try: if not self.auth.test_rights(resources, request=request): ...
Check rights for resources. :return bool: True if operation is success else HTTP_403_FORBIDDEN
def get_task_summary(self, task_name): """ Get a task's summary, mostly used for MapReduce. :param task_name: task name :return: summary as a dict parsed from JSON :rtype: dict """ params = {'instancesummary': '', 'taskname': task_name} resp = self._clie...
Get a task's summary, mostly used for MapReduce. :param task_name: task name :return: summary as a dict parsed from JSON :rtype: dict
def ekrced(handle, segno, recno, column, nelts=_SPICE_EK_EKRCEX_ROOM_DEFAULT): """ Read data from a double precision column in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekrced_c.html :param handle: Handle attached to EK file. :type handle: int :param segno:...
Read data from a double precision column in a specified EK record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekrced_c.html :param handle: Handle attached to EK file. :type handle: int :param segno: Index of segment containing record. :type segno: int :param recno: Record from whi...
def users_create_many(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/users#create-many-users" api_path = "/api/v2/users/create_many.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/users#create-many-users
def set_zerg_client_params(self, server_sockets, use_fallback_socket=None): """Zerg mode. Zergs params. :param str|unicode|list[str|unicode] server_sockets: Attaches zerg to a zerg server. :param bool use_fallback_socket: Fallback to normal sockets if the zerg server is not available ...
Zerg mode. Zergs params. :param str|unicode|list[str|unicode] server_sockets: Attaches zerg to a zerg server. :param bool use_fallback_socket: Fallback to normal sockets if the zerg server is not available
def listen(self, **kwargs: Any) -> Server: """ bind host, port or sock """ loop = cast(asyncio.AbstractEventLoop, self._loop) return (yield from loop.create_server( lambda: self._protocol( loop=loop, handle=self._handle, ...
bind host, port or sock