code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def get_states_geo_zone_by_id(cls, states_geo_zone_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_states_geo_zone_by_id_with_http_info(states_geo_zone_id, **kwargs) else: (data) = cls._get_states_geo_zone_by_id_with...
Find StatesGeoZone Return single instance of StatesGeoZone by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_states_geo_zone_by_id(states_geo_zone_id, async=True) >>> result = thr...
def list_all_states_geo_zones(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_states_geo_zones_with_http_info(**kwargs) else: (data) = cls._list_all_states_geo_zones_with_http_info(**kwargs) return ...
List StatesGeoZones Return a list of StatesGeoZones This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_states_geo_zones(async=True) >>> result = thread.get() :param async bool ...
def replace_states_geo_zone_by_id(cls, states_geo_zone_id, states_geo_zone, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_states_geo_zone_by_id_with_http_info(states_geo_zone_id, states_geo_zone, **kwargs) else: (d...
Replace StatesGeoZone Replace all attributes of StatesGeoZone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_states_geo_zone_by_id(states_geo_zone_id, states_geo_zone, async=True) >>>...
def update_states_geo_zone_by_id(cls, states_geo_zone_id, states_geo_zone, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_states_geo_zone_by_id_with_http_info(states_geo_zone_id, states_geo_zone, **kwargs) else: (dat...
Update StatesGeoZone Update attributes of StatesGeoZone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_states_geo_zone_by_id(states_geo_zone_id, states_geo_zone, async=True) >>> result...
def compaction(self, request_compaction=False): url = self._service_url + 'compaction/' if request_compaction: response = requests.post(url, **self._instances._default_request_kwargs) else: response = requests.get(url, **self._instances._default_request_kwargs) ...
Retrieve a report on, or request compaction for this instance. :param bool request_compaction: A boolean indicating whether or not to request compaction.
def get_authenticated_connection(self, user, passwd, db='admin', ssl=True): # Attempt to establish an authenticated connection. try: connection = self.get_connection(ssl=ssl) connection[db].authenticate(user, passwd) return connection # Catch excepti...
Get an authenticated connection to this instance. :param str user: The username to use for authentication. :param str passwd: The password to use for authentication. :param str db: The name of the database to authenticate against. Defaults to ``'Admin'``. :param bool ssl: Use SSL/TLS if...
def shards(self, add_shard=False): url = self._service_url + 'shards/' if add_shard: response = requests.post(url, **self._instances._default_request_kwargs) else: response = requests.get(url, **self._instances._default_request_kwargs) return response.js...
Get a list of shards belonging to this instance. :param bool add_shard: A boolean indicating whether to add a new shard to the specified instance.
def new_relic_stats(self): if self._new_relic_stats is None: # if this is a sharded instance, fetch shard stats in parallel if self.type == 'mongodb_sharded': shards = [Shard(self.name, self._service_url + 'shards/', self._client, ...
Get stats for this instance.
def _rollup_shard_stats_to_instance_stats(self, shard_stats): instance_stats = {} opcounters_per_node = [] # aggregate replication_lag instance_stats['replication_lag'] = max(map(lambda s: s['replication_lag'], shard_stats.values())) aggregate_server_statistics = {} ...
roll up all shard stats to instance level stats :param shard_stats: dict of {shard_name: shard level stats}
def get_stepdown_window(self): url = self._service_url + 'stepdown/' response = requests.get(url, **self._instances._default_request_kwargs) return response.json()
Get information on this instance's stepdown window.
def set_stepdown_window(self, start, end, enabled=True, scheduled=True, weekly=True): # Ensure a logical start and endtime is requested. if not start < end: raise TypeError('Parameter "start" must occur earlier in time than "end".') # Ensure specified window is less than a ...
Set the stepdown window for this instance. Date times are assumed to be UTC, so use UTC date times. :param datetime.datetime start: The datetime which the stepdown window is to open. :param datetime.datetime end: The datetime which the stepdown window is to close. :param bool enabled: ...
def _get_connection(self, ssl): # Use SSL/TLS if requested and available. connect_string = self.connect_string if ssl and self.ssl_connect_string: connect_string = self.ssl_connect_string return pymongo.MongoClient(connect_string)
Get a live connection to this instance.
def get_shard_stats(self): return requests.get(self._stats_url, params={'include_stats': True}, headers={'X-Auth-Token': self._client.auth._token} ).json()['data']['stats']
:return: get stats for this mongodb shard
def brand(self, brand): allowed_values = ["visa", "mastercard", "americanExpress", "discover"] if brand is not None and brand not in allowed_values: raise ValueError( "Invalid value for `brand` ({0}), must be one of {1}" .format(brand, allowed_values)...
Sets the brand of this PaymentCard. :param brand: The brand of this PaymentCard. :type: str
def create_payment_card(cls, payment_card, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_payment_card_with_http_info(payment_card, **kwargs) else: (data) = cls._create_payment_card_with_http_info(payment_card, **kwa...
Create PaymentCard Create a new PaymentCard This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_payment_card(payment_card, async=True) >>> result = thread.get() :param async bool ...
def delete_payment_card_by_id(cls, payment_card_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._delete_payment_card_by_id_with_http_info(payment_card_id, **kwargs) else: (data) = cls._delete_payment_card_by_id_with_http_...
Delete PaymentCard Delete an instance of PaymentCard by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_payment_card_by_id(payment_card_id, async=True) >>> result = thread.get()...
def get_payment_card_by_id(cls, payment_card_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_payment_card_by_id_with_http_info(payment_card_id, **kwargs) else: (data) = cls._get_payment_card_by_id_with_http_info(paym...
Find PaymentCard Return single instance of PaymentCard by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_payment_card_by_id(payment_card_id, async=True) >>> result = thread.get() ...
def list_all_payment_cards(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_payment_cards_with_http_info(**kwargs) else: (data) = cls._list_all_payment_cards_with_http_info(**kwargs) return data
List PaymentCards Return a list of PaymentCards This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_payment_cards(async=True) >>> result = thread.get() :param async bool ...
def replace_payment_card_by_id(cls, payment_card_id, payment_card, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_payment_card_by_id_with_http_info(payment_card_id, payment_card, **kwargs) else: (data) = cls._replac...
Replace PaymentCard Replace all attributes of PaymentCard This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_payment_card_by_id(payment_card_id, payment_card, async=True) >>> result = thr...
def update_payment_card_by_id(cls, payment_card_id, payment_card, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_payment_card_by_id_with_http_info(payment_card_id, payment_card, **kwargs) else: (data) = cls._update_p...
Update PaymentCard Update attributes of PaymentCard This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_payment_card_by_id(payment_card_id, payment_card, async=True) >>> result = thread.get...
def rec2csv(r, filename): names = r.dtype.names def translate(x): if x is None or str(x).lower == "none": x = "" return str(x) with open(filename, "w") as csv: csv.write(",".join([str(x) for x in names])+"\n") for data in r: csv.write(",".join([tr...
Export a recarray *r* to a CSV file *filename*
def latex_quote(s): special = {'_':r'\_', '$':r'\$', '#':r'\#'} s = str(s) for char,repl in special.items(): new = s.replace(char, repl) s = new[:] return s
Quote special characters for LaTeX. (Incomplete, currently only deals with underscores, dollar and hash.)
def rec2latex(r, filename, empty=""): with open(filename, "w") as latex: latex.write(s_rec2latex(r, empty=empty)) return filename
Export a recarray *r* to a LaTeX table in *filename*
def s_rec2latex(r, empty=""): latex = "" names = r.dtype.names def translate(x): if x is None or str(x).lower == "none": x = empty return latex_quote(x) latex += r"\begin{tabular}{%s}" % ("".join(["c"]*len(names)),) + "\n" # simple c columns latex += r"\hline"+"\n" ...
Export a recarray *r* to a LaTeX table in a string
def on(self, type): '''Decorator function''' def decorator(self, func): '''decorated functions should be written as class methods @on('join') def on_join(self, channel): print("Joined channel %s" % channel) ''' self....
Decorator function
def tree_to_file(tree:'BubbleTree', outfile:str): with open(outfile, 'w') as fd: fd.write(tree_to_bubble(tree))
Compute the bubble representation of given power graph, and push it into given file.
def lines_from_tree(tree, nodes_and_set:bool=False) -> iter: NODE = 'NODE\t{}' INCL = 'IN\t{}\t{}' EDGE = 'EDGE\t{}\t{}\t1.0' SET = 'SET\t{}' if nodes_and_set: for node in tree.nodes(): yield NODE.format(node) for node in tree.powernodes(): yield SET.f...
Yield lines of bubble describing given BubbleTree
def to_python(self): if isinstance(self.data, str): return self.data.strip().lower() == 'true' if isinstance(self.data, int): return self.data > 0 return bool(self.data)
The string ``'True'`` (case insensitive) will be converted to ``True``, as will any positive integers.
def to_python(self): '''A :class:`datetime.datetime` object is returned.''' if self.data is None: return None # don't parse data that is already native if isinstance(self.data, datetime.datetime): return self.data elif self.use_int: return da...
A :class:`datetime.datetime` object is returned.
def get_api_call_headers(app): headers = { "content-type": "application/json;charset=UTF-8", "User-Agent": app.user_agent, } if not app.developer_settings: raise AuthError({"message": "Для корректной работы SDK нужно установить настройки разработчика", "url": "https://apps.devis...
Генерирует заголовки для API запроса. Тут же подкладывается авторизация :type app: metasdk.MetaApp
def extract_filename_from_url(log, url): ## > IMPORTS ## import re # EXTRACT THE FILENAME FROM THE URL try: log.debug("extracting filename from url " + url) reEoURL = re.compile('([\w\.]*)$') filename = reEoURL.findall(url)[0] # log.debug(filename) if(len(fil...
*get the filename from a URL.* *Will return 'untitled.html', if no filename is found.* **Key Arguments:** - ``url`` -- the url to extract filename from Returns: - ``filename`` -- the filename **Usage:** .. code-block:: python from fundamentals.download import ex...
def build_from_developer_settings(api_name: str, api_version: str): developer_settings = read_developer_settings() api_host = "http://" + api_name + ".apis.devision.io" return ApiClient( host=api_host, api_version=api_version, access_token=None, ...
:param api_name: Example hello :param api_version: Example v1, v2alpha :return: ApiClient
def process_formdata(self, valuelist): if valuelist: time_str = u' '.join(valuelist) try: timetuple = time.strptime(time_str, self.format) self.data = datetime.time(*timetuple[3:6]) except ValueError: self.data = None ...
Join time string.
def validate_csrf_token(self, field): if current_app.testing: return super(InvenioBaseForm, self).validate_csrf_token(field)
Disable CRSF proection during testing.
def access_SUSY_dataset_format_file(filename): # Load the CSV file to a list. with open(filename, "rb") as dataset_file: dataset_CSV = [row for row in csv.reader(dataset_file, delimiter = ",")] # Reorganise the data. return [ i for i in itertools.chain(*[list((element[1:...
This function accesses a CSV file containing data of the form of the [SUSY dataset](https://archive.ics.uci.edu/ml/datasets/SUSY), i.e. with the first column being class labels and other columns being features.
def select_event( event = None, selection = "ejets" ): if selection == "ejets": # Require single lepton. # Require >= 4 jets. if \ 0 < len(event.el_pt) < 2 and \ len(event.jet_pt) >= 4 and \ len(event.ljet_m) >= 1: return T...
Select a HEP event.
def sentiment( text = None, confidence = False ): try: words = text.split(" ") # Remove empty strings. words = [word for word in words if word] features = word_features(words) classification = classifier.classify(features) confidence_classificat...
This function accepts a string text input. It calculates the sentiment of the text, "pos" or "neg". By default, it returns this calculated sentiment. If selected, it returns a tuple of the calculated sentiment and the classificaton confidence.
def usernames( self ): try: return list(set([tweet.username for tweet in self])) except: log.error("error -- possibly a problem with tweets stored")
This function returns the list of unique usernames corresponding to the tweets stored in self.
def user_sentiments( self, username = None ): try: return [tweet.sentiment for tweet in self if tweet.username == username] except: log.error("error -- possibly no username specified") return None
This function returns a list of all sentiments of the tweets of a specified user.
def user_sentiments_most_frequent( self, username = None, single_most_frequent = True ): try: sentiment_frequencies = collections.Counter(self.user_sentiments( username = username )) if single_most_frequent:...
This function returns the most frequent calculated sentiments expressed in tweets of a specified user. By default, the single most frequent sentiment is returned. All sentiments with their corresponding frequencies can be returned also.
def users_sentiments_single_most_frequent( self, usernames = None, ): users_sentiments_single_most_frequent = dict() if usernames is None: usernames = self.usernames() try: for username in usernames: sentiment = self.user_s...
This function returns the single most frequent calculated sentiment expressed by all stored users or by a list of specified users as a dictionary.
def create_stripe_gateway(cls, stripe_gateway, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_stripe_gateway_with_http_info(stripe_gateway, **kwargs) else: (data) = cls._create_stripe_gateway_with_http_info(stripe_ga...
Create StripeGateway Create a new StripeGateway This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_stripe_gateway(stripe_gateway, async=True) >>> result = thread.get() :param asyn...
def delete_stripe_gateway_by_id(cls, stripe_gateway_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._delete_stripe_gateway_by_id_with_http_info(stripe_gateway_id, **kwargs) else: (data) = cls._delete_stripe_gateway_by_id_...
Delete StripeGateway Delete an instance of StripeGateway by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_stripe_gateway_by_id(stripe_gateway_id, async=True) >>> result = thre...
def get_stripe_gateway_by_id(cls, stripe_gateway_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_stripe_gateway_by_id_with_http_info(stripe_gateway_id, **kwargs) else: (data) = cls._get_stripe_gateway_by_id_with_http...
Find StripeGateway Return single instance of StripeGateway by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_stripe_gateway_by_id(stripe_gateway_id, async=True) >>> result = threa...
def list_all_stripe_gateways(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_stripe_gateways_with_http_info(**kwargs) else: (data) = cls._list_all_stripe_gateways_with_http_info(**kwargs) return dat...
List StripeGateways Return a list of StripeGateways This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_stripe_gateways(async=True) >>> result = thread.get() :param async bool ...
def replace_stripe_gateway_by_id(cls, stripe_gateway_id, stripe_gateway, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_stripe_gateway_by_id_with_http_info(stripe_gateway_id, stripe_gateway, **kwargs) else: (data) =...
Replace StripeGateway Replace all attributes of StripeGateway This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_stripe_gateway_by_id(stripe_gateway_id, stripe_gateway, async=True) >>> re...
def update_stripe_gateway_by_id(cls, stripe_gateway_id, stripe_gateway, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_stripe_gateway_by_id_with_http_info(stripe_gateway_id, stripe_gateway, **kwargs) else: (data) = c...
Update StripeGateway Update attributes of StripeGateway This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_stripe_gateway_by_id(stripe_gateway_id, stripe_gateway, async=True) >>> result = ...
def format_underline(s, char="=", indents=0): n = len(s) ind = " " * indents return ["{}{}".format(ind, s), "{}{}".format(ind, char*n)]
Traces a dashed line below string Args: s: string char: indents: number of leading intenting spaces Returns: list >>> print("\\n".join(format_underline("Life of João da Silva", "^", 2))) Life of João da Silva ^^^^^^^^^^^^^^^^^^^^^
def format_h1(s, format="text", indents=0): _CHAR = "=" if format.startswith("text"): return format_underline(s, _CHAR, indents) elif format.startswith("markdown"): return ["# {}".format(s)] elif format.startswith("rest"): return format_underline(s, _CHAR, 0)
Encloses string in format text Args: s: string format: string starting with "text", "markdown", or "rest" indents: number of leading intenting spaces Returns: list >>> print("\\n".join(format_h2("Header 1", indents=10))) Header 1 -------- ...
def format_h2(s, format="text", indents=0): _CHAR = "-" if format.startswith("text"): return format_underline(s, _CHAR, indents) elif format.startswith("markdown"): return ["## {}".format(s)] elif format.startswith("rest"): return format_underline(s, _CHAR, 0)
Encloses string in format text Args, Returns: see format_h1() >>> print("\\n".join(format_h2("Header 2", indents=2))) Header 2 -------- >>> print("\\n".join(format_h2("Header 2", "markdown", 2))) ## Header 2
def format_h3(s, format="text", indents=0): _CHAR = "~" if format.startswith("text"): return format_underline(s, _CHAR, indents) elif format.startswith("markdown"): return ["### {}".format(s)] elif format.startswith("rest"): return format_underline(s, _CHAR, 0)
Encloses string in format text Args, Returns: see format_h1()
def format_h4(s, format="text", indents=0): _CHAR = "^" if format.startswith("text"): return format_underline(s, _CHAR, indents) elif format.startswith("markdown"): return ["#### {}".format(s)] elif format.startswith("rest"): return format_underline(s, _CHAR, 0)
Encloses string in format text Args, Returns: see format_h1()
def question(question, options, default=None): # Make sure options is a list options_ = [x for x in options] if default is not None and default not in options_: raise ValueError("Default option '{}' is not in options {}.".format(default, options)) oto = "/".join([x.upper() if x ...
Ask a question with case-insensitive options of answers Args: question: string **without** the question mark and without the options. Example: 'Commit changes' options_: string or sequence of strings. If string, options will be single-lettered. Examples: 'YNC', ['yes',...
def yesno(question, default=None): if default is not None: if isinstance(default, bool): pass else: default_ = default.upper() if default_ not in ('Y', 'YES', 'N', 'NO'): raise RuntimeError("Invalid default value: '{}'".format(defaul...
Asks a yes/no question Args: question: string **without** the question mark and without the options. Example: 'Create links' default: default option. Accepted values are 'Y', 'YES', 'N', 'NO' or lowercase versions of these valus (this argument is case-insensitive) ...
def menu(title, options, cancel_label="Cancel", flag_allow_empty=False, flag_cancel=True, ch='.'): num_options, flag_ok = len(options), 0 option = None # result min_allowed = 0 if flag_cancel else 1 # minimum option value allowed (if option not empty) while True: print("") for line in fo...
Text menu. Arguments: title -- menu title, to appear at the top options -- sequence of strings cancel_label='Cancel' -- label to show at last "zero" option flag_allow_empty=0 -- Whether to allow empty option flag_cancel=True -- whether there is a "0 - Cancel" option ch="." -- characte...
def format_box(title, ch="*"): lt = len(title) return [(ch * (lt + 8)), (ch * 3 + " " + title + " " + ch * 3), (ch * (lt + 8)) ]
Encloses title in a box. Result is a list >>> for line in format_box("Today's TODO list"): ... print(line) ************************* *** Today's TODO list *** *************************
def format_progress(i, n): if n == 0: fraction = 0 else: fraction = float(i)/n LEN_BAR = 25 num_plus = int(round(fraction*LEN_BAR)) s_plus = '+'*num_plus s_point = '.'*(LEN_BAR-num_plus) return '[{0!s}{1!s}] {2:d}/{3:d} - {4:.1f}%'.format(s_plus, s_point, i, n,...
Returns string containing a progress bar, a percentage, etc.
def _format_exe_info(py_len, exeinfo, format, indlevel): ret = [] ind = " " * indlevel * NIND if format.startswith("text") else "" if format == "markdown-list": for si in exeinfo: ret.append(" - `{0!s}`: {1!s}".format(si.filename, si.description)) if format == "rest-list...
Renders ExeInfo object in specified format
def format_exe_info(exeinfo, format="text", indlevel=0): py_len = max([len(si.filename) for si in exeinfo]) sisi_gra = [si for si in exeinfo if si.flag_gui == True] sisi_cmd = [si for si in exeinfo if si.flag_gui == False] sisi_none = [si for si in exeinfo if si.flag_gui is None] de...
Generates listing of all Python scripts available as command-line programs. Args: exeinfo -- list of ExeInfo objects format -- One of the options below: "text" -- generates plain text for printing at the console "markdown-list" -- generates MarkDown as list "markdown-ta...
def markdown_table(data, headers): maxx = [max([len(x) for x in column]) for column in zip(*data)] maxx = [max(ll) for ll in zip(maxx, [len(x) for x in headers])] mask = " | ".join(["%-{0:d}s".format(n) for n in maxx]) ret = [mask % headers] ret.append(" | ".join(["-"*n for n in max...
Creates MarkDown table. Returns list of strings Arguments: data -- [(cell00, cell01, ...), (cell10, cell11, ...), ...] headers -- sequence of strings: (header0, header1, ...)
def expand_multirow_data(data): num_cols = len(data[0]) # number of columns # calculates row heights row_heights = [] for mlrow in data: row_height = 0 for j, cell in enumerate(mlrow): row_height = max(row_height, 1 if not isinstance(cell, (list, tuple)) else...
Converts multirow cells to a list of lists and informs the number of lines of each row. Returns: tuple: new_data, row_heights
def rest_table(data, headers): num_cols = len(headers) new_data, row_heights = expand_multirow_data(data) new_data = [[str(x) for x in row] for row in new_data] col_widths = [max([len(x) for x in col]) for col in zip(*new_data)] col_widths = [max(cw, len(s)) for cw, s in zip(col_widths,...
Creates reStructuredText table (grid format), allowing for multiline cells Arguments: data -- [((cell000, cell001, ...), (cell010, cell011, ...), ...), ...] headers -- sequence of strings: (header0, header1, ...) **Note** Tolerant to non-strings **Note** Cells may or may not be multil...
def _map_relations(relations, p, language='any'): ''' :param: :class:`list` relations: Relations to be mapped. These are concept or collection id's. :param: :class:`skosprovider.providers.VocabularyProvider` p: Provider to look up id's. :param string language: Language to render the rela...
:param: :class:`list` relations: Relations to be mapped. These are concept or collection id's. :param: :class:`skosprovider.providers.VocabularyProvider` p: Provider to look up id's. :param string language: Language to render the relations' labels in :rtype: :class:`list`
def _map_relation(c, language='any'): label = c.label(language) return { 'id': c.id, 'type': c.type, 'uri': c.uri, 'label': label.label if label else None }
Map related concept or collection, leaving out the relations. :param c: the concept or collection to map :param string language: Language to render the relation's label in :rtype: :class:`dict`
def note_adapter(obj, request): ''' Adapter for rendering a :class:`skosprovider.skos.Note` to json. :param skosprovider.skos.Note obj: The note to be rendered. :rtype: :class:`dict` ''' return { 'note': obj.note, 'type': obj.type, 'language': obj.language, 'mark...
Adapter for rendering a :class:`skosprovider.skos.Note` to json. :param skosprovider.skos.Note obj: The note to be rendered. :rtype: :class:`dict`
def get_indicators(self): response = self._get('', 'get-indicators') response['message'] = "%i indicators:\n%s" % ( len(response['indicators']), "\n".join(response['indicators']) ) return response
List indicators available on the remote instance.
def to_unicode(obj, encoding='utf-8'): if isinstance(obj, basestring): if not isinstance(obj, unicode): obj = unicode(obj, encoding) return obj
Convert obj to unicode (if it can be be converted) from http://farmdev.com/talks/unicode/
def besttype(x, encoding="utf-8", percentify=True): def unicodify(x): return to_unicode(x, encoding) def percent(x): try: if x.endswith("%"): x = float(x[:-1]) / 100. else: raise ValueError except (AttributeError, ValueError): ...
Convert string x to the most useful type, i.e. int, float or unicode string. If x is a quoted string (single or double quotes) then the quotes are stripped and the enclosed string returned. The string can contain any number of quotes, it is only important that it begins and ends with either single or d...
def _onsuccess(cls, kmsg, result): logger.info( "{}.Success: {}[{}]: {}".format( cls.__name__, kmsg.entrypoint, kmsg.uuid, result ), extra=dict( kmsg=kmsg.dump(), kresult=ResultSchema().dump(result) if result else dict(...
To execute on execution success :param kser.schemas.Message kmsg: Kafka message :param kser.result.Result result: Execution result :return: Execution result :rtype: kser.result.Result
def _onerror(cls, kmsg, result): logger.error( "{}.Failed: {}[{}]: {}".format( cls.__name__, kmsg.entrypoint, kmsg.uuid, result ), extra=dict( kmsg=kmsg.dump(), kresult=ResultSchema().dump(result) if result else dict() ...
To execute on execution failure :param kser.schemas.Message kmsg: Kafka message :param kser.result.Result result: Execution result :return: Execution result :rtype: kser.result.Result
def _onmessage(cls, kmsg): logger.debug( "{}.ReceivedMessage {}[{}]".format( cls.__name__, kmsg.entrypoint, kmsg.uuid ), extra=dict(kmsg=kmsg.dump()) ) return cls.onmessage(kmsg)
Call on received message :param kser.schemas.Message kmsg: Kafka message :return: Kafka message :rtype: kser.schemas.Message
def register(cls, name, entrypoint): if not issubclass(entrypoint, Entrypoint): raise ValidationError( "Invalid type for entry '{}', MUST implement " "kser.entry.Entrypoint".format(name), extra=dict(entrypoint=name) ) cls.E...
Register a new entrypoint :param str name: Key used by messages :param kser.entry.Entrypoint entrypoint: class to load :raises ValidationError: Invalid entry
def run(cls, raw_data): logger.debug("{}.ReceivedFromKafka: {}".format( cls.__name__, raw_data )) try: kmsg = cls._onmessage(cls.TRANSPORT.loads(raw_data)) except Exception as exc: logger.error( "{}.ImportError: Failed to load ...
description of run
def interval_condition(value, inf, sup, dist): return (value > inf - dist and value < sup + dist)
Checks if value belongs to the interval [inf - dist, sup + dist].
def deactivate(self, node_id): node = self.node_list[node_id] self.node_list[node_id] = node._replace(active=False)
Deactivate the node identified by node_id. Deactivates the node corresponding to node_id, which means that it can never be the output of a nearest_point query. Note: The node is not removed from the tree, its data is steel available. Args: node_id (int): The no...
def insert(self, point, data=None): assert len(point) == self.k if self.size == 0: if self.region is None: self.region = [[-math.inf, math.inf]] * self.k axis = 0 return self.new_node(point, self.region, axis, data) # Iteratively des...
Insert a new node in the tree. Args: point (:obj:`tuple` of float or int): Stores the position of the node. data (:obj, optional): The information stored by the node. Returns: int: The identifier of the new node. Example: >>> tre...
def find_nearest_point(self, query, dist_fun=euclidean_dist): def get_properties(node_id): return self.node_list[node_id][:6] return nearest_point(query, 0, get_properties, dist_fun)
Find the point in the tree that minimizes the distance to the query. Args: query (:obj:`tuple` of float or int): Stores the position of the node. dist_fun (:obj:`function`, optional): The distance function, euclidean distance by default. Returns:...
def set_to_public(self, request, queryset): queryset.update(is_public=True, modified=now())
Set one or several releases to public
def loads(cls, json_data): try: return cls(**cls.MARSHMALLOW_SCHEMA.loads(json_data)) except marshmallow.exceptions.ValidationError as exc: raise ValidationError("Failed to load message", extra=exc.args[0])
description of load
def format(self, response): res = self._prepare_response(response) res.content = self._format_data(res.content, self.charset) return self._finalize_response(res)
Format the data. In derived classes, it is usually better idea to override ``_format_data()`` than this method. :param response: devil's ``Response`` object or the data itself. May also be ``None``. :return: django's ``HttpResponse`` todo: this shouldn...
def parse(self, data, charset=None): charset = charset or self.charset return self._parse_data(data, charset)
Parse the data. It is usually a better idea to override ``_parse_data()`` than this method in derived classes. :param charset: the charset of the data. Uses datamapper's default (``self.charset``) if not given. :returns:
def _decode_data(self, data, charset): try: return smart_unicode(data, charset) except UnicodeDecodeError: raise errors.BadRequest('wrong charset')
Decode string data. :returns: unicode string
def _parse_data(self, data, charset): return self._decode_data(data, charset) if data else u''
Parse the data :param data: the data (may be None)
def _finalize_response(self, response): res = HttpResponse(content=response.content, content_type=self._get_content_type()) # status_code is set separately to allow zero res.status_code = response.code return res
Convert the ``Response`` object into django's ``HttpResponse`` :return: django's ``HttpResponse``
def register_mapper(self, mapper, content_type, shortname=None): self._check_mapper(mapper) cont_type_names = self._get_content_type_names(content_type, shortname) self._datamappers.update(dict([(name, mapper) for name in cont_type_names]))
Register new mapper. :param mapper: mapper object needs to implement ``parse()`` and ``format()`` functions.
def select_formatter(self, request, resource): # 1. get from resource if resource.mapper: return resource.mapper # 2. get from url mapper_name = self._get_name_from_url(request) if mapper_name: return self._get_mapper(mapper_name) # 3. ge...
Select appropriate formatter based on the request. :param request: the HTTP request :param resource: the invoked resource
def select_parser(self, request, resource): # 1. get from resource if resource.mapper: return resource.mapper # 2. get from content type mapper_name = self._get_name_from_content_type(request) if mapper_name: return self._get_mapper(mapper_name) ...
Select appropriate parser based on the request. :param request: the HTTP request :param resource: the invoked resource
def get_mapper_by_content_type(self, content_type): content_type = util.strip_charset(content_type) return self._get_mapper(content_type)
Returs mapper based on the content type.
def _get_mapper(self, mapper_name): if mapper_name in self._datamappers: # mapper found return self._datamappers[mapper_name] else: # unsupported format return self._unknown_format(mapper_name)
Return the mapper based on the given name. :returns: the mapper based on the given ``mapper_name`` :raises: NotAcceptable if we don't support the requested format.
def _get_name_from_content_type(self, request): content_type = request.META.get('CONTENT_TYPE', None) if content_type: # remove the possible charset-encoding info return util.strip_charset(content_type) return None
Get name from Content-Type header
def _get_name_from_accept(self, request): accepts = util.parse_accept_header(request.META.get("HTTP_ACCEPT", "")) if not accepts: return None for accept in accepts: if accept[0] in self._datamappers: return accept[0] raise errors.NotAcce...
Process the Accept HTTP header. Find the most suitable mapper that the client wants and we support. :returns: the preferred mapper based on the accept header or ``None``.
def _get_name_from_url(self, request): format = request.GET.get('format', None) if not format: match = self._format_query_pattern.match(request.path) if match and match.group('format'): format = match.group('format') return format
Determine short name for the mapper based on the URL. Short name can be either in query string (e.g. ?format=json) or as an extension to the URL (e.g. myresource.json). :returns: short name of the mapper or ``None`` if not found.
def _check_mapper(self, mapper): if not hasattr(mapper, 'parse') or not callable(mapper.parse): raise ValueError('mapper must implement parse()') if not hasattr(mapper, 'format') or not callable(mapper.format): raise ValueError('mapper must implement format()')
Check that the mapper has valid signature.
def cleanup(self, cluster): if self._storage_path and os.path.exists(self._storage_path): fname = '%s.%s' % (AnsibleSetupProvider.inventory_file_ending, cluster.name) inventory_path = os.path.join(self._storage_path, fname) if os.path....
Deletes the inventory file used last recently used. :param cluster: cluster to clear up inventory file for :type cluster: :py:class:`elasticluster.cluster.Cluster`
def await_task(self, task_id, service_id, callback_fn=None, sleep_sec=15): while True: import time time.sleep(sleep_sec) task_info = self.__metadb.one(""" SELECT id, service_id, status, result_data FROM job.task WHERE ...
Подождать выполнения задачи запускатора :param task_id: ID задачи, за которой нужно следить :param service_id: ID сервиса :param callback_fn: Функция обратного вызова, в нее будет передаваться task_info и is_finish как признак, что обработка завершена :param sleep_sec: задержка между пр...
def submit(self, service_id: str, data: dict = None): if self.__app.starter_api_url == 'http://STUB_URL': self.log.info('STARTER DEV. Задача условно поставлена', { "service_id": service_id, "data": data, }) return task = {"ser...
Отправить задачу в запускатор :param service_id: ID службы. Например "meta.docs_generate" :param data: Полезная нагрузка задачи :return: dict
def parse_version_string(version_string): components = version_string.split('-') + [None, None] version = list(map(int, components[0].split('.'))) build_tag = components[1] if components[1] else BUILD_TAG build_number = int(components[2]) if components[2] else components[2] return (version, bu...
Parse a version string into it's components. >>> parse_version_string("0.1") ([0, 1], 'jenkins', None) >>> parse_version_string("0.3.2-jenkins-3447876") ([0, 3, 2], 'jenkins', 3447876)
def format_version(version, build_number=None, build_tag=BUILD_TAG): formatted_version = ".".join(map(str, version)) if build_number is not None: return "{formatted_version}-{build_tag}-{build_number}".format(**locals()) return formatted_version
Format a version string for use in packaging. >>> format_version([0,3,5]) '0.3.5' >>> format_version([8, 8, 9], 23676) '8.8.9-jenkins-23676' >>> format_version([8, 8, 9], 23676, 'koekjes') '8.8.9-koekjes-23676'
def based_on(self, based_on): allowed_values = ["shippingAddress", "billingAddress"] if based_on is not None and based_on not in allowed_values: raise ValueError( "Invalid value for `based_on` ({0}), must be one of {1}" .format(based_on, allowed_value...
Sets the based_on of this TaxRate. :param based_on: The based_on of this TaxRate. :type: str
def create_tax_rate(cls, tax_rate, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_tax_rate_with_http_info(tax_rate, **kwargs) else: (data) = cls._create_tax_rate_with_http_info(tax_rate, **kwargs) return ...
Create TaxRate Create a new TaxRate This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_tax_rate(tax_rate, async=True) >>> result = thread.get() :param async bool :param Ta...