positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def _translate_cond(self, c): #pylint:disable=no-self-use """ Checks whether this condition can be supported by FastMemory." """ if isinstance(c, claripy.ast.Base) and not c.singlevalued: raise SimFastMemoryError("size not supported") if c is None: return ...
Checks whether this condition can be supported by FastMemory."
def p_iteration_statement_6(self, p): """ iteration_statement \ : FOR LPAREN VAR identifier initializer_noin IN expr RPAREN statement """ p[0] = ast.ForIn(item=ast.VarDecl(identifier=p[4], initializer=p[5]), iterable=p[7], statement=p[9])
iteration_statement \ : FOR LPAREN VAR identifier initializer_noin IN expr RPAREN statement
def list_event_sources(self): """ Returns the existing event sources. :rtype: ~collections.Iterable[str] """ # Server does not do pagination on listings of this resource. # Return an iterator anyway for similarity with other API methods path = '/archive/{}/events...
Returns the existing event sources. :rtype: ~collections.Iterable[str]
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): """Operation: Add Permission to User Role.""" assert wait_for_completion is True # synchronous operation user_role_oid = uri_parms[0] user_role_uri = '/api/user-roles/' + user_role_oid ...
Operation: Add Permission to User Role.
def documento(self, *args, **kwargs): """Resulta no documento XML como string, que pode ou não incluir a declaração XML no início do documento. """ forcar_unicode = kwargs.pop('forcar_unicode', False) incluir_xml_decl = kwargs.pop('incluir_xml_decl', True) doc = ET.tostri...
Resulta no documento XML como string, que pode ou não incluir a declaração XML no início do documento.
def refresh(self): """Return a deferred.""" d = self.request('get', self.instance_url()) return d.addCallback(self.refresh_from).addCallback(lambda _: self)
Return a deferred.
def estimate_hmm(observations, nstates, lag=1, initial_model=None, output=None, reversible=True, stationary=False, p=None, accuracy=1e-3, maxit=1000, maxit_P=100000, mincount_connectivity=1e-2): r""" Estimate maximum-likelihood HMM Generic maximum-likelihood estimation of HMMs...
r""" Estimate maximum-likelihood HMM Generic maximum-likelihood estimation of HMMs Parameters ---------- observations : list of numpy arrays representing temporal data `observations[i]` is a 1d numpy array corresponding to the observed trajectory index `i` nstates : int The number ...
def prepend_string_list(self, key, value, max_length_key): """Prepend a fixed-length string list with a new string. The oldest string will be removed from the list. If the string is already in the list, it is shuffled to the top. Use this to implement things like a 'most recent files' e...
Prepend a fixed-length string list with a new string. The oldest string will be removed from the list. If the string is already in the list, it is shuffled to the top. Use this to implement things like a 'most recent files' entry.
def player_stats(game_id): """Return dictionary of individual stats of a game with matching id. The additional pitching/batting is mostly the same stats, except it contains some useful stats such as groundouts/flyouts per pitcher (go/ao). MLB decided to have two box score files, thus we return...
Return dictionary of individual stats of a game with matching id. The additional pitching/batting is mostly the same stats, except it contains some useful stats such as groundouts/flyouts per pitcher (go/ao). MLB decided to have two box score files, thus we return the data from both.
def delete(self): """ Destructor. """ if self.glucose: pysolvers.glucose3_del(self.glucose) self.glucose = None if self.prfile: self.prfile.close()
Destructor.
def load_virt_stream(virt_fd): """ Loads the given conf stream into a dict, trying different formats if needed Args: virt_fd (str): file like objcect with the virt config to load Returns: dict: Loaded virt config """ try: virt_conf = json.load(virt_fd) except Va...
Loads the given conf stream into a dict, trying different formats if needed Args: virt_fd (str): file like objcect with the virt config to load Returns: dict: Loaded virt config
def s_l(l, alpha): """ get sigma as a function of degree l from Constable and Parker (1988) """ a2 = alpha**2 c_a = 0.547 s_l = np.sqrt(old_div(((c_a**(2. * l)) * a2), ((l + 1.) * (2. * l + 1.)))) return s_l
get sigma as a function of degree l from Constable and Parker (1988)
def getPharLapPath(): """Reads the registry to find the installed path of the Phar Lap ETS development kit. Raises UserError if no installed version of Phar Lap can be found.""" if not SCons.Util.can_read_reg: raise SCons.Errors.InternalError("No Windows registry module was found") try...
Reads the registry to find the installed path of the Phar Lap ETS development kit. Raises UserError if no installed version of Phar Lap can be found.
def return_dat(self, chan, begsam, endsam): """Return the data as 2D numpy.ndarray. Parameters ---------- chan : int or list index (indices) of the channels to read begsam : int index of the first sample endsam : int index of the last ...
Return the data as 2D numpy.ndarray. Parameters ---------- chan : int or list index (indices) of the channels to read begsam : int index of the first sample endsam : int index of the last sample Returns ------- numpy.n...
def _upsample(self, method, limit=None, fill_value=None): """ Parameters ---------- method : string {'backfill', 'bfill', 'pad', 'ffill', 'asfreq'} method for upsampling limit : int, default None Maximum size gap to fill when reindexing fill_value ...
Parameters ---------- method : string {'backfill', 'bfill', 'pad', 'ffill', 'asfreq'} method for upsampling limit : int, default None Maximum size gap to fill when reindexing fill_value : scalar, default None Value to use for missing values Se...
def list_of_objects_from_api(url): ''' API only serves 20 pages by default This fetches info on all of items and return them as a list Assumption: limit of API is not less than 20 ''' response = requests.get(url) content = json.loads(response.content) count = content["meta"]["total_cou...
API only serves 20 pages by default This fetches info on all of items and return them as a list Assumption: limit of API is not less than 20
def stop(self): """Stops all session activity. Blocks until io and writer thread dies """ if self._io_thread is not None: self.log.info("Waiting for I/O thread to stop...") self.closed = True self._io_thread.join() if self._writer_thread is n...
Stops all session activity. Blocks until io and writer thread dies
def get_asset_admin_session_for_repository(self, repository_id=None, proxy=None): """Gets an asset administration session for the given repository. arg: repository_id (osid.id.Id): the ``Id`` of the repository arg: proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetAd...
Gets an asset administration session for the given repository. arg: repository_id (osid.id.Id): the ``Id`` of the repository arg: proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetAdminSession) - an ``AssetAdminSession`` raise: NotFound - ``repositor...
def standardUncertainties(self, sharpness=0.5): ''' sharpness -> image sharpness // std of Gaussian PSF [px] returns a list of standard uncertainties for the x and y component: (1x,2x), (1y, 2y), (intensity:None) 1. px-size-changes(due to deflection) 2. reprojecti...
sharpness -> image sharpness // std of Gaussian PSF [px] returns a list of standard uncertainties for the x and y component: (1x,2x), (1y, 2y), (intensity:None) 1. px-size-changes(due to deflection) 2. reprojection error
def translate(script): '''translate zipline script into pylivetrader script. ''' tree = ast.parse(script) ZiplineImportVisitor().visit(tree) return astor.to_source(tree)
translate zipline script into pylivetrader script.
def load_from_rdf_file(self, rdf_file): """Initialize given an RDF input file representing the hierarchy." Parameters ---------- rdf_file : str Path to an RDF file. """ self.graph = rdflib.Graph() self.graph.parse(os.path.abspath(rdf_file), format='nt...
Initialize given an RDF input file representing the hierarchy." Parameters ---------- rdf_file : str Path to an RDF file.
def is_valid_url(value): """Check if given value is a valid URL string. :param value: a value to test :returns: True if the value is valid """ match = URL_REGEX.match(value) host_str = urlparse(value).hostname return match and is_valid_host(host_str)
Check if given value is a valid URL string. :param value: a value to test :returns: True if the value is valid
async def execute_insert( self, sql: str, parameters: Iterable[Any] = None ) -> Optional[sqlite3.Row]: """Helper to insert and get the last_insert_rowid.""" if parameters is None: parameters = [] return await self._execute(self._execute_insert, sql, parameters)
Helper to insert and get the last_insert_rowid.
def _get_group_no(self, tag_name): """ Takes tag name and returns the number of the group to which tag belongs """ if tag_name in self.full: return self.groups.index(self.full[tag_name]["parent"]) else: return len(self.groups)
Takes tag name and returns the number of the group to which tag belongs
def parse(self, argument): """See base class.""" if isinstance(argument, list): return argument elif not argument: return [] else: return [s.strip() for s in argument.split(self._token)]
See base class.
def deactivate_object(brain_or_object): """Deactivate the given object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Nothing :rtype: None """ obj = get_object(brain_or_object) # we do not...
Deactivate the given object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Nothing :rtype: None
def energies(self, samples_like, dtype=np.float): """Determine the energies of the given samples. Args: samples_like (samples_like): A collection of raw samples. `samples_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. ...
Determine the energies of the given samples. Args: samples_like (samples_like): A collection of raw samples. `samples_like` is an extension of NumPy's array_like structure. See :func:`.as_samples`. dtype (:class:`numpy.dtype`): The data t...
def sendCode(self, mobile, templateId, region, verifyId=None, verifyCode=None): """ 发送短信验证码方法。 方法 @param mobile:接收短信验证码的目标手机号,每分钟同一手机号只能发送一次短信验证码,同一手机号 1 小时内最多发送 3 次。(必传) @param templateId:短信模板 Id,在开发者...
发送短信验证码方法。 方法 @param mobile:接收短信验证码的目标手机号,每分钟同一手机号只能发送一次短信验证码,同一手机号 1 小时内最多发送 3 次。(必传) @param templateId:短信模板 Id,在开发者后台->短信服务->服务设置->短信模版中获取。(必传) @param region:手机号码所属国家区号,目前只支持中图区号 86) @param verifyId:图片验证标识 Id ,开启图片验证功能后此参数必传,否则可以不传。在获取图片验证码方法返回值中获取。 @param verifyCode:图片验证码...
def get(self, name): """ Get the resource URI for a specified resource name. If an entry for the specified resource name does not exist in the Name-URI cache, the cache is refreshed from the HMC with all resources of the manager holding this cache. If an entry for the s...
Get the resource URI for a specified resource name. If an entry for the specified resource name does not exist in the Name-URI cache, the cache is refreshed from the HMC with all resources of the manager holding this cache. If an entry for the specified resource name still does not exi...
def get_render_configurations(self, request, **kwargs): """Render image interface""" data = self.process_form_data(self._get_form_defaults(), kwargs) variable_set = self.get_variable_set(self.service.variable_set.order_by('index'), data) base_config = ImageConfiguration( ex...
Render image interface
def is_equal(self, other_consonnant): """ >>> v_consonant = Consonant(Place.labio_dental, Manner.fricative, True, "v", False) >>> f_consonant = Consonant(Place.labio_dental, Manner.fricative, False, "f", False) >>> v_consonant.is_equal(f_consonant) False :param other_con...
>>> v_consonant = Consonant(Place.labio_dental, Manner.fricative, True, "v", False) >>> f_consonant = Consonant(Place.labio_dental, Manner.fricative, False, "f", False) >>> v_consonant.is_equal(f_consonant) False :param other_consonnant: :return:
def potential_purviews(self, direction, mechanism, purviews=False): """Override Subsystem implementation using Network-level indices.""" all_purviews = utils.powerset(self.node_indices) return irreducible_purviews( self.cm, direction, mechanism, all_purviews)
Override Subsystem implementation using Network-level indices.
def json_paginate(self, base_url, page_number): """ Return a dict for a JSON paginate """ data = self.page(page_number) first_id = None last_id = None if data: first_id = data[0].id last_id = data[-1].id return { 'meta': { ...
Return a dict for a JSON paginate
def to(self, space): """ Convert color to a different color space. :param str space: Name of the color space. :rtype: Color :returns: A new spectra.Color in the given color space. """ if space == self.space: return self new_color = convert_color(self.col...
Convert color to a different color space. :param str space: Name of the color space. :rtype: Color :returns: A new spectra.Color in the given color space.
def update(self, id, newObj): """Update a object Args: id (int): Target Object ID newObj (object): New object will be merged into original object Returns: Object: Updated object None: If specified object id is not found ...
Update a object Args: id (int): Target Object ID newObj (object): New object will be merged into original object Returns: Object: Updated object None: If specified object id is not found MultipleInvalid: If input obj...
def _calculateCoverageMasks(proteindb, peptidedb): """Calcualte the sequence coverage masks for all proteindb elements. Private method used by :class:`ProteinDatabase`. A coverage mask is a numpy boolean array with the length of the protein sequence. Each protein position that has been ...
Calcualte the sequence coverage masks for all proteindb elements. Private method used by :class:`ProteinDatabase`. A coverage mask is a numpy boolean array with the length of the protein sequence. Each protein position that has been covered in at least one peptide is set to True. Covera...
def threshold_monitor_hidden_threshold_monitor_Memory_retry(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor") threshold_mon...
Auto Generated Code
def delete_node_1ton(node_list, begin, node, end): # type: ([],LinkedNode, LinkedNode, LinkedNode)->[] """ delete the node which has 1-input and n-output """ if end is None: assert end is not None end = node.successor elif not isinstance(end, list): ...
delete the node which has 1-input and n-output
def create_basic_url(self): """ Create URL prefix for API calls based on type of repo. Repo may be forked and may be in namespace. That makes total 4 different types of URL. :return: """ if self.username is None: if self.namespace is None: re...
Create URL prefix for API calls based on type of repo. Repo may be forked and may be in namespace. That makes total 4 different types of URL. :return:
def make_c_header(name, front, body): """ Build a C header from the front and body. """ return """ {0} # ifndef _GU_ZHENGXIONG_{1}_H # define _GU_ZHENGXIONG_{1}_H {2} # endif /* {3}.h */ """.strip().format(front, name.upper(), body, name) + '\n'
Build a C header from the front and body.
def setTabText(self, index, text): """ Returns the text for the tab at the inputed index. :param index | <int> :return <str> """ try: self.items()[index].setText(text) except IndexError: pass
Returns the text for the tab at the inputed index. :param index | <int> :return <str>
def __get_pending_revisions(self): """ Get all the pending revisions after the current time :return: A list of revisions :rtype: list """ dttime = time.mktime(datetime.datetime.now().timetuple()) changes = yield self.revisions.find({ "toa" : { ...
Get all the pending revisions after the current time :return: A list of revisions :rtype: list
def status(self): """ One of C{STARTED_STATUS}, C{SUCCEEDED_STATUS}, C{FAILED_STATUS} or C{None}. """ message = self.end_message if self.end_message else self.start_message if message: return message.contents[ACTION_STATUS_FIELD] else: retu...
One of C{STARTED_STATUS}, C{SUCCEEDED_STATUS}, C{FAILED_STATUS} or C{None}.
def with_vtk(plot=True): """ Tests VTK interface and mesh repair of Stanford Bunny Mesh """ mesh = vtki.PolyData(bunny_scan) meshfix = pymeshfix.MeshFix(mesh) if plot: print('Plotting input mesh') meshfix.plot() meshfix.repair() if plot: print('Plotting repaired mesh') ...
Tests VTK interface and mesh repair of Stanford Bunny Mesh
def setrange(self, min, max): """Set the dataset min and max values. Args:: min dataset minimum value (attribute 'valid_range') max dataset maximum value (attribute 'valid_range') Returns:: None The data range is part of the so-called "st...
Set the dataset min and max values. Args:: min dataset minimum value (attribute 'valid_range') max dataset maximum value (attribute 'valid_range') Returns:: None The data range is part of the so-called "standard" SDS attributes. Calling m...
def _get_link(self, cobj): """Get a valid link, False if not found""" fullname = cobj['module_short'] + '.' + cobj['name'] try: value = self._searchindex['objects'][cobj['module_short']] match = value[cobj['name']] except KeyError: link = False ...
Get a valid link, False if not found
def site_occupation_statistics( self ): """ Average site occupation for each site type Args: None Returns: (Dict(Str:Float)): Dictionary of occupation statistics, e.g.:: { 'A' : 2.5, 'B' : 25.3 } """ if self.time == 0.0: ...
Average site occupation for each site type Args: None Returns: (Dict(Str:Float)): Dictionary of occupation statistics, e.g.:: { 'A' : 2.5, 'B' : 25.3 }
def raw(self) -> str: """ Return a raw format string of the Peer document :return: """ doc = """Version: {0} Type: Peer Currency: {1} PublicKey: {2} Block: {3} Endpoints: """.format(self.version, self.currency, self.pubkey, self.blockUID) for _endpoint in self.endpoints...
Return a raw format string of the Peer document :return:
def checktext(sometext, interchange = ALL): """ Checks that some text is palindrome. Checking performs case-insensitive :param str sometext: It is some string that will be checked for palindrome as text. What is the text see at help(palindromus.istext) The text can be multiline. ...
Checks that some text is palindrome. Checking performs case-insensitive :param str sometext: It is some string that will be checked for palindrome as text. What is the text see at help(palindromus.istext) The text can be multiline. :keyword dict interchange: It is dictionary o...
def widont(value, count=1): """ Add an HTML non-breaking space between the final two words of the string to avoid "widowed" words. Examples: >>> print(widont('Test me out')) Test me&nbsp;out >>> print("'",widont('It works with trailing spaces too '), "'") ' It works with traili...
Add an HTML non-breaking space between the final two words of the string to avoid "widowed" words. Examples: >>> print(widont('Test me out')) Test me&nbsp;out >>> print("'",widont('It works with trailing spaces too '), "'") ' It works with trailing spaces&nbsp;too ' >>> print(wi...
def canonical_request(self): """ The AWS SigV4 canonical request given parameters from an HTTP request. This process is outlined here: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html The canonical request is: request_method + '\n' + ...
The AWS SigV4 canonical request given parameters from an HTTP request. This process is outlined here: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html The canonical request is: request_method + '\n' + canonical_uri_path + '\n' + ...
def _resolve_group_location(self, group: str) -> str: """ Resolves the location of a setting file based on the given identifier. :param group: the identifier for the group's settings file (~its location) :return: the absolute path of the settings location """ if os.path.i...
Resolves the location of a setting file based on the given identifier. :param group: the identifier for the group's settings file (~its location) :return: the absolute path of the settings location
def io_size_kb(prev, curr, counters): """ calculate the io size based on bandwidth and throughput formula: average_io_size = bandwidth / throughput :param prev: prev resource, not used :param curr: current resource :param counters: two stats, bandwidth in MB and throughput count :return: value,...
calculate the io size based on bandwidth and throughput formula: average_io_size = bandwidth / throughput :param prev: prev resource, not used :param curr: current resource :param counters: two stats, bandwidth in MB and throughput count :return: value, NaN if invalid
def parse_from_environ(self, environ): """Parses the information from the environment as form data. :param environ: the WSGI environment to be used for parsing. :return: A tuple in the form ``(stream, form, files)``. """ content_type = environ.get("CONTENT_TYPE", "") con...
Parses the information from the environment as form data. :param environ: the WSGI environment to be used for parsing. :return: A tuple in the form ``(stream, form, files)``.
def start_tree(self, tree, filename): """Some fixers need to maintain tree-wide state. This method is called once, at the start of tree fix-up. tree - the root node of the tree to be processed. filename - the name of the file the tree came from. """ self.used_names = tre...
Some fixers need to maintain tree-wide state. This method is called once, at the start of tree fix-up. tree - the root node of the tree to be processed. filename - the name of the file the tree came from.
def from_jd(jd): '''Calculate Mayan long count from Julian day''' d = jd - EPOCH baktun = trunc(d / 144000) d = (d % 144000) katun = trunc(d / 7200) d = (d % 7200) tun = trunc(d / 360) d = (d % 360) uinal = trunc(d / 20) kin = int((d % 20)) return (baktun, katun, tun, uinal,...
Calculate Mayan long count from Julian day
def strip_head(sequence, values): """Strips elements of `values` from the beginning of `sequence`.""" values = set(values) return list(itertools.dropwhile(lambda x: x in values, sequence))
Strips elements of `values` from the beginning of `sequence`.
def batch_iterable(l, n): ''' Chunks iterable into n sized batches Solution from: http://stackoverflow.com/questions/1915170/split-a-generator-iterable-every-n-items-in-python-splitevery''' i = iter(l) piece = list(islice(i, n)) while piece: yield piece piece = list(islice(i, n))
Chunks iterable into n sized batches Solution from: http://stackoverflow.com/questions/1915170/split-a-generator-iterable-every-n-items-in-python-splitevery
def search_info(self, search_index): """ Retrieves information about a specified search index within the design document, returns dictionary GET databasename/_design/{ddoc}/_search_info/{search_index} """ ddoc_search_info = self.r_session.get( '/'.join([self....
Retrieves information about a specified search index within the design document, returns dictionary GET databasename/_design/{ddoc}/_search_info/{search_index}
def auth(name, nodes, pcsuser='hacluster', pcspasswd='hacluster', extra_args=None): ''' Ensure all nodes are authorized to the cluster name Irrelevant, not used (recommended: pcs_auth__auth) nodes a list of nodes which should be authorized to the cluster pcsuser user for com...
Ensure all nodes are authorized to the cluster name Irrelevant, not used (recommended: pcs_auth__auth) nodes a list of nodes which should be authorized to the cluster pcsuser user for communication with pcs (default: hacluster) pcspasswd password for pcsuser (default: ha...
def sample(self, cursor): """Extract records randomly from the database. Continue until the target proportion of the items have been extracted, or until `min_items` if this is larger. If `max_items` is non-negative, do not extract more than these. This function is a generator, y...
Extract records randomly from the database. Continue until the target proportion of the items have been extracted, or until `min_items` if this is larger. If `max_items` is non-negative, do not extract more than these. This function is a generator, yielding items incrementally. ...
def calcgain(self, ant1, ant2, skyfreq, pol): """ Calculates the complex gain product (g1*g2) for a pair of antennas. """ select = self.select[n.where( (self.skyfreq[self.select] == skyfreq) & (self.polarization[self.select] == pol) )[0]] if len(select): # for when telcal solutions do...
Calculates the complex gain product (g1*g2) for a pair of antennas.
def items(self, *keys): """ Return the fields of the record as a list of key and value tuples :return: """ if keys: d = [] for key in keys: try: i = self.index(key) except KeyError: d.append(...
Return the fields of the record as a list of key and value tuples :return:
def listar_por_tipo_ambiente(self, id_tipo_equipamento, id_ambiente): """Lista os equipamentos de um tipo e que estão associados a um ambiente. :param id_tipo_equipamento: Identificador do tipo do equipamento. :param id_ambiente: Identificador do ambiente. :return: Dicionário com a seg...
Lista os equipamentos de um tipo e que estão associados a um ambiente. :param id_tipo_equipamento: Identificador do tipo do equipamento. :param id_ambiente: Identificador do ambiente. :return: Dicionário com a seguinte estrutura: :: {'equipamento': [{'id': < id_equipament...
def get(self, request): '''The home page of this router''' ul = Html('ul') for router in sorted(self.routes, key=lambda r: r.creation_count): a = router.link(escape(router.route.path)) a.addClass(router.name) for method in METHODS: if router.ge...
The home page of this router
def wrapper__ignore(self, type_): """ Selectively ignore certain types when wrapping attributes. :param class type: The class/type definition to ignore. :rtype list(type): The current list of ignored types """ if type_ not in self.__exclusion_list: self.__ex...
Selectively ignore certain types when wrapping attributes. :param class type: The class/type definition to ignore. :rtype list(type): The current list of ignored types
def get_filepaths_with_extension(extname, root_dir='.'): """Get relative filepaths of files in a directory, and sub-directories, with the given extension. Parameters ---------- extname : `str` Extension name (e.g. 'txt', 'rst'). Extension comparison is case-insensitive. root_dir...
Get relative filepaths of files in a directory, and sub-directories, with the given extension. Parameters ---------- extname : `str` Extension name (e.g. 'txt', 'rst'). Extension comparison is case-insensitive. root_dir : `str`, optional Root directory. Current working direc...
def calculate_time_difference(startDate, endDate): """ *Return the time difference between two dates as a string* **Key Arguments:** - ``startDate`` -- the first date in YYYY-MM-DDTHH:MM:SS format - ``endDate`` -- the final date YYYY-MM-DDTHH:MM:SS format **Return:** - ``relTim...
*Return the time difference between two dates as a string* **Key Arguments:** - ``startDate`` -- the first date in YYYY-MM-DDTHH:MM:SS format - ``endDate`` -- the final date YYYY-MM-DDTHH:MM:SS format **Return:** - ``relTime`` -- the difference between the two dates in Y,M,D,h,m,s (str...
def urlsplit(name): """ Parse :param:`name` into (netloc, port, ssl) """ if not (isinstance(name, string_types)): name = str(name) if not name.startswith(('http://', 'https://')): name = 'http://' + name rv = urlparse(name) if rv.scheme == 'https' and rv.port is None: ...
Parse :param:`name` into (netloc, port, ssl)
def post_revert_tags(self, post_id, history_id): """Function to reverts a post to a previous set of tags (Requires login) (UNTESTED). Parameters: post_id (int): The post id number to update. history_id (int): The id number of the tag history. """ params =...
Function to reverts a post to a previous set of tags (Requires login) (UNTESTED). Parameters: post_id (int): The post id number to update. history_id (int): The id number of the tag history.
def calculate_solidity(labels,indexes=None): """Calculate the area of each label divided by the area of its convex hull labels - a label matrix indexes - the indexes of the labels to measure """ if indexes is not None: """ Convert to compat 32bit integer """ indexes = np.array(i...
Calculate the area of each label divided by the area of its convex hull labels - a label matrix indexes - the indexes of the labels to measure
def generate_branches(scales=None, angles=None, shift_angle=0): """Generates branches with alternative system. Args: scales (tuple/array): Indicating how the branch/es length/es develop/s from age to age. angles (tuple/array): Holding the branch and shift angle in radians. shift_angle (...
Generates branches with alternative system. Args: scales (tuple/array): Indicating how the branch/es length/es develop/s from age to age. angles (tuple/array): Holding the branch and shift angle in radians. shift_angle (float): Holding the rotation angle for all branches. Returns: ...
def _index_fs(self): """Returns a deque object full of local file system items. :returns: ``deque`` """ indexed_objects = self._return_deque() directory = self.job_args.get('directory') if directory: indexed_objects = self._return_deque( deq...
Returns a deque object full of local file system items. :returns: ``deque``
def _departure(self) -> datetime: """Extract departure time.""" departure_time = datetime.strptime( self.journey.MainStop.BasicStop.Dep.Time.text, "%H:%M" ).time() if departure_time > (self.now - timedelta(hours=1)).time(): return datetime.combine(self.now.date(),...
Extract departure time.
def directionaldiff(f, x0, vec, **options): """ Return directional derivative of a function of n variables Parameters ---------- fun: callable analytical function to differentiate. x0: array vector location at which to differentiate fun. If x0 is an nxm array, then fun i...
Return directional derivative of a function of n variables Parameters ---------- fun: callable analytical function to differentiate. x0: array vector location at which to differentiate fun. If x0 is an nxm array, then fun is assumed to be a function of n*m variables. vec: ar...
def get_aggregation_propensity(self, seq, outdir, cutoff_v=5, cutoff_n=5, run_amylmuts=False): """Run the AMYLPRED2 web server for a protein sequence and get the consensus result for aggregation propensity. Args: seq (str, Seq, SeqRecord): Amino acid sequence outdir (str): Direc...
Run the AMYLPRED2 web server for a protein sequence and get the consensus result for aggregation propensity. Args: seq (str, Seq, SeqRecord): Amino acid sequence outdir (str): Directory to where output files should be saved cutoff_v (int): The minimal number of methods that ...
def hsv_2_hex(self, h, s, v): """ convert a hsv color to hex """ return self.rgb_2_hex(*hsv_to_rgb(h, s, v))
convert a hsv color to hex
def get_min_distance(self, mesh): """ For each point in ``mesh`` compute the minimum distance to each surface element and return the smallest value. See :meth:`superclass method <.base.BaseSurface.get_min_distance>` for spec of input and result values. """ ...
For each point in ``mesh`` compute the minimum distance to each surface element and return the smallest value. See :meth:`superclass method <.base.BaseSurface.get_min_distance>` for spec of input and result values.
def set_relay(self, relay_pin=0, state=True): '''Set relay_pin to value of state''' if self.mavlink10(): self.mav.command_long_send( self.target_system, # target_system self.target_component, # target_component mavlink.MAV_CMD_DO_SET_RELAY, # ...
Set relay_pin to value of state
def rmdir(self, directory, missing_okay=False): """Forcefully remove the specified directory and all its children.""" # Build a script to walk an entire directory structure and delete every # file and subfolder. This is tricky because MicroPython has no os.walk # or similar function to ...
Forcefully remove the specified directory and all its children.
def land(self, velocity=VELOCITY): """ Go straight down and turn off the motors. Do not call this function if you use the with keyword. Landing is done automatically when the context goes out of scope. :param velocity: The velocity (meters/second) when going down :retur...
Go straight down and turn off the motors. Do not call this function if you use the with keyword. Landing is done automatically when the context goes out of scope. :param velocity: The velocity (meters/second) when going down :return:
def build_interfaces_by_method(interfaces): """ Create new dictionary from INTERFACES hashed by method then the endpoints name. For use when using the disqusapi by the method interface instead of the endpoint interface. For instance: 'blacklists': { 'add': { 'formats': ['jso...
Create new dictionary from INTERFACES hashed by method then the endpoints name. For use when using the disqusapi by the method interface instead of the endpoint interface. For instance: 'blacklists': { 'add': { 'formats': ['json', 'jsonp'], 'method': 'POST', ...
def dfTObedtool(df): """ Transforms a pandas dataframe into a bedtool :param df: Pandas dataframe :returns: a bedtool """ df=df.astype(str) df=df.drop_duplicates() df=df.values.tolist() df=["\t".join(s) for s in df ] df="\n".join(df) df=BedTool(df, from_string=True) re...
Transforms a pandas dataframe into a bedtool :param df: Pandas dataframe :returns: a bedtool
def to_sql(self, frame, name, if_exists='fail', index=True, index_label=None, schema=None, chunksize=None, dtype=None, method=None): """ Write records stored in a DataFrame to a SQL database. Parameters ---------- frame : DataFrame name : st...
Write records stored in a DataFrame to a SQL database. Parameters ---------- frame : DataFrame name : string Name of SQL table. if_exists : {'fail', 'replace', 'append'}, default 'fail' - fail: If table exists, do nothing. - replace: If table ...
def _get_utxos(self, address, services, **modes): """ Using the service fallback engine, get utxos from remote service. """ return get_unspent_outputs( self.crypto, address, services=services, **modes )
Using the service fallback engine, get utxos from remote service.
def _get_options(self, style): """Get the list of keywords for a particular style :param style: the style that the keywords are wanted """ return [self.opt[o][style]['name'] for o in self.opt]
Get the list of keywords for a particular style :param style: the style that the keywords are wanted
def save(self, filename, format_='fasta'): """ Write the reads to C{filename} in the requested format. @param filename: Either a C{str} file name to save into (the file will be overwritten) or an open file descriptor (e.g., sys.stdout). @param format_: A C{str} format to sav...
Write the reads to C{filename} in the requested format. @param filename: Either a C{str} file name to save into (the file will be overwritten) or an open file descriptor (e.g., sys.stdout). @param format_: A C{str} format to save as, either 'fasta', 'fastq' or 'fasta-ss'. ...
def send_email_with_callback_token(user, email_token, **kwargs): """ Sends a Email to user.email. Passes silently without sending in test environment """ try: if api_settings.PASSWORDLESS_EMAIL_NOREPLY_ADDRESS: # Make sure we have a sending address before sending. ...
Sends a Email to user.email. Passes silently without sending in test environment
def get_line(cls, parent, current_line, line_count): """ Gets user selected line. :param parent: Parent widget :param current_line: Current line number :param line_count: Number of lines in the current text document. :returns: tuple(line, status) status is False if the ...
Gets user selected line. :param parent: Parent widget :param current_line: Current line number :param line_count: Number of lines in the current text document. :returns: tuple(line, status) status is False if the dialog has been rejected.
def homoscedasticity(*args, alpha=.05): """Test equality of variance. Parameters ---------- sample1, sample2,... : array_like Array of sample data. May be different lengths. Returns ------- equal_var : boolean True if data have equal variance. p : float P-value....
Test equality of variance. Parameters ---------- sample1, sample2,... : array_like Array of sample data. May be different lengths. Returns ------- equal_var : boolean True if data have equal variance. p : float P-value. See Also -------- normality : Tes...
def make_choices(*args): """Convert a 1-D sequence into a 2-D sequence of tuples for use in a Django field choices attribute >>> make_choices(range(3)) ((0, u'0'), (1, u'1'), (2, u'2')) >>> make_choices(dict(enumerate('abcd'))) ((0, u'a'), (1, u'b'), (2, u'c'), (3, u'd')) >>> make_choices('hell...
Convert a 1-D sequence into a 2-D sequence of tuples for use in a Django field choices attribute >>> make_choices(range(3)) ((0, u'0'), (1, u'1'), (2, u'2')) >>> make_choices(dict(enumerate('abcd'))) ((0, u'a'), (1, u'b'), (2, u'c'), (3, u'd')) >>> make_choices('hello') (('hello', u'hello'),) ...
def internal_only(view_func): """ A view decorator which blocks access for requests coming through the load balancer. """ @functools.wraps(view_func) def wrapper(request, *args, **kwargs): forwards = request.META.get("HTTP_X_FORWARDED_FOR", "").split(",") # The nginx in the docker c...
A view decorator which blocks access for requests coming through the load balancer.
def check_array(array, accept_sparse=None, dtype="numeric", order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False, ensure_min_samples=1, ensure_min_features=1, warn_on_dtype=False): """Input validation on an array, list, sparse matrix or simila...
Input validation on an array, list, sparse matrix or similar. By default, the input is converted to an at least 2nd numpy array. If the dtype of the array is object, attempt converting to float, raising on failure. Parameters ---------- array : object Input object to check / convert. ...
def word_tokenize(text, stopwords=_stopwords, ngrams=None, min_length=0, ignore_numeric=True): """ Parses the given text and yields tokens which represent words within the given text. Tokens are assumed to be divided by any form of whitespace character. """ if ngrams is None: ngrams = 1 ...
Parses the given text and yields tokens which represent words within the given text. Tokens are assumed to be divided by any form of whitespace character.
def util_granulate_time_series(time_series, scale): """Extract coarse-grained time series Args: time_series: Time series scale: Scale factor Returns: Vector of coarse-grained time series with given scale factor """ n = len(time_series) b = int(np.fix(n / scale)) tem...
Extract coarse-grained time series Args: time_series: Time series scale: Scale factor Returns: Vector of coarse-grained time series with given scale factor
def _integrate(cls, fn, emin, emax, params, scale=1.0, extra_params=None, npt=20): """Fast numerical integration method using mid-point rule.""" emin = np.expand_dims(emin, -1) emax = np.expand_dims(emax, -1) params = copy.deepcopy(params) for i, p in enumera...
Fast numerical integration method using mid-point rule.
def remove_user_from_user_groups(self, id, **kwargs): # noqa: E501 """Removes specific user groups from the user # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = a...
Removes specific user groups from the user # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.remove_user_from_user_groups(id, async_req=True) >>> result = thread...
def get_centroids(data,k,labels,centroids,data_norms): """ For each element in the dataset, choose the closest centroid Parameters ------------ data: array-like, shape= (m_samples,n_samples) K: integer, number of K clusters centroids: array-like, shape=(K, n_samples) labels: ...
For each element in the dataset, choose the closest centroid Parameters ------------ data: array-like, shape= (m_samples,n_samples) K: integer, number of K clusters centroids: array-like, shape=(K, n_samples) labels: array-like, shape (1,n_samples) returns ------------- c...
def revoke_admin_privileges(name, **client_args): ''' Revoke cluster administration privileges from a user. name Name of the user from whom admin privileges will be revoked. CLI Example: .. code-block:: bash salt '*' influxdb.revoke_admin_privileges <name> ''' client = _c...
Revoke cluster administration privileges from a user. name Name of the user from whom admin privileges will be revoked. CLI Example: .. code-block:: bash salt '*' influxdb.revoke_admin_privileges <name>
def get_real_end_line(token): """Finds the line on which the token really ends. With pyyaml, scalar tokens often end on a next line. """ end_line = token.end_mark.line + 1 if not isinstance(token, yaml.ScalarToken): return end_line pos = token.end_mark.pointer - 1 while (pos >= to...
Finds the line on which the token really ends. With pyyaml, scalar tokens often end on a next line.