code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def update_metadata(self, metadata): """Update cluster state given a MetadataResponse. Arguments: metadata (MetadataResponse): broker response to a metadata request Returns: None """ # In the common case where we ask for a single topic and get back an # erro...
Update cluster state given a MetadataResponse. Arguments: metadata (MetadataResponse): broker response to a metadata request Returns: None
def show_patterned_file(dir_path, pattern=list(), filename_only=True): """Print all file that file name contains ``pattern``. """ pattern = [i.lower() for i in pattern] if filename_only: def filter(winfile): for p in pattern: if p in winfil...
Print all file that file name contains ``pattern``.
def quality_to_apply(self): """Value of quality parameter to use in processing request. Simple substitution of 'native' or 'default' if no quality parameter is specified. """ if (self.request.quality is None): if (self.api_version <= '1.1'): return('n...
Value of quality parameter to use in processing request. Simple substitution of 'native' or 'default' if no quality parameter is specified.
def color_toggle(self): """Toggle between the currently active color scheme and NoColor.""" if self.color_scheme_table.active_scheme_name == 'NoColor': self.color_scheme_table.set_active_scheme(self.old_scheme) self.Colors = self.color_scheme_table.active_colors else: ...
Toggle between the currently active color scheme and NoColor.
def write_registers(self, registeraddress, values): """Write integers to 16-bit registers in the slave. The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16"). Uses Modbus function code 16. The number of registers that will be written is defined by the l...
Write integers to 16-bit registers in the slave. The slave register can hold integer values in the range 0 to 65535 ("Unsigned INT16"). Uses Modbus function code 16. The number of registers that will be written is defined by the length of the ``values`` list. Args: * regi...
def resolve_dist(cls, dist, working_set): """Given a local distribution and a working set, returns all dependencies from the set. :param dist: A single distribution to find the dependencies of :type dist: :class:`pkg_resources.Distribution` :param working_set: A working set to search fo...
Given a local distribution and a working set, returns all dependencies from the set. :param dist: A single distribution to find the dependencies of :type dist: :class:`pkg_resources.Distribution` :param working_set: A working set to search for all packages :type working_set: :class:`pkg...
def edit_scheme(self): """Edit current scheme.""" dlg = self.scheme_editor_dialog dlg.set_scheme(self.current_scheme) if dlg.exec_(): # Update temp scheme to reflect instant edits on the preview temporal_color_scheme = dlg.get_edited_color_scheme() fo...
Edit current scheme.
def warning(*args): """Display warning message via stderr or GUI.""" if sys.stdin.isatty(): print('WARNING:', *args, file=sys.stderr) else: notify_warning(*args)
Display warning message via stderr or GUI.
def no_empty_value(func): """Raises an exception if function argument is empty.""" @wraps(func) def wrapper(value): if not value: raise Exception("Empty value not allowed") return func(value) return wrapper
Raises an exception if function argument is empty.
def get_volume_steps(self): """Read the maximum volume level of the device.""" if not self.__volume_steps: self.__volume_steps = yield from self.handle_int( self.API.get('volume_steps')) return self.__volume_steps
Read the maximum volume level of the device.
async def add_relation(self, relation1, relation2): """Add a relation between two applications. :param str relation1: '<application>[:<relation_name>]' :param str relation2: '<application>[:<relation_name>]' """ connection = self.connection() app_facade = client.Applica...
Add a relation between two applications. :param str relation1: '<application>[:<relation_name>]' :param str relation2: '<application>[:<relation_name>]'
def epochs(steps=None, epoch_steps=1): """Iterator over epochs until steps is reached. 1-indexed. Args: steps: int, total number of steps. Infinite if None. epoch_steps: int, number of steps per epoch. Can also be an iterable<int> to enable variable length epochs. Yields: (epoch: int, epoch id...
Iterator over epochs until steps is reached. 1-indexed. Args: steps: int, total number of steps. Infinite if None. epoch_steps: int, number of steps per epoch. Can also be an iterable<int> to enable variable length epochs. Yields: (epoch: int, epoch id, epoch_steps: int, number of steps in this ...
def depth(self): """ Compute the depth of the tree (depth of a leaf=0). """ return self.fold_up(lambda n, fl, fg: max(fl + 1, fg + 1), lambda leaf: 0)
Compute the depth of the tree (depth of a leaf=0).
def add_item(self, assessment_id, item_id): """Adds an existing ``Item`` to an assessment. arg: assessment_id (osid.id.Id): the ``Id`` of the ``Assessment`` arg: item_id (osid.id.Id): the ``Id`` of the ``Item`` raise: NotFound - ``assessment_id`` or ``item_id`` no...
Adds an existing ``Item`` to an assessment. arg: assessment_id (osid.id.Id): the ``Id`` of the ``Assessment`` arg: item_id (osid.id.Id): the ``Id`` of the ``Item`` raise: NotFound - ``assessment_id`` or ``item_id`` not found raise: NullArgument - ``assessment_id`...
def timestamp_filename(basename, ext=None): """ Return a string of the form [basename-TIMESTAMP.ext] where TIMESTAMP is of the form YYYYMMDD-HHMMSS-MILSEC """ dt = datetime.now().strftime('%Y%m%d-%H%M%S-%f') if ext: return '%s-%s.%s' % (basename, dt, ext) return '%s-%s' % (basename, ...
Return a string of the form [basename-TIMESTAMP.ext] where TIMESTAMP is of the form YYYYMMDD-HHMMSS-MILSEC
def send_one_ping(self, current_socket): """ Send one ICMP ECHO_REQUEST. """ # Header is type (8), code (8), checksum (16), id (16), sequence (16) checksum = 0 # Make a dummy header with a 0 checksum. header = struct.pack( "!BBHHH", ICMP_ECHO, 0, chec...
Send one ICMP ECHO_REQUEST.
def p_block_statements(self, p): 'block_statements : block_statements block_statement' p[0] = p[1] + (p[2],) p.set_lineno(0, p.lineno(1))
block_statements : block_statements block_statement
def embeddedFileGet(self, id): """Retrieve embedded file content by name or by number.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") return _fitz.Document_embeddedFileGet(self, id)
Retrieve embedded file content by name or by number.
def _get_marX(self, attr_name, default): """ Generalized method to get margin values. """ if self.tcPr is None: return Emu(default) return Emu(int(self.tcPr.get(attr_name, default)))
Generalized method to get margin values.
def prime_check(n): """Return True if n is a prime number Else return False. """ if n <= 1: return False if n == 2 or n == 3: return True if n % 2 == 0 or n % 3 == 0: return False j = 5 while j * j <= n: if n % j == 0 or n % (j + 2) == 0: retu...
Return True if n is a prime number Else return False.
def copy_figure(self): """Copy figure to clipboard.""" if self.fmt in ['image/png', 'image/jpeg']: qpixmap = QPixmap() qpixmap.loadFromData(self.fig, self.fmt.upper()) QApplication.clipboard().setImage(qpixmap.toImage()) elif self.fmt == 'image/svg+xml': ...
Copy figure to clipboard.
def p_try_statement_3(self, p): """try_statement : TRY block catch finally""" p[0] = self.asttypes.Try(statements=p[2], catch=p[3], fin=p[4]) p[0].setpos(p)
try_statement : TRY block catch finally
def update_particle(self, part, chi=0.729843788, c=2.05): """Constriction factor update particle method. Notes ----- Looks for a list of neighbours attached to a particle and uses the particle's best position and that of the best neighbour. """ neighbour_...
Constriction factor update particle method. Notes ----- Looks for a list of neighbours attached to a particle and uses the particle's best position and that of the best neighbour.
def _represent_match_traversal(match_traversal): """Emit MATCH query code for an entire MATCH traversal sequence.""" output = [] output.append(_first_step_to_match(match_traversal[0])) for step in match_traversal[1:]: output.append(_subsequent_step_to_match(step)) return u''.join(output)
Emit MATCH query code for an entire MATCH traversal sequence.
def _type_insert(self, handle, key, value): ''' Insert the value into the series. ''' if value!=0: if isinstance(value,float): handle.incrbyfloat(key, value) else: handle.incr(key,value)
Insert the value into the series.
def get_sites(self): """ Returns a list of sites. http://dev.wheniwork.com/#listing-sites """ url = "/2/sites" data = self._get_resource(url) sites = [] for entry in data['sites']: sites.append(self.site_from_json(entry)) return site...
Returns a list of sites. http://dev.wheniwork.com/#listing-sites
def add_op_request_access_to_group(self, name, namespace=None, permission=None, key_name=None, object_prefix_permissions=None): """ Adds the requested permissions to the current service's Ceph key, allowing the key to ...
Adds the requested permissions to the current service's Ceph key, allowing the key to access only the specified pools or object prefixes. object_prefix_permissions should be a dictionary keyed on the permission with the corresponding value being a list of prefixes to apply that permissio...
def perform_put(self, path, body, x_ms_version=None): ''' Performs a PUT request and returns the response. path: Path to the resource. Ex: '/<subscription-id>/services/hostedservices/<service-name>' body: Body for the PUT request. x_ms_version...
Performs a PUT request and returns the response. path: Path to the resource. Ex: '/<subscription-id>/services/hostedservices/<service-name>' body: Body for the PUT request. x_ms_version: If specified, this is used for the x-ms-version header. ...
def catch_all(path): """Catch all path - return a JSON 404 """ return (dict(error='Invalid URL: /{}'.format(path), links=dict(root='{}{}'.format(request.url_root, PREFIX[1:]))), HTTPStatus.NOT_FOUND)
Catch all path - return a JSON 404
def uninstall(self, updates): ''' Uninstall the updates passed in the updates collection. Load the updates collection using the ``search`` or ``available`` functions. .. note:: Starting with Windows 10 the Windows Update Agent is unable to uninstall updates. An ``Uninstall Not A...
Uninstall the updates passed in the updates collection. Load the updates collection using the ``search`` or ``available`` functions. .. note:: Starting with Windows 10 the Windows Update Agent is unable to uninstall updates. An ``Uninstall Not Allowed`` error is returned. If this error ...
def dialectfromstring(s): """ Attempts to convert a string representation of a CSV dialect (as would be read from a file header, for instance) into an actual csv.Dialect object. """ try: AST = compiler.parse(s) except SyntaxError: return else: try: ...
Attempts to convert a string representation of a CSV dialect (as would be read from a file header, for instance) into an actual csv.Dialect object.
def move_in_stack(move_up): '''Move up or down the stack (for the py-up/py-down command)''' frame = Frame.get_selected_python_frame() while frame: if move_up: iter_frame = frame.older() else: iter_frame = frame.newer() if not iter_frame: break ...
Move up or down the stack (for the py-up/py-down command)
def _echo_setting(key): """Echo a setting to the CLI.""" value = getattr(settings, key) secho('%s: ' % key, fg='magenta', bold=True, nl=False) secho( six.text_type(value), bold=True, fg='white' if isinstance(value, six.text_type) else 'cyan', )
Echo a setting to the CLI.
def make_strain_from_inj_object(self, inj, delta_t, detector_name, distance_scale=1): """Make a h(t) strain time-series from an injection object as read from an hdf file. Parameters ----------- inj : injection object The injection ...
Make a h(t) strain time-series from an injection object as read from an hdf file. Parameters ----------- inj : injection object The injection object to turn into a strain h(t). delta_t : float Sample rate to make injection at. detector_name : stri...
def _check_error(self, response, json_response=None): ''' Check for HTTP error code from the response, raise exception if there's any Args: response (object): Object returned by requests' `get` and `post` methods json_response (dict): JSON response, if applicabl...
Check for HTTP error code from the response, raise exception if there's any Args: response (object): Object returned by requests' `get` and `post` methods json_response (dict): JSON response, if applicable Raises: HTTPError: If the status code of re...
def select_catalogue(self, selector, distance=None): ''' Selects the catalogue of earthquakes attributable to the source :param selector: Populated instance of openquake.hmtk.seismicity.selector.CatalogueSelector class :param float distance: Distance ...
Selects the catalogue of earthquakes attributable to the source :param selector: Populated instance of openquake.hmtk.seismicity.selector.CatalogueSelector class :param float distance: Distance (in km) to extend or contract (if negative) the zone for sele...
async def join(self, ctx, *, channel: discord.VoiceChannel): """Joins a voice channel""" if ctx.voice_client is not None: return await ctx.voice_client.move_to(channel) await channel.connect()
Joins a voice channel
def read_scanimage_metadata(fh): """Read ScanImage BigTIFF v3 static and ROI metadata from open file. Return non-varying frame data as dict and ROI group data as JSON. The settings can be used to read image data and metadata without parsing the TIFF file. Raise ValueError if file does not contain...
Read ScanImage BigTIFF v3 static and ROI metadata from open file. Return non-varying frame data as dict and ROI group data as JSON. The settings can be used to read image data and metadata without parsing the TIFF file. Raise ValueError if file does not contain valid ScanImage v3 metadata.
def get_user(username): ''' Get username line from switch .. code-block: bash salt '*' onyx.cmd get_user username=admin ''' try: enable() configure_terminal() cmd_out = sendline('show running-config | include "username {0} password 7"'.format(username)) cmd_...
Get username line from switch .. code-block: bash salt '*' onyx.cmd get_user username=admin
async def entries_exists(self, url, urls=''): """ GET /api/entries/exists.{_format} Check if an entry exist by url. :param url string true An url Url to check if it exists :param urls string false An array of urls (?urls[]=http...&urls[]=http...) Urls (as an array...
GET /api/entries/exists.{_format} Check if an entry exist by url. :param url string true An url Url to check if it exists :param urls string false An array of urls (?urls[]=http...&urls[]=http...) Urls (as an array) to check if it exists :return result
def recommend(self, userid, user_items, N=10, filter_already_liked_items=True, filter_items=None, recalculate_user=False): """ Recommends items for a user Calculates the N best recommendations for a user, and returns a list of itemids, score. Parameters ------...
Recommends items for a user Calculates the N best recommendations for a user, and returns a list of itemids, score. Parameters ---------- userid : int The userid to calculate recommendations for user_items : csr_matrix A sparse matrix of shape (number_us...
async def send_venue(self, latitude: base.Float, longitude: base.Float, title: base.String, address: base.String, foursquare_id: typing.Union[base.String, None] = None, disable_notification: typing.Union[base.Boolean, None] = None, reply_markup=...
Use this method to send information about a venue. Source: https://core.telegram.org/bots/api#sendvenue :param latitude: Latitude of the venue :type latitude: :obj:`base.Float` :param longitude: Longitude of the venue :type longitude: :obj:`base.Float` :param title: Nam...
def get_trunk_interfaces(auth, url, devid=None, devip=None): """Function takes devId as input to RESTFULL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass ...
Function takes devId as input to RESTFULL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: str requires devid of the target device :param d...
def get_timefactor(cls) -> float: """Factor to adjust a new value of a time-dependent parameter. For a time-dependent parameter, its effective value depends on the simulation step size. Method |Parameter.get_timefactor| returns the fraction between the current simulation step size and ...
Factor to adjust a new value of a time-dependent parameter. For a time-dependent parameter, its effective value depends on the simulation step size. Method |Parameter.get_timefactor| returns the fraction between the current simulation step size and the current parameter step size. ...
def run_application(component: Union[Component, Dict[str, Any]], *, event_loop_policy: str = None, max_threads: int = None, logging: Union[Dict[str, Any], int, None] = INFO, start_timeout: Union[int, float, None] = 10): """ Configure logging and start the given root compo...
Configure logging and start the given root component in the default asyncio event loop. Assuming the root component was started successfully, the event loop will continue running until the process is terminated. Initializes the logging system first based on the value of ``logging``: * If the value i...
def read(cls, f): """Read header from file. Headers end with length and then 1 blank line.""" url = None line = f.readline() if not line: # EOF return None while not line.startswith(cls.LENGTH_HEADER): if line.startswith(cls.URI_HEADER): url = line[len(cls.URI_HEADER):].st...
Read header from file. Headers end with length and then 1 blank line.
def import_task_to_graph(diagram_graph, process_id, process_attributes, task_element): """ Adds to graph the new element that represents BPMN task. In our representation tasks have only basic attributes and elements, inherited from Activity type, so this method only needs to call add_flo...
Adds to graph the new element that represents BPMN task. In our representation tasks have only basic attributes and elements, inherited from Activity type, so this method only needs to call add_flownode_to_graph. :param diagram_graph: NetworkX graph representing a BPMN process diagram, ...
def _map_filtered_clusters_to_full_clusters(self, clusters, filter_map): """ Input: clusters, a list of cluster lists filter_map, the seq_id in each clusters ...
Input: clusters, a list of cluster lists filter_map, the seq_id in each clusters is the key to the filter_map containing all seq_ids with duplicate FASTA sequences Output: an extended list of...
def Nu_plate_Muley_Manglik(Re, Pr, chevron_angle, plate_enlargement_factor): r'''Calculates Nusselt number for single-phase flow in a Chevron-style plate heat exchanger according to [1]_, also shown in [2]_ and [3]_. .. math:: Nu = [0.2668 - 0.006967(\beta) + 7.244\times 10^{-5}(\beta)^2]...
r'''Calculates Nusselt number for single-phase flow in a Chevron-style plate heat exchanger according to [1]_, also shown in [2]_ and [3]_. .. math:: Nu = [0.2668 - 0.006967(\beta) + 7.244\times 10^{-5}(\beta)^2] \times[20.7803 - 50.9372\phi + 41.1585\phi^2 - 10.1507\phi^3] \t...
def __load_file(self, key_list) -> str: """ Load a translator file """ file = str(key_list[0]) + self.extension key_list.pop(0) file_path = os.path.join(self.path, file) if os.path.exists(file_path): return Json.from_file(file_path) else: r...
Load a translator file
def params_as_tensors_for(*objs, convert=True): """ Context manager which changes the representation of parameters and data holders for the specific parameterized object(s). This can also be used to turn off tensor conversion functions wrapped with `params_as_tensors`: ``` @gpflow.params_as...
Context manager which changes the representation of parameters and data holders for the specific parameterized object(s). This can also be used to turn off tensor conversion functions wrapped with `params_as_tensors`: ``` @gpflow.params_as_tensors def compute_something(self): # self is paramet...
def _validate_calibration_params(strategy='accuracy', min_rate=None, beta=1.): """Ensure that calibration parameters have allowed values""" if strategy not in ('accuracy', 'f_beta', 'max_tpr', 'max_tnr'): raise ValueError('Strategy can either be "...
Ensure that calibration parameters have allowed values
def verifydropdown(self, window_name, object_name): """ Verify drop down list / menu poped up @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type i...
Verify drop down list / menu poped up @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type in, either full name, LDTP's name convention, or a Unix glob. ...
def unregister(self, condition_set): """ Unregisters a condition set with the manager. >>> gargoyle.unregister(condition_set) #doctest: +SKIP """ if callable(condition_set): condition_set = condition_set() self._registry.pop(condition_set.get_id(), None)
Unregisters a condition set with the manager. >>> gargoyle.unregister(condition_set) #doctest: +SKIP
def get_event_consumer(config, success_channel, error_channel, metrics, **kwargs): """Get a GPSEventConsumer client. A factory function that validates configuration, creates schema validator and parser clients, creates an auth and a pubsub client, and returns an event consumer (:...
Get a GPSEventConsumer client. A factory function that validates configuration, creates schema validator and parser clients, creates an auth and a pubsub client, and returns an event consumer (:interface:`gordon.interfaces. IRunnable` and :interface:`gordon.interfaces.IMessageHandler`) provider. ...
def getArguments(parser): "Provides additional validation of the arguments collected by argparse." args = parser.parse_args() if args.width <= 0: raise argparse.ArgumentError(args.width, 'The contour width must be a positive number.') return args
Provides additional validation of the arguments collected by argparse.
def adjust_weights_discrepancy(self, resfile=None,original_ceiling=True): """adjusts the weights of each non-zero weight observation based on the residual in the pest residual file so each observations contribution to phi is 1.0 Parameters ---------- resfile : str ...
adjusts the weights of each non-zero weight observation based on the residual in the pest residual file so each observations contribution to phi is 1.0 Parameters ---------- resfile : str residual file name. If None, try to use a residual file with the P...
def float_greater_or_equal(threshold: float) -> Callable: """ Returns a method that can be used in argument parsing to check that the float argument is greater or equal to `threshold`. :param threshold: The threshold that we assume the cli argument value is greater or equal to. :return: A method that c...
Returns a method that can be used in argument parsing to check that the float argument is greater or equal to `threshold`. :param threshold: The threshold that we assume the cli argument value is greater or equal to. :return: A method that can be used as a type in argparse.
def mergecn(args): """ %prog mergecn FACE.csv Compile matrix of GC-corrected copy numbers. Place a bunch of folders in csv file. Each folder will be scanned, one chromosomes after another. """ p = OptionParser(mergecn.__doc__) opts, args = p.parse_args(args) if len(args) != 1: ...
%prog mergecn FACE.csv Compile matrix of GC-corrected copy numbers. Place a bunch of folders in csv file. Each folder will be scanned, one chromosomes after another.
def mechanism(self): """tuple[int]: The nodes of the mechanism in the partition.""" return tuple(sorted( chain.from_iterable(part.mechanism for part in self)))
tuple[int]: The nodes of the mechanism in the partition.
def notify(title, message, api_key=NTFY_API_KEY, provider_key=None, priority=0, url=None, retcode=None): """ Optional parameters: * ``api_key`` - use your own application token * ``provider_key`` - if you are whitelisted *...
Optional parameters: * ``api_key`` - use your own application token * ``provider_key`` - if you are whitelisted * ``priority`` * ``url``
def load(self): """ Loads updated attributues for a LoadBalancer object. Requires self.id to be set. """ data = self.get_data('load_balancers/%s' % self.id, type=GET) load_balancer = data['load_balancer'] # Setting the attribute values for attr in load_b...
Loads updated attributues for a LoadBalancer object. Requires self.id to be set.
def verifySignature(ecPublicSigningKey, message, signature): """ :type ecPublicSigningKey: ECPublicKey :type message: bytearray :type signature: bytearray """ if ecPublicSigningKey.getType() == Curve.DJB_TYPE: result = _curve.verifySignature(ecPublicSigningKe...
:type ecPublicSigningKey: ECPublicKey :type message: bytearray :type signature: bytearray
def get_login_theme(): """Load a custom login theme (e.g. snow)""" today = datetime.now().date() if today.month == 12 or today.month == 1: # Snow return {"js": "themes/snow/snow.js", "css": "themes/snow/snow.css"} if today.month == 3 and (14 <= today.day <= 16): return {"js": "t...
Load a custom login theme (e.g. snow)
def unpack_grad_tuple(gv, gpt): """Unpack a previously packed collection of gradient tensors. Args: gv: A (grad, var) pair to be unpacked. gpt: A GradPackTuple describing the packing operation that produced gv. Returns: A list of (grad, var) pairs corresponding to the values that were origina...
Unpack a previously packed collection of gradient tensors. Args: gv: A (grad, var) pair to be unpacked. gpt: A GradPackTuple describing the packing operation that produced gv. Returns: A list of (grad, var) pairs corresponding to the values that were originally packed into gv, maybe following sub...
def compile(self, module): '''compile High-level api: Compile a module. Parameters ---------- module : `str` Module name that is inquired about. Returns ------- Model A Model object. ''' imports, depends = self...
compile High-level api: Compile a module. Parameters ---------- module : `str` Module name that is inquired about. Returns ------- Model A Model object.
def get_new(mserver_url, token, board): '''get node sn and key''' thread = termui.waiting_echo("Getting message from Server...") thread.daemon = True thread.start() try: params = {"name":"node000", "board":board, "access_token":token} r = requests.post("%s%s" %(mserver_url, nodes_cre...
get node sn and key
def _select_Generic_superclass_parameters(subclass, superclass_origin): """Helper for _issubclass_Generic. """ subclass = _find_base_with_origin(subclass, superclass_origin) if subclass is None: return None if subclass.__origin__ is superclass_origin: return subclass.__args__ prm...
Helper for _issubclass_Generic.
def _update_centers(X, membs, n_clusters): """ Update Cluster Centers: calculate the mean of feature vectors for each cluster """ centers = np.empty(shape=(n_clusters, X.shape[1]), dtype=float) sse = np.empty(shape=n_clusters, dtype=float) for clust_id in range(n_clusters): memb_i...
Update Cluster Centers: calculate the mean of feature vectors for each cluster
def _download_query(self, as_of): """Formulate the specific query needed for download Not intended to be called by developers directly. :param as_of: Date in 'YYYYMMDD' format :type as_of: string """ c = self.institution.client() q = c.bank_account_query( ...
Formulate the specific query needed for download Not intended to be called by developers directly. :param as_of: Date in 'YYYYMMDD' format :type as_of: string
def spec(self) -> list: """Returns prefix unary operators list. Sets only one regex for all items in the dict.""" spec = [item for op, pat in self.ops.items() for item in [('{' + op, {'pat': pat, 'postf': self.postf, 'regex': None}), (...
Returns prefix unary operators list. Sets only one regex for all items in the dict.
async def ListModels(self, tag): ''' tag : str Returns -> typing.Sequence[~UserModel] ''' # map input types to rpc msg _params = dict() msg = dict(type='ModelManager', request='ListModels', version=5, params...
tag : str Returns -> typing.Sequence[~UserModel]
def mt_fields(fields, nomaster=False, onlydefaultlang=False): """ Returns list of fields for multilanguage fields of model. Examples: print(mt_fields('name', 'desc')) ['name', 'name_en', 'name_uk', 'desc', 'desc_en', 'desc_uk'] MyModel.objects.only(*mt_fields('name', 'desc', 'conten...
Returns list of fields for multilanguage fields of model. Examples: print(mt_fields('name', 'desc')) ['name', 'name_en', 'name_uk', 'desc', 'desc_en', 'desc_uk'] MyModel.objects.only(*mt_fields('name', 'desc', 'content')) If nomaster then master field will not be append. F.e.: ['na...
def generate_lines(input_file, start=0, stop=float('inf')): """Generate (yield) lines in a gzipped file (*.txt.gz) one line at a time""" with gzip.GzipFile(input_file, 'rU') as f: for i, line in enumerate(f): if i < start: continue ...
Generate (yield) lines in a gzipped file (*.txt.gz) one line at a time
def check_site_enabled(site): ''' Checks to see if the specific site symlink is in /etc/apache2/sites-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_site_enabled example.com ...
Checks to see if the specific site symlink is in /etc/apache2/sites-enabled. This will only be functional on Debian-based operating systems (Ubuntu, Mint, etc). CLI Examples: .. code-block:: bash salt '*' apache.check_site_enabled example.com salt '*' apache.check_site_enabled exampl...
def parse_argument(string: str) -> Union[str, Tuple[str, str]]: """Return a single value for a string understood as a positional argument or a |tuple| containing a keyword and its value for a string understood as a keyword argument. |parse_argument| is intended to be used as a helper function for f...
Return a single value for a string understood as a positional argument or a |tuple| containing a keyword and its value for a string understood as a keyword argument. |parse_argument| is intended to be used as a helper function for function |execute_scriptfunction| only. See the following examples ...
def query_nexus(query_url, timeout_sec, basic_auth=None): """Queries Nexus for an artifact :param query_url: (str) Query URL :param timeout_sec: (int) query timeout :param basic_auth (HTTPBasicAuth) object or none :return: requests.Response object :raises: RuntimeError """ log = logging...
Queries Nexus for an artifact :param query_url: (str) Query URL :param timeout_sec: (int) query timeout :param basic_auth (HTTPBasicAuth) object or none :return: requests.Response object :raises: RuntimeError
def p2pkh_input_and_witness(outpoint, sig, pubkey, sequence=0xFFFFFFFE): ''' OutPoint, hex_string, hex_string, int -> (TxIn, InputWitness) Create a signed legacy TxIn from a p2pkh prevout Create an empty InputWitness for it Useful for transactions spending some witness and some legacy prevouts '...
OutPoint, hex_string, hex_string, int -> (TxIn, InputWitness) Create a signed legacy TxIn from a p2pkh prevout Create an empty InputWitness for it Useful for transactions spending some witness and some legacy prevouts
def send_invite_email(application, link, is_secret): """ Sends an email inviting someone to create an account""" if not application.applicant.email: return context = CONTEXT.copy() context['receiver'] = application.applicant context['application'] = application context['link'] = link ...
Sends an email inviting someone to create an account
def map_entity(self, entity: dal.Price) -> PriceModel: """ Map the price entity """ if not entity: return None result = PriceModel() result.currency = entity.currency # date/time dt_string = entity.date format_string = "%Y-%m-%d" if entity.ti...
Map the price entity
def replace_between_tags(text, repl_, start_tag, end_tag=None): r""" Replaces text between sentinal lines in a block of text. Args: text (str): repl_ (str): start_tag (str): end_tag (str): (default=None) Returns: str: new_text CommandLine: python -m...
r""" Replaces text between sentinal lines in a block of text. Args: text (str): repl_ (str): start_tag (str): end_tag (str): (default=None) Returns: str: new_text CommandLine: python -m utool.util_str --exec-replace_between_tags Example: >>...
def _get_error_code(self, e): """Extract error code from ftp exception""" try: matches = self.error_code_pattern.match(str(e)) code = int(matches.group(0)) return code except ValueError: return e
Extract error code from ftp exception
def get_host(environ): # type: (Dict[str, str]) -> str """Return the host for the given WSGI environment. Yanked from Werkzeug.""" if environ.get("HTTP_HOST"): rv = environ["HTTP_HOST"] if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"): rv = rv[:-3] elif envi...
Return the host for the given WSGI environment. Yanked from Werkzeug.
def insert_object_into_db_pk_unknown(self, obj: Any, table: str, fieldlist: Sequence[str]) -> None: """Inserts object into database table, with PK (first field) initially unknown (a...
Inserts object into database table, with PK (first field) initially unknown (and subsequently set in the object from the database).
def toggle_exclusivity(self,override=None): """ Toggles mouse exclusivity via pyglet's :py:meth:`set_exclusive_mouse()` method. If ``override`` is given, it will be used instead. You may also read the current exclusivity state via :py:attr:`exclusive`\ . """ ...
Toggles mouse exclusivity via pyglet's :py:meth:`set_exclusive_mouse()` method. If ``override`` is given, it will be used instead. You may also read the current exclusivity state via :py:attr:`exclusive`\ .
def crop(self, vector, resolution=None, masked=None, bands=None, resampling=Resampling.cubic): """ crops raster outside vector (convex hull) :param vector: GeoVector, GeoFeature, FeatureCollection :param resolution: output resolution, None for full resolution :param ...
crops raster outside vector (convex hull) :param vector: GeoVector, GeoFeature, FeatureCollection :param resolution: output resolution, None for full resolution :param resampling: reprojection resampling method, default `cubic` :return: GeoRaster
def alerts(self, alert_level='High'): """Get a filtered list of alerts at the given alert level, and sorted by alert level.""" alerts = self.zap.core.alerts() alert_level_value = self.alert_levels[alert_level] alerts = sorted((a for a in alerts if self.alert_levels[a['risk']] >= alert_l...
Get a filtered list of alerts at the given alert level, and sorted by alert level.
def get_rich_menu_image(self, rich_menu_id, timeout=None): """Call download rich menu image API. https://developers.line.me/en/docs/messaging-api/reference/#download-rich-menu-image :param str rich_menu_id: ID of the rich menu with the image to be downloaded :param timeout: (optional) ...
Call download rich menu image API. https://developers.line.me/en/docs/messaging-api/reference/#download-rich-menu-image :param str rich_menu_id: ID of the rich menu with the image to be downloaded :param timeout: (optional) How long to wait for the server to send data before giving...
def generate_code_cover(self): """ Generate a list of all recovered basic blocks. """ lst = [] for cfg_node in self.graph.nodes(): size = cfg_node.size lst.append((cfg_node.addr, size)) lst = sorted(lst, key=lambda x: x[0]) return lst
Generate a list of all recovered basic blocks.
def write_data(self, data, dstart=None, swap_axes=True): """Write ``data`` to `file`. Parameters ---------- data : `array-like` Data that should be written to `file`. dstart : non-negative int, optional Offset in bytes of the start position of the written...
Write ``data`` to `file`. Parameters ---------- data : `array-like` Data that should be written to `file`. dstart : non-negative int, optional Offset in bytes of the start position of the written data. If provided, reshaping and axis swapping of ``dat...
def update(self, campaign_id, area, nick=None): '''xxxxx.xxxxx.campaign.area.update =================================== 更新一个推广计划的投放地域''' request = TOPRequest('xxxxx.xxxxx.campaign.area.update') request['campaign_id'] = campaign_id request['area'] = area if nick!=N...
xxxxx.xxxxx.campaign.area.update =================================== 更新一个推广计划的投放地域
def create(cls, options, session, build_root=None, exclude_patterns=None, tags=None): """ :param Options options: An `Options` instance to use. :param session: The Scheduler session :param string build_root: The build root. """ # Determine the literal target roots. spec_roots = cls.parse_spe...
:param Options options: An `Options` instance to use. :param session: The Scheduler session :param string build_root: The build root.
def actor2ImageData(actor, spacing=(1, 1, 1)): """ Convert a mesh it into volume representation as ``vtkImageData`` where the foreground (exterior) voxels are 1 and the background (interior) voxels are 0. Internally the ``vtkPolyDataToImageStencil`` class is used. .. hint:: |mesh2volume| |mesh2...
Convert a mesh it into volume representation as ``vtkImageData`` where the foreground (exterior) voxels are 1 and the background (interior) voxels are 0. Internally the ``vtkPolyDataToImageStencil`` class is used. .. hint:: |mesh2volume| |mesh2volume.py|_
def control_gate(control: Qubit, gate: Gate) -> Gate: """Return a controlled unitary gate. Given a gate acting on K qubits, return a new gate on K+1 qubits prepended with a control bit. """ if control in gate.qubits: raise ValueError('Gate and control qubits overlap') qubits = [control, *gate....
Return a controlled unitary gate. Given a gate acting on K qubits, return a new gate on K+1 qubits prepended with a control bit.
def _add_logo(fig, x=10, y=25, zorder=100, which='metpy', size='small', **kwargs): """Add the MetPy or Unidata logo to a figure. Adds an image to the figure. Parameters ---------- fig : `matplotlib.figure` The `figure` instance used for plotting x : int x position padding in pixe...
Add the MetPy or Unidata logo to a figure. Adds an image to the figure. Parameters ---------- fig : `matplotlib.figure` The `figure` instance used for plotting x : int x position padding in pixels y : float y position padding in pixels zorder : int The zorder of...
def as_html(self, max_rows=0): """Format table as HTML.""" if not max_rows or max_rows > self.num_rows: max_rows = self.num_rows omitted = max(0, self.num_rows - max_rows) labels = self.labels lines = [ (0, '<table border="1" class="dataframe">'), ...
Format table as HTML.
def _learning_rate_decay(hparams, warmup_steps=0): """Learning rate decay multiplier.""" scheme = hparams.learning_rate_decay_scheme warmup_steps = tf.to_float(warmup_steps) global_step = _global_step(hparams) if not scheme or scheme == "none": return tf.constant(1.) tf.logging.info("Applying learning...
Learning rate decay multiplier.
def clean(self): """Remove internal fields""" doc = self._resource result = {k: v for k, v in doc.iteritems() if k not in self.internal_fields} if '_id' in doc and 'id' not in result: result['id'] = doc['_id'] return result
Remove internal fields
def lcsr(s1, s2): '''longest common sequence ratio >>> lcsr('ab', 'abcd') 0.5 ''' if s1 == s2: return 1.0 return llcs(s1, s2) / max(1, len(s1), len(s2))
longest common sequence ratio >>> lcsr('ab', 'abcd') 0.5
def use(ctx, shortcut): """Use a shortcut.""" git_dir = current_git_dir() if git_dir is None: output(NOT_GIT_REPO_MSG) exit(1) repo_root = os.path.dirname(git_dir) config = get_config(repo_root) try: use_shortcut = config.shortcuts.get(shortcut) while use_sho...
Use a shortcut.