code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_api_gateway_resource(name): """Get the resource associated with our gateway.""" client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] match = matches.pop() resources = clie...
Get the resource associated with our gateway.
def optimize(self, piter=3, pmaxf=300, ppert=0.1): ''' Runs :py:obj:`pPLD` on the target in an attempt to further optimize the values of the PLD priors. See :py:class:`everest.detrender.pPLD`. ''' self._save_npz() optimized = pPLD(self.ID, piter=piter, pmaxf=pmaxf, ...
Runs :py:obj:`pPLD` on the target in an attempt to further optimize the values of the PLD priors. See :py:class:`everest.detrender.pPLD`.
def length_of_associated_transcript(effect): """ Length of spliced mRNA sequence of transcript associated with effect, if there is one (otherwise return 0). """ return apply_to_transcript_if_exists( effect=effect, fn=lambda t: len(t.sequence), default=0)
Length of spliced mRNA sequence of transcript associated with effect, if there is one (otherwise return 0).
def remove(self, line): """Delete all lines matching the given line.""" nb = 0 for block in self.blocks: nb += block.remove(line) return nb
Delete all lines matching the given line.
def is_multilingual_project(site_id=None): """ Whether the current Django project is configured for multilingual support. """ from parler import appsettings if site_id is None: site_id = getattr(settings, 'SITE_ID', None) return appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS or site_id i...
Whether the current Django project is configured for multilingual support.
def axis_names_without(self, axis): """Return axis names without axis, or None if axis_names is None""" if self.axis_names is None: return None return itemgetter(*self.other_axes(axis))(self.axis_names)
Return axis names without axis, or None if axis_names is None
def now_heating(self): """Return current heating state.""" try: if self.side == 'left': heat = self.device.device_data['leftNowHeating'] elif self.side == 'right': heat = self.device.device_data['rightNowHeating'] return heat ex...
Return current heating state.
def get_object(self): """ Get the object for publishing Raises a http404 error if the object is not found. """ obj = super(PublishView, self).get_object() if not obj or not hasattr(obj, 'publish'): raise http.Http404 return obj
Get the object for publishing Raises a http404 error if the object is not found.
def update_position(self, newpos): '''update trail''' tnow = time.time() if tnow >= self.last_time + self.timestep: self.points.append(newpos.latlon) self.last_time = tnow while len(self.points) > self.count: self.points.pop(0)
update trail
def printComparison(results, class_or_prop): """ print(out the results of the comparison using a nice table) """ data = [] Row = namedtuple('Row',[class_or_prop,'VALIDATED']) for k,v in sorted(results.items(), key=lambda x: x[1]): data += [Row(k, str(v))] pprinttable(data)
print(out the results of the comparison using a nice table)
def _make_images(self, images): """ Takes an image dict from the giphy api and converts it to attributes. Any fields expected to be int (width, height, size, frames) will be attempted to be converted. Also, the keys of `data` serve as the attribute names, but with special action ...
Takes an image dict from the giphy api and converts it to attributes. Any fields expected to be int (width, height, size, frames) will be attempted to be converted. Also, the keys of `data` serve as the attribute names, but with special action taken. Keys are split by the last underscore; anythi...
def submit(self, fn, *args, **kwargs): """Submits a callable to be executed with the given arguments. Count maximum reached work queue size in ThreadPoolExecutor.max_queue_size_reached. """ future = super().submit(fn, *args, **kwargs) work_queue_size = self._work_queue.qsize() ...
Submits a callable to be executed with the given arguments. Count maximum reached work queue size in ThreadPoolExecutor.max_queue_size_reached.
def parse(self, fo): """ Convert AMD output to motifs Parameters ---------- fo : file-like File object containing AMD output. Returns ------- motifs : list List of Motif instances. """ motifs = [] ...
Convert AMD output to motifs Parameters ---------- fo : file-like File object containing AMD output. Returns ------- motifs : list List of Motif instances.
def refresh(self, thread=None): """refresh thread metadata from the index""" if not thread: thread = self._dbman._get_notmuch_thread(self._id) self._total_messages = thread.get_total_messages() self._notmuch_authors_string = thread.get_authors() subject_type = setti...
refresh thread metadata from the index
def create_partition(self, partition_spec, if_not_exists=False, async_=False, **kw): """ Create a partition within the table. :param partition_spec: specification of the partition. :param if_not_exists: :param async_: :return: partition object :rtype: odps.models...
Create a partition within the table. :param partition_spec: specification of the partition. :param if_not_exists: :param async_: :return: partition object :rtype: odps.models.partition.Partition
def parse_form_request(api_secret, request): """ >>> parse_form_request("123456",{"nonce": 1451122677, "msg": "helllo", "code": 0, "sign": "DB30F4D1112C20DFA736F65458F89C64"}) <Storage {'nonce': 1451122677, 'msg': 'helllo', 'code': 0, 'sign': 'DB30F4D1112C20DFA736F65458F89C64'}> """ if not c...
>>> parse_form_request("123456",{"nonce": 1451122677, "msg": "helllo", "code": 0, "sign": "DB30F4D1112C20DFA736F65458F89C64"}) <Storage {'nonce': 1451122677, 'msg': 'helllo', 'code': 0, 'sign': 'DB30F4D1112C20DFA736F65458F89C64'}>
def process_common_disease_file(self, raw, unpadded_doids, limit=None): """ Make disaese-phenotype associations. Some identifiers need clean up: * DOIDs are listed as DOID-DOID: --> DOID: * DOIDs may be unnecessarily zero-padded. these are remapped to their non-padded equ...
Make disaese-phenotype associations. Some identifiers need clean up: * DOIDs are listed as DOID-DOID: --> DOID: * DOIDs may be unnecessarily zero-padded. these are remapped to their non-padded equivalent. :param raw: :param unpadded_doids: :param limit: :...
def _delete_request(self, url, headers, data=None): """ Issue a DELETE request to the specified endpoint with the data provided. :param url: str :pararm headers: dict :param data: dict """ return self._session.delete(url, headers=headers, data=data)
Issue a DELETE request to the specified endpoint with the data provided. :param url: str :pararm headers: dict :param data: dict
def set_config(self, key, option, value): """Set a configuration option for a key""" if '_config' not in self.proxy: newopt = dict(default_cfg) newopt[option] = value self.proxy['_config'] = {key: newopt} else: if key in self.proxy['_config']: ...
Set a configuration option for a key
def ask_int(question: str, default: int = None) -> int: """Asks for a number in a question""" default_q = " [default: {0}]: ".format( default) if default is not None else "" answer = input("{0} [{1}]: ".format(question, default_q)) if not answer: if default is None: print("N...
Asks for a number in a question
def extractLargestSubNetwork(cls, network_file, out_subset_network_file, river_id_field, next_down_id_field, river_magnitude_field, ...
Extracts the larges sub network from the watershed based on the magnitude parameter. Parameters ---------- network_file: str Path to the stream network shapefile. out_subset_network_file: str Path to the output subset stream network shapefile. riv...
def recompute(self, quiet=False, **kwargs): """ Re-compute a previously computed model. You might want to do this if the kernel parameters change and the kernel is labeled as ``dirty``. :param quiet: (optional) If ``True``, return false when the computation fails. Otherwise,...
Re-compute a previously computed model. You might want to do this if the kernel parameters change and the kernel is labeled as ``dirty``. :param quiet: (optional) If ``True``, return false when the computation fails. Otherwise, throw an error if something goes wrong. (default: `...
def window_visu(N=51, name='hamming', **kargs): """A Window visualisation tool :param N: length of the window :param name: name of the window :param NFFT: padding used by the FFT :param mindB: the minimum frequency power in dB :param maxdB: the maximum frequency power in dB :param kargs: op...
A Window visualisation tool :param N: length of the window :param name: name of the window :param NFFT: padding used by the FFT :param mindB: the minimum frequency power in dB :param maxdB: the maximum frequency power in dB :param kargs: optional arguments passed to :func:`create_window` T...
def search(self, query): """ Search the play store for an app. nb_result (int): is the maximum number of result to be returned offset (int): is used to take result starting from an index. """ if self.authSubToken is None: raise LoginError("You need to login before e...
Search the play store for an app. nb_result (int): is the maximum number of result to be returned offset (int): is used to take result starting from an index.
def t_FLOAT(tok): # pylint: disable=locally-disabled,invalid-name r'\d+\.\d+' tok.value = (tok.type, float(tok.value)) return tok
r'\d+\.\d+
def htmlNodeDumpOutput(self, doc, cur, encoding): """Dump an HTML node, recursive behaviour,children are printed too, and formatting returns/spaces are added. """ if doc is None: doc__o = None else: doc__o = doc._o if cur is None: cur__o = None else: cur__o = cur._o ...
Dump an HTML node, recursive behaviour,children are printed too, and formatting returns/spaces are added.
def fail(message=None, exit_status=None): """Prints the specified message and exits the program with the specified exit status. """ print('Error:', message, file=sys.stderr) sys.exit(exit_status or 1)
Prints the specified message and exits the program with the specified exit status.
def get_oa_policy(doi): """ Get OA policy for a given DOI. .. note:: Uses beta.dissem.in API. :param doi: A canonical DOI. :returns: The OpenAccess policy for the associated publications, or \ ``None`` if unknown. >>> tmp = get_oa_policy('10.1209/0295-5075/111/40005'); (t...
Get OA policy for a given DOI. .. note:: Uses beta.dissem.in API. :param doi: A canonical DOI. :returns: The OpenAccess policy for the associated publications, or \ ``None`` if unknown. >>> tmp = get_oa_policy('10.1209/0295-5075/111/40005'); (tmp["published"], tmp["preprint"], tm...
def load(cls, file): """ Loads a :class:`~pypot.primitive.move.Move` from a json file. """ d = json.load(file) return cls.create(d)
Loads a :class:`~pypot.primitive.move.Move` from a json file.
def _reset(self, index, total, percentage_step, length): """Resets to the progressbar to start a new one""" self._start_time = datetime.datetime.now() self._start_index = index self._current_index = index self._percentage_step = percentage_step self._total = float(total) ...
Resets to the progressbar to start a new one
def loadVars(filename, ask=True, into=None, only=None): r"""Load variables pickled with `saveVars`. Parameters: - `ask`: If `True` then don't overwrite existing variables without asking. - `only`: A list to limit the variables to or `None`. - `into`: The dictionary the ...
r"""Load variables pickled with `saveVars`. Parameters: - `ask`: If `True` then don't overwrite existing variables without asking. - `only`: A list to limit the variables to or `None`. - `into`: The dictionary the variables should be loaded into (defaults ...
def check_column_id( problems: List, table: str, df: DataFrame, column: str, *, column_required: bool = True, ) -> List: """ A specialization of :func:`check_column`. Parameters ---------- problems : list A four-tuple containing 1. A problem type (string) eq...
A specialization of :func:`check_column`. Parameters ---------- problems : list A four-tuple containing 1. A problem type (string) equal to ``'error'`` or ``'warning'``; ``'error'`` means the GTFS is violated; ``'warning'`` means there is a problem but it is not a ...
def get_commit_request(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a commit request for a staged import. :param id: Staged import ID as an int. :return: :class:`imports.Request <imports.Request>` object :rtype: imports.Request """ schema = RequestS...
Get a commit request for a staged import. :param id: Staged import ID as an int. :return: :class:`imports.Request <imports.Request>` object :rtype: imports.Request
def check_dns_name_availability(name, region, **kwargs): ''' .. versionadded:: 2019.2.0 Check whether a domain name in the current zone is available for use. :param name: The DNS name to query. :param region: The region to query for the DNS name in question. CLI Example: .. code-block::...
.. versionadded:: 2019.2.0 Check whether a domain name in the current zone is available for use. :param name: The DNS name to query. :param region: The region to query for the DNS name in question. CLI Example: .. code-block:: bash salt-call azurearm_network.check_dns_name_availability...
def reset_stats(self): """ Returns: mean, max: two stats of the runners, to be added to backend """ scores = list(itertools.chain.from_iterable([v.total_scores for v in self._runners])) for v in self._runners: v.total_scores.clear() try: ...
Returns: mean, max: two stats of the runners, to be added to backend
def add_extra_chain_cert(self, certobj): """ Add certificate to chain :param certobj: The X509 certificate object to add to the chain :return: None """ if not isinstance(certobj, X509): raise TypeError("certobj must be an X509 instance") copy = _lib....
Add certificate to chain :param certobj: The X509 certificate object to add to the chain :return: None
def run_container(name, image, command=None, environment=None, ro=None, rw=None, links=None, detach=True, volumes_from=None, port_bindings=None, log_syslog=False): """ Wrapper for docker create_container, start calls :param log_syslog: bool flag to redirect container's l...
Wrapper for docker create_container, start calls :param log_syslog: bool flag to redirect container's logs to host's syslog :returns: container info dict or None if container couldn't be created Raises PortAllocatedError if container couldn't start on the requested port.
def geocode(client, address=None, components=None, bounds=None, region=None, language=None): """ Geocoding is the process of converting addresses (like ``"1600 Amphitheatre Parkway, Mountain View, CA"``) into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which y...
Geocoding is the process of converting addresses (like ``"1600 Amphitheatre Parkway, Mountain View, CA"``) into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map. :param address: The address to geocode. :type address: ...
def _fill_naked_singles(self): """Look for naked singles, i.e. cells with ony one possible value. :return: If any Naked Single has been found. :rtype: bool """ simple_found = False for i in utils.range_(self.side): for j in utils.range_(self.side): ...
Look for naked singles, i.e. cells with ony one possible value. :return: If any Naked Single has been found. :rtype: bool
def check_interactive_docker_worker(link): """Given a task, make sure the task was not defined as interactive. * ``task.payload.features.interactive`` must be absent or False. * ``task.payload.env.TASKCLUSTER_INTERACTIVE`` must be absent or False. Args: link (LinkOfTrust): the task link we're ...
Given a task, make sure the task was not defined as interactive. * ``task.payload.features.interactive`` must be absent or False. * ``task.payload.env.TASKCLUSTER_INTERACTIVE`` must be absent or False. Args: link (LinkOfTrust): the task link we're checking. Returns: list: the list of ...
def iter_rows(self): """Generator reading .dbf row one by one. Yields named tuple Row object. :rtype: Row """ fileobj = self._fileobj cls_row = self.cls_row fields = self.fields for idx in range(self.prolog.records_count): data = fileobj.rea...
Generator reading .dbf row one by one. Yields named tuple Row object. :rtype: Row
def selects(self, code, start, end=None): """ 选择code,start,end 如果end不填写,默认获取到结尾 @2018/06/03 pandas 的索引问题导致 https://github.com/pandas-dev/pandas/issues/21299 因此先用set_index去重做一次index 影响的有selects,select_time,select_month,get_bar @2018/06/04 当选择的时间...
选择code,start,end 如果end不填写,默认获取到结尾 @2018/06/03 pandas 的索引问题导致 https://github.com/pandas-dev/pandas/issues/21299 因此先用set_index去重做一次index 影响的有selects,select_time,select_month,get_bar @2018/06/04 当选择的时间越界/股票不存在,raise ValueError @2018/06/04 pandas索引问题已经解决 ...
def init(self): """ Adds custom calculations to orbit simulation. This routine is run once, and only once, upon instantiation. Adds quasi-dipole coordiantes, velocity calculation in ECEF coords, adds the attitude vectors of spacecraft assuming x is ram pointing and z is generally nadir, add...
Adds custom calculations to orbit simulation. This routine is run once, and only once, upon instantiation. Adds quasi-dipole coordiantes, velocity calculation in ECEF coords, adds the attitude vectors of spacecraft assuming x is ram pointing and z is generally nadir, adds ionospheric parameters fro...
def calc_signal_power(params): ''' calculates power spectrum of sum signal for all channels ''' for i, data_type in enumerate(['CSD','LFP','CSD_10_0', 'LFP_10_0']): if i % SIZE == RANK: # Load data if data_type in ['CSD','LFP']: fname=os.path.join(para...
calculates power spectrum of sum signal for all channels
def t_UFIXEDMN(t): r"ufixed(?P<M>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8)x(?P<N>80|79|78|77|76|75|74|73|72|71|70|69|68|67|66|65|64|63|62|61|60|59|58|57|56|55|54|53|52|51|50|49|48|47|46|45|44|43|42|41|40|39|38|37|36|35|34|33|32|31|30|29|28|27...
r"ufixed(?P<M>256|248|240|232|224|216|208|200|192|184|176|168|160|152|144|136|128|120|112|104|96|88|80|72|64|56|48|40|32|24|16|8)x(?P<N>80|79|78|77|76|75|74|73|72|71|70|69|68|67|66|65|64|63|62|61|60|59|58|57|56|55|54|53|52|51|50|49|48|47|46|45|44|43|42|41|40|39|38|37|36|35|34|33|32|31|30|29|28|27|26|25|24|23|22|21|20|1...
def get_genus_type(self): """Gets the genus type of this object. return: (osid.type.Type) - the genus type of this object compliance: mandatory - This method must be implemented. """ if self._my_genus_type_map is None: url_path = '/handcar/services/learning/types/' ...
Gets the genus type of this object. return: (osid.type.Type) - the genus type of this object compliance: mandatory - This method must be implemented.
def disassemble_current(self, dwThreadId): """ Disassemble the instruction at the program counter of the given thread. @type dwThreadId: int @param dwThreadId: Global thread ID. The program counter for this thread will be used as the disassembly address. ...
Disassemble the instruction at the program counter of the given thread. @type dwThreadId: int @param dwThreadId: Global thread ID. The program counter for this thread will be used as the disassembly address. @rtype: tuple( long, int, str, str ) @return: The tu...
def remove_user_from_group(group, role, email): """Remove a user from a group the caller owns Args: group (str): Group name role (str) : Role of user for group; either 'member' or 'admin' email (str): Email of user or group to remove Swagger: https://api.firecloud.org/#...
Remove a user from a group the caller owns Args: group (str): Group name role (str) : Role of user for group; either 'member' or 'admin' email (str): Email of user or group to remove Swagger: https://api.firecloud.org/#!/Groups/removeUserFromGroup
def set_XY(self, X, Y): """ Set the input / output data of the model This is useful if we wish to change our existing data but maintain the same model :param X: input observations :type X: np.ndarray :param Y: output observations :type Y: np.ndarray or ObsAr ...
Set the input / output data of the model This is useful if we wish to change our existing data but maintain the same model :param X: input observations :type X: np.ndarray :param Y: output observations :type Y: np.ndarray or ObsAr
def merge_labeled_intervals(x_intervals, x_labels, y_intervals, y_labels): r"""Merge the time intervals of two sequences. Parameters ---------- x_intervals : np.ndarray Array of interval times (seconds) x_labels : list or None List of labels y_intervals : np.ndarray Arra...
r"""Merge the time intervals of two sequences. Parameters ---------- x_intervals : np.ndarray Array of interval times (seconds) x_labels : list or None List of labels y_intervals : np.ndarray Array of interval times (seconds) y_labels : list or None List of label...
def delete_password(self, service, username): """Delete the password for the username of the service. """ items = self._find_passwords(service, username, deleting=True) if not items: raise PasswordDeleteError("Password not found") for current in items: res...
Delete the password for the username of the service.
def tc_at_grid_col(self, idx): """ The ``<w:tc>`` element appearing at grid column *idx*. Raises |ValueError| if no ``w:tc`` element begins at that grid column. """ grid_col = 0 for tc in self.tc_lst: if grid_col == idx: return tc g...
The ``<w:tc>`` element appearing at grid column *idx*. Raises |ValueError| if no ``w:tc`` element begins at that grid column.
def sbd_to_steem(self, sbd=0, price=0, account=None): ''' Uses the ticker to get the lowest ask and moves the sbd at that price. ''' if not account: account = self.mainaccount if self.check_balances(account): if sbd == 0: sbd = self.sbdbal ...
Uses the ticker to get the lowest ask and moves the sbd at that price.
def clear_widget(self): """ Clears the thumbnail display widget of all thumbnails, but does not remove them from the thumb_dict or thumb_list. """ if not self.gui_up: return canvas = self.c_view.get_canvas() canvas.delete_all_objects() self.c_v...
Clears the thumbnail display widget of all thumbnails, but does not remove them from the thumb_dict or thumb_list.
def success(self): """Return boolean indicating whether a solution was found""" self._check_valid() return self._problem._cp.solution.get_status() in ( self._problem._cp.solution.status.optimal, self._problem._cp.solution.status.optimal_tolerance, self._proble...
Return boolean indicating whether a solution was found
def declare_api_routes(config): """Declaration of routing""" add_route = config.add_route add_route('get-content', '/contents/{ident_hash}') add_route('get-resource', '/resources/{hash}') # User actions API add_route('license-request', '/contents/{uuid}/licensors') add_route('roles-request'...
Declaration of routing
def select_storage_for(cls, section_name, storage): """Selects the data storage for a config section within the :param:`storage`. The primary config section is normally merged into the :param:`storage`. :param section_name: Config section (name) to process. :param storage: ...
Selects the data storage for a config section within the :param:`storage`. The primary config section is normally merged into the :param:`storage`. :param section_name: Config section (name) to process. :param storage: Data storage to use. :return: :param:`storage` or...
def _parseStats(self, lines, parse_slabs = False): """Parse stats output from memcached and return dictionary of stats- @param lines: Array of lines of input text. @param parse_slabs: Parse slab stats if True. @return: Stats dictionary. """ ...
Parse stats output from memcached and return dictionary of stats- @param lines: Array of lines of input text. @param parse_slabs: Parse slab stats if True. @return: Stats dictionary.
def _quoteattr(self, attr): """Escape an XML attribute. Value can be unicode.""" attr = xml_safe(attr) if isinstance(attr, unicode) and not UNICODE_STRINGS: attr = attr.encode(self.encoding) return saxutils.quoteattr(attr)
Escape an XML attribute. Value can be unicode.
def get_action(self, parent, undo_stack: QUndoStack, sel_range, protocol, view: int): """ :type parent: QTableView :type undo_stack: QUndoStack """ self.command = ZeroHideAction(protocol, self.following_zeros, view, self.zero_hide_offsets) action = QAction(self.command.te...
:type parent: QTableView :type undo_stack: QUndoStack
def append(self, P, closed=False, itemsize=None, **kwargs): """ Append a new set of vertices to the collection. For kwargs argument, n is the number of vertices (local) or the number of item (shared) Parameters ---------- P : np.array Vertices posit...
Append a new set of vertices to the collection. For kwargs argument, n is the number of vertices (local) or the number of item (shared) Parameters ---------- P : np.array Vertices positions of the path(s) to be added closed: bool Whether path(s...
def _setup_rpc(self): """Setup the RPC client for the current agent.""" self._state_rpc = agent_rpc.PluginReportStateAPI(topics.REPORTS) report_interval = CONF.AGENT.report_interval if report_interval: heartbeat = loopingcall.FixedIntervalLoopingCall( self._re...
Setup the RPC client for the current agent.
def _make_package(args): # pragma: no cover """Prepare transcriptiondata from the transcription sources.""" from lingpy.sequence.sound_classes import token2class from lingpy.data import Model columns = ['LATEX', 'FEATURES', 'SOUND', 'IMAGE', 'COUNT', 'NOTE'] bipa = TranscriptionSystem('bipa') ...
Prepare transcriptiondata from the transcription sources.
def get_parameter_names(self, include_frozen=False): """ Get a list of the parameter names Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``) """ if include_frozen: ...
Get a list of the parameter names Args: include_frozen (Optional[bool]): Should the frozen parameters be included in the returned value? (default: ``False``)
def setup(app): ''' Required Sphinx extension setup function. ''' app.add_role('bokeh-commit', bokeh_commit) app.add_role('bokeh-issue', bokeh_issue) app.add_role('bokeh-pull', bokeh_pull) app.add_role('bokeh-tree', bokeh_tree)
Required Sphinx extension setup function.
def getActionReflexRules(self, analysis, wf_action): """ This function returns a list of dictionaries with the rules to be done for the analysis service. :analysis: the analysis full object which we want to obtain the rules for. :wf_action: it is the workflow action t...
This function returns a list of dictionaries with the rules to be done for the analysis service. :analysis: the analysis full object which we want to obtain the rules for. :wf_action: it is the workflow action that the analysis is doing, we have to act in consideration of...
def lam_at_index(self, lidx): """Compute the scaled lambda used at index lidx. """ if self.path_ is None: return self.lam * self.lam_scale_ return self.lam * self.lam_scale_ * self.path_[lidx]
Compute the scaled lambda used at index lidx.
def add_warning (self, s, tag=None): """ Add a warning string. """ item = (tag, s) if item not in self.warnings and \ tag not in self.aggregate.config["ignorewarnings"]: self.warnings.append(item)
Add a warning string.
def add_sms_spec_to_request(self, req, federation='', loes=None, context='', url=''): """ Add signed metadata statements to the request :param req: The request so far :param federation: If only signed metadata statements from a specific set of...
Add signed metadata statements to the request :param req: The request so far :param federation: If only signed metadata statements from a specific set of federations should be included this is the set. :param loes: - not used - :param context: What kind of request/response i...
def pipe(self, other_task): """ Add a pipe listener to the execution of this task. The output of this task is required to be an iterable. Each item in the iterable will be queued as the sole argument to an execution of the listener task. Can also be written as:: pip...
Add a pipe listener to the execution of this task. The output of this task is required to be an iterable. Each item in the iterable will be queued as the sole argument to an execution of the listener task. Can also be written as:: pipeline = task1 | task2
def remove_im_params(model, im): """Remove parameter nodes from the influence map. Parameters ---------- model : pysb.core.Model PySB model. im : networkx.MultiDiGraph Influence map. Returns ------- networkx.MultiDiGraph Influence map with the parameter nodes re...
Remove parameter nodes from the influence map. Parameters ---------- model : pysb.core.Model PySB model. im : networkx.MultiDiGraph Influence map. Returns ------- networkx.MultiDiGraph Influence map with the parameter nodes removed.
def size_in_bytes(self, offset, timestamp, key, value, headers=None): """ Actual size of message to add """ assert not headers, "Headers not supported in v0/v1" magic = self._magic return self.LOG_OVERHEAD + self.record_size(magic, key, value)
Actual size of message to add
def _check_resources(name, expr, resources): """Validate that the expression and resources passed match up. Parameters ---------- name : str The name of the argument we are checking. expr : Expr The potentially bound expr. resources The explicitly passed resources to com...
Validate that the expression and resources passed match up. Parameters ---------- name : str The name of the argument we are checking. expr : Expr The potentially bound expr. resources The explicitly passed resources to compute expr. Raises ------ ValueError ...
async def setvolume(self, value): """The volume command Args: value (str): The value to set the volume to """ self.logger.debug("volume command") if self.state != 'ready': return logger.debug("Volume command received") if value == '+':...
The volume command Args: value (str): The value to set the volume to
def units(self): """ Tuple of the units for length, time and mass. Can be set in any order, and strings are not case-sensitive. See ipython_examples/Units.ipynb for more information. You can check the units' exact values and add Additional units in rebound/rebound/units.py. Units should be set befor...
Tuple of the units for length, time and mass. Can be set in any order, and strings are not case-sensitive. See ipython_examples/Units.ipynb for more information. You can check the units' exact values and add Additional units in rebound/rebound/units.py. Units should be set before adding particles to the simulation ...
def getChildTimeoutValue(self): """get child timeout""" print '%s call getChildTimeoutValue' % self.port childTimeout = self.__sendCommand(WPANCTL_CMD + 'getporp -v Thread:ChildTimeout')[0] return int(childTimeout)
get child timeout
def getDarkCurrentFunction(exposuretimes, imgs, **kwargs): ''' get dark current function from given images and exposure times ''' exposuretimes, imgs = getDarkCurrentAverages(exposuretimes, imgs) offs, ascent, rmse = getLinearityFunction(exposuretimes, imgs, **kwargs) return offs, ascent, ...
get dark current function from given images and exposure times
def show(self): """ Prints the content of this method to stdout. This will print the method signature and the decompiled code. """ args, ret = self.method.get_descriptor()[1:].split(")") if self.code: # We patch the descriptor here and add the registers, if c...
Prints the content of this method to stdout. This will print the method signature and the decompiled code.
def isubset(self, *keys): # type: (*Hashable) -> ww.g """Return key, self[key] as generator for key in keys. Raise KeyError if a key does not exist Args: keys: Iterable containing keys Example: >>> from ww import d >>> list(d({1: 1, 2: 2, 3...
Return key, self[key] as generator for key in keys. Raise KeyError if a key does not exist Args: keys: Iterable containing keys Example: >>> from ww import d >>> list(d({1: 1, 2: 2, 3: 3}).isubset(1, 3)) [(1, 1), (3, 3)]
def add_arguments(self, parser): """ Define optional arguments with default values """ parser.add_argument('--length', default=self.length, type=int, help=_('SECRET_KEY length default=%d' % self.length)) parser.add_argument('--alphabet', default=self....
Define optional arguments with default values
def main(client, adgroup_id): """Runs the example.""" adgroup_criterion_service = client.GetService( 'AdGroupCriterionService', version='v201809') helper = ProductPartitionHelper(adgroup_id) # The most trivial partition tree has only a unit node as the root, e.g.: # helper.CreateUnit(bid_amount=100000...
Runs the example.
def clone_name(s, ca=False): """ >>> clone_name("120038881639") "0038881639" >>> clone_name("GW11W6RK01DAJDWa") "GW11W6RK01DAJDW" """ if not ca: return s[:-1] if s[0] == '1': return s[2:] return s.rstrip('ab')
>>> clone_name("120038881639") "0038881639" >>> clone_name("GW11W6RK01DAJDWa") "GW11W6RK01DAJDW"
def get_report(time='hour', threshold='significant', online=False): """ Retrieves a new Report about recent earthquakes. :param str time: A string indicating the time range of earthquakes to report. Must be either "hour" (only earthquakes in the past hour), "day" (only earthquakes that happened today),...
Retrieves a new Report about recent earthquakes. :param str time: A string indicating the time range of earthquakes to report. Must be either "hour" (only earthquakes in the past hour), "day" (only earthquakes that happened today), "week" (only earthquakes that happened in the past 7 days), or "month" (only ea...
def rc(self): """Flip the direction""" ntx = self.copy() newstrand = '+' if ntx.strand == '+': newstrand = '-' ntx._options = ntx._options._replace(direction=newstrand) return ntx
Flip the direction
def train(model, X_train=None, Y_train=None, save=False, predictions_adv=None, evaluate=None, args=None, rng=None, var_list=None, attack=None, attack_args=None): """ Train a TF Eager model :param model: cleverhans.model.Model :param X_train: numpy array with training inputs :para...
Train a TF Eager model :param model: cleverhans.model.Model :param X_train: numpy array with training inputs :param Y_train: numpy array with training outputs :param save: boolean controlling the save operation :param predictions_adv: if set with the adversarial example tensor, will ...
def generate_protocol(self): """ Recreate the command stimulus (protocol) for the current sweep. It's not stored point by point (that's a waste of time and memory!) Instead it's stored as a few (x,y) points which can be easily graphed. TODO: THIS for segment in abf.ABFre...
Recreate the command stimulus (protocol) for the current sweep. It's not stored point by point (that's a waste of time and memory!) Instead it's stored as a few (x,y) points which can be easily graphed. TODO: THIS for segment in abf.ABFreader.read_protocol(): for analogsigna...
def _get_column(cls, name): """ Based on cqlengine.models.BaseModel._get_column. But to work with 'pk' """ if name == 'pk': return cls._meta.get_field(cls._meta.pk.name) return cls._columns[name]
Based on cqlengine.models.BaseModel._get_column. But to work with 'pk'
def _rebin(self,xdx,rebin): """ Rebin array x with weights 1/dx**2 by factor rebin. Inputs: xdx = [x,dx] rebin = int Returns [x,dx] after rebinning. """ x = xdx[0] dx = xdx[1] rebin = int(rebin) ...
Rebin array x with weights 1/dx**2 by factor rebin. Inputs: xdx = [x,dx] rebin = int Returns [x,dx] after rebinning.
def add_nest(self, name=None, **kw): """A simple decorator which wraps :meth:`nestly.core.Nest.add`.""" def deco(func): self.add(name or func.__name__, func, **kw) return func return deco
A simple decorator which wraps :meth:`nestly.core.Nest.add`.
def cancel(batch_fn, cancel_fn, ops): """Cancel operations. Args: batch_fn: API-specific batch function. cancel_fn: API-specific cancel function. ops: A list of operations to cancel. Returns: A list of operations canceled and a list of error messages. """ # Canceling many operations one-by-...
Cancel operations. Args: batch_fn: API-specific batch function. cancel_fn: API-specific cancel function. ops: A list of operations to cancel. Returns: A list of operations canceled and a list of error messages.
def coverage(self, container: Container, *, instrument: bool = True ) -> TestSuiteCoverage: """ Computes complete test suite coverage for a given container. Parameters: container: the container for which coverage sh...
Computes complete test suite coverage for a given container. Parameters: container: the container for which coverage should be computed. rebuild: if set to True, the program will be rebuilt before coverage is computed.
def handle_message(received_message, control_plane_sockets, data_plane_sockets): """ Handle a LISP message. The default handle method determines the type of message and delegates it to the more specific method """ logger.debug(u"Handling message #{0} ({1}) from {2}".format(received_message.message_n...
Handle a LISP message. The default handle method determines the type of message and delegates it to the more specific method
def reset_and_halt(self, reset_type=None): """ perform a reset and stop the core on the reset handler """ delegateResult = self.call_delegate('set_reset_catch', core=self, reset_type=reset_type) # halt the target if not delegateResult: self.h...
perform a reset and stop the core on the reset handler
def _tofile(self, fh, pam=False): """Write Netbm file.""" fh.seek(0) fh.write(self._header(pam)) data = self.asarray(copy=False) if self.maxval == 1: data = numpy.packbits(data, axis=-1) data.tofile(fh)
Write Netbm file.
def __write(path, data, mode="w"): ''' Writes to a File. Returns the data written. path - (string) path to the file to write to. data - (json) data from a request. mode - (string) mode to open the file in. Default to 'w'. Overwrites. ''' with open(path, mode) as d...
Writes to a File. Returns the data written. path - (string) path to the file to write to. data - (json) data from a request. mode - (string) mode to open the file in. Default to 'w'. Overwrites.
def _logmessage_transform(cls, s, by=2): """ Preprocess/cleanup a bzr log message before parsing Args: s (str): log message string by (int): cutoff threshold for log message length Returns: str: preprocessed log message string """ if ...
Preprocess/cleanup a bzr log message before parsing Args: s (str): log message string by (int): cutoff threshold for log message length Returns: str: preprocessed log message string
def get_river_index(self, river_id): """ This method retrieves the river index in the netCDF dataset corresponding to the river ID. Parameters ---------- river_id: int The ID of the river segment. Returns ------- int: The ...
This method retrieves the river index in the netCDF dataset corresponding to the river ID. Parameters ---------- river_id: int The ID of the river segment. Returns ------- int: The index of the river ID's in the file. Example:: ...
def remove_colormap(self, removal_type): """Remove a palette (colormap); if no colormap, returns a copy of this image removal_type - any of lept.REMOVE_CMAP_* """ with _LeptonicaErrorTrap(): return Pix( lept.pixRemoveColormapGeneral(self._cdata, ...
Remove a palette (colormap); if no colormap, returns a copy of this image removal_type - any of lept.REMOVE_CMAP_*
def get_create_option(self, context, q): """Form the correct create_option to append to results.""" create_option = [] display_create_option = False if self.create_field and q: page_obj = context.get('page_obj', None) if page_obj is None or page_obj.number =...
Form the correct create_option to append to results.
def remove_all_cts_records_by(file_name, crypto_idfp): """ Remove all cts records set by player with CRYPTO_IDFP """ db = XonoticDB.load_path(file_name) db.remove_all_cts_records_by(crypto_idfp) db.save(file_name)
Remove all cts records set by player with CRYPTO_IDFP