Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
381,100
def is_running(self): if self._process: if self._process.returncode is None: return True else: self._process = None return False
Checks if the QEMU process is running :returns: True or False
381,101
def GetEventTypeString(self, event_type): if 0 <= event_type < len(self._EVENT_TYPES): return self._EVENT_TYPES[event_type] return .format(event_type)
Retrieves a string representation of the event type. Args: event_type (int): event type. Returns: str: description of the event type.
381,102
def to_funset(self, lname="clamping", cname="clamped"): fs = set() for i, clamping in enumerate(self): fs.add(gringo.Fun(lname, [i])) fs = fs.union(clamping.to_funset(i, cname)) return fs
Converts the list of clampings to a set of `gringo.Fun`_ instances Parameters ---------- lname : str Predicate name for the clamping id cname : str Predicate name for the clamped variable Returns ------- set Representation of...
381,103
def singular(plural): if plural.endswith(): return plural[:-3] + if plural.endswith(): return plural[:-1] raise ValueError( % (plural,))
Take a plural English word and turn it into singular Obviously, this doesn't work in general. It know just enough words to generate XML tag names for list items. For example, if we have an element called 'tracks' in the response, it will be serialized as a list without named items in JSON, but we need ...
381,104
def collect(self): if libvirt is None: self.log.error() return {} conn = libvirt.openReadOnly(None) conninfo = conn.getInfo() memallocated = 0 coresallocated = 0 totalcores = 0 results = {} domIds...
Collect libvirt data
381,105
def get_time(self): command = const.CMD_GET_TIME response_size = 1032 cmd_response = self.__send_command(command, b, response_size) if cmd_response.get(): return self.__decode_time(self.__data[:4]) else: raise ZKErrorResponse("can't get time")
:return: the machine's time
381,106
def delete_shifts(self, shifts): url = "/2/shifts/?%s" % urlencode( {: ",".join(str(s) for s in shifts)}) data = self._delete_resource(url) return data
Delete existing shifts. http://dev.wheniwork.com/#delete-shift
381,107
def add_how(voevent, descriptions=None, references=None): if not voevent.xpath(): etree.SubElement(voevent, ) if descriptions is not None: for desc in _listify(descriptions): etree.SubElement(voevent.How, ) voevent.How.Descripti...
Add descriptions or references to the How section. Args: voevent(:class:`Voevent`): Root node of a VOEvent etree. descriptions(str): Description string, or list of description strings. references(:py:class:`voeventparse.misc.Reference`): A reference element (or list ...
381,108
def add(self, key, column_parent, column, consistency_level): self._seqid += 1 d = self._reqs[self._seqid] = defer.Deferred() self.send_add(key, column_parent, column, consistency_level) return d
Increment or decrement a counter. Parameters: - key - column_parent - column - consistency_level
381,109
def export(request, page_id, export_unpublished=False): try: if export_unpublished: root_page = Page.objects.get(id=page_id) else: root_page = Page.objects.get(id=page_id, live=True) except Page.DoesNotExist: return JsonResponse({: _()}) payload = export...
API endpoint of this source site to export a part of the page tree rooted at page_id Requests are made by a destination site's import_from_api view.
381,110
def summarycanvas(args): p = OptionParser(summarycanvas.__doc__) opts, args = p.parse_args(args) if len(args) < 1: sys.exit(not p.print_help()) for vcffile in args: counter = get_gain_loss_summary(vcffile) pf = op.basename(vcffile).split(".")[0] print(pf + " " + ...
%prog summarycanvas output.vcf.gz Generate tag counts (GAIN/LOSS/REF/LOH) of segments in Canvas output.
381,111
def byte_adaptor(fbuffer): if six.PY3: strings = fbuffer.read().decode() fbuffer = six.StringIO(strings) return fbuffer else: return fbuffer
provides py3 compatibility by converting byte based file stream to string based file stream Arguments: fbuffer: file like objects containing bytes Returns: string buffer
381,112
def paintNormal( self, painter ): rect = self.rect() x = 0 y = self.padding() w = rect.width() h = rect.height() - (2 * self.padding()) - 1 radius = self.borderRadius() color =...
Paints this item as the normal look. :param painter | <QPainter>
381,113
def toString(self): string = "Layer : (Kind: %s, Size: %d, Active: %d, Frozen: %d)\n" % ( self.name, self.kind, self.size, self.active, self.frozen) if (self.type == ): string += toStringArray(, self.target, self.displayWidth) string += toStringArray(, self.acti...
Returns a string representation of Layer instance.
381,114
def _as_versioned_jar(self, internal_target): jar, _ = internal_target.get_artifact_info() pushdb_entry = self._get_db(internal_target).get_entry(internal_target) return jar.copy(rev=pushdb_entry.version().version())
Fetches the jar representation of the given target, and applies the latest pushdb version.
381,115
def _draw(self, prev_angle = None, prev_length = None): if (prev_angle is None) or (prev_length is None): (length, angle)= np.unravel_index(self.drawFrom(, self.getrand()), self.firstLenAng_shape) angle = angle-((self.firs...
Draws a new length- and angle-difference pair and calculates length and angle absolutes matching the last saccade drawn. Parameters: prev_angle : float, optional The last angle that was drawn in the current trajectory prev_length : float, optional ...
381,116
def name_insertion(sbjct_seq, codon_no, sbjct_nucs, aa_alt, start_offset): start_codon_no = codon_no - 1 if len(sbjct_nucs) == 3: start_codon_no = codon_no start_codon = get_codon(sbjct_seq, start_codon_no, start_offset) end_codon = get_codon(sbjct_seq, codon_no, start_offset) pos_name ...
This function is used to name a insertion mutation based on the HGVS recommendation.
381,117
def convertFsDirWavToWav(dirName, Fs, nC): types = (dirName+os.sep+,) filesToProcess = [] for files in types: filesToProcess.extend(glob.glob(files)) newDir = dirName + os.sep + "Fs" + str(Fs) + "_" + "NC"+str(nC) if os.path.exists(newDir) and newDir!=".": shutil.rmtree...
This function converts the WAV files stored in a folder to WAV using a different sampling freq and number of channels. ARGUMENTS: - dirName: the path of the folder where the WAVs are stored - Fs: the sampling rate of the generated WAV files - nC: the number of channesl of the ge...
381,118
def month_name_to_number(month, to_int=False): number = { : , : , : , : , : , : , : , : , : , : , : , : , }.get(month) return int(number) if to_int else number
Convert a month name (MMM) to its number (01-12). Args: month (str): 3-letters string describing month. to_int (bool): cast number to int or not. Returns: str/int: the month's number (between 01 and 12).
381,119
def figsize(x=8, y=7., aspect=1.): mpl.rcParams.update({: (x*aspect, y)})
manually set the default figure size of plots ::Arguments:: x (float): x-axis size y (float): y-axis size aspect (float): aspect ratio scalar
381,120
def read_ndk_version(ndk_dir): try: with open(join(ndk_dir, )) as fileh: ndk_data = fileh.read() except IOError: info( ) return for line in ndk_data.split(): if line.startswith(): break else: info( ) ...
Read the NDK version from the NDK dir, if possible
381,121
def get_as_nullable_datetime(self, key): value = self.get(key) return DateTimeConverter.to_nullable_datetime(value)
Converts map element into a Date or returns None if conversion is not possible. :param key: an index of element to get. :return: Date value of the element or None if conversion is not supported.
381,122
def _do_highlight(content, query, tag=): for term in query: term = term.decode() for match in re.findall(, term): match_re = re.compile(match, re.I) content = match_re.sub( % (tag, term, tag), content) return content
Highlight `query` terms in `content` with html `tag`. This method assumes that the input text (`content`) does not contain any special formatting. That is, it does not contain any html tags or similar markup that could be screwed up by the highlighting. Required arguments: ...
381,123
def get_json_results(self, response): try: print ("CODE 429, sleeping for {timeout} seconds").format(timeout=str(timeout)) time.sleep(timeout) except (AttributeError, ValueError) as e: if not self.silent_fail: ...
Parses the request result and returns the JSON object. Handles all errors.
381,124
def _index_idiom(el_name, index, alt=None): el_index = "%s[%d]" % (el_name, index) if index == 0: cond = "%s" % el_name else: cond = "len(%s) - 1 >= %d" % (el_name, index) output = IND + " return output + IND + "%s = %s if %s else %s\n\n" % ( el_name, el_index...
Generate string where `el_name` is indexed by `index` if there are enough items or `alt` is returned. Args: el_name (str): Name of the `container` which is indexed. index (int): Index of the item you want to obtain from container. alt (whatever, default None): Alternative value. Re...
381,125
def register_date_conversion_handler(date_specifier_patterns): def _decorator(func): global DATE_SPECIFIERS_CONVERSION_HANDLERS DATE_SPECIFIERS_CONVERSION_HANDLERS[DATE_SPECIFIERS_REGEXES[date_specifier_patterns]] = func return func return _decorator
Decorator for registering handlers that convert text dates to dates. Args: date_specifier_patterns (str): the date specifier (in regex pattern format) for which the handler is registered
381,126
def http_method(self, method): self.build_url() try: response = self.get_http_method(method) is_success = response.ok try: response_message = response.json() except ValueError: response_message = response.text ...
Execute the given HTTP method and returns if it's success or not and the response as a string if not success and as python object after unjson if it's success.
381,127
def _get_cache_key(self, args, kwargs): hash_input = json.dumps({: self.name, : args, : kwargs}, sort_keys=True) return hashlib.md5(hash_input).hexdigest()
Returns key to be used in cache
381,128
def get_evidence(self, relation): provenance = relation.get() text = None context = None if provenance: sentence_tag = provenance[0].get() if sentence_tag and in sentence_tag: sentence_id = sentence_tag[] sentenc...
Return the Evidence object for the INDRA Statment.
381,129
def get_macs(vm_): * macs = [] nics = get_nics(vm_) if nics is None: return None for nic in nics: macs.append(nic) return macs
Return a list off MAC addresses from the named vm CLI Example: .. code-block:: bash salt '*' virt.get_macs <vm name>
381,130
def launch_job(job_spec): project_id = "projects/{}".format( text_encoder.native_to_unicode(default_project())) credentials = GoogleCredentials.get_application_default() cloudml = discovery.build("ml", "v1", credentials=credentials, cache_discovery=False) request = cloudml.p...
Launch job on ML Engine.
381,131
def tokenize_paragraphs(cls, text): paragraphs = [] paragraphs_first_pass = text.split() for p in paragraphs_first_pass: paragraphs_second_pass = re.split(, p) paragraphs += paragraphs_second_pass paragraphs = [p for p in paragraphs if p] ...
Convert an input string into a list of paragraphs.
381,132
def validate_url(url): if not isinstance(url, basestring): raise TypeError("url must be a string, not %r"%type(url)) url = url.lower() proto_addr = url.split() assert len(proto_addr) == 2, %url proto, addr = proto_addr assert proto in [,,,,], "Invalid protocol: %r"%proto ...
validate a url for zeromq
381,133
def _etextno_to_uri_subdirectory(etextno): str_etextno = str(etextno).zfill(2) all_but_last_digit = list(str_etextno[:-1]) subdir_part = "/".join(all_but_last_digit) subdir = "{}/{}".format(subdir_part, etextno) return subdir
Returns the subdirectory that an etextno will be found in a gutenberg mirror. Generally, one finds the subdirectory by separating out each digit of the etext number, and uses it for a directory. The exception here is for etext numbers less than 10, which are prepended with a 0 for the directory traversa...
381,134
def _dfromtimestamp(timestamp): try: return datetime.date.fromtimestamp(timestamp) except OSError: timestamp -= time.timezone d = datetime.date(1970, 1, 1) + datetime.timedelta(seconds=timestamp) if _isdst(d): timestamp += 3600 d = datetime.date(1970,...
Custom date timestamp constructor. ditto
381,135
def tag_wordnet(self, **kwargs): global wordnet_tagger if wordnet_tagger is None: wordnet_tagger = WordnetTagger() self.__wordnet_tagger = wordnet_tagger if len(kwargs) > 0: return self.__wordnet_tagger.tag_text(self, **kwargs) return self.__word...
Create wordnet attribute in ``words`` layer. See :py:meth:`~estnltk.text.wordnet_tagger.WordnetTagger.tag_text` method for applicable keyword arguments.
381,136
def get_lldp_neighbor_detail_input_request_type_get_request_interface_type(self, **kwargs): config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail input = ET.SubElement(get_lldp_neighbor_detail, "input") ...
Auto Generated Code
381,137
def get(self, name): path = self._get_cluster_storage_path(name) try: with open(path, ) as storage: cluster = self.load(storage) for node in sum(cluster.nodes.values(), []): if not hasattr(node, ): ...
Retrieves the cluster with the given name. :param str name: name of the cluster (identifier) :return: :py:class:`elasticluster.cluster.Cluster`
381,138
def send(remote_host=None): my_facts = get() if not remote_host: remote_host = nago.extensions.settings.get() remote_node = nago.core.get_node(remote_host) if not remote_node: raise Exception("Remote host with token= not found" % remote_host) response = remote_node.send_command(...
Send my facts to a remote host if remote_host is provided, data will be sent to that host. Otherwise it will be sent to master.
381,139
def register_entrypoints(self): for spec in iter_entry_points(self.entry_point_group): format_properties = {"name": spec.name} try: format_properties.update(spec.load()) except (DistributionNotFound, ImportError) as err: self.log.info(...
Look through the `setup_tools` `entry_points` and load all of the formats.
381,140
def add_info(self, data): for key in data: if key in (,,,,,,): raise ValueError("Sorry, cannot set build info with key of {}".format(key)) self.obj[key] = data[key] self.changes.append("Adding build info") return self
add info to a build
381,141
def remove_entity_tags(self): t spaCy entity tags. Note: Used if entity types are censored using FeatsFromSpacyDoc(tag_types_to_censor=...). ' terms_to_remove = [term for term in self._term_idx_store._i2val if any([word in SPACY_ENTITY_TAGS for word in term.sp...
Returns ------- A new TermDocumentMatrix consisting of only terms in the current TermDocumentMatrix that aren't spaCy entity tags. Note: Used if entity types are censored using FeatsFromSpacyDoc(tag_types_to_censor=...).
381,142
def _binary_enable_zero_disable_one_conversion(cls, val, **kwargs): try: if val is not None: if ord(val) == 0: return elif ord(val) == 1: return else: return .format(val) ...
converts a binary 0/1 to Disabled/Enabled
381,143
def transform_cur_commands_interactive(_, **kwargs): event_payload = kwargs.get(, {}) cur_commands = event_payload.get(, ).split() _transform_cur_commands(cur_commands) event_payload.update({ : .join(cur_commands) })
Transform any aliases in current commands in interactive into their respective commands.
381,144
def get(*args, **kwargs): from invenio.modules.oauth2server.models import Client q = Client.query return q.count(), q.all()
Get users.
381,145
def radii_of_curvature(self): rocs = [] for i, _ in enumerate(self): if 0 < i < len(self) - 1: rocs.append(radius_of_circumcircle( self[i - 1][], self[i][], self[i + 1][])) else: rocs.append(None) return rocs
The radius of curvature at each point on the Polymer primitive. Notes ----- Each element of the returned list is the radius of curvature, at a point on the Polymer primitive. Element i is the radius of the circumcircle formed from indices [i-1, i, i+1] of the primitve. T...
381,146
def add_option(self, section, option, value=None): if not self.config.has_section(section): message = self.add_section(section) if not message[0]: return message if not self.config.has_option(section, option): if value: ...
Creates an option for a section. If the section does not exist, it will create the section.
381,147
def compile(cls, code, path=None, libraries=None, contract_name=, extra_args=None): result = cls._code_or_path( code, path, contract_name, libraries, , extra_args) return result[]
Return the binary of last contract in code.
381,148
def load_imdb_df(dirpath=os.path.join(BIGDATA_PATH, ), subdirectories=((, ), (, , ))): dfs = {} for subdirs in tqdm(list(product(*subdirectories))): urlspath = os.path.join(dirpath, subdirs[0], .format(subdirs[1])) if not os.path.isfile(urlspath): if subdirs != (, ): d...
Walk directory tree starting at `path` to compile a DataFrame of movie review text labeled with their 1-10 star ratings Returns: DataFrame: columns=['url', 'rating', 'text'], index=MultiIndex(['train_test', 'pos_neg_unsup', 'id']) TODO: Make this more robust/general by allowing the subdirectories ...
381,149
def call_temperature(*args, **kwargs): *** res = dict() if not in kwargs: raise CommandExecutionError("Parameter (150~500) is missing") try: value = max(min(int(kwargs[]), 500), 150) except Exception as err: raise CommandExecutionError("Parameter does not contains an inte...
Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired Arguments: * **value**: 150~500. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.temperature value=150 salt ...
381,150
def display_dataset(self): header = self.dataset.header self.parent.setWindowTitle(basename(self.filename)) short_filename = short_strings(basename(self.filename)) self.idx_filename.setText(short_filename) self.idx_s_freq.setText(str(header[])) self.idx_n_chan.s...
Update the widget with information about the dataset.
381,151
def insert_mass_range_option_group(parser,nonSpin=False): massOpts = parser.add_argument_group("Options related to mass and spin " "limits for bank generation") massOpts.add_argument("--min-mass1", action="store", type=positive_float, required=True, he...
Adds the options used to specify mass ranges in the bank generation codes to an argparser as an OptionGroup. This should be used if you want to use these options in your code. Parameters ----------- parser : object OptionParser instance. nonSpin : boolean, optional (default=False) ...
381,152
def main(): parser = argparse.ArgumentParser(description=) parser.add_argument(, dest=, metavar=, help=, required=True) parser.add_argument(, dest=, type=int,...
Main function
381,153
def cli(env): manager = SoftLayer.DNSManager(env.client) zones = manager.list_zones() table = formatting.Table([, , , ]) table.align[] = table.align[] = for zone in zones: table.add_row([ zone[], zone[], zone[], zone[], ]) ...
List all zones.
381,154
def start(self): service_names = .join(self.service_names) _log.info(, service_names) SpawningProxy(self.containers).start() _log.debug(, service_names)
Start all the registered services. A new container is created for each service using the container class provided in the __init__ method. All containers are started concurrently and the method will block until all have completed their startup routine.
381,155
def map_clusters(self, size, sampled, clusters): ids = np.zeros(size, dtype=int) ids[:] = -2 ids[sampled] = clusters return ids
Translate cluster identity back to original data size. Parameters ---------- size : int size of original dataset sampled : array-like integer array describing location of finite values in original data. clusters : array-like intege...
381,156
def recursively_preempt_states(self): self.preempted = True self.paused = False self.started = False
Preempt the state
381,157
def trace(self, urls=None, **overrides): if urls is not None: overrides[] = urls return self.where(accept=, **overrides)
Sets the acceptable HTTP method to TRACE
381,158
def _data(self, received_data): if self.listener.on_data(received_data) is False: self.stop() raise ListenerError(self.listener.connection_id, received_data)
Sends data to listener, if False is returned; socket is closed. :param received_data: Decoded data received from socket.
381,159
def create_db_instance_read_replica(DBInstanceIdentifier=None, SourceDBInstanceIdentifier=None, DBInstanceClass=None, AvailabilityZone=None, Port=None, AutoMinorVersionUpgrade=None, Iops=None, OptionGroupName=None, PubliclyAccessible=None, Tags=None, DBSubnetGroupName=None, StorageType=None, CopyTagsToSnapshot=None, Mo...
Creates a DB instance for a DB instance running MySQL, MariaDB, or PostgreSQL that acts as a Read Replica of a source DB instance. All Read Replica DB instances are created as Single-AZ deployments with backups disabled. All other DB instance attributes (including DB security groups and DB parameter groups) are inh...
381,160
def parse_localclasspath(self, tup_tree): self.check_node(tup_tree, ) k = kids(tup_tree) if len(k) != 2: raise CIMXMLParseError( _format("Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " ...
Parse a LOCALCLASSPATH element and return the class path it represents as a CIMClassName object. :: <!ELEMENT LOCALCLASSPATH (LOCALNAMESPACEPATH, CLASSNAME)>
381,161
def mmi_ramp_roman(raster_layer): items = [] sorted_mmi_scale = sorted( earthquake_mmi_scale[], key=itemgetter()) for class_max in sorted_mmi_scale: colour = class_max[] label = % class_max[] ramp_item = QgsColorRampShader.ColorRampItem( class_max[], colour...
Generate an mmi ramp using range of 1-10 on roman. A standarised range is used so that two shakemaps of different intensities can be properly compared visually with colours stretched accross the same range. The colours used are the 'standard' colours commonly shown for the mercalli scale e.g. on w...
381,162
def valid(*things): for thing in things: if type(thing) is str and not os.path.exists(thing): return False if thing.valid is None: return False return True
Return True if all tasks or files are valid. Valid tasks have been completed already. Valid files exist on the disk.
381,163
def randoffset(self, rstate=None): if rstate is None: rstate = np.random return np.dot(self.axes, randsphere(self.n, rstate=rstate))
Return a random offset from the center of the ellipsoid.
381,164
def find_value_at_cursor(ast_tree, filename, line, col, root_env=gcl.default_env): q = gcl.SourceQuery(filename, line, col) rootpath = ast_tree.find_tokens(q) rootpath = path_until(rootpath, is_thunk) if len(rootpath) <= 1: return None tup = inflate_context_tuple(rootpath, root_env) try: i...
Find the value of the object under the cursor.
381,165
def is_cursor_on_first_line(self): cursor = self.textCursor() cursor.movePosition(QTextCursor.StartOfBlock) return cursor.atStart()
Return True if cursor is on the first line
381,166
def uninstall_host(trg_queue, *hosts, **kwargs): item_user = kwargs.pop(, None) item_group = kwargs.pop(, None) item_mode = kwargs.pop(, None) for host in hosts: try: down_host(trg_queue, host, user=item_user, group=item_group, mode=(_c.FSQ_ITEM_MODE i...
Idempotently uninstall a host queue, should you want to subvert FSQ_ROOT settings, merely pass in an abolute path
381,167
def sentiment(self, text, method = "vocabulary"): assert method == "vocabulary" or method == "rnn" endpoint = method == "vocabulary" and "sentiment" or "sentimentRNN" return self._er.jsonRequestAnalytics("/api/v1/" + endpoint, { "text": text })
determine the sentiment of the provided text in English language @param text: input text to categorize @param method: method to use to compute the sentiment. possible values are "vocabulary" (vocabulary based sentiment analysis) and "rnn" (neural network based sentiment classification) ...
381,168
def sg_summary_image(tensor, prefix=None, name=None): r prefix = if prefix is None else prefix + name = prefix + _pretty_name(tensor) if name is None else prefix + name if not tf.get_variable_scope().reuse: tf.summary.image(name + , tensor)
r"""Register `tensor` to summary report as `image` Args: tensor: A tensor to log as image prefix: A `string`. A prefix to display in the tensor board web UI. name: A `string`. A name to display in the tensor board web UI. Returns: None
381,169
def schema_completer(prefix): from c7n import schema load_resources() components = prefix.split() if components[0] in provider.clouds.keys(): cloud_provider = components.pop(0) provider_resources = provider.resources(cloud_provider) else: cloud_provider = provi...
For tab-completion via argcomplete, return completion options. For the given prefix so far, return the possible options. Note that filtering via startswith happens after this list is returned.
381,170
def check_status_code(response, codes=None): codes = codes or [httplib.OK] checker = ( codes if callable(codes) else lambda resp: resp.status_code in codes ) if not checker(response): raise exceptions.ApiError(response, response.json())
Check HTTP status code and raise exception if incorrect. :param Response response: HTTP response :param codes: List of accepted codes or callable :raises: ApiError if code invalid
381,171
def age(self): aff4_type = self.Get(self.Schema.TYPE) if aff4_type: return aff4_type.age else: return rdfvalue.RDFDatetime.Now()
RDFDatetime at which the object was created.
381,172
def align(self, referencewords, datatuple): targetwords = [] for i, (word,lemma,postag) in enumerate(zip(datatuple[0],datatuple[1],datatuple[2])): if word: subwords = word.split("_") for w in subwords: targetwords.append( (w, lemm...
align the reference sentence with the tagged data
381,173
def adjust_opts(in_opts, config): memory_adjust = config["algorithm"].get("memory_adjust", {}) out_opts = [] for opt in in_opts: if opt.startswith("-Xmx") or (opt.startswith("-Xms") and memory_adjust.get("direction") == "decrease"): arg = opt[:4] opt = "{arg}{val}".forma...
Establish JVM opts, adjusting memory for the context if needed. This allows using less or more memory for highly parallel or multicore supporting processes, respectively.
381,174
def transform(self, data, data_type=, content_type=None, compression_type=None, split_type=None, job_name=None): local_mode = self.sagemaker_session.local_mode if not local_mode and not data.startswith(): raise ValueError(.format(data)) if job_name is not ...
Start a new transform job. Args: data (str): Input data location in S3. data_type (str): What the S3 location defines (default: 'S3Prefix'). Valid values: * 'S3Prefix' - the S3 URI defines a key name prefix. All objects with this prefix will be used as ...
381,175
def parse(self, data, doctype): self.doctype = doctype self.lexer.lineno = 0 del self.errors[:] del self.warnings[:] self.lexer.lexerror = False ast = self.parser.parse(data, lexer=self.lexer) if self.lexer.lexerror: ast = None if ast ...
Parse an input string, and return an AST doctype must have WCADocument as a baseclass
381,176
def process_input(self, stream, value, rpc_executor): self.sensor_log.push(stream, value) if stream.important: associated_output = stream.associated_stream() self.sensor_log.push(associated_output, value) to_check = deque([x for x in self.roots]) ...
Process an input through this sensor graph. The tick information in value should be correct and is transfered to all results produced by nodes acting on this tick. Args: stream (DataStream): The stream the input is part of value (IOTileReading): The value to process ...
381,177
def _aggregate_metrics(self, session_group): if (self._request.aggregation_type == api_pb2.AGGREGATION_AVG or self._request.aggregation_type == api_pb2.AGGREGATION_UNSET): _set_avg_session_metrics(session_group) elif self._request.aggregation_type == api_pb2.AGGREGATION_MEDIAN: _set_me...
Sets the metrics of the group based on aggregation_type.
381,178
def set_settings_secret(self, password): if not isinstance(password, basestring): raise TypeError("password can only be an instance of type basestring") self._call("setSettingsSecret", in_p=[password])
Unlocks the secret data by passing the unlock password to the server. The server will cache the password for that machine. in password of type str The cipher key. raises :class:`VBoxErrorInvalidVmState` Virtual machine is not mutable.
381,179
def _split_op( self, identifier, hs_label=None, dagger=False, args=None): if self._isinstance(identifier, ): identifier = QnetAsciiDefaultPrinter()._print_SCALAR_TYPES( identifier.expr) name, total_subscript = self._split_identifier(identifier) to...
Return `name`, total `subscript`, total `superscript` and `arguments` str. All of the returned strings are fully rendered. Args: identifier (str or SymbolicLabelBase): A (non-rendered/ascii) identifier that may include a subscript. The output `name` will be t...
381,180
def _localize_inputs_command(self, task_dir, inputs, user_project): commands = [] for i in inputs: if i.recursive or not i.value: continue source_file_path = i.uri local_file_path = task_dir + + _DATA_SUBDIR + + i.docker_path dest_file_path = self._get_input_target_path(l...
Returns a command that will stage inputs.
381,181
def skip_build(self): skip_msg = self.config.get(, ) return ( os.environ.get() == or self.info[] or skip_msg in self.info[][] )
Check if build should be skipped
381,182
def feed(self, data): send = self._send_to_parser draw = self.listener.draw match_text = self._text_pattern.match taking_plain_text = self._taking_plain_text length = len(data) offset = 0 while offset < length: if taking_plain_text: ...
Consume some data and advances the state as necessary. :param str data: a blob of data to feed from.
381,183
def modify_signature(self, signature): dic = signature.to_creator(for_modify=True) self.request(, {: dic})
Modify an existing signature Can modify the content, contenttype and name. An unset attribute will not delete the attribute but leave it untouched. :param: signature a zobject.Signature object, with modified content/contentype/name, the id should be present and ...
381,184
def set_logger_level(logger_name, log_level=): s logging level ' logging.getLogger(logger_name).setLevel( LOG_LEVELS.get(log_level.lower(), logging.ERROR) )
Tweak a specific logger's logging level
381,185
def _realValue_to_float(value_str): if REAL_VALUE.match(value_str): value = float(value_str) else: value = None return value
Convert a value string that conforms to DSP0004 `realValue`, into the corresponding float and return it. The special values 'INF', '-INF', and 'NAN' are supported. Note that the Python `float()` function supports a superset of input formats compared to the `realValue` definition in DSP0004. For exampl...
381,186
def dump(data, stream=None, **kwds): class OrderedDumper(SafeDumper): pass def _dict_representer(dumper, data): return dumper.represent_mapping( original_yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, list(data.items())) def _long_str_representer(du...
Serialize a Python object into a YAML stream. If stream is None, return the produced string instead. Dict keys are produced in the order in which they appear in OrderedDicts. Safe version. If objects are not "conventional" objects, they will be dumped converted to string with the str()...
381,187
def file_sort(my_list): def alphanum_key(key): return [int(s) if s.isdigit() else s for s in re.split("([0-9]+)", key)] my_list.sort(key=alphanum_key) return my_list
Sort a list of files in a nice way. eg item-10 will be after item-9
381,188
def parse_checks(self, conf): checks = conf.get(, conf.get(, [])) checks = list(self.unpack_batches(checks)) checks = list(self.unpack_templates(checks, conf.get(, {}))) self.inject_missing_names(checks) for check in checks: self.inject_scenarios(check, conf....
Unpack configuration from human-friendly form to strict check definitions.
381,189
def UnicodeFromCodePage(string): codepage = ctypes.windll.kernel32.GetOEMCP() try: return string.decode("cp%s" % codepage) except UnicodeError: try: return string.decode("utf16", "ignore") except UnicodeError: return string.decode("utf8", "ignore")
Attempt to coerce string into a unicode object.
381,190
def _minimal_y(self, p): y0 = self.pattern_y y1 = y0 + self._pixelsize(p)/2. return y0 if self._count_pixels_on_line(y0, p) < self._count_pixels_on_line(y1, p) else y1
For the specified y and one offset by half a pixel, return the one that results in the fewest pixels turned on, so that when the thickness has been enforced to be at least one pixel, no extra pixels are needlessly included (which would cause double-width lines).
381,191
def load_config(strCsvCnfg, lgcTest=False, lgcPrint=True): dicCnfg = {} with open(strCsvCnfg, ) as fleConfig: csvIn = csv.reader(fleConfig, delimiter=, skipinitialspace=True) for lstTmp in csvIn: ...
Load py_pRF_mapping config file. Parameters ---------- strCsvCnfg : string Absolute file path of config file. lgcTest : Boolean Whether this is a test (pytest). If yes, absolute path of this function will be prepended to config file paths. lgcPrint : Boolean Print co...
381,192
def _setup_conn(**kwargs): kubeconfig = kwargs.get() or __salt__[]() kubeconfig_data = kwargs.get() or __salt__[]() context = kwargs.get() or __salt__[]() if (kubeconfig_data and not kubeconfig) or (kubeconfig_data and kwargs.get()): with tempfile.NamedTemporaryFile(prefix=, delete=False) ...
Setup kubernetes API connection singleton
381,193
def is_valid_data(obj): if obj: try: tmp = json.dumps(obj, default=datetime_encoder) del tmp except (TypeError, UnicodeDecodeError): return False return True
Check if data is JSON serializable.
381,194
def fetch(self, category=CATEGORY_BUILD): kwargs = {} items = super().fetch(category, **kwargs) return items
Fetch the builds from the url. The method retrieves, from a Jenkins url, the builds updated since the given date. :param category: the category of items to fetch :returns: a generator of builds
381,195
def is_read_only(cls, db: DATABASE_SUPPORTER_FWD_REF, logger: logging.Logger = None) -> bool: def convert_enums(row_): return [True if x == else (False if x == else None) for x in row_] ...
Do we have read-only access?
381,196
def cancel(self, mark_completed_as_cancelled=False): with self._lock: if not self._completed or mark_completed_as_cancelled: self._cancelled = True callbacks = self._prepare_done_callbacks() callbacks()
Cancel the future. If the future has not been started yet, it will never start running. If the future is already running, it will run until the worker function exists. The worker function can check if the future has been cancelled using the :meth:`cancelled` method. If the future has already been compl...
381,197
def clean_names(lines, ensure_unique_names=False, strip_prefix=False, make_database_safe=False): names = {} for row in lines: if strip_prefix: row[] = row[][row[].find() + 1:] if row[] is not None: row[] = row[][row[].find( ...
Clean the names. Options to: - strip prefixes on names - enforce unique names - make database safe names by converting - to _
381,198
def download_supplementary_files(self, directory=, download_sra=True, email=None, sra_kwargs=None, nproc=1): if sra_kwargs is None: sra_kwargs = dict() if directory == : dirpath = os.path.abspath(s...
Download supplementary data. .. warning:: Do not use parallel option (nproc > 1) in the interactive shell. For more details see `this issue <https://stackoverflow.com/questions/23641475/multiprocessing-working-in-python-but-not-in-ipython/23641560#23641560>`_ on SO. ...
381,199
def go_to_line(self, line): cursor = self.textCursor() cursor.setPosition(self.document().findBlockByNumber(line - 1).position()) self.setTextCursor(cursor) return True
Moves the text cursor to given line. :param line: Line to go to. :type line: int :return: Method success. :rtype: bool