code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _get_backend_router(self, locations, item): """Returns valid router options for ordering a dedicated host.""" mask = ''' id, hostname ''' cpu_count = item['capacity'] for capacity in item['bundleItems']: for category in capacity['categorie...
Returns valid router options for ordering a dedicated host.
def loads(cls, s): """Parse from a string representation (repr)""" try: currency, amount = s.strip().split(' ') return cls(amount, currency) except ValueError as err: # RADAR: Python2 money.six.raise_from(ValueError("failed to parse string " ...
Parse from a string representation (repr)
def det4D(m): ''' det4D(array) yields the determinate of the given matrix array, which may have more than 2 dimensions, in which case the later dimensions are multiplied and added point-wise. ''' # I just solved this in Mathematica, copy-pasted, and replaced the string '] m' with ']*m': # Math...
det4D(array) yields the determinate of the given matrix array, which may have more than 2 dimensions, in which case the later dimensions are multiplied and added point-wise.
def crossvalidate_model(self, classifier, data, num_folds, rnd, output=None): """ Crossvalidates the model using the specified data, number of folds and random number generator wrapper. :param classifier: the classifier to cross-validate :type classifier: Classifier :param data:...
Crossvalidates the model using the specified data, number of folds and random number generator wrapper. :param classifier: the classifier to cross-validate :type classifier: Classifier :param data: the data to evaluate on :type data: Instances :param num_folds: the number of fol...
def merge(self, other): """ Merges two BoolCells """ other = BoolCell.coerce(other) if self.is_equal(other): # pick among dependencies return self elif other.is_entailed_by(self): return self elif self.is_entailed_by(other): ...
Merges two BoolCells
def get_region_products(self, region): """获得指定区域的产品信息 Args: - region: 区域,如:"nq" Returns: 返回该区域的产品信息,若失败则返回None """ regions, retInfo = self.list_regions() if regions is None: return None for r in regions: if r.get...
获得指定区域的产品信息 Args: - region: 区域,如:"nq" Returns: 返回该区域的产品信息,若失败则返回None
def _set_fcoe(self, v, load=False): """ Setter method for fcoe, mapped from YANG variable /interface/fcoe (list) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe is considered as a private method. Backends looking to populate this variable should do so via ca...
Setter method for fcoe, mapped from YANG variable /interface/fcoe (list) If this variable is read-only (config: false) in the source YANG file, then _set_fcoe is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_fcoe() directly. YANG De...
def focus(self, f): """ Get a new UI proxy copy with the given focus. Return a new UI proxy object as the UI proxy is immutable. Args: f (2-:obj:`tuple`/2-:obj:`list`/:obj:`str`): the focus point, it can be specified as 2-list/2-tuple coordinates (x, y) in NormalizedCoo...
Get a new UI proxy copy with the given focus. Return a new UI proxy object as the UI proxy is immutable. Args: f (2-:obj:`tuple`/2-:obj:`list`/:obj:`str`): the focus point, it can be specified as 2-list/2-tuple coordinates (x, y) in NormalizedCoordinate system or as 'center' or 'anchor...
def create(dataset, label=None, features=None, distance=None, method='auto', verbose=True, **kwargs): """ Create a nearest neighbor model, which can be searched efficiently and quickly for the nearest neighbors of a query observation. If the `method` argument is specified as `auto`, the type ...
Create a nearest neighbor model, which can be searched efficiently and quickly for the nearest neighbors of a query observation. If the `method` argument is specified as `auto`, the type of model is chosen automatically based on the type of data in `dataset`. .. warning:: The 'dot_product' dis...
def watch_login(status_code=302, msg='', get_username=utils.get_username_from_request): """ Used to decorate the django.contrib.admin.site.login method or any other function you want to protect by brute forcing. To make it work on normal functions just pass the status code that should ...
Used to decorate the django.contrib.admin.site.login method or any other function you want to protect by brute forcing. To make it work on normal functions just pass the status code that should indicate a failure and/or a string that will be checked within the response body.
def clear_alert_destination(self, destination=0, channel=None): """Clear an alert destination Remove the specified alert destination configuration. :param destination: The destination to clear (defaults to 0) """ if channel is None: channel = self.get_network_chann...
Clear an alert destination Remove the specified alert destination configuration. :param destination: The destination to clear (defaults to 0)
def add_lvl_to_ui(self, level, header): """Insert the level and header into the ui. :param level: a newly created level :type level: :class:`jukeboxcore.gui.widgets.browser.AbstractLevel` :param header: a newly created header :type header: QtCore.QWidget|None :returns: N...
Insert the level and header into the ui. :param level: a newly created level :type level: :class:`jukeboxcore.gui.widgets.browser.AbstractLevel` :param header: a newly created header :type header: QtCore.QWidget|None :returns: None :rtype: None :raises: None
def get_atom_feed_entry(self, feedentry_id): """ Get a specific feed entry :param id: id of the feed entry to retrieve :return: the feed entry """ return self.session.query(self.feedentry_model).filter( self.feedentry_model.id == feedentry_id ).one()
Get a specific feed entry :param id: id of the feed entry to retrieve :return: the feed entry
def create(source, requirement_files=None, force=False, keep_wheels=False, archive_destination_dir='.', python_versions=None, validate_archive=False, wheel_args='', archive_format='zip', build_tag=''): """Create a Wag...
Create a Wagon archive and returns its path. Package name and version are extracted from the setup.py file of the `source` or from the PACKAGE_NAME==PACKAGE_VERSION if the source is a PyPI package. Supported `python_versions` must be in the format e.g [33, 27, 2, 3].. `force` will remove any exce...
def generate_item_instances(cls, items, mediawiki_api_url='https://www.wikidata.org/w/api.php', login=None, user_agent=config['USER_AGENT_DEFAULT']): """ A method which allows for retrieval of a list of Wikidata items or properties. The method generates a list of ...
A method which allows for retrieval of a list of Wikidata items or properties. The method generates a list of tuples where the first value in the tuple is the QID or property ID, whereas the second is the new instance of WDItemEngine containing all the data of the item. This is most useful for mass retr...
def getColorMapAsDiscreetSLD(self, uniqueValues, nodata=-9999): """ Create the color map SLD format from a list of values. :rtype: str """ colorMap = ET.Element('ColorMap', type='values') # Add a line for the no-data values (nv) ET.SubElement(colorMap, 'ColorMapEn...
Create the color map SLD format from a list of values. :rtype: str
def _populate_trie(self, values: List[str]) -> CharTrie: """Takes a list and inserts its elements into a new trie and returns it""" if self._default_tokenizer: return reduce(self._populate_trie_reducer, iter(values), CharTrie()) return reduce(self._populate_trie_reducer_regex, iter(v...
Takes a list and inserts its elements into a new trie and returns it
def get_bhavcopy_url(self, d): """take date and return bhavcopy url""" d = parser.parse(d).date() day_of_month = d.strftime("%d") mon = d.strftime("%b").upper() year = d.year url = self.bhavcopy_base_url % (year, mon, day_of_month, mon, year) return url
take date and return bhavcopy url
def isRunActive(g): """ Polls the data server to see if a run is active """ if g.cpars['hcam_server_on']: url = g.cpars['hipercam_server'] + 'summary' response = urllib.request.urlopen(url, timeout=2) rs = ReadServer(response.read(), status_msg=True) if not rs.ok: ...
Polls the data server to see if a run is active
def on_connect(self, client, userdata, flags, rc): ''' Callback for when the client receives a ``CONNACK`` response from the broker. Parameters ---------- client : paho.mqtt.client.Client The client instance for this callback. userdata : object ...
Callback for when the client receives a ``CONNACK`` response from the broker. Parameters ---------- client : paho.mqtt.client.Client The client instance for this callback. userdata : object The private user data as set in :class:`paho.mqtt.client.Client` ...
def zone(self, name, dns_name=None, description=None): """Construct a zone bound to this client. :type name: str :param name: Name of the zone. :type dns_name: str :param dns_name: (Optional) DNS name of the zone. If not passed, then calls to :meth:`zon...
Construct a zone bound to this client. :type name: str :param name: Name of the zone. :type dns_name: str :param dns_name: (Optional) DNS name of the zone. If not passed, then calls to :meth:`zone.create` will fail. :type description: str :para...
def insert_chain(cur, chain, encoded_data=None): """Insert a chain into the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. chain (iterable): A collection of nodes. Chains in embedding act a...
Insert a chain into the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. chain (iterable): A collection of nodes. Chains in embedding act as one node. encoded_data (dict, optional): ...
def current_bed_temp(self): """Return current bed temperature for in-progress session.""" try: bedtemps = self.intervals[0]['timeseries']['tempBedC'] num_temps = len(bedtemps) if num_temps == 0: return None bedtemp = bedtemps[num_temps-1]...
Return current bed temperature for in-progress session.
def set_start_date(self, date): """Sets the start date. arg: date (osid.calendaring.DateTime): the new date raise: InvalidArgument - ``date`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``date`` is ``null`` *compliance: ...
Sets the start date. arg: date (osid.calendaring.DateTime): the new date raise: InvalidArgument - ``date`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``date`` is ``null`` *compliance: mandatory -- This method must be implemente...
def acceptEdit(self): """ Accepts the current edit for this label. """ if not self._lineEdit: return self.setText(self._lineEdit.text()) self._lineEdit.hide() if not self.signalsBlocked(): self.editingFinished.e...
Accepts the current edit for this label.
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidTextClock, self).init_widget() d = self.declaration if d.format_12_hour: self.set_format_12_hour(d.format_12_hour) if d.format_24_hour: self.set_format_24_hour(d.format_...
Initialize the underlying widget.
def do_before_loop(self): """Called before the main daemon loop. :return: None """ logger.info("I am the arbiter: %s", self.link_to_myself.name) # If I am a spare, I do not have anything to do here... if not self.is_master: logger.debug("Waiting for my maste...
Called before the main daemon loop. :return: None
def checkSanity(cls, trust_root_string): """str -> bool is this a sane trust root? """ trust_root = cls.parse(trust_root_string) if trust_root is None: return False else: return trust_root.isSane()
str -> bool is this a sane trust root?
def add_host_to_segment(ipaddress, name, description, network_address, auth, url): ''' Function to abstract existing add_scope_ip_function. Allows for use of network address rather than forcing human to learn the scope_id :param ipaddress: :param name: name of the owner of this host :param descrip...
Function to abstract existing add_scope_ip_function. Allows for use of network address rather than forcing human to learn the scope_id :param ipaddress: :param name: name of the owner of this host :param description: Description of the host :param: network_address: network address of the target s...
def is_object(brain_or_object): """Check if the passed in object is a supported portal content object :param brain_or_object: A single catalog brain or content object :type brain_or_object: Portal Object :returns: True if the passed in object is a valid portal content """ if is_portal(brain_or_...
Check if the passed in object is a supported portal content object :param brain_or_object: A single catalog brain or content object :type brain_or_object: Portal Object :returns: True if the passed in object is a valid portal content
def stop_instance(self, instance_id): """Stops the instance gracefully. :param str instance_id: instance identifier """ instance = self._load_instance(instance_id) instance.terminate() del self._instances[instance_id]
Stops the instance gracefully. :param str instance_id: instance identifier
def get_validator(filter_data): """ ask every matcher whether it can serve such filter data :param filter_data: :return: """ for matcher_type, m in matchers.items(): if hasattr(m, 'can_handle') and m.can_handle(filter_data): filter_data = m.handle(filter_data) return fi...
ask every matcher whether it can serve such filter data :param filter_data: :return:
def db_create(cls, impl, working_dir): """ Create a sqlite3 db at the given path. Create all the tables and indexes we need. Returns a db connection on success Raises an exception on error """ global VIRTUALCHAIN_DB_SCRIPT log.debug("Setup chain s...
Create a sqlite3 db at the given path. Create all the tables and indexes we need. Returns a db connection on success Raises an exception on error
def change_sample(self, old_samp_name, new_samp_name, new_site_name=None, new_er_data=None, new_pmag_data=None, replace_data=False): """ Find actual data objects for sample and site. Then call Sample class change method to update sample name and data.. """ s...
Find actual data objects for sample and site. Then call Sample class change method to update sample name and data..
def add(ctx, short_name, uri, interval, buffer): """Add a subscription with a given short_name for a given uri This command can be used to create subscriptions to receive new pieces of vehicle data on the stream channel on a periodic basis. By default, subscriptions are buffered and have a 5 second interval: \b ...
Add a subscription with a given short_name for a given uri This command can be used to create subscriptions to receive new pieces of vehicle data on the stream channel on a periodic basis. By default, subscriptions are buffered and have a 5 second interval: \b $ wva subscriptions add speed vehicle/data/VehicleSp...
def collate_data(in_dir, extension='.csv', out_dir=None): """ Copy all csvs in nested directroy to single directory. Function to copy all csvs from a directory, and place them in a new directory. Parameters ---------- in_dir : str Input directory containing csv files in subfolders ...
Copy all csvs in nested directroy to single directory. Function to copy all csvs from a directory, and place them in a new directory. Parameters ---------- in_dir : str Input directory containing csv files in subfolders extension : str The extension that identifies your data fi...
def run(self, backend_args, archive_args=None, resume=False): """Run the backend with the given parameters. The method will run the backend assigned to this job, storing the fetched items in a Redis queue. The ongoing status of the job, can be accessed through the property `resu...
Run the backend with the given parameters. The method will run the backend assigned to this job, storing the fetched items in a Redis queue. The ongoing status of the job, can be accessed through the property `result`. When `resume` is set, the job will start from the last execu...
def _set_nd_basic_indexing(self, key, value): """This function is called by __setitem__ when key is a basic index, i.e. an integer, or a slice, or a tuple of integers and slices. No restrictions on the values of slices' steps.""" shape = self.shape if isinstance(key, integer_type...
This function is called by __setitem__ when key is a basic index, i.e. an integer, or a slice, or a tuple of integers and slices. No restrictions on the values of slices' steps.
def resolve_font(name): """Turns font names into absolute filenames This is case sensitive. The extension should be omitted. For example:: >>> path = resolve_font('NotoSans-Bold') >>> fontdir = os.path.join(os.path.dirname(__file__), 'fonts') >>> noto_path = os.path.join(fontdir,...
Turns font names into absolute filenames This is case sensitive. The extension should be omitted. For example:: >>> path = resolve_font('NotoSans-Bold') >>> fontdir = os.path.join(os.path.dirname(__file__), 'fonts') >>> noto_path = os.path.join(fontdir, 'NotoSans-Bold.ttf') >...
def compute_fov(self, x, y, fov='PERMISSIVE', radius=None, light_walls=True, sphere=True, cumulative=False): """Compute the field-of-view of this Map and return an iterator of the points touched. Args: x (int): Point of view, x-coordinate. y (int): Po...
Compute the field-of-view of this Map and return an iterator of the points touched. Args: x (int): Point of view, x-coordinate. y (int): Point of view, y-coordinate. fov (Text): The type of field-of-view to be used. Available types are: ...
def split(self, sequence): """ Split into subsequences according to `sequence`.""" major_idx = sequence.idx idx2 = 0 for start, end in zip(major_idx[:-1], major_idx[1:]): idx1 = self.idx.index(start, idx2) idx2 = self.idx.index(end, idx2) seq = Sequence(self.text[start:end]) seq...
Split into subsequences according to `sequence`.
def transform_to_length(nndata, length): """ Given NNData, transforms data to the specified fingerprint length Args: nndata: (NNData) length: (int) desired length of NNData """ if length is None: return nndata if length: f...
Given NNData, transforms data to the specified fingerprint length Args: nndata: (NNData) length: (int) desired length of NNData
def getEstablishments(self, city_id, **kwargs): """ :param city_id: id of the city for which collections are needed :param lat: latitude :param lon: longitude Get a list of restaurant types in a city. The location/City input can be provided in the following ways - Using Z...
:param city_id: id of the city for which collections are needed :param lat: latitude :param lon: longitude Get a list of restaurant types in a city. The location/City input can be provided in the following ways - Using Zomato City ID - Using coordinates of any location within a c...
def parse_date(value): """Attempts to parse `value` into an instance of ``datetime.date``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string, datetime.date, or datetime.datetime value. """ if not value: return Non...
Attempts to parse `value` into an instance of ``datetime.date``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string, datetime.date, or datetime.datetime value.
def parse_frequencies(variant, transcripts): """Add the frequencies to a variant Frequencies are parsed either directly from keys in info fieds or from the transcripts is they are annotated there. Args: variant(cyvcf2.Variant): A parsed vcf variant transcripts(iterable(dict)): Parsed t...
Add the frequencies to a variant Frequencies are parsed either directly from keys in info fieds or from the transcripts is they are annotated there. Args: variant(cyvcf2.Variant): A parsed vcf variant transcripts(iterable(dict)): Parsed transcripts Returns: frequencies(dict): ...
def determine_coords(list_of_variable_dicts): # type: (List[Dict]) -> Tuple[Set, Set] """Given a list of dicts with xarray object values, identify coordinates. Parameters ---------- list_of_variable_dicts : list of dict or Dataset objects Of the same form as the arguments to expand_variable...
Given a list of dicts with xarray object values, identify coordinates. Parameters ---------- list_of_variable_dicts : list of dict or Dataset objects Of the same form as the arguments to expand_variable_dicts. Returns ------- coord_names : set of variable names noncoord_names : set...
def register_plugin(self, name): """Load and register a plugin given its package name.""" logger.info("Registering plugin: " + name) module = importlib.import_module(name) module.register_plugin(self)
Load and register a plugin given its package name.
def _pages_to_generate(self): '''Return list of slugs that correspond to pages to generate.''' # right now it gets all the files. In theory, It should only # get what's changed... but the program is not doing that yet. all_pages = self.get_page_names() # keep only those whose st...
Return list of slugs that correspond to pages to generate.
def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0): """Show detailed information about an object. Optional arguments: - oname: name of the variable pointing to the object. - formatter: special formatter for docstrings (see pdoc) - info: a structure with some...
Show detailed information about an object. Optional arguments: - oname: name of the variable pointing to the object. - formatter: special formatter for docstrings (see pdoc) - info: a structure with some information fields which may have been precomputed already. - d...
def connect(token, protocol=RtmProtocol, factory=WebSocketClientFactory, factory_kwargs=None, api_url=None, debug=False): """ Creates a new connection to the Slack Real-Time API. Returns (connection) which represents this connection to the API server. """ if factory_kwargs is None: factory_kwargs = dict() me...
Creates a new connection to the Slack Real-Time API. Returns (connection) which represents this connection to the API server.
def _updown(self, direction): """Provides curses scroll functionality. """ if direction == "up" and self.top_line != 0: self.top_line -= 1 elif direction == "down" and \ self.screen.getmaxyx()[0] + self.top_line\ <= self.content_lines + 3: ...
Provides curses scroll functionality.
def get_user_information(): """ Returns the user's information :rtype: (str, int, str) """ try: import pwd _username = pwd.getpwuid(os.getuid())[0] _userid = os.getuid() _uname = os.uname()[1] except ImportError: import getpass _username = getpass...
Returns the user's information :rtype: (str, int, str)
def make_backup_files(*, mongodump=MONGODB_DEFAULT_MONGODUMP, hosts={}, host_defaults={}, dry_run=False, **kwargs): """ Backup all specified databases into a gzipped tarball via mongodump :param mo...
Backup all specified databases into a gzipped tarball via mongodump :param mongodump(str, optional): Path to mongodump executable :param hosts(dict, optional): A dict containing hosts info to be backed up :param host_defaults(dict, optional): Default values applied to each host :param dry_run(bool, opt...
def _handle_continue(self, node, scope, ctxt, stream): """Handle continue node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling continue") raise errors.InterpContinue()
Handle continue node :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
def load(self, orbit=None): """Load a particular orbit into .data for loaded day. Parameters ---------- orbit : int orbit number, 1 indexed Note ---- A day of data must be loaded before this routine functions properly. If the last orbit o...
Load a particular orbit into .data for loaded day. Parameters ---------- orbit : int orbit number, 1 indexed Note ---- A day of data must be loaded before this routine functions properly. If the last orbit of the day is requested, it will automat...
def load_sanitizers(self, config_data): """ Loads sanitizers possibly defined in the configuration under dictionary called "strategy", which should contain mapping of database tables with column names mapped into sanitizer function names. :param config_data: Already parsed confi...
Loads sanitizers possibly defined in the configuration under dictionary called "strategy", which should contain mapping of database tables with column names mapped into sanitizer function names. :param config_data: Already parsed configuration data, as dictionary. :type config_data: dic...
def get_client(quiet=False, debug=False): ''' get the client and perform imports not on init, in case there are any initialization or import errors. Parameters ========== quiet: if True, suppress most output about the client debug: turn on debugging mode ''' from...
get the client and perform imports not on init, in case there are any initialization or import errors. Parameters ========== quiet: if True, suppress most output about the client debug: turn on debugging mode
def clinvar_export(store, institute_id, case_name, variant_id): """Gather the required data for creating the clinvar submission form Args: store(scout.adapter.MongoAdapter) institute_id(str): Institute ID case_name(str): case ID variant_id(str): variant._id ...
Gather the required data for creating the clinvar submission form Args: store(scout.adapter.MongoAdapter) institute_id(str): Institute ID case_name(str): case ID variant_id(str): variant._id Returns: a dictionary with all the required data (c...
def sam_list(sam): """ get a list of mapped reads """ list = [] for file in sam: for line in file: if line.startswith('@') is False: line = line.strip().split() id, map = line[0], int(line[1]) if map != 4 and map != 8: list.append(id) return set(list)
get a list of mapped reads
def assert_conditions(self): """Handles various HTTP conditions and raises HTTP exceptions to abort the request. - Content-MD5 request header must match the MD5 hash of the full input (:func:`assert_condition_md5`). - If-Match and If-None-Match etags are checked ag...
Handles various HTTP conditions and raises HTTP exceptions to abort the request. - Content-MD5 request header must match the MD5 hash of the full input (:func:`assert_condition_md5`). - If-Match and If-None-Match etags are checked against the ETag of this res...
def validate_init_args_statically(distribution, batch_shape): """Helper to __init__ which makes or raises assertions.""" if tensorshape_util.rank(batch_shape.shape) is not None: if tensorshape_util.rank(batch_shape.shape) != 1: raise ValueError("`batch_shape` must be a vector " "(sa...
Helper to __init__ which makes or raises assertions.
def Deserialize(self, reader): """ Deserialize full object. Args: reader (neo.IO.BinaryReader): """ self.HashStart = reader.ReadSerializableArray('neocore.UInt256.UInt256') self.HashStop = reader.ReadUInt256()
Deserialize full object. Args: reader (neo.IO.BinaryReader):
def get_tools_paths(self): """Get tools' paths.""" if settings.DEBUG or is_testing(): return list(get_apps_tools().values()) else: tools_root = settings.FLOW_TOOLS_ROOT subdirs = next(os.walk(tools_root))[1] return [os.path.join(tools_root, sdir)...
Get tools' paths.
def maps_get_default_rules_output_rules_rbridgeid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") maps_get_default_rules = ET.Element("maps_get_default_rules") config = maps_get_default_rules output = ET.SubElement(maps_get_default_rules, "output...
Auto Generated Code
def makeCredBearerTokenLoginMethod(username, password, stsUrl, stsCert=None): '''Return a function that will call the vim.SessionManager.LoginByToken() after obtaining a Bearer token from the ST...
Return a function that will call the vim.SessionManager.LoginByToken() after obtaining a Bearer token from the STS. The result of this function can be passed as the "loginMethod" to a SessionOrientedStub constructor. @param username: username of the user/service registered with STS. @param pass...
def backwards(apps, schema_editor): """ Delete sample events, including derivative repeat and variation events. """ titles = [ 'Daily Event', 'Weekday Event', 'Weekend Event', 'Weekly Event', 'Monthly Event', 'Yearly Event', ] samples = EventBase.o...
Delete sample events, including derivative repeat and variation events.
def new_dxfile(mode=None, write_buffer_size=dxfile.DEFAULT_BUFFER_SIZE, expected_file_size=None, file_is_mmapd=False, **kwargs): ''' :param mode: One of "w" or "a" for write and append modes, respectively :type mode: string :rtype: :class:`~dxpy.bindings.dxfile.DXFile` Additional opt...
:param mode: One of "w" or "a" for write and append modes, respectively :type mode: string :rtype: :class:`~dxpy.bindings.dxfile.DXFile` Additional optional parameters not listed: all those under :func:`dxpy.bindings.DXDataObject.new`. Creates a new remote file object that is ready to be written t...
def _rec_get_names(args, names=None): """return a list of all argument names""" if names is None: names = [] for arg in args: if isinstance(arg, node_classes.Tuple): _rec_get_names(arg.elts, names) else: names.append(arg.name) return names
return a list of all argument names
def psffunc(self, *args, **kwargs): """Calculates a linescan psf""" if self.polychromatic: func = psfcalc.calculate_polychrome_linescan_psf else: func = psfcalc.calculate_linescan_psf return func(*args, **kwargs)
Calculates a linescan psf
def add_result(self, scan_id, result_type, host='', name='', value='', port='', test_id='', severity='', qod=''): """ Add a result to a scan in the table. """ assert scan_id assert len(name) or len(value) result = dict() result['type'] = result_type re...
Add a result to a scan in the table.
def _pop_letters(char_list): """Pop consecutive letters from the front of a list and return them Pops any and all consecutive letters from the start of the provided character list and returns them as a list of characters. Operates on (and possibly alters) the passed list :param list char_list: a l...
Pop consecutive letters from the front of a list and return them Pops any and all consecutive letters from the start of the provided character list and returns them as a list of characters. Operates on (and possibly alters) the passed list :param list char_list: a list of characters :return: a lis...
def uninstall(cls): """Remove the package manager from the system.""" if os.path.exists(cls.home): shutil.rmtree(cls.home)
Remove the package manager from the system.
def list_users(ctx, search, uuid, active): """List all locally known users""" users = ctx.obj['db'].objectmodels['user'] for found_user in users.find(): if not search or (search and search in found_user.name): # TODO: Not 2.x compatible print(found_user.name, end=' ' if act...
List all locally known users
def get_default_sess_config(mem_fraction=0.99): """ Return a tf.ConfigProto to use as default session config. You can modify the returned config to fit your needs. Args: mem_fraction(float): see the `per_process_gpu_memory_fraction` option in TensorFlow's GPUOptions protobuf: ...
Return a tf.ConfigProto to use as default session config. You can modify the returned config to fit your needs. Args: mem_fraction(float): see the `per_process_gpu_memory_fraction` option in TensorFlow's GPUOptions protobuf: https://github.com/tensorflow/tensorflow/blob/master/t...
def _duplicateLayer(self, layerName, newLayerName): """ This is the environment implementation of :meth:`BaseFont.duplicateLayer`. **layerName** will be a :ref:`type-string` representing a valid layer name. The value will have been normalized with :func:`normalizers.normalizeLayerName` ...
This is the environment implementation of :meth:`BaseFont.duplicateLayer`. **layerName** will be a :ref:`type-string` representing a valid layer name. The value will have been normalized with :func:`normalizers.normalizeLayerName` and **layerName** will be a layer that exists in the font. **newL...
def evaluate(self, instance, step, extra): """Evaluate the current definition and fill its attributes. Uses attributes definition in the following order: - values defined when defining the ParameteredAttribute - additional values defined when instantiating the containing factory ...
Evaluate the current definition and fill its attributes. Uses attributes definition in the following order: - values defined when defining the ParameteredAttribute - additional values defined when instantiating the containing factory Args: instance (builder.Resolver): The o...
def data_struct(*args, **kw): ''' data_struct(args...) collapses all arguments (which must be maps) and keyword arguments right-to-left into a single mapping and uses this mapping to create a DataStruct object. ''' m = pimms.merge(*args, **kw) return DataStruct(**m)
data_struct(args...) collapses all arguments (which must be maps) and keyword arguments right-to-left into a single mapping and uses this mapping to create a DataStruct object.
def currentGrouping( self ): """ Returns the current grouping for this widget. :return [<str> group level, ..] """ groupBy = self.groupBy() if ( groupBy == XOrbBrowserWidget.GroupByAdvancedKey ): return self.advancedGrouping() els...
Returns the current grouping for this widget. :return [<str> group level, ..]
def _get_event_request_header(self): """Return EventRequestHeader for conversation.""" otr_status = (hangouts_pb2.OFF_THE_RECORD_STATUS_OFF_THE_RECORD if self.is_off_the_record else hangouts_pb2.OFF_THE_RECORD_STATUS_ON_THE_RECORD) return hangouts_pb2....
Return EventRequestHeader for conversation.
def _check_initialized(self): """Internal helper to check for uninitialized properties. Raises: BadValueError if it finds any. """ baddies = self._find_uninitialized() if baddies: raise datastore_errors.BadValueError( 'Entity has uninitialized properties: %s' % ', '.join(baddi...
Internal helper to check for uninitialized properties. Raises: BadValueError if it finds any.
def __discoverPlugins(): """ Discover the plugin classes contained in Python files, given a list of directory names to scan. Return a list of plugin classes. """ for app in settings.INSTALLED_APPS: if not app.startswith('django'): module = __import__(app) moduledir = ...
Discover the plugin classes contained in Python files, given a list of directory names to scan. Return a list of plugin classes.
def _clean(self, magic): """ Given a magic string, remove the output tag designator. """ if magic.lower() == 'o': self.magic = '' elif magic[:2].lower() == 'o:': self.magic = magic[2:] elif magic[:2].lower() == 'o.': self.ext = magic[1:]
Given a magic string, remove the output tag designator.
def save_devices(self): """ save devices that have been obtained from LaMetric cloud to a local file """ log.debug("saving devices to ''...".format(self._devices_filename)) if self._devices != []: with codecs.open(self._devices_filename, "wb", "utf-8") as f: ...
save devices that have been obtained from LaMetric cloud to a local file
def similar(names=None, ids=None, start=0, results=15, buckets=None, limit=False, max_familiarity=None, min_familiarity=None, max_hotttnesss=None, min_hotttnesss=None, seed_catalog=None,artist_start_year_before=None, \ artist_start_year_after=None,artist_end_year_before=None,artist_end_year_afte...
Return similar artists to this one Args: Kwargs: ids (str/list): An artist id or list of ids names (str/list): An artist name or list of names results (int): An integer number of results to return buckets (list): A list of strings specifying w...
def create_comment_browser(self, layout): """Create a comment browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` ...
Create a comment browser and insert it into the given layout :param layout: the layout to insert the browser into :type layout: QLayout :returns: the created browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ListBrowser` :raises: None
def by_user_and_perm(cls, user_id, perm_name, db_session=None): """ return by user and permission name :param user_id: :param perm_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model).fi...
return by user and permission name :param user_id: :param perm_name: :param db_session: :return:
def expected_h(nvals, fit="RANSAC"): """ Uses expected_rs to calculate the expected value for the Hurst exponent h based on the values of n used for the calculation. Args: nvals (iterable of int): the values of n used to calculate the individual (R/S)_n KWargs: fit (str): the fitting met...
Uses expected_rs to calculate the expected value for the Hurst exponent h based on the values of n used for the calculation. Args: nvals (iterable of int): the values of n used to calculate the individual (R/S)_n KWargs: fit (str): the fitting method to use for the line fit, either 'poly' fo...
def _recv_sf(self, data): """Process a received 'Single Frame' frame""" self.rx_timer.cancel() if self.rx_state != ISOTP_IDLE: warning("RX state was reset because single frame was received") self.rx_state = ISOTP_IDLE length = six.indexbytes(data, 0) & 0xf ...
Process a received 'Single Frame' frame
def preorder(self): """Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] *...
Return the nodes in the binary tree using pre-order_ traversal. A pre-order_ traversal visits root, left subtree, then right subtree. .. _pre-order: https://en.wikipedia.org/wiki/Tree_traversal :return: List of nodes. :rtype: [binarytree.Node] **Example**: .. doctest...
def load_py(stream, filepath=None): """Load python-formatted data from a stream. Args: stream (file-like object). Returns: dict. """ with add_sys_paths(config.package_definition_build_python_paths): return _load_py(stream, filepath=filepath)
Load python-formatted data from a stream. Args: stream (file-like object). Returns: dict.
def run(): """ Module level test. """ logging.basicConfig(level=logging.DEBUG) load_config.ConfigLoader().load() config.debug = True print(repr(config.engine.item(sys.argv[1])))
Module level test.
def conf_budget(self, budget): """ Set limit on the number of conflicts. """ if self.maplesat: pysolvers.maplechrono_cbudget(self.maplesat, budget)
Set limit on the number of conflicts.
def validate_one(func_name): """ Validate the docstring for the given func_name Parameters ---------- func_name : function Function whose docstring will be evaluated (e.g. pandas.read_csv). Returns ------- dict A dictionary containing all the information obtained from v...
Validate the docstring for the given func_name Parameters ---------- func_name : function Function whose docstring will be evaluated (e.g. pandas.read_csv). Returns ------- dict A dictionary containing all the information obtained from validating the docstring.
def count(self, source, target): """ The 'count' relationship is used for listing endpoints where a specific attribute might hold the value to the number of instances of another attribute. """ try: source_value = self._response_holder[source] except KeyError: ...
The 'count' relationship is used for listing endpoints where a specific attribute might hold the value to the number of instances of another attribute.
def scale(self, scalex, scaley=None, center=(0, 0)): """ Scale this object. Parameters ---------- scalex : number Scaling factor along the first axis. scaley : number or ``None`` Scaling factor along the second axis. If ``None``, same as ...
Scale this object. Parameters ---------- scalex : number Scaling factor along the first axis. scaley : number or ``None`` Scaling factor along the second axis. If ``None``, same as ``scalex``. center : array-like[2] Center point f...
def reservations(self): """get nodes of every reservations""" command = [SINFO, '--reservation'] output = subprocess.check_output(command, env=SINFO_ENV) output = output.decode() it = iter(output.splitlines()) next(it) for line in it: rsv = Reservation...
get nodes of every reservations
def tagged(self, tag): """Returns a new PostCollection containing the subset of posts that are tagged with *tag*.""" return PostCollection([p for p in self if unicode(tag) in p.tags])
Returns a new PostCollection containing the subset of posts that are tagged with *tag*.
def _set_service(self, v, load=False): """ Setter method for service, mapped from YANG variable /service (container) If this variable is read-only (config: false) in the source YANG file, then _set_service is considered as a private method. Backends looking to populate this variable should do so...
Setter method for service, mapped from YANG variable /service (container) If this variable is read-only (config: false) in the source YANG file, then _set_service is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_service() directly.
def note(name, source=None, contents=None, **kwargs): ''' Add content to a document generated using `highstate_doc.render`. This state does not preform any tasks on the host. It only is used in highstate_doc lowstate proccessers to include extra documents. .. code-block:: yaml {{sls}} exa...
Add content to a document generated using `highstate_doc.render`. This state does not preform any tasks on the host. It only is used in highstate_doc lowstate proccessers to include extra documents. .. code-block:: yaml {{sls}} example note: highstate_doc.note: - name:...
def get_gcp_client(**kwargs): """Public GCP client builder.""" return _gcp_client(project=kwargs['project'], mod_name=kwargs['mod_name'], pkg_name=kwargs.get('pkg_name', 'google.cloud'), key_file=kwargs.get('key_file', None), http_auth=kwargs....
Public GCP client builder.