Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
15,300
def make_data(self, message): if not isinstance(message, Message): return message return message.export(self.transport_content_type)
make data string from message according to transport_content_type Returns: str: message data
15,301
def iyang(imgIn, krnl, imgSeg, Cnt, itr=5): dim = imgIn.shape m = np.int32(np.max(imgSeg)) m_a = np.zeros(( m+1, itr ), dtype=np.float32) for jr in range(0,m+1): m_a[jr, 0] = np.mean( imgIn[imgSeg==jr] ) imgOut = np.copy(imgIn) for i in range(0, itr): if Cnt[]:...
partial volume correction using iterative Yang method imgIn: input image which is blurred due to the PSF of the scanner krnl: shift invariant kernel of the PSF imgSeg: segmentation into regions starting with 0 (e.g., background) and then next integer numbers itr: number of iteration (default 5)
15,302
def convert_references_json(ref_content, soup=None): "Check for references that will not pass schema validation, fix or convert them to unknown" if ( (ref_content.get("type") == "other") or (ref_content.get("type") == "book-chapter" and "editors" not in ref_content) or ...
Check for references that will not pass schema validation, fix or convert them to unknown
15,303
def post(self, request, bot_id, format=None): return super(StateList, self).post(request, bot_id, format)
Add a new state --- serializer: StateSerializer responseMessages: - code: 401 message: Not authenticated - code: 400 message: Not valid request
15,304
def _cleanup_pods(namespace, labels): api = kubernetes.client.CoreV1Api() pods = api.list_namespaced_pod(namespace, label_selector=format_labels(labels)) for pod in pods.items: try: api.delete_namespaced_pod(pod.metadata.name, namespace) logger.info(, pod.metadata.name) ...
Remove all pods with these labels in this namespace
15,305
def update_node_attributes(self, attributes_flags=int(Qt.ItemIsSelectable | Qt.ItemIsEnabled)): self.traced.value = foundations.trace.is_traced(self.__module) self.traced.roles[Qt.DisplayRole] = foundations.strings.to_string(self.traced.value).title()
Updates the Node attributes. :param attributes_flags: Attributes flags. :type attributes_flags: int :return: Method success. :rtype: bool
15,306
def run(self): case = self.case baseMVA = case.base_mva buses = self.case.connected_buses branches = case.online_branches generators = case.online_generators meas = self.measurements self.case.index_buses() self.case.index_branches() ...
Solves a state estimation problem.
15,307
def check_error(self, response, status, err_cd): " Check an error in the response." if not in response: return False if response[] != status: return False if not in response: return False if not isinstance(response[], list): r...
Check an error in the response.
15,308
def link(url, text=, classes=, target=, get="", **kwargs): if not (url.startswith() or url.startswith()): urlargs = {} for arg, val in kwargs.items(): if arg[:4] == "url_": urlargs[arg[4:]] = val url = reverse(url, kwargs=urlargs) if get: ...
Output a link tag.
15,309
def newline(self): self.carriage_return() if self._cy + (2 * self._ch) >= self._device.height: copy = self._backing_image.crop((0, self._ch, self._device.width, self._device.height)) self._backing_image.paste(copy, (0, 0)) self._...
Advances the cursor position ot the left hand side, and to the next line. If the cursor is on the lowest line, the displayed contents are scrolled, causing the top line to be lost.
15,310
def add_secondary_ip(self, ip_address, interface=1): log = logging.getLogger(self.cls_logger + ) eni_id = self.get_eni_id(interface) if eni_id is None: msg = . \ format(i=interface) log.error(msg) raise EC2UtilError...
Adds an IP address as a secondary IP address :param ip_address: String IP address to add as a secondary IP :param interface: Integer associated to the interface/device number :return: None :raises: AWSAPIError, EC2UtilError
15,311
def _systemd_notify_once(): notify_socket = os.getenv() if notify_socket: if notify_socket.startswith(): notify_socket = % notify_socket[1:] sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) with contextlib.closing(soc...
Send notification once to Systemd that service is ready. Systemd sets NOTIFY_SOCKET environment variable with the name of the socket listening for notifications from services. This method removes the NOTIFY_SOCKET environment variable to ensure notification is sent only once.
15,312
def gateways_info(): data = netifaces.gateways() results = {: {}} with suppress(KeyError): results[] = data[netifaces.AF_INET] results[][] = data[][netifaces.AF_INET] with suppress(KeyError): results[] = data[netifaces.AF_INET6] results[][] = data[][netifaces.AF_INE...
Returns gateways data.
15,313
def _set_visible(self, visibility, grid_index=None): if grid_index is None: for ax in self.flat_grid: ax.set_visible(visibility) else: if grid_index < 0 or grid_index >= len(self.grids): raise IndexError(.format(len(self.grids) - 1)) ...
Sets the visibility property of all axes.
15,314
def _has_y(self, kwargs): return (( in kwargs) or (self._element_y in kwargs) or (self._type == 3 and self._element_1my in kwargs))
Returns True if y is explicitly defined in kwargs
15,315
def save_image(image, filename=None): local_name = filename or .format(image) cli.save_image(image, local_name)
Saves a Docker image from the remote to a local files. For performance reasons, uses the Docker command line client on the host, generates a gzip-tarball and downloads that. :param image: Image name or id. :type image: unicode :param filename: File name to store the local file. If not provided, will us...
15,316
def body(quantity=2, separator=, wrap_start=, wrap_end=, html=False, sentences_quantity=3, as_list=False): return lorem_ipsum.paragraphs(quantity=quantity, separator=separator, wrap_start=wrap_start, wrap_end=wrap_end, html=html, ...
Return a random email text.
15,317
def select_many_with_index( self, collection_selector=IndexedElement, result_selector=lambda source_element, collection_element: collection_element): if self.closed(): raise ValueError("Attempt to call select_many_with_i...
Projects each element of a sequence to an intermediate new sequence, incorporating the index of the element, flattens the resulting sequence into one sequence and optionally transforms the flattened sequence using a selector function. Note: This method uses deferred execution. ...
15,318
def tag_labels(self): if not self.is_tagged(ANALYSIS): self.tag_analysis() if self.__ner_tagger is None: self.__ner_tagger = load_default_ner_tagger() self.__ner_tagger.tag_document(self) return self
Tag named entity labels in the ``words`` layer.
15,319
def stats_set_value(self, key, value=1): if not self._measurement: if not self.IGNORE_OOB_STATS: self.logger.warning( ) return self._measurement.set_value(key, value)
Set the specified key/value in the per-message measurements .. versionadded:: 3.13.0 .. note:: If this method is called when there is not a message being processed, a message will be logged at the ``warning`` level to indicate the value is being dropped. To suppress these warni...
15,320
def save_to_file(self, file_path, labels=None, predict_proba=True, show_predicted_value=True, **kwargs): file_ = open(file_path, , encoding=) file_.write(self.as_html(labels=labels, ...
Saves html explanation to file. . Params: file_path: file to save explanations to See as_html() for additional parameters.
15,321
def prepare_transaction(*, operation=, signers=None, recipients=None, asset=None, metadata=None, inputs=None): operation = _normalize_operation(operation) return _prepare_transaction( operation, signers=signers, recipients=recipients, ...
Prepares a transaction payload, ready to be fulfilled. Depending on the value of ``operation``, simply dispatches to either :func:`~.prepare_create_transaction` or :func:`~.prepare_transfer_transaction`. Args: operation (str): The operation to perform. Must be ``'CREATE'`` or ``'TRA...
15,322
def read_line(self, line): if self.ignore: return for i, char in enumerate(line): if char not in [, "\\': continue if self.single == char: self.single = None continue if self.single is not None: ...
Read a new line
15,323
def translate_wp_comment(self, e): comment_dict = {} comment_dict[] = e.find().text comment_dict[] = e.find().text comment_dict[] = e.find().text comment_dict[] = e.find().text comment_dict[] = "approved" if comment_dict[] == "1" else "rejected" comment_d...
<wp:comment> <wp:comment_id>1234</wp:comment_id> <wp:comment_author><![CDATA[John Doe]]></wp:comment_author> <wp:comment_author_email><![CDATA[info@adsasd.com]]></wp:comment_author_email> <wp:comment_author_url>http://myhomepage.com/</wp:comment_author_url> <wp:comment_author_IP><![CD...
15,324
def charts_slug_get(self, slug, **kwargs): kwargs[] = True if kwargs.get(): return self.charts_slug_get_with_http_info(slug, **kwargs) else: (data) = self.charts_slug_get_with_http_info(slug, **kwargs) return data
Chart A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysis on Questions instead. Charts are derived data; Pollster editors publish them and change them as editorial priorities ch...
15,325
def match(cls, event): if not in event: return False if not in event[]: return False k = event[][] if k in cls.trail_events: v = dict(cls.trail_events[k]) if isinstance(v[], six.string_types): ...
Match a given cwe event as cloudtrail with an api call That has its information filled out.
15,326
def is_rfc822(self) -> bool: ct_hdr = self.header.parsed.content_type if ct_hdr is None: return False else: return ct_hdr.content_type ==
True if the content-type of the message is ``message/rfc822``.
15,327
def register_layouts(layouts, app, url="/api/props/", brand="Pyxley"): def props(name): if name not in layouts: name = list(layouts.keys())[0] return jsonify({"layouts": layouts[name]["layout"]}) def apps(): paths = [] for i, k in enumerate(layouts....
register UILayout with the flask app create a function that will send props for each UILayout Args: layouts (dict): dict of UILayout objects by name app (object): flask app url (string): address of props; default is /api/props/
15,328
def register_preset(cls, name, preset): if cls._presets is None: cls._presets = {} cls._presets[name] = preset
Register a preset instance with the class of the hub it corresponds to. This allows individual plugin objects to automatically register themselves with a preset by using a classmethod of their own with only the name of the preset to register with.
15,329
def get_thread_info(self, enforce_re=True, latest_date=None): result = [] my_re = re.compile(self.topic_re) url = % (self.base_url) latest_date = self.parse_date(latest_date) if latest_date else None while url: kwargs = {} if not self.gh_info.user else {: ( ...
Return a json list with information about threads in the group. :param enforce_re=True: Whether to require titles to match regexp in self.topic_re. :param latest_date=None: Optional datetime.datetime for latest ...
15,330
def _logpdf(self, **kwargs): for p in self._params: if p not in kwargs.keys(): raise ValueError( .format(p)) if kwargs in self: log_pdf = self._lognorm + \ (self.dim - 1) * \ numpy.lo...
Returns the log of the pdf at the given values. The keyword arguments must contain all of parameters in self's params. Unrecognized arguments are ignored.
15,331
def dict_factory(self, cursor, row): d = {} for idx, col in enumerate(cursor.description): val = row[idx] name = col[0] if name == Field.Time_Stamp: d[col[0]] = str(val) continue if name == "Raw_A" or name == "Raw_B...
Sqlite callback accepting the cursor and the original row as a tuple. Simple return of JSON safe types. Args: cursor (sqlite cursor): Original cursory row (sqlite row tuple): Original row. Returns: dict: modified row.
15,332
def linestrings_intersect(line1, line2): intersects = [] for i in range(0, len(line1[]) - 1): for j in range(0, len(line2[]) - 1): a1_x = line1[][i][1] a1_y = line1[][i][0] a2_x = line1[][i + 1][1] a2_y = line1[][i + 1][0] b1_x = line2[][j...
To valid whether linestrings from geojson are intersected with each other. reference: http://www.kevlindev.com/gui/math/intersection/Intersection.js Keyword arguments: line1 -- first line geojson object line2 -- second line geojson object if(line1 intersects with other) return intersect point arra...
15,333
def spawn_missing_classes(self, context=None): if context is None: if self.context is not None: context = self.context else: frame = inspect.currentframe().f_back context = frame.f_locals del frame ...
Creates the appropriate python user relation classes from tables in the schema and places them in the context. :param context: alternative context to place the missing classes into, e.g. locals()
15,334
def dict_2_mat(data, fill = True): if any([type(k) != int for k in list(data.keys())]): raise RuntimeError("Dictionary cannot be converted to matrix, " + "not all keys are ints") base_shape = np.array(list(data.values())[0]).shape result_shape = list(base_shape) ...
Creates a NumPy array from a dictionary with only integers as keys and NumPy arrays as values. Dimension 0 of the resulting array is formed from data.keys(). Missing values in keys can be filled up with np.nan (default) or ignored. Parameters ---------- data : dict a dictionary with int...
15,335
def parse_version(package): init_file = f with open(init_file, , encoding=) as f: for line in f.readlines(): if in line: return line.split()[1].strip()[1:-1] return
Parse versions
15,336
def multigrad_dict(fun): "Takes gradients wrt all arguments simultaneously," "returns a dict mapping to " import funcsigs sig = funcsigs.signature(fun) def select(preds, lst): idx = lambda item: next( (i for i, pred in enumerate(preds) if pred(item)), len(preds)) resul...
Takes gradients wrt all arguments simultaneously,
15,337
def isprintable(string): string = string.strip() if not string: return True if sys.version_info[0] == 3: try: return string.isprintable() except Exception: pass try: return string.decode().isprintable() except Exception: ...
Return if all characters in string are printable. >>> isprintable('abc') True >>> isprintable(b'\01') False
15,338
def nlp(self, inputString, sourceTime=None, version=None): orig_inputstring = inputString inputString = re.sub(r, r, inputString).lower() inputString = re.sub(r|")(\s|$)\1 \3(\s|^)(\, r, inputString) startpos = 0 ...
Utilizes parse() after making judgements about what datetime information belongs together. It makes logical groupings based on proximity and returns a parsed datetime for each matched grouping of datetime text, along with location info within the given inputString. @type input...
15,339
def wifi_status(self): return self._info_json.get(CONST.STATUS, {}).get(CONST.WIFI_LINK)
Get the wifi status.
15,340
def get_usedby_and_readonly(self, id): uri = self.URI + "/" + id + "/usedby/readonly" return self._client.get(uri)
Gets the build plans details os teh selected plan script as per the selected attributes. Args: id: ID of the Plan Script. Returns: array of build plans
15,341
def update_body(app, pagename, templatename, context, doctree): STATIC_URL = context.get(, DEFAULT_STATIC_URL) online_builders = [ , , ] if app.builder.name == : if in context and context[] == : theme_css = else: theme_css = elif app.builder....
Add Read the Docs content to Sphinx body content. This is the most reliable way to inject our content into the page.
15,342
async def get_state(self): await self._protocol.send_command("getstate", callback=False) return await self._protocol.await_event()
Get the latest state change of QTM. If the :func:`~qtm.connect` on_event callback was set the callback will be called as well. :rtype: A :class:`qtm.QRTEvent`
15,343
def get_userinfo(self, access_token, id_token, payload): user_response = requests.get( self.OIDC_OP_USER_ENDPOINT, headers={ : .format(access_token) }, verify=self.get_settings(, True)) user_response.raise_for_status() ret...
Return user details dictionary. The id_token and payload are not used in the default implementation, but may be used when overriding this method
15,344
def status_message(self): if self.is_available: return "INSTALLED {0!s}" elif self.why and self.package: return "MISSING {0!s:<20}needed for {0.why}, part of the {0.package} package" elif self.why: return "MISSING {0!s:<20}needed for {0.why}" ...
Detailed message about whether the dependency is installed. :rtype: str
15,345
def P(self): try: return self._diff_op except AttributeError: self._diff_op = normalize(self.kernel, , axis=1) return self._diff_op
Diffusion operator (cached) Return or calculate the diffusion operator Returns ------- P : array-like, shape=[n_samples, n_samples] diffusion operator defined as a row-stochastic form of the kernel matrix
15,346
def _setup_aggregation(self, aggregator=None): from nefertari.elasticsearch import ES if aggregator is None: aggregator = ESAggregator aggregations_enabled = ( ES.settings and ES.settings.asbool()) if not aggregations_enabled: log.debug() ...
Wrap `self.index` method with ESAggregator. This makes `self.index` to first try to run aggregation and only on fail original method is run. Method is wrapped only if it is defined and `elasticsearch.enable_aggregations` setting is true.
15,347
def load(robot, container_name, slot, label=None, share=False): def is_ot_one_slot_name(s): return isinstance(s, str) and len(s) == 2 and s[0] in def convert_ot_one_slot_names(s): col = .index(slot[0]) row = int(slot[1]) - 1 slot_number = col + (row * robot.get_...
Examples -------- >>> from opentrons import containers >>> containers.load('96-flat', '1') <Deck>/<Slot 1>/<Container 96-flat> >>> containers.load('96-flat', '4', 'plate') <Deck>/<Slot 4>/<Container plate> >>> containers.load('non-existent-type', '4') # doctest: +ELLIPSIS Exception: Cont...
15,348
def put_method(restApiId=None, resourceId=None, httpMethod=None, authorizationType=None, authorizerId=None, apiKeyRequired=None, operationName=None, requestParameters=None, requestModels=None, requestValidatorId=None): pass
Add a method to an existing Resource resource. See also: AWS API Documentation :example: response = client.put_method( restApiId='string', resourceId='string', httpMethod='string', authorizationType='string', authorizerId='string', apiKeyRequired=True|F...
15,349
def url(self): if self._url is not None: url = self._url else: url = getattr(self.nb.metadata, , None) if url is not None: return nbviewer_link(url)
The url on jupyter nbviewer for this notebook or None if unknown
15,350
def convert_ages_to_calendar_year(self, er_ages_rec): if "age" not in list(er_ages_rec.keys()): return(er_ages_rec) if "age_unit" not in list(er_ages_rec.keys()): return(er_ages_rec) if er_ages_rec["age_unit"] == "": return(er_ages_rec) if er...
convert all age units to calendar year Parameters ---------- er_ages_rec : Dict type object containing preferbly at least keys 'age', 'age_unit', and either 'age_range_high', 'age_range_low' or 'age_sigma' Returns ------- er_ages_rec : Same dict ...
15,351
def query(self): if self._rawquery==True: return self.__query return flatten(self.__query)
The mongo query object which would be executed if this Query object were used
15,352
def _create_raw_data(self): result = {} for section in self.get_sections(): result[section.get()] = return result
Gathers the different sections ids and creates a string as first cookie data. :return: A dictionary like: {'analyses':'all','analysisrequest':'all','worksheets':'all'}
15,353
def start(self): if self._send_greenlet is None: self._send_greenlet = gevent.spawn(self._send_loop)
Start the message sending loop.
15,354
def strip_unreferenced_labels(asm_lines): asm_stripped = [] for line in asm_lines: if re.match(r, line): label = line[0:line.find()] if not any([re.match(r + re.escape(label) + , l) for l in asm_lines]): line = ...
Strip all labels, which are never referenced.
15,355
def getattribute(value, arg): if hasattr(value, str(arg)): return getattr(value, arg) elif hasattr(value, ) and value.has_key(arg): return value[arg] elif numeric_test.match(str(arg)) and len(value) > int(arg): return value[int(arg)] else: return settings.TEMPLATE_S...
Gets an attribute of an object dynamically from a string name
15,356
def main(): print("\t\tCalculator\n\n") while True: user_input = input("expression or exit: ") if user_input == "exit": break try: print("The result is {0}".format(evaluate(user_input))) except Exception: print("invalid syntax!")...
simple user-interface
15,357
def pad_equal_whitespace(string, pad=None): if pad is None: pad = max(map(len, string.split())) + 1 return .join(( % pad).format(line) for line in string.split())
Given a multiline string, add whitespaces to every line so that every line has the same length.
15,358
def _rts_smoother_update_step(k, p_m , p_P, p_m_pred, p_P_pred, p_m_prev_step, p_P_prev_step, p_dynamic_callables): A = p_dynamic_callables.Ak(k,p_m,p_P) tmp = np.dot( A, p_P.T) if A.shape[0] == 1: G = tmp.T / p_P_pred else: ...
Rauch–Tung–Striebel(RTS) update step Input: ----------------------------- k: int Iteration No. Starts at 0. Total number of iterations equal to the number of measurements. p_m: matrix of size (state_dim, time_series_no) Filter mean on step k ...
15,359
def rename_tokens(docgraph_with_old_names, docgraph_with_new_names, verbose=False): old2new = create_token_mapping(docgraph_with_old_names, docgraph_with_new_names, verbose=verbose) if hasattr(docgraph_with_new_names, ): docgraph_with_new_names.renamed_...
Renames the tokens of a graph (``docgraph_with_old_names``) in-place, using the token names of another document graph (``docgraph_with_new_names``). Also updates the ``.tokens`` list of the old graph. This will only work, iff both graphs have the same tokenization.
15,360
def left_complement(clr): left = split_complementary(clr)[1] colors = complementary(clr) colors[3].h = left.h colors[4].h = left.h colors[5].h = left.h colors = colorlist( colors[0], colors[2], colors[1], colors[3], colors[4], colors[5] ) return colors
Returns the left half of the split complement. A list is returned with the same darker and softer colors as in the complementary list, but using the hue of the left split complement instead of the complement itself.
15,361
def create_git_release(self, tag, name, message, draft=False, prerelease=False, target_commitish=github.GithubObject.NotSet): assert isinstance(tag, (str, unicode)), tag assert isinstance(name, (str, unicode)), name assert isinstance(message, (str, unicode)), message assert isin...
:calls: `POST /repos/:owner/:repo/releases <http://developer.github.com/v3/repos/releases>`_ :param tag: string :param name: string :param message: string :param draft: bool :param prerelease: bool :param target_commitish: string or :class:`github.Branch.Branch` or :class...
15,362
def get_rendered_toctree(builder, docname, prune=False, collapse=True): fulltoc = build_full_toctree(builder, docname, prune=prune, collapse=collapse, ) rendered_toc = builder...
Build the toctree relative to the named document, with the given parameters, and then return the rendered HTML fragment.
15,363
def tail(collection, filter=None, projection=None, limit=0, timeout=None, aggregate=False): if not collection.options().get(, False): raise TypeError("Can only tail capped collections.") if timeout: if aggregate: cursor = cursor.max_time_ms(int(timeout * 1000)).max_await_time_ms(int(timeout * 1000)...
A generator which will block and yield entries as they are added to a capped collection. Only use this on capped collections; behaviour is undefined against non-tailable cursors. Accepts a timeout as an integer or floating point number of seconds, indicating how long to wait for a result. Correct operation requires...
15,364
def latex_defs_to_katex_macros(defs): r Example ------- import sphinxcontrib.katex as katex latex_macros = katex.import_macros_from_latex(latex_defs) katex_options = + latex_macros + ^\\def[ ]?( return macros
r'''Converts LaTeX \def statements to KaTeX macros. This is a helper function that can be used in conf.py to translate your already specified LaTeX definitions. https://github.com/Khan/KaTeX#rendering-options, e.g. `\def \e #1{\mathrm{e}^{#1}}` => `"\\e:" "\\mathrm{e}^{#1}"`' Example ------- ...
15,365
def validate_swagger_schema(schema_dir, resource_listing): schema_filepath = os.path.join(schema_dir, API_DOCS_FILENAME) swagger_spec_validator.validator12.validate_spec( resource_listing, urlparse.urljoin(, pathname2url(os.path.abspath(schema_filepath))), )
Validate the structure of Swagger schemas against the spec. **Valid only for Swagger v1.2 spec** Note: It is possible that resource_listing is not present in the schema_dir. The path is passed in the call so that ssv can fetch the api-declaration files from the path. :param resource_listing: Swag...
15,366
def results(self, trial_ids): metadata_folder = os.path.join(self.log_dir, constants.METADATA_FOLDER) dfs = [] for trial_id in trial_ids: result_file = os.path.join( metadata_folder, trial_id + "_"...
Accepts a sequence of trial ids and returns a pandas dataframe with the schema trial_id, iteration?, *metric_schema_union where iteration is an optional column that specifies the iteration when a user logged a metric, if the user supplied one. The iteration column is added if a...
15,367
def calledTwice(cls, spy): cls.__is_spy(spy) if not (spy.calledTwice): raise cls.failException(cls.message)
Checking the inspector is called twice Args: SinonSpy
15,368
def render_table(self, headers, rows, style=None): table = self.table(headers, rows, style) table.render(self._io)
Format input to textual table.
15,369
def append(self, parent, content): log.debug(, parent, content) if self.start(content): self.appender.append(parent, content) self.end(parent, content)
Append the specified L{content} to the I{parent}. @param parent: The parent node to append to. @type parent: L{Element} @param content: The content to append. @type content: L{Object}
15,370
def validate_response(self): if self.is_success(): return if self.details: error = self.details.get(, None) if error == PushResponse.ERROR_DEVICE_NOT_REGISTERED: raise DeviceNotRegisteredError(self) elif error == PushRes...
Raises an exception if there was an error. Otherwise, do nothing. Clients should handle these errors, since these require custom handling to properly resolve.
15,371
def promote_transaction( self, transaction, depth=3, min_weight_magnitude=None, ): if min_weight_magnitude is None: min_weight_magnitude = self.default_min_weight_magnitude return extended.PromoteTransactionCommand(self.a...
Promotes a transaction by adding spam on top of it. :return: Dict with the following structure:: { 'bundle': Bundle, The newly-published bundle. }
15,372
def parse_default_property_value(property_name, property_type_id, default_value_string): if property_type_id == PROPERTY_TYPE_EMBEDDED_SET_ID and default_value_string == : return set() elif property_type_id == PROPERTY_TYPE_EMBEDDED_LIST_ID and default_value_string == : return list() el...
Parse the default value string into its proper form given the property type ID. Args: property_name: string, the name of the property whose default value is being parsed. Used primarily to construct meaningful error messages, should the default value prove inva...
15,373
def keys_values(data, *keys): values = [] if is_mapping(data): for key in keys: if key in data: values.extend(ensure_list(data[key])) return values
Get an entry as a list from a dict. Provide a fallback key.
15,374
def eval_callx(self, exp): "dispatch for CallX" return (self.eval_agg_call if consumes_rows(exp) else self.eval_nonagg_call)(exp)
dispatch for CallX
15,375
def Satisfy_Constraints(U, B, BtBinv): RowsPerBlock = U.blocksize[0] ColsPerBlock = U.blocksize[1] num_block_rows = int(U.shape[0]/RowsPerBlock) UB = np.ravel(U*B) pyamg.amg_core.satisfy_constraints_helper(RowsPerBlock, ColsPerBlock, num...
U is the prolongator update. Project out components of U such that U*B = 0. Parameters ---------- U : bsr_matrix m x n sparse bsr matrix Update to the prolongator B : array n x k array of the coarse grid near nullspace vectors BtBinv : array Local inv(B_i.H*B_i) mat...
15,376
def publish_active_scene(self, scene_id): self.sequence_number += 1 self.publisher.send_multipart(msgs.MessageBuilder.scene_active(self.sequence_number, scene_id)) return self.sequence_number
publish changed active scene
15,377
def stream_time(self, significant_digits=3): try: return round( self._timestamps[] - self._timestamps[], significant_digits) except Exception as e: return None
:param significant_digits: int of the number of significant digits in the return :return: float of the time in seconds of how long the data took to stream
15,378
def date_time_this_century( self, before_now=True, after_now=False, tzinfo=None): now = datetime.now(tzinfo) this_century_start = datetime( now.year - (now.year % 100), 1, 1, tzinfo=tzinfo) next_century_start = datetime( ...
Gets a DateTime object for the current century. :param before_now: include days in current century before today :param after_now: include days in current century after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :r...
15,379
def _to_DOM(self): root_node = ET.Element() created_at_node = ET.SubElement(root_node, "created_at") created_at_node.text = \ timeformatutils.to_ISO8601(self.created_at)if self.created_at is not None else updated_at_node = ET.SubElement(root_node, "updated_at") ...
Dumps object data to a fully traversable DOM representation of the object. :returns: a ``xml.etree.Element`` object
15,380
def Search(pattern, s): if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].search(s)
Searches the string for the pattern, caching the compiled regexp.
15,381
def GetValues(self): if not self._registry_key and self._registry: self._GetKeyFromRegistry() if self._registry_key: return self._registry_key.GetValues() return iter([])
Retrieves all values within the key. Returns: generator[WinRegistryValue]: Windows Registry value generator.
15,382
def numa_nodemask_to_set(mask): result = set() for i in range(0, get_max_node() + 1): if __nodemask_isset(mask, i): result.add(i) return result
Convert NUMA nodemask to Python set.
15,383
def surfaceIntersection(actor1, actor2, tol=1e-06, lw=3): bf = vtk.vtkIntersectionPolyDataFilter() poly1 = actor1.GetMapper().GetInput() poly2 = actor2.GetMapper().GetInput() bf.SetInputData(0, poly1) bf.SetInputData(1, poly2) bf.Update() actor = Actor(bf.GetOutput(), "k", 1) actor....
Intersect 2 surfaces and return a line actor. .. hint:: |surfIntersect.py|_
15,384
def resolve_push_to(push_to, default_url, default_namespace): s default_index value (e.g. docker.io). :return: tuple: registry_url, namespace http://http://https:///.:localhost': registry_url = default_url namespace = push_to else: registry_url = protocol + parts[...
Given a push-to value, return the registry and namespace. :param push_to: string: User supplied --push-to value. :param default_url: string: Container engine's default_index value (e.g. docker.io). :return: tuple: registry_url, namespace
15,385
def backward(self, diff_x, influences, activations, **kwargs): diff_y = kwargs[] bmu = self._get_bmu(activations) influence = influences[bmu] x_update = np.multiply(diff_x, influence) y_update = np.multiply(diff_y, influence) return x_update, y_update
Backward pass through the network, including update. Parameters ---------- diff_x : numpy array A matrix containing the differences between the input and neurons. influences : numpy array A matrix containing the influence each neuron has on each other...
15,386
def remove_editor(self, username, *args, **kwargs): return self.add_editor(username=username, _delete=True, *args, **kwargs)
Remove an editor from this wiki page. :param username: The name or Redditor object of the user to remove. This method points to :meth:`add_editor` with _delete=True. Additional parameters are are passed to :meth:`add_editor` and subsequently into :meth:`~praw.__init__.BaseReddit.reque...
15,387
def from_hex(cls, value): if len(value) == 8: return cls(int(value, 16)) elif len(value) == 32: return cls(int(value, 16)) else: raise ValueError( % (value,))
Initialize a new network from hexadecimal notation.
15,388
def spawn_worker(params): setup_logging(params) log.info("Adding worker: idx=%s\tconcurrency=%s\tresults=%s", params.worker_index, params.concurrency, params.report) worker = Worker(params) worker.start() worker.join()
This method has to be module level function :type params: Params
15,389
def load_excel(self, filepath, **kwargs): try: df = pd.read_excel(filepath, **kwargs) if len(df.index) == 0: self.warning("Empty Excel file. Can not set the dataframe.") return self.df = df except Exception as e: se...
Set the main dataframe with the content of an Excel file :param filepath: url of the csv file to load, can be absolute if it starts with ``/`` or relative if it starts with ``./`` :type filepath: str :param kwargs: keyword arguments to pass to ...
15,390
def _formatter(self, x=None, y=None, z=None, s=None, label=None, **kwargs): def is_date(axis): fmt = axis.get_major_formatter() return (isinstance(fmt, mdates.DateFormatter) or isinstance(fmt, mdates.AutoDateFormatter)) def format_date(num): ...
Default formatter function, if no `formatter` kwarg is specified. Takes information about the pick event as a series of kwargs and returns the string to be displayed.
15,391
def expandRecs(G, RecCollect, nodeType, weighted): for Rec in RecCollect: fullCiteList = [makeID(c, nodeType) for c in Rec.createCitation(multiCite = True)] if len(fullCiteList) > 1: for i, citeID1 in enumerate(fullCiteList): if citeID1 in G: for ...
Expand all the citations from _RecCollect_
15,392
def get_asset_content(self, asset_content_id): return AssetContent(self._provider_session.get_asset_content(asset_content_id), self._config_map)
Gets the ``AssetContent`` specified by its ``Id``. In plenary mode, the exact ``Id`` is found or a ``NotFound`` results. Otherwise, the returned ``AssetContent`` may have a different ``Id`` than requested, such as the case where a duplicate ``Id`` was assigned to an ``AssetContent`` and...
15,393
def handle(self, *args, **options): cron_classes = options[] if cron_classes: cron_class_names = cron_classes else: cron_class_names = getattr(settings, , []) try: crons_to_run = [get_class(x) for x in cron_class_names] except Excepti...
Iterates over all the CRON_CLASSES (or if passed in as a commandline argument) and runs them.
15,394
def list_path(root_dir): res = [] if os.path.isdir(root_dir): for name in os.listdir(root_dir): res.append(name) return res
List directory if exists. :param dir: str :return: list
15,395
def get_valences(self, structure): els = [Element(el.symbol) for el in structure.composition.elements] if not set(els).issubset(set(BV_PARAMS.keys())): raise ValueError( "Structure contains elements not in set of BV parameters!" ) if se...
Returns a list of valences for the structure. This currently works only for ordered structures only. Args: structure: Structure to analyze Returns: A list of valences for each site in the structure (for an ordered structure), e.g., [1, 1, -2] or a list of li...
15,396
def _get_menu_meta_width(self, max_width, complete_state): if self._show_meta(complete_state): return min(max_width, max(get_cwidth(c.display_meta) for c in complete_state.current_completions) + 2) else: return 0
Return the width of the meta column.
15,397
def _GetEarliestYearFromFileEntry(self): file_entry = self.GetFileEntry() if not file_entry: return None stat_object = file_entry.GetStat() posix_time = getattr(stat_object, , None) if posix_time is None: posix_time = getattr(stat_object, , None) return None
Retrieves the year from the file entry date and time values. This function uses the creation time if available otherwise the change time (metadata last modification time) is used. Returns: int: year of the file entry or None.
15,398
def get_app_dir(app_name, roaming=True, force_posix=False): r if WIN: key = roaming and or folder = os.environ.get(key) if folder is None: folder = os.path.expanduser() return os.path.join(folder, app_name) if force_posix: return os.path.join(os.path.exp...
r"""Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system. To give you an idea, for an app called ``"Foo Bar"``, something like the following folders could be returned: Mac OS X: ``~/Library/Application Support/Foo...
15,399
def get_results(self, job_id): url = self._url( % job_id) return self.client.get(url)
Get results of a job Args: job_id (str): The ID of the job. See: https://auth0.com/docs/api/management/v2#!/Jobs/get_results