code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _activity_endpoint(self, athlete, filename): """Construct activity endpoint from host, athlete name and filename Keyword arguments: athlete -- Full athlete name filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\') """ return '{host}{athlete}/a...
Construct activity endpoint from host, athlete name and filename Keyword arguments: athlete -- Full athlete name filename -- filename of request activity (e.g. \'2015_04_29_09_03_16.json\')
def create_dhcprelay_ipv6(self): """Get an instance of DHCPRelayIPv6 services facade.""" return DHCPRelayIPv6( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of DHCPRelayIPv6 services facade.
def load_alias_table(self): """ Load (create, if not exist) the alias config file. """ try: # w+ creates the alias config file if it does not exist open_mode = 'r+' if os.path.exists(GLOBAL_ALIAS_PATH) else 'w+' with open(GLOBAL_ALIAS_PATH, open_mode) ...
Load (create, if not exist) the alias config file.
def pbc_diff(fcoords1, fcoords2): """ Returns the 'fractional distance' between two coordinates taking into account periodic boundary conditions. Args: fcoords1: First set of fractional coordinates. e.g., [0.5, 0.6, 0.7] or [[1.1, 1.2, 4.3], [0.5, 0.6, 0.7]]. It can be a single ...
Returns the 'fractional distance' between two coordinates taking into account periodic boundary conditions. Args: fcoords1: First set of fractional coordinates. e.g., [0.5, 0.6, 0.7] or [[1.1, 1.2, 4.3], [0.5, 0.6, 0.7]]. It can be a single coord or any array of coords. ...
def _notify_receiver(self, receiver, params, doc): """Send notification to the receiver""" verb = VMAP[doc['op']] ns = doc['ns'] notification_id = Id(ns + 'Notification:' + str(ObjectId()) + '@' + params['authority']) object_id = Id(ns + ':' + str(doc['o']['_id']) + '@' + params[...
Send notification to the receiver
def _name(self): """Define object name.""" return "{0} {1} {2}".format( self._camera.name, pretty_timestamp(self.created_at), self._attrs.get('mediaDuration'))
Define object name.
def set_connections_params(self, harakiri=None, timeout_socket=None): """Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60. """ self._set_aliased('harakiri', ha...
Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60.
def move_state(self, direction, activate): """ Set the camera position move state :param direction: What direction to update :param activate: Start or stop moving in the direction """ if direction == RIGHT: self._xdir = POSITIVE if activate else STILL ...
Set the camera position move state :param direction: What direction to update :param activate: Start or stop moving in the direction
def _raw_split(itxt): """ Parse HTML from text into array filled with tags end text. Source code is little bit unintutive, because it is state machine parser. For better understanding, look at http://bit.ly/1rXRcJj Example:: >>> dhtmlparser._raw_split('<html><tag params="true"></html>') ...
Parse HTML from text into array filled with tags end text. Source code is little bit unintutive, because it is state machine parser. For better understanding, look at http://bit.ly/1rXRcJj Example:: >>> dhtmlparser._raw_split('<html><tag params="true"></html>') ['<html>', '<tag params="t...
def parse_datetime(time_str): """ Wraps dateutil's parser function to set an explicit UTC timezone, and to make sure microseconds are 0. Unified Uploader format and EMK format bother don't use microseconds at all. :param str time_str: The date/time str to parse. :rtype: datetime.datetime :r...
Wraps dateutil's parser function to set an explicit UTC timezone, and to make sure microseconds are 0. Unified Uploader format and EMK format bother don't use microseconds at all. :param str time_str: The date/time str to parse. :rtype: datetime.datetime :returns: A parsed, UTC datetime.
def neverCalledWith(cls, spy, *args, **kwargs): #pylint: disable=invalid-name """ Checking the inspector is never called with partial args/kwargs Args: SinonSpy, args/kwargs """ cls.__is_spy(spy) if not (spy.neverCalledWith(*args, **kwargs)): raise cls.failExc...
Checking the inspector is never called with partial args/kwargs Args: SinonSpy, args/kwargs
def get_market_history(self, market): """ Used to retrieve the latest trades that have occurred for a specific market. Endpoint: 1.1 /market/getmarkethistory 2.0 NO Equivalent Example :: {'success': True, 'message': '', 'resul...
Used to retrieve the latest trades that have occurred for a specific market. Endpoint: 1.1 /market/getmarkethistory 2.0 NO Equivalent Example :: {'success': True, 'message': '', 'result': [ {'Id': 5625015, 'TimeStamp'...
def sendmess(self, msgtype, payload, flags=0, size=0, offset=0, timeout=0): """ retcode, data = sendmess(msgtype, payload) send generic message and returns retcode, data """ # reuse last valid connection or create new conn = self.conn or self._new_connection() # ...
retcode, data = sendmess(msgtype, payload) send generic message and returns retcode, data
def get_mnist(sc, data_type="train", location="/tmp/mnist"): """ Get mnist dataset and parallelize into RDDs. Data would be downloaded automatically if it doesn't present at the specific location. :param sc: SparkContext. :param data_type: "train" for training data and "test" for testing data. ...
Get mnist dataset and parallelize into RDDs. Data would be downloaded automatically if it doesn't present at the specific location. :param sc: SparkContext. :param data_type: "train" for training data and "test" for testing data. :param location: Location to store mnist dataset. :return: RDD of (fe...
def _set_inexp_outexp(self, v, load=False): """ Setter method for inexp_outexp, mapped from YANG variable /qos_mpls/map/inexp_outexp (list) If this variable is read-only (config: false) in the source YANG file, then _set_inexp_outexp is considered as a private method. Backends looking to populate th...
Setter method for inexp_outexp, mapped from YANG variable /qos_mpls/map/inexp_outexp (list) If this variable is read-only (config: false) in the source YANG file, then _set_inexp_outexp is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in...
def v2_translator(self, option): """ This is a temporary function that helps move from v1 API to v2 without breaking already running script and keep backwards compatibility. Translates option name from API v1 to renamed one of v2 API. """ new_option = option new_v...
This is a temporary function that helps move from v1 API to v2 without breaking already running script and keep backwards compatibility. Translates option name from API v1 to renamed one of v2 API.
def make_codon_list(protein_seq, template_dna=None, include_stop=True): """ Return a list of codons that would be translated to the given protein sequence. Codons are picked first to minimize the mutations relative to a template DNA sequence and second to prefer "optimal" codons. """ codon_l...
Return a list of codons that would be translated to the given protein sequence. Codons are picked first to minimize the mutations relative to a template DNA sequence and second to prefer "optimal" codons.
def create_table_index(self, key, **kwargs): """ Create a pytables index on the table Parameters ---------- key : object (the node to index) Exceptions ---------- raises if the node is not a table """ # version requirements _tables() ...
Create a pytables index on the table Parameters ---------- key : object (the node to index) Exceptions ---------- raises if the node is not a table
def resource_update(sender, instance, created=False, **kwargs): """ Update resource consumption details and price estimate if its configuration has changed. Create estimates for previous months if resource was created not in current month. """ resource = instance try: new_configuration =...
Update resource consumption details and price estimate if its configuration has changed. Create estimates for previous months if resource was created not in current month.
def setup_default_layouts(self, index, settings): """Setup default layouts when run for the first time.""" self.setUpdatesEnabled(False) first_spyder_run = bool(self.first_spyder_run) # Store copy if first_spyder_run: self.set_window_settings(*settings) els...
Setup default layouts when run for the first time.
def wwpn_free(self, wwpn): """ Free a WWPN allocated with :meth:`wwpn_alloc`. The WWPN must be allocated. Parameters: WWPN (string): The WWPN as 16 hexadecimal digits. Raises: ValueError: WWPN not in pool range or not currently allocated. ...
Free a WWPN allocated with :meth:`wwpn_alloc`. The WWPN must be allocated. Parameters: WWPN (string): The WWPN as 16 hexadecimal digits. Raises: ValueError: WWPN not in pool range or not currently allocated.
def get_bitcoind_client(config_path=None, bitcoind_opts=None): """ Connect to bitcoind """ if bitcoind_opts is None and config_path is None: raise ValueError("Need bitcoind opts or config path") bitcoind_opts = get_bitcoind_config(config_file=config_path) log.debug("Connect to bitcoind ...
Connect to bitcoind
def _draw_button(self, overlay, text, location): """Draws a button on the won and lost overlays, and return its hitbox.""" label = self.button_font.render(text, True, (119, 110, 101)) w, h = label.get_size() # Let the callback calculate the location based on # the width and heigh...
Draws a button on the won and lost overlays, and return its hitbox.
def GetArgs(): """ Supports the command-line arguments listed below. """ parser = argparse.ArgumentParser( description='Process args for retrieving all the Virtual Machines') parser.add_argument('-s', '--host', required=True, action='store', help='Remote host to connect to')...
Supports the command-line arguments listed below.
def ReqUserLogout(self): """退出接口(正常退出,不会触发OnFrontDisconnected)""" self.q.Release() # 确保隔夜或重新登录时的第1个tick不被发送到客户端 self.inst_tick.clear() self.logined = False threading.Thread(target=self.OnDisConnected, args=(self, 0)).start()
退出接口(正常退出,不会触发OnFrontDisconnected)
def download_data(self, configuration, output_file): """ Выполняет указанный в конфигурации запрос и отдает файл на скачивание :param configuration: Конфгурация запроса :param output_file: Место, куда надо скачать файл :return: """ params = configuration r...
Выполняет указанный в конфигурации запрос и отдает файл на скачивание :param configuration: Конфгурация запроса :param output_file: Место, куда надо скачать файл :return:
def binarize_sets(df, columns, cast=False, drop=True, min_freq=None): """ Create dummies for the elements of a set-valued column. Operates in place. Args: df: data frame columns: either a dictionary of column: values pairs or a collection of columns. cast: whether or not to cast valu...
Create dummies for the elements of a set-valued column. Operates in place. Args: df: data frame columns: either a dictionary of column: values pairs or a collection of columns. cast: whether or not to cast values to set drop: whether or not to drop the binarized columns TODO: mak...
def delete_fabric_fw_internal(self, tenant_id, fw_dict, is_fw_virt, result): """Internal routine to delete the fabric configuration. This runs the SM and deletes the entries from DB and local cache. """ if not self.auto_nwk_create: LOG.info(...
Internal routine to delete the fabric configuration. This runs the SM and deletes the entries from DB and local cache.
def describe(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> dict: """ Return a dictionary that describes a given language tag in a specified natural language. See `language_name` and related methods for more specific versions of this. The desired `language` will in fact...
Return a dictionary that describes a given language tag in a specified natural language. See `language_name` and related methods for more specific versions of this. The desired `language` will in fact be matched against the available options using the matching technique that this modul...
def format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = format_job_instance(job) ret.update({'StartTime': jid_to_time(jid)}) return ret
Format the jid correctly
def simple_parse_process( parser: Parser[A, B], node: str, output: List[str], result: List[OutputEvent[A, B]], current: List[OutputLine[A]], ) -> List[OutputEvent[A, B]]: ''' Parse a list of output lines. The algorithm starts at the graph node 'start' 1. detach th...
Parse a list of output lines. The algorithm starts at the graph node 'start' 1. detach the first output line into *line* and *rest* and call *parse_line* 2. find an edge that matches to current line a) if a match was found 3. construct an *OutputLine* 4. set the current node to t...
def delete_user(self, user): """ ADMIN ONLY. Removes the user from the system. There is no 'undo' available, so you should be certain that the user specified is the user you wish to delete. """ user_id = utils.get_id(user) uri = "users/%s" % user_id resp, ...
ADMIN ONLY. Removes the user from the system. There is no 'undo' available, so you should be certain that the user specified is the user you wish to delete.
def reject_worker(self, assignment_id): ''' Reject worker ''' if not self.connect_to_turk(): return False try: self.mtc.reject_assignment(AssignmentId=assignment_id, RequesterFeedback='') return True except Exception as e: print e ...
Reject worker
def subject_pair_overlap(subject1, subject2, object_category=None, **kwargs): """ Jaccard similarity """ set1 = get_object_closure(subject1, object_category=object_category, **kwargs) set2 = get_object_closure(subject2, ...
Jaccard similarity
def read_data(self, chan=None, begtime=None, endtime=None, begsam=None, endsam=None, s_freq=None): """Read the data and creates a ChanTime instance Parameters ---------- chan : list of strings names of the channels to read begtime : int or datedelta...
Read the data and creates a ChanTime instance Parameters ---------- chan : list of strings names of the channels to read begtime : int or datedelta or datetime or list start of the data to read; if it's int or float, it's assumed it's s; i...
def _compare_expected(expected, output, sess, onnx, decimal=5, onnx_shape=None, **kwargs): """ Compares the expected output against the runtime outputs. This is specific to *onnxruntime* due to variable *sess* of type *onnxruntime.InferenceSession*. """ tested = 0 if isinstance(expected, lis...
Compares the expected output against the runtime outputs. This is specific to *onnxruntime* due to variable *sess* of type *onnxruntime.InferenceSession*.
def parseInt(self, words): """Parses words to the integer they describe. Args: words (str): Description of the integer. Returns: An integer representation of the words. """ # Remove 'and', case-sensitivity words = words.replace(" and ", " ").lowe...
Parses words to the integer they describe. Args: words (str): Description of the integer. Returns: An integer representation of the words.
def get_binary_annotations(request, response): """Helper method for getting all binary annotations from the request. :param request: the Pyramid request object :param response: the Pyramid response object :returns: binary annotation dict of {str: str} """ route = request.matched_route.pattern i...
Helper method for getting all binary annotations from the request. :param request: the Pyramid request object :param response: the Pyramid response object :returns: binary annotation dict of {str: str}
def _poll_slapd(self, timeout=DEFAULT_STARTUP_DELAY): """Poll slapd port until available.""" begin = time.time() time.sleep(0.5) while time.time() < begin + timeout: if self._process.poll() is not None: raise RuntimeError("LDAP server has exited before starti...
Poll slapd port until available.
def visit_Rule(self, node: parsing.Rule) -> ast.expr: """Generates python code calling a rule. self.evalRule('rulename') """ return ast.Call( ast.Attribute(ast.Name('self', ast.Load()), 'evalRule', ast.Load()), [ast.Str(node.name)], [], ...
Generates python code calling a rule. self.evalRule('rulename')
def create_wsgi_factory(mounts_factories): """Create a WSGI application factory. Usage example: .. code-block:: python wsgi_factory = create_wsgi_factory({'/api': create_api}) :param mounts_factories: Dictionary of mount points per application factory. .. versionadded:: 1.0.0 ...
Create a WSGI application factory. Usage example: .. code-block:: python wsgi_factory = create_wsgi_factory({'/api': create_api}) :param mounts_factories: Dictionary of mount points per application factory. .. versionadded:: 1.0.0
def _guess_diffusion_axis(process_or_domain): """Scans given process, domain or dictionary of domains for a diffusion axis and returns appropriate name. In case only one axis with length > 1 in the process or set of domains exists, the name of that axis is returned. Otherwise an error is raised. :...
Scans given process, domain or dictionary of domains for a diffusion axis and returns appropriate name. In case only one axis with length > 1 in the process or set of domains exists, the name of that axis is returned. Otherwise an error is raised. :param process_or_domain: input from where diffusion...
def ensure_unicode(str_): """ TODO: rob gp "isinstance\\(.*\\\\bstr\\\\b\\)" """ if isinstance(str_, __STR__): return str_ else: try: return __STR__(str_) except UnicodeDecodeError: if str_.startswith(codecs.BOM_UTF8): # Can saf...
TODO: rob gp "isinstance\\(.*\\\\bstr\\\\b\\)"
def build_system_components(device_type, os_id, navigator_id): """ For given os_id build random platform and oscpu components Returns dict {platform_version, platform, ua_platform, oscpu} platform_version is OS name used in different places ua_platform goes to navigator.platform platform i...
For given os_id build random platform and oscpu components Returns dict {platform_version, platform, ua_platform, oscpu} platform_version is OS name used in different places ua_platform goes to navigator.platform platform is used in building navigator.userAgent oscpu goes to navigator.oscpu
def raster(self, name=None, **creteria): """Generates a GeoRaster2 object based on the asset name(key) or a creteria(protety name and value).""" if name: asset = self.assets[name] if asset["type"] in raster_types: __object = asset.get('__object') i...
Generates a GeoRaster2 object based on the asset name(key) or a creteria(protety name and value).
def data_to_stream(self, data_element, stream): """ Writes the given data element to the given stream. """ generator = \ self._make_representation_generator(stream, self.resource_class, self._mapping) generator.run(data_...
Writes the given data element to the given stream.
def connect(self, taskspec): """ Connect the *following* task to this one. In other words, the given task is added as an output task. :type taskspec: TaskSpec :param taskspec: The new output task. """ self.outputs.append(taskspec) taskspec._connect_notif...
Connect the *following* task to this one. In other words, the given task is added as an output task. :type taskspec: TaskSpec :param taskspec: The new output task.
def get_cities(self): """Get a dictionary of cities keyed by geonameid.""" if self.cities is None: self.cities = self._load_data(self.cities, 'cities.json') return self.cities
Get a dictionary of cities keyed by geonameid.
def analyze_one(self, nm, importernm=None, imptyp=0, level=-1): """ break the name being imported up so we get: a.b.c -> [a, b, c] ; ..z -> ['', '', z] """ #print '## analyze_one', nm, importernm, imptyp, level if not nm: nm = importernm importernm...
break the name being imported up so we get: a.b.c -> [a, b, c] ; ..z -> ['', '', z]
def parse_eora26(path, year=None, price='bp', country_names='eora'): """ Parse the Eora26 database Note ---- This parser deletes the statistical disrecpancy columns from the parsed Eora system (reports the amount of loss in the meta recors). Eora does not provide any information on the un...
Parse the Eora26 database Note ---- This parser deletes the statistical disrecpancy columns from the parsed Eora system (reports the amount of loss in the meta recors). Eora does not provide any information on the unit of the monetary values. Based on personal communication the unit i...
def get_dirty_items(item_list, flag_list): """ Returns each item in item_list where not flag in flag_list Args: item_list (list): flag_list (list): Returns: dirty_items """ assert len(item_list) == len(flag_list) dirty_items = [item for (item, flag) in ...
Returns each item in item_list where not flag in flag_list Args: item_list (list): flag_list (list): Returns: dirty_items
def function(self, rule, args, **kwargs): """ Callback method for rule tree traversing. Will be called at proper time from :py:class:`pynspect.rules.FunctionRule.traverse` method. :param pynspect.rules.Rule rule: Reference to rule. :param args: Optional function arguments. ...
Callback method for rule tree traversing. Will be called at proper time from :py:class:`pynspect.rules.FunctionRule.traverse` method. :param pynspect.rules.Rule rule: Reference to rule. :param args: Optional function arguments. :param dict kwargs: Optional callback arguments.
def detect_proc(): """Detect /proc filesystem style. This checks the /proc/{pid} directory for possible formats. Returns one of the followings as str: * `stat`: Linux-style, i.e. ``/proc/{pid}/stat``. * `status`: BSD-style, i.e. ``/proc/{pid}/status``. """ pid = os.getpid() for name in...
Detect /proc filesystem style. This checks the /proc/{pid} directory for possible formats. Returns one of the followings as str: * `stat`: Linux-style, i.e. ``/proc/{pid}/stat``. * `status`: BSD-style, i.e. ``/proc/{pid}/status``.
def block_pop_front(self, timeout=10): '''Remove the first element from of the list. If no elements are available, blocks for at least ``timeout`` seconds.''' value = yield self.backend_structure().block_pop_front(timeout) if value is not None: yield self.value_pickler.loads(val...
Remove the first element from of the list. If no elements are available, blocks for at least ``timeout`` seconds.
def get_stress(self, a): """Calculate stress tensor.""" s = np.zeros( 6, dtype=float ) for c in self.calcs: s += c.get_stress(a) return s
Calculate stress tensor.
def __extract_resources_from_droplets(self, data): """ Private method to extract from a value, the resources. It will check the type of object in the array provided and build the right structure for the API. """ resources = [] if not isinstance(data, l...
Private method to extract from a value, the resources. It will check the type of object in the array provided and build the right structure for the API.
def rget(obj, attrstr, default=None, delim='.'): # pragma: no cover """ Returns the value at the specified attrstr location within a nexted tree of dicts, lists, tuples, functions, classes, etc. The lookup is done recursivley for each key in attrstr (split by by the delimiter) This function is heav...
Returns the value at the specified attrstr location within a nexted tree of dicts, lists, tuples, functions, classes, etc. The lookup is done recursivley for each key in attrstr (split by by the delimiter) This function is heavily influenced by the lookups used in Django templates. Para...
def unwrap_or(self, optb: T) -> T: """ Returns the success value in the :class:`Result` or ``optb``. Args: optb: The default return value. Returns: The success value in the :class:`Result` if it is a :meth:`Result.Ok` value, otherwise ``optb``. ...
Returns the success value in the :class:`Result` or ``optb``. Args: optb: The default return value. Returns: The success value in the :class:`Result` if it is a :meth:`Result.Ok` value, otherwise ``optb``. Notes: If you wish to use a result of a...
def _refine_candidate(self, width, height): """ Use bottom-left packing algorithm to find a lower height for the container. Arguments: width height Returns: tuple (width, height, PackingAlgorithm): """ packer = newPacker(Pack...
Use bottom-left packing algorithm to find a lower height for the container. Arguments: width height Returns: tuple (width, height, PackingAlgorithm):
def _convert_label(label): """ Convert a label from 1.X to the new format """ style = qt_font_to_style(label.get("font"), label.get("color")) return { "text": html.escape(label["text"]), "rotation": 0, "style": style, "x": int(label["x"]), "y": int(label["y"])...
Convert a label from 1.X to the new format
def _create_ip_report(self): ''' this will take the obfuscated ip and hostname databases and output csv files ''' try: ip_report_name = os.path.join(self.report_dir, "%s-ip.csv" % self.session) self.logger.con_out('Creating IP Report - %s', ip_report_name) ...
this will take the obfuscated ip and hostname databases and output csv files
def clone(src, **kwargs): """Clones object with optionally overridden fields""" obj = object.__new__(type(src)) obj.__dict__.update(src.__dict__) obj.__dict__.update(kwargs) return obj
Clones object with optionally overridden fields
def llcs(s1, s2): '''length of the longest common sequence This implementation takes O(len(s1) * len(s2)) time and O(min(len(s1), len(s2))) space. Use only with short strings. >>> llcs('a.b.cd','!a!b!c!!!d!') 4 ''' m, n = len(s1), len(s2) if m < n: # ensure n <= m, to use O(min(n...
length of the longest common sequence This implementation takes O(len(s1) * len(s2)) time and O(min(len(s1), len(s2))) space. Use only with short strings. >>> llcs('a.b.cd','!a!b!c!!!d!') 4
def spkt_welch_density(x, param): """ This feature calculator estimates the cross power spectral density of the time series x at different frequencies. To do so, the time series is first shifted from the time domain to the frequency domain. The feature calculators returns the power spectrum of the diff...
This feature calculator estimates the cross power spectral density of the time series x at different frequencies. To do so, the time series is first shifted from the time domain to the frequency domain. The feature calculators returns the power spectrum of the different frequencies. :param x: the time ser...
def is_auth_alive(self): "Return true if the auth is not expired, else false" model = self.model('ir.model') try: model.search([], None, 1, None) except ClientError as err: if err and err.message['code'] == 403: return False raise ...
Return true if the auth is not expired, else false
def long_click(self, x, y): '''long click at arbitrary coordinates.''' return self.swipe(x, y, x + 1, y + 1)
long click at arbitrary coordinates.
def assertDateTimesPast(self, sequence, strict=True, msg=None): '''Fail if any elements in ``sequence`` are not in the past. If the max element is a datetime, "past" is defined as anything prior to ``datetime.now()``; if the max element is a date, "past" is defined as anything prior to ...
Fail if any elements in ``sequence`` are not in the past. If the max element is a datetime, "past" is defined as anything prior to ``datetime.now()``; if the max element is a date, "past" is defined as anything prior to ``date.today()``. If ``strict=True``, fail unless all elements in ...
def _generate_metadata(path, cookbook_path, name): """Checks whether metadata.rb has changed and regenerate metadata.json""" global knife_installed if not knife_installed: return metadata_path_rb = os.path.join(path, 'metadata.rb') metadata_path_json = os.path.join(path, 'metadata.json') ...
Checks whether metadata.rb has changed and regenerate metadata.json
def get_encoded_seq_len(self, seq_len: int) -> int: """ Returns the size of the encoded sequence. """ for encoder in self.encoders: seq_len = encoder.get_encoded_seq_len(seq_len) return seq_len
Returns the size of the encoded sequence.
def descriptor_factory(self, type_name, shard=u'lobby', **kwargs): """ Creates and returns a descriptor to pass it later for starting the agent. First parameter is a type_name representing the descirptor. Second parameter is optional (default lobby). Usage: > descriptor_f...
Creates and returns a descriptor to pass it later for starting the agent. First parameter is a type_name representing the descirptor. Second parameter is optional (default lobby). Usage: > descriptor_factory('shard_descriptor', 'some shard')
def T92(mu=1.0, pi_GC=0.5, kappa=0.1, **kwargs): """ Tamura 1992 model. Extending Kimura (1980) model for the case where a G+C-content bias exists. Link: Tamura K (1992), Mol. Biol. Evol. 9 (4): 678–687. DOI: 10.1093/oxfordjournals.molbev.a040752 Current implementation of the model does not acc...
Tamura 1992 model. Extending Kimura (1980) model for the case where a G+C-content bias exists. Link: Tamura K (1992), Mol. Biol. Evol. 9 (4): 678–687. DOI: 10.1093/oxfordjournals.molbev.a040752 Current implementation of the model does not account for the gaps Parameters ----------- mu : ...
def _datetime64_index(self, recarr): """ Given a np.recarray find the first datetime64 column """ # TODO: Handle multi-indexes names = recarr.dtype.names for name in names: if recarr[name].dtype == DTN64_DTYPE: return name return None
Given a np.recarray find the first datetime64 column
def safe_download(self): """Download a song respecting Grooveshark's API. :return: The raw song data. """ def _markStreamKeyOver30Seconds(stream): self._connection.request( 'markStreamKeyOver30Seconds', {'streamServerID': stream.ip, ...
Download a song respecting Grooveshark's API. :return: The raw song data.
def safe_filepath(file_path_name, dir_sep=None): ''' Input the full path and filename, splits on directory separator and calls safe_filename_leaf for each part of the path. dir_sep allows coder to force a directory separate to a particular character .. versionadded:: 2017.7.2 :codeauthor: Damon At...
Input the full path and filename, splits on directory separator and calls safe_filename_leaf for each part of the path. dir_sep allows coder to force a directory separate to a particular character .. versionadded:: 2017.7.2 :codeauthor: Damon Atkins <https://github.com/damon-atkins>
def add_parent(self, parent): """ Adds self as child of parent, then adds parent. """ parent.add_child(self) self.parent = parent return parent
Adds self as child of parent, then adds parent.
def G(self, singular_value): """get the parameter solution Matrix at a singular value V_1 * S_1^(_1) * U_1^T Parameters ---------- singular_value : int singular value to calc R at Returns ------- G : pyemu.Matrix parameter sol...
get the parameter solution Matrix at a singular value V_1 * S_1^(_1) * U_1^T Parameters ---------- singular_value : int singular value to calc R at Returns ------- G : pyemu.Matrix parameter solution matrix at singular value
def iter_rate(self): """ pun not intended # TODO: record iteration times for analysis # TODO Incorporate this better # FIXME; pad_stdout into subfunctions import dis dis.dis(ut.ProgressIter.iter_rate) """ #class IterState(object): # de...
pun not intended # TODO: record iteration times for analysis # TODO Incorporate this better # FIXME; pad_stdout into subfunctions import dis dis.dis(ut.ProgressIter.iter_rate)
def show_slice(data2d, contour2d=None, seeds2d=None): """ :param data2d: :param contour2d: :param seeds2d: :return: """ import copy as cp # Show results colormap = cp.copy(plt.cm.get_cmap('brg')) colormap._init() colormap._lut[:1:, 3] = 0 plt.imshow(da...
:param data2d: :param contour2d: :param seeds2d: :return:
def launch_topology_server(cl_args, topology_file, topology_defn_file, topology_name): ''' Launch a topology given topology jar, its definition file and configurations :param cl_args: :param topology_file: :param topology_defn_file: :param topology_name: :return: ''' service_apiurl = cl_args['service_...
Launch a topology given topology jar, its definition file and configurations :param cl_args: :param topology_file: :param topology_defn_file: :param topology_name: :return:
def write_function_bashscriptline(self, job): ''' Writes a function to create a bashscript for injection into the docker container. :param job_task_reference: The job referenced in WDL's Task section. :param job_alias: The actual job name to be written. :return: A string...
Writes a function to create a bashscript for injection into the docker container. :param job_task_reference: The job referenced in WDL's Task section. :param job_alias: The actual job name to be written. :return: A string writing all of this.
def __convert_enum(node): """Converts an EnumProperty node to JSON format.""" name = __get_attribute(node, 'Name') logging.debug('Found EnumProperty named %s', name) converted_values = [] for value in node.getElementsByTagName('EnumValue'): converted = __convert_node(value) conver...
Converts an EnumProperty node to JSON format.
def _who_when(self, s, cmd, section, accept_just_who=False): """Parse who and when information from a string. :return: a tuple of (name,email,timestamp,timezone). name may be the empty string if only an email address was given. """ match = _WHO_AND_WHEN_RE.search(s) ...
Parse who and when information from a string. :return: a tuple of (name,email,timestamp,timezone). name may be the empty string if only an email address was given.
def setup_remoteckan(self, remoteckan=None, **kwargs): # type: (Optional[ckanapi.RemoteCKAN], Any) -> None """ Set up remote CKAN from provided CKAN or by creating from configuration Args: remoteckan (Optional[ckanapi.RemoteCKAN]): CKAN instance. Defaults to setting one up f...
Set up remote CKAN from provided CKAN or by creating from configuration Args: remoteckan (Optional[ckanapi.RemoteCKAN]): CKAN instance. Defaults to setting one up from configuration. Returns: None
def __is_outside_of_builddir(project, path_to_check): """Check if a project lies outside of its expected directory.""" bdir = project.builddir cprefix = os.path.commonprefix([path_to_check, bdir]) return cprefix != bdir
Check if a project lies outside of its expected directory.
def get_route(self, name): '''Get a child :class:`Router` by its :attr:`name`. This method search child routes recursively. ''' for route in self.routes: if route.name == name: return route for child in self.routes: route = child.get_route...
Get a child :class:`Router` by its :attr:`name`. This method search child routes recursively.
def bvlci_contents(self, use_dict=None, as_class=dict): """Return the contents of an object as a dict.""" if _debug: BVLCI._debug("bvlci_contents use_dict=%r as_class=%r", use_dict, as_class) # make/extend the dictionary of content if use_dict is None: use_dict = as_class() ...
Return the contents of an object as a dict.
def tables(self): """Return the list of table names in the database""" tables = [] self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table'") for table_info in self.cursor.fetchall(): if table_info[0] != 'sqlite_sequence': tables.append(tab...
Return the list of table names in the database
def _wrap_callback_errors(callback, message): """Wraps a user callback so that if an exception occurs the message is nacked. Args: callback (Callable[None, Message]): The user callback. message (~Message): The Pub/Sub message. """ try: callback(message) except Exception:...
Wraps a user callback so that if an exception occurs the message is nacked. Args: callback (Callable[None, Message]): The user callback. message (~Message): The Pub/Sub message.
def get_ref(profile, ref): """Fetch a ref. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. ref The ref to fetc...
Fetch a ref. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. ref The ref to fetch, e.g., ``heads/my-feature-branch...
def progress(self, *msg): """ Prints a progress message """ label = colors.purple("Progress") self._msg(label, *msg)
Prints a progress message
def add_download_total(rows): """Add a final row to rows showing the total downloads""" total_row = [""] * len(rows[0]) total_row[0] = "Total" total_downloads, downloads_column = get_download_total(rows) total_row[downloads_column] = str(total_downloads) rows.append(total_row) return rows
Add a final row to rows showing the total downloads
def creation_time(self): """dfdatetime.DateTimeValues: creation time or None if not available.""" timestamp = self._fsntfs_file_entry.get_creation_time_as_integer() return dfdatetime_filetime.Filetime(timestamp=timestamp)
dfdatetime.DateTimeValues: creation time or None if not available.
def get_last_data(self, uuid, period=0, average_by=0): """ Get the data from one device for period till now. :param uuid: Id of the device :type uuid: str :param period: Number of seconds between start time of search and now :type period: integer :param average_b...
Get the data from one device for period till now. :param uuid: Id of the device :type uuid: str :param period: Number of seconds between start time of search and now :type period: integer :param average_by: amount of seconds to average data over. 0 or 300 for no aver...
def drop_prefix(strings): """ Removes common prefix from a collection of strings """ strings_without_extensions = [ s.split(".", 2)[0] for s in strings ] if len(strings_without_extensions) == 1: return [os.path.basename(strings_without_extensions[0])] prefix_len = len(os.pat...
Removes common prefix from a collection of strings
def t_INITIAL_comment(self, token): r'[#][^\n]*\n+' token.lexer.lineno += token.value.count('\n') # Scan backwards from the comment hash to figure out which type of # comment this is. If we find an non-ws character, we know it was a # partial line. But, if we find a newline befor...
r'[#][^\n]*\n+
def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: ...
Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0
def rename_keys_in_dict(d: Dict[str, Any], renames: Dict[str, str]) -> None: """ Renames, IN PLACE, the keys in ``d`` according to the mapping in ``renames``. Args: d: a dictionary to modify renames: a dictionary of the format ``{old_key_name: new_key_name}`` See h...
Renames, IN PLACE, the keys in ``d`` according to the mapping in ``renames``. Args: d: a dictionary to modify renames: a dictionary of the format ``{old_key_name: new_key_name}`` See https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary.
def __GetTypeInfo(self, attrs, name_hint): """Return a TypeInfo object for attrs, creating one if needed.""" type_ref = self.__names.ClassName(attrs.get('$ref')) type_name = attrs.get('type') if not (type_ref or type_name): raise ValueError('No type found for %s' % attrs) ...
Return a TypeInfo object for attrs, creating one if needed.
def _patched_run_hook(hook_name, project_dir, context): """Used to patch cookiecutter's ``run_hook`` function. This patched version ensures that the temple.yaml file is created before any cookiecutter hooks are executed """ if hook_name == 'post_gen_project': with temple.utils.cd(project_di...
Used to patch cookiecutter's ``run_hook`` function. This patched version ensures that the temple.yaml file is created before any cookiecutter hooks are executed
def reassign_assessment_part_to_bank(self, assessment_part_id, from_biank_id, to_bank_id): """Moves an ``AssessmentPart`` from one ``Bank`` to another. Mappings to other ``Banks`` are unaffected. arg: assessment_part_id (osid.id.Id): the ``Id`` of the ``AssessmentPart`` ...
Moves an ``AssessmentPart`` from one ``Bank`` to another. Mappings to other ``Banks`` are unaffected. arg: assessment_part_id (osid.id.Id): the ``Id`` of the ``AssessmentPart`` arg: from_biank_id (osid.id.Id): the ``Id`` of the current ``Bank`` arg...