code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def workdir_is_clean(self, quiet=False): """ Check for uncommitted changes, return `True` if everything is clean. Inspired by http://stackoverflow.com/questions/3878624/. """ # Update the index self.run('git update-index -q --ignore-submodules --refresh', **RUN_KWARGS) ...
Check for uncommitted changes, return `True` if everything is clean. Inspired by http://stackoverflow.com/questions/3878624/.
def load_response_microservices(plugin_path, plugins, internal_attributes, base_url): """ Loads response micro services (handling outgoing responses). :type plugin_path: list[str] :type plugins: list[str] :type internal_attributes: dict[string, dict[str, str | list[str]]] :type base_url: str ...
Loads response micro services (handling outgoing responses). :type plugin_path: list[str] :type plugins: list[str] :type internal_attributes: dict[string, dict[str, str | list[str]]] :type base_url: str :rtype satosa.micro_service.service_base.ResponseMicroService :param plugin_path: Path to t...
def _validate(self, key, cls=None): """Verify the manifest schema.""" if key not in self.manifest: raise ValueError("Manifest %s requires '%s'." % (self.manifest_path, key)) if cls: if not isinstance(self.manifest[key], cls): r...
Verify the manifest schema.
def _rescale_and_convert_field_inplace(self, array, name, scale, zero): """ Apply fits scalings. Also, convert bool to proper numpy boolean values """ self._rescale_array(array[name], scale, zero) if array[name].dtype == numpy.bool: array[name] = self._conver...
Apply fits scalings. Also, convert bool to proper numpy boolean values
def get_plugin_actions(self): """Return a list of actions related to plugin""" quit_action = create_action(self, _("&Quit"), icon=ima.icon('exit'), tip=_("Quit"), triggered=self.quit) ...
Return a list of actions related to plugin
def stats_shooting(self, kind='R', summary=False): """Returns a DataFrame of shooting stats.""" return self._get_stats_table('shooting', kind=kind, summary=summary)
Returns a DataFrame of shooting stats.
def check_all_servers(): """Checks all servers, removing any that Modis isn't part of any more""" data = datatools.get_data() for server_id in data["discord"]["servers"]: is_in_client = False for client_server in client.servers: if server_id == client_server.id: i...
Checks all servers, removing any that Modis isn't part of any more
def _validate_sort_field(self, sort_by): """ :param sort_by: string :raises: pybomb.exceptions.InvalidSortFieldException """ if ( sort_by not in self.RESPONSE_FIELD_MAP or not self.RESPONSE_FIELD_MAP[sort_by].is_sort ): raise InvalidSor...
:param sort_by: string :raises: pybomb.exceptions.InvalidSortFieldException
def metafetcher(bamfile, metacontig2contig, metatag): ''' return reads in order of metacontigs''' for metacontig in metacontig2contig: for contig in metacontig2contig[metacontig]: for read in bamfile.fetch(contig): read.set_tag(metatag, metacontig) yield read
return reads in order of metacontigs
def _get_headers(self): """Built headers for request to IPinfo API.""" headers = { 'user-agent': 'IPinfoClient/Python{version}/1.0'.format(version=sys.version_info[0]), 'accept': 'application/json' } if self.access_token: headers['authorization'] = 'B...
Built headers for request to IPinfo API.
def encode_exception(exception): """Encode exception to a form that can be passed around and serialized. This will grab the stack, then strip off the last two calls which are encode_exception and the function that called it. """ import sys return AsyncException(unicode(exception), ...
Encode exception to a form that can be passed around and serialized. This will grab the stack, then strip off the last two calls which are encode_exception and the function that called it.
def from_metadata(self, db_path, db_name='engine_metadata.db'): """ Registers in the current session the views of the MetadataSource so the data is obtained from the metadata database instead of reading the repositories with the DefaultSource. :param db_path: path to the folder ...
Registers in the current session the views of the MetadataSource so the data is obtained from the metadata database instead of reading the repositories with the DefaultSource. :param db_path: path to the folder that contains the database. :type db_path: str :param db_name: name ...
def p2th_address(self) -> Optional[str]: '''P2TH address of this deck''' if self.id: return Kutil(network=self.network, privkey=bytearray.fromhex(self.id)).address else: return None
P2TH address of this deck
def long_description(*filenames): """Provide a long description.""" res = [''] for filename in filenames: with open(filename) as fp: for line in fp: res.append(' ' + line) res.append('') res.append('\n') return EMPTYSTRING.join(res)
Provide a long description.
def _shrink_update(self, rmstart: int, rmstop: int) -> None: """Update self._type_to_spans according to the removed span. Warning: If an operation involves both _shrink_update and _insert_update, you might wanna consider doing the _insert_update before the _shrink_update as this functio...
Update self._type_to_spans according to the removed span. Warning: If an operation involves both _shrink_update and _insert_update, you might wanna consider doing the _insert_update before the _shrink_update as this function can cause data loss in self._type_to_spans.
def configfield_ref_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Process a role that references the Task configuration field nodes created by the ``lsst-config-fields``, ``lsst-task-config-subtasks``, and ``lsst-task-config-subtasks`` directives. P...
Process a role that references the Task configuration field nodes created by the ``lsst-config-fields``, ``lsst-task-config-subtasks``, and ``lsst-task-config-subtasks`` directives. Parameters ---------- name The role name used in the document. rawtext The entire markup snippet,...
def plot_mean_field_conv(N=1, n=0.5, Uspan=np.arange(0, 3.6, 0.5)): """Generates the plot on the convergenge of the mean field in single site spin hamiltonian under with N degenerate half-filled orbitals """ sl = Spinon(slaves=2*N, orbitals=N, avg_particles=2*n, hopping=[0.5]*2*N,...
Generates the plot on the convergenge of the mean field in single site spin hamiltonian under with N degenerate half-filled orbitals
def sanitize_and_wrap(self, task_id, args, kwargs): """This function should be called **ONLY** when all the futures we track have been resolved. If the user hid futures a level below, we will not catch it, and will (most likely) result in a type error. Args: task_id (uuid ...
This function should be called **ONLY** when all the futures we track have been resolved. If the user hid futures a level below, we will not catch it, and will (most likely) result in a type error. Args: task_id (uuid str) : Task id func (Function) : App function ...
def import_keypair(kwargs=None, call=None): ''' Import an SSH public key. .. versionadded:: 2015.8.3 ''' if call != 'function': log.error( 'The import_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} ...
Import an SSH public key. .. versionadded:: 2015.8.3
def find_sdl_attrs(prefix: str) -> Iterator[Tuple[str, Any]]: """Return names and values from `tcod.lib`. `prefix` is used to filter out which names to copy. """ from tcod._libtcod import lib if prefix.startswith("SDL_"): name_starts_at = 4 elif prefix.startswith("SDL"): name_s...
Return names and values from `tcod.lib`. `prefix` is used to filter out which names to copy.
def read_array(self, key, start=None, stop=None): """ read an array for the specified node (off of group """ import tables node = getattr(self.group, key) attrs = node._v_attrs transposed = getattr(attrs, 'transposed', False) if isinstance(node, tables.VLArray): ...
read an array for the specified node (off of group
def get_range(self): """ Return the possible types for this parameter's value. (I.e. return {name: <class>} for all classes that are concrete_descendents() of self.class_.) Only classes from modules that have been imported are added (see concrete_descendents()). ...
Return the possible types for this parameter's value. (I.e. return {name: <class>} for all classes that are concrete_descendents() of self.class_.) Only classes from modules that have been imported are added (see concrete_descendents()).
def simple_moving_matrix(x, n=10): """ Create simple moving matrix. Parameters ---------- x : ndarray A numpy array n : integer The number of sample points used to make average Returns ------- ndarray A n x n numpy array which will be useful for calculating ...
Create simple moving matrix. Parameters ---------- x : ndarray A numpy array n : integer The number of sample points used to make average Returns ------- ndarray A n x n numpy array which will be useful for calculating confidentail interval of simple moving ...
def get_templates(self): """ Get list of templates this object use :return: list of templates :rtype: list """ use = getattr(self, 'use', '') if isinstance(use, list): return [n.strip() for n in use if n.strip()] return [n.strip() for n in us...
Get list of templates this object use :return: list of templates :rtype: list
def local_assortativity_wu_sign(W): ''' Local assortativity measures the extent to which nodes are connected to nodes of similar strength. Adapted from Thedchanamoorthy et al. 2014 formula to allowed weighted/signed networks. Parameters ---------- W : NxN np.ndarray undirected conne...
Local assortativity measures the extent to which nodes are connected to nodes of similar strength. Adapted from Thedchanamoorthy et al. 2014 formula to allowed weighted/signed networks. Parameters ---------- W : NxN np.ndarray undirected connection matrix with positive and negative weights ...
def add_message(self, text, type=None): """Add a message with an optional type.""" key = self._msg_key self.setdefault(key, []) self[key].append(message(type, text)) self.save()
Add a message with an optional type.
def decode_transformer(encoder_output, encoder_decoder_attention_bias, targets, hparams, name, task=None, causal=True): """Original Transformer decoder.""" orig_hparams = hparams...
Original Transformer decoder.
def cover(ctx, html=False): '''Run tests suite with coverage''' header('Run tests suite with coverage') cmd = 'pytest --cov udata --cov-report term' if html: cmd = ' '.join((cmd, '--cov-report html:reports/python/cover')) with ctx.cd(ROOT): ctx.run(cmd, pty=True)
Run tests suite with coverage
def global_maxpooling(attrs, inputs, proto_obj): """Performs max pooling on the input.""" new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True, 'kernel': (1, 1), ...
Performs max pooling on the input.
def buffered_write(self, buf): """Appends a bytes like object to the transport write buffer. Raises BufferOverflowError if buf would cause the buffer to grow beyond the specified maximum. buf -- bytes to send """ if self.closed: raise ConnectionClosed() ...
Appends a bytes like object to the transport write buffer. Raises BufferOverflowError if buf would cause the buffer to grow beyond the specified maximum. buf -- bytes to send
def full_name(self, gender: Optional[Gender] = None, reverse: bool = False) -> str: """Generate a random full name. :param reverse: Return reversed full name. :param gender: Gender's enum object. :return: Full name. :Example: Johann Wolfgang. ...
Generate a random full name. :param reverse: Return reversed full name. :param gender: Gender's enum object. :return: Full name. :Example: Johann Wolfgang.
def index(credentials=None): """Get list of projects""" user, oauth_access_token = parsecredentials(credentials) if not settings.ADMINS or user not in settings.ADMINS: return flask.make_response('You shall not pass!!! You are not an administrator!',403) usersprojects = {} ...
Get list of projects
def failover(self, sync=None, force=None): """ Fails over a replication session. :param sync: True - sync the source and destination resources before failing over the asynchronous replication session or keep them in sync after failing over the synchronous replication ses...
Fails over a replication session. :param sync: True - sync the source and destination resources before failing over the asynchronous replication session or keep them in sync after failing over the synchronous replication session. False - don't sync. :param force: Tru...
def process_config(self): """ Intended to put any code that should be run after any config reload event """ if 'byte_unit' in self.config: if isinstance(self.config['byte_unit'], basestring): self.config['byte_unit'] = self.config['byte_unit'].split() ...
Intended to put any code that should be run after any config reload event
def main( gpus:Param("The GPUs to use for distributed training", str)='all', script:Param("Script to run", str, opt=False)='', args:Param("Args to pass to script", nargs='...', opt=False)='' ): "PyTorch distributed training launch helper that spawns multiple distributed processes" # Loosely based on...
PyTorch distributed training launch helper that spawns multiple distributed processes
def _pluck_feature_pacts(pr_body: str) -> FrozenSet[str]: """ # Returns set with one feature pact if specified >>> body = 'gitlab: mygitlaburl.com\\r\\nfeature-pacts: zh-feature-a' >>> _pluck_feature_pacts(body) == frozenset({'zh-feature-a'}) True # Returns set with multiple feature pacts if sp...
# Returns set with one feature pact if specified >>> body = 'gitlab: mygitlaburl.com\\r\\nfeature-pacts: zh-feature-a' >>> _pluck_feature_pacts(body) == frozenset({'zh-feature-a'}) True # Returns set with multiple feature pacts if specified >>> body = 'gitlab: mygitlaburl.com\\r\\nfeature-pacts: zh...
def __process_warc_gz_file(self, path_name): """ Iterates all transactions in one WARC file and for each transaction tries to extract an article object. Afterwards, each article is checked against the filter criteria and if all are passed, the function on_valid_article_extracted is invok...
Iterates all transactions in one WARC file and for each transaction tries to extract an article object. Afterwards, each article is checked against the filter criteria and if all are passed, the function on_valid_article_extracted is invoked with the article object. :param path_name: :re...
def _getData(self, data): """ Check that data is acceptable and return it. Default behavior is that the data has to be of type `dict`. In derived classes this method could for example allow `None` or empty strings and just return empty dictionary. :raises: ``ValidationError`` i...
Check that data is acceptable and return it. Default behavior is that the data has to be of type `dict`. In derived classes this method could for example allow `None` or empty strings and just return empty dictionary. :raises: ``ValidationError`` if data is missing or wrong type ...
def getAnalogChannelData(self,ChNumber): """ Returns an array of numbers containing the data values of the channel number "ChNumber". ChNumber is the number of the channal as in .cfg file. """ if not self.DatFileContent: print "No data file content. ...
Returns an array of numbers containing the data values of the channel number "ChNumber". ChNumber is the number of the channal as in .cfg file.
def fixLabel(label, maxlen, delim=None, repl='', truncend=True): """Truncate long graph and field labels. @param label: Label text. @param maxlen: Maximum field label length in characters. No maximum field label length is enforced by default. @param delim: ...
Truncate long graph and field labels. @param label: Label text. @param maxlen: Maximum field label length in characters. No maximum field label length is enforced by default. @param delim: Delimiter for field labels field labels longer than ...
def get_special_scen_code(regions, emissions): """ Get special code for MAGICC6 SCEN files. At the top of every MAGICC6 and MAGICC5 SCEN file there is a two digit number. The first digit, the 'scenfile_region_code' tells MAGICC how many regions data is being provided for. The second digit, the 'sce...
Get special code for MAGICC6 SCEN files. At the top of every MAGICC6 and MAGICC5 SCEN file there is a two digit number. The first digit, the 'scenfile_region_code' tells MAGICC how many regions data is being provided for. The second digit, the 'scenfile_emissions_code', tells MAGICC which gases are in ...
def update_record(self, name, recordid, content, username, password): ''' Update record ''' # headers = {'key': username, 'secret': password} req = requests.put(self.api_server + '/api/' + name + '/' + str(recordid), data=json.dumps(content), ...
Update record
def make_cell(table, span, widths, heights, use_headers): """ Convert the contents of a span of the table to a grid table cell Parameters ---------- table : list of lists of str The table of rows containg strings to convert to a grid table span : list of lists of int list of [ro...
Convert the contents of a span of the table to a grid table cell Parameters ---------- table : list of lists of str The table of rows containg strings to convert to a grid table span : list of lists of int list of [row, column] pairs that make up a span in the table widths : list of...
def contourf_to_geojson_overlap(contourf, geojson_filepath=None, min_angle_deg=None, ndigits=5, unit='', stroke_width=1, fill_opacity=.9, geojson_properties=None, strdump=False, serialize=True): """Transform matplotlib.contourf to geojson with overlapp...
Transform matplotlib.contourf to geojson with overlapping filled contours.
def printData(self, output = sys.stdout): """Output all the file data to be written to any writable output""" self.printDatum("Name : ", self.fileName, output) self.printDatum("Author : ", self.author, output) self.printDatum("Repository : ", self.repository, output) self.printDatum("Catego...
Output all the file data to be written to any writable output
async def update_object(obj, only=None): """Update object asynchronously. :param obj: object to update :param only: list or tuple of fields to updata, is `None` then all fields updated This function does the same as `Model.save()`_ for already saved object, but it doesn't invoke ``save...
Update object asynchronously. :param obj: object to update :param only: list or tuple of fields to updata, is `None` then all fields updated This function does the same as `Model.save()`_ for already saved object, but it doesn't invoke ``save()`` method on model class. That is impo...
def detokenize(self, inputs, delim=' '): """ Detokenizes single sentence and removes token separator characters. :param inputs: sequence of tokens :param delim: tokenization delimiter returns: string representing detokenized sentence """ detok = delim.join([self...
Detokenizes single sentence and removes token separator characters. :param inputs: sequence of tokens :param delim: tokenization delimiter returns: string representing detokenized sentence
def perform_request(self, request): ''' Sends request to cloud service server and return the response. ''' connection = self.get_connection(request) try: connection.putrequest(request.method, request.path) self.send_request_headers(connection, request.headers) ...
Sends request to cloud service server and return the response.
def DateStringToDateObject(date_string): """Return a date object for a string "YYYYMMDD".""" # If this becomes a bottleneck date objects could be cached if re.match('^\d{8}$', date_string) == None: return None try: return datetime.date(int(date_string[0:4]), int(date_string[4:6]), ...
Return a date object for a string "YYYYMMDD".
def _load(self, filename=None): """Load the Himawari AHI RSR data for the band requested """ if not filename: filename = self.filename wb_ = open_workbook(filename) self.rsr = {} sheet_names = [] for sheet in wb_.sheets(): if sheet.name in...
Load the Himawari AHI RSR data for the band requested
def get(remote_file, local_file): """ Retrieve a file from the board. Get will download a file from the board and print its contents or save it locally. You must pass at least one argument which is the path to the file to download from the board. If you don't specify a second argument then th...
Retrieve a file from the board. Get will download a file from the board and print its contents or save it locally. You must pass at least one argument which is the path to the file to download from the board. If you don't specify a second argument then the file contents will be printed to standard ou...
def get_relative_abundance(biomfile): """ Return arcsine transformed relative abundance from a BIOM format file. :type biomfile: BIOM format file :param biomfile: BIOM format file used to obtain relative abundances for each OTU in a SampleID, which are used as node sizes in network...
Return arcsine transformed relative abundance from a BIOM format file. :type biomfile: BIOM format file :param biomfile: BIOM format file used to obtain relative abundances for each OTU in a SampleID, which are used as node sizes in network plots. :type return: Dictionary of dictionar...
def pool(arr, block_size, func, cval=0, preserve_dtype=True): """ Resize an array by pooling values within blocks. dtype support:: * ``uint8``: yes; fully tested * ``uint16``: yes; tested * ``uint32``: yes; tested (2) * ``uint64``: no (1) * ``int8``: yes; tested ...
Resize an array by pooling values within blocks. dtype support:: * ``uint8``: yes; fully tested * ``uint16``: yes; tested * ``uint32``: yes; tested (2) * ``uint64``: no (1) * ``int8``: yes; tested * ``int16``: yes; tested * ``int32``: yes; tested (2) ...
def decode(self, bytes, raw=False): """decode(bytearray, raw=False) -> value Decodes the given bytearray according the corresponding EVR Definition (:class:`EVRDefn`) for the underlying 'MSB_U16' EVR code. If the optional parameter ``raw`` is ``True``, the EVR code itse...
decode(bytearray, raw=False) -> value Decodes the given bytearray according the corresponding EVR Definition (:class:`EVRDefn`) for the underlying 'MSB_U16' EVR code. If the optional parameter ``raw`` is ``True``, the EVR code itself will be returned instead of the EVR Definiti...
def simple_newton(f, x0, lb=None, ub=None, infos=False, verbose=False, maxit=50, tol=1e-8, eps=1e-8, numdiff=True): '''Solves many independent systems f(x)=0 simultaneously using a simple gradient descent. :param f: objective function to be solved with values p x N . The second output argument represents the de...
Solves many independent systems f(x)=0 simultaneously using a simple gradient descent. :param f: objective function to be solved with values p x N . The second output argument represents the derivative with values in (p x p x N) :param x0: initial value ( p x N ) :return: solution x such that f(x) = 0
def construct_user_list(raw_users=None): """Construct a list of User objects from a list of dicts.""" users = Users(oktypes=User) for user_dict in raw_users: public_keys = None if user_dict.get('public_keys'): public_keys = [PublicKey(b64encoded=x, raw=Non...
Construct a list of User objects from a list of dicts.
def bond_canonical_statistics( microcanonical_statistics, convolution_factors, **kwargs ): """ canonical cluster statistics for a single run and a single probability Parameters ---------- microcanonical_statistics : ndarray Return value of `bond_microcanonical_statistics` ...
canonical cluster statistics for a single run and a single probability Parameters ---------- microcanonical_statistics : ndarray Return value of `bond_microcanonical_statistics` convolution_factors : 1-D array_like The coefficients of the convolution for the given probabilty ``p`` ...
def _add_to_index(index, obj): """Adds the given object ``obj`` to the given ``index``""" id_set = index.value_map.setdefault(indexed_value(index, obj), set()) if index.unique: if len(id_set) > 0: raise UniqueConstraintError() id_set.add(obj.id)
Adds the given object ``obj`` to the given ``index``
def highlight_text(text, lexer_name='python', **kwargs): r""" SeeAlso: color_text """ # Resolve extensions to languages lexer_name = { 'py': 'python', 'h': 'cpp', 'cpp': 'cpp', 'c': 'cpp', }.get(lexer_name.replace('.', ''), lexer_name) if lexer_name in...
r""" SeeAlso: color_text
def datasets_view(self, owner_slug, dataset_slug, **kwargs): # noqa: E501 """Show details about a dataset # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_view(owner_slug, d...
Show details about a dataset # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_view(owner_slug, dataset_slug, async_req=True) >>> result = thread.get() :param async_r...
def p_expr_LE_expr(p): """ expr : expr LE expr """ p[0] = make_binary(p.lineno(2), 'LE', p[1], p[3], lambda x, y: x <= y)
expr : expr LE expr
def __convertRlocToRouterId(self, xRloc16): """mapping Rloc16 to router id Args: xRloc16: hex rloc16 short address Returns: actual router id allocated by leader """ routerList = [] routerList = self.__sendCommand(WPANCTL_CMD + 'getprop -v Thread:...
mapping Rloc16 to router id Args: xRloc16: hex rloc16 short address Returns: actual router id allocated by leader
def on_menu_exit(self, event): """ Runs whenever Thellier GUI exits """ if self.close_warning: TEXT = "Data is not saved to a file yet!\nTo properly save your data:\n1) Analysis --> Save current interpretations to a redo file.\nor\n1) File --> Save MagIC tables.\n\n Press OK ...
Runs whenever Thellier GUI exits
def count_function(func): """ Decorator for functions that return a collection (technically a dict of collections) that should be counted up. Also automatically falls back to the Cohort-default filter_fn and normalized_per_mb if not specified. """ # Fall back to Cohort-level defaults. @use_d...
Decorator for functions that return a collection (technically a dict of collections) that should be counted up. Also automatically falls back to the Cohort-default filter_fn and normalized_per_mb if not specified.
def index_based_complete(self, text: str, line: str, begidx: int, endidx: int, index_dict: Mapping[int, Union[Iterable, Callable]], all_else: Union[None, Iterable, Callable] = None) -> List[str]: """ Tab completes based on a fixed position in the...
Tab completes based on a fixed position in the input string :param text: the string prefix we are attempting to match (all returned matches must begin with it) :param line: the current input line with leading whitespace removed :param begidx: the beginning index of the prefix text :param...
def from_record(cls, record, crs): """Load vector from record.""" if 'type' not in record: raise TypeError("The data isn't a valid record.") return cls(to_shape(record), crs)
Load vector from record.
def prepend(cls, d, s, filter=Filter()): """ Prepend schema object's from B{s}ource list to the B{d}estination list while applying the filter. @param d: The destination list. @type d: list @param s: The source list. @type s: list @param filter: A filter th...
Prepend schema object's from B{s}ource list to the B{d}estination list while applying the filter. @param d: The destination list. @type d: list @param s: The source list. @type s: list @param filter: A filter that allows items to be prepended. @type filter: L{Filt...
def send_document(chat_id, document, reply_to_message_id=None, reply_markup=None, **kwargs): """ Use this method to send general files. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param document: File to send. You can either pa...
Use this method to send general files. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param document: File to send. You can either pass a file_id as String to resend a file that is already on the Telegram servers, or upload a new file using multipart/fo...
def get_login_redirect(self, provider, account): """Return url to redirect authenticated users.""" info = self.model._meta.app_label, self.model._meta.model_name # inline import to prevent circular imports. from .admin import PRESERVED_FILTERS_SESSION_KEY preserved_filters = self...
Return url to redirect authenticated users.
def delete(self, name, **kwargs): """Delete a Label on the server. Args: name: The name of the label **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabDeleteError: ...
Delete a Label on the server. Args: name: The name of the label **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabDeleteError: If the server cannot perform the request
def _normalize_path(self, path): """ Normalizes a file path so that it returns a path relative to the root repo directory. """ norm_path = os.path.normpath(path) return os.path.relpath(norm_path, start=self._get_working_dir())
Normalizes a file path so that it returns a path relative to the root repo directory.
def plot(self, series, series_diff=None, label='', color=None, style=None): ''' :param pandas.Series series: The series to be plotted, all values must be positive if stacked is True. :param pandas.Series series_diff: The series representing the diff that will ...
:param pandas.Series series: The series to be plotted, all values must be positive if stacked is True. :param pandas.Series series_diff: The series representing the diff that will be plotted in the bottom part. :param string label: The label fo...
def verify(self, tool): """ check that the tool exists """ if os.path.isfile(tool['file']): print('Toolbox: program exists = TOK :: ' + tool['file']) return True else: print('Toolbox: program exists = FAIL :: ' + tool['file']) retu...
check that the tool exists
def template(self): """ Create a rules file in ipset --restore format """ s = Template(self._IPSET_TEMPLATE) return s.substitute(sets='\n'.join(self.sets), date=datetime.today())
Create a rules file in ipset --restore format
def add_training_sample(self, text=u'', lang=''): """ Initial step for adding new sample to training data. You need to call `save_training_samples()` afterwards. :param text: Sample text to be added. :param lang: Language label for the input text. """ self.tr...
Initial step for adding new sample to training data. You need to call `save_training_samples()` afterwards. :param text: Sample text to be added. :param lang: Language label for the input text.
async def send_rpc(self, conn_id, address, rpc_id, payload, timeout): """Send an RPC to a device. See :meth:`AbstractDeviceAdapter.send_rpc`. """ adapter_id = self._get_property(conn_id, 'adapter') return await self.adapters[adapter_id].send_rpc(conn_id, address, rpc_id, payloa...
Send an RPC to a device. See :meth:`AbstractDeviceAdapter.send_rpc`.
def users_get_avatar(self, user_id=None, username=None, **kwargs): """Gets the URL for a user’s avatar.""" if user_id: return self.__call_api_get('users.getAvatar', userId=user_id, kwargs=kwargs) elif username: return self.__call_api_get('users.getAvatar', username=userna...
Gets the URL for a user’s avatar.
def _at_if(self, calculator, rule, scope, block): """ Implements @if and @else if """ # "@if" indicates whether any kind of `if` since the last `@else` has # succeeded, in which case `@else if` should be skipped if block.directive != '@if': if '@if' not in rul...
Implements @if and @else if
def run_in_transaction(self, func, *args, **kw): """Perform a unit of work in a transaction, retrying on abort. :type func: callable :param func: takes a required positional argument, the transaction, and additional positional / keyword arguments as supplied ...
Perform a unit of work in a transaction, retrying on abort. :type func: callable :param func: takes a required positional argument, the transaction, and additional positional / keyword arguments as supplied by the caller. :type args: tuple :par...
def get_album_songs(self, album_id): """Get a album's all songs. warning: use old api. :params album_id: album id. :return: a list of Song object. """ url = 'http://music.163.com/api/album/{}/'.format(album_id) result = self.get_request(url) songs = res...
Get a album's all songs. warning: use old api. :params album_id: album id. :return: a list of Song object.
def resolve_symbol(self, symbol, bCaseSensitive = False): """ Resolves a debugging symbol's address. @type symbol: str @param symbol: Name of the symbol to resolve. @type bCaseSensitive: bool @param bCaseSensitive: C{True} for case sensitive matches, C{Fal...
Resolves a debugging symbol's address. @type symbol: str @param symbol: Name of the symbol to resolve. @type bCaseSensitive: bool @param bCaseSensitive: C{True} for case sensitive matches, C{False} for case insensitive. @rtype: int or None @return: Memor...
def _fix_unsafe(shell_input): """Find characters used to escape from a string into a shell, and wrap them in quotes if they exist. Regex pilfered from Python3 :mod:`shlex` module. :param str shell_input: The input intended for the GnuPG process. """ _unsafe = re.compile(r'[^\w@%+=:,./-]', 256) ...
Find characters used to escape from a string into a shell, and wrap them in quotes if they exist. Regex pilfered from Python3 :mod:`shlex` module. :param str shell_input: The input intended for the GnuPG process.
def padded_to_same_length(seq1, seq2, item=0): """Return a pair of sequences of the same length by padding the shorter sequence with ``item``. The padded sequence is a tuple. The unpadded sequence is returned as-is. """ len1, len2 = len(seq1), len(seq2) if len1 == len2: return (seq1, s...
Return a pair of sequences of the same length by padding the shorter sequence with ``item``. The padded sequence is a tuple. The unpadded sequence is returned as-is.
def validate(self): """Checks integrity of workflow and reports any problems with it. Detects: - loops (tasks that wait on each other in a loop) :returns: empty list if valid, a list of errors if not """ results = [] from ..specs import Join def recursiv...
Checks integrity of workflow and reports any problems with it. Detects: - loops (tasks that wait on each other in a loop) :returns: empty list if valid, a list of errors if not
def install(): """Basic Ceph client installation.""" ceph_dir = "/etc/ceph" if not os.path.exists(ceph_dir): os.mkdir(ceph_dir) apt_install('ceph-common', fatal=True)
Basic Ceph client installation.
def probe_image(self, labels, instance, column_name=None, num_scaled_images=50, top_percent=10): """ Get pixel importance of the image. It performs pixel sensitivity analysis by showing only the most important pixels to a certain label in the image. It uses integrated gradie...
Get pixel importance of the image. It performs pixel sensitivity analysis by showing only the most important pixels to a certain label in the image. It uses integrated gradients to measure the importance of each pixel. Args: labels: labels to compute gradients from. ...
def seek_to_end(self, *partitions): """Seek to the most recent available offset for partitions. Arguments: *partitions: Optionally provide specific TopicPartitions, otherwise default to all assigned partitions. Raises: AssertionError: If any partition is...
Seek to the most recent available offset for partitions. Arguments: *partitions: Optionally provide specific TopicPartitions, otherwise default to all assigned partitions. Raises: AssertionError: If any partition is not currently assigned, or if ...
def write_header(self, out_strm, delim, f1_num_fields, f2_num_fields, f1_header=None, f2_header=None, missing_val=None): """ Write the header for a joined file. If headers are provided for one or more of the input files, then a header is generated for the output file. Otherwise, this ...
Write the header for a joined file. If headers are provided for one or more of the input files, then a header is generated for the output file. Otherwise, this does not output anything. :param out_strm: write to this stream :param delim: :param f1_num_fields: the number of columns in the first file...
def updateFromKwargs(self, kwargs, properties, collector, **kw): """By default, the child values will be collapsed into a dictionary. If the parent is anonymous, this dictionary is the top-level properties.""" yield self.collectChildProperties(kwargs=kwargs, properties=properties, ...
By default, the child values will be collapsed into a dictionary. If the parent is anonymous, this dictionary is the top-level properties.
def md2rst(md_lines): 'Only converts headers' lvl2header_char = {1: '=', 2: '-', 3: '~'} for md_line in md_lines: if md_line.startswith('#'): header_indent, header_text = md_line.split(' ', 1) yield header_text header_char = lvl2header_char[len(header_indent)] ...
Only converts headers
def overlap(self, x, ctrs, kdtree=None): """Check how many balls `x` falls within. Uses a K-D Tree to perform the search if provided.""" q = len(self.within(x, ctrs, kdtree=kdtree)) return q
Check how many balls `x` falls within. Uses a K-D Tree to perform the search if provided.
def GET_subdomain_ops(self, path_info, txid): """ Get all subdomain operations processed in a given transaction. Returns the list of subdomains on success (can be empty) Returns 502 on failure to get subdomains """ blockstackd_url = get_blockstackd_url() subdomain...
Get all subdomain operations processed in a given transaction. Returns the list of subdomains on success (can be empty) Returns 502 on failure to get subdomains
def create_srv_record(self, name, values, ttl=60): """ Creates a SRV record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record ...
Creates a SRV record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record (in seconds). :rtype: tuple :returns: A tuple in the fo...
def pickleFile(self, name, minPartitions=None): """ Load an RDD previously saved using L{RDD.saveAsPickleFile} method. >>> tmpFile = NamedTemporaryFile(delete=True) >>> tmpFile.close() >>> sc.parallelize(range(10)).saveAsPickleFile(tmpFile.name, 5) >>> sorted(sc.pickleFi...
Load an RDD previously saved using L{RDD.saveAsPickleFile} method. >>> tmpFile = NamedTemporaryFile(delete=True) >>> tmpFile.close() >>> sc.parallelize(range(10)).saveAsPickleFile(tmpFile.name, 5) >>> sorted(sc.pickleFile(tmpFile.name, 3).collect()) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9...
def sort_key_for_numeric_suffixes(path, sep='.', suffix_index=-2): """ Sort files taking into account potentially absent suffixes like somefile.dcd somefile.1000.dcd somefile.2000.dcd To be used with sorted(..., key=callable). """ chunks = path.split(sep) # Remove suffix...
Sort files taking into account potentially absent suffixes like somefile.dcd somefile.1000.dcd somefile.2000.dcd To be used with sorted(..., key=callable).
def get_sum(path, form='sha256'): ''' Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI...
Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI Example: .. code-block:: bash s...
def _check_valid(key, val, valid): """Helper to check valid options""" if val not in valid: raise ValueError('%s must be one of %s, not "%s"' % (key, valid, val))
Helper to check valid options
def read_group_info(self): """Get information about groups directly from the widget.""" self.groups = [] for i in range(self.tabs.count()): one_group = self.tabs.widget(i).get_info() # one_group['name'] = self.tabs.tabText(i) self.groups.append(one_group)
Get information about groups directly from the widget.
async def validate(self, request: web.Request): """ Returns parameters extract from request and multidict errors :param request: Request :return: tuple of parameters and errors """ parameters = {} files = {} errors = self.errors_factory() body = None ...
Returns parameters extract from request and multidict errors :param request: Request :return: tuple of parameters and errors
def write_training_data(self, features, targets): """ Writes data dictionary to filename """ assert len(features) == len(targets) data = dict(zip(features, targets)) with open(os.path.join(self.repopath, 'training.pkl'), 'w') as fp: pickle.dump(data, fp)
Writes data dictionary to filename