Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
357,900
def from_path_by_pattern(dir_path, pattern=list()): pattern = [i.lower() for i in pattern] def filter(winfile): relpath = os.path.relpath(winfile.abspath, dir_path).lower() for p in pattern: if p in relpath: return True ret...
Create a new FileCollection, and select all files except file matching ignore-rule:: dir_path = "your/path" fc = FileCollection.from_path_by_pattern( dir_path, pattern=["log"]) :param dir_path: the root directory you want to start with ...
357,901
def update_now_playing( self, artist, title, album=None, album_artist=None, duration=None, track_number=None, mbid=None, context=None, ): params = {"track": title, "artist": artist} if album: params["album...
Used to notify Last.fm that a user has started listening to a track. Parameters: artist (Required) : The artist name title (Required) : The track title album (Optional) : The album name. album_artist (Optional) : The album artist - if this dif...
357,902
def _build_named_object_ids(parameters): if isinstance(parameters, str): return [_build_named_object_id(parameters)] return [_build_named_object_id(parameter) for parameter in parameters]
Builds a list of NamedObjectId.
357,903
def update_text(self, selector, new_value, by=By.CSS_SELECTOR, timeout=settings.LARGE_TIMEOUT, retry=False): if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: timeout = self.__get_new_timeout(timeout) if page_utils.is_xpath_selector(selector): ...
The shorter version of update_text_value(), which clears existing text and adds new text into the text field. We want to keep the old version for backward compatibility.
357,904
def delete_unused_versions(self, versions_to_keep=10): environments = self.ebs.describe_environments(application_name=self.app_name, include_deleted=False) environments = environments[][][] versions_in_use = [] for env in environments: versions_in_use.appen...
Deletes unused versions
357,905
def _unify_keywords(): old_path = BASE_PATH.format() if os.path.exists(old_path): if os.path.isdir(old_path): for triplet in salt.utils.path.os_walk(old_path): for file_name in triplet[2]: file_path = .format(triplet[0], file_name) ...
Merge /etc/portage/package.keywords and /etc/portage/package.accept_keywords.
357,906
def _parse_method_data(self, method_name, method_data): method_params = {} method_models = {} if in method_data: for param in method_data[]: p = _Swagger.SwaggerParameter(param) if p.name: method_params[p.name] = True ...
Helper function to construct the method request params, models, request_templates and integration_type values needed to configure method request integration/mappings.
357,907
def profile(prof=None, instances=None, opts=None, **kwargs): if prof is None and in kwargs: prof = kwargs[] if prof is None: return {: } if instances is None and in kwargs: instances = kwargs[] if instances is None: return {: } client = _get_client() if...
Create a cloud vm with the given profile and instances, instances can be a list or comma-delimited string CLI Example: .. code-block:: bash salt-run cloud.profile prof=my-ec2 instances=node1,node2,node3
357,908
def update_image_location(self, timeline_json): if not timeline_json: return False if isinstance(timeline_json, (tuple, list)): timeline_json = timeline_json[0] event_code = timeline_json.get() if event_code != TIMELINE.CAPTUR...
Update the image location.
357,909
def get_setup(Cnt = {}): Cnt[] = DIRTOOLS Cnt[] = CMAKE_TLS_PAR Cnt[] = hrdwr_mu Cnt[] = MSVC_VRSN Cnt = get_gpu_constants(Cnt) if in globals() and PATHTOOLS!=: Cnt[] = PATHTOOLS if in globals() and RESPATH!=: Cnt[] = RESP...
Return a dictionary of GPU, mu-map hardware and third party set-up.
357,910
def new_batch(self): i = next(self.slicer) return self.X_all[i], self.Y_all[i]
Return a new batch of X and Y by taking a chunk of data from the complete X and Y
357,911
def merge(a, b): for item in a: setattr(b, item[0], item[1]) b.__metadata__ = b.__metadata__ return b
Merge all attributes and metadata from I{a} to I{b}. @param a: A I{source} object @type a: L{Object} @param b: A I{destination} object @type b: L{Object}
357,912
def _subscribed_event_count(self) -> int: event_counter = Counter() for key, values in self._events.items(): event_counter[key] = len(values) return sum(event_counter.values())
Returns the total amount of subscribed events. :return: Integer amount events. :rtype: int
357,913
def app_activate(caption): try: shell = win32com.client.Dispatch("WScript.Shell") shell.AppActivate(caption) except Exception as ex: print()
use shell to bring the application with caption to front
357,914
def crs_text_element(crs, feature, parent): _ = feature, parent crs_definition = QgsCoordinateReferenceSystem(crs) crs_description = crs_definition.description() text = crs_text[].format(crs=crs_description) return text
Retrieve coordinate reference system text string from definitions. Example usage: crs_text_element('EPSG:3857').
357,915
def install_program(self, extra_args): pip = Command(path.join(self.env, , )) args = [, self.raw_name, , .format(self.env_bin)] + list(extra_args) print_pretty("<BOLD>pip {}<END>\n".format(.join(args))) pip(args, _out=sys.stdout, _err=sys.stderr)...
Install the app to the virtualenv
357,916
def quote(c): i = ord(c) return ESCAPE + HEX[i//16] + HEX[i%16]
Quote a single character.
357,917
def send_reset_password_instructions(self, user): token = self.security_utils_service.generate_reset_password_token(user) reset_link = url_for(, token=token, _external=True) self.send_mail( _(), to=user.email, template=, ...
Sends the reset password instructions email for the specified user. Sends signal `reset_password_instructions_sent`. :param user: The user to send the instructions to.
357,918
def ticket_macro_apply(self, ticket_id, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/macros api_path = "/api/v2/tickets/{ticket_id}/macros/{id}/apply.json" api_path = api_path.format(ticket_id=ticket_id, id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/macros#show-ticket-after-changes
357,919
def tagged_projects( self, tag): self.refresh projectList = [] tag = tag.replace("@", "").lower() for p in self.projects: for aTag in p.tags: if "(" not in tag: aTag = aTag.split("(")[0] if a...
*return a list of projects contained within this taskpaper object filtered by a given tag* **Key Arguments:** - ``tag`` -- the tag to filter the projects by. **Return:** - ``projectList`` -- the list of filtered projects **Usage:** To filter the projects r...
357,920
def PrivateToPublicOpenSSH(key, host): ssh_rsa = + base64.b16encode() exponent = % (key.e,) if len(exponent) % 2: exponent = + exponent ssh_rsa += % (len(exponent) / 2,) ssh_rsa += exponent modulus = % (key.n,) if len(modulus) % 2: modulus = + modulus if modulus[0] in : ...
Computes the OpenSSH public key format given a private key.
357,921
def getCitations(self, field = None, values = None, pandasFriendly = True, counts = True): retCites = [] if values is not None: if isinstance(values, (str, int, float)) or not isinstance(values, collections.abc.Container): values = [values] for R in self: ...
Creates a pandas ready dict with each row a different citation the contained Records and columns containing the original string, year, journal, author's name and the number of times it occured. There are also options to filter the output citations with _field_ and _values_ # Parameters _field...
357,922
def ResourceEnum(ctx): return Enum( ctx, food=0, wood=1, stone=2, gold=3, decay=12, fish=17, default=Pass )
Resource Type Enumeration.
357,923
def debug_text_simple(self, text: str): self._debug_texts.append(self.to_debug_message(text))
Draws a text in the top left corner of the screen (up to a max of 6 messages it seems). Don't forget to add 'await self._client.send_debug'.
357,924
def _parse_contract_headers(self, table): years = [i.text() for i in table().items()] years.remove() return years
Parse the years on the contract. The years are listed as the headers on the contract. The first header contains 'Team' which specifies the player's current team and should not be included in the years. Parameters ---------- table : PyQuery object A PyQuery o...
357,925
def wrap_node(self, node, options): ll wrap our code with theirs in a nice package celery can execute. celery_taskcelery_task'](node) return self.celery_task(node)
\ celery registers tasks by decorating them, and so do we, so the user can pass a celery task and we'll wrap our code with theirs in a nice package celery can execute.
357,926
def _from_dict(cls, _dict): args = {} if in _dict: args[] = _dict.get() else: raise ValueError( classifier_id\ ) if in _dict: args[] = _dict.get() else: raise ValueError( name\)...
Initialize a Classifier object from a json dictionary.
357,927
def _extract_country_code(number): if len(number) == 0 or number[0] == U_ZERO: return (0, number) for ii in range(1, min(len(number), _MAX_LENGTH_COUNTRY_CODE) + 1): try: country_code = int(number[:ii]) if country_code in COUNTRY_CODE_TO_REGION_CODE: ...
Extracts country calling code from number. Returns a 2-tuple of (country_calling_code, rest_of_number). It assumes that the leading plus sign or IDD has already been removed. Returns (0, number) if number doesn't start with a valid country calling code.
357,928
def build_routes(iface, **settings): * opts = _parse_routes(iface, settings) try: template = JINJA.get_template() except jinja2.exceptions.TemplateNotFound: log.error() return add_routecfg = template.render(route_type=, routes=opts[], ...
Add route scripts for a network interface using up commands. CLI Example: .. code-block:: bash salt '*' ip.build_routes eth0 <settings>
357,929
def run_on_opencv_image(self, image): predictions = self.compute_prediction(image) top_predictions = self.select_top_predictions(predictions) result = image.copy() if self.show_mask_heatmaps: return self.create_mask_montage(result, top_predictions) result = ...
Arguments: image (np.ndarray): an image as returned by OpenCV Returns: prediction (BoxList): the detected objects. Additional information of the detection properties can be found in the fields of the BoxList via `prediction.fields()`
357,930
def GET_blockchain_ops( self, path_info, blockchain_name, blockheight ): try: blockheight = int(blockheight) assert check_block(blockheight) except: return self._reply_json({: }, status_code=400) if blockchain_name != : retur...
Get the name's historic name operations Reply the list of nameops at the given block height Reply 404 for blockchains other than those supported Reply 502 for any error we have in talking to the blockstack server
357,931
def send_message(self,body): m=Message(to_jid=self.room_jid.bare(),stanza_type="groupchat",body=body) self.manager.stream.send(m)
Send a message to the room. :Parameters: - `body`: the message body. :Types: - `body`: `unicode`
357,932
def groupby_field(records, field_name, skip_none=True): return apply_groupby( records, lambda obj: getattr(obj, field_name), skip_none=skip_none)
Given a list of objects, group them into a dictionary by the unique values of a given field name.
357,933
def _deserialize(self, value, attr, data): try: return super()._deserialize(value, attr, data) except ValidationError as ex: if in ex.messages[0]: ex.messages[0] = raise
Override ``_deserialize`` for customizing the exception raised.
357,934
def validate_sqs_policy(self, accounts): sqs_queue_name = self.dbconfig.get(, self.ns) sqs_queue_region = self.dbconfig.get(, self.ns) sqs_account = AWSAccount.get(self.dbconfig.get(, self.ns)) session = get_aws_session(sqs_account) sqs = session.client(, region_name=sq...
Given a list of accounts, ensures that the SQS policy allows all the accounts to write to the queue Args: accounts (`list` of :obj:`Account`): List of accounts Returns: `None`
357,935
def update_window(turn_from, tick_from, turn_to, tick_to, updfun, branchd): if turn_from in branchd: for past_state in branchd[turn_from][tick_from+1:]: updfun(*past_state) for midturn in range(turn_from+1, turn_to): if midturn in branchd: for past_state in ...
Iterate over a window of time in ``branchd`` and call ``updfun`` on the values
357,936
def get_bootstrap_connectivity(self, measure_names, repeats=100, num_samples=None, plot=False, random_state=None): if num_samples is None: num_samples = np.sum(self.trial_mask_) cb = bootstrap_connectivity(measure_names, self.activations_[self.trial_mask_, :, :], ...
Calculate bootstrap estimates of spectral connectivity measures. Bootstrapping is performed on trial level. Parameters ---------- measure_names : {str, list of str} Name(s) of the connectivity measure(s) to calculate. See :class:`Connectivity` for supported measures. ...
357,937
def add_attempt(self): self.attempt += 1 self.attempt = min(self.attempt, self.max_check_attempts)
Add an attempt when a object is a non-ok state :return: None
357,938
def count_reads(self, l): if self.__paired: cmd = [self.__samtools, , , , , self.__bam, l] else: cmd = [self.__samtools, , , , , self.__bam, l] stdout = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout ret = int(st...
Iterate over the reads on a particular genome in the bam file. Parameters ---------- l : str A location.
357,939
def make_table(self, renderable): self._make_prefix() diffs = renderable.diff._diff if self._wrapcolumn: diffs = self._line_wrapper(diffs, renderable.diff.hide_expected) fromlist, tolist, flaglist = self._collect_lines(diffs) fro...
Makes unique anchor prefixes so that multiple tables may exist on the same page without conflict.
357,940
def usb_info(self): return UsbInformation(self._abilities.usb_vendor, self._abilities.usb_product, self._abilities.usb_class, self._abilities.usb_subclass, self._abilities.usb_protoco...
The camera's USB information.
357,941
def laid_out_slice_num(self, tensor_shape): ret = self.slicewise(lambda: tf.to_int32(0)) tensor_layout = self.tensor_layout(tensor_shape) for mesh_axis in tensor_layout.tensor_axis_to_mesh_axis: if mesh_axis is not None: def my_fn(x, pcoord, mesh_dim_size): return x * mesh_dim_s...
A LaidOutTensor with an int32 scalar, identical for identical slices. This is useful for synchronizing random operations. Args: tensor_shape: a TensorShape Returns: a LaidOutTensor where each slice is an integer scalar.
357,942
def _from_stream(cls, stream, blob, filename=None): image_header = _ImageHeaderFactory(stream) if filename is None: filename = % image_header.default_ext return cls(blob, filename, image_header)
Return an instance of the |Image| subclass corresponding to the format of the image in *stream*.
357,943
def _analyze_txt_config(self, config_string=None): self.log(u"Analyzing container with TXT config string") if config_string is None: self.log(u"Analyzing container with TXT config file") config_entry = self.container.entry_config_txt self.log([u"Found TXT co...
Analyze the given container and return the corresponding job. If ``config_string`` is ``None``, try reading it from the TXT config file inside the container. :param string config_string: the configuration string :rtype: :class:`~aeneas.job.Job`
357,944
def _detect_screen_size(use_curses, screen_lines_def): TERM = os.environ.get(,None) if (TERM== or TERM==) and sys.platform != : local_use_curses = use_curses else: local_use_curses = False if local_use_curses: import termios import curses ...
Attempt to work out the number of lines on the screen. This is called by page(). It can raise an error (e.g. when run in the test suite), so it's separated out so it can easily be called in a try block.
357,945
def as_namedtuple(self): d = self.as_dict() return namedtuple(, d.keys())(*d.values())
Export color register as namedtuple.
357,946
def mac_access_list_extended_hide_mac_acl_ext_seq_seq_id(self, **kwargs): config = ET.Element("config") mac = ET.SubElement(config, "mac", xmlns="urn:brocade.com:mgmt:brocade-mac-access-list") access_list = ET.SubElement(mac, "access-list") extended = ET.SubElement(access_list, ...
Auto Generated Code
357,947
def shot_create_task(self, *args, **kwargs): if not self.cur_shot: return task = self.create_task(element=self.cur_shot) if task: taskdata = djitemdata.TaskItemData(task) treemodel.TreeItem(taskdata, self.shot_task_model.root)
Create a new task :returns: None :rtype: None :raises: None
357,948
def make_interface_child(device_name, interface_name, parent_name): nb_device = get_(, , name=device_name) nb_parent = get_(, , device_id=nb_device[], name=parent_name) if nb_device and nb_parent: return update_interface(device_name, interface_name, lag=nb_parent[]) else: return Fal...
.. versionadded:: 2019.2.0 Set an interface as part of a LAG. device_name The name of the device, e.g., ``edge_router``. interface_name The name of the interface to be attached to LAG, e.g., ``xe-1/0/2``. parent_name The name of the LAG interface, e.g., ``ae13``. CLI Exa...
357,949
def comments(self,minutes=False): if self.comments==0: return self.log.debug("adding comments to plot") for i,t in enumerate(self.abf.comment_times): if minutes: t/=60.0 plt.axvline(t,color=,ls=) X1,X2,Y1,Y2=plt.axis() ...
Add comment lines/text to an existing plot. Defaults to seconds. Call after a plot has been made, and after margins have been set.
357,950
def registergrant(source=None, setspec=None): with open(source, ) as fp: data = json.load(fp) register_grant(data)
Harvest grants from OpenAIRE.
357,951
def get_centers(self): if isinstance(self.__centers, list): return self.__centers return self.__centers.tolist()
! @brief Returns list of centers of allocated clusters. @see process() @see get_clusters()
357,952
def get_create_api(self, resource): create_api = { : % resource.get_api_name(), : % resource.model.__name__, : [ { : , : % resource.model .__name__, : % resource.mode...
Generates the meta descriptor for the resource listing api.
357,953
def installed(name, pkgs=None, user=None, install_global=False, env=None): ret = {: name, : None, : , : {}} try: call = __salt__[](user=user, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret[] = False ...
Verify that the given package is installed and is at the correct version (if specified). .. code-block:: yaml ShellCheck-0.3.5: cabal: - installed: name The package to install user The user to run cabal install with install_global Install pack...
357,954
def get_active_window(self): window_ret = window_t(0) _libxdo.xdo_get_active_window(self._xdo, ctypes.byref(window_ret)) return window_ret.value
Get the currently-active window. Requires your window manager to support this. Uses ``_NET_ACTIVE_WINDOW`` from the EWMH spec.
357,955
def has_value(cls, value: int) -> bool: return any(value == item.value for item in cls)
True if specified value exists in int enum; otherwise, False.
357,956
def get(self): self.log.info() self.theseBatches, self.theseBatchParams = self._split_incoming_queries_into_batches( sources=self.uplist, searchParams=self.searchParams ) self._build_api_url_and_download_results() self.results,...
*get the namesearch object* **Return:** - ``results``
357,957
def get_list(cache_length=24, map_vendor_oids=True, cert_callback=None): if not _in_memory_up_to_date(cache_length): with memory_lock: if not _in_memory_up_to_date(cache_length): certs = [] for cert_bytes, trust_oids, reject_oids in extract_from_system(cert_...
Retrieves (and caches in memory) the list of CA certs from the OS. Includes trust information from the OS - purposes the certificate should be trusted or rejected for. Trust information is encoded via object identifiers (OIDs) that are sourced from various RFCs and vendors (Apple and Microsoft). This t...
357,958
def refallele(args): p = OptionParser(refallele.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) vcffile, = args fp = open(vcffile) for row in fp: if row[0] == : continue atoms = row.split() marker = "{0}:...
%prog refallele vcffile > out.refAllele Make refAllele file which can be used to convert PLINK file to VCF file.
357,959
def twopercent(station_code): temp = None try: fin = open( % (env.WEATHER_DATA_PATH, _basename(station_code, ))) for line in fin: value = re.search(, line) if value: temp = float(value.groups()[0]) except IOError...
Two percent high design temperature for a location. Degrees in Celcius Args: station_code (str): Weather Station Code Returns: float degrees Celcius
357,960
def scan_ids(self, *key_ranges): key_ranges = [(tuplify(s), tuplify(e)) for s, e in key_ranges] scanner = self.kvl.scan_keys(self.TABLE, *key_ranges) return imap(itemgetter(0), scanner)
Retrieve content ids in a range of ids. Returns a generator of ``content_id`` corresponding to the content identifier ranges given. `key_ranges` can be a possibly empty list of 2-tuples, where the first element of the tuple is the beginning of a range and the second element is the end ...
357,961
def calc_surface_intensity(self, factor=10): pixels = self.roi.pixels_interior nside_in = self.config[][] surface_intensity = self.kernel.pdf(pixels.lon,pixels.lat) for i in np.arange(1,5): nside_out = 2**i * nside_in ...
Calculate the surface intensity for each pixel in the interior region of the ROI. Pixels are adaptively subsampled around the kernel centroid out to a radius of 'factor * max_pixrad'. Parameters: ----------- factor : the radius of the oversample region in units of max_pixrad ...
357,962
def _get_file_version(self, infile): for line1 in infile: if line1.strip() != "[Pyspread save file version]": raise ValueError(_("File format unsupported.")) break for line2 in infile: return line2.strip()
Returns infile version string.
357,963
def _send_data(self, data): total_sent = 0 while total_sent < len(data): sent = self.socket.send(data[total_sent:].encode("ascii")) if sent == 0: self.close() raise RuntimeError("Socket connection dropped, " ...
Send data to the ADB server
357,964
def to_feature_importances(regressor_type, regressor_kwargs, trained_regressor): if is_oob_heuristic_supported(regressor_type, regressor_kwargs): n_estimators = len(trained_regressor.estimators_) denormalized_importances = trained_regresso...
Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing by the number of trees in the regression ensemble by multiplying again by the number of trees used. This enables prioritizing links that were inferred in a regression where lots of :param regre...
357,965
def order_by(self, *order_bys): self._order_bys = [] for ingr in order_bys: order_by = self._shelf.find(ingr, (Dimension, Metric)) self._order_bys.append(order_by) self.dirty = True return self
Add a list of ingredients to order by to the query. These can either be Dimension or Metric objects or strings representing order_bys on the shelf. The Order_by expression will be added to the query's order_by statement :param order_bys: Order_bys to add to the recipe. Order_bys can ...
357,966
def get_active_for(self, user, user_agent=_MARK, ip_address=_MARK): conditions = [LoginSession.user == user] if user_agent is not _MARK: if user_agent is None: user_agent = request.environ.get("HTTP_USER_AGENT", "") conditions.append(LoginSession.user_ag...
Return last known session for given user. :param user: user session :type user: `abilian.core.models.subjects.User` :param user_agent: *exact* user agent string to lookup, or `None` to have user_agent extracted from request object. If not provided at all, no filtering on user_a...
357,967
def date_to_datetime_tz( cr, table_name, user_field_name, date_field_name, datetime_field_name): cr.execute( % (table_name, user_field_name,)) for timezone, in cr.fetchall(): cr.execute("SET TIMEZONE=%s", (timezone,)) values = { : table_name, : date_...
Take the related user's timezone into account when converting date field to datetime in a given table. This function must be call in post migration script. :param table_name : Name of the table where the field is; :param user_field_name : The name of the user field (res.users); :param date_field_na...
357,968
def _execute_handler(self, p_command, p_todo_id=None, p_output=None): p_output = p_output or self._output self._console_visible = False self._last_cmd = (p_command, p_output == self._output) try: p_command = shlex.split(p_command) except ValueError as verr:...
Executes a command, given as a string.
357,969
def handle_hotmaps_results(permutation_result): if len(permutation_result[0]) == 6: mycols = [, , , , , ] else: mycols = [, , , , , , ] permutation_df = pd.DataFrame(permutation_result, columns=mycols) permutation_df[] = 1 for w in per...
Takes in output from multiprocess_permutation function and converts to a better formatted dataframe. Parameters ---------- permutation_result : list output from multiprocess_permutation Returns ------- permutation_df : pd.DataFrame formatted output suitable to save
357,970
def selector_production(self, tokens): validators = [] if self.peek(tokens, ): type_ = self.match(tokens, ) validators.append(self.type_production(type_)) if self.peek(tokens, ): key = self.match(tokens, ) validators.append(sel...
Production for a full selector.
357,971
def merge_modified_section_data(self): for section in self.sections: section_data_start = adjust_FileAlignment( section.PointerToRawData, self.OPTIONAL_HEADER.FileAlignment ) section_data_end = section_data_start+section.SizeOfRawData if sect...
Update the PE image content with any individual section data that has been modified.
357,972
def add_feed(self, feedlike, **kwargs): if in kwargs: fnum = kwargs[] del kwargs[] else: fnum = None if isinstance(feedlike, bFeed): munging = feedlike.munging if in kwargs: explicit_munging = kwar...
Add a feed to the Symbol Parameters ---------- feedlike : Feed or bFeed-like The feed template, or Feed object to be added. kwargs Munging instructions
357,973
def _set_nport_menu(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=nport_menu.nport_menu, is_container=, presence=False, yang_name="nport-menu", rest_name="nport", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_path...
Setter method for nport_menu, mapped from YANG variable /rbridge_id/ag/nport_menu (container) If this variable is read-only (config: false) in the source YANG file, then _set_nport_menu is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_np...
357,974
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter(.format( event.data_type)) event_values = event.CopyToDict() event_type = event_values.get(, None) if event_type is not None: event_values[] = self.GetEventTyp...
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
357,975
def auth_uri(self): return self.oauth.auth_uri(redirect_uri=self.redirect_uri, scope=self.scope)
The authorzation URL that should be provided to the user
357,976
def qth_pw(self, q): return heapq.nlargest(q + 2, self._T.iteritems(), key=operator.itemgetter(1))[-1]
returns the qth most probable element in the dawg.
357,977
def then(self, *tasks): nodes = [x.node for x in tasks] self.node.then(*nodes) return self
Interfaces the GraphNode `then` method
357,978
def stringify(obj, trimmable=False): if obj is None: return None elif isinstance(obj, (basestring, bool, int, long, float, complex)): return obj elif isinstance(obj, (list, set, tuple)): return [stringify(item, trimmable=trimmable) for item in obj] elif isinstance(obj, dict)...
Convert an object to a stringified version of this object where the initial object's attribute values have been stringified when these values are not native Python types. This function differs from the standard Python ``str`` as the latter returns a string version of object, while this function returns...
357,979
def makeThumbnail(inputFile, outputFile, thumbnailSize, outputFormat=): if Image is None: import PIL image = Image.open(inputFile) if thumbnailSize < max(image.size): if image.mode == : image = image.convert() elif image.mode == : ...
Make a thumbnail of the image stored at C{inputPath}, preserving its aspect ratio, and write the result to C{outputPath}. @param inputFile: The image file (or path to the file) to thumbnail. @type inputFile: C{file} or C{str} @param outputFile: The file (or path to the file) to write the thumbnail ...
357,980
def _S(kappa, alpha, beta): kappa = 1. * np.abs(kappa) alpha = 1. * alpha beta = 1. * np.abs(beta) a_plus_b = alpha + beta u = np.sqrt(kappa ** 2 + beta ** 2) if alpha == 0: alpha_scale = 0 else: alpha_scale = alpha * np.log((alpha + u) / a_plus_b) return u - beta -...
Compute the antiderivative of the Amos-type bound G on the modified Bessel function ratio. Note: Handles scalar kappa, alpha, and beta only. See "S <-" in movMF.R and utility function implementation notes from https://cran.r-project.org/web/packages/movMF/index.html
357,981
def isdisjoint(self, other): if other == FullSpace: return False else: for ls in self.local_factors: if isinstance(ls.label, StrLabel): return False for ls in other.local_factors: if isinstance(ls.label, Str...
Check whether two Hilbert spaces are disjoint (do not have any common local factors). Note that `FullSpace` is *not* disjoint with any other Hilbert space, while `TrivialSpace` *is* disjoint with any other HilbertSpace (even itself)
357,982
def finish_target(self, name): with self._lock: pbar = self._bar(name, 100, 100) if sys.stdout.isatty(): self.clearln() self._print(pbar) self._n_finished += 1 self._line = None
Finishes progress bar for a specified target.
357,983
def we_should_stop(self, start, start_): if start > self.finish or \ self.event.end_repeat is not None and \ start_ > self.event.end_repeat: return True else: return False
Checks 'start' to see if we should stop collecting upcoming events. 'start' should be a datetime.datetime, 'start_' should be the same as 'start', but it should be a datetime.date to allow comparison w/ end_repeat.
357,984
def consume_length_prefix(rlp, start): b0 = safe_ord(rlp[start]) if b0 < 128: return (str, 1, start) elif b0 < 128 + 56: return (str, b0 - 128, start + 1) elif b0 < 192: ll = b0 - 128 - 56 + 1 l = big_endian_to_int(rlp[start + 1:start + 1 + ll]) return ...
Read a length prefix from an RLP string. :param rlp: the rlp string to read from :param start: the position at which to start reading :returns: a tuple ``(type, length, end)``, where ``type`` is either ``str`` or ``list`` depending on the type of the following payload, ``length`...
357,985
def merge(self, other): print "MERGING", self, other other = self.coerce(other) if self.is_contradictory(other): raise Contradiction("Cannot merge %s and %s" % (self, other)) elif self.value is None and not other.value is None: self.r, self.g, self.b = ot...
Merges the values
357,986
def accept(self): return self._issue._nation._accept_issue(self._issue.id, self._id)
Accept the option. Returns ------- an awaitable of :class:`IssueResult`
357,987
def update_configs(self, release): git_repo = release[] git_cache = release[] if not os.path.isdir(git_cache): self.call([, , , git_repo, git_cache]) else: self.call([, , , ], cwd=git_cache) git_dir = release[] = os.path.join(release[], ...
Update the fedora-atomic.git repositories for a given release
357,988
def loop(self, events=[]): try: for e in events: if e.type == METAEVENT: e = self.MetaEvent(e) for func in self.event_funcs.get(e.type, []): func(self, self.gstate, e) except self.Message as e: retur...
Run the loop.
357,989
def boolValue(self): if self.lastValue == 1 or self.lastValue == "active": self._key = 1 self._boolKey = True else: self._key = 0 self._boolKey = False return self._boolKey
returns : (boolean) Value
357,990
def checksum(data): assert isinstance(data, bytes) assert len(data) >= MINIMUM_MESSAGE_SIZE - 2 assert len(data) <= MAXIMUM_MESSAGE_SIZE - 2 __checksum = 0 for data_byte in data: __checksum += data_byte __checksum = -(__checksum % 256) + 256 try: __checksum = bytes([__ch...
:return: int
357,991
def unpack_values(format_string, stream, verifier=None): try: message_bytes = stream.read(struct.calcsize(format_string)) if verifier: verifier.update(message_bytes) values = struct.unpack(format_string, message_bytes) except struct.error as error: raise Serializ...
Helper function to unpack struct data from a stream and update the signature verifier. :param str format_string: Struct format string :param stream: Source data stream :type stream: io.BytesIO :param verifier: Signature verifier object :type verifier: aws_encryption_sdk.internal.crypto.Verifier ...
357,992
def put_bits( self, value, count ): for _ in range( count ): bit = (value & 1) value >>= 1 if self.bits_reverse: if self.insert_at_msb: self.current_bits |= (bit << (self.bits_remaining-1)) ...
Push bits into the target. value Integer containing bits to push, ordered from least-significant bit to most-significant bit. count Number of bits to push to the target.
357,993
def error_removed_option(message: str): def f(_, param, value): if value is not None: raise click.NoSuchOption( f + message, ) return f
Takes a message and returns a callback that raises NoSuchOption if the value is not None. The message is used as an argument to NoSuchOption.
357,994
def getPhoneInfo(numb): cc text = str(numb) info = {} node = phonetree for c in text: chld = node[2].get(c) if chld is None: break if chld[1]: info = chld[1] node = chld return info
Walk the phone info tree to find the best-match info for the given number. Example: info = getPhoneInfo(17035551212) country = info.get('cc')
357,995
def pad_to_3d(a): a_pad = np.zeros([len(a), 3], dtype=a.dtype) a_pad[:, :a.shape[-1]] = a return a_pad
Return 1- or 2-dimensional cartesian vectors, converted into a 3-dimensional representation, with additional dimensional coordinates assumed to be zero. Parameters ---------- a: array, shape (n, d), d < 3 Returns ------- ap: array, shape (n, 3)
357,996
def parse_debug_object(response): "Parse the results of Redistypet response = nativestr(response) response = + response response = dict([kv.split() for kv in response.split()]) int_fields = (, , , ) for field in int_fields: if field in response: response[fiel...
Parse the results of Redis's DEBUG OBJECT command into a Python dict
357,997
def is_downloadable(self): is_plugin_avaiable = False if self.is_dnf: is_plugin_avaiable = self.is_package_installed( ) else: is_plugin_avaiable = self.is_package_installed( ) ...
Return if rpm is downloadable by the package command. Check if dnf or yum plugin package exists.
357,998
def _send_signed_request(url, payload): payload64 = _b64(json.dumps(payload).encode()) out = parse_account_key() header = get_boulder_header(out) protected = copy.deepcopy(header) protected["nonce"] = urlopen(DEFAULT_CA + "/directory").headers[] protected64 = _b64(json.dumps(protected).en...
Helper function to make signed requests to Boulder
357,999
def autodiscover(): from django.conf import settings try: from django.utils.module_loading import import_module except ImportError: from django.utils.importlib import import_module from django.utils.module_loading import module_has_submodule from backbone....
Auto-discover INSTALLED_APPS backbone_api.py modules.