code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def annotate_metadata_data(repo, task, patterns=["*"], size=0): """ Update metadata with the content of the files """ mgr = plugins_get_mgr() keys = mgr.search('representation')['representation'] representations = [mgr.get_by_key('representation', k) for k in keys] matching_files = repo.f...
Update metadata with the content of the files
def getOffbids(self, g): """ Returns the offers/bids for the given generator. """ if not g.is_load: offbids = [x for x in self.offers if x.generator == g] else: offbids = [x for x in self.bids if x.vLoad == g] return offbids
Returns the offers/bids for the given generator.
def pre_save(self, model_instance, add): """Updates socket.gethostname() on each save.""" value = socket.gethostname() setattr(model_instance, self.attname, value) return value
Updates socket.gethostname() on each save.
def verification_upload( self, verification_id, audio_file=None, bypass=False, bypass_pin=None, bypass_code=None, ): """ Upload verification data. Uses PUT to /verfications/<verification_id> interface :Args: ...
Upload verification data. Uses PUT to /verfications/<verification_id> interface :Args: * *verification_id*: (str) Verification ID * *audio_file*: (str) Path to the audio file of the recorded words. Not required for phone verifications. * *bypass*: (boolean) True if using a ...
def _wns_prepare_toast(data, **kwargs): """ Creates the xml tree for a `toast` notification :param data: dict: The notification data to be converted to an xml tree. { "text": ["Title text", "Message Text", "Another message!"], "image": ["src1", "src2"], } :return: str """ root = ET.Element("toast") visu...
Creates the xml tree for a `toast` notification :param data: dict: The notification data to be converted to an xml tree. { "text": ["Title text", "Message Text", "Another message!"], "image": ["src1", "src2"], } :return: str
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id if hasattr(self, 'status') and self.status is not None: _dict['...
Return a json dictionary representing this model.
def iter_links_by_js_attrib(self, attrib_name, attrib_value): '''Iterate links of a JavaScript pseudo-link attribute.''' links = self.javascript_scraper.scrape_links(attrib_value) for link in links: yield attrib_name, link
Iterate links of a JavaScript pseudo-link attribute.
def merge_params(params, lparams): """Merge global ignore/select with linter local params.""" ignore = params.get('ignore', set()) if 'ignore' in lparams: ignore = ignore | set(lparams['ignore']) select = params.get('select', set()) if 'select' in lparams: select = select | set(lpar...
Merge global ignore/select with linter local params.
def set_auxiliary_basis_set(self, folder, auxiliary_folder, auxiliary_basis_set_type="aug_cc_pvtz"): """ copy in the desired folder the needed auxiliary basis set "X2.ion" where X is a specie. :param auxiliary_folder: folder where the auxiliary basis sets are stor...
copy in the desired folder the needed auxiliary basis set "X2.ion" where X is a specie. :param auxiliary_folder: folder where the auxiliary basis sets are stored :param auxiliary_basis_set_type: type of basis set (string to be found in the extension of the file name; must be in lower case) ...
def CompileReport(self, mediator): """Compiles an analysis report. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. Returns: AnalysisReport: analysis report. """ lines_of_text = [] for user,...
Compiles an analysis report. Args: mediator (AnalysisMediator): mediates interactions between analysis plugins and other components, such as storage and dfvfs. Returns: AnalysisReport: analysis report.
def parseFeatureRequest(response): """ Get the list of Part10 features supported by the reader. @param response: result of CM_IOCTL_GET_FEATURE_REQUEST commmand @rtype: list @return: a list of list [[tag1, value1], [tag2, value2]] """ features = [] while (len(response) > 0): tag = ...
Get the list of Part10 features supported by the reader. @param response: result of CM_IOCTL_GET_FEATURE_REQUEST commmand @rtype: list @return: a list of list [[tag1, value1], [tag2, value2]]
def coerce_nc3_dtype(arr): """Coerce an array to a data type that can be stored in a netCDF-3 file This function performs the following dtype conversions: int64 -> int32 bool -> int8 Data is checked for equality, or equivalence (non-NaN values) with `np.allclose` with the default keywo...
Coerce an array to a data type that can be stored in a netCDF-3 file This function performs the following dtype conversions: int64 -> int32 bool -> int8 Data is checked for equality, or equivalence (non-NaN values) with `np.allclose` with the default keyword arguments.
async def load_project(self, project_path): """Load a project. :param project_path: Path to project you want to load. """ cmd = "loadproject %s" % project_path return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
Load a project. :param project_path: Path to project you want to load.
def _determine_function_name_type(node, config=None): """Determine the name type whose regex the a function's name should match. :param node: A function node. :type node: astroid.node_classes.NodeNG :param config: Configuration from which to pull additional property classes. :type config: :class:`o...
Determine the name type whose regex the a function's name should match. :param node: A function node. :type node: astroid.node_classes.NodeNG :param config: Configuration from which to pull additional property classes. :type config: :class:`optparse.Values` :returns: One of ('function', 'method', ...
def statics(self) -> typing.Iterator['Static']: """ Returns: generator over all statics in this coalition """ for country in self.countries: for static in country.statics: yield static
Returns: generator over all statics in this coalition
def process_raw_data(cls, raw_data): """Create a new model using raw API response.""" properties = raw_data["properties"] qos_settings = properties.get("qosSettings", {}) properties["qosSettings"] = VirtualSwtichQosSettings.from_raw_data( raw_data=qos_settings) return...
Create a new model using raw API response.
def get_url(url): """获取url地址并根据网页编码格式自动解析 Keyword arguments: url -- 用户传入地址,头部必须含有http:// Return: 网页源代码(为了下一步预处理方便,所有英文字母转换为小写) 网页编解码 """ r = requests.get(url) charset = r.apparent_encoding r.encoding = charset html_code = r.text.lower() log('...
获取url地址并根据网页编码格式自动解析 Keyword arguments: url -- 用户传入地址,头部必须含有http:// Return: 网页源代码(为了下一步预处理方便,所有英文字母转换为小写) 网页编解码
def _get_root_object(models): ''' Read list of models and returns a Root object with the proper models added. ''' root = napalm_yang.base.Root() for model in models: current = napalm_yang for part in model.split('.'): current = getattr(current, part) root.add_mode...
Read list of models and returns a Root object with the proper models added.
def setLang(self,lang): """ Sets the default language for all domains. For recommendations regarding the format of the language code, see :py:class:`TranslationManager`\ . Note that the ``lang`` parameter of both :py:meth:`translate()` and :py:meth:`tran...
Sets the default language for all domains. For recommendations regarding the format of the language code, see :py:class:`TranslationManager`\ . Note that the ``lang`` parameter of both :py:meth:`translate()` and :py:meth:`translate_lazy()` will override this setting. ...
def undelete(self, original_filepath): """Restore the most recent version of a filepath, returning the filepath it was restored to(as rename-on-collision will apply if a file already exists at that path). """ candidates = self.versions(original_filepath) if not candidates...
Restore the most recent version of a filepath, returning the filepath it was restored to(as rename-on-collision will apply if a file already exists at that path).
def bandwidth(data, period, std=2.0): """ Bandwidth. Formula: bw = u_bb - l_bb / m_bb """ catch_errors.check_for_period_error(data, period) period = int(period) bandwidth = ((upper_bollinger_band(data, period, std) - lower_bollinger_band(data, period, std)) / ...
Bandwidth. Formula: bw = u_bb - l_bb / m_bb
def prepare_to_render(self, request, contextual_vals, option_vals): """ Before calling ``render_to_template()``, this method is called to give the instance opportunity to prepare itself. For example, ``AbstractMainMenu`` and ``AbstractFlatMenu`` needs to call ``set_max_levels()``...
Before calling ``render_to_template()``, this method is called to give the instance opportunity to prepare itself. For example, ``AbstractMainMenu`` and ``AbstractFlatMenu`` needs to call ``set_max_levels()`` and ``set_use_specific()`` to update the ``max_levels`` and ``use_specific`` fi...
def move_up(self): """Move up one level in the hierarchy, unless already on top.""" if self.current_item.parent is not None: self.current_item = self.current_item.parent for f in self._hooks["up"]: f(self) if self.current_item is self.root: for f in s...
Move up one level in the hierarchy, unless already on top.
def connect(url): """Connect to UNIX or TCP socket. url can be either tcp://<host>:port or ipc://<path> """ url = urlparse(url) if url.scheme == 'tcp': sock = socket() netloc = tuple(url.netloc.rsplit(':', 1)) hostname = socket.gethostname() elif url.scheme == 'ipc':...
Connect to UNIX or TCP socket. url can be either tcp://<host>:port or ipc://<path>
def parametererror(self): """Return the first parameter error, or False if there is none""" for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable for parameter in parameters: if parameter.error: return parameter.error ...
Return the first parameter error, or False if there is none
def tokenMatchesNomAdvVinf( self, token, verb, vinf): ''' Teeb kindlaks, kas etteantud token v6iks olla verb'i alluv ning vinf'i ylemus (st paikneda nende vahel). Kui see nii on, tagastab j2rjendi vahele sobiva s6na morf analyysidega (meetodi _getMatchingAnalysisIDs abil), vastasel ...
Teeb kindlaks, kas etteantud token v6iks olla verb'i alluv ning vinf'i ylemus (st paikneda nende vahel). Kui see nii on, tagastab j2rjendi vahele sobiva s6na morf analyysidega (meetodi _getMatchingAnalysisIDs abil), vastasel juhul tagastab tyhja j2rjendi;
def pyramid_analysis(Gs, f, **kwargs): r"""Compute the graph pyramid transform coefficients. Parameters ---------- Gs : list of graphs A multiresolution sequence of graph structures. f : ndarray Graph signal to analyze. h_filters : list A list of filter that will be used...
r"""Compute the graph pyramid transform coefficients. Parameters ---------- Gs : list of graphs A multiresolution sequence of graph structures. f : ndarray Graph signal to analyze. h_filters : list A list of filter that will be used for the analysis and sythesis operator. ...
def Buzzelli_2008(Re, eD): r'''Calculates Darcy friction factor using the method in Buzzelli (2008) [2]_ as shown in [1]_. .. math:: \frac{1}{\sqrt{f_d}} = B_1 - \left[\frac{B_1 +2\log(\frac{B_2}{Re})} {1 + \frac{2.18}{B_2}}\right] .. math:: B_1 = \frac{0.774\ln(Re)-1.41}{1+1.3...
r'''Calculates Darcy friction factor using the method in Buzzelli (2008) [2]_ as shown in [1]_. .. math:: \frac{1}{\sqrt{f_d}} = B_1 - \left[\frac{B_1 +2\log(\frac{B_2}{Re})} {1 + \frac{2.18}{B_2}}\right] .. math:: B_1 = \frac{0.774\ln(Re)-1.41}{1+1.32\sqrt{\frac{\epsilon}{D}}} ...
def precision(links_true, links_pred=None): """precision(links_true, links_pred) Compute the precision. The precision is given by TP/(TP+FP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) collection of links. links_pred: ...
precision(links_true, links_pred) Compute the precision. The precision is given by TP/(TP+FP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) collection of links. links_pred: pandas.MultiIndex, pandas.DataFrame, pandas.Series ...
def InvokeMethod(self, MethodName, ObjectName, Params=None, **params): # pylint: disable=invalid-name """ Invoke a method on a target instance or on a target class. The methods that can be invoked are static and non-static methods defined in a class (also known as *extrinsic* me...
Invoke a method on a target instance or on a target class. The methods that can be invoked are static and non-static methods defined in a class (also known as *extrinsic* methods). Static methods can be invoked on instances and on classes. Non-static methods can be invoked only on insta...
def rand_imancon(X, rho): """Iman-Conover Method to generate random ordinal variables (Implementation adopted from Ekstrom, 2005) x : ndarray <obs x cols> matrix with "cols" ordinal variables that are uncorrelated. rho : ndarray Spearman Rank Correlation Matrix Links ...
Iman-Conover Method to generate random ordinal variables (Implementation adopted from Ekstrom, 2005) x : ndarray <obs x cols> matrix with "cols" ordinal variables that are uncorrelated. rho : ndarray Spearman Rank Correlation Matrix Links * Iman, R.L., Conover, W.J., 1...
def FindDevices(cls, setting_matcher, device_matcher=None, usb_info='', timeout_ms=None): """Find and yield the devices that match. Args: setting_matcher: Function that returns the setting to use given a usb1.USBDevice, or None if the device doesn't have a vali...
Find and yield the devices that match. Args: setting_matcher: Function that returns the setting to use given a usb1.USBDevice, or None if the device doesn't have a valid setting. device_matcher: Function that returns True if the given UsbHandle is valid. None to matc...
def fileBrowser(self): """Invoke a tkinter file dialog""" if capable.OF_TKFD_IN_EPAR: fname = askopenfilename(parent=self.entry, title="Select File") else: from . import filedlg self.fd = filedlg.PersistLoadFileDialog(self.entry, "...
Invoke a tkinter file dialog
def _parse_date(date): """Parse from the user input `date`. e.g. current year 2016: input 6-26, 626, ... return 2016626 input 2016-6-26, 2016/6/26, ... retrun 2016626 This fn wouldn't check the date, it only gather the number as a string. """ result = ''.j...
Parse from the user input `date`. e.g. current year 2016: input 6-26, 626, ... return 2016626 input 2016-6-26, 2016/6/26, ... retrun 2016626 This fn wouldn't check the date, it only gather the number as a string.
def _get_dns_cname(name, link=False): """ Looks for associated domain zone, nameservers and linked record name until no more linked record name was found for the given fully qualified record name or the CNAME lookup was disabled, and then returns the parameters as a tuple. """ ...
Looks for associated domain zone, nameservers and linked record name until no more linked record name was found for the given fully qualified record name or the CNAME lookup was disabled, and then returns the parameters as a tuple.
def _unpickle_method(func_name, obj, cls): """Unpickle methods properly, including class methods.""" if obj is None: return cls.__dict__[func_name].__get__(obj, cls) for cls in cls.__mro__: try: func = cls.__dict__[func_name] except KeyError: pass else: break return func.__get...
Unpickle methods properly, including class methods.
def get_polygon_from_nuts(conn, nuts): r"""A one-line summary that does not use variable names or the function name. Several sentences providing an extended description. Refer to variables using back-ticks, e.g. `var`. Parameters ---------- var1 : array_like Array_like means all th...
r"""A one-line summary that does not use variable names or the function name. Several sentences providing an extended description. Refer to variables using back-ticks, e.g. `var`. Parameters ---------- var1 : array_like Array_like means all those objects -- lists, nested lists, etc. --...
def serialize(obj, **options): ''' Serialize Python data to YAML. :param obj: the data structure to serialize :param options: options given to lower yaml module. ''' options.setdefault('Dumper', Dumper) try: response = yaml.dump(obj, **options) if response.endswith('\n...\n...
Serialize Python data to YAML. :param obj: the data structure to serialize :param options: options given to lower yaml module.
def staged_rewards(self): """ Helper function to return staged rewards based on current physical states. Returns: r_reach (float): reward for reaching and grasping r_lift (float): reward for lifting and aligning r_stack (float): reward for stacking ""...
Helper function to return staged rewards based on current physical states. Returns: r_reach (float): reward for reaching and grasping r_lift (float): reward for lifting and aligning r_stack (float): reward for stacking
def flip_ctrlpts2d(ctrlpts2d, size_u=0, size_v=0): """ Flips a list of surface 2-D control points from *[u][v]* to *[v][u]* order. :param ctrlpts2d: 2-D control points :type ctrlpts2d: list, tuple :param size_u: size in U-direction (row length) :type size_u: int :param size_v: size in V-directi...
Flips a list of surface 2-D control points from *[u][v]* to *[v][u]* order. :param ctrlpts2d: 2-D control points :type ctrlpts2d: list, tuple :param size_u: size in U-direction (row length) :type size_u: int :param size_v: size in V-direction (column length) :type size_v: int :return: flipp...
def commit(config, no_verify): """Commit the current branch with all files.""" repo = config.repo active_branch = repo.active_branch if active_branch.name == "master": error_out( "Can't commit when on the master branch. " "You really ought to do work in branches." ...
Commit the current branch with all files.
def get_collection(self, namespace): """Get a pymongo collection from a namespace.""" database, coll = namespace.split(".", 1) return self.primary_client[database][coll]
Get a pymongo collection from a namespace.
def _mosaic_4d_to_nifti(dicom_input, output_file): """ This function will convert siemens 4d series to a nifti Some inspiration on which fields can be used was taken from http://slicer.org/doc/html/DICOMDiffusionVolumePlugin_8py_source.html """ # Get the sorted mosaics logger.info('Sorting d...
This function will convert siemens 4d series to a nifti Some inspiration on which fields can be used was taken from http://slicer.org/doc/html/DICOMDiffusionVolumePlugin_8py_source.html
def dimod_object_hook(obj): """JSON-decoding for dimod objects. See Also: :class:`json.JSONDecoder` for using custom decoders. """ if _is_sampleset_v2(obj): # in the future we could handle subtypes but right now we just have the # one return SampleSet.from_serializable(...
JSON-decoding for dimod objects. See Also: :class:`json.JSONDecoder` for using custom decoders.
def run_exit_code(self, returncode): """Handle the exit code for the current run. Args: returncode (int): The return exit code. Raises: RuntimeError: Raise on invalid exit code if halt_on_fail is True. Returns: bool: True if exit code is a valid exi...
Handle the exit code for the current run. Args: returncode (int): The return exit code. Raises: RuntimeError: Raise on invalid exit code if halt_on_fail is True. Returns: bool: True if exit code is a valid exit code, else False.
def Mersmann_Kind_thermal_conductivity_liquid(T, MW, Tc, Vc, atoms): r'''Estimates the thermal conductivity of organic liquid substances according to the method of [1]_. .. math:: \lambda^* = \frac{\lambda\cdot V_c^{2/3}\cdot T_c\cdot \text{MW}^{0.5}} {(k\cdot T_c)^{1.5}\cdot N_A^{7/6}} ...
r'''Estimates the thermal conductivity of organic liquid substances according to the method of [1]_. .. math:: \lambda^* = \frac{\lambda\cdot V_c^{2/3}\cdot T_c\cdot \text{MW}^{0.5}} {(k\cdot T_c)^{1.5}\cdot N_A^{7/6}} \lambda^* = \frac{2}{3}\left(n_a + 40\sqrt{1-T_r}\right) ...
def dbg_draw(self, filename): """ Draw the graph and save it to a PNG file. """ import matplotlib.pyplot as pyplot # pylint: disable=import-error from networkx.drawing.nx_agraph import graphviz_layout # pylint: disable=import-error tmp_graph = networkx.DiGraph() ...
Draw the graph and save it to a PNG file.
def _aggregate(self): ''' The function aggreagtes all pre_stream, layout and post_stream and components, and yields them one by one. ''' # Yielding everything under pre_stream for x in self._yield_all(self.pre_stream): yield x # Yielding layout for x in s...
The function aggreagtes all pre_stream, layout and post_stream and components, and yields them one by one.
def create_next_tag(): """ creates a tag based on the date and previous tags """ date = datetime.utcnow() date_tag = '{}.{}.{}'.format(date.year, date.month, date.day) if date_tag in latest_tag(): # if there was an update already today latest = latest_tag().split('.') # split by spaces i...
creates a tag based on the date and previous tags
def in_navitem(self, resources, nav_href): """ Given href of nav item, determine if resource is in it """ # The navhref might end with '/index' so remove it if so if nav_href.endswith('/index'): nav_href = nav_href[:-6] return self.docname.startswith(nav_href)
Given href of nav item, determine if resource is in it
def randomize(length=6, choices=None): """Returns a random string of the given length.""" if type(choices) == str: choices = list(choices) choices = choices or ascii_lowercase return "".join(choice(choices) for _ in range(length))
Returns a random string of the given length.
def __read_byte_offset(decl, attrs): """Using duck typing to set the offset instead of in constructor""" offset = attrs.get(XML_AN_OFFSET, 0) # Make sure the size is in bytes instead of bits decl.byte_offset = int(offset) / 8
Using duck typing to set the offset instead of in constructor
def run_custom_config_command(self, custom_command): """ Execute custom command in configuration mode on device :param custom_command: command :return: result of command execution """ return self.run_command_flow.execute_flow(custom_command=custom_command, is_config=True)
Execute custom command in configuration mode on device :param custom_command: command :return: result of command execution
def get_normalized_bdew_profile(self): """ Calculation of the normalized hourly heat demand """ self.df['temperature'] = self.temperature.values self.df['temperature_geo'] = self.weighted_temperature( how='geometric_series') sf = self.get_sf_values() [a, b, ...
Calculation of the normalized hourly heat demand
def index(self, row, column, parent): """ Returns the index of the item in the model specified by the given row, column and parent index. row, column == int, parent == QModelIndex """ if not self.hasIndex(row, column, parent): return QtCore.QModelIndex() if not pare...
Returns the index of the item in the model specified by the given row, column and parent index. row, column == int, parent == QModelIndex
def create_asset_class(self, item: AssetClass): """ Inserts the record """ session = self.open_session() session.add(item) session.commit()
Inserts the record
def set_attribute(self, attribute, value, callback=None): """ Set a new value for an attribute of the Queue. :type attribute: String :param attribute: The name of the attribute you want to set. The only valid value at this time is: VisibilityTimeout ...
Set a new value for an attribute of the Queue. :type attribute: String :param attribute: The name of the attribute you want to set. The only valid value at this time is: VisibilityTimeout :type value: int :param value: The new value for the attribute....
def load(self, filename='classifier.dump'): """ Unpickles the classifier used """ ifile = open(filename, 'r+') self.classifier = pickle.load(ifile) ifile.close()
Unpickles the classifier used
def attendee_data(request, form, user_id=None): ''' Lists attendees for a given product/category selection along with profile data.''' status_display = { commerce.Cart.STATUS_ACTIVE: "Unpaid", commerce.Cart.STATUS_PAID: "Paid", commerce.Cart.STATUS_RELEASED: "Refunded", } o...
Lists attendees for a given product/category selection along with profile data.
def get_link_mappings(link_id, link_2_id=None, **kwargs): """ Get all the resource attribute mappings in a network. If another network is specified, only return the mappings between the two networks. """ qry = db.DBSession.query(ResourceAttrMap).filter( or_( and_( ...
Get all the resource attribute mappings in a network. If another network is specified, only return the mappings between the two networks.
def convert_elementwise_sub( params, w_name, scope_name, inputs, layers, weights, names ): """ Convert elementwise subtraction. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs ...
Convert elementwise subtraction. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short nam...
def earthquake_fatality_rate(hazard_level): """Earthquake fatality ratio for a given hazard level. It reads the QGIS QSettings to know what is the default earthquake function. :param hazard_level: The hazard level. :type hazard_level: int :return: The fatality rate. :rtype: float """ ...
Earthquake fatality ratio for a given hazard level. It reads the QGIS QSettings to know what is the default earthquake function. :param hazard_level: The hazard level. :type hazard_level: int :return: The fatality rate. :rtype: float
def get_template(self, name=None, params=None): """ Retrieve an index template by its name. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html>`_ :arg name: The name of the template :arg flat_settings: Return settings in flat format (default:...
Retrieve an index template by its name. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html>`_ :arg name: The name of the template :arg flat_settings: Return settings in flat format (default: false) :arg local: Return local information, do not retriev...
def create_folder_structure(project_name, batch_name): """This function creates a folder structure for the batch project. The folder structure consists of main working folder ``project_name` located in the ``outdatadir`` (as defined in the cellpy configuration file) with a sub-folder named ``batch_name...
This function creates a folder structure for the batch project. The folder structure consists of main working folder ``project_name` located in the ``outdatadir`` (as defined in the cellpy configuration file) with a sub-folder named ``batch_name``. It also creates a folder inside the ``batch_name`` fol...
def _get_contour_values(min_val, max_val, base=0, interval=100): """Return a list of values between min and max within an interval.""" i = base out = [] if min_val < base: while i >= min_val: i -= interval while i <= max_val: if i >= min_val: out.append(i) ...
Return a list of values between min and max within an interval.
def connection_from_url(self, url, pool_kwargs=None): """ Similar to :func:`urllib3.connectionpool.connection_from_url`. If ``pool_kwargs`` is not provided and a new pool needs to be constructed, ``self.connection_pool_kw`` is used to initialize the :class:`urllib3.connectionpoo...
Similar to :func:`urllib3.connectionpool.connection_from_url`. If ``pool_kwargs`` is not provided and a new pool needs to be constructed, ``self.connection_pool_kw`` is used to initialize the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs`` is provided, it is used inst...
def list(cls, params=None): """ Retrieves a list of the model :param params: params as dictionary :type params: dict :return: the list of the parsed xml objects :rtype: list """ return fields.ListField(name=cls.ENDPOINT, init_class=cls).decode( ...
Retrieves a list of the model :param params: params as dictionary :type params: dict :return: the list of the parsed xml objects :rtype: list
def count_stages(self, matrix_name): """ Number of registered stages for given matrix name. Parameters: matrix_name (str): name of the matrix Returns: int: number of reported stages for given matrix name. """ return len(self.data[matrix_name]) if...
Number of registered stages for given matrix name. Parameters: matrix_name (str): name of the matrix Returns: int: number of reported stages for given matrix name.
def _PreprocessSources(self, extraction_engine): """Preprocesses the sources. Args: extraction_engine (BaseEngine): extraction engine to preprocess the sources. """ logger.debug('Starting preprocessing.') try: artifacts_registry = engine.BaseEngine.BuildArtifactsRegistry( ...
Preprocesses the sources. Args: extraction_engine (BaseEngine): extraction engine to preprocess the sources.
def assistants(self): '''Get all assistants in this DAP''' return [strip_suffix(f, '.yaml') for f in self._stripped_files if self._assistants_pattern.match(f)]
Get all assistants in this DAP
def _compute_input_activations(self, X): """Compute input activations given X""" n_samples = X.shape[0] mlp_acts = np.zeros((n_samples, self.n_hidden)) if (self._use_mlp_input): b = self.components_['biases'] w = self.components_['weights'] mlp_acts ...
Compute input activations given X
def url(self): """ Full URL as requested by the client (computed). This value is constructed out of different environment variables and includes scheme, host, port, scriptname, path and query string. """ scheme = self.environ.get('wsgi.url_scheme', 'http') host ...
Full URL as requested by the client (computed). This value is constructed out of different environment variables and includes scheme, host, port, scriptname, path and query string.
def eight_node(cm=False): """Eight-node network.""" tpm = np.array([ [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 1], [1, 1, 1, 0, 0, 0, 0, 0], ...
Eight-node network.
def add_subdispatch(self, dispatcher, prefix=''): """Adds a subdispatcher, possibly in its own namespace. :param dispatcher: The dispatcher to add as a subdispatcher. :type dispatcher: RPCDispatcher :param str prefix: A prefix. All of the new subdispatchers methods will be ...
Adds a subdispatcher, possibly in its own namespace. :param dispatcher: The dispatcher to add as a subdispatcher. :type dispatcher: RPCDispatcher :param str prefix: A prefix. All of the new subdispatchers methods will be available as prefix + their original name.
def set_advertising(self, enabled): """Toggle advertising.""" if enabled: self.bable.set_advertising( enabled=True, uuids=[TileBusService.uuid], name="V_IOTile ", company_id=ArchManuID, advertising_data=self._adv...
Toggle advertising.
def refine(video, episode_refiners=None, movie_refiners=None, **kwargs): """Refine a video using :ref:`refiners`. .. note:: Exceptions raised in refiners are silently passed and logged. :param video: the video to refine. :type video: :class:`~subliminal.video.Video` :param tuple episode_r...
Refine a video using :ref:`refiners`. .. note:: Exceptions raised in refiners are silently passed and logged. :param video: the video to refine. :type video: :class:`~subliminal.video.Video` :param tuple episode_refiners: refiners to use for episodes. :param tuple movie_refiners: refiners...
def read(self, size=None): """Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all re...
Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all remaining data. Returns: ...
def revert(self, version, url): """ Set the given version to be the active draft. This is done by calling the object's `make_draft` method. Logs the revert as a 'save' and messages the user. """ message = "Draft replaced with %s version. This revert has not been published...
Set the given version to be the active draft. This is done by calling the object's `make_draft` method. Logs the revert as a 'save' and messages the user.
def download_pisa_multimers_xml(pdb_ids, save_single_xml_files=True, outdir=None, force_rerun=False): """Download the PISA XML file for multimers. See: http://www.ebi.ac.uk/pdbe/pisa/pi_download.html for more info XML description of macromolecular assemblies: http://www.ebi.ac.uk/pdbe/pisa/cgi-bin...
Download the PISA XML file for multimers. See: http://www.ebi.ac.uk/pdbe/pisa/pi_download.html for more info XML description of macromolecular assemblies: http://www.ebi.ac.uk/pdbe/pisa/cgi-bin/multimers.pisa?pdbcodelist where "pdbcodelist" is a comma-separated (strictly no spaces) list of PDB...
def porosimetry(im, sizes=25, inlets=None, access_limited=True, mode='hybrid'): r""" Performs a porosimetry simulution on the image Parameters ---------- im : ND-array An ND image of the porous material containing True values in the pore space. sizes : array_lik...
r""" Performs a porosimetry simulution on the image Parameters ---------- im : ND-array An ND image of the porous material containing True values in the pore space. sizes : array_like or scalar The sizes to invade. If a list of values of provided they are used dire...
def get_config_set(self, section, option): """Returns a set with each value per config file in it. """ values = set() for cp, filename, fp in self.layers: filename = filename # pylint fp = fp # pylint if cp.has_option(section, option): values.add(cp.get(section, option)) return values
Returns a set with each value per config file in it.
def cli_empty_container(context, path, until_empty=False): """ Deletes all objects in the container. By default, this will perform one pass at deleting all objects in the container; so if objects revert to previous versions or if new objects otherwise arise during the process, the container may not...
Deletes all objects in the container. By default, this will perform one pass at deleting all objects in the container; so if objects revert to previous versions or if new objects otherwise arise during the process, the container may not be empty once done. Set `until_empty` to True if you want mul...
def add_line_wrappers(data_passed_from_pelican): """A function to read through each page and post as it comes through from Pelican, find all instances of triple-backtick (```...```) code blocks, and add an HTML wrapper to each line of each of those code blocks""" if data_passed_from_pelican._content: # If the ...
A function to read through each page and post as it comes through from Pelican, find all instances of triple-backtick (```...```) code blocks, and add an HTML wrapper to each line of each of those code blocks
def aggregate(self, pipeline, **kwargs): """Perform an aggregation and make sure that result will be everytime CommandCursor. Will take care for pymongo version differencies :param pipeline: {list} of aggregation pipeline stages :return: {pymongo.command_cursor.CommandCursor} """...
Perform an aggregation and make sure that result will be everytime CommandCursor. Will take care for pymongo version differencies :param pipeline: {list} of aggregation pipeline stages :return: {pymongo.command_cursor.CommandCursor}
def _set_arg(self, a, s="main", c=False): """ Set a single argument. :param a: argparse.Action instance :param s: config section title :param c: use class' ConfigParser instance to get parameters """ # if action of an argument that suppresses any other, j...
Set a single argument. :param a: argparse.Action instance :param s: config section title :param c: use class' ConfigParser instance to get parameters
def get_payload(self, payload_class, payload_key = None, specialize = False): """Get the first payload item matching the given class and optional key. Payloads may be addressed using a specific payload class or via the generic `XML...
Get the first payload item matching the given class and optional key. Payloads may be addressed using a specific payload class or via the generic `XMLPayload` element, though the `XMLPayload` representation is available only as long as the element is not requested by a more spec...
def arducopter_arm(self): '''arm motors (arducopter only)''' if self.mavlink10(): self.mav.command_long_send( self.target_system, # target_system self.target_component, mavlink.MAV_CMD_COMPONENT_ARM_DISARM, # command 0, # confi...
arm motors (arducopter only)
def do_eval(self, inputs, ctx): """Evalute ourselves.""" return cwltool.expression.do_eval( self.expr, inputs, self.req, None, None, {}, context=ctx)
Evalute ourselves.
def setup_stack(self, argv, envp): """ :param Cpu cpu: The cpu instance :param argv: list of parameters for the program to execute. :param envp: list of environment variables for the program to execute. http://www.phrack.org/issues.html?issue=58&id=5#article position ...
:param Cpu cpu: The cpu instance :param argv: list of parameters for the program to execute. :param envp: list of environment variables for the program to execute. http://www.phrack.org/issues.html?issue=58&id=5#article position content size (bytes) + com...
def disconnect(self, node): """ Disconnect node :param node: :return: """ if super(OneOrMore, self).__len__() < 2: raise AttemptedCardinalityViolation("One or more expected") return super(OneOrMore, self).disconnect(node)
Disconnect node :param node: :return:
def _pollMouse(self): """ Polls @10Hz, with a slight delay at the start. """ if self._mouseJustPressed: delay = 300 self._mouseJustPressed = False else: delay = 100 if self._leftMousePressed: self.add(1) ...
Polls @10Hz, with a slight delay at the start.
def createNetwork(dataSource): """Create the Network instance. The network has a sensor region reading data from `dataSource` and passing the encoded representation to an Identity Region. :param dataSource: a RecordStream instance to get data from :returns: a Network instance ready to run """ network = ...
Create the Network instance. The network has a sensor region reading data from `dataSource` and passing the encoded representation to an Identity Region. :param dataSource: a RecordStream instance to get data from :returns: a Network instance ready to run
def apply_deduct(self, body, total_fee, contract_id, notify_url, out_trade_no=None, detail=None, attach=None, fee_type='CNY', goods_tag=None, clientip=None, deviceid=None, mobile=None, email=None, qq=None, openid=None, creid=None, outerid=None): """ 申请扣款 api ...
申请扣款 api :param body: 商品描述 商品或支付单简要描述 :param out_trade_no: 可选 商户订单号 商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号 :param total_fee: 总金额 订单总金额,单位为分,只能为整数,详见支付金额 :param contract_id: 委托代扣协议id 签约成功后,微信返回的委托代扣协议id :param notify_url: 回调通知url 接受扣款结果异步回调通知的url :param detail: 可选 商品详情 商品名称明...
def tag_sites(self, scaled_positions, symprec=1e-3): """Returns an integer array of the same length as *scaled_positions*, tagging all equivalent atoms with the same index. Example: >>> from ase.lattice.spacegroup import Spacegroup >>> sg = Spacegroup(225) # fcc >>> s...
Returns an integer array of the same length as *scaled_positions*, tagging all equivalent atoms with the same index. Example: >>> from ase.lattice.spacegroup import Spacegroup >>> sg = Spacegroup(225) # fcc >>> sg.tag_sites([[0.0, 0.0, 0.0], ... [0.5, 0...
def temperature_data_from_json(data, orient="list"): """ Load temperature data from json. (Must be given in degrees Fahrenheit). Default format:: [ ['2017-01-01T00:00:00+00:00', 3.5], ['2017-01-01T01:00:00+00:00', 5.4], ['2017-01-01T02:00:00+00:00', 7.4], ...
Load temperature data from json. (Must be given in degrees Fahrenheit). Default format:: [ ['2017-01-01T00:00:00+00:00', 3.5], ['2017-01-01T01:00:00+00:00', 5.4], ['2017-01-01T02:00:00+00:00', 7.4], ] Parameters ---------- data : :any:`list` ...
def debconf_set_selections(package, selections): """Given package and map config:(type,value), set selections""" text = '\n'.join(' '.join([package, k, t, v]) for k, (t, v) in selections.iteritems()) sudo('debconf-set-selections <<-HEREDOC\n{}\nHEREDOC'.format(text))
Given package and map config:(type,value), set selections
def _find_new_partners(self): """ Search the token network for potential channel partners. """ open_channels = views.get_channelstate_open( chain_state=views.state_from_raiden(self.raiden), payment_network_id=self.registry_address, token_address=self.token_address, ...
Search the token network for potential channel partners.
def destandardize(self, estimates, se, **kwargs): """Revert the betas and variance components back to the original scale. """ pvalues = kwargs["pvalues"] v = kwargs["v"] nonmissing=kwargs["nonmissing"] pheno = self.datasource.phenotype_data[self.idx][self.datasource.phen...
Revert the betas and variance components back to the original scale.
def load_system(cls, dict_, system_id='system'): """ Create a :class:`MolecularSystem` from a python :class:`dict`. As the loaded :class:`MolecularSystem` is storred as a :class:`dict` in the :class:`MolecularSystem.system` it can also be loaded directly from a :class:`dict` inp...
Create a :class:`MolecularSystem` from a python :class:`dict`. As the loaded :class:`MolecularSystem` is storred as a :class:`dict` in the :class:`MolecularSystem.system` it can also be loaded directly from a :class:`dict` input. This feature is used by :mod:`trajectory` that extracts t...
def on(self, val=None): """Turns the MixedParameter ON by setting its Value to val An attempt to turn the parameter on with value 'False' will result in an error, since this is the same as turning the parameter off. Turning the MixedParameter ON without a value or with value 'None'...
Turns the MixedParameter ON by setting its Value to val An attempt to turn the parameter on with value 'False' will result in an error, since this is the same as turning the parameter off. Turning the MixedParameter ON without a value or with value 'None' will let the parameter...