code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def _get_manifest_data(self): with tempfile.NamedTemporaryFile(delete=True) as tmp: try: self.s3.download_fileobj(self.sitename, self.manifest_file, tmp) tmp.seek(0) data = tmp.read() if data is not None: re...
Return the list of items in the manifest :return: list
def _yass_vars(self): utc = arrow.utcnow() return { "NAME": __title__, "VERSION": __version__, "URL": __uri__, "GENERATOR": "%s %s" % (__title__, __version__), "YEAR": utc.year }
Global variables
def _get_page_meta(self, page): meta = self._pages_meta.get(page) if not meta: src_file = os.path.join(self.pages_dir, page) with open(src_file) as f: _, _ext = os.path.splitext(src_file) markup = _ext.replace(".", "") _met...
Cache the page meta from the frontmatter and assign new keys The cache data will be used to build links or other properties
def _get_page_content(self, page): src_file = os.path.join(self.pages_dir, page) with open(src_file) as f: _meta, content = frontmatter.parse(f.read()) return content
Get the page content without the frontmatter
def _link_to(self, page, text=None, title=None, _class="", id="", alt="", **kwargs): anchor = "" if "#" in page: page, anchor = page.split("#") anchor = "#" + anchor meta = self._get_page_meta(page) return "<a href='{url}' class='{_class}' id='{id}' titl...
Build the A HREF LINK To a page.
def _url_to(self, page): anchor = "" if "#" in page: page, anchor = page.split("#") anchor = "#" + anchor meta = self._get_page_meta(page) return meta.get("url")
Get the url of a page
def _get_dest_file_and_url(self, filepath, page_meta={}): filename = filepath.split("/")[-1] filepath_base = filepath.replace(filename, "").rstrip("/") slug = page_meta.get("slug") fname = slugify(slug) if slug else filename \ .replace(".html", "") \ .re...
Return tuple of the file destination and url
def build_static(self): if not os.path.isdir(self.build_static_dir): os.makedirs(self.build_static_dir) copy_tree(self.static_dir, self.build_static_dir) if self.webassets_cmd: self.webassets_cmd.build()
Build static files
def build_pages(self): for root, _, files in os.walk(self.pages_dir): base_dir = root.replace(self.pages_dir, "").lstrip("/") if not base_dir.startswith("_"): for f in files: src_file = os.path.join(base_dir, f) self._build...
Iterate over the pages_dir and build the pages
def publish(self, target="S3", sitename=None, purge_files=True): self.build() endpoint = self.config.get("hosting.%s" % target) if target.upper() == "S3": p = publisher.S3Website(sitename=sitename or self.config.get("sitename"), aws_acces...
To publish programatically :param target: Where to pusblish at, S3 :param sitename: The site name :param purge_files: if True, it will delete old files :return:
def create_refund_transaction(cls, refund_transaction, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._create_refund_transaction_with_http_info(refund_transaction, **kwargs) else: (data) = cls._create_refund_transaction_with...
Create RefundTransaction Create a new RefundTransaction This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_refund_transaction(refund_transaction, async=True) >>> result = thread.get() ...
def delete_refund_transaction_by_id(cls, refund_transaction_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._delete_refund_transaction_by_id_with_http_info(refund_transaction_id, **kwargs) else: (data) = cls._delete_refun...
Delete RefundTransaction Delete an instance of RefundTransaction 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_refund_transaction_by_id(refund_transaction_id, async=True) >...
def get_refund_transaction_by_id(cls, refund_transaction_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_refund_transaction_by_id_with_http_info(refund_transaction_id, **kwargs) else: (data) = cls._get_refund_transac...
Find RefundTransaction Return single instance of RefundTransaction 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_refund_transaction_by_id(refund_transaction_id, async=True) >>...
def list_all_refund_transactions(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_refund_transactions_with_http_info(**kwargs) else: (data) = cls._list_all_refund_transactions_with_http_info(**kwargs) ...
List RefundTransactions Return a list of RefundTransactions This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_refund_transactions(async=True) >>> result = thread.get() :param a...
def replace_refund_transaction_by_id(cls, refund_transaction_id, refund_transaction, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_refund_transaction_by_id_with_http_info(refund_transaction_id, refund_transaction, **kwargs) el...
Replace RefundTransaction Replace all attributes of RefundTransaction This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_refund_transaction_by_id(refund_transaction_id, refund_transaction, async=...
def update_refund_transaction_by_id(cls, refund_transaction_id, refund_transaction, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._update_refund_transaction_by_id_with_http_info(refund_transaction_id, refund_transaction, **kwargs) else...
Update RefundTransaction Update attributes of RefundTransaction This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_refund_transaction_by_id(refund_transaction_id, refund_transaction, async=True) ...
def get_skos_registry(registry): ''' Get the :class:`skosprovider.registry.Registry` attached to this pyramid application. :rtype: :class:`skosprovider.registry.Registry` ''' # Argument might be a config or request regis = getattr(registry, 'registry', None) if regis is None: re...
Get the :class:`skosprovider.registry.Registry` attached to this pyramid application. :rtype: :class:`skosprovider.registry.Registry`
def sort_matches(matches): '''Sorts a ``list`` of matches best to worst''' multipliers = {'exact':10**5,'fname':10**4,'fuzzy':10**2,'fuzzy_fragment':1} matches = [(multipliers[x.type]*(x.amount if x.amount else 1),x) for x in matches] return [x[1] for x in sorted(matches,reverse=True)f sort_matches(matc...
Sorts a ``list`` of matches best to worst
def matches(self,string,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False): '''Returns whether this :class:`Concept` matches ``string``''' matches = [] for item in self.examples: m = best_match_from_list(string,self.examples[item],fuzzy,fname_match,fuzzy_fragment,gue...
Returns whether this :class:`Concept` matches ``string``
def set_action(self,concept_name,action_meth): '''helper function to set the ``action`` attr of any :class:`Concept`s in ``self.vocab`` that match ``concept_name`` to ``action_meth``''' for concept in self.vocab: if concept.name == concept_name: concept.action = action_metf s...
helper function to set the ``action`` attr of any :class:`Concept`s in ``self.vocab`` that match ``concept_name`` to ``action_meth``
def match_all_concepts(self,string): '''Returns sorted list of all :class:`Concept`s matching ``string``''' multipliers = {'exact':10**5,'fname':10**4,'fuzzy':10**2,'fuzzy_fragment':1} matches = [] for concept in self.vocab: matches += concept.matches(string,self.fuzzy,self.f...
Returns sorted list of all :class:`Concept`s matching ``string``
def match_concept(self,string): '''Find all matches in this :class:`Bottle` for ``string`` and return the best match''' matches = self.match_all_concepts(string) if len(matches)>0: return matches[0] return Nonf match_concept(self,string): '''Find all matches in this :...
Find all matches in this :class:`Bottle` for ``string`` and return the best match
def parse_string(self,string,best=False): '''Parses ``string`` trying to match each word to a :class:`Concept`. If ``best``, will only return the top matches''' if isinstance(string,list): items = string else: items = string.split() item_list = [] not_next...
Parses ``string`` trying to match each word to a :class:`Concept`. If ``best``, will only return the top matches
def process_string(self,string): '''Searches the string (or list of strings) for an action word (a :class:`Concept` that has and ``action`` attached to it), then calls the appropriate function with a dictionary of the identified words (according to ``vocab``). For examples, see ``demo.p...
Searches the string (or list of strings) for an action word (a :class:`Concept` that has and ``action`` attached to it), then calls the appropriate function with a dictionary of the identified words (according to ``vocab``). For examples, see ``demo.py``
def all(self): response = requests.get(self._url, **self._default_request_kwargs) data = self._get_response_data(response) return self._concrete_instance_list(data)
Get all ObjectRocket instances the current client has access to. :returns: A list of :py:class:`bases.BaseInstance` instances. :rtype: list
def create(self, name, plan, zone, service_type='mongodb', instance_type='mongodb_sharded', version='2.4.6'): # Build up request data. url = self._url request_data = { 'name': name, 'service': service_type, 'plan': plan, 'ty...
Create an ObjectRocket instance. :param str name: The name to give to the new instance. :param int plan: The plan size of the new instance. :param str zone: The zone that the new instance is to exist in. :param str service_type: The type of service that the new instance is to provide. ...
def get(self, instance_name): url = self._url + instance_name + '/' response = requests.get(url, **self._default_request_kwargs) data = self._get_response_data(response) return self._concrete_instance(data)
Get an ObjectRocket instance by name. :param str instance_name: The name of the instance to retrieve. :returns: A subclass of :py:class:`bases.BaseInstance`, or None if instance does not exist. :rtype: :py:class:`bases.BaseInstance`
def _concrete_instance(self, instance_doc): if not isinstance(instance_doc, dict): return None # Attempt to instantiate the appropriate class for the given instance document. try: service = instance_doc['service'] cls = self._service_class_map[servic...
Concretize an instance document. :param dict instance_doc: A document describing an instance. Should come from the API. :returns: A subclass of :py:class:`bases.BaseInstance`, or None. :rtype: :py:class:`bases.BaseInstance`
def _concrete_instance_list(self, instance_docs): if not instance_docs: return [] return list( filter(None, [self._concrete_instance(instance_doc=doc) for doc in instance_docs]) )
Concretize a list of instance documents. :param list instance_docs: A list of instance documents. Should come from the API. :returns: A list of :py:class:`bases.BaseInstance`s. :rtype: list
def load_plugin_by_name(name): plugins = load(PLUGIN_NAMESPACE) full_name = "%s.%s" % (PLUGIN_NAMESPACE, name) try: plugins = (plugin for plugin in plugins if plugin.__name__ == full_name) plugin = next(plugins) return plugin except StopIteration: raise UnknownPlugin...
Load the plugin with the specified name. >>> plugin = load_plugin_by_name('default') >>> api = dir(plugin) >>> 'build_package' in api True >>> 'get_version' in api True >>> 'set_package_version' in api True >>> 'set_version' in api True
def change_directory(path=None): if path is not None: try: oldpwd = getcwd() logger.debug('changing directory from %s to %s' % (oldpwd, path)) chdir(path) yield finally: chdir(oldpwd) else: yield
Context manager that changes directory and resets it when existing >>> with change_directory('/tmp'): >>> pass
def empty_directory(path=None): install_dir = tempfile.mkdtemp(dir=path) try: yield install_dir finally: shutil.rmtree(install_dir)
Context manager that creates a temporary directory, and cleans it up when exiting. >>> with empty_directory(): >>> pass
def get(self, name): path = self._get_cluster_storage_path(name) try: with open(path, 'r') as storage: cluster = self.load(storage) # Compatibility with previous version of Node for node in sum(cluster.nodes.values(), []): ...
Retrieves the cluster with the given name. :param str name: name of the cluster (identifier) :return: :py:class:`elasticluster.cluster.Cluster`
def save_or_update(self, cluster): if not os.path.exists(self.storage_path): os.makedirs(self.storage_path) path = self._get_cluster_storage_path(cluster.name) cluster.storage_file = path with open(path, 'wb') as storage: self.dump(cluster, storage)
Save or update the cluster to persistent state. :param cluster: cluster to save or update :type cluster: :py:class:`elasticluster.cluster.Cluster`
def _get_store_by_name(self, name): for cls in self.storage_type_map.values(): cluster_files = glob.glob( '%s/%s.%s' % (self.storage_path, name, cls.file_ending)) if cluster_files: try: return cls(self.storage_path) ...
Return an instance of the correct DiskRepository based on the *first* file that matches the standard syntax for repository files
def _format(color, style=''): _color = QColor() _color.setNamedColor(color) _format = QTextCharFormat() _format.setForeground(_color) if 'bold' in style: _format.setFontWeight(QFont.Bold) if 'italic' in style: _format.setFontItalic(True) return _format
Return a QTextCharFormat with the given attributes.
def highlightBlock(self, text): # Do other syntax formatting for expression, nth, format in self.rules: index = expression.indexIn(text, 0) while index >= 0: # We actually want the index of the nth match index = expression.pos(nth...
Apply syntax highlighting to the given block of text.
def match_multiline(self, text, delimiter, in_state, style): # If inside triple-single quotes, start at 0 if self.previousBlockState() == in_state: start = 0 add = 0 # Otherwise, look for the delimiter on this line else: start = delimi...
Do highlighting of multi-line strings. ``delimiter`` should be a ``QRegExp`` for triple-single-quotes or triple-double-quotes, and ``in_state`` should be a unique integer to represent the corresponding state changes when inside those strings. Returns True if we're still inside a mult...
def __import_pem(self, key_name, pem_file_path, password): key_import = self.__get_function_or_ex_function('import_key_pair_from_file') pem_file = os.path.expandvars(os.path.expanduser(pem_file_path)) try: pem = paramiko.RSAKey.from_private_key_file(pem_file, password) ...
Import PEM certificate with provider :param key_name: name of the key to import :param pem_file_path: path to the pem file :param password: optional password for the pem file
def __get_function_by_pattern(self, pattern): function_names = [name for name in dir(self.driver) if pattern in name] if function_names: name = function_names[0] if len(function_names) > 1: log.warn( "Several functions match pattern `%...
Return first function whose name *contains* the string `pattern`. :param func: partial function name (ex. key_pair) :return: list function that goes with it (ex. list_key_pairs)
def __get_function_or_ex_function(self, func_name): # try function name as given try: return getattr(self.driver, func_name) except AttributeError: pass # try prefixing name with `ex_` try: return getattr(self.driver, 'ex_' + func_name...
Check if a function (or an 'extended' function) exists for a key on a driver, and if it does, return it. :param func_name: name of the function :return: a callable or none
def __pop_driver_auth_args(**kwargs): if 'username' in kwargs: return [kwargs.pop('username'), kwargs.pop('password')] elif 'access_token' in kwargs: return kwargs.pop('access token') elif 'access_id' in kwargs: return kwargs.pop('access_id'), kwargs....
Try to construct the arguments that should be passed as initialization of a driver :param kwargs: options passed to the class :return: args or none
def from_dict(cls, D, is_json=False): '''This factory for :class:`Model` takes either a native Python dictionary or a JSON dictionary/object if ``is_json`` is ``True``. The dictionary passed does not need to contain all of the values that the Model declares. ''' instance...
This factory for :class:`Model` takes either a native Python dictionary or a JSON dictionary/object if ``is_json`` is ``True``. The dictionary passed does not need to contain all of the values that the Model declares.
def add_field(self, key, value, field): ''':meth:`add_field` must be used to add a field to an existing instance of Model. This method is required so that serialization of the data is possible. Data on existing fields (defined in the class) can be reassigned without using this method. ...
:meth:`add_field` must be used to add a field to an existing instance of Model. This method is required so that serialization of the data is possible. Data on existing fields (defined in the class) can be reassigned without using this method.
def to_dict(self, serial=False): '''A dictionary representing the the data of the class is returned. Native Python objects will still exist in this dictionary (for example, a ``datetime`` object will be returned rather than a string) unless ``serial`` is set to True. ''' ...
A dictionary representing the the data of the class is returned. Native Python objects will still exist in this dictionary (for example, a ``datetime`` object will be returned rather than a string) unless ``serial`` is set to True.
def run(self, loopinfo=None, batch_size=1): logger.info("{}.Starting...".format(self.__class__.__name__)) if loopinfo: while True: for topic in self.topics: self.call_kafka(topic, batch_size) time.sleep(loopinfo.sleep) else...
Run consumer
def import_from_string(path, slient=True): names = path.split(".") for i in range(len(names), 0, -1): p1 = ".".join(names[0:i]) module = import_module(p1) if module: p2 = ".".join(names[i:]) if p2: return select(module, p2, slient=slient) ...
根据给定的对象路径,动态加载对象。
def parse_search_url(url): config = {} url = urlparse.urlparse(url) # Remove query strings. path = url.path[1:] path = path.split('?', 2)[0] if url.scheme in SEARCH_SCHEMES: config["ENGINE"] = SEARCH_SCHEMES[url.scheme] if url.scheme in USES_URL: config["URL"] = url...
Parses a search URL.
def config(name='SEARCH_URL', default='simple://'): config = {} s = env(name, default) if s: config = parse_search_url(s) return config
Returns configured SEARCH dictionary from SEARCH_URL
def _control_nonterminal(nonterm): # type: (Type[Nonterminal]) -> None if not inspect.isclass(nonterm) or not issubclass(nonterm, Nonterminal): raise NotNonterminalException(nonterm)
Check if the nonterminal is valid. :param nonterm: Nonterminal to check. :raise NotNonterminalException: If the object doesn't inherit from Nonterminal class.
def add(self, *nonterminals): # type: (Iterable[Type[Nonterminal]]) -> None for nonterm in nonterminals: if nonterm in self: continue _NonterminalSet._control_nonterminal(nonterm) super().add(nonterm) self._assign_map[nonterm] = se...
Add nonterminals into the set. :param nonterminals: Nonterminals to insert. :raise NotNonterminalException: If the object doesn't inherit from Nonterminal class.
def remove(self, *nonterminals): # type: (Iterable[Type[Nonterminal]]) -> None for nonterm in set(nonterminals): _NonterminalSet._control_nonterminal(nonterm) if nonterm not in self: raise KeyError('Nonterminal ' + nonterm.__name__ + ' is not inside') ...
Remove nonterminals from the set. Removes also rules using this nonterminal. Set start symbol to None if deleting nonterminal is start symbol at the same time. :param nonterminals: Nonterminals to remove.
def wash_html_id(dirty): import re if not dirty[0].isalpha(): # we make sure that the first character is a lowercase letter dirty = 'i' + dirty non_word = re.compile(r'[^\w]+') return non_word.sub('', dirty)
Strip non-alphabetic or newline characters from a given string. It can be used as a HTML element ID (also with jQuery and in all browsers). :param dirty: the string to wash :returns: the HTML ID ready string
def quote(self, text=None): text = text or re.sub(r'\[quote=.+?\[/quote\]', '', self.text, flags=re.DOTALL ).strip('\n') return f'[quote={self.author.id};{self.id}]{text}[/quote]'
Quote this post. Parameters ---------- text : str Text to quote. Defaults to the whole text of the post. Returns ------- str A NationStates bbCode quote of the post.
async def factbook(self, root): # This lib might have been a mistake, but the line below # definitely isn't. return html.unescape(html.unescape(root.find('FACTBOOK').text))
Region's World Factbook Entry. Returns ------- an :class:`ApiQuery` of str
async def delegate(self, root): nation = root.find('DELEGATE').text if nation == '0': return None return aionationstates.Nation(nation)
Regional World Assembly Delegate. Returns ------- an :class:`ApiQuery` of :class:`Nation` an :class:`ApiQuery` of None If the region has no delegate.
async def founder(self, root): nation = root.find('FOUNDER').text if nation == '0': return None return aionationstates.Nation(nation)
Regional Founder. Returned even if the nation has ceased to exist. Returns ------- an :class:`ApiQuery` of :class:`Nation` an :class:`ApiQuery` of None If the region is Game-Created and doesn't have a founder.
async def officers(self, root): officers = sorted( root.find('OFFICERS'), # I struggle to say what else this tag would be useful for. key=lambda elem: int(elem.find('ORDER').text) ) return [Officer(elem) for elem in officers]
Regional Officers. Does not include the Founder or the Delegate, unless they have additional titles as Officers. In the correct order. Returns ------- an :class:`ApiQuery` of a list of :class:`Officer`
async def messages(self): # Messages may be posted on the RMB while the generator is running. oldest_id_seen = float('inf') for offset in count(step=100): posts_bunch = await self._get_messages(offset=offset) for post in reversed(posts_bunch): if ...
Iterate through RMB posts from newest to oldest. Returns ------- an asynchronous generator that yields :class:`Post`
def accumulate_items(items, reduce_each=False): if not items: return {} accumulated = defaultdict(list) for key, val in items: accumulated[key].append(val) if not reduce_each: return accumulated else: return {k: reduce_value(v, v) for k, v in iteritems(accumul...
:return: item pairs as key: val, with vals under duplicate keys accumulated under each
def _to_key_val_pairs(defs): if isinstance(defs, STRING_TYPES): # Convert 'a' to [('a', None)], or 'a.b.c' to [('a', 'b.c')] return [defs.split('.', 1) if '.' in defs else (defs, None)] else: pairs = [] # Convert collections of strings or lists as above; break dicts into c...
Helper to split strings, lists and dicts into (current, value) tuples for accumulation
def filter_empty(values, default=None): if values is None: return default elif hasattr(values, '__len__') and len(values) == 0: return default elif hasattr(values, '__iter__') and not isinstance(values, _filtered_types): filtered = type(values) if isinstance(values, _filter_typ...
Eliminates None or empty items from lists, tuples or sets passed in. If values is None or empty after filtering, the default is returned.
def flatten_items(items, recurse=False): if not items: return items elif not hasattr(items, '__iter__'): return items elif isinstance(items, _flattened_types): return items flattened = [] for item in items: if item and hasattr(item, '__iter__') and not isinstan...
Expands inner lists (tuples, sets, Etc.) within items so that each extends its parent. If items is None or empty after filtering, the default is returned. If recurse is False, only the first level of items is flattened, otherwise all levels.
def remove_duplicates(items, in_reverse=False, is_unhashable=False): if not items: return items elif isinstance(items, _removed_dup_types): return items elif not hasattr(items, '__iter__') and not hasattr(items, '__getitem__'): return items _items = items if in_reverse...
With maximum performance, iterate over items and return unique ordered values. :param items: an iterable of values: lists, tuples, strings, or generator :param in_reverse: if True, iterate backwards to remove initial duplicates (less performant) :param is_unhashable: if False, use a set to track duplicates;...
def rfind(values, value): if isinstance(values, STRING_TYPES): try: return values.rfind(value) except TypeError: # Python 3 compliance: search for str values in bytearray return values.rfind(type(values)(value, DEFAULT_ENCODING)) else: try: ...
:return: the highest index in values where value is found, or -1
def rindex(values, value): if isinstance(values, STRING_TYPES): try: return values.rindex(value) except TypeError: # Python 3 compliance: search for str values in bytearray return values.rindex(type(values)(value, DEFAULT_ENCODING)) else: return ...
:return: the highest index in values where value is found, else raise ValueError
def reduce_value(value, default=EMPTY_STR): if hasattr(value, '__len__'): vlen = len(value) if vlen == 0: return default elif vlen == 1: if isinstance(value, set): return value.pop() elif isinstance(value, _reduce_types): ...
:return: a single value from lists, tuples or sets with one item; otherwise, the value itself if not empty or the default if it is.
def wrap_value(value, include_empty=False): if value is None: return [None] if include_empty else [] elif hasattr(value, '__len__') and len(value) == 0: return [value] if include_empty else [] elif isinstance(value, _wrap_types): return [value] elif not hasattr(value, '__it...
:return: the value wrapped in a list unless it is already iterable (and not a dict); if so, empty values will be filtered out by default, and an empty list is returned.
def unit(self, unit): allowed_values = ["cm", "inch", "foot"] # noqa: E501 if unit is not None and unit not in allowed_values: raise ValueError( "Invalid value for `unit` ({0}), must be one of {1}" # noqa: E501 .format(unit, allowed_values) ...
Sets the unit of this Dimensions. :param unit: The unit of this Dimensions. :type: str
def map_names(lang="en"): cache_name = "map_names.%s.json" % lang data = get_cached("map_names.json", cache_name, params=dict(lang=lang)) return dict([(item["id"], item["name"]) for item in data])
This resource returns an dictionary of the localized map names for the specified language. Only maps with events are listed - if you need a list of all maps, use ``maps.json`` instead. :param lang: The language to query the names for. :return: the response is a dictionary where the key is the map id an...
def maps(map_id=None, lang="en"): if map_id: cache_name = "maps.%s.%s.json" % (map_id, lang) params = {"map_id": map_id, "lang": lang} else: cache_name = "maps.%s.json" % lang params = {"lang": lang} data = get_cached("maps.json", cache_name, params=params).get("maps") ...
This resource returns details about maps in the game, including details about floor and translation data on how to translate between world coordinates and map coordinates. :param map_id: Only list this map. :param lang: Show localized texts in the specified language. The response is a dictionary w...
def get_random_value(field): func = get_factory_func(field) if field.default is not None: if callable(field.default): return field.default() return field.default if field.choices: return random.choice(field.choices) return func(field)
Calls the dispatch method (``get_factory_func``) and passes the field obj argument to the callable returned. Returns: random value depending on field type and constraints in the field object
def get_value_based_inclusive_interval(cls, field, max_value=None): if field.max_value is None: field.max_value = max_value or MAX_LENGTH if field.min_value is None: field.min_value = 0 Interval = namedtuple('interval', ['start', 'stop']) return Interv...
This is applicable to fields with max_value and min_value as validators. Note: 1. This is different from fields with max_length as a validator 2. This means that the two methods based on value and length are almost the same method but for the max_* attribute ...
def make_string_field_value(cls, field): if field.regex is not None: raise NotImplementedError string_range = cls.get_range(field) return cls.get_random_string(string_range)
String Field has three constraints (apart from anything in the super class) Args: field (StringField): actual string field object from a model declaration Returns: random string value
def _async_recv(self): logging.info("Receive loop started") recbuffer = b"" while not self._stop_event.is_set(): time.sleep(0.01) try: recbuffer = recbuffer + self._socket.recv(1024) data = recbuffer.split(b'\r\n') ...
No raw bytes should escape from this, all byte encoding and decoding should be handling inside this function
def main(arguments=None): # setup the command-line util settings su = tools( arguments=arguments, docString=__doc__, logLevel="WARNING", options_first=False, projectName="fundmentals" ) arguments, settings, log, dbConn = su.setup() # UNPACK REMAINING CL...
The main function used when ``directory_script_runner.py`` is run as a single script from the cl, or when installed as a cl command
def Eoi(compiler, cont): '''end of parse_state''' return il.If(il.Ge(il.GetItem(il.parse_state, il.Integer(1)), il.Len(il.GetItem(il.parse_state, il.Integer(0)))), cont(TRUE), il.failcont(FALSE)f Eoi(compiler, cont): '''end of parse_state''' return il.If(il.Ge(il...
end of parse_state
def Boi(compiler, cont): '''end of parse_state''' return il.If(il.Le(il.GetItem(il.parse_state, il.Integer(1)),0), cont(TRUE), il.failcont(FALSE)f Boi(compiler, cont): '''end of parse_state''' return il.If(il.Le(il.GetItem(il.parse_state, il.Integer(1)),0), cont(TRUE), ...
end of parse_state
def get_database_table_column_names( dbConn, log, dbTable ): log.debug('starting the ``get_database_table_column_names`` function') sqlQuery = """SELECT * FROM %s LIMIT 1""" \ % (dbTable, ) # ############### >ACTION(S) ################ try: rows = readquery( ...
get database table column names **Key Arguments:** - ``dbConn`` -- mysql database connection - ``log`` -- logger - ``dbTable`` -- database tablename **Return:** - ``columnNames`` -- table column names **Usage:** To get the column names of a table in a given databa...
def normalize(df, style = 'mean'): if style == 'mean': df_mean,df_std = df.mean(),df.std() return (df-df_mean)/df_std elif style == 'minmax': col_min,col_max = df.min(),df.max() return (df-col_min)/(col_max-col_min) else: return style(df)
Returns a normalized version of a DataFrame or Series Parameters: df - DataFrame or Series The data to normalize style - function or string, default 'mean' The style to use when computing the norms. Takes 'mean' or 'minmax' to do mean or min-max normalization respectively. User-defin...
def norms(df, col_names = None,row_names = None,style = 'mean', as_group = False, axis = 0): if col_names is None: if row_names is not None: df = df.loc[row_names,:] else: if row_names is None: df = df.loc[:,col_names] else: df = df.loc[row_names,...
Returns a normalized version of the input Dataframe Parameters: df - pandas DataFrame The input data to normalize col_names - list or string, default None The column(s) to use when computing the norms row_names - list or string, default None The row(s) to use when computing the n...
def set_finished(self): component_name = self.get_component_name() self.log( logging.INFO, "Component [%s] is being marked as finished.", component_name) existing_state = self.__get_state(component_name) assert existing_state == fss.const...
This stores the number of items that have been pushed, and transitions the current component to the FINISHED state (which precedes the STOPPED state). The FINISHED state isn't really necessary unless methods/hooks are overridden to depend on it, but the count must be stored at one po...
def weight_unit(self, weight_unit): allowed_values = ["pound", "kilogram"] # noqa: E501 if weight_unit is not None and weight_unit not in allowed_values: raise ValueError( "Invalid value for `weight_unit` ({0}), must be one of {1}" # noqa: E501 .for...
Sets the weight_unit of this MeasurementSettings. :param weight_unit: The weight_unit of this MeasurementSettings. :type: str
def dimensions_unit(self, dimensions_unit): allowed_values = ["inch", "cm", "foot", "meter"] # noqa: E501 if dimensions_unit is not None and dimensions_unit not in allowed_values: raise ValueError( "Invalid value for `dimensions_unit` ({0}), must be one of {1}" # n...
Sets the dimensions_unit of this MeasurementSettings. :param dimensions_unit: The dimensions_unit of this MeasurementSettings. :type: str
def add_result_hook(self, hook: Type["QueryResultHook"]) -> Type["QueryResultHook"]: hook.next_hook = self._query_result_hook self._query_result_hook = hook return hook
Add a query result hook to the chain :param hook: hook to add :return: added hook (same as hook to add)
def already_resolved(self, pattern: QueryTriple) -> bool: if self.sparql_locked or pattern == (None, None, None): return True for resolved_node in self.resolved_nodes: if resolved_node != (None, None, None) and \ (pattern[0] == resolved_node[0] or res...
Determine whether pattern has already been loaded into the cache. The "wild card" - `(None, None, None)` - always counts as resolved. :param pattern: pattern to check :return: True it is a subset of elements already loaded
def add(self, t: RDFTriple) -> None: if self.chained_hook is not None: self.chained_hook.add(t)
Add a triple as a query result :param t: triple being added
def fix_base(fix_environ): def _is_android(): import os vm_path = os.sep+"system"+os.sep+"bin"+os.sep+"dalvikvm" if os.path.exists(vm_path) or os.path.exists(os.sep+"system"+vm_path): return True try: import android del android # Unused impo...
Activate the base compatibility.
def fix_subprocess(override_debug=False, override_exception=False): import subprocess # Exceptions if subprocess.__dict__.get("SubprocessError") is None: subprocess.SubprocessError = _Internal.SubprocessError if _InternalReferences.UsedCalledProcessError is None: if "CalledProcessE...
Activate the subprocess compatibility.
def fix_all(override_debug=False, override_all=False): fix_base(True) fix_builtins(override_debug) fix_subprocess(override_debug, override_all) return True
Activate the full compatibility.
def smart_scrub(df,col_name,error_rate = 0): scrubf = smart_scrubf(df,col_name,error_rate) scrubb = smart_scrubb(df,col_name,error_rate) return (scrubf, scrubb)
Scrubs from the front and back of an 'object' column in a DataFrame until the scrub would semantically alter the contents of the column. If only a subset of the elements in the column are scrubbed, then a boolean array indicating which elements have been scrubbed is appended to the dataframe. Returns a tup...
def smart_scrubf(df,col_name,error_rate = 0): scrubbed = "" while True: valcounts = df[col_name].str[:len(scrubbed)+1].value_counts() if not len(valcounts): break if not valcounts[0] >= (1-error_rate) * _utils.rows(df): break scrubbed=valcounts.index[...
Scrubs from the front of an 'object' column in a DataFrame until the scrub would semantically alter the contents of the column. If only a subset of the elements in the column are scrubbed, then a boolean array indicating which elements have been scrubbed is appended to the dataframe. Returns the string tha...
def smart_scrubb(df,col_name,error_rate = 0): scrubbed = "" while True: valcounts = df[col_name].str[-len(scrubbed)-1:].value_counts() if not len(valcounts): break if not valcounts[0] >= (1-error_rate) * _utils.rows(df): break scrubbed=valcounts.index...
Scrubs from the back of an 'object' column in a DataFrame until the scrub would semantically alter the contents of the column. If only a subset of the elements in the column are scrubbed, then a boolean array indicating which elements have been scrubbed is appended to the dataframe. Returns the string that...
def find_all_for_order(cls, order_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._find_all_for_order_with_http_info(order_id, **kwargs) else: (data) = cls._find_all_for_order_with_http_info(order_id, **kwargs) ...
Find shipping methods for order. Find all shipping methods suitable for an order. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.find_all_for_order(order_id, async=True) >>> result = thread.g...
def list_all_shipping_methods(cls, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._list_all_shipping_methods_with_http_info(**kwargs) else: (data) = cls._list_all_shipping_methods_with_http_info(**kwargs) return ...
List ShippingMethods Return a list of ShippingMethods This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_shipping_methods(async=True) >>> result = thread.get() :param async bool...
def extract(cls, obj): span = cls.extract_span(obj) if span: return span.context
Extract span context from the given object :param Any obj: Object to use as context :return: a SpanContext instance extracted from the inner span object or None if no such span context could be found.
def inject(cls, span, obj): obj.metadata['__parent-span__'] = dict() cls.inject_span(span, obj.metadata['__parent-span__'])
Injects the span context into a `carrier` object. :param opentracing.span.SpanContext span: the SpanContext instance :param Any obj: Object to use as context
def extract_tags(cls, obj): return dict(uuid=obj.uuid, entrypoint=obj.__class__.path)
Extract tags from the given object :param Any obj: Object to use as context :return: Tags to add on span :rtype: dict
def _postrun(cls, span, obj, **kwargs): for key, value in ResultSchema().dump(obj.result).items(): if isinstance(value, dict): try: flat_data = cls.filter_keys( cls.fix_additional_fields(value) ) ...
Trigger to execute just before closing the span :param opentracing.span.Span span: the SpanContext instance :param Any obj: Object to use as context :param dict kwargs: additional data
def fix_additional_fields(data): result = dict() for key, value in data.items(): if isinstance(value, dict): result.update(KserSpan.to_flat_dict(key, value)) else: result[key] = value return result
description of fix_additional_fields