code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def suggest(query): ''' Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found. ''' search_params = { 'list': 'search', 'srinfo': 'suggestion', 'srprop': '', } search_params['srsearch'] = query raw_result = _wiki_request(search_params) if raw_...
Get a Wikipedia search suggestion for `query`. Returns a string or None if no suggestion was found.
def diag(ax=None, linecolor='0.0', linestyle='--', **kwargs): """Plot the diagonal.""" ax = get_ax(ax) xy_min = np.min((ax.get_xlim(), ax.get_ylim())) xy_max = np.max((ax.get_ylim(), ax.get_xlim())) return ax.plot([xy_min, xy_max], [xy_min, xy_max], ls=linestyle, ...
Plot the diagonal.
def extract_stack(start=0): """ SNAGGED FROM traceback.py Altered to return Data Extract the raw traceback from the current stack frame. Each item in the returned list is a quadruple (filename, line number, function name, text), and the entries are in order from newest to oldest """ ...
SNAGGED FROM traceback.py Altered to return Data Extract the raw traceback from the current stack frame. Each item in the returned list is a quadruple (filename, line number, function name, text), and the entries are in order from newest to oldest
def rotate(self, word): """Replaced by a letter 5 right shift. e.g. a->f, b->g, . -> .""" before = string.printable[:62] after = ''.join([i[5:] + i[:5] for i in [string.digits, string.ascii_lowercase, ...
Replaced by a letter 5 right shift. e.g. a->f, b->g, . -> .
def to_latex(self): """ Returns a LaTeX representation of an attribute-value matrix """ latex = r"[{} " for attribute, value in self: if attribute in ['speaker_model', 'is_in_commonground']: continue value_l = value.to_latex() if value_l == "": continue ...
Returns a LaTeX representation of an attribute-value matrix
def modify_process_summary(self, pid=None, text='', append=False): ''' modify_process_summary(self, pid=None, text='') Modifies the summary text of the process execution :Parameters: * *key* (`pid`) -- Identifier of an existing process * *key* (`text`) -- summary text ...
modify_process_summary(self, pid=None, text='') Modifies the summary text of the process execution :Parameters: * *key* (`pid`) -- Identifier of an existing process * *key* (`text`) -- summary text * *append* (`boolean`) -- True to append to summary. False to override it.
def sort(self, **parameters): """ Parameters: `by`: pass either a field name or a wildcard string to sort on prefix with `-` to make a desc sort. `alpha`: set it to True to sort lexicographically instead of numerically. """ parameters = self._coerce_by_param...
Parameters: `by`: pass either a field name or a wildcard string to sort on prefix with `-` to make a desc sort. `alpha`: set it to True to sort lexicographically instead of numerically.
def is_transaction_signer_authorized(self, transactions, state_root, from_state): """ Check the transaction signing key against the allowed transactor permissions. The roles being checked are the following, from first to last: "tra...
Check the transaction signing key against the allowed transactor permissions. The roles being checked are the following, from first to last: "transactor.transaction_signer.<TP_Name>" "transactor.transaction_signer" "transactor" "def...
async def connect_message(self, message, context): """Handle a connect message. See :meth:`AbstractDeviceAdapter.connect`. """ conn_string = message.get('connection_string') client_id = context.user_data await self.connect(client_id, conn_string)
Handle a connect message. See :meth:`AbstractDeviceAdapter.connect`.
def centroid(X): """ Calculate the centroid from a matrix X """ C = np.sum(X, axis=0) / len(X) return C
Calculate the centroid from a matrix X
def _call_command(self, name, *args, **kwargs): """ Check if the command to be executed is a modifier, to connect the object. Then call _traverse_command. """ obj = getattr(self, '_instance', self) # _instance if a field, self if an instance # The object may not be alre...
Check if the command to be executed is a modifier, to connect the object. Then call _traverse_command.
def play_video(self, video_id, playlist_id=None): """ Play video(video_id) now. This ignores the current play queue order. :param video_id: YouTube video id(http://youtube.com/watch?v=video_id) :param playlist_id: youtube.com/watch?v=video_id&list=playlist_id """ self.sta...
Play video(video_id) now. This ignores the current play queue order. :param video_id: YouTube video id(http://youtube.com/watch?v=video_id) :param playlist_id: youtube.com/watch?v=video_id&list=playlist_id
def is_valid_ext_comm_attr(attr): """Validates *attr* as string representation of RT or SOO. Returns True if *attr* is as per our convention of RT or SOO, else False. Our convention is to represent RT/SOO is a string with format: *global_admin_part:local_admin_path* """ if not isinstance(attr, ...
Validates *attr* as string representation of RT or SOO. Returns True if *attr* is as per our convention of RT or SOO, else False. Our convention is to represent RT/SOO is a string with format: *global_admin_part:local_admin_path*
def _set_media_type(self, v, load=False): """ Setter method for media_type, mapped from YANG variable /brocade_interface_ext_rpc/get_interface_detail/output/interface/media_type (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_media_type is considered as a p...
Setter method for media_type, mapped from YANG variable /brocade_interface_ext_rpc/get_interface_detail/output/interface/media_type (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_media_type is considered as a private method. Backends looking to populate this v...
def initial_finall_mass_relation(self,marker='o',linestyle='--'): ''' INtiial to final mass relation ''' final_m=[] ini_m=[] for i in range(len(self.runs_H5_surf)): sefiles=se(self.runs_H5_out[i]) ini_m.append(sefiles.get("mini")) h1=sefiles.get(i...
INtiial to final mass relation
def block_sep1(self, Y): """Separate variable into component corresponding to Y1 in Y.""" Y1 = Y[..., self.cri.M:] # If cri.Cd > 1 (multi-channel dictionary), we need to undo the # reshape performed in block_cat if self.cri.Cd > 1: shp = list(Y1.shape) s...
Separate variable into component corresponding to Y1 in Y.
def join_url_parts(*args): """ Joins a list of segments into a URL-like string :type args: List<string> """ # check for edge case if len(args) == 1: return args[0] return_val = clean_url_segment(args[0]) for i in range(1, len(args)): arg = args[i] if i == len(a...
Joins a list of segments into a URL-like string :type args: List<string>
def regress_components( data, components, remove_mean=True ): """ Returns data with components regressed out. :param bool remove_mean: whether or not demean data (i.e. degree 0), :param int axis: numpy array axes along which regression is performed """ timepoints = data.shape[0] betas = np.l...
Returns data with components regressed out. :param bool remove_mean: whether or not demean data (i.e. degree 0), :param int axis: numpy array axes along which regression is performed
def change_password(): """ Changes the standard password from neo4j to testing to be able to run the test suite. """ basic_auth = '%s:%s' % (DEFAULT_USERNAME, DEFAULT_PASSWORD) try: # Python 2 auth = base64.encodestring(basic_auth) except TypeError: # Python 3 auth = base64.enc...
Changes the standard password from neo4j to testing to be able to run the test suite.
def main(args=None): """ Main function. This function is the command line entry point. Args: args (list of str): the arguments passed to the program. Returns: int: return code being 0 (OK), 1 (dsm empty) or 2 (error). """ parser = get_parser() args = parser.parse_args(...
Main function. This function is the command line entry point. Args: args (list of str): the arguments passed to the program. Returns: int: return code being 0 (OK), 1 (dsm empty) or 2 (error).
def map_single_axis(low, high, dead_zone, hot_zone, value): """ Apply dead and hot zones before mapping a value to a range. The dead and hot zones are both expressed as the proportion of the axis range which should be regarded as 0.0 or 1.0 (or -1.0 depending on cardinality) respectively, so for example...
Apply dead and hot zones before mapping a value to a range. The dead and hot zones are both expressed as the proportion of the axis range which should be regarded as 0.0 or 1.0 (or -1.0 depending on cardinality) respectively, so for example setting dead zone to 0.2 means the first 20% of the range of the axis w...
def fetch(code) : """ Fetch keywords by Code """ ret = {} code = KeywordFetcher._remove_strings(code) result = KeywordFetcher.prog.findall(code) for keyword in result : if len(keyword) <= 1: continue # Ignore single-length word if keyword.isdigit(): continue # Ignore number if keyword[0] == '-' ...
Fetch keywords by Code
def song_detail(ids): """通过歌曲 ID 获取歌曲的详细信息 :param ids: 歌曲 ID 的 list """ if not isinstance(ids, list): raise ParamsError() c = [] for id in ids: c.append({'id': id}) r = NCloudBot() r.method = 'SONG_DETAIL' r.data = {'c': json.dumps(c), 'ids': c, "csrf_token": ""} ...
通过歌曲 ID 获取歌曲的详细信息 :param ids: 歌曲 ID 的 list
def selection(self): """ Selection property. :return: None if no font is selected and font family name if one is selected. :rtype: None or str """ if self._font.get() is "" or self._font.get() not in self._fonts: return None else: ...
Selection property. :return: None if no font is selected and font family name if one is selected. :rtype: None or str
def genus_specific(self): """ For genus-specific targets, MLST and serotyping, determine if the closest refseq genus is known - i.e. if 16S analyses have been performed. Perform the analyses if required """ # Initialise a variable to store whether the necessary analyses have alre...
For genus-specific targets, MLST and serotyping, determine if the closest refseq genus is known - i.e. if 16S analyses have been performed. Perform the analyses if required
def parse_args(): """ Parse the command line arguments """ parser = argparse.ArgumentParser( description="Import existing secrets to YubiHSM eco system", add_help=True, formatter_class=argparse.ArgumentDefaultsHelpFormatter,) parser.add_argument('-D', '--device', ...
Parse the command line arguments
def _ProcessZipFileWithPlugins(self, parser_mediator, zip_file): """Processes a zip file using all compound zip files. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. zip_file (zipfile.ZipFile): the zip file. I...
Processes a zip file using all compound zip files. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. zip_file (zipfile.ZipFile): the zip file. It should not be closed in this method, but will be closed in P...
def _entity_list_as_bel(entities: Iterable[BaseEntity]) -> str: """Stringify a list of BEL entities.""" return ', '.join( e.as_bel() for e in entities )
Stringify a list of BEL entities.
def guest_inspect_vnics(self, userid_list): """Get the vnics statistics of the guest virtual machines :param userid_list: a single userid string or a list of guest userids :returns: dictionary describing the vnics statistics of the vm in the form {'UID1': ...
Get the vnics statistics of the guest virtual machines :param userid_list: a single userid string or a list of guest userids :returns: dictionary describing the vnics statistics of the vm in the form {'UID1': [{ 'vswitch_name': xx,...
def cli(env, identifier, wait): """Check if a virtual server is ready.""" vsi = SoftLayer.VSManager(env.client) vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS') ready = vsi.wait_for_ready(vs_id, wait) if ready: env.fout("READY") else: raise exceptions.CLIAbort("Inst...
Check if a virtual server is ready.
def get_include_methods(request): """Retrieve include_methods values from the request """ methods = request.get("include_methods", "") include_methods = [ x.strip() for x in methods.split(",") if x.strip()] return include_methods
Retrieve include_methods values from the request
def from_values(cls, vals): "Deprecated method to construct tree from list of objects" if util.config.future_deprecations: param.main.param.warning("%s.from_values is deprecated, the %s " "constructor may now be used directly.") return cls(items=c...
Deprecated method to construct tree from list of objects
def parseFilename(filename): """ Parse out filename from any specified extensions. Returns rootname and string version of extension name. """ # Parse out any extension specified in filename _indx = filename.find('[') if _indx > 0: # Read extension name provided _fname = fil...
Parse out filename from any specified extensions. Returns rootname and string version of extension name.
def list_certificates(self): """Get the attributes of the current array certificate. :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert** :type \*\*kwargs: optional :returns: A l...
Get the attributes of the current array certificate. :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert** :type \*\*kwargs: optional :returns: A list of dictionaries describing all confi...
def add_route(route, endpoint=None, **kw): """Add a new JSON API route """ # ensure correct amout of slashes def apiurl(route): return '/'.join(s.strip('/') for s in ["", BASE_URL, route]) return add_senaite_route(apiurl(route), endpoint, **kw)
Add a new JSON API route
def put(self, instance, errors): """ Update a model instance. :param instance: The model instance. :param errors: Any errors. :return: The updated model instance, or a dictionary of errors. """ if errors: return self.errors(errors) return self...
Update a model instance. :param instance: The model instance. :param errors: Any errors. :return: The updated model instance, or a dictionary of errors.
def dump_memory_map(memoryMap, mappedFilenames = None, bits = None): """ Dump the memory map of a process. Optionally show the filenames for memory mapped files as well. @type memoryMap: list( L{win32.MemoryBasicInformation} ) @param memoryMap: Memory map returned by L{Process....
Dump the memory map of a process. Optionally show the filenames for memory mapped files as well. @type memoryMap: list( L{win32.MemoryBasicInformation} ) @param memoryMap: Memory map returned by L{Process.get_memory_map}. @type mappedFilenames: dict( int S{->} str ) @param ma...
async def do_del_aldb(self, args): """Delete device All-Link record. WARNING THIS METHOD CAN DAMAGE YOUR DEVICE IF USED INCORRECTLY. Please ensure the memory id is appropriate for the device. You must load the ALDB of the device before using this method. The memory id must be an...
Delete device All-Link record. WARNING THIS METHOD CAN DAMAGE YOUR DEVICE IF USED INCORRECTLY. Please ensure the memory id is appropriate for the device. You must load the ALDB of the device before using this method. The memory id must be an existing memory id in the ALDB or this ...
def after_match(self, func, full_fallback=False): """Returns an iterator for all the elements after the first match. If `full_fallback` is `True`, it will return all the messages if the function never matched. """ iterator = iter(self) for item in iterator: i...
Returns an iterator for all the elements after the first match. If `full_fallback` is `True`, it will return all the messages if the function never matched.
def get_parameter(self, name): """ Get the parameter on this schema with the given C{name}. """ for parameter in self._parameters: if parameter.name == name: return parameter
Get the parameter on this schema with the given C{name}.
def set_unix_socket_params(self, abstract=None, permissions=None, owner=None, umask=None): """Sets Unix-socket related params. :param bool abstract: Force UNIX socket into abstract mode (Linux only). :param str permissions: UNIX sockets are filesystem objects that obey UNIX permiss...
Sets Unix-socket related params. :param bool abstract: Force UNIX socket into abstract mode (Linux only). :param str permissions: UNIX sockets are filesystem objects that obey UNIX permissions like any other filesystem object. You can set the UNIX sockets' permissions with thi...
def validate(self, schema=None): """ Validate that we have a valid object. On error, this will raise a `ScrapeValueError` This also expects that the schemas assume that omitting required in the schema asserts the field is optional, not required. This is due to upstream ...
Validate that we have a valid object. On error, this will raise a `ScrapeValueError` This also expects that the schemas assume that omitting required in the schema asserts the field is optional, not required. This is due to upstream schemas being in JSON Schema v3, and not validictory'...
def get_browser_datetime(webdriver): """ Get the current date/time on the web browser as a Python datetime object. This date matches 'new Date();' when ran in JavaScript console. Args: webdriver: Selenium WebDriver instance Returns: datetime - Py...
Get the current date/time on the web browser as a Python datetime object. This date matches 'new Date();' when ran in JavaScript console. Args: webdriver: Selenium WebDriver instance Returns: datetime - Python datetime object. Usage:: ...
def update_config(self): """Pull any changes made with :py:meth:`set_config`. Call this from within your component before using any config values to ensure you have the latest values set by the user. :return: Whether the config was updated. :rtype: bool """ res...
Pull any changes made with :py:meth:`set_config`. Call this from within your component before using any config values to ensure you have the latest values set by the user. :return: Whether the config was updated. :rtype: bool
def LVMPathSpecGetVolumeIndex(path_spec): """Retrieves the volume index from the path specification. Args: path_spec (PathSpec): path specification. Returns: int: volume index or None if not available. """ volume_index = getattr(path_spec, 'volume_index', None) if volume_index is None: locati...
Retrieves the volume index from the path specification. Args: path_spec (PathSpec): path specification. Returns: int: volume index or None if not available.
def reset(self): """Reset simulated and real environments.""" self._frame_counter = 0 ob_real = self.real_env.reset() # Initialize simulated environment with frames from real one. self.sim_env.add_to_initial_stack(ob_real) for _ in range(3): ob_real, _, _, _ = self.real_env.step(self.name_...
Reset simulated and real environments.
def _call_extractor(extractor, text): """This method calls an extractor on some text. If extractor is just a string, it is passed as the first value to _get_terminal. Otherwise it is treated as a callable and text is passed directly to it. This makes it so you can have a shorthand of terminal(val) <-> val. ...
This method calls an extractor on some text. If extractor is just a string, it is passed as the first value to _get_terminal. Otherwise it is treated as a callable and text is passed directly to it. This makes it so you can have a shorthand of terminal(val) <-> val.
def process_email(ctx, param, value): """Return an user if it exists.""" user = User.query.filter(User.email == value).first() if not user: raise click.BadParameter('User with email \'%s\' not found.', value) return user
Return an user if it exists.
def average_fft(self, fftlength=None, overlap=0, window=None): """Compute the averaged one-dimensional DFT of this `TimeSeries`. This method computes a number of FFTs of duration ``fftlength`` and ``overlap`` (both given in seconds), and returns the mean average. This method is analogou...
Compute the averaged one-dimensional DFT of this `TimeSeries`. This method computes a number of FFTs of duration ``fftlength`` and ``overlap`` (both given in seconds), and returns the mean average. This method is analogous to the Welch average method for power spectra. Paramete...
def python_value(self, value): """ Convert binary blob to UUID instance """ value = super(OrderedUUIDField, self).python_value(value) u = binascii.b2a_hex(value) value = u[8:16] + u[4:8] + u[0:4] + u[16:22] + u[22:32] return UUID(value.decode())
Convert binary blob to UUID instance
def runOnExecutor(self, *commands, oper=ACCEPT, defer_shell_expansion=False): """ This runs in the executor of the current scope. You cannot magically back out since there are no gurantees that ssh keys will be in place (they shouldn't be). """ return self.makeOutput(EXE, command...
This runs in the executor of the current scope. You cannot magically back out since there are no gurantees that ssh keys will be in place (they shouldn't be).
def vcs_virtual_ip_address_inband_interface_ve(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") vcs = ET.SubElement(config, "vcs", xmlns="urn:brocade.com:mgmt:brocade-vcs") virtual = ET.SubElement(vcs, "virtual") ip = ET.SubElement(virtual, "ip") ...
Auto Generated Code
def get_params(self, deep=True): """ Get parameters for this estimator. Arguments --------- deep: boolean, optional If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- ...
Get parameters for this estimator. Arguments --------- deep: boolean, optional If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- params : mapping of string to any Pa...
def get(self, page_size, current_page, session): '''taobao.crm.groups.get 查询卖家的分组 查询卖家的分组,返回查询到的分组列表,分页返回分组''' request = TOPRequest('taobao.crm.groups.get') request['page_size'] = page_size request['current_page'] = current_page self.create(self.execute(request, ...
taobao.crm.groups.get 查询卖家的分组 查询卖家的分组,返回查询到的分组列表,分页返回分组
def partition(src, key=None): """No relation to :meth:`str.partition`, ``partition`` is like :func:`bucketize`, but for added convenience returns a tuple of ``(truthy_values, falsy_values)``. >>> nonempty, empty = partition(['', '', 'hi', '', 'bye']) >>> nonempty ['hi', 'bye'] *key* defaul...
No relation to :meth:`str.partition`, ``partition`` is like :func:`bucketize`, but for added convenience returns a tuple of ``(truthy_values, falsy_values)``. >>> nonempty, empty = partition(['', '', 'hi', '', 'bye']) >>> nonempty ['hi', 'bye'] *key* defaults to :class:`bool`, but can be caref...
def get_sf_values(self, filename='shlp_hour_factors.csv'): """ Determine the h-values Parameters ---------- filename : string name of file where sigmoid factors are stored """ file = os.path.join(self.datapath, filename) hour_factors = pd.read_csv(fil...
Determine the h-values Parameters ---------- filename : string name of file where sigmoid factors are stored
def pb(name, labels, predictions, num_thresholds=None, weights=None, display_name=None, description=None): """Create a PR curves summary protobuf. Arguments: name: A name for the generated node. Will also serve as a series name in TensorBoard. labels: The g...
Create a PR curves summary protobuf. Arguments: name: A name for the generated node. Will also serve as a series name in TensorBoard. labels: The ground truth values. A bool numpy array. predictions: A float32 numpy array whose values are in the range `[0, 1]`. Dimensions must match those...
def _get_statements(self, lines, start): """Returns a list of complete Fortran statements for the specified lines by dealing with comments and line continuations. Returns a list of tuples of the form (linenum, statement, orginal character length). :arg start: the start index in the over...
Returns a list of complete Fortran statements for the specified lines by dealing with comments and line continuations. Returns a list of tuples of the form (linenum, statement, orginal character length). :arg start: the start index in the overall document for these lines.
def ack(self, items): """Acknowledge the given messages. Args: items(Sequence[AckRequest]): The items to acknowledge. """ # If we got timing information, add it to the histogram. for item in items: time_to_ack = item.time_to_ack if time_to_ack...
Acknowledge the given messages. Args: items(Sequence[AckRequest]): The items to acknowledge.
def badRequestMethod(self, environ, start_response): """ Return HTTP 400 Bad Request. """ response = "400 Bad Request\n\nTo access this PyAMF gateway you " \ "must use POST requests (%s received)" % environ['REQUEST_METHOD'] start_response('400 Bad Request', [ ...
Return HTTP 400 Bad Request.
def get_customjs(self, references, plot_id=None): """ Creates a CustomJS callback that will send the requested attributes back to python. """ # Generate callback JS code to get all the requested data if plot_id is None: plot_id = self.plot.id or 'PLACEHOLDER_P...
Creates a CustomJS callback that will send the requested attributes back to python.
def _rc_sdiffstore(self, dst, src, *args): """ Store the difference of sets ``src``, ``args`` into a new set named ``dest``. Returns the number of keys in the new set. """ args = list_or_args(src, args) result = self.sdiff(*args) if result is not set([]): ...
Store the difference of sets ``src``, ``args`` into a new set named ``dest``. Returns the number of keys in the new set.
def get_config(self, config_filename): """ Collection all config file in all available apps, and merge them into ini object :return: ini object """ x = pyini.Ini(lazy=True, basepath=os.path.join(self.project_dir, 'apps')) for p in reversed(self.apps): app_path...
Collection all config file in all available apps, and merge them into ini object :return: ini object
def smart_account(app): """尝试使用内置方式构建账户""" if os.environ['FANTASY_ACTIVE_ACCOUNT'] == 'no': return from flask_security import SQLAlchemyUserDatastore, Security account_module_name, account_class_name = os.environ[ 'FANTASY_ACCOUNT_MODEL'].rsplit('.', 1) account_module = importlib....
尝试使用内置方式构建账户
def controversial(self, limit=None): """GETs controversial links from this subreddit. Calls :meth:`narwal.Reddit.controversial`. :param limit: max number of links to return """ return self._reddit.controversial(self.display_name, limit=limit)
GETs controversial links from this subreddit. Calls :meth:`narwal.Reddit.controversial`. :param limit: max number of links to return
def clean_source_index(self): """ Cleanup broken symbolic links in the local source distribution index. The purpose of this method requires some context to understand. Let me preface this by stating that I realize I'm probably overcomplicating things, but I like to preserve forw...
Cleanup broken symbolic links in the local source distribution index. The purpose of this method requires some context to understand. Let me preface this by stating that I realize I'm probably overcomplicating things, but I like to preserve forward / backward compatibility when possible...
def query(query, use_sudo=True, **kwargs): """ Run a MySQL query. """ func = use_sudo and run_as_root or run user = kwargs.get('mysql_user') or env.get('mysql_user') password = kwargs.get('mysql_password') or env.get('mysql_password') options = [ '--batch', '--raw', ...
Run a MySQL query.
def get_dataset(): """Create a dataset for machine learning of segmentations. Returns ------- tuple : (X, y) where X is a list of tuples. Each tuple is a feature. y is a list of labels (0 for 'not in one symbol' and 1 for 'in symbol') """ seg_data = "segmentation-X.npy" seg_...
Create a dataset for machine learning of segmentations. Returns ------- tuple : (X, y) where X is a list of tuples. Each tuple is a feature. y is a list of labels (0 for 'not in one symbol' and 1 for 'in symbol')
def parallel_apply_transformations(x, transforms, black_border_size=0): """ Apply image transformations in parallel. :param transforms: TODO :param black_border_size: int, size of black border to apply Returns: Transformed images """ transforms = tf.convert_to_tensor(transforms, dtype=tf.float32) x ...
Apply image transformations in parallel. :param transforms: TODO :param black_border_size: int, size of black border to apply Returns: Transformed images
def _read_para_via_rvs(self, code, cbit, clen, *, desc, length, version): """Read HIP VIA_RVS parameter. Structure of HIP VIA_RVS parameter [RFC 6028]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1...
Read HIP VIA_RVS parameter. Structure of HIP VIA_RVS parameter [RFC 6028]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ...
def log_flush_for_obj_for_interval(self, log_type, obj_id, interval): """Flush logs for an interval of time for a specific object. Please note, log_type is a variable according to the API docs, but acceptable values are not listed. Only "policies" is demonstrated as an acceptable value....
Flush logs for an interval of time for a specific object. Please note, log_type is a variable according to the API docs, but acceptable values are not listed. Only "policies" is demonstrated as an acceptable value. Args: log_type (str): Only documented type is "policies". T...
def GetSitelinksFromFeed(client, feed): """Gets the sitelinks from a feed. Args: client: an AdWordsClient instance. feed: the feed used to retrieve sitelinks. Returns: A dictionary mapping the feed item ID to SiteLinkFromFeed. """ # Retrieve the feed's attribute mapping. feed_mappings = GetFee...
Gets the sitelinks from a feed. Args: client: an AdWordsClient instance. feed: the feed used to retrieve sitelinks. Returns: A dictionary mapping the feed item ID to SiteLinkFromFeed.
def build(opts=None): """ Build a new board using the given options. :param opts: dictionary mapping str->Opt :return: the new board, Board """ board = catan.board.Board() modify(board, opts) return board
Build a new board using the given options. :param opts: dictionary mapping str->Opt :return: the new board, Board
def getResultsTotalCount(self): """ The total number of analysis results parsed """ count = 0 for val in self.getRawResults().values(): count += len(val) return count
The total number of analysis results parsed
def groups(username, **kwargs): ''' Authenticate against an LDAP group Behavior is highly dependent on if Active Directory is in use. AD handles group membership very differently than OpenLDAP. See the :ref:`External Authentication <acl-eauth>` documentation for a thorough discussion of availa...
Authenticate against an LDAP group Behavior is highly dependent on if Active Directory is in use. AD handles group membership very differently than OpenLDAP. See the :ref:`External Authentication <acl-eauth>` documentation for a thorough discussion of available parameters for customizing the search. ...
def p_recipe(self, t): """recipe : RECIPE_LINE | RECIPE_LINE recipe""" if len(t) == 3: t[0] = t[1] + t[2] else: t[0] = t[1]
recipe : RECIPE_LINE | RECIPE_LINE recipe
def set_state(self): """ Sets the state required for this vertex region. Currently binds and enables the texture of the material of the region. """ glEnable(self.region.material.target) glBindTexture(self.region.material.target, self.region.material.id) s...
Sets the state required for this vertex region. Currently binds and enables the texture of the material of the region.
def get_registers(self, cpu_id): """Gets all the registers for the given CPU. in cpu_id of type int The identifier of the Virtual CPU. out names of type str Array containing the lowercase register names. out values of type str Array parallel to the ...
Gets all the registers for the given CPU. in cpu_id of type int The identifier of the Virtual CPU. out names of type str Array containing the lowercase register names. out values of type str Array parallel to the names holding the register values as if the ...
def get_for_resource(resource): """ Get list of all price list items that should be used for resource. If price list item is defined for service - return it, otherwise - return default price list item. """ resource_content_type = ContentType.objects.get_for_model(resourc...
Get list of all price list items that should be used for resource. If price list item is defined for service - return it, otherwise - return default price list item.
def parse_dunder_all(self): """Parse the __all__ definition in a module.""" assert self.current.value == '__all__' self.consume(tk.NAME) # More than one __all__ definition means we ignore all __all__. if self.dunder_all is not None or self.dunder_all_error is not None: ...
Parse the __all__ definition in a module.
def get_hash(path, form='sha1', chunk_size=4096): ''' Generate a hash digest string for a file. ''' try: hash_type = getattr(hashlib, form) except AttributeError: raise ValueError('Invalid hash type: {0}'.format(form)) with open(path, 'rb') as ifile: hash_obj = hash_type(...
Generate a hash digest string for a file.
def zopen(filename, *args, **kwargs): """ This function wraps around the bz2, gzip and standard python's open function to deal intelligently with bzipped, gzipped or standard text files. Args: filename (str/Path): filename or pathlib.Path. \*args: Standard args for python open(..). ...
This function wraps around the bz2, gzip and standard python's open function to deal intelligently with bzipped, gzipped or standard text files. Args: filename (str/Path): filename or pathlib.Path. \*args: Standard args for python open(..). E.g., 'r' for read, 'w' for write. ...
def hacking_docstring_multiline_end(physical_line, previous_logical, tokens): r"""Check multi line docstring end. OpenStack HACKING guide recommendation for docstring: Docstring should end on a new line Okay: '''foobar\nfoo\nbar\n''' Okay: def foo():\n '''foobar\n\nfoo\nbar\n''' Okay: class...
r"""Check multi line docstring end. OpenStack HACKING guide recommendation for docstring: Docstring should end on a new line Okay: '''foobar\nfoo\nbar\n''' Okay: def foo():\n '''foobar\n\nfoo\nbar\n''' Okay: class Foo(object):\n '''foobar\n\nfoo\nbar\n''' Okay: def foo():\n a = '''not...
def sparse_dot_product_attention_truncated( q, k, v, bi, # Unused experts_params, use_map_fn=False, # Unused mask_right=False, ): # pylint: disable=unused-argument """Sparse multihead self attention. Perform an approximation of the full multihead attention by dispatching the tokens...
Sparse multihead self attention. Perform an approximation of the full multihead attention by dispatching the tokens using their keys/values. Thus the attention matrix are only computed each times on a subset of the tokens. Notes: * The function don't perform scaling here (multihead_attention does the /sq...
def dataset_filepath(filename, dataset_name=None, task=None, **kwargs): """Get the path of the corresponding dataset file. Parameters ---------- filename : str The name of the file. dataset_name : str, optional The name of the dataset. Used to define a sub-directory to contain all ...
Get the path of the corresponding dataset file. Parameters ---------- filename : str The name of the file. dataset_name : str, optional The name of the dataset. Used to define a sub-directory to contain all instances of the dataset. If not given, a dataset-specific directory is ...
def pop(self): ''' Restores the previous position and returns the last move from the stack. ''' move = self.move_stack.pop() # Update transposition table. self.transpositions.subtract((self.zobrist_hash(), )) # Decrement move number. self.move_number -= ...
Restores the previous position and returns the last move from the stack.
def plot_summary(self, parameters=None, truth=None, extents=None, display=False, filename=None, chains=None, figsize=1.0, errorbar=False, include_truth_chain=True, blind=None, watermark=None, extra_parameter_spacing=0.5, vertical_spacing_ratio=1.0, show_nam...
Plots parameter summaries This plot is more for a sanity or consistency check than for use with final results. Plotting this before plotting with :func:`plot` allows you to quickly see if the chains give well behaved distributions, or if certain parameters are suspect or require a great...
def seek(self, offset, whence=SEEK_SET): """ Change the stream position to the given byte offset. Args: offset (int): Offset is interpreted relative to the position indicated by whence. whence (int): The default value for whence is SEEK_SET. ...
Change the stream position to the given byte offset. Args: offset (int): Offset is interpreted relative to the position indicated by whence. whence (int): The default value for whence is SEEK_SET. Values for whence are: SEEK_SET or 0 – sta...
def cli_values(self, argv): """Parse command-line arguments into values. Parses arguments provided on the command-line (or sys.argv). Only returns arguments that are explicitly supplied, so we strip out defaults and validation rules like `required` in this call. """ opti...
Parse command-line arguments into values. Parses arguments provided on the command-line (or sys.argv). Only returns arguments that are explicitly supplied, so we strip out defaults and validation rules like `required` in this call.
def _get_operation_rpc(self): """Polls the status of the current operation. Uses gRPC request to check. :rtype: :class:`~google.longrunning.operations_pb2.Operation` :returns: The latest status of the current operation. """ request_pb = operations_pb2.GetOperationReques...
Polls the status of the current operation. Uses gRPC request to check. :rtype: :class:`~google.longrunning.operations_pb2.Operation` :returns: The latest status of the current operation.
def dsn(): """ Return a libpq connection string using the variables defined in this file. """ configs = {'host': host, 'port': port, 'dbname': database, 'user': user, 'password': password} return ' '.join(['{0}={1}'.format(_[0], _[1]) for _...
Return a libpq connection string using the variables defined in this file.
def __load(self): """ Loads dynamically the class that acts like a namespace for constants. """ parts = self.__class_name.split('.') module_name = ".".join(parts[:-1]) module = __import__(module_name) modules = [] for comp in parts[1:]: module ...
Loads dynamically the class that acts like a namespace for constants.
def save_model(self, request, entry, form, change): """ Fill the content field with the interpretation of the placeholder """ context = RequestContext(request) try: content = render_placeholder(entry.content_placeholder, context) entry.content = co...
Fill the content field with the interpretation of the placeholder
def print_user(self, user): '''print a relational database user ''' status = "active" token = user.token if token in ['finished', 'revoked']: status = token if token is None: token = '' subid = "%s\t%s[%s]" %(user.id, token, status) print(subid) return subid
print a relational database user
def _set_name(self, version=AUTO): """Returns plugin name.""" name = 'python' if version: if version is AUTO: version = sys.version_info[0] if version == 2: version = '' name = '%s%s' % (name, version) self....
Returns plugin name.
def peek_with_kwargs(init, args=[]): """ Make datatypes passing keyworded arguments to the constructor. This is a factory function; returns the actual `peek` routine. Arguments: init (callable): type constructor. args (iterable): arguments NOT to be keyworded; order does matter. ...
Make datatypes passing keyworded arguments to the constructor. This is a factory function; returns the actual `peek` routine. Arguments: init (callable): type constructor. args (iterable): arguments NOT to be keyworded; order does matter. Returns: callable: deserializer (`peek`...
def production_variant(model_name, instance_type, initial_instance_count=1, variant_name='AllTraffic', initial_weight=1, accelerator_type=None): """Create a production variant description suitable for use in a ``ProductionVariant`` list as part of a ``CreateEndpointConfig`` request. ...
Create a production variant description suitable for use in a ``ProductionVariant`` list as part of a ``CreateEndpointConfig`` request. Args: model_name (str): The name of the SageMaker model this production variant references. instance_type (str): The EC2 instance type for this production vari...
def getname(obj): """ Return the most qualified name of an object :param obj: object to fetch name :return: name of ``obj`` """ for name_attribute in ('__qualname__', '__name__'): try: # an object always has a class, as per Python data model return getattr(obj, n...
Return the most qualified name of an object :param obj: object to fetch name :return: name of ``obj``
def get_auth_token(self, user_payload): """ Extracts username, password from the `user_payload` and encode the credentials `username:password` in `base64` form """ username = user_payload.get('username') or None password = user_payload.get('password') or None if ...
Extracts username, password from the `user_payload` and encode the credentials `username:password` in `base64` form
def show_fuzzy_date(self): """Return whether the event is in the next or previous 2 weeks. Determines whether to display the fuzzy date. """ date = self.time.replace(tzinfo=None) if date <= datetime.now(): diff = datetime.now() - date if diff.days >= 14:...
Return whether the event is in the next or previous 2 weeks. Determines whether to display the fuzzy date.