Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
355,500
def _parseSpec(values): split = values.split(":", 1) name = split[0].strip() rest = split[1] if len(split) == 2 else "" args = [] kwargs = {} def carveRest(s, sep): quotepairs = {"", "\"": "\"", "{":"}", "[":"]", "(":")"} val = "" quote = "" prevC = "" for i, c in enumerate(s): if quote:...
Split the argument string. Example: --arg name:value0,value1,key2=value2,key3=value3 gets split into name, args, kwargs = ( "name", (value0, value1), {"key2":value2, "key3":value3}, )
355,501
def _build_compatibility_members(binding, decorators=None): decorators = decorators or dict() try: import QtSiteConfig except ImportError: pass else: if hasattr(QtSiteConfig, ): QtSiteConfig.update_compatibility_decorators(binding, decorators) _Q...
Apply `binding` to QtCompat Arguments: binding (str): Top level binding in _compatibility_members. decorators (dict, optional): Provides the ability to decorate the original Qt methods when needed by a binding. This can be used to change the returned value to a standard valu...
355,502
def load_stencil_set(self, stencilset_name): if stencilset_name not in self._stencil_sets: if stencilset_name not in self.manifest[].keys(): raise exc.FastfoodStencilSetNotListed( "Stencil set not listed in %s under stencil_sets." % (...
Return the Stencil Set from this template pack.
355,503
def eflux(self, emin, emax, params=None): params = self.params if params is None else params return np.squeeze(self.eval_eflux(emin, emax, params, self.scale, self.extra_params))
Evaluate the integral energy flux.
355,504
def correlation(self, n, k, error=False): r self._calculate_corr(n, k) corr_nk = self._corr[n][k] if error: self._calculate_corr_err(n, k) return corr_nk, self._corr_err[n][k] else: return corr_nk
r""" Calculate `\langle k \rangle_n`, the `k`-particle correlation function for `n`\ th-order anisotropy. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate statistical error (for `\langle 2 \rangle` ...
355,505
def register(self, new_calc, *args, **kwargs): kwargs.update(zip(self.meta_names, args)) if isinstance(kwargs[], basestring): kwargs[] = [kwargs[]] super(CalcRegistry, self).register(new_calc, **kwargs)
Register calculations and meta data. * ``dependencies`` - list of prerequisite calculations * ``always_calc`` - ``True`` if calculation ignores thresholds * ``frequency`` - frequency of calculation in intervals or units of time :param new_calc: register new calculation
355,506
def create(self): logger.info("creating snap7 client") self.library.Cli_Create.restype = c_void_p self.pointer = S7Object(self.library.Cli_Create())
create a SNAP7 client.
355,507
def define_association(self, rel_id, source_kind, source_keys, source_many, source_conditional, source_phrase, target_kind, target_keys, target_many, target_conditional, target_phrase): if isinstance(rel_id, int): ...
Define and return an association from one kind of class (the source kind) to some other kind of class (the target kind).
355,508
def b1_theory(N, mu): if mu == 2: return float(N)*(float(N)+1.0)/6.0 elif mu == 1: return float(N)/2.0 elif mu == 0: return N*np.log(N)/(2.0*(N-1.0)*np.log(2)) elif mu == -1: return 1 elif mu == -2: return (pow(N,2)-1....
Expected B1 ratio for given time-series length N and exponent mu FIXME: add reference (paper & link) The exponents are defined as S_y(f) = h_a f^alpha (power spectrum of y) S_x(f) = g_b f^b (power spectrum of x) bias = const * tau^mu and (...
355,509
def add_link(dataset, source, target, count=1): try: node = dataset[source] values, links = node if isinstance(links, list): try: idx = links.index(target) values[idx] += count except ValueError:...
Add a link. Parameters ---------- dataset : `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`]) Dataset. source : `iterable` of `str` Link source. target : `str` Link target. count : `int`, optional Link count ...
355,510
def get_anchor_contents(markup): soup = BeautifulSoup(markup, ) return [ % link.contents[0] for link in soup.find_all()]
Given HTML markup, return a list of href inner html for each anchor tag.
355,511
def to_python(fname, converter): with hdf5.File(fname, ) as f: source_model = f[] for sg in source_model: for src in sg: if hasattr(src, ): kwargs = getattr(src.mfd, , {}) if not in kwargs: kw...
Convert a source model .hdf5 file into a :class:`SourceModel` object
355,512
def _get_op_name(op, special): opname = op.__name__.strip() if special: opname = .format(opname=opname) return opname
Find the name to attach to this method according to conventions for special and non-special methods. Parameters ---------- op : binary operator special : bool Returns ------- op_name : str
355,513
def sub(self, topics=(b,)): sock = self.__sock(zmq.SUB) for topic in topics: if not isinstance(topic, bytes): error = log.error(error) raise TypeError(error) sock.setsockopt(zmq.SUBSCRIBE, topic) return self.__re...
Returns an iterable that can be used to iterate over incoming messages, that were published with one of the topics specified in ``topics``. Note that the iterable returns as many parts as sent by subscribed publishers. :param topics: a list of topics to subscribe to (default=b'') :type ...
355,514
def get_output_from_steps(stmt, last_step): step_1 opt_values = get_param_of_function( , stmt, extra_dict=env.sos_dict.dict()) def step_name(val): if isinstance(val, str): return val elif isinstance(val, int): if val == -1: if last_step is Non...
Extract output_from(1), output_from('step_1'), and output_from([1, 2]) to determine dependent steps
355,515
def generate (self, ps): assert isinstance(ps, property_set.PropertySet) self.manager_.errors().push_user_context( "Generating target " + self.full_name(), self.user_context_) if self.manager().targets().logging(): self.manager().targets().log( "...
Determines final build properties, generates sources, and calls 'construct'. This method should not be overridden.
355,516
def download_metadata_tar(self,download_dir): if not os.path.isdir(download_dir): os.makedirs(download_dir) res = dxpy.find_one_data_object(project=self.dx_project_id,folder=self.DX_RAW_DATA_FOLDER,name="*metadata.tar",name_mode="glob") dx_file = dxpy.D...
Downloads the ${run_name}.metadata.tar file from the DNAnexus sequencing results project. Args: download_dir: `str` - The local directory path to download the QC report to. Returns: `str`: The filepath to the downloaded metadata tarball.
355,517
def get_data_path(self, filename, env_prefix=None): if env_prefix == None: target_file = filename else: target_file = os.path.join(env_prefix, filename) if os.path.exists(os.path.join(self._data_path, target_file)): return os.path.join(self._data_pat...
Get data path. Args: filename (string) : Name of file inside of /data folder to retrieve. Kwargs: env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa Returns: String - path to file. Usage:: open(WTF_DATA_MANAG...
355,518
def nominate(self, owner_id, player_idx, bid): owner = self.owners[owner_id] nominated_player = self.players[player_idx] if self.state != AuctionState.NOMINATE: raise InvalidActionError("Owner " + str(owner_id) + " tried to nominate, bu...
Nominates the player for auctioning. :param int owner_id: index of the owner who is nominating :param int player_idx: index of the player to nominate in the players list :param int bid: starting bid :raise InvalidActionError: if the action is not allowed according to the rules. See the...
355,519
def _add_op_node(self, op, qargs, cargs, condition=None): node_properties = { "type": "op", "op": op, "name": op.name, "qargs": qargs, "cargs": cargs, "condition": condition } self._max_node_id += 1 ...
Add a new operation node to the graph and assign properties. Args: op (Instruction): the operation associated with the DAG node qargs (list): list of quantum wires to attach to. cargs (list): list of classical wires to attach to. condition (tuple or None): option...
355,520
def update_identity_pool(IdentityPoolId, IdentityPoolName=None, AllowUnauthenticatedIdentities=False, SupportedLoginProviders=None, DeveloperProviderName=None, OpenIdConnectProviderARNs=None, ...
Updates the given IdentityPoolId's properties. All parameters except for IdentityPoolId, is optional. SupportedLoginProviders should be a dictionary mapping provider names to provider app IDs. OpenIdConnectProviderARNs should be a list of OpenID Connect provider ARNs. To clear SupportedLoginProvider...
355,521
def GET_subdomains( self, path_info ): qs_values = path_info[] page = qs_values.get(, None) if page is None: log.error("Page required") return self._reply_json({: }, status_code=400) try: page = int(page) assert page >= 0 ...
Get all subdomains in existence. Requires page={int} Returns the list on success Returns 400 on invalid arguments Returns 502 on failure to get names
355,522
def is_null(value): if type(value) in (tuple, list): for v in value: if v is None: return True return False else: return value is None
Check if the scalar value or tuple/list value is NULL. :param value: Value to check. :type value: a scalar or tuple or list :return: Returns ``True`` if and only if the value is NULL (scalar value is None or _any_ tuple/list elements are None). :rtype: bool
355,523
def current_time_is_in_interval(start, end): interval_start = parse_lms_api_datetime(start or UNIX_MIN_DATE_STRING) interval_end = parse_lms_api_datetime(end or UNIX_MAX_DATE_STRING) return interval_start <= timezone.now() <= interval_end
Determine whether the current time is on the interval [start, end].
355,524
def __schema_descriptor(self, services): methods_desc = {} for service in services: protorpc_methods = service.all_remote_methods() for protorpc_method_name in protorpc_methods.iterkeys(): rosy_method = % (service.__name__, protorpc_method_name) method_id = self.__id_from_name...
Descriptor for the all the JSON Schema used. Args: services: List of protorpc.remote.Service instances implementing an api/version. Returns: Dictionary containing all the JSON Schema used in the service.
355,525
def _base_placeholder(self): layout, idx = self.part.slide_layout, self._element.ph_idx return layout.placeholders.get(idx=idx)
Return the layout placeholder this slide placeholder inherits from. Not to be confused with an instance of |BasePlaceholder| (necessarily).
355,526
async def get_image( self, input_source: str, output_format: str = IMAGE_JPEG, extra_cmd: Optional[str] = None, timeout: int = 15, ) -> Optional[bytes]: command = ["-an", "-frames:v", "1", "-c:v", output_format] is_open = await self.open( ...
Open FFmpeg process as capture 1 frame.
355,527
def get_own_ip(): own_ip = None interfaces = psutil.net_if_addrs() for _, details in interfaces.items(): for detail in details: if detail.family == socket.AF_INET: ip_address = ipaddress.ip_address(detail.address) if not (ip_address.is_link_local or i...
Gets the IP from the inet interfaces.
355,528
def has_successor(self, graph, orig, dest, branch, turn, tick, *, forward=None): if forward is None: forward = self.db._forward return dest in self._get_destcache(graph, orig, branch, turn, tick, forward=forward)
Return whether an edge connects the origin to the destination at the given time. Doesn't require the edge's index, which makes it slower than retrieving a particular edge.
355,529
def start(self, trunk_type): if not isinstance(trunk_type, basestring): raise TypeError("trunk_type can only be an instance of type basestring") self._call("start", in_p=[trunk_type])
Type of internal network trunk. in trunk_type of type str Type of internal network trunk.
355,530
def get_negative_cycle(self): costcost nl = self.get_node_list() i = nl[0] (valid, distance, nextn) = self.floyd_warshall() if not valid: cycle = self.floyd_warshall_get_cycle(distance, nextn) return cycle else: return None
API: get_negative_cycle(self) Description: Finds and returns negative cost cycle using 'cost' attribute of arcs. Return value is a list of nodes representing cycle it is in the following form; n_1-n_2-...-n_k, when the cycle has k nodes. Pre: A...
355,531
def discard(self, msg, reason, logMethod=logging.error, cliOutput=False): reason = "" if not reason else " because {}".format(reason) logMethod("{} discarding message {}{}".format(self, msg, reason), extra={"cli": cliOutput})
Discard a message and log a reason using the specified `logMethod`. :param msg: the message to discard :param reason: the reason why this message is being discarded :param logMethod: the logging function to be used :param cliOutput: if truthy, informs a CLI that the logged msg should ...
355,532
def _get_reference(self): sha, target_ref_path = self._get_ref_info(self.repo, self.path) if target_ref_path is None: raise TypeError("%s is a detached symbolic reference as it points to %r" % (self, sha)) return self.from_path(self.repo, target_ref_path)
:return: Reference Object we point to :raise TypeError: If this symbolic reference is detached, hence it doesn't point to a reference, but to a commit
355,533
def _value_from_label(self, label): unser_val = (label.rel_strength.value, label.meta) return cbor.dumps(unser_val)
Convert a label into a kvl value.
355,534
def _extract_local_histogram(image, mask=slice(None), bins=19, rang="image", cutoffp=(0.0, 100.0), size=None, footprint=None, output=None, mode="ignore", origin=0): if "constant" == mode: raise RuntimeError() elif "ignore" == mode: mode = "constant" if == rang: rang = tuple(num...
Internal, single-image version of @see local_histogram Note: Values outside of the histograms range are not considered. Note: Mode constant is not available, instead a mode "ignore" is provided. Note: Default dtype of returned values is float.
355,535
def configure_logging(level=logging.DEBUG): fmt = datefmt = formatter = logging.Formatter(fmt=fmt, datefmt=datefmt) logger = logging.getLogger() stderr_handler = logging.StreamHandler(stream=sys.stderr) stderr_handler.name = stderr_handler.setLevel(level) stderr_handler.setFo...
Configures the root logger for command line applications. A stream handler will be added to the logger that directs messages to the standard error stream. By default, *no* messages will be filtered out: set a higher level on derived/child loggers to achieve filtering. Warning ------- Logg...
355,536
def _SerializeAttributeContainer(self, attribute_container): if self._serializers_profiler: self._serializers_profiler.StartTiming( attribute_container.CONTAINER_TYPE) try: attribute_container_data = self._serializer.WriteSerialized( attribute_container) if not attrib...
Serializes an attribute container. Args: attribute_container (AttributeContainer): attribute container. Returns: bytes: serialized attribute container. Raises: IOError: if the attribute container cannot be serialized. OSError: if the attribute container cannot be serialized.
355,537
def _exec_eval(data, expr): ns = {} exec(data, ns) return eval(expr, ns)
Internal function to isolate an exec. Executes ``data`` and returns the ``expr`` evaluation afterwards.
355,538
def update_instance( self, update_mask, instance, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): if "update_instance" not in self._inner_api_calls: self._inner_api...
Updates the metadata and configuration of a specific Redis instance. Completed longrunning.Operation will contain the new instance object in the response field. The returned operation is automatically deleted after a few hours, so there is no need to call DeleteOperation. Example: ...
355,539
def ingest(self): self.log.debug() dictList = self._create_dictionary_of_ned_d() self.primaryIdColumnName = "primaryId" self.raColName = "raDeg" self.declColName = "decDeg" tableName = self.dbTableName createStatement = u % locals() self.add_da...
Import the ned_d catalogue into the catalogues database The method first generates a list of python dictionaries from the ned_d datafile, imports this list of dictionaries into a database table and then generates the HTMIDs for that table. **Usage:** See class docstring for usage ...
355,540
def add_password_arg(cmd, psw, ___required=False): if UNRAR_TOOL == ALT_TOOL: return if psw is not None: cmd.append( + psw) else: cmd.append()
Append password switch to commandline.
355,541
def convert_to_experiment_list(experiments): exp_list = experiments if experiments is None: exp_list = [] elif isinstance(experiments, Experiment): exp_list = [experiments] elif type(experiments) is dict: exp_list = [ Experiment.from_json(name, spec) ...
Produces a list of Experiment objects. Converts input from dict, single experiment, or list of experiments to list of experiments. If input is None, will return an empty list. Arguments: experiments (Experiment | list | dict): Experiments to run. Returns: List of experiments.
355,542
def onPersonRemoved( self, mid=None, removed_id=None, author_id=None, thread_id=None, ts=None, msg=None, ): log.info("{} removed: {} in {}".format(author_id, removed_id, thread_id))
Called when the client is listening, and somebody removes a person from a group thread :param mid: The action ID :param removed_id: The ID of the person who got removed :param author_id: The ID of the person who removed the person :param thread_id: Thread ID that the action was sent to....
355,543
def parse_init_dat(infile): init_dict = {} log.debug(.format(infile)) with open(infile, ) as f: head = [next(f).strip() for x in range(2)] summary = head[0].split() difficulty = summary[1] top_template_info = head[1].split() top_template_pdbchain = top_template...
Parse the main init.dat file which contains the modeling results The first line of the file init.dat contains stuff like:: "120 easy 40 8" The other lines look like this:: " 161 11.051 1 1guqA MUSTER" and getting the first 10 gives you the top 10 templates us...
355,544
def keyval_typ2str(var, val): varout = var.strip() if isinstance(val, list): data = ", ".join([keyval_typ2str(var, it)[1] for it in val]) valout = "["+data+"]" elif isinstance(val, float): valout = "{:.12f}".format(val) else: valout = "{}".format(val) return varo...
Convert a variable to a string Parameters ---------- var: str The variable name val: any type The value of the variable Returns ------- varout: str Stripped lowercase `var` valout: any type The value converted to a useful string representation See A...
355,545
def values(self, multi=False): for values in itervalues(self): if multi: for value in values: yield value else: yield values[-1]
Yield the last value on every key list. :param multi: If set to `True` the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the lasted added of each key.
355,546
def command_loop(self, run_script_event): while True: obj = remote_client.receive(self) command = obj["command"] args = obj.get(, {}) if command == : breakpoints_list = IKBreakpoint.get_breakpoints_list() ...
This is the debugger command loop that processes (protocol) client requests.
355,547
def on_session_destroyed(self, *callbacks): for callback in callbacks: _check_callback(callback, (,)) self._session_destroyed_callbacks.add(callback)
Provide callbacks to invoke when the session serving the Document is destroyed
355,548
def color_hex(self): def clamp(x): return max(0, min(int(x), 255)) r, g, b = np.trunc(self.color_rgb * 255) return "
Node color as Hex Triplet https://en.wikipedia.org/wiki/Web_colors#Hex_triplet
355,549
def add_default(self, key: str, value: Optional[str], default_type: type = str) -> None: self.defaults[key] = HierarkeyDefault(value, default_type)
Adds a default value and a default type for a key. :param key: Key :param value: *Serialized* default value, i.e. a string or ``None``. :param default_type: The type to unserialize values for this key to, defaults to ``str``.
355,550
def main(): usage = "usage: %(prog)s [options] " description = "Gather source maps from Fermi-LAT files." parser = argparse.ArgumentParser(usage=usage, description=description) parser.add_argument(, , default=None, type=str, help=) parser.add_argument(, default=False, ...
Main function for command line usage
355,551
def recursive_exclude(self, dir, pattern): match = translate_pattern(os.path.join(dir, , pattern)) return self._remove_files(match.match)
Exclude any file anywhere in 'dir/' that match the pattern.
355,552
def latsrf(method, target, et, fixref, lonlat): method = stypes.stringToCharP(method) target = stypes.stringToCharP(target) et = ctypes.c_double(et) fixref = stypes.stringToCharP(fixref) npts = ctypes.c_int(len(lonlat)) lonlat = stypes.toDoubleMatrix(lonlat) srfpts = stypes.emptyD...
Map array of planetocentric longitude/latitude coordinate pairs to surface points on a specified target body. The surface of the target body may be represented by a triaxial ellipsoid or by topographic data provided by DSK files. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latsrf_...
355,553
def new_ele_description(**kwargs): desc = { :None, :None, :None, :None, :None, :None, :None, :None, :None, :None, :None, :None, :None, :None, :None, :None, :None, :Non...
from elist.elist import * from elist.jprint import pobj root_desc = new_ele_description(leaf=False,depth=0,breadth_path=[],path=[],parent_path=[],parent_breadth_path=[]) pobj(root_desc) #None means not handled
355,554
def wrongstatus(data, sb, msb, lsb): status = int(data[sb-1]) value = bin2int(data[msb-1:lsb]) if not status: if value != 0: return True return False
Check if the status bit and field bits are consistency. This Function is used for checking BDS code versions.
355,555
def load_unicode(self, resource_path): resource_content = pkg_resources.resource_string(self.module_name, resource_path) return resource_content.decode()
Gets the content of a resource
355,556
def send_item(self, destination, item_id, force_send): data = json.dumps({ : force_send, }) url_suffix = "{}/send/".format(item_id) resp = requests.post(self.make_url(destination, url_suffix), headers=self.json_headers, data=data) self.check_response(resp) ...
Run send method for item_id at destination. :param destination: str which type of operation are we doing (SHARE_DESTINATION or DELIVER_DESTINATION) :param item_id: str D4S2 service id representing the item we want to send :param force_send: bool it's ok to email the item again :return: r...
355,557
def post_resource(url, body): response = Bridge_DAO().postURL(url, PHEADER, body) log_data = "POST %s %s ==status==> %s" % (url, body, response.status) if response.status != 200 and response.status != 201: _raise_exception(log_data, url, response) _log_resp(log_data, response.dat...
Post resource with the given json body :returns: http response data
355,558
def results(self, Pc): r phase = self.project.find_phase(self) net = self.project.network inv_p = self[].copy() inv_t = self[].copy() if np.sum(self[] == -1) > 0: inv_p[self[] == -1] = Pc + 1 if np.sum(self[] == -1) > 0: ...
r""" Places the results of the IP simulation into the Phase object. Parameters ---------- Pc : float Capillary Pressure at which phase configuration was reached
355,559
def unicode_urlencode(obj, charset=, for_qs=False): if not isinstance(obj, string_types): obj = text_type(obj) if isinstance(obj, text_type): obj = obj.encode(charset) safe = not for_qs and b or b rv = text_type(url_quote(obj, safe)) if for_qs: rv = rv.replace(, ) re...
URL escapes a single bytestring or unicode string with the given charset if applicable to URL safe quoting under all rules that need to be considered under all supported Python versions. If non strings are provided they are converted to their unicode representation first.
355,560
def data_groups(self, groups, entity_count): data = [] for xid in groups.keys(): assoc_group_data = self.data_group_association(xid) data += assoc_group_data entity_count += len(assoc_group_data) if entity_count >= self._bat...
Process Group data. Args: groups (list): The list of groups to process. Returns: list: A list of groups including associations
355,561
def to_csv(self, path_or_buf=None, sep=",", na_rep=, float_format=None, columns=None, header=True, index=True, index_label=None, mode=, encoding=None, compression=, quoting=None, quotechar=, line_terminator=None, chunksize=None, tupleize_cols=None, date_format...
r""" Write object to a comma-separated values (csv) file. .. versionchanged:: 0.24.0 The order of arguments for Series was changed. Parameters ---------- path_or_buf : str or file handle, default None File path or object, if None is provided the result i...
355,562
def peekView(self, newLength): return memoryview(self.buf)[self.offset:self.offset + newLength]
Return a view of the next newLength bytes.
355,563
def get_logger(process_name, append_to_console=None, redirect_stdstream=None): if append_to_console is None: append_to_console = settings.settings[] if redirect_stdstream is None: redirect_stdstream=not settings.settings[] if process_name not in logger_pool: file_name = get_log...
method returns initiated logger
355,564
def listar_por_ambiente(self, id_ambiente): if not is_valid_int_param(id_ambiente): raise InvalidParameterError(u) url = + str(id_ambiente) + code, xml = self.submit(None, , url) key = return get_list_map(self.response(code, xml, [key]), key)
List all VLANs from an environment. ** The itens returning from network is there to be compatible with other system ** :param id_ambiente: Environment identifier. :return: Following dictionary: :: {'vlan': [{'id': < id_vlan >, 'nome': < nome_vlan >, 'num_...
355,565
def iterate(self, func, args=None, filter=[]): def blag(node, args)nodec1c2pc1c2 hellohello phello c2hello c1hello_name=="c1"hello c1 with self._mutex: result = [] if filter: filters_passed = True for f in filter: if type(f) == ...
Call a function on this node, and recursively all its children. This is a depth-first iteration. @param func The function to call. Its declaration must be 'def blag(node, args)', where 'node' is the current node in the iteration and args is the value of @ref arg...
355,566
def update_function( cfg, path_to_zip_file, existing_cfg, use_s3=False, s3_file=None, preserve_vpc=False ): print() byte_stream = read(path_to_zip_file, binary_file=True) profile_name = cfg.get() aws_access_key_id = cfg.get() aws_secret_access_key = cfg.get() account_id = get_acco...
Updates the code of an existing Lambda function
355,567
def show(fig=None, path=, **kwargs): import webbrowser fullpath = os.path.abspath(path) with open(fullpath, ) as f: save_html(fig, fileobj=f, **kwargs) webbrowser.open( + fullpath)
Convert a Matplotlib Figure to a Leaflet map. Open in a browser Parameters ---------- fig : figure, default gcf() Figure used to convert to map path : string, default '_map.html' Filename where output html will be saved See fig_to_html() for description of keyword args.
355,568
def get_qrcode_url(self, shop_id, img_id): res = self._post( , data={ : shop_id, : img_id, }, result_processor=lambda x: x[][] ) return res
获取物料二维码图片网址 详情请参考 http://mp.weixin.qq.com/wiki/7/fcd0378ef00617fc276be2b3baa80973.html :param shop_id: 门店 ID :param img_id: 物料样式编号:0-二维码,可用于自由设计宣传材料; 1-桌贴(二维码),100mm×100mm(宽×高),可直接张贴 :return: 二维码图片网址
355,569
def geometric_fba(model, epsilon=1E-06, max_tries=200, processes=None): with model: consts = [] obj_vars = [] updating_vars_cons = [] prob = model.problem add_pfba(model) model.optimize() fva_sol = flux_variability_analysis(model, pr...
Perform geometric FBA to obtain a unique, centered flux distribution. Geometric FBA [1]_ formulates the problem as a polyhedron and then solves it by bounding the convex hull of the polyhedron. The bounding forms a box around the convex hull which reduces with every iteration and extracts a unique solu...
355,570
def optimize(model,cand,obj): model.setObjective(obj,"minimize") model.optimize() x,y,C,U = model.data status = model.getStatus() if status == "optimal" or status == "bestsollimit": sols = model.getSols() for sol in sols: cand.append((model.getVal(var=U,soluti...
optimize: function for solving the model, updating candidate solutions' list Parameters: - model: Gurobi model object - cand: list of pairs of objective functions (for appending more solutions) - obj: name of a model's variable to setup as objective Returns the solver's exit status
355,571
def listscripts(self): code, data, listing = self.__send_command( "LISTSCRIPTS", withcontent=True) if code == "NO": return None ret = [] active_script = None for l in listing.splitlines(): if self.__size_expr.match(l): ...
List available scripts. See MANAGESIEVE specifications, section 2.7 :returns: a 2-uple (active script, [script1, ...])
355,572
def aggregate(self, rankings, breaking="full", k=None): breakings = { "full": self._full, "top": self._top, "bottom": self._bot, "adjacent": self._adj, "position": self._pos } if (k == ...
Description: Takes in a set of rankings and computes the Plackett-Luce model aggregate ranking. Parameters: rankings: set of rankings to aggregate breaking: type of breaking to use k: number to be used for top, bottom, and position breakin...
355,573
def edit(self, title=github.GithubObject.NotSet, body=github.GithubObject.NotSet, assignee=github.GithubObject.NotSet, state=github.GithubObject.NotSet, milestone=github.GithubObject.NotSet, labels=github.GithubObject.NotSet, assignees=github.GithubObject.NotSet): assert title is github.GithubObject.No...
:calls: `PATCH /repos/:owner/:repo/issues/:number <http://developer.github.com/v3/issues>`_ :param title: string :param body: string :param assignee: string or :class:`github.NamedUser.NamedUser` or None :param assignees: list (of string or :class:`github.NamedUser.NamedUser`) :p...
355,574
def reset_dq_bits(input,bits,extver=None,extname=): bits = interpret_bit_flags(bits) flist, fcol = parseinput.parseinput(input) for filename in flist: p = fits.open(filename, mode=, memmap=False) if extver is None: extver = [] fo...
This function resets bits in the integer array(s) of a FITS file. Parameters ---------- filename : str full filename with path bits : str sum or list of integers corresponding to all the bits to be reset extver : int, optional List of version numbers of the DQ arrays ...
355,575
def start_output (self): super(DOTLogger, self).start_output() if self.has_part("intro"): self.write_intro() self.writeln() self.writeln(u"digraph G {") self.writeln(u" graph [") self.writeln(u" charset=\"%s\"," % self.get_charset_encoding()) ...
Write start of checking info as DOT comment.
355,576
def unpack(self, data, namedstruct): try: result = self.struct.unpack(data[0:self.struct.size]) except struct.error as exc: raise BadFormatError(exc) start = 0 t = namedstruct._target for p in self.properties: if len(p) > 1: ...
Unpack the struct from specified bytes. If the struct is sub-classed, definitions from the sub type is not unpacked. :param data: bytes of the struct, including fields of sub type and "extra" data. :param namedstruct: a NamedStruct object of this type :returns:...
355,577
def save_policy(self, path): with open(path, ) as f: pickle.dump(self.policy, f)
Pickles the current policy for later inspection.
355,578
def convert_from_eclipse(self, eclipse_projects): projects = {} projects[] = { "gerrit": ["git.eclipse.org"], "bugzilla": ["https://bugs.eclipse.org/bugs/"] } projects = compose_title(projects, eclipse_projects) projects = compose_proj...
Convert from eclipse projects format to grimoire projects json format
355,579
def get_target_state(): sdp_state = SDPState() errval, errdict = _check_status(sdp_state) if errval == "error": LOG.debug(errdict[]) return dict( current_target_state="unknown", last_updated="unknown", reason=errdict[] ) LOG.debug() ta...
SDP target State. Returns the target state; allowed target states and time updated
355,580
def name(self, filetype, **kwargs): full = kwargs.get(, None) if not full: full = self.full(filetype, **kwargs) return os.path.basename(full)
Return the directory containing a file of a given type. Parameters ---------- filetype : str File type parameter. Returns ------- name : str Name of a file with no directory information.
355,581
def copy(self): return CIMQualifierDeclaration( self.name, self.type, value=self.value, is_array=self.is_array, array_size=self.array_size, scopes=self.scopes, overridable=self.overridable, tosubclass=self...
Return a new :class:`~pywbem.CIMQualifierDeclaration` object that is a copy of this CIM qualifier type. Objects of this class have no mutable types in any attributes, so modifications of the original object will not affect the returned copy, and vice versa. Note that the Python...
355,582
def knot_removal(degree, knotvector, ctrlpts, u, **kwargs): tol = kwargs.get(, 10e-4) num = kwargs.get(, 1) s = kwargs.get(, find_multiplicity(u, knotvector)) r = kwargs.get(, find_span_linear(degree, knotvector, len(ctrlpts), u)) if num < 1: return ctrlpts first...
Computes the control points of the rational/non-rational spline after knot removal. Implementation based on Algorithm A5.8 and Equation 5.28 of The NURBS Book by Piegl & Tiller Keyword Arguments: * ``num``: number of knot removals :param degree: degree :type degree: int :param knotvector:...
355,583
def _processValueItem(element, reg_key, reg_valuename, policy, parent_element, check_deleted=False, this_element_value=None): registry = Registry() expected_string = None this_vtype = encoded_semicolon = .encode() encoded_null = chr(0).encode() if reg_key: ...
helper function to process a value type item and generate the expected string in the Registry.pol file element - the element to process reg_key - the registry key associated with the element (some inherit from their parent policy) reg_valuename - the registry valueName associated with the...
355,584
def make_figs(dcfg,dp=,force=False): doutp=abspath(dp) if isinstance(dcfg,str): dcfg=pd.read_table(dcfg, error_bad_lines=False, comment=,) dcfg=configure(dcfg,doutp,force=force) templatep=f"{doutp}/masonry/index.html" if not ...
'figi','plotp'
355,585
def parse(self, scope): self.name, args, self.guards = self.tokens[0] self.args = [a for a in utility.flatten(args) if a] self.body = Block([None, self.tokens[1]], 0) self.vars = list( utility.flatten([ list(v.values()) for v in [s[] for s in scope] ...
Parse node args: scope (Scope): current scope raises: SyntaxError returns: self
355,586
def parser_factory(lang): class_ = { : ChineseSimplifiedParser, : ChineseTraditionalParser, : ChineseParser, : CantoneseSimplifiedParser, : CantoneseTraditionalParser, : CantoneseParser, : ThaiParser, : Tha...
Returns a Parser object specific to the language specified by :param:`lang`. :param lang: A string naming the desired parser. See the keys in :var:`class_` for valid strings. :Example: >>> chinese_parser = parser_factory('zh-Hans') >>> isinstance(chinese_parser, ChineseSimplifiedParser) True...
355,587
def set_fetcher(self, fetcher_class): self._lock.acquire() try: self._fetcher = fetcher_class finally: self._lock.release()
Set the fetcher class. :Parameters: - `fetcher_class`: the fetcher class. :Types: - `fetcher_class`: `CacheFetcher` based class
355,588
def get_age_info(self, filename=None): if not filename: short_filename = magic_file = os.path.join(self.WD, short_filename) else: magic_file = filename if not os.path.isfile(magic_file): print(.format(magic_file)) ret...
Read er_ages.txt file. Parse information into dictionaries for each site/sample. Then add it to the site/sample object as site/sample.age_data.
355,589
def factory(opts, **kwargs): import salt.transport.ipc return salt.transport.ipc.IPCMessageServer(opts, **kwargs)
If we have additional IPC transports other than UXD and TCP, add them here
355,590
def returner(load): conn = _get_conn() if conn is None: return None cur = conn.cursor() sql = try: ret = six.text_type(load[]) except UnicodeDecodeError: ret = str(load[]) job_ret = {: ret} if in load: job_ret[] = load[] if in load: job...
Return data to a postgres server
355,591
def add_to_file_links(self): if not self._initialized: raise pycdlibexception.PyCdlibInternalError() if self.dr_entries.px_record is None: if self.ce_entries.px_record is None: raise pycdlibexception.PyCdlibInvalidInput() self.ce_ent...
Increment the number of POSIX file links on this entry by one. Parameters: None. Returns: Nothing.
355,592
def log(self, *lines): if getattr(self, "debug", False): print(dt.datetime.now().time(), end=) for line in lines: print(line, end=) print()
will print out the lines in console if debug is enabled for the specific sprite
355,593
def compute_key_composite(password=None, keyfile=None): if password: password_composite = hashlib.sha256(password.encode()).digest() else: password_composite = b if keyfile: try: with open(keyfile, ) as f: tree = etree.parse(f).get...
Compute composite key. Used in header verification and payload decryption.
355,594
def oldest_frame(self, raw=False): if raw: return self.buffer.values[:, self._oldest_frame_idx(), :] return self.buffer.iloc[:, self._oldest_frame_idx(), :]
Get the oldest frame in the panel.
355,595
def load(self, key): if isinstance(key, basestring): key = BucketKey.decode(key) if key.uuid != self.uuid: raise ValueError("%s is not a bucket corresponding to this limit" % key) if key.version ...
Given a bucket key, load the corresponding bucket. :param key: The bucket key. This may be either a string or a BucketKey object. :returns: A Bucket object.
355,596
def init_layout(self): self.widget = QGraphicsProxyWidget(self.parent_widget()) widget = self.widget for item in self.child_widgets(): widget.setWidget(item) break super(QtGraphicsWidget, self).init_widget() super(QtGraphicsWidget, self).init_layo...
Create the widget in the layout pass after the child widget has been created and intialized. We do this so the child widget does not attempt to use this proxy widget as its parent and because repositioning must be done after the widget is set.
355,597
def raise_exception(entity_type, entity, exception): raise exception( u.format(entity_type, entity).encode() )
Exception helper
355,598
def getApplicationsThatSupportMimeType(self, pchMimeType, pchAppKeysThatSupportBuffer, unAppKeysThatSupportBuffer): fn = self.function_table.getApplicationsThatSupportMimeType result = fn(pchMimeType, pchAppKeysThatSupportBuffer, unAppKeysThatSupportBuffer) return result
Get the list of app-keys that support this mime type, comma-delimited, the return value is number of bytes you need to return the full string
355,599
def append(*vectors): r if len(vectors) < 2: return vectors[0] vectors = list(vectors) for i in range(len(vectors)): vectors[i] = numpy.asarray(vectors[i]) if vectors[i].ndim == 1: vectors[i] = numpy.asarray([vectors[i]]).T return numpy.squeeze(num...
r""" Takes an arbitrary number of vectors containing features and append them (horizontally). E.g. taking a 100 and a 200 sample vector with 7 features each, a 300x7 vector is returned. The vectors are expected to have the form samples*features i.e.:: s1 s2 s3 [.....