Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
364,100
def execute_remote(self, remote_target, cmd, **kwargs): data = self._build_command(cmd, kwargs, self._contexts[-1], remote_target) with self._lock: rootelem = self.transport.send(data) try: return self._build_response(rootelem) ...
Executes the given command (with the given arguments) on the given remote target of the connected machine
364,101
def _starfeatures_worker(task): try: (lcfile, outdir, kdtree, objlist, lcflist, neighbor_radius_arcsec, deredden, custom_bandpasses, lcformat, lcformatdir) = task return get_starfeatures(lcfile, outdir, kdtree, objlist, lcflist, ...
This wraps starfeatures.
364,102
def visible(self): delete = self._element.delete_ if delete is None: return False return False if delete.val else True
Read/write. |True| if axis is visible, |False| otherwise.
364,103
async def iterUnivRows(self, prop): penc = prop.encode() pref = penc + b for _, pval in self.layrslab.scanByPref(pref, db=self.byuniv): buid = s_msgpack.un(pval)[0] byts = self.layrslab.get(buid + penc, db=self.bybuid) if byts is None: ...
Iterate (buid, valu) rows for the given universal prop
364,104
def get_subsites(self): url = self.build_url( self._endpoints.get().format(id=self.object_id)) response = self.con.get(url) if not response: return [] data = response.json() return [self.__class__(parent=self, **{self._cloud_data_key: ...
Returns a list of subsites defined for this site :rtype: list[Site]
364,105
def get_reservations_for_booking_ids(self, booking_ids): try: resp = self._request("GET", "/1.1/space/booking/{}".format(booking_ids)) except resp.exceptions.HTTPError as error: raise APIError("Server Error: {}".format(error)) return resp.json()
Gets booking information for a given list of booking ids. :param booking_ids: a booking id or a list of room ids (comma separated). :type booking_ids: string
364,106
def derivative(xdata, ydata): D_ydata = [] D_xdata = [] for n in range(1, len(xdata)-1): D_xdata.append(xdata[n]) D_ydata.append((ydata[n+1]-ydata[n-1])/(xdata[n+1]-xdata[n-1])) return [D_xdata, D_ydata]
performs d(ydata)/d(xdata) with nearest-neighbor slopes must be well-ordered, returns new arrays [xdata, dydx_data] neighbors:
364,107
def element_count(self): result = conf.lib.clang_getNumElements(self) if result < 0: raise Exception() return result
Retrieve the number of elements in this type. Returns an int. If the Type is not an array or vector, this raises.
364,108
def _model_abilities_two_components(self,beta): parm = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(beta.shape[0])]) scale, shape, skewness = self._get_scale_and_shape(parm) state_vectors = np.zeros(shape=(self.max_team+1)) state_vectors_2 =...
Creates the structure of the model - store abilities Parameters ---------- beta : np.array Contains untransformed starting values for latent variables Returns ---------- theta : np.array Contains the predicted values for the time series ...
364,109
def calc_directional_aop(self, report, parameter, parameter_dir): lg.debug( + parameter) tmp_zenith = [] param_zenith = parameter_dir.split()[0] param_azimuth = parameter_dir.split()[1] for i_iter in range(0, int(report[][1])): tm...
Will calcuate the directional AOP (only sub-surface rrs for now) if the direction is defined using @ e.g. rrs@32.0:45 where <zenith-theta>:<azimuth-phi> :param report: The planarrad report dictionary. should include the quadtables and the directional info :param parameter: parameter to calc. ...
364,110
def check_native_jsonfield_postgres_engine(app_configs=None, **kwargs): from . import settings as djstripe_settings messages = [] error_msg = "DJSTRIPE_USE_NATIVE_JSONFIELD is not compatible with engine {engine} for database {name}" if djstripe_settings.USE_NATIVE_JSONFIELD: for db_name, db_config in settings...
Check that the DJSTRIPE_USE_NATIVE_JSONFIELD isn't set unless Postgres is in use.
364,111
def _set_precision(self, precision): if self.one_mutation: self.min_width = 10*self.one_mutation else: self.min_width = 0.001 if precision in [0,1,2,3]: self.precision=precision if self.one_mutation and self.one_mutation<1e-4 and...
function that sets precision to an (hopfully) reasonable guess based on the length of the sequence if not explicitly set
364,112
def error_handler(self, e, request, meth, em_format): if isinstance(e, FormValidationError): return self.form_validation_response(e) elif isinstance(e, TypeError): result = rc.BAD_REQUEST hm = HandlerMethod(meth) sig = hm.signature m...
Override this method to add handling of errors customized for your needs
364,113
def create_package_file(root, master_package, subroot, py_files, opts, subs, is_namespace): use_templates = False fullname = makename(master_package, subroot) if opts.templates: use_templates = True template_loader = FileSystemLoader(opts.templates) template_env = Sandbox...
Build the text of the file and write the file.
364,114
def executed_block_set(trace): executed_set = set() for entry in trace: if entry[0] == : executed_set.add(entry[get_trace_index(, )]) return executed_set
Given an execution trace, returns a python set object containing the names of each block for which the user code was executed. Block names can be set via set_debug_name().
364,115
def find_line_containing(strings: Sequence[str], contents: str) -> int: for i in range(len(strings)): if strings[i].find(contents) != -1: return i return -1
Finds the index of the line in ``strings`` that contains ``contents``, or ``-1`` if none is found.
364,116
def trim_ordered_range_list(ranges,start,finish): z = 0 keep_ranges = [] for inrng in self.ranges: z+=1 original_rng = inrng rng = inrng.copy() done = False; if start >= index and start < index+original_rng.length(): rng.start = original_rng.start+(start-index) if f...
A function to help with slicing a mapping Start with a list of ranges and get another list of ranges constrained by start (0-indexed) and finish (1-indexed) :param ranges: ordered non-overlapping ranges on the same chromosome :param start: start 0-indexed :param finish: ending 1-indexed :type ...
364,117
def run(self): try: self._run() except Exception: self.action.put( ServiceCheckDiedError(self.name, traceback.format_exc()) )
Wrap _run method.
364,118
def fix_config(self, options): options = super(CommandlineToAny, self).fix_config(options) opt = "wrapper" if opt not in options: options[opt] = "weka.core.classes.OptionHandler" if opt not in self.help: self.help[opt] = "The name of the wrapper class to...
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict
364,119
def external(name, value, dtype=tf.sg_floatx, summary=True, regularizer=None, trainable=True): r x = tf.get_variable(name, initializer=tf.constant(value, dtype=dtype), regularizer=regularizer, trainable=trainable) if summary: tf.sg_summary_pa...
r"""Creates a tensor variable of which initial values are `value`. For example, ``` external("external", [3,3,1,2]) => [3. 3. 1. 2.] ``` Args: name: The name of new variable. value: A constant value (or list) of output type `dtype`. dtype: The type of the element...
364,120
def write_points(self, data, time_precision=, *args, **kwargs): def list_chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i + n] batch_size = kwargs.get() if batch_size and batch_size > 0: for item in data: name...
Write to multiple time series names. An example data blob is: data = [ { "points": [ [ 12 ] ], "name": "cpu_load_short", "columns": [ "value" ...
364,121
def _init_virtual_io(self, file): @_ffi.callback("sf_vio_get_filelen") def vio_get_filelen(user_data): curr = file.tell() file.seek(0, SEEK_END) size = file.tell() file.seek(curr, SEEK_SET) return size @_ffi.callback("sf_vio_s...
Initialize callback functions for sf_open_virtual().
364,122
def fit_interval_censoring( self, df, lower_bound_col, upper_bound_col, event_col=None, ancillary_df=None, show_progress=False, timeline=None, weights_col=None, robust=False, initial_point=None, entry_col=None, ): ...
Fit the accelerated failure time model to a left-censored dataset. Parameters ---------- df: DataFrame a Pandas DataFrame with necessary columns ``lower_bound_col``, ``upper_bound_col`` (see below), and any other covariates or weights. lower_bound_col: string ...
364,123
def divideHosts(self, hosts, qty): maximumWorkers = sum(host[1] for host in hosts) if qty > maximumWorkers: index = 0 while qty > maximumWorkers: hosts[index] = (hosts[index][0], hosts[index][1] + 1) index = (index + 1) % len(hos...
Divide processes among hosts.
364,124
def collect_variables(self, selections) -> None: super().collect_variables(selections) for device in sorted(self.device2target.keys(), key=lambda x: x.name): self._device2name[device] = f for target in self.device2target.values(): self.ndim = target.NDIM ...
Apply method |ExchangeItem.collect_variables| of the base class |ExchangeItem| and determine the `ndim` attribute of the current |ChangeItem| object afterwards. The value of `ndim` depends on whether the values of the target variable or its time series is of interest: >>> from ...
364,125
def gt(self, v, limit=None, offset=None): if limit is not None and offset is None: offset = 0 return self.zrangebyscore("(%f" % v, self._max_score, start=offset, num=limit)
Returns the list of the members of the set that have scores greater than v.
364,126
def makeReadPacket(ID, reg, values=None): pkt = makePacket(ID, xl320.XL320_READ, reg, values) return pkt
Creates a packet that reads the register(s) of servo ID at location reg. Make sure the values are in little endian (use Packet.le() if necessary) for 16 b (word size) values.
364,127
def get_column_def(self): static = "static" if self.static else "" db_type = self.db_type.format(self.value_type.db_type) return .format(self.cql, db_type, static)
Returns a column definition for CQL table definition
364,128
def GET_account_balance(self, path_info, account_addr, token_type): if not check_account_address(account_addr): return self._reply_json({: }, status_code=400) if not check_token_type(token_type): return self._reply_json({: }, status_code=400) blockstackd_url = ...
Get the balance of a particular token Returns {'balance': ...}
364,129
def attributs(self): if self.user: attr = {} try: field_names = [ field.attname for field in self.user._meta.get_fields() if hasattr(field, "attname") ] except Attribute...
The user attributes, defined as the fields on the :attr:`user` object. :return: a :class:`dict` with the :attr:`user` object fields. Attributes may be If the user do not exists, the returned :class:`dict` is empty. :rtype: dict
364,130
def stop_app(self): try: if self._conn: finally: self.clear_host_port()
Overrides superclass.
364,131
def check_trademark_symbol(text): err = "typography.symbols.trademark" msg = u"(TM) is a goofy alphabetic approximation, use the symbol ™." regex = "\(TM\)" return existence_check( text, [regex], err, msg, max_errors=3, require_padding=False)
Use the trademark symbol instead of (TM).
364,132
def qteKeyPress(self, msgObj): (srcObj, keysequence, macroName) = msgObj.data key = keysequence.toQKeyEventList()[-1] if macroName is None: return if self.input_complete: self.qteRepeatTheMacro(msgObj) ...
Record the key presses reported by the key handler.
364,133
def instance(): if not hasattr(Vabamorf, ) or Vabamorf.pid != os.getpid(): Vabamorf.pid = os.getpid() Vabamorf.morf = Vabamorf() return Vabamorf.morf
Return an PyVabamorf instance. It returns the previously initialized instance or creates a new one if nothing exists. Also creates new instance in case the process has been forked.
364,134
def img(url, alt=, classes=, style=): if not url.startswith() and not url[:1] == : url = settings.STATIC_URL + url attr = { : classes, : alt, : style, : url } return html.tag(, , attr)
Image tag helper.
364,135
def get_payload(self): ret = self._software_version ret += bytes([self.hardware_version, self.product_group, self.product_type]) return ret
Return Payload.
364,136
def deleteFile(self, CorpNum, MgtKeyType, MgtKey, FileID, UserID=None): if MgtKeyType not in self.__MgtKeyTypes: raise PopbillException(-99999999, "관리번호 형태가 올바르지 않습니다.") if MgtKey == None or MgtKey == "": raise PopbillException(-99999999, "관리번호가 입력되지 않았습니다.") if ...
첨부파일 삭제 args CorpNum : 회원 사업자 번호 MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE'] MgtKey : 파트너 관리번호 UserID : 팝빌 회원아이디 return 처리결과. consist of code and message raise PopbillException
364,137
def to_fastq_str(self): return "@" + self.name + "\n" + self.sequenceData +\ "\n" + "+" + self.name + "\n" + self.seq_qual
:return: string representation of this NGS read in FastQ format
364,138
def analyze(self, input_directory, output_directory, **kwargs): is_api_call = True if len(self._analyses) == 0: if not in kwargs.keys(): return CONSTANTS.ERROR self.create_analysis(kwargs[]) if in kwargs: self._process_args(self._analyses[0], kwargs[]) is_api_call = Fa...
Run all the analysis saved in self._analyses, sorted by test_id. This is useful when Naarad() is used by other programs and multiple analyses are run In naarad CLI mode, len(_analyses) == 1 :param: input_directory: location of log files :param: output_directory: root directory for analysis output :p...
364,139
def _get_chain_parent_symbol(self, symbol, fullsymbol): chain = fullsymbol.split("%") if len(chain) < 2: return ([], None) previous = chain[-2].lower() target_name = "" if previous in self.element.members: ...
Gets the code element object for the parent of the specified symbol in the fullsymbol chain.
364,140
def format_names(raw): if raw: raw = [ .format( header.lower(), .join(func[0] for func in funcs) ) for header, funcs in raw ] return .join(raw) return
Format a string representing the names contained in the files.
364,141
def __reg_query_value(handle, value_name): item_value, item_type = win32api.RegQueryValueEx(handle, value_name) if six.PY2 and isinstance(item_value, six.string_types) and not isinstance(item_value, six.text_type): try: item_value = six.text_type(item_valu...
Calls RegQueryValueEx If PY2 ensure unicode string and expand REG_EXPAND_SZ before returning Remember to catch not found exceptions when calling. Args: handle (object): open registry handle. value_name (str): Name of the value you wished returned Returns: ...
364,142
def _serialize_dict(cls, dict_): obj_serialized = {} for key in dict_.keys(): item_serialized = cls.serialize(dict_[key]) if item_serialized is not None: key = key.rstrip(cls._SUFFIX_KEY_OVERLAPPING) key = key.lstrip(cls._PREFIX_KEY_PRO...
:type dict_ dict :rtype: dict
364,143
def create_model(schema, collection, class_name=None): if not class_name: class_name = camelize(str(collection.name)) model_class = type(class_name, (Model,), dict(schema=schema, _collection_factory=staticmethod(lambda: collection))) mod...
Main entry point to creating a new mongothon model. Both schema and Pymongo collection objects must be provided. Returns a new class which can be used as a model class. The class name of the model class by default is inferred from the provided collection (converted to camel case). Optionally, a cl...
364,144
def snakecase(string): string = re.sub(r"[\-\.\s]", , str(string)) if not string: return string return lowercase(string[0]) + re.sub(r"[A-Z]", lambda matched: + lowercase(matched.group(0)), string[1:])
Convert string into snake case. Join punctuation with underscore Args: string: String to convert. Returns: string: Snake cased string.
364,145
def createService(self, createServiceParameter, description=None, tags="Feature Service", snippet=None): url = "%s/createService" % self.location val = createServiceParameter.value params = { "f" : "json", ...
The Create Service operation allows users to create a hosted feature service. You can use the API to create an empty hosted feaure service from feature service metadata JSON. Inputs: createServiceParameter - create service object
364,146
def MetricValueTypeFromPythonType(python_type): if python_type in (int, long): return rdf_stats.MetricMetadata.ValueType.INT elif python_type == float: return rdf_stats.MetricMetadata.ValueType.FLOAT else: raise ValueError("Invalid value type: %s" % python_type)
Converts Python types to MetricMetadata.ValueType enum values.
364,147
def import_string(import_name, silent=False): assert isinstance(import_name, string_types) import_name = str(import_name) try: if in import_name: module, obj = import_name.split(, 1) elif in import_name: module, obj = import_name.rsplit(, 1) e...
Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If `silent` is True the ret...
364,148
def Print(self, x, data, message, **kwargs): del data, message, kwargs tf.logging.warning("Warning - mtf.Print not implemented for this mesh type") return x
Calls tf.Print. Args: x: LaidOutTensor. data: list of LaidOutTensor. message: str. **kwargs: keyword arguments to tf.print. Returns: LaidOutTensor.
364,149
def SendTextMessage(self, Text): if self.Type == cctReliable: self.Stream.Write(Text) elif self.Type == cctDatagram: self.Stream.SendDatagram(Text) else: raise SkypeError(0, & repr(self.Type))
Sends a text message over channel. :Parameters: Text : unicode Text to send.
364,150
def refresh(self): if not self._client: return current_containers = self._client.containers(all=True) self.clear() for container in current_containers: container_names = container.get() if container_names: c_id = container[] ...
Fetches all current container names from the client, along with their id.
364,151
def render(self): while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self
Runs the render until thread flag is set. Returns ------- self
364,152
def estimate(init_values, estimator, method, loss_tol, gradient_tol, maxiter, print_results, use_hessian=True, just_point=False, **kwargs): if not just_point: log_likelihood_at_...
Estimate the given choice model that is defined by `estimator`. Parameters ---------- init_vals : 1D ndarray. Should contain the initial values to start the optimization process with. estimator : an instance of the EstimationObj class. method : str, optional. Should be a val...
364,153
def _clean_data(cls, *args, **kwargs): datadict = cls.clean(*args, **kwargs) if in datadict: data = datadict[] data = cls._ensure_dict_or_list(data) else: data = {} for key in datadict: if key == : da...
Convert raw data into a dictionary with plot-type specific methods. The result of the cleaning operation should be a dictionary. If the dictionary contains a 'data' field it will be passed directly (ensuring appropriate formatting). Otherwise, it should be a dictionary of data-type spec...
364,154
def wait_for_relation(service_name, relation_name, timeout=120): start_time = time.time() while True: relation = unit_info(service_name, ).get(relation_name) if relation is not None and relation[] == : break if time.time() - start_time >= timeout: raise Runti...
Wait `timeout` seconds for a given relation to come up.
364,155
def as_string(self): if type(self.instruction) is str: return self.instruction if self.action == "FROM" and not isinstance(self.command, six.string_types): extra = "" if self.extra is NotSpecified else " {0}".format(self.extra) return "{0} {1}{2}".format(sel...
Return the command as a single string for the docker file
364,156
def __getLogger(cls): if cls.__logger is None: cls.__logger = opf_utils.initLogger(cls) return cls.__logger
Get the logger for this object. :returns: (Logger) A Logger object.
364,157
def add_resource(self, name, file_path, ind_obj): new_resource = Resource(name=name, individual=ind_obj, path=file_path) self.session.add(new_resource) self.save() return new_resource
Link a resource to an individual.
364,158
def path_qs(self): if not self.query_string: return self.path return "{}?{}".format(self.path, self.query_string)
Decoded path of URL with query.
364,159
def is_ipfs_uri(value: str) -> bool: parse_result = parse.urlparse(value) if parse_result.scheme != "ipfs": return False if not parse_result.netloc and not parse_result.path: return False return True
Return a bool indicating whether or not the value is a valid IPFS URI.
364,160
def find_nearest_leaf(self, entry, search_node = None): if (search_node is None): search_node = self.__root; nearest_node = search_node; if (search_node.type == cfnode_type.CFNODE_NONLEAF): min_key = lambda child_node: child_no...
! @brief Search nearest leaf to the specified clustering feature. @param[in] entry (cfentry): Clustering feature. @param[in] search_node (cfnode): Node from that searching should be started, if None then search process will be started for the root. @return (leaf_n...
364,161
def createReference(self, fromnode, tonode, edge_data=None): if fromnode is None: fromnode = self fromident, toident = self.getIdent(fromnode), self.getIdent(tonode) if fromident is None or toident is None: return self.msg(4, "createReference", fromnode, ...
Create a reference from fromnode to tonode
364,162
def set_basic_params(self, msg_size=None, cheap=None, anti_loop_timeout=None): self._set(, msg_size) self._set(, cheap, cast=bool) self._set(, anti_loop_timeout) return self._section
:param int msg_size: Set the max size of an alarm message in bytes. Default: 8192. :param bool cheap: Use main alarm thread rather than create dedicated threads for curl-based alarms :param int anti_loop_timeout: Tune the anti-loop alarm system. Default: 3 seconds.
364,163
def do_stored_procedure_check(self, instance, proc): guardSql = instance.get() custom_tags = instance.get("tags", []) if (guardSql and self.proc_check_guard(instance, guardSql)) or not guardSql: self.open_db_connections(instance, self.DEFAULT_DB_KEY) cursor = s...
Fetch the metrics from the stored proc
364,164
def quadratic_forms(h1, h2): r h1, h2 = __prepare_histogram(h1, h2) A = __quadratic_forms_matrix_euclidean(h1, h2) return math.sqrt((h1-h2).dot(A.dot(h1-h2)))
r""" Quadrativ forms metric. Notes ----- UNDER DEVELOPMENT This distance measure shows very strange behaviour. The expression transpose(h1-h2) * A * (h1-h2) yields egative values that can not be processed by the square root. Some examples:: h1 h2 ...
364,165
def page_index(request): letters = {} for page in Page.query.order_by(Page.name): letters.setdefault(page.name.capitalize()[0], []).append(page) return Response( generate_template("page_index.html", letters=sorted(letters.items())) )
Index of all pages.
364,166
def create_apppool(name): *MyTestPool current_apppools = list_apppools() apppool_path = r.format(name) if name in current_apppools: log.debug("Application pool already present.", name) return True ps_cmd = [, , r"".format(apppool_path)] cmd_ret = _srvmgr(ps_cmd) if cmd_r...
Create an IIS application pool. .. note:: This function only validates against the application pool name, and will return True even if the application pool already exists with a different configuration. It will not modify the configuration of an existing application pool. Args...
364,167
def get_removed_obs_importance(self,obslist_dict=None, reset_zero_weight=False): if obslist_dict is not None: if type(obslist_dict) == list: obslist_dict = dict(zip(obslist_dict,obslist_dict)) elif reset_zero_weight is False and ...
get a dataframe the posterior uncertainty as a result of losing some observations Parameters ---------- obslist_dict : dict dictionary of groups of observations that are to be treated as lost. key values become row labels in returned dataframe. If No...
364,168
def generalized_negative_binomial(mu=1, alpha=1, shape=_Null, dtype=_Null, **kwargs): return _random_helper(_internal._random_generalized_negative_binomial, _internal._sample_generalized_negative_binomial, [mu, alpha], shape, dtype, kwargs)
Draw random samples from a generalized negative binomial distribution. Samples are distributed according to a generalized negative binomial distribution parametrized by *mu* (mean) and *alpha* (dispersion). *alpha* is defined as *1/k* where *k* is the failure limit of the number of unsuccessful experim...
364,169
def ConsultarTributos(self, sep="||"): "Retorna un listado de tributos con código, descripción y signo." ret = self.client.consultarTributos( auth={ : self.Token, : self.Sign, : self.Cuit, }, )[] ...
Retorna un listado de tributos con código, descripción y signo.
364,170
def insert(self, key, value): if key in self.map: return try: tag_key = TagKey(key) tag_val = TagValue(value) self.map[tag_key] = tag_val except ValueError: raise
Inserts a key and value in the map if the map does not already contain the key. :type key: :class: '~opencensus.tags.tag_key.TagKey' :param key: a tag key to insert into the map :type value: :class: '~opencensus.tags.tag_value.TagValue' :param value: a tag value that is associa...
364,171
def copy_security(source, target, obj_type=, copy_owner=True, copy_group=True, copy_dacl=True, copy_sacl=True): rC:\\temp\\source_file.txtC:\\temp\\target_file.txtfileHKLM\\SOFTWARE\\salt\\test_sourceHKLM\\SO...
r''' Copy the security descriptor of the Source to the Target. You can specify a specific portion of the security descriptor to copy using one of the `copy_*` parameters. .. note:: At least one `copy_*` parameter must be ``True`` .. note:: The user account running this command must...
364,172
def publish_event(event_t, data=None, extra_channels=None, wait=None): event = Event(event_t, data) pubsub.publish("shoebot", event) for channel_name in extra_channels or []: pubsub.publish(channel_name, event) if wait is not None: channel = pubsub.subscribe(wait) channel.li...
Publish an event ot any subscribers. :param event_t: event type :param data: event data :param extra_channels: :param wait: :return:
364,173
def equirectangular_distance(self, other): x = math.radians(other.longitude - self.longitude) \ * math.cos(math.radians(other.latitude + self.latitude) / 2); y = math.radians(other.latitude - self.latitude); return math.sqrt(x * x + y * y) * GeoPoint.EARTH_RADIUS_METERS;
Return the approximate equirectangular when the location is close to the center of the cluster. For small distances, Pythagoras’ theorem can be used on an equirectangular projection. Equirectangular formula:: x = Δλ ⋅ cos φm y = Δφ d = R ⋅ √(x² + y)...
364,174
def summarize(self, n_timescales_to_report=5): nonzeros = np.sum(np.abs(self.eigenvectors_) > 0, axis=0) active = % .join([ % (n, self.n_features) for n in nonzeros[:n_timescales_to_report]]) return .format(n_components=self.n_components, shrinkage=self.shrinkage_, lag_time=self.lag_t...
Some summary information.
364,175
def meaning(phrase, source_lang="en", dest_lang="en", format="json"): base_url = Vocabulary.__get_api_link("glosbe") url = base_url.format(word=phrase, source_lang=source_lang, dest_lang=dest_lang) json_obj = Vocabulary.__return_json(url) if json_obj: try: ...
make calls to the glosbe API :param phrase: word for which meaning is to be found :param source_lang: Defaults to : "en" :param dest_lang: Defaults to : "en" For eg: "fr" for french :param format: response structure type. Defaults to: "json" :returns: returns a json object as st...
364,176
def clean_data(data): new_data = [] VALID = ?!.,:; UNK') new_data.append(new_sample) return new_data
Shift to lower case, replace unknowns with UNK, and listify
364,177
def get_context(self, arr, expr, context): expression_names = [x for x in self.get_expression_names(expr) if x not in set(context.keys()).union([])] if len(expression_names) != 1: raise ValueError() return {expression_names[0]: arr}
Returns a context dictionary for use in evaluating the expression. :param arr: The input array. :param expr: The input expression. :param context: Evaluation context.
364,178
def _add_namespace(self, namespace): src_name = namespace.source_name if "*" in src_name: self._regex_map.append((namespace_to_regex(src_name), namespace)) else: self._add_plain_namespace(namespace)
Add an included and possibly renamed Namespace.
364,179
def timezone(zone): rUTCUS/EasternUS/EasternUS/Eastern%Y-%m-%d %H:%M:%S %Z (%z)2002-10-27 01:00:00 EST (-0500)2002-10-27 00:50:00 EST (-0500)2002-10-27 01:50:00 EDT (-0400)2002-10-27 01:10:00 EST (-0500)Asia/Shangri-LaUnknown\N{TRADE MARK SIGN}Unknown if zone.upper() == : return utc try: zo...
r''' Return a datetime.tzinfo implementation for the given timezone >>> from datetime import datetime, timedelta >>> utc = timezone('UTC') >>> eastern = timezone('US/Eastern') >>> eastern.zone 'US/Eastern' >>> timezone(unicode('US/Eastern')) is eastern True >>> utc_dt = datetime(2002, 1...
364,180
def import_complex_gateway_to_graph(diagram_graph, process_id, process_attributes, element): element_id = element.getAttribute(consts.Consts.id) BpmnDiagramGraphImport.import_gateway_to_graph(diagram_graph, process_id, process_attributes, element) diagram_graph.node[element_id][consts.C...
Adds to graph the new element that represents BPMN complex gateway. In addition to attributes inherited from Gateway type, complex gateway has additional attribute default flow (default value - none). :param diagram_graph: NetworkX graph representing a BPMN process diagram, :param proce...
364,181
def apply_all(self, force=False, quiet=False): self._check() top = self.db.top_patch() if top: patches = self.series.patches_after(top) else: patches = self.series.patches() if not patches: raise AllPatchesApplied(self.series, top) ...
Apply all patches in series file
364,182
def delete_resource(self, session, data, api_type, obj_id): resource = self._fetch_resource(session, api_type, obj_id, Permissions.VIEW) self._check_instance_relationships_for_delete(resource) session.delete(resource) session.commit() ...
Delete a resource. :param session: SQLAlchemy session :param data: JSON data provided with the request :param api_type: Type of the resource :param obj_id: ID of the resource
364,183
def unpack_rsp(cls, rsp_pb): if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None return RET_OK, "", None
Convert from PLS response to user response
364,184
def process_block(self, current_block, previous_block, text): prev_fold_level = TextBlockHelper.get_fold_lvl(previous_block) if text.strip() == : fold_level = prev_fold_level else: fold_level = self.detect_fold_level( previous_block, ...
Processes a block and setup its folding info. This method call ``detect_fold_level`` and handles most of the tricky corner cases so that all you have to do is focus on getting the proper fold level foreach meaningful block, skipping the blank ones. :param current_block: current block t...
364,185
def make_fileitem_filepath(filepath, condition=, negate=False, preserve_case=False): document = search = content_type = content = filepath ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate...
Create a node for FileItem/FilePath :return: A IndicatorItem represented as an Element node
364,186
def main(): if not sys.platform.startswith("win"): if "--daemon" in sys.argv: daemonize() from gns3server.run import run run()
Entry point for GNS3 server
364,187
def sendFuture(self, future): future = copy.copy(future) future.greenlet = None future.children = {} try: if shared.getConst(hash(future.callable), timeout=0): future.callable = SharedElementEncapsulation(hash(future.callable)) ...
Send a Future to be executed remotely.
364,188
def append_response(self, response): self._responses.append(response) if in response.headers: LOGGER.warning( , response.request.method, response.request.url, response.code, response.headers[], len(self._responses))
Append the response to the stack of responses. :param tornado.httpclient.HTTPResponse response: The HTTP response
364,189
def split_size(size): rem = size % CHUNK_SIZE if rem == 0: cnt = size // CHUNK_SIZE else: cnt = size // CHUNK_SIZE + 1 chunks = [] for i in range(cnt): pos = i * CHUNK_SIZE if i == cnt - 1: disp = size - pos else: disp = CHUNK_SIZ...
Split the file size into several chunks.
364,190
def writeUTFBytes(self, value): val = None if isinstance(value, unicode): val = value else: val = unicode(value, ) self.stream.write_utf8_string(val)
Writes a UTF-8 string. Similar to L{writeUTF}, but does not prefix the string with a 16-bit length word. @type value: C{str} @param value: The string value to be written.
364,191
def iter_doc_objs(self, **kwargs): _LOG = get_logger() try: for doc_id, fp in self.iter_doc_filepaths(**kwargs): if not self._is_alias(doc_id): with codecs.open(fp, , ) as fo: try: ...
Returns a pair: (doc_id, nexson_blob) for each document in this repository. Order is arbitrary.
364,192
def sample_bitstrings(self, n_samples): possible_bitstrings = np.array(list(itertools.product((0, 1), repeat=len(self)))) inds = np.random.choice(2 ** len(self), n_samples, p=self.probabilities()) bitstrings = possible_bitstrings[inds, :] return bitstrings
Sample bitstrings from the distribution defined by the wavefunction. :param n_samples: The number of bitstrings to sample :return: An array of shape (n_samples, n_qubits)
364,193
def call(self, event, *event_args): assert self.num_listeners(event) == 1, ( % self.num_listeners(event)) listener = self._listeners[event][0] args = list(event_args) + list(listener.user_args) return listener.callback(*args)
Call the single registered listener for ``event``. The listener will be called with any extra arguments passed to :meth:`call` first, and then the extra arguments passed to :meth:`on` Raises :exc:`AssertionError` if there is none or multiple listeners for ``event``. Returns the listene...
364,194
def parse_config_files_and_bindings(config_files, bindings, finalize_config=True, skip_unknown=False): if config_files is None: config_files = [] if bindings is None: bindings = for config_file ...
Parse a list of config files followed by extra Gin bindings. This function is equivalent to: for config_file in config_files: gin.parse_config_file(config_file, skip_configurables) gin.parse_config(bindings, skip_configurables) if finalize_config: gin.finalize() Args: config...
364,195
def z2r(z): with np.errstate(invalid=, divide=): return (np.exp(2 * z) - 1) / (np.exp(2 * z) + 1)
Function that calculates the inverse Fisher z-transformation Parameters ---------- z : int or ndarray Fishers z transformed correlation value Returns ---------- result : int or ndarray Correlation value
364,196
def send_dm_sos(self, message: str) -> None: if self.owner_handle: try: owner_id = self.api.get_user(screen_name=self.owner_handle).id event = { "event": { ...
Send DM to owner if something happens. :param message: message to send to owner. :returns: None.
364,197
def value(self): try: value = self.lastValue except IndexError: value = "NaN" except ValueError: value = "NaN" return value
Take last known value as the value
364,198
def module2md(self, module): modname = module.__name__ path = self.get_src_path(module, append_base=False) path = "[{}]({})".format(path, os.path.join(self.github_link, path)) found = set() classes = [] line_nos = [] for name, obj in getmembers(module, i...
Takes an imported module object and create a Markdown string containing functions and classes.
364,199
def load(self): data = self.dict_class() for path in self.paths: if path in self.paths_loaded: continue try: with open(path, ) as file: path_data = yaml.load(file.read()) data = dict_merge(data...
Load each path in order. Remember paths already loaded and only load new ones.