Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
14,900
def from_ZNM(cls, Z, N, M, name=): df = pd.DataFrame.from_dict({: Z, : N, : M}).set_index([, ])[] df.name = name return cls(df=df, name=name)
Creates a table from arrays Z, N and M Example: ________ >>> Z = [82, 82, 83] >>> N = [126, 127, 130] >>> M = [-21.34, -18.0, -14.45] >>> Table.from_ZNM(Z, N, M, name='Custom Table') Z N 82 126 -21.34 127 -18.00 83 130 -14.4...
14,901
def run_synthetic_SGLD(): theta1 = 0 theta2 = 1 sigma1 = numpy.sqrt(10) sigma2 = 1 sigmax = numpy.sqrt(2) X = load_synthetic(theta1=theta1, theta2=theta2, sigmax=sigmax, num=100) minibatch_size = 1 total_iter_num = 1000000 lr_scheduler = SGLDScheduler(begin_rate=0.01, end_rate=0...
Run synthetic SGLD
14,902
def remove_notification_listener(self, notification_id): for v in self.notifications.values(): toRemove = list(filter(lambda tup: tup[0] == notification_id, v)) if len(toRemove) > 0: v.remove(toRemove[0]) return True return False
Remove a previously added notification callback. Args: notification_id: The numeric id passed back from add_notification_listener Returns: The function returns boolean true if found and removed, false otherwise.
14,903
def space(self,bins=None,units=None,conversion_function=convert_time,resolution=None,end_at_end=True,scale=None): if scale in [] or (scale is None and self.scale in []): return self.logspace(bins=bins,units=units,conversion_function=conversion_function,resolution=resolution,end_at_end=end_a...
Computes adequat binning for the dimension (on the values). bins: number of bins or None units: str or None conversion_function: function to convert units to other units resolution: step size or None end_at_end: Boolean ...
14,904
def parse(self, stream, mimetype, content_length, options=None): if ( self.max_content_length is not None and content_length is not None and content_length > self.max_content_length ): raise exceptions.RequestEntityTooLarge() if options is...
Parses the information from the given stream, mimetype, content length and mimetype parameters. :param stream: an input stream :param mimetype: the mimetype of the data :param content_length: the content length of the incoming data :param options: optional mimetype parameters (u...
14,905
def grid_expansion_costs(network, without_generator_import=False): def _get_transformer_costs(transformer): if isinstance(transformer.grid, LVGrid): return float(network.config[][]) elif isinstance(transformer.grid, MVGrid): return float(network.config[][]) def _get...
Calculates grid expansion costs for each reinforced transformer and line in kEUR. Attributes ---------- network : :class:`~.grid.network.Network` without_generator_import : Boolean If True excludes lines that were added in the generator import to connect new generators to the grid f...
14,906
def mangle_signature(sig, max_chars=30): s = re.sub(r"^\((.*)\)$", r"\1", sig).strip() s = re.sub(r"\\\\", "", s) s = re.sub(r"\\[^", "", s) args = [] opts = [] opt_re = re.compile(r"^(.*, |)([a-zA-Z0-9_*]+)=") while s: m = opt_re.search(s) if not m: ...
Reformat a function signature to a more compact form.
14,907
def register_type(cls, name): x = TypeDefinition(name, (cls,), ()) Validator.types_mapping[name] = x
Register `name` as a type to validate as an instance of class `cls`.
14,908
def VxLANTunnelState_originator_switch_info_switchIdentifier(self, **kwargs): config = ET.Element("config") VxLANTunnelState = ET.SubElement(config, "VxLANTunnelState", xmlns="http://brocade.com/ns/brocade-notification-stream") originator_switch_info = ET.SubElement(VxLANTunnelState, "o...
Auto Generated Code
14,909
def create_optimizer(name, **kwargs): if name.lower() in Optimizer.opt_registry: return Optimizer.opt_registry[name.lower()](**kwargs) else: raise ValueError( % name)
Instantiates an optimizer with a given name and kwargs. .. note:: We can use the alias `create` for ``Optimizer.create_optimizer``. Parameters ---------- name: str Name of the optimizer. Should be the name of a subclass of Optimizer. Case insensitive. k...
14,910
def isConnected(self, fromName, toName): for c in self.connections: if (c.fromLayer.name == fromName and c.toLayer.name == toName): return 1 return 0
Are these two layers connected this way?
14,911
def _submit(self, pool, args, callback): if self.config.args.single_threaded: callback(self.call_runner(*args)) else: pool.apply_async(self.call_runner, args=args, callback=callback)
If the caller has passed the magic 'single-threaded' flag, call the function directly instead of pool.apply_async. The single-threaded flag is intended for gathering more useful performance information about what appens beneath `call_runner`, since python's default profiling tools ignor...
14,912
def comments(self): record_numbers = range(2, self.fward) if not record_numbers: return data = b.join(self.read_record(n)[0:1000] for n in record_numbers) try: return data[:data.find(b)].decode().replace(, ) except IndexError: raise V...
Return the text inside the comment area of the file.
14,913
def _parse_tensor(self, indices=False): if indices: self.line = self._skip_lines(1) tensor = np.zeros((3, 3)) for i in range(3): tokens = self.line.split() if indices: tensor[i][0] = float(tokens[1]) tensor[i][1] = flo...
Parse a tensor.
14,914
def downstream(self, f, n=1): if f.strand == -1: return self.left(f, n) return self.right(f, n)
find n downstream features where downstream is determined by the strand of the query Feature f Overlapping features are not considered. f: a Feature object n: the number of features to return
14,915
def from_file(path): with open(path) as f: content = f.readlines() content = [x.strip() for x in content] urls = list(filter(None, content)) return NewsPlease.from_urls(urls)
Crawls articles from the urls and extracts relevant information. :param path: path to file containing urls (each line contains one URL) :return: A dict containing given URLs as keys, and extracted information as corresponding values.
14,916
def get_active_pitch_range(self): if self.pianoroll.shape[1] < 1: raise ValueError("Cannot compute the active pitch range for an " "empty pianoroll") lowest = 0 highest = 127 while lowest < highest: if np.any(self.pianoroll[:,...
Return the active pitch range as a tuple (lowest, highest). Returns ------- lowest : int The lowest active pitch in the pianoroll. highest : int The highest active pitch in the pianoroll.
14,917
def no_use_pep517_callback(option, opt, value, parser): if value is not None: msg = raise_option_error(parser, option=option, msg=msg) parser.values.use_pep517 = False
Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option.
14,918
def find_page_of_state_m(self, state_m): for state_identifier, page_info in list(self.tabs.items()): if page_info[] is state_m: return page_info[], state_identifier return None, None
Return the identifier and page of a given state model :param state_m: The state model to be searched :return: page containing the state and the state_identifier
14,919
def Rizk(mp, dp, rhog, D): rs equation." Proceedings of Pneumotransport 3, paper D4. BHRA Fluid Engineering, Cranfield, England (1973) .. [2] Klinzing, G. E., F. Rizk, R. Marcus, and L. S. Leung. Pneumatic Conveying of Solids: A Theoretical and Practical Approach. Springer, 2013. .. [3]...
r'''Calculates saltation velocity of the gas for pneumatic conveying, according to [1]_ as described in [2]_ and many others. .. math:: \mu=\left(\frac{1}{10^{1440d_p+1.96}}\right)\left(Fr_s\right)^{1100d_p+2.5} Fr_s = \frac{V_{salt}}{\sqrt{gD}} \mu = \frac{m_p}{\frac{\pi}{4}D^2V \rho...
14,920
def task_ref_role(name, rawtext, text, lineno, inliner, options=None, content=None): node = pending_task_xref(rawsource=text) return [node], []
Process a role that references the target nodes created by the ``lsst-task`` directive. Parameters ---------- name The role name used in the document. rawtext The entire markup snippet, with role. text The text marked with the role. lineno The line number whe...
14,921
def predict_is(self, h): result = pd.DataFrame([self.run(h=h)[2]]).T result.index = self.index[-h:] return result
Outputs predictions for the Aggregate algorithm on the in-sample data Parameters ---------- h : int How many steps to run the aggregating algorithm on Returns ---------- - pd.DataFrame of ensemble predictions
14,922
def save(self, data): if not self.is_connected: raise Exception("No database selected") if not data: return False if isinstance(data, dict): doc = couchdb.Document() doc.update(data) self.db.create(doc) elif isinstance(...
Save a document or list of documents
14,923
def _write_color (self, text, color=None): if color is None: self.fp.write(text) else: write_color(self.fp, text, color)
Print text with given color. If color is None, print text as-is.
14,924
def user_field_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/user_fields api_path = "/api/v2/user_fields.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/user_fields#create-user-fields
14,925
def tokenize(text, to_lower=False, delimiters=DEFAULT_DELIMITERS): _raise_error_if_not_sarray(text, "text") sf = _turicreate.SFrame({: text}) fe = _feature_engineering.Tokenizer(features=, to_lower=to_lower, ...
Tokenize the input SArray of text strings and return the list of tokens. Parameters ---------- text : SArray[str] Input data of strings representing English text. This tokenizer is not intended to process XML, HTML, or other structured text formats. to_lower : bool, optional If...
14,926
def end_element (self, tag): tag = tag.encode(self.encoding, "ignore") self.fd.write("</%s>" % tag)
Print HTML end element. @param tag: tag name @type tag: string @return: None
14,927
def hash_vector(self, v, querying=False): bucket_keys = [] if querying: for child_hash in self.child_hashes: lshash = child_hash[] if not lshash.hash_name in self.permutation.permutedIndexs: raise At...
Hashes the vector and returns the bucket key as string.
14,928
def neighbours(self, word, size = 10): word = word.strip() v = self.word_vec(word) [distances], [points] = self.kdt.query(array([v]), k = size, return_distance = True) assert len(distances) == len(points), "distances and points should be in same shape." words, scores = [...
Get nearest words with KDTree, ranking by cosine distance
14,929
def save_figure(self, event=None, transparent=False, dpi=600): file_choices = "PNG (*.png)|*.png|SVG (*.svg)|*.svg|PDF (*.pdf)|*.pdf" try: ofile = self.conf.title.strip() except: ofile = if len(ofile) > 64: ofile = ofile[:63].strip() ...
save figure image to file
14,930
def set_num_special_tokens(self, num_special_tokens): self.transformer.set_num_special_tokens(num_special_tokens) self.lm_head.set_embeddings_weights(self.transformer.tokens_embed.weight)
Update input and output embeddings with new embedding matrice Make sure we are sharing the embeddings
14,931
def get_instance(self, payload): return TaskQueueInstance(self._version, payload, workspace_sid=self._solution[], )
Build an instance of TaskQueueInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueueInstance
14,932
def is_symbol(string): return ( is_int(string) or is_float(string) or is_constant(string) or is_unary(string) or is_binary(string) or (string == ) or (string == ) )
Return true if the string is a mathematical symbol.
14,933
def map_trigger(library, session, trigger_source, trigger_destination, mode): return library.viMapTrigger(session, trigger_source, trigger_destination, mode)
Map the specified trigger source line to the specified destination line. Corresponds to viMapTrigger function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param trigger_source: Source line from which to map. (Constant...
14,934
def getAllSystemVariables(self, remote): variables = {} if self.remotes[remote][] and self.remotes[remote][]: LOG.debug( "ServerThread.getAllSystemVariables: Getting all System variables via JSON-RPC") session = self.jsonRpcLogin(remote) if no...
Get all system variables from CCU / Homegear
14,935
def build_time(start_time): diff_time = round(time.time() - start_time, 2) if diff_time <= 59.99: sum_time = str(diff_time) + " Sec" elif diff_time > 59.99 and diff_time <= 3599.99: sum_time = round(diff_time / 60, 2) sum_time_list = re.findall(r"\d+", str(sum_time)) sum...
Calculate build time per package
14,936
def interfaces_info(): def replace(value): if value == netifaces.AF_LINK: return if value == netifaces.AF_INET: return if value == netifaces.AF_INET6: return return value results = {} for iface in netifaces.interfaces(): ad...
Returns interfaces data.
14,937
def _append_array(self, value, _file): _labs = _file.write(_labs) self._tctr += 1 for _item in value: _cmma = if self._vctr[self._tctr] else _file.write(_cmma) self._vctr[self._tctr] += 1 _item = self.object_hook(_item) ...
Call this function to write array contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
14,938
def text(self): if isinstance(self._value, CommentedMap): raise TypeError("{0} is a mapping, has no text value.".format(repr(self))) if isinstance(self._value, CommentedSeq): raise TypeError("{0} is a sequence, has no text value.".format(repr(self))) return self....
Return string value of scalar, whatever value it was parsed as.
14,939
def kids(tup_tree): k = tup_tree[2] if k is None: return [] return [x for x in k if type(x) == tuple]
Return a list with the child elements of tup_tree. The child elements are represented as tupletree nodes. Child nodes that are not XML elements (e.g. text nodes) in tup_tree are filtered out.
14,940
def _get_offset_day(self, other): mstart = datetime(other.year, other.month, 1) wday = mstart.weekday() shift_days = (self.weekday - wday) % 7 return 1 + shift_days + self.week * 7
Find the day in the same month as other that has the same weekday as self.weekday and is the self.week'th such day in the month. Parameters ---------- other : datetime Returns ------- day : int
14,941
def read_properties(group): if not in group: raise IOError() data = group[][...][0].replace(b, b) return pickle.loads(data)
Returns properties loaded from a group
14,942
def __fork_pty(self): parent_fd, child_fd = os.openpty() if parent_fd < 0 or child_fd < 0: raise ExceptionPexpect, "Error! Could not open pty with os.openpty()." pid = os.fork() if pid < 0: raise ExceptionPexpect, "Error! Failed os.fork()." eli...
This implements a substitute for the forkpty system call. This should be more portable than the pty.fork() function. Specifically, this should work on Solaris. Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to resolve the issue with Python's pty.fork() not supporti...
14,943
def _html(title: str, field_names: List[str]) -> str: inputs = .join(_SINGLE_INPUT_TEMPLATE.substitute(field_name=field_name) for field_name in field_names) quoted_field_names = [f"" for field_name in field_names] quoted_field_list = f"[{.join(quoted_field_names)}]" return _P...
Returns bare bones HTML for serving up an input form with the specified fields that can render predictions from the configured model.
14,944
def fromstring(text, schema=None): if schema: parser = objectify.makeparser(schema = schema.schema) return objectify.fromstring(text, parser=parser) else: return objectify.fromstring(text)
Parses a KML text string This function parses a KML text string and optionally validates it against a provided schema object
14,945
def is_valid_name_error(name: str, node: Node = None) -> Optional[GraphQLError]: if not isinstance(name, str): raise TypeError("Expected string") if name.startswith("__"): return GraphQLError( f"Name {name!r} must not begin with ," " which is reserved by GraphQL intr...
Return an Error if a name is invalid.
14,946
def start(self): vms = yield from self.list() for vm in vms: if vm["vmname"] == self.vmname: self._vmx_path = vm["vmx_path"] break if not self._vmx_path: raise GNS3VMError("VMWare VM {} not found".format(self.vmname)) ...
Starts the GNS3 VM.
14,947
def decode_union_old(self, data_type, obj): val = None if isinstance(obj, six.string_types): tag = obj if data_type.definition._is_tag_present(tag, self.caller_permissions): val_data_type = data_type.definition._get_val_data_type(tag, ...
The data_type argument must be a Union. See json_compat_obj_decode() for argument descriptions.
14,948
def __find_sentence_initial_proper_names(self, docs): sentInitialNames = set() for doc in docs: for sentence in doc.divide( layer=WORDS, by=SENTENCES ): sentencePos = 0 for i in range(len(sentence)): word = sentence[i] ...
Moodustame lausealguliste pärisnimede loendi: vaatame sõnu, millel nii pärisnimeanalüüs(id) kui ka mittepärisnimeanalüüs(id) ning mis esinevad lause või nummerdatud loendi alguses - jäädvustame selliste sõnade unikaalsed lemmad;
14,949
def subscribe_multi(self, topics): if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("SUBSCRIBE: %s", .join([t for (t,q) in topics])) return self.send_subscribe(False, [(utf8encode(topic), qos) for (topic, qos) in topics])
Subscribe to some topics.
14,950
def before_after_send_handling(self): self._init_delivery_statuses_dict() self.before_send() try: yield finally: self.after_send() self._update_dispatches()
Context manager that allows to execute send wrapped in before_send() and after_send().
14,951
def _set_nsx_controller(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("name",nsx_controller.nsx_controller, yang_name="nsx-controller", rest_name="nsx-controller", parent=self, is_container=, user_ordered=False, path_helper=self._path_h...
Setter method for nsx_controller, mapped from YANG variable /nsx_controller (list) If this variable is read-only (config: false) in the source YANG file, then _set_nsx_controller is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_nsx_contr...
14,952
def _validate_geometry(self, geometry): if geometry is not None and geometry not in self.valid_geometries: raise InvalidParameterError("{} is not a valid geometry".format(geometry)) return geometry
Validates geometry, raising error if invalid.
14,953
def convert_conelp(c, G, h, dims, A = None, b = None, **kwargs): offsets = dims[] + sum(dims[]) G_lq = G[:offsets,:] h_lq = h[:offsets,0] G_s = G[offsets:,:] h_s = h[offsets:,0] G_converted = [G_lq]; h_converted = [h_lq] G_coupling = [] dims_list = [] symbs = [] ...
Applies the clique conversion method of Fukuda et al. to the positive semidefinite blocks of a cone LP. :param c: :py:class:`matrix` :param G: :py:class:`spmatrix` :param h: :py:class:`matrix` :param dims: dictionary :param A: ...
14,954
def mode_reader(self): code, message = self.command("MODE READER") if not code in [200, 201]: raise NNTPReplyError(code, message) return code == 200
MODE READER command. Instructs a mode-switching server to switch modes. See <http://tools.ietf.org/html/rfc3977#section-5.3> Returns: Boolean value indicating whether posting is allowed or not.
14,955
def _capture_as_text(capture: Callable[..., Any]) -> str: if not icontract._represent._is_lambda(a_function=capture): signature = inspect.signature(capture) param_names = list(signature.parameters.keys()) return "{}({})".format(capture.__qualname__, ", ".join(param_names)) lines, ...
Convert the capture function into its text representation by parsing the source code of the decorator.
14,956
def chuid(name, uid): * pre_info = info(name) if not pre_info: raise CommandExecutionError( {0}\.format(name) ) if uid == pre_info[]: return True cmd = [, , , uid, , name] __salt__[](cmd, python_shell=False) return info(name).get() == uid
Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376
14,957
def _pys2row_heights(self, line): split_line = self._split_tidy(line) key = row, tab = self._get_key(*split_line[:2]) height = float(split_line[2]) shape = self.code_array.shape try: if row < shape[0] and tab < shape[2]: self.code_...
Updates row_heights in code_array
14,958
def generate_name(self, name=None): t supply one. -_')
generate a Robot Name for the instance to use, if the user doesn't supply one.
14,959
def batchccn(args): p = OptionParser(batchccn.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) csvfile, = args mm = MakeManager() pf = op.basename(csvfile).split(".")[0] mkdir(pf) header = next(open(csvfile)) header = None if he...
%prog batchccn test.csv Run CCN script in batch. Write makefile.
14,960
def periodicvar_recovery(fakepfpkl, simbasedir, period_tolerance=1.0e-3): recovered if fakepfpkl.endswith(): infd = gzip.open(fakepfpkl,) else: infd = open(fakepfpkl,) fakepf = pickle.load(infd) infd.close() objectid, lcf...
Recovers the periodic variable status/info for the simulated PF result. - Uses simbasedir and the lcfbasename stored in fakepfpkl to figure out where the LC for this object is. - Gets the actual_varparams, actual_varperiod, actual_vartype, actual_varamplitude elements from the LC. - Figures out...
14,961
def to_json(self) -> dict: d = self.__dict__ d[] = self.p2th_wif return d
export the Deck object to json-ready format
14,962
def _psed(text, before, after, limit, flags): atext = text if limit: limit = re.compile(limit) comps = text.split(limit) atext = .join(comps[1:]) count = 1 if in flags: count = 0 flags = flags.replace(, ) aflags ...
Does the actual work for file.psed, so that single lines can be passed in
14,963
async def get_soundfield(self) -> List[Setting]: res = await self.services["audio"]["getSoundSettings"]({"target": "soundField"}) return Setting.make(**res[0])
Get the current sound field settings.
14,964
def _numpy_index_by_percentile(self, data, percentile): data_perc_low = np.nanpercentile(data, percentile, axis=0, interpolation=self.interpolation) indices = np.empty(data_perc_low.shape, dtype=np.uint8) indices[:] = np.nan abs_diff = np.where(np.isnan(data_perc_low), np.inf,...
Calculate percentile of numpy stack and return the index of the chosen pixel. numpy percentile function is used with one of the following interpolations {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
14,965
def _from_dict(cls, _dict): args = {} if in _dict: args[] = [ QueryRelationsRelationship._from_dict(x) for x in (_dict.get()) ] return cls(**args)
Initialize a QueryRelationsResponse object from a json dictionary.
14,966
def getUnitCost(self, CorpNum): result = self._httpget(, CorpNum) return int(result.unitCost)
팩스 전송 단가 확인 args CorpNum : 팝빌회원 사업자번호 return 전송 단가 by float raise PopbillException
14,967
def cli(env, account_id): manager = SoftLayer.CDNManager(env.client) origins = manager.get_origins(account_id) table = formatting.Table([, , , ]) for origin in origins: table.add_row([origin[], origin[], origin.get(, formatting.blank()), ...
List origin pull mappings.
14,968
def create_temporaries(self, r=True, f=True): inverse = isinstance(self, FourierTransformInverse) if inverse: rspace = self.range fspace = self.domain else: rspace = self.domain fspace = self.range if r: self._tmp_r =...
Allocate and store reusable temporaries. Existing temporaries are overridden. Parameters ---------- r : bool, optional Create temporary for the real space f : bool, optional Create temporary for the frequency space Notes ----- To...
14,969
def process_header(self, headers): return [c.name for c in self.source.dest_table.columns][1:]
Ignore the incomming header and replace it with the destination header
14,970
def _upload_folder_recursive(local_folder, parent_folder_id, leaf_folders_as_items=False, reuse_existing=False): if leaf_folders_as_items and _has_only_files(local_folder): print(.format(local_folder)) _uploa...
Function to recursively upload a folder and all of its descendants. :param local_folder: full path to local folder to be uploaded :type local_folder: string :param parent_folder_id: id of parent folder on the Midas Server instance, where the new folder will be added :type parent_folder_id: int ...
14,971
async def i2c_read_request(self, address, register, number_of_bytes, read_type, cb=None, cb_type=None): if address not in self.i2c_map: self.i2c_map[address] = {: None, : cb, : cb_type} data = [address,...
This method requests the read of an i2c device. Results are retrieved by a call to i2c_get_read_data(). or by callback. If a callback method is provided, when data is received from the device it will be sent to the callback method. Some devices require that transmission be restarted ...
14,972
def write_config_file(self, params, path): cfgp = ConfigParser() cfgp.add_section(params[]) for p in params: if p == : continue cfgp.set(params[], p, params[p]) f = open(os.path.join(path, ), ) cfgp.write(f) f.close()
write a config file for this single exp in the folder path.
14,973
def text_bounding_box(self, size_pt, text): if size_pt == 12: mult = {"h": 9, "w_digit": 5, "w_space": 2} elif size_pt == 18: mult = {"h": 14, "w_digit": 9, "w_space": 2} num_chars = len(text) return (num_chars * mult["w_digit"] + (num_chars - 1) * mult["...
Return the bounding box of the given text at the given font size. :param int size_pt: the font size in points :param string text: the text :rtype: tuple (width, height)
14,974
def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): if axis is not None: axis = self._get_axis_number(axis) if bool_only and axis == 0: if hasattr(self, "dtype"): raise NotImplementedError( ...
Return whether all elements are True over requested axis Note: If axis=None or axis=0, this call applies df.all(axis=1) to the transpose of df.
14,975
def get_new_broks(self): for satellites in [self.schedulers, self.pollers, self.reactionners, self.receivers]: for satellite_link in list(satellites.values()): logger.debug("Getting broks from %s", satellite_link) _t0 = time.time() try: ...
Get new broks from our satellites :return: None
14,976
def pytwis_clt(): epilog = twis, prompt = get_pytwis(epilog) if twis is None: return -1 auth_secret = [] while True: try: arg_dict = pytwis_command_parser( input( \ .format(prompt)))...
The main routine of this command-line tool.
14,977
def _get_field(self, field_name, default=None): full_field_name = .format(field_name) if full_field_name in self.extras: return self.extras[full_field_name] else: return default
Fetches a field from extras, and returns it. This is some Airflow magic. The grpc hook type adds custom UI elements to the hook page, which allow admins to specify scopes, credential pem files, etc. They get formatted as shown below.
14,978
def connect(self, slot): if not callable(slot): raise ValueError("Connection to non-callable object failed" % slot.__class__.__name__) if (isinstance(slot, partial) or in slot.__name__): slotSelf = slot.__self__ slotDict = weakref.WeakKeyDicti...
Connects the signal to any callable object
14,979
def get_ip_interface_output_interface_vrf(self, **kwargs): config = ET.Element("config") get_ip_interface = ET.Element("get_ip_interface") config = get_ip_interface output = ET.SubElement(get_ip_interface, "output") interface = ET.SubElement(output, "interface") ...
Auto Generated Code
14,980
def entity(self): if not issubclass(self.cls, Base) or issubclass(self.cls, DerivedBase): raise ValueError("Cannot get entity for non-base-class {}".format(self.cls)) return self.cls(self._client, self.id)
Returns the object this grant is for. The objects type depends on the type of object this grant is applied to, and the object returned is not populated (accessing its attributes will trigger an api request). :returns: This grant's entity :rtype: Linode, NodeBalancer, Domain, StackScrip...
14,981
def list_namespaced_service_account(self, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.list_namespaced_service_account_with_http_info(namespace, **kwargs) else: (data) = self.list_namespaced_service_account_with_http_info(namespace, **kwargs...
list or watch objects of kind ServiceAccount This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_service_account(namespace, async_req=True) >>> result = thread.get() :param asy...
14,982
def DeserializeMessage(self, response_type, data): try: message = encoding.JsonToMessage(response_type, data) except (exceptions.InvalidDataFromServerError, messages.ValidationError, ValueError) as e: raise exceptions.InvalidDataFromServerError( ...
Deserialize the given data as method_config.response_type.
14,983
def _update_prx(self): qx = scipy.ones(N_CODON, dtype=) for j in range(3): for w in range(N_NT): qx[CODON_NT[j][w]] *= self.phi[w] frx = self.pi_codon**self.beta self.prx = frx * qx with scipy.errstate(divide=, under=, over=, i...
Update `prx` from `phi`, `pi_codon`, and `beta`.
14,984
def _read_next_line(self): prev_line = self._line self._line = self.stream.readline() return prev_line
Read next line store in self._line and return old one
14,985
def summary(model, input_size): def register_hook(module): def hook(module, input, output): class_name = str(module.__class__).split()[-1].split("%s-%iinput_shapeinput_shapeoutput_shapeoutput_shapeoutput_shapeweightsizetrainablebiassizenb_params----------------------------------------------...
Print summary of the model
14,986
def can_group_commands(command, next_command): multi_capable_commands = (, , ) if next_command is None: return False name = command.get_name() if name not in multi_capable_commands: return False if name != next_command.get_name(): return False if group...
Returns a boolean representing whether these commands can be grouped together or not. A few things are taken into account for this decision: For ``set`` commands: - Are all arguments other than the key/value the same? For ``delete`` and ``get`` commands: - Are all arguments other than the k...
14,987
def add_handler(self, type, actions, **kwargs): l = self._events.get(type, []) h = Handler(self, type, kwargs, actions) l.append(h) self._events[type] = l return h
Add an event handler to be processed by this session. type - The type of the event (pygame.QUIT, pygame.KEYUP ETC). actions - The methods which should be called when an event matching this specification is received. more than one action can be tied to a single event. This allows for secondary ...
14,988
def literal_struct(cls, elems): tys = [el.type for el in elems] return cls(types.LiteralStructType(tys), elems)
Construct a literal structure constant made of the given members.
14,989
def remove_repeat_coordinates(x, y, z): r coords = [] variable = [] for (x_, y_, t_) in zip(x, y, z): if (x_, y_) not in coords: coords.append((x_, y_)) variable.append(t_) coords = np.array(coords) x_ = coords[:, 0] y_ = coords[:, 1] z_ = np.array(var...
r"""Remove all x, y, and z where (x,y) is repeated and keep the first occurrence only. Will not destroy original values. Parameters ---------- x: array_like x coordinate y: array_like y coordinate z: array_like observation value Returns ------- x, y, z ...
14,990
def compute_best_path(local_asn, path1, path2): best_path = None best_path_reason = BPR_UNKNOWN if best_path is None: best_path = _cmp_by_reachable_nh(path1, path2) best_path_reason = BPR_REACHABLE_NEXT_HOP if best_path is None: best_path = _cmp_by_highest_wg(path1, pa...
Compares given paths and returns best path. Parameters: -`local_asn`: asn of local bgpspeaker -`path1`: first path to compare -`path2`: second path to compare Best path processing will involve following steps: 1. Select a path with a reachable next hop. 2. Select the path wit...
14,991
def getFaxStatsSessions(self): if not self.hasFax(): return None info_dict = {} info_dict[] = 0 fax_types = (, ) fax_operations = (, ) fax_states = (, , , , , , ,) info_dict[] = dict([(k,0) for k in fax_types]) i...
Query Asterisk Manager Interface for Fax Stats. CLI Command - fax show sessions @return: Dictionary of fax stats.
14,992
def _worker_process(self): while not self.terminated: try: key, lpath, fpath, remote_md5, pagealign, lpview = \ self._task_queue.get(True, 0.1) except queue.Empty: continue if lpview is None: ...
Compute MD5 for local file :param LocalFileMd5Offload self: this
14,993
def create_project(self, name, **kwargs): data = self._wrap_dict("project", kwargs) data["customer"]["name"] = name return self.post("/projects.json", data=data)
Creates a project with a name. All other parameters are optional. They are: `note`, `customer_id`, `budget`, `budget_type`, `active_hourly_rate`, `hourly_rate`, `hourly_rates_per_service`, and `archived`.
14,994
def _ip_is_usable(self, current_ip): try: ipaddress.ip_address(current_ip) except ValueError: return False if current_ip == self.real_ip: return False if not self._ip_is_safe(current_ip): return False ...
Check if the current Tor's IP is usable. :argument current_ip: current Tor IP :type current_ip: str :returns bool
14,995
def iaf_flow(one_hot_assignments, scale_weights, scale_bias, num_codes, summary=True, name=None): with tf.name_scope(name, default_name="iaf"): padded_assignments = tf.pad( one_hot_assignments, [[0, 0], [0, 0], [1, 0], [0, 0]])[...
Performs a single IAF flow using scale and normalization transformations. Args: one_hot_assignments: Assignments Tensor with shape [num_samples, batch_size, latent_size, num_codes]. scale_weights: Tensor corresponding to lower triangular matrix used to autoregressively generate scale matrix from ...
14,996
def prt_gene_aart_details(self, geneids, prt=sys.stdout): _go2nt = self.sortobj.grprobj.go2nt patgene = self.datobj.kws["fmtgene2"] patgo = self.datobj.kws["fmtgo2"] itemid2name = self.datobj.kws.get("itemid2name") chr2i = self.datobj.get_chr2idx() for geneid in ...
For each gene, print ASCII art which represents its associated GO IDs.
14,997
def add_data(self, conf): self.validate_data(conf) self.process_data(conf) self.data.append(conf)
Add data to the graph object. May be called several times to add additional data sets. conf should be a dictionary including 'data' and 'title' keys
14,998
def cleanup(self): for k in self._children: self._children[k].cleanup() if self._cleanup: self.remove(True)
Clean up children and remove the directory. Directory will only be removed if the cleanup flag is set.
14,999
def color_palette(name=None, n_colors=6, desat=None): seaborn_palettes = dict( deep=[" " muted=[" " pastel=[" " bright=[" " dark=[" " colorblind=[" " ) if name...
Return a list of colors defining a color palette. Availible seaborn palette names: deep, muted, bright, pastel, dark, colorblind Other options: hls, husl, any matplotlib palette Matplotlib paletes can be specified as reversed palettes by appending "_r" to the name or as dark palettes ...