code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'dialog_node') and self.dialog_node is not None: _dict['dialog_node'] = self.dialog_node if hasattr(self, 'description') and self.description is not None: _dict...
Return a json dictionary representing this model.
def aggregate_weights(weights, drop_date=False): """ Transforms list of tuples of weights into pandas.DataFrame of weights. Parameters: ----------- weights: list A list of tuples consisting of the generic instrument name, the tradeable contract as a string, the weight on this contra...
Transforms list of tuples of weights into pandas.DataFrame of weights. Parameters: ----------- weights: list A list of tuples consisting of the generic instrument name, the tradeable contract as a string, the weight on this contract as a float and the date as a pandas.Timestamp. ...
def init(names, host=None, saltcloud_mode=False, quiet=False, **kwargs): ''' Initialize a new container .. code-block:: bash salt-run lxc.init name host=minion_id [cpuset=cgroups_cpuset] \\ [cpushare=cgroups_cpushare] [memory=cgroups_memory] \\ [template=lxc_templa...
Initialize a new container .. code-block:: bash salt-run lxc.init name host=minion_id [cpuset=cgroups_cpuset] \\ [cpushare=cgroups_cpushare] [memory=cgroups_memory] \\ [template=lxc_template_name] [clone=original name] \\ [profile=lxc_profile] [network_prof...
def sources_to_nr_vars(sources): """ Converts a source type to number of sources mapping into a source numbering variable to number of sources mapping. If, for example, we have 'point', 'gaussian' and 'sersic' source types, then passing the following dict as an argument sources_to_nr_vars({'po...
Converts a source type to number of sources mapping into a source numbering variable to number of sources mapping. If, for example, we have 'point', 'gaussian' and 'sersic' source types, then passing the following dict as an argument sources_to_nr_vars({'point':10, 'gaussian': 20}) will return an...
def connect_from(self, vertex, weight=1): """ Connect another vertex to this one. Args: vertex (Vertex): vertex to connect from. weight (int): weight of the edge. Returns: Edge: the newly created edge. """ for edge in self.edges_in: ...
Connect another vertex to this one. Args: vertex (Vertex): vertex to connect from. weight (int): weight of the edge. Returns: Edge: the newly created edge.
def f_measure(precision, recall, beta=1.0): """Compute the f-measure from precision and recall scores. Parameters ---------- precision : float in (0, 1] Precision recall : float in (0, 1] Recall beta : float > 0 Weighting factor for f-measure (Default value = 1.0...
Compute the f-measure from precision and recall scores. Parameters ---------- precision : float in (0, 1] Precision recall : float in (0, 1] Recall beta : float > 0 Weighting factor for f-measure (Default value = 1.0) Returns ------- f_measure : float ...
def get_distinct_values_from_cols(self, l_col_list): """ returns the list of distinct combinations in a dataset based on the columns in the list. Note that this is currently implemented as MAX permutations of the combo so it is not guarenteed to have values in each case. ...
returns the list of distinct combinations in a dataset based on the columns in the list. Note that this is currently implemented as MAX permutations of the combo so it is not guarenteed to have values in each case.
def _create_hosting_device_templates_from_config(self): """To be called late during plugin initialization so that any hosting device templates defined in the config file is properly inserted in the DB. """ hdt_dict = config.get_specific_config('cisco_hosting_device_template') ...
To be called late during plugin initialization so that any hosting device templates defined in the config file is properly inserted in the DB.
def send_response(self, response): """Send a unicode object as reply to the most recently-issued command """ response_bytes = response.encode(config.CODEC) log.debug("About to send reponse: %r", response_bytes) self.socket.send(response_bytes)
Send a unicode object as reply to the most recently-issued command
def transform_cb(self, setting, value): """Handle callback related to changes in transformations.""" self.make_callback('transform') # whence=0 because need to calculate new extents for proper # cutout for rotation (TODO: always make extents consider # room for rotation) ...
Handle callback related to changes in transformations.
def solution(self, x0, y0): """ Create a solution function ``y(x)`` such that ``y(x0) = y0``. A list of solution values ``[y(x0), y(x1) ...]`` is returned if the function is called with a list ``[x0, x1 ...]`` of ``x`` values. """ def soln(x): if numpy.size(x) > 1: ...
Create a solution function ``y(x)`` such that ``y(x0) = y0``. A list of solution values ``[y(x0), y(x1) ...]`` is returned if the function is called with a list ``[x0, x1 ...]`` of ``x`` values.
def cmd_create(self, name, auto=False): """Create a new migration.""" LOGGER.setLevel('INFO') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_table=self.app.config['PEEWEE_MIG...
Create a new migration.
def astra_parallel_3d_geom_to_vec(geometry): """Create vectors for ASTRA projection geometries from ODL geometry. The 3D vectors are used to create an ASTRA projection geometry for parallel beam geometries, see ``'parallel3d_vec'`` in the `ASTRA projection geometry documentation`_. Each row of the...
Create vectors for ASTRA projection geometries from ODL geometry. The 3D vectors are used to create an ASTRA projection geometry for parallel beam geometries, see ``'parallel3d_vec'`` in the `ASTRA projection geometry documentation`_. Each row of the returned vectors corresponds to a single projection...
def events_system(self): """ Get all system events. Uses GET to /events/system interface. :Returns: (list) Events """ # TODO Add paging to this response = self._get(url.events_system) self._check_response(response, 200) return self._create_response(respo...
Get all system events. Uses GET to /events/system interface. :Returns: (list) Events
def translate_changes(initial_change): """Translate rope.base.change.Change instances to dictionaries. See Refactor.get_changes for an explanation of the resulting dictionary. """ agenda = [initial_change] result = [] while agenda: change = agenda.pop(0) if isinstance(chang...
Translate rope.base.change.Change instances to dictionaries. See Refactor.get_changes for an explanation of the resulting dictionary.
def object_as_dict(obj): """Turn an SQLAlchemy model into a dict of field names and values. Based on https://stackoverflow.com/a/37350445/1579058 """ return {c.key: getattr(obj, c.key) for c in inspect(obj).mapper.column_attrs}
Turn an SQLAlchemy model into a dict of field names and values. Based on https://stackoverflow.com/a/37350445/1579058
def p_arr_decl_initialized(p): """ var_arr_decl : DIM idlist LP bound_list RP typedef RIGHTARROW const_vector | DIM idlist LP bound_list RP typedef EQ const_vector """ def check_bound(boundlist, remaining): """ Checks if constant vector bounds matches the array one """ ...
var_arr_decl : DIM idlist LP bound_list RP typedef RIGHTARROW const_vector | DIM idlist LP bound_list RP typedef EQ const_vector
def remove(self, nodes): """Remove a node and its edges.""" nodes = nodes if isinstance(nodes, list) else [nodes] for node in nodes: k = self.id(node) self.edges = list(filter(lambda e: e[0] != k and e[1] != k, self.edges)) del self.nodes[k]
Remove a node and its edges.
def indexXY(self, index): """Returns the top left coordinates of the item for the given index :param index: index for the item :type index: :qtdoc:`QModelIndex` :returns: (int, int) -- (x, y) view coordinates of item """ rect = self.visualRect(index) return rect....
Returns the top left coordinates of the item for the given index :param index: index for the item :type index: :qtdoc:`QModelIndex` :returns: (int, int) -- (x, y) view coordinates of item
def is_contiguous(self): """Return offset and size of contiguous data, else None.""" if self._keyframe is None: raise RuntimeError('keyframe not set') if self._keyframe.is_contiguous: return self._offsetscounts[0][0], self._keyframe.is_contiguous[1] return None
Return offset and size of contiguous data, else None.
def __serve_forever(self): """Main client loop.""" # No need to update the server list # It's done by the GlancesAutoDiscoverListener class (autodiscover.py) # Or define staticaly in the configuration file (module static_list.py) # For each server in the list, grab elementary sta...
Main client loop.
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: AvailablePhoneNumberCountryContext for this AvailablePhoneNumberCountryInstance :rtype: twilio.re...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: AvailablePhoneNumberCountryContext for this AvailablePhoneNumberCountryInstance :rtype: twilio.rest.api.v2010.account.available_phone_n...
def submit_all(self): """ :returns: an IterResult object """ for args in self.task_args: self.submit(*args) return self.get_results()
:returns: an IterResult object
def fast_kde(x, y, gridsize=(200,200), extents=None, nocorrelation=False, weights=None): """ Performs a gaussian kernel density estimate over a regular grid using a convolution of the gaussian kernel with a 2D histogram of the data. This function is typically several orders of magnitude faster than ...
Performs a gaussian kernel density estimate over a regular grid using a convolution of the gaussian kernel with a 2D histogram of the data. This function is typically several orders of magnitude faster than scipy.stats.kde.gaussian_kde for large (>1e7) numbers of points and produces an essentially id...
def zone(self) -> Optional[str]: """Zone the device is assigned to.""" if self._device_category == DC_BASEUNIT: return None return '{:02x}-{:02x}'.format(self._group_number, self._unit_number)
Zone the device is assigned to.
def compiled_quil(self): """ If the Quil program associated with the Job was compiled (e.g., to translate it to the QPU's natural gateset) return this compiled program. :rtype: Optional[Program] """ prog = self._raw.get("program", {}).get("compiled-quil", None) i...
If the Quil program associated with the Job was compiled (e.g., to translate it to the QPU's natural gateset) return this compiled program. :rtype: Optional[Program]
def line(self, lines): """Creates a POLYLINE shape. Lines is a collection of lines, each made up of a list of xy values.""" shapeType = POLYLINE self._shapeparts(parts=lines, shapeType=shapeType)
Creates a POLYLINE shape. Lines is a collection of lines, each made up of a list of xy values.
def readlink(self, path): """ Return the target of a symbolic link (shortcut). You can use L{symlink} to create these. The result may be either an absolute or relative pathname. @param path: path of the symbolic link file @type path: str @return: target path ...
Return the target of a symbolic link (shortcut). You can use L{symlink} to create these. The result may be either an absolute or relative pathname. @param path: path of the symbolic link file @type path: str @return: target path @rtype: str
def write_xml(xml, output_file=None): """Outputs the XML content into a file.""" gen_filename = "requirements-{:%Y%m%d%H%M%S}.xml".format(datetime.datetime.now()) utils.write_xml(xml, output_loc=output_file, filename=gen_filename)
Outputs the XML content into a file.
def missing_parameter_values(self, parameter_values): """ Checks if the given input contains values for all parameters used by this template :param dict parameter_values: Dictionary of values for each parameter used in the template :return list: List of names of parameters that are miss...
Checks if the given input contains values for all parameters used by this template :param dict parameter_values: Dictionary of values for each parameter used in the template :return list: List of names of parameters that are missing. :raises InvalidParameterValues: When parameter values is not ...
def getDataset(self, itemId): """gets a dataset class""" if self._url.lower().find('datasets') > -1: url = self._url else: url = self._url + "/datasets" return OpenDataItem(url=url, itemId=itemId, securityHan...
gets a dataset class
def get_profile( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the specified profile. Example: >>> from google.cloud import talent_v4beta1 ...
Gets the specified profile. Example: >>> from google.cloud import talent_v4beta1 >>> >>> client = talent_v4beta1.ProfileServiceClient() >>> >>> name = client.profile_path('[PROJECT]', '[TENANT]', '[PROFILE]') >>> >>> response =...
def get_collection_instance(klass, api_client = None, request_api=True, **kwargs): """ instatiates the collection lookup of json type klass :param klass: json file name :param api_client: transportation api :param request_api: if True uses the default APIClient """ _type = klass if api_c...
instatiates the collection lookup of json type klass :param klass: json file name :param api_client: transportation api :param request_api: if True uses the default APIClient
def stickers_translate_get(self, api_key, s, **kwargs): """ Sticker Translate Endpoint The translate API draws on search, but uses the Giphy `special sauce` to handle translating from one vocabulary to another. In this case, words and phrases to GIFs. This method makes a synchronous HTTP...
Sticker Translate Endpoint The translate API draws on search, but uses the Giphy `special sauce` to handle translating from one vocabulary to another. In this case, words and phrases to GIFs. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please de...
def _competition(self, x): """! @brief Calculates neuron winner (distance, neuron index). @param[in] x (list): Input pattern from the input data set, for example it can be coordinates of point. @return (uint) Returns index of neuron that is winner. ...
! @brief Calculates neuron winner (distance, neuron index). @param[in] x (list): Input pattern from the input data set, for example it can be coordinates of point. @return (uint) Returns index of neuron that is winner.
def _kill_process(self, pid, cgroups=None, sig=signal.SIGKILL): """ Try to send signal to given process, either directly of with sudo. Because we cannot send signals to the sudo process itself, this method checks whether the target is the sudo process and redirects the signal to ...
Try to send signal to given process, either directly of with sudo. Because we cannot send signals to the sudo process itself, this method checks whether the target is the sudo process and redirects the signal to sudo's child in this case.
def _read_register(self, reg): """Read 16 bit register value.""" self.buf[0] = reg with self.i2c_device as i2c: i2c.write(self.buf, end=1, stop=False) i2c.readinto(self.buf, end=2) return self.buf[0] << 8 | self.buf[1]
Read 16 bit register value.
def remove_cache(self, namespace, key=None): """Remove all cached values for the specified namespace, optionally specifying a key""" if key is None: self.cursor.execute('DELETE FROM gauged_cache ' 'WHERE namespace = %s', (namespace,)) else: ...
Remove all cached values for the specified namespace, optionally specifying a key
def coroutine(func): """ A decorator to wrap a generator function into a callable interface. >>> @coroutine ... def sum(count): ... sum = 0 ... for _ in range(0, count): ... # note that generator arguments are passed as a tuple, hence `num, = ...` instead...
A decorator to wrap a generator function into a callable interface. >>> @coroutine ... def sum(count): ... sum = 0 ... for _ in range(0, count): ... # note that generator arguments are passed as a tuple, hence `num, = ...` instead of `num = ...` ... ...
def endswith(self, search_str): """Check whether the provided string exists in Journal file. Only checks the last 5 lines of the journal file. This method is usually used when tracking a journal from an active Revit session. Args: search_str (str): string to search for ...
Check whether the provided string exists in Journal file. Only checks the last 5 lines of the journal file. This method is usually used when tracking a journal from an active Revit session. Args: search_str (str): string to search for Returns: bool: if True the...
def purge(vm_, dirs=False, removables=None, **kwargs): ''' Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy ...
Recursively destroy and delete a persistent virtual machine, pass True for dir's to also delete the directories containing the virtual machine disk images - USE WITH EXTREME CAUTION! Pass removables=False to avoid deleting cdrom and floppy images. To avoid disruption, the default but dangerous value is...
def _infer_all_output_dims(self, inputs): """Calculate the output shape for `inputs` after a deconvolution. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. Returns: output_shape: A tensor of shape (`batch_size`, `conv_output_shap...
Calculate the output shape for `inputs` after a deconvolution. Args: inputs: A Tensor of shape `data_format` and of type `tf.float16`, `tf.bfloat16` or `tf.float32`. Returns: output_shape: A tensor of shape (`batch_size`, `conv_output_shape`).
def more_than_one_error(self, field): """Logs a more than one error. field is the field/property that has more than one defined. """ msg = 'More than one {0} defined.'.format(field) self.logger.log(msg) self.error = True
Logs a more than one error. field is the field/property that has more than one defined.
def from_dynacRepr(cls, pynacRepr): """ Construct a ``AccGap`` instance from the Pynac lattice element """ pynacList = pynacRepr[1][0] L = float(pynacList[3]) TTF = float(pynacList[4]) TTFprime = float(pynacList[5]) TTFprimeprime = float(pynacList[13]) ...
Construct a ``AccGap`` instance from the Pynac lattice element
def distrib_release(): """ Get the release number of the distribution. Example:: from burlap.system import distrib_id, distrib_release if distrib_id() == 'CentOS' and distrib_release() == '6.1': print(u"CentOS 6.2 has been released. Please upgrade.") """ with settings...
Get the release number of the distribution. Example:: from burlap.system import distrib_id, distrib_release if distrib_id() == 'CentOS' and distrib_release() == '6.1': print(u"CentOS 6.2 has been released. Please upgrade.")
def t_IDENTIFER(self, t): r'\#?[a-zA-Z_][a-zA-Z_0-9]*' t.type = SpecParser.reserved.get(t.value, 'IDENTIFIER') return t
r'\#?[a-zA-Z_][a-zA-Z_0-9]*
def write_document(self, document: BioCDocument): """Encode and write a single document.""" tree = self.encoder.encode(document) self.__writer.send(tree)
Encode and write a single document.
def get_hash(fName, readSize, dire=pDir()): """ creates the required hash """ if not fileExists(fName, dire): return -1 readSize = readSize * 1024 # bytes to be read fName = os.path.join(dire, fName) # name coupled with path with open(fName, 'rb') as f: size = os.path.getsize...
creates the required hash
def redact_secrets(line): """ Returns a sanitized string for any ``line`` that looks like it contains a secret (i.e. matches SECRET_PATTERN). """ def redact(match): if match.group(2) in SECRET_WHITELIST: return match.group(0) return match.group(1) + 'TOO_TOO_SEXY' ret...
Returns a sanitized string for any ``line`` that looks like it contains a secret (i.e. matches SECRET_PATTERN).
def pager(__text: str, *, pager: Optional[str] = 'less'): """Pass output through pager. See :manpage:`less(1)`, if you wish to configure the default pager. For example, you may wish to check ``FRSX`` options. Args: __text: Text to page pager: Pager to use """ if pager: ...
Pass output through pager. See :manpage:`less(1)`, if you wish to configure the default pager. For example, you may wish to check ``FRSX`` options. Args: __text: Text to page pager: Pager to use
def has_active_subscription(self, plan=None): """ Checks to see if this customer has an active subscription to the given plan. :param plan: The plan for which to check for an active subscription. If plan is None and there exists only one active subscription, this method will check if that subscription is v...
Checks to see if this customer has an active subscription to the given plan. :param plan: The plan for which to check for an active subscription. If plan is None and there exists only one active subscription, this method will check if that subscription is valid. Calling this method with no plan and multiple va...
def run(self): """Listener method that keeps pulling new messages.""" t_last_click = -1 while True: d = self.device.read(13) if d is not None and self._enabled: if d[0] == 1: ## readings from 6-DoF sensor self.y = convert(d[1], d[2]...
Listener method that keeps pulling new messages.
def count_of_certain_kind(kind): ''' Get the count of certain kind. ''' recs = TabPost.select().where(TabPost.kind == kind) return recs.count()
Get the count of certain kind.
def browse(fileNames=None, inspectorFullName=None, select=None, profile=DEFAULT_PROFILE, resetProfile=False, # TODO: should probably be moved to the main program resetAllProfiles=False, # TODO: should probably be moved to the main program resetRegi...
Opens the main window(s) for the persistent settings of the given profile, and executes the application. :param fileNames: List of file names that will be added to the repository :param inspectorFullName: The full path name of the inspector that will be loaded :param select: a path of t...
def iter_symbols(code): """Yield names and strings used by `code` and its nested code objects""" for name in code.co_names: yield name for const in code.co_consts: if isinstance(const, six.string_types): yield const elif isinstance(const, CodeType): for name i...
Yield names and strings used by `code` and its nested code objects
def set_weight(self, weight): """Set weight of each instance. Parameters ---------- weight : list, numpy 1-D array, pandas Series or None Weight to be set for each data point. Returns ------- self : Dataset Dataset with set weight. ...
Set weight of each instance. Parameters ---------- weight : list, numpy 1-D array, pandas Series or None Weight to be set for each data point. Returns ------- self : Dataset Dataset with set weight.
def stop(self, devices): """Power-Off one or more running devices. """ for device in devices: self.logger.info('Stopping: %s', device.id) try: device.power_off() except packet.baseapi.Error: raise PacketManagerException('Unable ...
Power-Off one or more running devices.
def fw_retry_failures(self): """Top level retry routine called. """ if not self.fw_init: return try: self.fw_retry_failures_create() self.fw_retry_failures_delete() except Exception as exc: LOG.error("Exception in retry failures %s", str(ex...
Top level retry routine called.
def from_dict(cls, data): """Transforms a Python dictionary to an Input object. Note: Optionally, this method can also serialize a Cryptoconditions- Fulfillment that is not yet signed. Args: data (dict): The Input to be transformed. ...
Transforms a Python dictionary to an Input object. Note: Optionally, this method can also serialize a Cryptoconditions- Fulfillment that is not yet signed. Args: data (dict): The Input to be transformed. Returns: :cla...
def connect_to_images(region=None, public=True): """Creates a client for working with Images.""" return _create_client(ep_name="image", region=region, public=public)
Creates a client for working with Images.
def alpha_view(qimage): """Returns alpha view of a given 32-bit color QImage_'s memory. The result is a 2D numpy.uint8 array, equivalent to byte_view(qimage)[...,3]. The image must have 32 bit pixel size, i.e. be RGB32, ARGB32, or ARGB32_Premultiplied. Note that it is not enforced that the given q...
Returns alpha view of a given 32-bit color QImage_'s memory. The result is a 2D numpy.uint8 array, equivalent to byte_view(qimage)[...,3]. The image must have 32 bit pixel size, i.e. be RGB32, ARGB32, or ARGB32_Premultiplied. Note that it is not enforced that the given qimage has a format that actuall...
def add_dicts(*args): """ Adds two or more dicts together. Common keys will have their values added. For example:: >>> t1 = {'a':1, 'b':2} >>> t2 = {'b':1, 'c':3} >>> t3 = {'d':4} >>> add_dicts(t1, t2, t3) {'a': 1, 'c': 3, 'b': 3, 'd': 4} """ counters = [...
Adds two or more dicts together. Common keys will have their values added. For example:: >>> t1 = {'a':1, 'b':2} >>> t2 = {'b':1, 'c':3} >>> t3 = {'d':4} >>> add_dicts(t1, t2, t3) {'a': 1, 'c': 3, 'b': 3, 'd': 4}
def Deserialize(self, reader): """ Deserialize full object. Args: reader (neocore.IO.BinaryReader): """ super(SpentCoinState, self).Deserialize(reader) self.TransactionHash = reader.ReadUInt256() self.TransactionHeight = reader.ReadUInt32() ...
Deserialize full object. Args: reader (neocore.IO.BinaryReader):
def clone(self): """ Create a complete copy of self. :returns: A MaterialPackage that is identical to self. """ result = copy.copy(self) result.compound_masses = copy.deepcopy(self.compound_masses) return result
Create a complete copy of self. :returns: A MaterialPackage that is identical to self.
def parse_version(v): """ Take a string version and conver it to a tuple (for easier comparison), e.g.: "1.2.3" --> (1, 2, 3) "1.2" --> (1, 2, 0) "1" --> (1, 0, 0) """ parts = v.split(".") # Pad the list to make sure there is three elements so that we get maj...
Take a string version and conver it to a tuple (for easier comparison), e.g.: "1.2.3" --> (1, 2, 3) "1.2" --> (1, 2, 0) "1" --> (1, 0, 0)
def create( cls, path, template_engine=None, output_filename=None, output_ext=None, view_name=None ): """Create the relevant subclass of StatikView based on the given path variable and parameters.""" # if it's a comp...
Create the relevant subclass of StatikView based on the given path variable and parameters.
def colon_subscripts(u): """ Array colon subscripts foo(1:10) and colon expressions 1:10 look too similar to each other. Now is the time to find out who is who. """ if u.__class__ in (node.arrayref,node.cellarrayref): for w in u.args: if w.__class__ is node.expr and w.op == ":":...
Array colon subscripts foo(1:10) and colon expressions 1:10 look too similar to each other. Now is the time to find out who is who.
def remove(self, key, column_path, timestamp, consistency_level): """ Remove data from the row specified by key at the granularity specified by column_path, and the given timestamp. Note that all the values in column_path besides column_path.column_family are truly optional: you can remove the entire ro...
Remove data from the row specified by key at the granularity specified by column_path, and the given timestamp. Note that all the values in column_path besides column_path.column_family are truly optional: you can remove the entire row by just specifying the ColumnFamily, or you can remove a SuperColumn or a si...
def fig_to_geojson(fig=None, **kwargs): """ Returns a figure's GeoJSON representation as a dictionary All arguments passed to fig_to_html() Returns ------- GeoJSON dictionary """ if fig is None: fig = plt.gcf() renderer = LeafletRenderer(**kwargs) exporter = Exporter(r...
Returns a figure's GeoJSON representation as a dictionary All arguments passed to fig_to_html() Returns ------- GeoJSON dictionary
def add_type(self, type: type, serialize: Callable[[Any], str], unserialize: Callable[[str], Any]) -> None: """ Adds serialization support for a new type. :param type: The type to add support for. :param serialize: A callable that takes an object of type ``type`` and returns a string. ...
Adds serialization support for a new type. :param type: The type to add support for. :param serialize: A callable that takes an object of type ``type`` and returns a string. :param unserialize: A callable that takes a string and returns an object of type ``type``.
def setText(self, text: str): """ Undo safe wrapper for the native ``setText`` method. |Args| * ``text`` (**str**): text to insert at the specified position. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invali...
Undo safe wrapper for the native ``setText`` method. |Args| * ``text`` (**str**): text to insert at the specified position. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
def controldata(self): """ return the contents of pg_controldata, or non-True value if pg_controldata call failed """ result = {} # Don't try to call pg_controldata during backup restore if self._version_file_exists() and self.state != 'creating replica': try: ...
return the contents of pg_controldata, or non-True value if pg_controldata call failed
def listidentifiers(**kwargs): """Create OAI-PMH response for verb ListIdentifiers.""" e_tree, e_listidentifiers = verb(**kwargs) result = get_records(**kwargs) for record in result.items: pid = oaiid_fetcher(record['id'], record['json']['_source']) header( e_listidentifiers...
Create OAI-PMH response for verb ListIdentifiers.
def forwardMessage(self, chat_id, from_chat_id, message_id, disable_notification=None): """ See: https://core.telegram.org/bots/api#forwardmessage """ p = _strip(locals()) return self._api_request('forwardMessage', _rectify(p))
See: https://core.telegram.org/bots/api#forwardmessage
def coerce(self, value): """ Takes one or two values in the domain and returns a LinearOrderedCell with the same domain """ if isinstance(value, LinearOrderedCell) and (self.domain == value.domain or \ list_diff(self.domain, value.domain) == []): # is Line...
Takes one or two values in the domain and returns a LinearOrderedCell with the same domain
def delete_subnet_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete an RDS subnet group. CLI example:: salt myminion boto_rds.delete_subnet_group my-subnet-group \ region=us-east-1 ''' try: conn = _get_conn(region=regio...
Delete an RDS subnet group. CLI example:: salt myminion boto_rds.delete_subnet_group my-subnet-group \ region=us-east-1
def gen_lazy_function(self): """ Will be called by Node at instantiation. """ # If value argument to __init__ was None, draw value from random # method. if self._value is None: # Use random function if provided if self._random is not None: ...
Will be called by Node at instantiation.
def clear(self): """ Clears all of the build variables. """ for variable in self._project.variables.list(all=True): variable.delete()
Clears all of the build variables.
def _get_default_values(self, default_values=None): """Gets the default values set for a resource""" if not default_values: default_values = self.DEFAULT_VALUES if default_values: api_version = str(self._connection._apiVersion) values = default_values.get(ap...
Gets the default values set for a resource
def answerPreCheckoutQuery(self, pre_checkout_query_id, ok, error_message=None): """ See: https://core.telegram.org/bots/api#answerprecheckoutquery """ p = _strip(locals()) return self._api_request('answerPreCheckoutQuery', _rectify(p))
See: https://core.telegram.org/bots/api#answerprecheckoutquery
def get_internal_urls(self): """ URL's, which may point to edeposit, aleph, kramerius and so on. Fields ``856u40``, ``998a`` and ``URLu``. Returns: list: List of internal URLs. """ internal_urls = self.get_subfields("856", "u", i1="4", i2="0") inter...
URL's, which may point to edeposit, aleph, kramerius and so on. Fields ``856u40``, ``998a`` and ``URLu``. Returns: list: List of internal URLs.
def hardware_flexport_flexport_type_instance(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware") flexport = ET.SubElement(hardware, "flexport") id_key = ET.Su...
Auto Generated Code
def getResultFromProcess(res, tempname, process): """Get a value from process, return tuple of value, res if succesful""" if not isinstance(res, (UndefinedValue, Exception)): value = getRepresentation(tempname, process) return value, res else: return res, str(res)
Get a value from process, return tuple of value, res if succesful
def parse_bdstoken(content): '''从页面中解析出bdstoken等信息. 这些信息都位于页面底部的<script>, 只有在授权后的页面中才出现. 这里, 为了保证兼容性, 就不再使用cssselect模块解析了. @return 返回bdstoken ''' bdstoken = '' bds_re = re.compile('"bdstoken"\s*:\s*"([^"]+)"', re.IGNORECASE) bds_match = bds_re.search(content) if bds_match: ...
从页面中解析出bdstoken等信息. 这些信息都位于页面底部的<script>, 只有在授权后的页面中才出现. 这里, 为了保证兼容性, 就不再使用cssselect模块解析了. @return 返回bdstoken
def speed_rms(Temperature,element,isotope): r"""This function calculates the average speed (in meters per second) of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution. This is simply sqrt(8*k_B*T/m/pi) where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and ...
r"""This function calculates the average speed (in meters per second) of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution. This is simply sqrt(8*k_B*T/m/pi) where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and m is the mass of the atom (in kilograms). ...
def restore(self, hist_uid): ''' Restore by ID ''' if self.check_post_role()['ADMIN']: pass else: return False histinfo = MWikiHist.get_by_uid(hist_uid) if histinfo: pass else: return False postinfo ...
Restore by ID
def main(argv, reactor=None): """Run the client GUI. Typical use: >>> sys.exit(main(sys.argv)) @param argv: The arguments to run it with, e.g. sys.argv. @param reactor: The reactor to use. Must be compatible with gtk as this module uses gtk API"s. @return exitcode: The exit code it ret...
Run the client GUI. Typical use: >>> sys.exit(main(sys.argv)) @param argv: The arguments to run it with, e.g. sys.argv. @param reactor: The reactor to use. Must be compatible with gtk as this module uses gtk API"s. @return exitcode: The exit code it returned, as per sys.exit.
def close(self): """ Close the connection. :param purge: If True (the default), the receive buffer will be purged. """ # Close the underlying socket if self._sock: with utils.ignore_except(): self._sock.close() ...
Close the connection. :param purge: If True (the default), the receive buffer will be purged.
def upload_image(self, image_file, referer_url=None, title=None, desc=None, created_at=None, collection_id=None): """Upload an image :param image_file: File-like object of an im...
Upload an image :param image_file: File-like object of an image file :param referer_url: Referer site URL :param title: Site title :param desc: Comment :param created_at: Image's created time in unix time :param collection_id: Collection ID
def create_or_replace_primary_key(self, table: str, fieldnames: Sequence[str]) -> int: """Make a primary key, or replace it if it exists.""" # *** create_or_replace_primary_key: Uses code specific to MySQL sql = """ ...
Make a primary key, or replace it if it exists.
def ok(self): """ Returns True if OK to use, else False """ try: v = int(self._value) if v < 0: return False else: return True except: return False
Returns True if OK to use, else False
def Start(self): """Retrieve all the clients for the AbstractClientStatsCollectors.""" try: self.stats = {} self.BeginProcessing() processed_count = 0 if data_store.RelationalDBEnabled(): for client_info_batch in _IterateAllClients( recency_window=self.recency_win...
Retrieve all the clients for the AbstractClientStatsCollectors.
def adapt_files(solver): """ Rename and remove files whenever necessary. """ print("adapting {0}'s files".format(solver)) root = os.path.join('solvers', solver) for arch in to_extract[solver]: arch = os.path.join(root, arch) extract_archive(arch, solver, put_inside=True) ...
Rename and remove files whenever necessary.
def get_match(sport, team1, team2): """ Get live scores for a single match :param sport: the sport being played :type sport: string :param team1: first team participating in the match :ttype team1: string :param team2: second team participating in the match :type team2: string :retu...
Get live scores for a single match :param sport: the sport being played :type sport: string :param team1: first team participating in the match :ttype team1: string :param team2: second team participating in the match :type team2: string :return: A specific match :rtype: Match
def assign(self, pm): """Reassign pixmap or xpm string array to wrapper""" if isinstance(pm, QPixmap): self._pm = pm else: # assume xpm string list to be decoded on-demand self._xpmstr = pm self._pm = None self._icon = None
Reassign pixmap or xpm string array to wrapper
def ssh_version(): ''' Returns the version of the installed ssh command ''' # This function needs more granular checks and to be validated against # older versions of ssh ret = subprocess.Popen( ['ssh', '-V'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).co...
Returns the version of the installed ssh command
def set_up(self, test_args=(), clear=True, debug=False): """ Sets properties right before calling run. ``test_args`` The arguments to pass to the test runner. ``clear`` Boolean. Set to True if we should clear console before running the tests. ``...
Sets properties right before calling run. ``test_args`` The arguments to pass to the test runner. ``clear`` Boolean. Set to True if we should clear console before running the tests. ``debug`` Boolean. Set to True if we want to print debugging ...
def execute(): """ Ensure provisioning """ boto_server_error_retries = 3 # Ensure provisioning for table_name, table_key in sorted(dynamodb.get_tables_and_gsis()): try: table_num_consec_read_checks = \ CHECK_STATUS['tables'][table_name]['reads'] except KeyErr...
Ensure provisioning
def infile(self): """Path of the input file""" return os.path.join(OPTIONS['base_dir'], '{0}.{1}'.format(self.name, OPTIONS['in_ext']))
Path of the input file
def p_rule(self, rule): '''rule : GUIDELINE | REGULATION''' if len(rule[1]) == 4: # This is a guideline rule[0] = Guideline(rule[1][1], rule[1][2], rule[1][3]) else: # This is a regulation indentsize = rule[1][0] number ...
rule : GUIDELINE | REGULATION