code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_property(self, property_key: str) -> str: """Get a scheduling object property.""" self._check_object_exists() return DB.get_hash_value(self.key, property_key)
Get a scheduling object property.
def subject_areas(self): """List of named tuples of subject areas in the form (area, abbreviation, code) of author's publication. """ path = ['subject-areas', 'subject-area'] area = namedtuple('Subjectarea', 'area abbreviation code') areas = [area(area=item['$'], code=ite...
List of named tuples of subject areas in the form (area, abbreviation, code) of author's publication.
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, 'keywords') and self.keywords is not None: _dict['keywords'] = [x._to_dict() for x...
Return a json dictionary representing this model.
def add_startup_file(dbg_initfiles): """ Read debugger startup file(s): both python code and debugger profile to dbg_initfiles.""" startup_python_file = default_configfile('profile.py') if Mfile.readable(startup_python_file): with codecs.open(startup_python_file, 'r', encoding='utf8') as fp: ...
Read debugger startup file(s): both python code and debugger profile to dbg_initfiles.
def create_firewall_rule(protocol, action, profile=None, **kwargs): ''' Creates a new firewall rule CLI Example: .. code-block:: bash salt '*' neutron.create_firewall_rule protocol action tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION ...
Creates a new firewall rule CLI Example: .. code-block:: bash salt '*' neutron.create_firewall_rule protocol action tenant_id=TENANT_ID name=NAME description=DESCRIPTION ip_version=IP_VERSION source_ip_address=SOURCE_IP_ADDRESS destination_ip_address=DESTINATION_IP_ADD...
def isdefined(obj, force_import=False, namespace=None): """Return True if object is defined in namespace If namespace is None --> namespace = locals()""" if namespace is None: namespace = locals() attr_list = obj.split('.') base = attr_list.pop(0) if len(base) == 0: return False ...
Return True if object is defined in namespace If namespace is None --> namespace = locals()
def set_id(self, dxid): ''' :param dxid: New job ID to be associated with the handler (localjob IDs also accepted for local runs) :type dxid: string Discards the currently stored ID and associates the handler with *dxid* ''' if dxid is not None: if not (isins...
:param dxid: New job ID to be associated with the handler (localjob IDs also accepted for local runs) :type dxid: string Discards the currently stored ID and associates the handler with *dxid*
def finish_section(section, name): '''finish_section will add the header to a section, to finish the recipe take a custom command or list and return a section. Parameters ========== section: the section content, without a header name: the name of the section for the header '...
finish_section will add the header to a section, to finish the recipe take a custom command or list and return a section. Parameters ========== section: the section content, without a header name: the name of the section for the header
def _read_loop_websocket(self): """Read packets from the Engine.IO WebSocket connection.""" while self.state == 'connected': p = None try: p = self.ws.recv() except websocket.WebSocketConnectionClosedException: self.logger.warning( ...
Read packets from the Engine.IO WebSocket connection.
def cf_string_to_unicode(value): """ Creates a python unicode string from a CFString object :param value: The CFString to convert :return: A python unicode string """ string = CoreFoundation.CFStringGetCStringPtr( _cast_pointer_p(val...
Creates a python unicode string from a CFString object :param value: The CFString to convert :return: A python unicode string
def group_list(items): """Items in the list are grouped into a dictionary Items should be a list of (key, value) pairs >>> grouped = group_list([(1,0), (2,0), (1,1)]) >>> grouped[1] == [0,1] True """ groups = defaultdict(list) for key, value in items: groups[key].append(value) ...
Items in the list are grouped into a dictionary Items should be a list of (key, value) pairs >>> grouped = group_list([(1,0), (2,0), (1,1)]) >>> grouped[1] == [0,1] True
def derive_expr_from_counter_entry(expression, species, counter_entry): r""" Derives an given expression with respect to arbitrary species and orders. This is used to compute :math:`\frac{\partial^n \mathbf{n}a_l(\mathbf{x})}{\partial \mathbf{x^n}}` in eq. 6 :param expression: the expression to be deri...
r""" Derives an given expression with respect to arbitrary species and orders. This is used to compute :math:`\frac{\partial^n \mathbf{n}a_l(\mathbf{x})}{\partial \mathbf{x^n}}` in eq. 6 :param expression: the expression to be derived :type expression: :class:`~sympy.Expr` :param species: the name ...
async def sleep(self, duration: float=0.0) -> None: '''Simple wrapper around `asyncio.sleep()`.''' duration = max(0, duration) if duration > 0: Log.debug('sleeping task %s for %.1f seconds', self.name, duration) await asyncio.sleep(duration)
Simple wrapper around `asyncio.sleep()`.
def time_window(self, window_width_ms): """Applies a system time window to the stream. Attributes: window_width_ms (int): The length of the window in ms. """ op = Operator( _generate_uuid(), OpType.TimeWindow, "TimeWindow", nu...
Applies a system time window to the stream. Attributes: window_width_ms (int): The length of the window in ms.
def list_line(self, line): """ Write the given iterable of values (line) to the file as items on the same line. Any argument that stringifies to a string legal as a TSV data item can be written. Does not copy the line or build a big string in memory. """ ...
Write the given iterable of values (line) to the file as items on the same line. Any argument that stringifies to a string legal as a TSV data item can be written. Does not copy the line or build a big string in memory.
def finish(self): """Clean up the JLigier controlhost connection""" log.debug("Disconnecting from JLigier.") self.client.socket.shutdown(socket.SHUT_RDWR) self.client._disconnect()
Clean up the JLigier controlhost connection
def number(self, number): """ Returns a floating point (or integer) number for a BASIC program. That is: It's ASCII representation followed by 5 bytes in floating point or integer format (if number in (-65535 + 65535) """ s = [ord(x) for x in str(number)] + [14] # Bytes of strin...
Returns a floating point (or integer) number for a BASIC program. That is: It's ASCII representation followed by 5 bytes in floating point or integer format (if number in (-65535 + 65535)
def pivot_table(expr, value_index, value_ty, index_index, index_ty, columns_index, columns_ty, aggfunc): """ Constructs a pivot table where the index_index and columns_index are used as keys and the value_index is used as the value which is aggregated. """ weld_obj = WeldObject(encoder_, decoder_) ...
Constructs a pivot table where the index_index and columns_index are used as keys and the value_index is used as the value which is aggregated.
def make_three_color(data, time, step, config, shape=(1280, 1280), lower_val=(0, 0, 0), upper_val=(2.5, 2.5, 2.5)): """ create a three color image according to the config file :param data: a dictionary of fetched data where keys correspond to products :param config: a config object :param shape: the...
create a three color image according to the config file :param data: a dictionary of fetched data where keys correspond to products :param config: a config object :param shape: the size of a composite image :param lower_val: a tuple of lower values for RGB, any value below this is set to the low value ...
def create_record_set_group(self, name, g_dict): """Accept a record_set dict. Return a Troposphere record_set object.""" rs = route53.RecordSetGroup.from_dict(name, g_dict) rs = add_hosted_zone_id_if_missing(rs, self.hosted_zone_id) rs = self.add_hosted_zone_id_for_alias_target_if_missin...
Accept a record_set dict. Return a Troposphere record_set object.
def addRelationship(self, pid, subject, predicate, object, isLiteral=False, datatype=None): """ Wrapper function for `Fedora REST API addRelationship <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-addRelationship>`_ :param pid: persistent id for the object...
Wrapper function for `Fedora REST API addRelationship <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-addRelationship>`_ :param pid: persistent id for the object to add the new relationship to :param subject: subject of the relationship; object or datastream URI :param predicate: ...
def order_by(self, field_path, direction=ASCENDING): """Modify the query to add an order clause on a specific field. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. Successive :meth:`~.firestore_v1beta1.query.Query.order_by` calls ...
Modify the query to add an order clause on a specific field. See :meth:`~.firestore_v1beta1.client.Client.field_path` for more information on **field paths**. Successive :meth:`~.firestore_v1beta1.query.Query.order_by` calls will further refine the ordering of results returned by the q...
def write(self, b): """ Write the given bytes-like object, b, to the underlying raw stream, and return the number of bytes written. Args: b (bytes-like object): Bytes to write. Returns: int: The number of bytes written. """ if not self._w...
Write the given bytes-like object, b, to the underlying raw stream, and return the number of bytes written. Args: b (bytes-like object): Bytes to write. Returns: int: The number of bytes written.
def get_versions(default={"version": "unknown", "full": ""}, verbose=False): """This variation of get_versions() will be used in _version.py .""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/no...
This variation of get_versions() will be used in _version.py .
def flatten_unique(l: Iterable) -> List: """ Return a list of UNIQUE non-list items in l """ rval = OrderedDict() for e in l: if not isinstance(e, str) and isinstance(e, Iterable): for ev in flatten_unique(e): rval[ev] = None else: rval[e] = None r...
Return a list of UNIQUE non-list items in l
def fromfile(self, path_to_file, mimetype=None): """ load blob content from file in StorageBlobModel instance. Parameters are: - path_to_file (required): path to a local file - mimetype (optional): set a mimetype. azurestoragewrap will guess it if not given """ if os....
load blob content from file in StorageBlobModel instance. Parameters are: - path_to_file (required): path to a local file - mimetype (optional): set a mimetype. azurestoragewrap will guess it if not given
def p_multiplicative_expr(self, p): """multiplicative_expr : unary_expr | multiplicative_expr MULT unary_expr | multiplicative_expr DIV unary_expr | multiplicative_expr MOD unary_expr """ if len(p) == 2:...
multiplicative_expr : unary_expr | multiplicative_expr MULT unary_expr | multiplicative_expr DIV unary_expr | multiplicative_expr MOD unary_expr
def MGMT_PANID_QUERY(self, sAddr, xCommissionerSessionId, listChannelMask, xPanId): """send MGMT_PANID_QUERY message to a given destination Args: xPanId: a given PAN ID to check the conflicts Returns: True: successful to send MGMT_PANID_QUERY message. False:...
send MGMT_PANID_QUERY message to a given destination Args: xPanId: a given PAN ID to check the conflicts Returns: True: successful to send MGMT_PANID_QUERY message. False: fail to send MGMT_PANID_QUERY message.
def make_ccw(points): """ Static method. Returns a counterclock wise ordered sequence of points. If there are any repeated point, the method will raise an error. Due to the 3D character of the package, the order or the points will be tried following this...
Static method. Returns a counterclock wise ordered sequence of points. If there are any repeated point, the method will raise an error. Due to the 3D character of the package, the order or the points will be tried following this order: 1. z=0 pprojection ...
def _process_underscores(self, tokens): "Strip underscores to make sure the number is correct after join" groups = [[str(''.join(el))] if b else list(el) for (b,el) in itertools.groupby(tokens, lambda k: k=='_')] flattened = [el for group in groups for el in group] proc...
Strip underscores to make sure the number is correct after join
def convert_complex_output(out_in): """ Convert complex values in the output dictionary `out_in` to pairs of real and imaginary parts. """ out = {} for key, val in out_in.iteritems(): if val.data.dtype in complex_types: rval = copy(val) rval.data = val.data.real...
Convert complex values in the output dictionary `out_in` to pairs of real and imaginary parts.
def _run(self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, repetitions: int) -> Dict[str, np.ndarray]: """See definition in `cirq.SimulatesSamples`.""" param_resolver = param_resolver or study.ParamResolver({}) resolved_circuit = protocols.resolve_pa...
See definition in `cirq.SimulatesSamples`.
def bandWave(self): """Return the binned wavelength set most appropriate for the observation mode, as defined by ``pysynphot.locations.wavecat``. Also see :ref:`pysynphot-refdata`. Returns ------- bandwave : array_like """ if self.binset.startswith('('):...
Return the binned wavelength set most appropriate for the observation mode, as defined by ``pysynphot.locations.wavecat``. Also see :ref:`pysynphot-refdata`. Returns ------- bandwave : array_like
def resolve_cert_reqs(candidate): """ Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_NONE`. If given a string it is assumed to be the name of the constant in the :mod:`ssl` module or its abbrevi...
Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_NONE`. If given a string it is assumed to be the name of the constant in the :mod:`ssl` module or its abbreviation. (So you can specify `REQUIRED` inst...
def load(self, *objs) -> "ReadTransaction": """ Add one or more objects to be loaded in this transaction. At most 10 items can be loaded in the same transaction. All objects will be loaded each time you call commit(). :param objs: Objects to add to the set that are loaded in ...
Add one or more objects to be loaded in this transaction. At most 10 items can be loaded in the same transaction. All objects will be loaded each time you call commit(). :param objs: Objects to add to the set that are loaded in this transaction. :return: this transaction for chaining...
def queryset(self, request): """ Filter objects which don't have a value in this language """ qs = super(MultilingualInlineAdmin, self).queryset(request) # Don't now what the hell I was thinking here, but this code breaks stuff: # # checkfield = self.get_fill_chec...
Filter objects which don't have a value in this language
def geodetic2geocentric(theta, alt): """ Conversion from geodetic to geocentric coordinates by using the WGS84 spheroid. :param theta: colatitude (float, rad) :param alt: altitude (float, km) :return gccolat: geocentric colatitude (float, rad) d: gccolat minus theta (float, rad) ...
Conversion from geodetic to geocentric coordinates by using the WGS84 spheroid. :param theta: colatitude (float, rad) :param alt: altitude (float, km) :return gccolat: geocentric colatitude (float, rad) d: gccolat minus theta (float, rad) r: geocentric radius (float, km)
def path_requests(self, path): """ Returns a Resource instace that will have attributes, one for each of the http-methods supported on that path. For example: >>> hcl_api = client.path_requests('/api/hcl/{id}') >>> dir(hcl_api) [u'delete', u'get', u'put'] ...
Returns a Resource instace that will have attributes, one for each of the http-methods supported on that path. For example: >>> hcl_api = client.path_requests('/api/hcl/{id}') >>> dir(hcl_api) [u'delete', u'get', u'put'] >>> resp, ok = hcl_api.get(id='Arista_vE...
def get_children_tag_names(self, xml_element): """Returns all tag names of xml element and its children.""" tags = set() tags.add(self.remove_namespace_from_tag(xml_element.tag)) for element in xml_element.iter(tag=etree.Element): if element != xml_element: n...
Returns all tag names of xml element and its children.
def get_lib_filename(category, name): """ Get a filename of a built-in library file. """ base_dir = os.path.dirname(os.path.abspath(__file__)) if category == 'js': filename = os.path.join('js', '{0}.js'.format(name)) elif category == 'css': filename = os.path.join('css', '{0}.css'.format...
Get a filename of a built-in library file.
def transform_coors(self, mtx_t, ref_coors=None): """ Transform coordinates of the mesh by the given transformation matrix. Parameters ---------- mtx_t : array The transformation matrix `T` (2D array). It is applied depending on its shape: - `(d...
Transform coordinates of the mesh by the given transformation matrix. Parameters ---------- mtx_t : array The transformation matrix `T` (2D array). It is applied depending on its shape: - `(dim, dim): x = T * x` - `(dim, dim + 1): x = T[:, :-1] * x +...
def write(self, vals): """ Overrides orm write method. @param self: The object pointer @param vals: dictionary of fields value. """ if 'isroom' in vals and vals['isroom'] is False: vals.update({'color': 2, 'status': 'occupied'}) if 'isroom'in vals and ...
Overrides orm write method. @param self: The object pointer @param vals: dictionary of fields value.
def remote_method(self, method, block=False, **params): """Creates a Python function that will attempt to call a remote method when used. :param method: str, Method name on the server to call :param block: bool, Wheter to wait for result or not Usage:: >>> send_us...
Creates a Python function that will attempt to call a remote method when used. :param method: str, Method name on the server to call :param block: bool, Wheter to wait for result or not Usage:: >>> send_usher_token = conn.remote_method("NetStream.Authenticate.UsherToken",...
def feature_from_line(line, dialect=None, strict=True, keep_order=False): """ Given a line from a GFF file, return a Feature object Parameters ---------- line : string strict : bool If True (default), assume `line` is a single, tab-delimited string that has at least 9 fields. ...
Given a line from a GFF file, return a Feature object Parameters ---------- line : string strict : bool If True (default), assume `line` is a single, tab-delimited string that has at least 9 fields. If False, then the input can have a more flexible format, useful for c...
def greaterThanOrEqual(self, value): """ Sets the operator type to Query.Op.GreaterThanOrEqual and sets the value to the inputted value. :param value <variant> :return <Query> :sa __ge__ :usage |>>> ...
Sets the operator type to Query.Op.GreaterThanOrEqual and sets the value to the inputted value. :param value <variant> :return <Query> :sa __ge__ :usage |>>> from orb import Query as Q |>>> query...
def run_query( self, project_id, partition_id, read_options=None, query=None, gql_query=None ): """Perform a ``runQuery`` request. :type project_id: str :param project_id: The project to connect to. This is usually your project name in the cloud console. ...
Perform a ``runQuery`` request. :type project_id: str :param project_id: The project to connect to. This is usually your project name in the cloud console. :type partition_id: :class:`.entity_pb2.PartitionId` :param partition_id: Partition ID corresponding to...
def create_top_level_index(api_docs_path, packages, max_depth=2): """Create the top level index page (writing to file) :param api_docs_path: Path to the api-docs of inasafe documentation. :type api_docs_path: str :param packages: List of packages which want to be extracted their api/ :type package...
Create the top level index page (writing to file) :param api_docs_path: Path to the api-docs of inasafe documentation. :type api_docs_path: str :param packages: List of packages which want to be extracted their api/ :type packages: list :param max_depth: The maximum depth of tree in the api docs....
def _load_output_data_port_models(self): """Reloads the output data port models directly from the the state """ self.output_data_ports = [] for output_data_port in self.state.output_data_ports.values(): self._add_model(self.output_data_ports, output_data_port, DataPortModel)
Reloads the output data port models directly from the the state
async def get_xy_address(self, xy): '''Get address of the agent residing in *xy* coordinate, or ``None`` if no such agent is in this multi-environment. ''' manager_addr = self.get_xy_environment(xy) if manager_addr is None: return None else: r_agen...
Get address of the agent residing in *xy* coordinate, or ``None`` if no such agent is in this multi-environment.
def remove_namespace(self, namespace): """This removes a Namespace object from the socket. This is usually called by :meth:`~socketio.namespace.BaseNamespace.disconnect`. """ if namespace in self.active_ns: del self.active_ns[namespace] if len(self.active_n...
This removes a Namespace object from the socket. This is usually called by :meth:`~socketio.namespace.BaseNamespace.disconnect`.
def assertCategoricalLevelsNotEqual(self, levels1, levels2, msg=None): '''Fail if ``levels1`` and ``levels2`` have the same domain. Parameters ---------- levels1 : iterable levels2 : iterable msg : str If not provided, the :mod:`marbles.mixins` or ...
Fail if ``levels1`` and ``levels2`` have the same domain. Parameters ---------- levels1 : iterable levels2 : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ ...
def format_runlog(runlog: List[Mapping[str, Any]]) -> str: """ Format a run log (return value of :py:meth:`simulate``) into a human-readable string :param runlog: The output of a call to :py:func:`simulate` """ to_ret = [] for command in runlog: to_ret.append( '\t' * com...
Format a run log (return value of :py:meth:`simulate``) into a human-readable string :param runlog: The output of a call to :py:func:`simulate`
def find_quality(positions): """ Find a quality consists of positions :param list[int] positions: note positions :rtype: str|None """ for q, p in QUALITY_DICT.items(): if positions == list(p): return q return None
Find a quality consists of positions :param list[int] positions: note positions :rtype: str|None
def trim(value): ''' Raise an exception if value is empty. Otherwise strip it down. :param value: :return: ''' value = (value or '').strip() if not value: raise CommandExecutionError("Empty value during sanitation") return six.text_type(value)
Raise an exception if value is empty. Otherwise strip it down. :param value: :return:
def call_contract_function( web3, address, normalizers, function_identifier, transaction, block_id=None, contract_abi=None, fn_abi=None, *args, **kwargs): """ Helper function for interacting with a contract function using the `e...
Helper function for interacting with a contract function using the `eth_call` API.
def write_hash_file(fpath, hash_tag='md5', recompute=False): r""" Creates a hash file for each file in a path CommandLine: python -m utool.util_hash --test-write_hash_file Example: >>> # DISABLE_DOCTEST >>> import utool as ut >>> from utool.util_hash import * # NOQA ...
r""" Creates a hash file for each file in a path CommandLine: python -m utool.util_hash --test-write_hash_file Example: >>> # DISABLE_DOCTEST >>> import utool as ut >>> from utool.util_hash import * # NOQA >>> fpath = ut.grab_test_imgpath('patsy.jpg') >>> write...
def _symlink(path, link, overwrite=0, verbose=0): """ Windows helper for ub.symlink """ if exists(link) and not os.path.islink(link): # On windows a broken link might still exist as a hard link or a # junction. Overwrite it if it is a file and we cannot symlink. # However, if it ...
Windows helper for ub.symlink
def set_scheduled(self): """ Returns True if state was successfully changed from idle to scheduled. """ with self._idle_lock: if self._idle: self._idle = False return True return False
Returns True if state was successfully changed from idle to scheduled.
def trains(self): """Filter rows according to `headers`""" for row in self._rows: train_no = row.get('station_train_code') initial = train_no[0].lower() if not self._opts or initial in self._opts: train = [ # Column: '车次' ...
Filter rows according to `headers`
def post_request( self, alias, uri, data=None, json=None, params=None, headers=None, files=None, allow_redirects=None, timeout=None): """ Send a POST request on the session object found using ...
Send a POST request on the session object found using the given `alias` ``alias`` that will be used to identify the Session object in the cache ``uri`` to send the POST request to ``data`` a dictionary of key-value pairs that will be urlencoded and sent as POST data ...
def set_rotation_matrices(self): """Set the meta information at each vertex to contain the correct matrices C and Cinv as prescribed by the rotations and rotation orders.""" for i in range(len(self.vertices)): self.vertices[i].meta['C'] = rotation_matrix(self.vertices[i].meta['axis'][0], ...
Set the meta information at each vertex to contain the correct matrices C and Cinv as prescribed by the rotations and rotation orders.
def dot_format(out, graph, name="digraph"): """Outputs the graph using the graphviz "dot" format.""" out.write("digraph %s {\n" % name) for step, deps in each_step(graph): for dep in deps: out.write(" \"%s\" -> \"%s\";\n" % (step, dep)) out.write("}\n")
Outputs the graph using the graphviz "dot" format.
def rows(self): """Yield rows for the section""" for t in self.terms: for row in t.rows: term, value = row # Value can either be a string, or a dict if isinstance(value, dict): # Dict is for properties, which might be arg-children term,...
Yield rows for the section
def splitset(num_trials, skipstep=None): """ Split-set cross validation Use half the trials for training, and the other half for testing. Then repeat the other way round. Parameters ---------- num_trials : int Total number of trials skipstep : int unused Returns --...
Split-set cross validation Use half the trials for training, and the other half for testing. Then repeat the other way round. Parameters ---------- num_trials : int Total number of trials skipstep : int unused Returns ------- gen : generator object the gene...
def to_yaml(self, destination, flow_style=False): """ Save a dictionnary into a YAML file. :param destination: A path to a file where we're going to write the converted dict into a JSON format. :type destination: str """ with open(destination, "w...
Save a dictionnary into a YAML file. :param destination: A path to a file where we're going to write the converted dict into a JSON format. :type destination: str
def send(self, data): """ Open transport, send data, and yield response chunks. """ try: proc = subprocess.Popen(self.cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError as exc: raise URLError("Calling %r failed (%s)!" % (' '...
Open transport, send data, and yield response chunks.
def delete_sched_block_instance(self, block_id): """Delete the specified Scheduling Block Instance. Removes the Scheduling Block Instance, and all Processing Blocks that belong to it from the database""" LOG.debug('Deleting SBI %s', block_id) scheduling_blocks = self._db.get_al...
Delete the specified Scheduling Block Instance. Removes the Scheduling Block Instance, and all Processing Blocks that belong to it from the database
def check_required_columns(df, filename, required_columns): """ Ensure that all required columns are present in the given dataframe, otherwise raise an exception. """ available_columns = set(df.columns) for column_name in required_columns: if column_name not in available_columns: ...
Ensure that all required columns are present in the given dataframe, otherwise raise an exception.
def gradient(self): """Gradient operator of the functional.""" functional = self class KLCrossEntCCGradient(Operator): """The gradient operator of this functional.""" def __init__(self): """Initialize a new instance.""" super(KLCrossEntC...
Gradient operator of the functional.
def image(name, data, step=None, max_outputs=3, description=None): """Write an image summary. Arguments: name: A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes. data: A `Tensor` representing pixe...
Write an image summary. Arguments: name: A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes. data: A `Tensor` representing pixel data with shape `[k, h, w, c]`, where `k` is the number of images, `h` and `w` are the height and ...
def mkbucketv2(self, bucket_name, region): """ 创建存储空间 https://developer.qiniu.com/kodo/api/1382/mkbucketv2 Args: bucket_name: 存储空间名 region: 存储区域 """ bucket_name = urlsafe_base64_encode(bucket_name) return self.__rs_do('mkbucketv2', bucket_...
创建存储空间 https://developer.qiniu.com/kodo/api/1382/mkbucketv2 Args: bucket_name: 存储空间名 region: 存储区域
def submit_to_gallery(self, title, bypass_terms=False): """ Add this to the gallery. Require that the authenticated user has accepted gallery terms and verified their email. :param title: The title of the new gallery item. :param bypass_terms: If the user has not accept...
Add this to the gallery. Require that the authenticated user has accepted gallery terms and verified their email. :param title: The title of the new gallery item. :param bypass_terms: If the user has not accepted Imgur's terms yet, this method will return an error. Set this...
def read_request(file_name, **params): """ 从文件中读取请求头,并根据格式化字符串模板,进行字符串格式化 :param file_name: :param params: :return: """ with open(file_name, 'r') as f: data = f.read() return read_request_from_str(data, **params)
从文件中读取请求头,并根据格式化字符串模板,进行字符串格式化 :param file_name: :param params: :return:
def _load_shader(filename): """Load a shader file.""" curdir = op.dirname(op.realpath(__file__)) glsl_path = op.join(curdir, 'glsl') path = op.join(glsl_path, filename) with open(path, 'r') as f: return f.read()
Load a shader file.
def register_view(design_doc, full_set=True): """Model document decorator to register its design document view:: @register_view('dev_books') class Book(Document): __bucket_name__ = 'mybucket' doc_type = 'book' structure = { # snip snip ...
Model document decorator to register its design document view:: @register_view('dev_books') class Book(Document): __bucket_name__ = 'mybucket' doc_type = 'book' structure = { # snip snip } :param design_doc: The name of the design doc...
def apply(self, node): """ Apply transformation and return if an update happened. """ new_node = self.run(node) return self.update, new_node
Apply transformation and return if an update happened.
def get(self, id, param): """ Returns the value of a configuration parameter. """ assert isinstance(id, basestring) assert isinstance(param, basestring) return self.params_.get(param, {}).get(id)
Returns the value of a configuration parameter.
def init(base_url, username=None, password=None, verify=True): """Initialize ubersmith API module with HTTP request handler.""" handler = RequestHandler(base_url, username, password, verify) set_default_request_handler(handler) return handler
Initialize ubersmith API module with HTTP request handler.
def auto_density(color): """ Given a SpectralColor, automatically choose the correct ANSI T filter. Returns a tuple with a string representation of the filter the calculated density. :param SpectralColor color: The SpectralColor object to calculate density for. :rtype: float :return...
Given a SpectralColor, automatically choose the correct ANSI T filter. Returns a tuple with a string representation of the filter the calculated density. :param SpectralColor color: The SpectralColor object to calculate density for. :rtype: float :returns: The density value, with the filter...
def put(self, filepath): """ Change the group or permissions of the specified file. Action must be specified when calling this method. """ action = self.get_body_argument('action') if action['action'] == 'update_group': newgrp = action['group'] tr...
Change the group or permissions of the specified file. Action must be specified when calling this method.
def threshold_monitor_hidden_threshold_monitor_sfp_apply(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor") threshold_monito...
Auto Generated Code
def should_not_sample_path(request): """Decided whether current request path should be sampled or not. This is checked previous to `should_not_sample_route` and takes precedence. :param: current active pyramid request :returns: boolean whether current request path is blacklisted. """ blackliste...
Decided whether current request path should be sampled or not. This is checked previous to `should_not_sample_route` and takes precedence. :param: current active pyramid request :returns: boolean whether current request path is blacklisted.
def format(self): """ Dictionary of available formats, corresponding to a list of the values Example: pod.format['plaintext'] will return a list of every plaintext content in the pod's subpods """ formats = {} # Iterate through all the tags (formats) in ...
Dictionary of available formats, corresponding to a list of the values Example: pod.format['plaintext'] will return a list of every plaintext content in the pod's subpods
async def collect(self): """ Create a `self` iterator and collect it into a `TotalList` (a normal list with a `.total` attribute). """ result = helpers.TotalList() async for message in self: result.append(message) result.total = self.total ret...
Create a `self` iterator and collect it into a `TotalList` (a normal list with a `.total` attribute).
def _collect_conflicts_within( context, # type: ValidationContext conflicts, # type: List[Tuple[Tuple[str, str], List[Node], List[Node]]] cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], L...
Collect all Conflicts "within" one collection of fields.
def save(self, name): """ Save the string buffer to a file. Finalizes prior to saving. :param name: File path. :type name: unicode | str """ self.finalize() with open(name, 'wb+') as f: if six.PY3: f.write(self.fileobj.getbuffer()) ...
Save the string buffer to a file. Finalizes prior to saving. :param name: File path. :type name: unicode | str
def save(self, fname: str): """ Saves this training state to fname. """ with open(fname, "wb") as fp: pickle.dump(self, fp)
Saves this training state to fname.
def sentence2freqt(docgraph, root, successors=None, include_pos=False, escape_func=FREQT_ESCAPE_FUNC): """convert a sentence subgraph into a FREQT string.""" if successors is None: successors = sorted_bfs_successors(docgraph, root) if root in successors: # root node has children...
convert a sentence subgraph into a FREQT string.
def csv_to_sqlite( input_filename, output_filename, samples=None, dialect=None, batch_size=10000, encoding="utf-8", callback=None, force_types=None, chunk_size=8388608, table_name="table1", schema=None, ): "Export a CSV file to SQLite, based on field type detection from s...
Export a CSV file to SQLite, based on field type detection from samples
def encode_span(self, v2_span): """Encodes the current span to thrift.""" span = v2_span.build_v1_span() thrift_endpoint = thrift.create_endpoint( span.endpoint.port, span.endpoint.service_name, span.endpoint.ipv4, span.endpoint.ipv6, ) ...
Encodes the current span to thrift.
def request(self, filter=None, stream_name=None, start_time=None, stop_time=None): """Creates a subscription for notifications from the server. *filter* specifies the subset of notifications to receive (by default all notificaitons are received) :seealso: :ref:`filter_params` ...
Creates a subscription for notifications from the server. *filter* specifies the subset of notifications to receive (by default all notificaitons are received) :seealso: :ref:`filter_params` *stream_name* specifies the notification stream name. The default is None meaning all ...
def get_output(self, assets_by_taxo, haz, rlzi=None): """ :param assets_by_taxo: a dictionary taxonomy index -> assets on a site :param haz: an array or a dictionary of hazard on that site :param rlzi: if given, a realization index """ if isinstance(haz, numpy.ndarray): ...
:param assets_by_taxo: a dictionary taxonomy index -> assets on a site :param haz: an array or a dictionary of hazard on that site :param rlzi: if given, a realization index
def AddDescriptorFromSchema(self, schema_name, schema): """Add a new MessageDescriptor named schema_name based on schema.""" # TODO(craigcitro): Is schema_name redundant? if self.__GetDescriptor(schema_name): return if schema.get('enum'): self.__DeclareEnum(schema...
Add a new MessageDescriptor named schema_name based on schema.
def _cache_init(self): """Initializes local cache from Django cache.""" cache_ = cache.get(self.CACHE_KEY) if cache_ is None: cache_ = defaultdict(dict) self._cache = cache_
Initializes local cache from Django cache.
def insert(self, index, key, value): """Inserts the key, value pair before the item with the given index.""" if key in self.keyOrder: n = self.keyOrder.index(key) del self.keyOrder[n] if n < index: index -= 1 self.keyOrder.insert(index, key) ...
Inserts the key, value pair before the item with the given index.
def apply(self, styles=None, verbose=False): """ Applies the specified style to the selected views and returns the SUIDs of the affected views. :param styles (string): Name of Style to be applied to the selected views. = ['Directed', 'BioPAX_SIF', 'Bridging Reads Histogram:u...
Applies the specified style to the selected views and returns the SUIDs of the affected views. :param styles (string): Name of Style to be applied to the selected views. = ['Directed', 'BioPAX_SIF', 'Bridging Reads Histogram:unique_0', 'PSIMI 25 Style', 'Coverage Histogram:best&...
def dict_contents(self, use_dict=None, as_class=dict): """Return the contents of an object as a dict.""" if _debug: NPDU._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class) # make/extend the dictionary of content if use_dict is None: use_dict = as_class() ...
Return the contents of an object as a dict.
def child(self, name): """ Create a new instance of this class derived from the current instance such that: (new.trace_id == current.trace_id and new.parent_span_id == current.span_id) The new L{Trace} instance will have a new unique span_id and if set the ...
Create a new instance of this class derived from the current instance such that: (new.trace_id == current.trace_id and new.parent_span_id == current.span_id) The new L{Trace} instance will have a new unique span_id and if set the endpoint of the current L{Trace} object...
def system_summary(providername=None): """ returns SystemSummary class from mentioned provider """ _providername = providername if not _providername: _providername = provider_check() import_str = 'netshowlib.%s.system_summary' % _providername return import_module(import_str).SystemS...
returns SystemSummary class from mentioned provider
def file_response(request, filepath, block=None, status_code=None, content_type=None, encoding=None, cache_control=None): """Utility for serving a local file Typical usage:: from pulsar.apps import wsgi class MyRouter(wsgi.Router): def get(self, request): ...
Utility for serving a local file Typical usage:: from pulsar.apps import wsgi class MyRouter(wsgi.Router): def get(self, request): return wsgi.file_response(request, "<filepath>") :param request: Wsgi request :param filepath: full path of file to serve :p...