code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def visit_BitVecExtract(self, expression, *operands): """ extract(sizeof(a), 0)(a) ==> a extract(16, 0)( concat(a,b,c,d) ) => concat(c, d) extract(m,M)(and/or/xor a b ) => and/or/xor((extract(m,M) a) (extract(m,M) a) """ op = expression.operands[0] begining = exp...
extract(sizeof(a), 0)(a) ==> a extract(16, 0)( concat(a,b,c,d) ) => concat(c, d) extract(m,M)(and/or/xor a b ) => and/or/xor((extract(m,M) a) (extract(m,M) a)
def get_billable_items(self): """Return a list of billable items """ items = [] for obj in self.context.getBillableItems(): if self.is_profile(obj): items.append({ "obj": obj, "title": obj.Title(), "v...
Return a list of billable items
def filter(self, index): #@ReservedAssignment """ Filters a datamat by different aspects. This function is a device to filter the datamat by certain logical conditions. It takes as input a logical array (contains only True or False for every datapoint) and kicks out all datapoin...
Filters a datamat by different aspects. This function is a device to filter the datamat by certain logical conditions. It takes as input a logical array (contains only True or False for every datapoint) and kicks out all datapoints for which the array says False. The logical array can c...
def get_order_parameters(self, structure, n, indices_neighs=None, \ tol=0.0, target_spec=None): """ Compute all order parameters of site n. Args: structure (Structure): input structure. n (int): index of site in input structure, ...
Compute all order parameters of site n. Args: structure (Structure): input structure. n (int): index of site in input structure, for which OPs are to be calculated. Note that we do not use the sites iterator here, but directly access site...
def filter(cls, filters, iterable): '''Returns the elements in `iterable` that pass given `filters`''' if isinstance(filters, Filter): filters = [filters] for filter in filters: iterable = filter.generator(iterable) return iterable
Returns the elements in `iterable` that pass given `filters`
def split_unescape(s, delim, escape='\\', unescape=True): """ >>> split_unescape('foo,bar', ',') ['foo', 'bar'] >>> split_unescape('foo$,bar', ',', '$') ['foo,bar'] >>> split_unescape('foo$$,bar', ',', '$', unescape=True) ['foo$', 'bar'] >>> split_unescape('fo...
>>> split_unescape('foo,bar', ',') ['foo', 'bar'] >>> split_unescape('foo$,bar', ',', '$') ['foo,bar'] >>> split_unescape('foo$$,bar', ',', '$', unescape=True) ['foo$', 'bar'] >>> split_unescape('foo$$,bar', ',', '$', unescape=False) ['foo$$', 'bar'] >>> s...
def remotesByConnected(self): """ Partitions the remotes into connected and disconnected :return: tuple(connected remotes, disconnected remotes) """ conns, disconns = [], [] for r in self.remotes.values(): array = conns if self.isRemoteConnected(r) else disco...
Partitions the remotes into connected and disconnected :return: tuple(connected remotes, disconnected remotes)
def versions(self): """Announce Versions of CLI and Server Args: None Returns: The running versions of both the CLI and the Workbench Server """ print '%s<<< Workbench CLI Version %s >>>%s' % (color.LightBlue, self.version, color.Normal) print self...
Announce Versions of CLI and Server Args: None Returns: The running versions of both the CLI and the Workbench Server
def __create_dynamic_connections(self): """! @brief Create dynamic connection in line with input stimulus. """ if (self._stimulus is None): raise NameError("Stimulus should initialed before creation of the dynamic connections in the network."); ...
! @brief Create dynamic connection in line with input stimulus.
def _call_scope(self, scope, *args, **kwargs): """ Call the given model scope. :param scope: The scope to call :type scope: str """ result = getattr(self._model, scope)(self, *args, **kwargs) return result or self
Call the given model scope. :param scope: The scope to call :type scope: str
def deps_from_pyp_format(requires, runtime=True): """Parses dependencies extracted from setup.py. Args: requires: list of dependencies as written in setup.py of the package. runtime: are the dependencies runtime (True) or build time (False)? Returns: List of semi-SPECFILE dependencie...
Parses dependencies extracted from setup.py. Args: requires: list of dependencies as written in setup.py of the package. runtime: are the dependencies runtime (True) or build time (False)? Returns: List of semi-SPECFILE dependencies (see dependency_to_rpm for format).
def function(self, x, y, amp, R_sersic, n_sersic, e1, e2, center_x=0, center_y=0): """ returns Sersic profile """ #if n_sersic < 0.2: # n_sersic = 0.2 #if R_sersic < 10.**(-6): # R_sersic = 10.**(-6) R_sersic = np.maximum(0, R_sersic) phi_G, ...
returns Sersic profile
def get_pixel(self, x: int, y: int) -> Tuple[int, int, int]: """Get the color of a pixel in this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. Returns: Tuple[int, int, in...
Get the color of a pixel in this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. Returns: Tuple[int, int, int]: An (r, g, b) tuple containing the pixels color value...
def add(self, interval): """ Adds an interval to the tree, if not already present. Completes in O(log n) time. """ if interval in self: return if interval.is_null(): raise ValueError( "IntervalTree: Null Interval objects not allow...
Adds an interval to the tree, if not already present. Completes in O(log n) time.
def sanitize_for_archive(url, headers, payload): """Sanitize payload of a HTTP request by removing the token information before storing/retrieving archived items :param: url: HTTP url request :param: headers: HTTP headers request :param: payload: HTTP payload request :r...
Sanitize payload of a HTTP request by removing the token information before storing/retrieving archived items :param: url: HTTP url request :param: headers: HTTP headers request :param: payload: HTTP payload request :returns url, headers and the sanitized payload
def save_config(self, cmd="write memory", confirm=False, confirm_response=""): """Saves configuration.""" return super(UbiquitiEdgeSSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Saves configuration.
def get_grade_system_form(self, *args, **kwargs): """Pass through to provider GradeSystemAdminSession.get_grade_system_form_for_update""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.get_resource_form_for_update # This method might be a bit sketchy. Time...
Pass through to provider GradeSystemAdminSession.get_grade_system_form_for_update
def AnalizarXml(self, xml=""): "Analiza un mensaje XML (por defecto el ticket de acceso)" try: if not xml or xml=='XmlResponse': xml = self.XmlResponse elif xml=='XmlRequest': xml = self.XmlRequest self.xml = SimpleXMLElement(xml) ...
Analiza un mensaje XML (por defecto el ticket de acceso)
def delete_mount_cache(real_name): ''' .. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share ''' cache = salt.utils.mount.read_cache(__opts__) if cache: if 'mounts' in cach...
.. versionadded:: 2018.3.0 Provide information if the path is mounted CLI Example: .. code-block:: bash salt '*' mount.delete_mount_cache /mnt/share
def infer_sedes(obj): """Try to find a sedes objects suitable for a given Python object. The sedes objects considered are `obj`'s class, `big_endian_int` and `binary`. If `obj` is a sequence, a :class:`rlp.sedes.List` will be constructed recursively. :param obj: the python object for which to find...
Try to find a sedes objects suitable for a given Python object. The sedes objects considered are `obj`'s class, `big_endian_int` and `binary`. If `obj` is a sequence, a :class:`rlp.sedes.List` will be constructed recursively. :param obj: the python object for which to find a sedes object :raises: ...
def teardown_cluster(config_file, yes, workers_only, override_cluster_name): """Destroys all nodes of a Ray cluster described by a config json.""" config = yaml.load(open(config_file).read()) if override_cluster_name is not None: config["cluster_name"] = override_cluster_name validate_config(co...
Destroys all nodes of a Ray cluster described by a config json.
def freeze(obj): """Transform tree of dict and list in read-only data structure. dict instances are transformed to FrozenDict, lists in FrozenList. """ if isinstance(obj, collections.Mapping): return FrozenDict({freeze(k): freeze(v) for k, v in six.iteritems(obj)}) elif isinstance(ob...
Transform tree of dict and list in read-only data structure. dict instances are transformed to FrozenDict, lists in FrozenList.
def lucas_gas(T, Tc, Pc, Zc, MW, dipole=0, CASRN=None): r'''Estimate the viscosity of a gas using an emperical formula developed in several sources, but as discussed in [1]_ as the original sources are in German or merely personal communications with the authors of [1]_. .. math:: \eta = \...
r'''Estimate the viscosity of a gas using an emperical formula developed in several sources, but as discussed in [1]_ as the original sources are in German or merely personal communications with the authors of [1]_. .. math:: \eta = \left[0.807T_r^{0.618}-0.357\exp(-0.449T_r) + 0.340\exp(-4.05...
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if len(mode) > 1 or mode not in "rw": raise ValueError("mode must be 'r' or 'w'") try: ...
Open gzip compressed tar archive name for reading or writing. Appending is not allowed.
def gdaOnes(shape, dtype, numGhosts=1): """ ghosted distributed array one constructor @param shape the shape of the array @param dtype the numpy data type @param numGhosts the number of ghosts (>= 0) """ res = GhostedDistArray(shape, dtype) res.setNumberOfGhosts(numGhosts) res[:] = 1...
ghosted distributed array one constructor @param shape the shape of the array @param dtype the numpy data type @param numGhosts the number of ghosts (>= 0)
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score return _d...
Return a json dictionary representing this model.
def update_one_time_key_counts(self, counts): """Update data on one-time keys count and upload new ones if necessary. Args: counts (dict): Counts of keys currently on the HS for each key type. """ self.one_time_keys_manager.server_counts = counts if self.one_time_key...
Update data on one-time keys count and upload new ones if necessary. Args: counts (dict): Counts of keys currently on the HS for each key type.
def export(export_path, vocabulary, embeddings, num_oov_buckets, preprocess_text): """Exports a TF-Hub module that performs embedding lookups. Args: export_path: Location to export the module. vocabulary: List of the N tokens in the vocabulary. embeddings: Numpy array of shape [N+K,M] the fi...
Exports a TF-Hub module that performs embedding lookups. Args: export_path: Location to export the module. vocabulary: List of the N tokens in the vocabulary. embeddings: Numpy array of shape [N+K,M] the first N rows are the M dimensional embeddings for the respective tokens and the next K ro...
def add_data(self, data, table, delimiter='|', bands='', clean_up=True, rename_columns={}, column_fill={}, verbose=False): """ Adds data to the specified database table. Column names must match table fields to insert, however order and completeness don't matter. Parameters ...
Adds data to the specified database table. Column names must match table fields to insert, however order and completeness don't matter. Parameters ---------- data: str, array-like, astropy.table.Table The path to an ascii file, array-like object, or table. The first ...
def new_with_array(self, array): """ Parameters ---------- array: ndarray An ndarray Returns ------- new_array: ScaledSquarePixelArray A new instance of this class that shares all of this instances attributes with a new ndarray. ""...
Parameters ---------- array: ndarray An ndarray Returns ------- new_array: ScaledSquarePixelArray A new instance of this class that shares all of this instances attributes with a new ndarray.
def _read_requirements(metadata, extras): """Read wheel metadata to know what it depends on. The `run_requires` attribute contains a list of dict or str specifying requirements. For dicts, it may contain an "extra" key to specify these requirements are for a specific extra. Unfortunately, not all field...
Read wheel metadata to know what it depends on. The `run_requires` attribute contains a list of dict or str specifying requirements. For dicts, it may contain an "extra" key to specify these requirements are for a specific extra. Unfortunately, not all fields are specificed like this (I don't know why)...
def business_match_query(self, **kwargs): """ Query the Yelp Business Match API. documentation: https://www.yelp.com/developers/documentation/v3/business_match required parameters: * name - business name * city * s...
Query the Yelp Business Match API. documentation: https://www.yelp.com/developers/documentation/v3/business_match required parameters: * name - business name * city * state * country * address1 ...
def return_multiple_convert_numpy_base(dbpath, folder_path, set_object, start_id, end_id, converter, add_args=None): """ Generic function which converts several objects, with ids in the range (start_id, end_id) into a 2d numpy array and returns the array, the conversion is done by the 'converter' function ...
Generic function which converts several objects, with ids in the range (start_id, end_id) into a 2d numpy array and returns the array, the conversion is done by the 'converter' function Parameters ---------- dbpath : string, path to SQLite database file folder_path : string, path to folder where th...
def enforce(self, rule, target, creds, exc=None, *args, **kwargs): """Checks authorization of a rule against the target and credentials.""" self.load_rules() if isinstance(rule, checks.BaseCheck): result = rule(target, creds, self, rule) elif not self.rules: # N...
Checks authorization of a rule against the target and credentials.
def _regex_flags_from_bits(self, bits): """Return the textual equivalent of numerically encoded regex flags.""" flags = 'ilmsuxa' return ''.join(flags[i - 1] if (1 << i) & bits else '' for i in range(1, len(flags) + 1))
Return the textual equivalent of numerically encoded regex flags.
def commit_input_persist_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") commit = ET.Element("commit") config = commit input = ET.SubElement(commit, "input") persist_id = ET.SubElement(input, "persist-id") persist_id.text = kwa...
Auto Generated Code
def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network, hourly, monthly, tag, columns, limit): """List virtual servers.""" vsi = SoftLayer.VSManager(env.client) guests = vsi.list_instances(hourly=hourly, monthly=monthly, ...
List virtual servers.
def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, ...
MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded. host : str (N...
def grouping_val(self): """ Return the value of the ``./c:grouping{val=?}`` attribute, taking defaults into account when items are not present. """ grouping = self.grouping if grouping is None: return ST_Grouping.CLUSTERED val = grouping.val if...
Return the value of the ``./c:grouping{val=?}`` attribute, taking defaults into account when items are not present.
def get_social_accounts(user): """ {% get_social_accounts user as accounts %} Then: {{accounts.twitter}} -- a list of connected Twitter accounts {{accounts.twitter.0}} -- the first Twitter account {% if accounts %} -- if there is at least one social account """ accounts = {}...
{% get_social_accounts user as accounts %} Then: {{accounts.twitter}} -- a list of connected Twitter accounts {{accounts.twitter.0}} -- the first Twitter account {% if accounts %} -- if there is at least one social account
def pages(self): """ The aggregate pages of all the parser objects. """ pages = [] for har_dict in self.har_data: har_parser = HarParser(har_data=har_dict) if self.page_id: for page in har_parser.pages: if page.page_id =...
The aggregate pages of all the parser objects.
def __netjson_channel_width(self, radio): """ determines NetJSON channel_width radio attribute """ htmode = radio.pop('htmode') if htmode == 'NONE': return 20 channel_width = htmode.replace('VHT', '').replace('HT', '') # we need to override htmode ...
determines NetJSON channel_width radio attribute
def update(self): """Update the ports list.""" if self.input_method == 'local': # Only refresh: # * if there is not other scanning thread # * every refresh seconds (define in the configuration file) if self._thread is None: thread_is_runnin...
Update the ports list.
def unwrap(tensor): """Returns the underlying tensor if tensor is wrapped or tensor. Args: tensor: The tensor to unwrap. Returns: Tensor or if it is a pretty tensor, the unwrapped version. Raises: ValueError: if tensor holds a sequence. """ while isinstance(tensor, (PrettyTensor, Loss)): te...
Returns the underlying tensor if tensor is wrapped or tensor. Args: tensor: The tensor to unwrap. Returns: Tensor or if it is a pretty tensor, the unwrapped version. Raises: ValueError: if tensor holds a sequence.
def structure_to_abivars(structure, **kwargs): """ Receives a structure and returns a dictionary with the ABINIT variables. """ if not structure.is_ordered: raise ValueError("""\ Received disordered structure with partial occupancies that cannot be converted into an Abinit input Please use Order...
Receives a structure and returns a dictionary with the ABINIT variables.
def snmp_server_group_write(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") group = ET.SubElement(snmp_server, "group") group_name_key = ET.SubElement(g...
Auto Generated Code
def controlled_by(self, *control_qubits: Qid) -> 'Operation': """Returns a controlled version of this operation. Args: control_qubits: Qubits to control the operation by. Required. """ # Avoids circular import. from cirq.ops import ControlledOperation if cont...
Returns a controlled version of this operation. Args: control_qubits: Qubits to control the operation by. Required.
def addEvent(self, event, fd, action): """ Add a new win32 event to the event loop. """ self._events[event] = (fd, action)
Add a new win32 event to the event loop.
def as_dict(self, **extra): """ Converts all available emails to dictionaries. :return: List of dictionaries. """ return [self._construct_email(email, **extra) for email in self.emails]
Converts all available emails to dictionaries. :return: List of dictionaries.
def remove(self, container, force=True, volumes=True): """ Remove a container. :param container: The container to remove. :param force: Whether to force the removal of the container, even if it is running. Note that this defaults to True, unlike the Docker ...
Remove a container. :param container: The container to remove. :param force: Whether to force the removal of the container, even if it is running. Note that this defaults to True, unlike the Docker default. :param volumes: Whether to remove any vo...
def _write_widget(self, val): """Writes value into the widget. If specified, user setter is invoked.""" self._itsme = True try: setter = self._wid_info[self._wid][1] wtype = self._wid_info[self._wid][2] if setter: if wtype is not None: ...
Writes value into the widget. If specified, user setter is invoked.
def delete_channel_cb(self, viewer, channel): """Called when a channel is deleted from the main interface. Parameter is a channel (a Channel object).""" chname = channel.name del self.name_dict[chname] # Unhighlight un_hilite_set = set([]) for path in self._hl_pa...
Called when a channel is deleted from the main interface. Parameter is a channel (a Channel object).
def set_flair(self, subreddit, item, flair_text='', flair_css_class=''): """Set flair for the user in the given subreddit. `item` can be a string, Redditor object, or Submission object. If `item` is a string it will be treated as the name of a Redditor. This method can only be called b...
Set flair for the user in the given subreddit. `item` can be a string, Redditor object, or Submission object. If `item` is a string it will be treated as the name of a Redditor. This method can only be called by a subreddit moderator with flair permissions. To set flair on yourself or ...
def replace_blocks(self, blocks): """Replace multiple blocks. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data, flags)""" start = 0 bulk_insert = self.bulk_insert blocks_len = len(blocks) select = 'SELECT ?,?,?,?,?' query ...
Replace multiple blocks. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data, flags)
def install(self, goal=None, first=False, replace=False, before=None, after=None): """Install the task in the specified goal (or a new goal with the same name as the task). The placement of the task in the execution list of the goal defaults to the end but can be :rtype : object influence by specifying...
Install the task in the specified goal (or a new goal with the same name as the task). The placement of the task in the execution list of the goal defaults to the end but can be :rtype : object influence by specifying exactly one of the following arguments: :API: public :param first: Places this ...
def update_PCA_box(self): """ updates PCA box with current fit's PCA type """ if self.s in list(self.pmag_results_data['specimens'].keys()): if self.current_fit: tmin = self.current_fit.tmin tmax = self.current_fit.tmax calcula...
updates PCA box with current fit's PCA type
def set_source(self, propname, pores): r""" Applies a given source term to the specified pores Parameters ---------- propname : string The property name of the source term model to be applied pores : array_like The pore indices where the source t...
r""" Applies a given source term to the specified pores Parameters ---------- propname : string The property name of the source term model to be applied pores : array_like The pore indices where the source term should be applied Notes --...
def _update_limits_from_api(self): """ Query ELB's DescribeAccountLimits API action, and update limits with the quotas returned. Updates ``self.limits``. """ self.connect() logger.debug("Querying ELB DescribeAccountLimits for limits") attribs = self.conn.describe_...
Query ELB's DescribeAccountLimits API action, and update limits with the quotas returned. Updates ``self.limits``.
def _aggregrate_scores(its,tss,num_sentences): """rerank the two vectors by min aggregrate rank, reorder""" final = [] for i,el in enumerate(its): for j, le in enumerate(tss): if el[2] == le[2]: assert el[1] == le[1] final.append((el[1],i+j,el[2])) ...
rerank the two vectors by min aggregrate rank, reorder
def allowed_info_messages(*info_messages): """ Decorator ignoring defined info messages at the end of test method. As param use what :py:meth:`~.WebdriverWrapperInfoMixin.get_info_messages` returns. .. versionadded:: 2.0 """ def wrapper(func): setattr(func, ALLOWED_INFO_MESSAGES...
Decorator ignoring defined info messages at the end of test method. As param use what :py:meth:`~.WebdriverWrapperInfoMixin.get_info_messages` returns. .. versionadded:: 2.0
def obfuscate(cls, idStr): """ Mildly obfuscates the specified ID string in an easily reversible fashion. This is not intended for security purposes, but rather to dissuade users from depending on our internal ID structures. """ return unicode(base64.urlsafe_b64encode( ...
Mildly obfuscates the specified ID string in an easily reversible fashion. This is not intended for security purposes, but rather to dissuade users from depending on our internal ID structures.
def get_extension_classes(): """ Hotdoc's setuptools entry point """ res = [SyntaxHighlightingExtension, SearchExtension, TagExtension, DevhelpExtension, LicenseExtension, GitUploadExtension, EditOnGitHubExtension] if sys.version_info[1] >= 5: res += [DBusExtension] ...
Hotdoc's setuptools entry point
def magic_file(filename): """ Returns tuple of (num_of_matches, array_of_matches) arranged highest confidence match first. :param filename: path to file :return: list of possible matches, highest confidence first """ head, foot = _file_details(filename) if not head: raise ValueError...
Returns tuple of (num_of_matches, array_of_matches) arranged highest confidence match first. :param filename: path to file :return: list of possible matches, highest confidence first
def file_to_md5(filename, block_size=8192): """Calculate the md5 hash of a file. Memory-friendly solution, it reads the file piece by piece. See stackoverflow.com/questions/1131220/ :param filename: filename to convert :param block_size: size of block :return: MD5 hash of file content """ m...
Calculate the md5 hash of a file. Memory-friendly solution, it reads the file piece by piece. See stackoverflow.com/questions/1131220/ :param filename: filename to convert :param block_size: size of block :return: MD5 hash of file content
def _map_trajectory(self): """ Return filepath as a class attribute""" self.trajectory_map = {} with open(self.filepath, 'r') as trajectory_file: with closing( mmap( trajectory_file.fileno(), 0, access=ACCESS_READ)) ...
Return filepath as a class attribute
def _GetDenseDimensions(list_of_lists): """Returns the inferred dense dimensions of a list of lists.""" if not isinstance(list_of_lists, (list, tuple)): return [] elif not list_of_lists: return [0] else: return [len(list_of_lists)] + _GetDenseDimensions(list_of_lists[0])
Returns the inferred dense dimensions of a list of lists.
def wrap_class(cls, error_threshold=None): ''' Wraps a class with reporting to errors backend by decorating each function of the class. Decorators are injected under the classmethod decorator if they exist. ''' methods = inspect.getmembers(cls, inspect.ismethod) + inspect.getmembers(cls, inspect...
Wraps a class with reporting to errors backend by decorating each function of the class. Decorators are injected under the classmethod decorator if they exist.
def run_backdoor(address, namespace=None): """start a server that runs python interpreters on connections made to it .. note:: this function blocks effectively indefinitely -- it runs the listening socket loop in the current greenlet. to keep the current greenlet free, :func:`schedule<...
start a server that runs python interpreters on connections made to it .. note:: this function blocks effectively indefinitely -- it runs the listening socket loop in the current greenlet. to keep the current greenlet free, :func:`schedule<greenhouse.scheduler.schedule>` this function. ...
def get_scanner(self, skey): """Find the appropriate scanner given a key (usually a file suffix). """ if skey and self['PLATFORM'] == 'win32': skey = skey.lower() return self._gsm().get(skey)
Find the appropriate scanner given a key (usually a file suffix).
def assign_global_ip(self, global_ip_id, target): """Assigns a global IP address to a specified target. :param int global_ip_id: The ID of the global IP being assigned :param string target: The IP address to assign """ return self.client['Network_Subnet_IpAddress_Global'].route(...
Assigns a global IP address to a specified target. :param int global_ip_id: The ID of the global IP being assigned :param string target: The IP address to assign
def _merge_array(lhs, rhs, type_): """Helper for '_merge_by_type'.""" element_type = type_.array_element_type if element_type.code in _UNMERGEABLE_TYPES: # Individual values cannot be merged, just concatenate lhs.list_value.values.extend(rhs.list_value.values) return lhs lhs, rhs...
Helper for '_merge_by_type'.
def _EncodeUnknownFields(message): """Remap unknown fields in message out of message.source.""" source = _UNRECOGNIZED_FIELD_MAPPINGS.get(type(message)) if source is None: return message # CopyProtoMessage uses _ProtoJsonApiTools, which uses this message. Use # the vanilla protojson-based co...
Remap unknown fields in message out of message.source.
def objects_for_push_notification(notification): """Decode a push notification with the given body XML. Returns a dictionary containing the constituent objects of the push notification. The kind of push notification is given in the ``"type"`` member of the returned dictionary. """ notification...
Decode a push notification with the given body XML. Returns a dictionary containing the constituent objects of the push notification. The kind of push notification is given in the ``"type"`` member of the returned dictionary.
def encode_bbox_target(boxes, anchors): """ Args: boxes: (..., 4), float32 anchors: (..., 4), float32 Returns: box_encoded: (..., 4), float32 with the same shape. """ anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2)) anchors_x1y1, anchors_x2y2 = tf.split(anchors_x1y1x2y...
Args: boxes: (..., 4), float32 anchors: (..., 4), float32 Returns: box_encoded: (..., 4), float32 with the same shape.
def delete_tracking_beacon(self, tracking_beacons_id, **data): """ DELETE /tracking_beacons/:tracking_beacons_id/ Delete the :format:`tracking_beacons` with the specified :tracking_beacons_id. """ return self.delete("/tracking_beacons/{0}/".format(tracking_beacons_id), d...
DELETE /tracking_beacons/:tracking_beacons_id/ Delete the :format:`tracking_beacons` with the specified :tracking_beacons_id.
def prepare_destruction(self, recursive=True): """Prepares the model for destruction Recursively un-registers all observers and removes references to child models. Extends the destroy method of the base class by child elements of a container state. """ # logger.verbose("Prepare ...
Prepares the model for destruction Recursively un-registers all observers and removes references to child models. Extends the destroy method of the base class by child elements of a container state.
def flatten(l): """Flatten a nested list.""" return sum(map(flatten, l), []) \ if isinstance(l, list) or isinstance(l, tuple) else [l]
Flatten a nested list.
def com(self): """Center of mass, calculated from the mean of the PMT positions""" if self._com is None: self._com = np.mean(self.pmts.pos, axis=0) return self._com
Center of mass, calculated from the mean of the PMT positions
def _populate_trace(self, graph: TraceGraph, trace_frame_ids: List[int]) -> None: """ Populates (from the given trace graph) the forward and backward traces reachable from the given traces (including input trace frames). Make sure to respect trace kind in successors """ while len...
Populates (from the given trace graph) the forward and backward traces reachable from the given traces (including input trace frames). Make sure to respect trace kind in successors
def poll(self, event, timeout=None): """Wait for a socket event. Posssible *event* values are the strings "recv", "send" and "acks". Whent the timeout is present and not :const:`None`, it should be a floating point number specifying the timeout for the operation in seconds (or fr...
Wait for a socket event. Posssible *event* values are the strings "recv", "send" and "acks". Whent the timeout is present and not :const:`None`, it should be a floating point number specifying the timeout for the operation in seconds (or fractions thereof). For "recv" or "send" the :meth...
def parse_data_directories(self, directories=None, forwarded_exports_only=False, import_dllnames_only=False): """Parse and process the PE file's data directories. If the optional argument 'directories' is given, only the directories ...
Parse and process the PE file's data directories. If the optional argument 'directories' is given, only the directories at the specified indexes will be parsed. Such functionality allows parsing of areas of interest without the burden of having to parse all others. The directori...
def serializeEc(P, compress=True): """ Generates a compact binary version of this point. """ return _serialize(P, compress, librelic.ec_size_bin_abi, librelic.ec_write_bin_abi)
Generates a compact binary version of this point.
def LAST(COND, N1, N2): """表达持续性 从前N1日到前N2日一直满足COND条件 Arguments: COND {[type]} -- [description] N1 {[type]} -- [description] N2 {[type]} -- [description] """ N2 = 1 if N2 == 0 else N2 assert N2 > 0 assert N1 > N2 return COND.iloc[-N1:-N2].all()
表达持续性 从前N1日到前N2日一直满足COND条件 Arguments: COND {[type]} -- [description] N1 {[type]} -- [description] N2 {[type]} -- [description]
def generation(self): """Returns the number of ancestors that are dictionaries""" if not self.parent: return 0 elif self.parent.is_dict: return 1 + self.parent.generation else: return self.parent.generation
Returns the number of ancestors that are dictionaries
def add(self, item): """ Add an item to the work queue. :param item: The work item to add. An item may be of any type; however, if it is not hashable, then the work queue must either be initialized with ``unique`` set to ``False``,...
Add an item to the work queue. :param item: The work item to add. An item may be of any type; however, if it is not hashable, then the work queue must either be initialized with ``unique`` set to ``False``, or a ``key`` callab...
def once(ctx, name): """Run kibitzr checks once and exit""" from kibitzr.app import Application app = Application() sys.exit(app.run(once=True, log_level=ctx.obj['log_level'], names=name))
Run kibitzr checks once and exit
def min(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the minimum function. Args: x: The first operand. y: The second operand. Returns: A TensorFluent wrapping the minimum function. ''' return cls...
Returns a TensorFluent for the minimum function. Args: x: The first operand. y: The second operand. Returns: A TensorFluent wrapping the minimum function.
def center_mass_exp(interval, scale=1.0): """ Calculate the center of mass of negative exponential distribution p(x) = exp(-x / scale) / scale in the interval of (interval_left, interval_right). scale is the same scale parameter as scipy.stats.expon.pdf Parameters ---------- in...
Calculate the center of mass of negative exponential distribution p(x) = exp(-x / scale) / scale in the interval of (interval_left, interval_right). scale is the same scale parameter as scipy.stats.expon.pdf Parameters ---------- interval: size 2 tuple, float interval must ...
def decode(self, encoding='utf-8', errors='strict'): """ Returns a newstr (i.e. unicode subclass) Decode B using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encodi...
Returns a newstr (i.e. unicode subclass) Decode B using the codec registered for encoding. Default encoding is 'utf-8'. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are ...
def get_reply(self, param, must=[APIKEY, START_TIME, END_TIME, PAGE_NUM, PAGE_SIZE]): '''查回复的短信 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 start_time String 是 短信回复开始时间 2013-08-11 00:00:00 end_time String 是 短信回复结束时间 2013-08-12 00:00:00 ...
查回复的短信 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 start_time String 是 短信回复开始时间 2013-08-11 00:00:00 end_time String 是 短信回复结束时间 2013-08-12 00:00:00 page_num Integer 是 页码,默认值为1 1 page_size Integer 是 每页个数,最大100个 20 mobile String...
def get_model_agents(self): """Return a list of all Agents from all Statements. Returns ------- agents : list[indra.statements.Agent] A list of Agents that are in the model. """ model_stmts = self.get_statements() agents = [] for stmt in model_...
Return a list of all Agents from all Statements. Returns ------- agents : list[indra.statements.Agent] A list of Agents that are in the model.
def enqueue(self, s): """ Append `s` to the queue. Equivalent to:: queue += s if `queue` where a regular string. """ self._parts.append(s) self._len += len(s)
Append `s` to the queue. Equivalent to:: queue += s if `queue` where a regular string.
def configure_upload(self, ns, definition): """ Register an upload endpoint. The definition's func should be an upload function, which must: - accept kwargs for path data and query string parameters - accept a list of tuples of the form (formname, tempfilepath, filename) ...
Register an upload endpoint. The definition's func should be an upload function, which must: - accept kwargs for path data and query string parameters - accept a list of tuples of the form (formname, tempfilepath, filename) - optionally return a resource :param ns: the namespac...
def create_role(self, name): '''Create a new :class:`Role` owned by this :class:`Subject`''' models = self.session.router return models.role.new(name=name, owner=self)
Create a new :class:`Role` owned by this :class:`Subject`
def get_abs_and_rel_paths(self, root_path, file_name, input_dir): """ Return absolute and relative path for file :type root_path: str|unicode :type file_name: str|unicode :type input_dir: str|unicode :rtype: tuple """ # todo: change relative path resolvi...
Return absolute and relative path for file :type root_path: str|unicode :type file_name: str|unicode :type input_dir: str|unicode :rtype: tuple
def download_post(self, post: Post, target: str) -> bool: """ Download everything associated with one instagram post node, i.e. picture, caption and video. :param post: Post to download. :param target: Target name, i.e. profile name, #hashtag, :feed; for filename. :return: True ...
Download everything associated with one instagram post node, i.e. picture, caption and video. :param post: Post to download. :param target: Target name, i.e. profile name, #hashtag, :feed; for filename. :return: True if something was downloaded, False otherwise, i.e. file was already there
def get_orm_columns(cls: Type) -> List[Column]: """ Gets :class:`Column` objects from an SQLAlchemy ORM class. Does not provide their attribute names. """ mapper = inspect(cls) # type: Mapper # ... returns InstanceState if called with an ORM object # http://docs.sqlalchemy.org/en/latest...
Gets :class:`Column` objects from an SQLAlchemy ORM class. Does not provide their attribute names.
def p_member_expr(self, p): """member_expr : primary_expr | function_expr | member_expr LBRACKET expr RBRACKET | member_expr PERIOD identifier | NEW member_expr arguments """ if len(p) == 2: p...
member_expr : primary_expr | function_expr | member_expr LBRACKET expr RBRACKET | member_expr PERIOD identifier | NEW member_expr arguments
def update(cls, name=None, public_nick_name=None, avatar_uuid=None, address_main=None, address_postal=None, language=None, region=None, country=None, ubo=None, chamber_of_commerce_number=None, legal_form=None, status=None, sub_status=None, session_timeout=None...
Modify a specific company's data. :type user_company_id: int :param name: The company name. :type name: str :param public_nick_name: The company's nick name. :type public_nick_name: str :param avatar_uuid: The public UUID of the company's avatar. :type avatar_uui...
def pack(self, value, nocheck=False, major=DEFAULT_KATCP_MAJOR): """Return the value formatted as a KATCP parameter. Parameters ---------- value : object The value to pack. nocheck : bool, optional Whether to check that the value is valid before ...
Return the value formatted as a KATCP parameter. Parameters ---------- value : object The value to pack. nocheck : bool, optional Whether to check that the value is valid before packing it. major : int, optional Major version of KA...