Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
13,800
def __return_json(url): with try_URL(): response = requests.get(url) if response.status_code == 200: return response.json() else: return False
Returns JSON data which is returned by querying the API service Called by - meaning() - synonym() :param url: the complete formatted url which is then queried using requests :returns: json content being fed by the API
13,801
def _get_warped_array( input_file=None, indexes=None, dst_bounds=None, dst_shape=None, dst_crs=None, resampling=None, src_nodata=None, dst_nodata=None ): try: return _rasterio_read( input_file=input_file, indexes=indexes, dst_bounds=ds...
Extract a numpy array from a raster file.
13,802
def from_xmldict(cls, xml_dict): name = xml_dict[] kwargs = {} if in xml_dict: kwargs[] = xml_dict[] return cls(name, **kwargs)
Create an `Author` from a datacite3 metadata converted by `xmltodict`. Parameters ---------- xml_dict : :class:`collections.OrderedDict` A `dict`-like object mapping XML content for a single record (i.e., the contents of the ``record`` tag in OAI-PMH XML). This d...
13,803
def estimate_size_in_bytes(cls, key, value, headers): return ( cls.HEADER_STRUCT.size + cls.MAX_RECORD_OVERHEAD + cls.size_of(key, value, headers) )
Get the upper bound estimate on the size of record
13,804
def load(self, context): try: import tensorflow except ImportError: return from tensorboard.plugins.beholder.beholder_plugin import BeholderPlugin return BeholderPlugin(context)
Returns the plugin, if possible. Args: context: The TBContext flags. Returns: A BeholderPlugin instance or None if it couldn't be loaded.
13,805
def _http_get_json(self, url): response = self._http_get(url) content_type = response.headers[] parsed_mimetype = mimeparse.parse_mime_type(content_type) if parsed_mimetype[1] not in (, ): raise PythonKCMeetupsNotJson(content_type) try: return j...
Make an HTTP GET request to the specified URL, check that it returned a JSON response, and returned the data parsed from that response. Parameters ---------- url The URL to GET. Returns ------- Dictionary of data parsed from a JSON HTTP response. ...
13,806
def list_(runas=None): * rubies = [] output = _rvm([], runas=runas) if output: regex = re.compile(r) for line in output.splitlines(): match = regex.match(line) if match: rubies.append([ match.group(2), match.group(3), match.grou...
List all rvm-installed rubies runas The user under which to run rvm. If not specified, then rvm will be run as the user under which Salt is running. CLI Example: .. code-block:: bash salt '*' rvm.list
13,807
def hello(self): for env in self.args.environment: juicer.utils.Log.log_info("Trying to open a connection to %s, %s ...", env, self.connectors[env].base_url) try: _r = self.connectors[env].get() juicer.utils.L...
Test pulp server connections defined in ~/.config/juicer/config.
13,808
def delete_mutating_webhook_configuration(self, name, **kwargs): kwargs[] = True if kwargs.get(): return self.delete_mutating_webhook_configuration_with_http_info(name, **kwargs) else: (data) = self.delete_mutating_webhook_configuration_with_http_info(name, **kwa...
delete a MutatingWebhookConfiguration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_mutating_webhook_configuration(name, async_req=True) >>> result = thread.get() :param async_req...
13,809
def add_instruction (self, instr): assert(isinstance(instr, Instruction)) self.instruction_list.append(instr) if instr.lhs not in self.defined_variables: if isinstance(instr.lhs, Variable): self.defined_variables.append(instr.lhs) if isinstance(instr,...
Adds the argument instruction in the list of instructions of this basic block. Also updates the variable lists (used_variables, defined_variables)
13,810
def varvalu(self, varn=None): self.ignore(whitespace) if varn is None: varn = self.varname() varv = s_ast.VarValue(kids=[varn]) while self.more(): if self.nextstr(): varv = self.varderef(varv) continue ...
$foo $foo.bar $foo.bar() $foo[0] $foo.bar(10)
13,811
def processRequest(cls, ps, **kw): resource = kw[] method = resource.getOperation(ps, None) rsp = method(ps, **kw)[1] return rsp
invokes callback that should return a (request,response) tuple. representing the SOAP request and response respectively. ps -- ParsedSoap instance representing HTTP Body. request -- twisted.web.server.Request
13,812
def remove(self, package, shutit_pexpect_child=None, options=None, echo=None, timeout=shutit_global.shutit_global_object.default_timeout, note=None): shutit_global.shutit_global_object.yield_to_draw() if package.find() != -1: for p in ...
Distro-independent remove function. Takes a package name and runs relevant remove function. @param package: Package to remove, which is run through package_map. @param shutit_pexpect_child: See send() @param options: Dict of options to pass to the remove command, mapped by install_type....
13,813
def get_json_files(files, recursive=False): json_files = [] if not files: return json_files for fn in files: if os.path.isdir(fn): children = list_json_files(fn, recursive) json_files.extend(children) elif is_json(fn): json_files.append(fn) ...
Return a list of files to validate from `files`. If a member of `files` is a directory, its children with a ``.json`` extension will be added to the return value. Args: files: A list of file paths and/or directory paths. recursive: If ``true``, this will descend into any subdirectories ...
13,814
def persist(filename): dem_projected = obtain_to(filename) with nc.loader(filename) as root: data = nc.getvar(root, ) dem = nc.getvar(root, , , source=data) stack = [dim for dim in dem.shape if dim not in dem_projected.shape] stack = stack[0] if stack else 1 dem[:] =...
Append the digital elevation map projected (using lat lon) as variables of the netcdf file. Keyword arguments: filename -- the name of a netcdf file.
13,815
def _recover_public_key(G, order, r, s, i, e): c = G.curve() x = r + (i // 2) * order alpha = (x * x * x + c.a() * x + c.b()) % c.p() beta = pycoin.ecdsa.numbertheory.modular_sqrt(alpha, c.p()) y = beta if (beta - i) % 2 == 0 else c.p() - beta R = pycoin.ecdsa.ellipticcur...
Recover a public key from a signature. See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public Key Recovery Operation". http://www.secg.org/sec1-v2.pdf
13,816
def update_endpoint(self, endpoint_name, endpoint_config_name): if not _deployment_entity_exists(lambda: self.sagemaker_client.describe_endpoint(EndpointName=endpoint_name)): raise ValueError( .format(endpoint_name)) self.sagemaker_client.update_endpoin...
Update an Amazon SageMaker ``Endpoint`` according to the endpoint configuration specified in the request Raise an error if endpoint with endpoint_name does not exist. Args: endpoint_name (str): Name of the Amazon SageMaker ``Endpoint`` to update. endpoint_config_name (str): Nam...
13,817
def program_global_reg(self): self._clear_strobes() gr_size = len(self[][:]) self[][][0:gr_size] = self[][:] self[][][0:gr_size] = bitarray(gr_size * ) self[][][gr_size + 1:gr_size + 2] = bitarray("1") self[][][gr_size + 1:gr_size + 2] = bitarray("1") ...
Send the global register to the chip. Loads the values of self['GLOBAL_REG'] onto the chip. Includes enabling the clock, and loading the Control (CTR) and DAC shadow registers.
13,818
def find_connected_atoms(struct, tolerance=0.45, ldict=JmolNN().el_radius): n_atoms = len(struct.species) fc = np.array(struct.frac_coords) fc_copy = np.repeat(fc[:, :, np.newaxis], 27, axis=2) neighbors = np.array(list(itertools.product([0, 1, -1], [0, 1, -1], [0, 1, -1]))).T neighbors = np.re...
Finds bonded atoms and returns a adjacency matrix of bonded atoms. Author: "Gowoon Cheon" Email: "gcheon@stanford.edu" Args: struct (Structure): Input structure tolerance: length in angstroms used in finding bonded atoms. Two atoms are considered bonded if (radius of atom 1) + ...
13,819
def move(self, dst, **kwargs): _fs, filename = opener.parse(self.uri) _fs_dst, filename_dst = opener.parse(dst) movefile(_fs, filename, _fs_dst, filename_dst, **kwargs) self.uri = dst
Move file to a new destination and update ``uri``.
13,820
def system_monitor_sfp_alert_state(self, **kwargs): config = ET.Element("config") system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor") sfp = ET.SubElement(system_monitor, "sfp") alert = ET.SubElement(sfp, "alert") ...
Auto Generated Code
13,821
def get_layout(self, object): layout = self.create_layout(object) if isinstance(layout, Component): layout = Layout(layout) if isinstance(layout, list): layout = Layout(*layout) for update_layout in self.layout_updates: update_layout(layout,...
Get complete layout for given object
13,822
def cancel(): cancel = threading.Event() def cancel_execution(signum, frame): signame = SIGNAL_NAMES.get(signum, signum) logger.info("Signal %s received, quitting " "(this can take some time)...", signame) cancel.set() signal.signal(signal.SIGINT, cancel_ex...
Returns a threading.Event() that will get set when SIGTERM, or SIGINT are triggered. This can be used to cancel execution of threads.
13,823
def redact_image( self, parent, inspect_config=None, image_redaction_configs=None, include_findings=None, byte_item=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): ...
Redacts potentially sensitive info from an image. This method has limits on input size, processing time, and output size. See https://cloud.google.com/dlp/docs/redacting-sensitive-data-images to learn more. When no InfoTypes or CustomInfoTypes are specified in this request, the ...
13,824
def search(filter, dn=None, scope=None, attrs=None, **kwargs): ldaphostmyhostcountresultscn=myhost,ou=hosts,o=acme,c=gbsaltKeyValuentpserver=ntp.acme.localfoo=myfoosaltStatefoobartimehuman1.2msraw0.00123ldaphostlocalhost7393ssh if not dn: dn = _conf...
Run an arbitrary LDAP query and return the results. CLI Example: .. code-block:: bash salt 'ldaphost' ldap.search "filter=cn=myhost" Return data: .. code-block:: python {'myhost': {'count': 1, 'results': [['cn=myhost,ou=hosts,o=acme,c=gb', ...
13,825
def validate_v_rgb(value): if len(value) != 6: raise vol.Invalid( .format(value)) return validate_hex(value)
Validate a V_RGB value.
13,826
def create_locks(context, network_ids, addresses): for address in addresses: address_model = None try: address_model = _find_or_create_address( context, network_ids, address) lock_holder = None if address_model.lock_id: lock_h...
Creates locks for each IP address that is null-routed. The function creates the IP address if it is not present in the database.
13,827
def _index_verify(index_file, **extra_kwargs): side_effect = extra_kwargs.pop("side_effect", None) with open(TEMPLATE_FILE, "r") as file_obj: template = file_obj.read() template_kwargs = { "code_block1": SPHINX_CODE_BLOCK1, "code_block2": SPHINX_CODE_BLOCK2, "code_block3...
Populate the template and compare to documentation index file. Used for both ``docs/index.rst`` and ``docs/index.rst.release.template``. Args: index_file (str): Filename to compare against. extra_kwargs (Dict[str, str]): Over-ride for template arguments. One **special** keyword is ...
13,828
def unmark_featured(self, request, queryset): queryset.update(featured=False) self.message_user( request, _())
Un-Mark selected featured posts.
13,829
def get_complex_and_node_state(self, hosts, services): states = [s.get_state(hosts, services) for s in self.sons] if 2 in states: worst_state = 2 else: worst_state = max(states) if self.not_value: return self.get_rev...
Get state , handle AND aggregation :: * Get the worst state. 2 or max of sons (3 <=> UNKNOWN < CRITICAL <=> 2) * Revert if it's a not node :param hosts: host objects :param services: service objects :return: 0, 1 or 2 :rtype: int
13,830
def getFaxResultRN(self, CorpNum, RequestNum, UserID=None): if RequestNum == None or RequestNum == : raise PopbillException(-99999999, "์š”์ฒญ๋ฒˆํ˜ธ๊ฐ€ ์ž…๋ ฅ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.") return self._httpget( + RequestNum, CorpNum, UserID)
ํŒฉ์Šค ์ „์†ก๊ฒฐ๊ณผ ์กฐํšŒ args CorpNum : ํŒ๋นŒํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ RequestNum : ์ „์†ก์š”์ฒญ์‹œ ํ• ๋‹นํ•œ ์ „์†ก์š”์ฒญ๋ฒˆํ˜ธ UserID : ํŒ๋นŒํšŒ์› ์•„์ด๋”” return ํŒฉ์Šค์ „์†ก์ •๋ณด as list raise PopbillException
13,831
def addSplits(self, login, tableName, splits): self.send_addSplits(login, tableName, splits) self.recv_addSplits()
Parameters: - login - tableName - splits
13,832
def _get_types_from_sample(result_vars, sparql_results_json): total_bindings = len(sparql_results_json[][]) homogeneous_types = {} for result_var in result_vars: var_types = set() var_datatypes = set() for i in range(0, min(total_bindings, 10)): binding = sparql_resu...
Return types if homogenous within sample Compare up to 10 rows of results to determine homogeneity. DESCRIBE and CONSTRUCT queries, for example, :param result_vars: :param sparql_results_json:
13,833
def to_key(literal_or_identifier): if literal_or_identifier[] == : return literal_or_identifier[] elif literal_or_identifier[] == : k = literal_or_identifier[] if isinstance(k, float): return unicode(float_repr(k)) elif in literal_or_identifier: retu...
returns string representation of this object
13,834
def fetch_and_parse(method, uri, params_prefix=None, **params): doc = ElementTree.parse(fetch(method, uri, params_prefix, **params)) return _parse(doc.getroot())
Fetch the given uri and return the root Element of the response.
13,835
def _report_disk_stats(self): stats = { : None, : None, : None, : None, : None, : None } info = self.docker_util.client.info() driver_status = info.get(, []) if...
Report metrics about the volume space usage
13,836
def calculate_path(self, remote_relative_path, input_type): directory, allow_nested_files = self._directory_for_file_type(input_type) return self.path_helper.remote_join(directory, remote_relative_path)
Only for used by Pulsar client, should override for managers to enforce security and make the directory if needed.
13,837
def _draw_text(self, pos, text, font, **kw): self.drawables.append((pos, text, font, kw))
Remember a single drawable tuple to paint later.
13,838
def check_index(self, key, *, index): self.append({ "Verb": "check-index", "Key": key, "Index": extract_attr(index, keys=["ModifyIndex", "Index"]) }) return self
Fails the transaction if Key does not have a modify index equal to Index Parameters: key (str): Key to check index (ObjectIndex): Index ID
13,839
def _raise_unrecoverable_error_client(self, exception): message = ( + self.DEPENDENCY + + repr(exception) + ) raise exceptions.ClientError(message, client_exception=exception)
Raises an exceptions.ClientError with a message telling that the error probably comes from the client configuration. :param exception: Exception that caused the ClientError :type exception: Exception :raise exceptions.ClientError
13,840
def get_arp_output_arp_entry_ip_address(self, **kwargs): config = ET.Element("config") get_arp = ET.Element("get_arp") config = get_arp output = ET.SubElement(get_arp, "output") arp_entry = ET.SubElement(output, "arp-entry") ip_address = ET.SubElement(arp_entry, ...
Auto Generated Code
13,841
def _spelling_pipeline(self, sources, options, personal_dict): for source in self._pipeline_step(sources, options, personal_dict): if encoding.startswith((, )): encoding = text = source.text.encode(encod...
Check spelling pipeline.
13,842
def generate_sky_catalog(image, refwcs, **kwargs): source_cats = generate_source_catalog(image, **kwargs) master_cat = None numSci = countExtn(image, extname=) if refwcs is None: refwcs = build_reference_wcs([image]) for chip in range(numSci): chip += 1 ...
Build source catalog from input image using photutils. This script borrows heavily from build_source_catalog. The catalog returned by this function includes sources found in all chips of the input image with the positions translated to the coordinate frame defined by the reference WCS `refwcs`. The s...
13,843
def string2json(self, string): kwargs = { : BytesEncoder, : 1, : True, : (, ), } return cast_unicode(json.dumps(string, **kwargs), )
Convert json into its string representation. Used for writing outputs to markdown.
13,844
def RIBSystemRouteLimitExceeded_originator_switch_info_switchIpV6Address(self, **kwargs): config = ET.Element("config") RIBSystemRouteLimitExceeded = ET.SubElement(config, "RIBSystemRouteLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") originator_switch_info = ...
Auto Generated Code
13,845
def _load_cell(args, cell_body): env = google.datalab.utils.commands.notebook_environment() config = google.datalab.utils.commands.parse_config(cell_body, env, False) or {} parameters = config.get() or [] if parameters: jsonschema.validate({: parameters}, BigQuerySchema.QUERY_PARAMS_SCHEMA) name = goo...
Implements the BigQuery load magic used to load data from GCS to a table. The supported syntax is: %bq load <optional args> Args: args: the arguments following '%bq load'. cell_body: optional contents of the cell interpreted as YAML or JSON. Returns: A message about whether the load succeed...
13,846
def _parseAttrs(self, attrsStr): attributes = dict() for attrStr in self.SPLIT_ATTR_COL_RE.split(attrsStr): name, vals = self._parseAttrVal(attrStr) if name in attributes: raise GFF3Exception( "duplicated attribute name: {}".format(nam...
Parse the attributes and values
13,847
def currentView(cls, parent=None): if parent is None: parent = projexui.topWindow() for inst in parent.findChildren(cls): if inst.isCurrent(): return inst return None
Returns the current view for the given class within a viewWidget. If no view widget is supplied, then a blank view is returned. :param viewWidget | <projexui.widgets.xviewwidget.XViewWidget> || None :return <XView> || None
13,848
def retrieve_activity_profile(self, activity, profile_id): if not isinstance(activity, Activity): activity = Activity(activity) request = HTTPRequest( method="GET", resource="activities/profile", ignore404=True ) request.query_par...
Retrieve activity profile with the specified parameters :param activity: Activity object of the desired activity profile :type activity: :class:`tincan.activity.Activity` :param profile_id: UUID of the desired profile :type profile_id: str | unicode :return: LRS Response object ...
13,849
def parse_setup(raw_frames, destination_frame=None, header=0, separator=None, column_names=None, column_types=None, na_strings=None, skipped_columns=None, custom_non_data_line_markers=None): coltype = U(None, "unknown", "uuid", "string", "float", "real", "double", "int", "numeric", ...
Retrieve H2O's best guess as to what the structure of the data file is. During parse setup, the H2O cluster will make several guesses about the attributes of the data. This method allows a user to perform corrective measures by updating the returning dictionary from this method. This dictionary is then fed...
13,850
def getTrackedDeviceIndexForControllerRole(self, unDeviceType): fn = self.function_table.getTrackedDeviceIndexForControllerRole result = fn(unDeviceType) return result
Returns the device index associated with a specific role, for example the left hand or the right hand. This function is deprecated in favor of the new IVRInput system.
13,851
def start(self): Global.LOGGER.info("starting the flow manager") self._start_actions() self._start_message_fetcher() Global.LOGGER.debug("flow manager started")
Start all the processes
13,852
def header_canonical(self, header_name): header_name = header_name.lower() if header_name == : return elif header_name == : return return % header_name.replace(, ).upper()
Translate HTTP headers to Django header names.
13,853
def escape(s, quote=False): if s is None: return if not isinstance(s, (str, bytes)): s = str(s) if isinstance(s, bytes): try: s.decode() except UnicodeDecodeError: s = s.decode(, ) s = s.replace(, ).replace(, ).replace(, ) if quote: ...
Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag `quote` is `True`, the quotation mark character is also translated. There is a special handling for `None` which escapes to an empty string. :param s: the string to escape. :param quote: set to true to also e...
13,854
def read_function(data, window, ij, g_args): output = (data[0] > numpy.mean(data[0])).astype(data[0].dtype) * data[0].max() return output
Takes an array, and sets any value above the mean to the max, the rest to 0
13,855
def download_album_by_id(self, album_id, album_name): try: songs = self.crawler.get_album_songs(album_id) except RequestException as exception: click.echo(exception) else: folder = os.path.join(self.folder, album_name) for so...
Download a album by its name. :params album_id: album id. :params album_name: album name.
13,856
def granularity_to_time(s): mfact = { : 1, : 60, : 3600, : 86400, : 604800, } try: f, n = re.match("(?P<f>[SMHDW])(?:(?P<n>\d+)|)", s).groups() n = n if n else 1 return mfact[f] * int(n) except Exception as e: raise ValueError...
convert a named granularity into seconds. get value in seconds for named granularities: M1, M5 ... H1 etc. >>> print(granularity_to_time("M5")) 300
13,857
def add_inverse_query(self, key_val={}): q = Q("match", **key_val) self.search = self.search.query(~q) return self
Add an es_dsl inverse query object to the es_dsl Search object :param key_val: a key-value pair(dict) containing the query to be added to the search object :returns: self, which allows the method to be chainable with the other methods
13,858
def route_election(self, election): if ( election.election_type.slug == ElectionType.GENERAL or ElectionType.GENERAL_RUNOFF ): self.bootstrap_general_election(election) elif election.race.special: self.bootstrap_special_election(election) ...
Legislative or executive office?
13,859
def get_network_attributegroup_items(network_id, **kwargs): user_id=kwargs.get() net_i = _get_network(network_id) net_i.check_read_permission(user_id) group_items_i = db.DBSession.query(AttrGroupItem).filter( AttrGroupItem.network_id==network_id).all() ...
Get all the group items in a network
13,860
def list_names(): names = get_all_names() nameslen = len(names) print(.format(nameslen)) namewidth = 20 swatch = * 9 third = nameslen // 3 lastthird = third * 2 cols = ( names[0: third], names[third: lastthird], names[lastthird:], ) ...
List all known color names.
13,861
def _set_ospf(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("vrf",ospf.ospf, yang_name="ospf", rest_name="ospf", parent=self, is_container=, user_ordered=False, path_helper=self._path_helper, yang_keys=, extensions={u: {u: u, u: u, u: u...
Setter method for ospf, mapped from YANG variable /rbridge_id/router/ospf (list) If this variable is read-only (config: false) in the source YANG file, then _set_ospf is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_ospf() directly.
13,862
def system_find_users(input_params={}, always_retry=True, **kwargs): return DXHTTPRequest(, input_params, always_retry=always_retry, **kwargs)
Invokes the /system/findUsers API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Search#API-method%3A-%2Fsystem%2FfindUsers
13,863
def from_dict(cls, d, ignore=()): filtered = {} for k, v in d.items(): if k == "typeid": assert v == cls.typeid, \ "Dict has typeid %s but %s has typeid %s" % \ (v, cls, cls.typeid) elif k not in ignore: ...
Create an instance from a serialized version of cls Args: d(dict): Endpoints of cls to set ignore(tuple): Keys to ignore Returns: Instance of this class
13,864
def try_checkpoint_metadata(self, trial): if trial._checkpoint.storage == Checkpoint.MEMORY: logger.debug("Not saving data for trial w/ memory checkpoint.") return try: logger.debug("Saving trial metadata.") self._cached_trial_state[trial.trial_id...
Checkpoints metadata. Args: trial (Trial): Trial to checkpoint.
13,865
def parse_url(self) -> RequestUrl: if self._URL is None: current_url = b"%s://%s%s" % ( encode_str(self.schema), encode_str(self.host), self._current_url ) self._URL = RequestUrl(current_url) return cast(Request...
่Žทๅ–url่งฃๆžๅฏน่ฑก
13,866
def _internal_network_removed(self, ri, port, ex_gw_port): itfc_deleted = False driver = self.driver_manager.get_driver(ri.id) vrf_name = driver._get_vrf_name(ri) network_name = ex_gw_port[].get() if self._router_ids_by_vrf_and_ext_net.get( vrf_name, {}).get(...
Remove an internal router port Check to see if this is the last port to be removed for a given network scoped by a VRF (note: there can be different mappings between VRFs and networks -- 1-to-1, 1-to-n, n-to-1, n-to-n -- depending on the configuration and workflow used). If it i...
13,867
def pvwatts_ac(pdc, pdc0, eta_inv_nom=0.96, eta_inv_ref=0.9637): r pac0 = eta_inv_nom * pdc0 zeta = pdc / pdc0 eta = np.zeros_like(pdc, dtype=float) pdc_neq_0 = ~np.equal(pdc, 0) eta = eta_inv_nom / eta_inv_ref * ( - 0.0162*zeta - np.divide(0.0059, zeta, out=eta, whe...
r""" Implements NREL's PVWatts inverter model [1]_. .. math:: \eta = \frac{\eta_{nom}}{\eta_{ref}} (-0.0162\zeta - \frac{0.0059}{\zeta} + 0.9858) .. math:: P_{ac} = \min(\eta P_{dc}, P_{ac0}) where :math:`\zeta=P_{dc}/P_{dc0}` and :math:`P_{dc0}=P_{ac0}/\eta_{nom}`. Parameters ...
13,868
def find_elb_dns_zone_id(name=, env=, region=): LOG.info(, name, env, region) client = boto3.Session(profile_name=env).client(, region_name=region) elbs = client.describe_load_balancers(LoadBalancerNames=[name]) return elbs[][0][]
Get an application's AWS elb dns zone id. Args: name (str): ELB name env (str): Environment/account of ELB region (str): AWS Region Returns: str: elb DNS zone ID
13,869
def zeroize(): device_name conn = __proxy__[]() ret = {} ret[] = True try: conn.cli() ret[] = except Exception as exception: ret[] = .format(exception) ret[] = False return ret
Resets the device to default factory settings CLI Example: .. code-block:: bash salt 'device_name' junos.zeroize
13,870
def get_private_name(self, f): f = self.__swagger_rename__[f] if f in self.__swagger_rename__.keys() else f return + self.__class__.__name__ + + f
get private protected name of an attribute :param str f: name of the private attribute to be accessed.
13,871
def _str(obj): values = [] for name in obj._attribs: val = getattr(obj, name) if isinstance(val, str): val = repr(val) val = str(val) if len(str(val)) < 10 else "(...)" values.append((name, val)) values = ", ".join("{}={}".format(k, v) for k, v in values) ...
Show nicely the generic object received.
13,872
def get_earth_radii(self): earth_model = self.prologue[][] a = earth_model[] * 1000 b = (earth_model[] + earth_model[]) / 2.0 * 1000 return a, b
Get earth radii from prologue Returns: Equatorial radius, polar radius [m]
13,873
def has(self, url, xpath=None): if not path.exists(self.db_path): return False return self._query(url, xpath).count() > 0
Check if a URL (and xpath) exists in the cache If DB has not been initialized yet, returns ``False`` for any URL. Args: url (str): If given, clear specific item only. Otherwise remove the DB file. xpath (str): xpath to search (may be ``None``) Returns: bool...
13,874
def _values_of_same_type(self, val1, val2): if self._is_supported_matrix(val1) and self._is_supported_matrix(val2): return True else: return super(SparseParameter, self)._values_of_same_type(val1, val2)
Checks if two values agree in type. The sparse parameter is less restrictive than the parameter. If both values are sparse matrices they are considered to be of same type regardless of their size and values they contain.
13,875
def db_open(cls, impl, working_dir): path = config.get_snapshots_filename(impl, working_dir) return cls.db_connect(path)
Open a connection to our chainstate db
13,876
def tf_loss_per_instance(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None): raise NotImplementedError
Creates the TensorFlow operations for calculating the loss per batch instance. Args: states: Dict of state tensors. internals: Dict of prior internal state tensors. actions: Dict of action tensors. terminal: Terminal boolean tensor. reward: Reward ten...
13,877
def track(self, tracking_number): "Track a UPS package by number. Returns just a delivery date." resp = self.send_request(tracking_number) return self.parse_response(resp)
Track a UPS package by number. Returns just a delivery date.
13,878
def add_quasi_dipole_coordinates(inst, glat_label=, glong_label=, alt_label=): import apexpy ap = apexpy.Apex(date=inst.date) qd_lat = []; qd_lon = []; mlt = [] for lat, lon, alt, time in zip(inst[glat_label], inst[glong_label], inst[alt_label],...
Uses Apexpy package to add quasi-dipole coordinates to instrument object. The Quasi-Dipole coordinate system includes both the tilt and offset of the geomagnetic field to calculate the latitude, longitude, and local time of the spacecraft with respect to the geomagnetic field. This system is ...
13,879
def string_to_sign(self): return (AWS4_HMAC_SHA256 + "\n" + self.request_timestamp + "\n" + self.credential_scope + "\n" + sha256(self.canonical_request.encode("utf-8")).hexdigest())
The AWS SigV4 string being signed.
13,880
def null(alphabet): return fsm( alphabet = alphabet, states = {0}, initial = 0, finals = set(), map = { 0: dict([(symbol, 0) for symbol in alphabet]), }, )
An FSM accepting nothing (not even the empty string). This is demonstrates that this is possible, and is also extremely useful in some situations
13,881
def _get_number_of_slices(self, slice_type): if slice_type == SliceType.AXIAL: return self.dimensions[self.axial_orientation.normal_component] elif slice_type == SliceType.SAGITTAL: return self.dimensions[self.sagittal_orientation.normal_component] elif slice_typ...
Get the number of slices in a certain direction
13,882
def create_pth(): if prefix == : print("Not creating PTH in real prefix: %s" % prefix) return False with open(vext_pth, ) as f: f.write(DEFAULT_PTH_CONTENT) return True
Create the default PTH file :return:
13,883
def delist(values): assert isinstance(values, list) if not values: return None elif len(values) == 1: return values[0] return values
Reduce lists of zero or one elements to individual values.
13,884
def bootstrap_vi(version=None, venvargs=None): if not version: version = get_latest_virtualenv_version() tarball = download_virtualenv(version) p = subprocess.Popen(.format(tarball), shell=True) p.wait() p = .format(version) create_virtualenv(p, venvargs)
Bootstrap virtualenv into current directory :param str version: Virtualenv version like 13.1.0 or None for latest version :param list venvargs: argv list for virtualenv.py or None for default
13,885
def rgb_color_picker(obj, min_luminance=None, max_luminance=None): color_value = int.from_bytes( hashlib.md5(str(obj).encode()).digest(), , ) % 0xffffff color = Color(f) if min_luminance and color.get_luminance() < min_luminance: color.set_luminance(min_luminance) elif m...
Modified version of colour.RGB_color_picker
13,886
def pending_items(self) -> Iterable[Tuple[bytes, bytes]]: for key, value in self._changes.items(): if value is not DELETED: yield key, value
A tuple of (key, value) pairs for every key that has been updated. Like :meth:`pending_keys()`, this does not return any deleted keys.
13,887
def cmp_ast(node1, node2): if type(node1) != type(node2): return False if isinstance(node1, (list, tuple)): if len(node1) != len(node2): return False for left, right in zip(node1, node2): if not cmp_ast(left, right): return False elif ...
Compare if two nodes are equal.
13,888
def createResourceMapFromStream(in_stream, base_url=d1_common.const.URL_DATAONE_ROOT): pids = [] for line in in_stream: pid = line.strip() if pid == " continue if len(pids) < 2: raise ValueError("Insufficient numbers of identifiers provided.") logging.info("Rea...
Create a simple OAI-ORE Resource Map with one Science Metadata document and any number of Science Data objects, using a stream of PIDs. Args: in_stream: The first non-blank line is the PID of the resource map itself. Second line is the science metadata PID and remaining lines are science ...
13,889
def tab(tab_name, element_list=None, section_list=None): _tab = { : , : tab_name, } if element_list is not None: if isinstance(element_list, list): _tab[] = element_list else: _tab[] = [element_list] if section_list is not Non...
Returns a dictionary representing a new tab to display elements. This can be thought of as a simple container for displaying multiple types of information. Args: tab_name: The title to display element_list: The list of elements to display. If a single element is given ...
13,890
def output_datacenter(gandi, datacenter, output_keys, justify=14): output_generic(gandi, datacenter, output_keys, justify) if in output_keys: output_line(gandi, , datacenter[], justify) if in output_keys: deactivate_at = datacenter.get() if deactivate_at: output_...
Helper to output datacenter information.
13,891
def delete_wallet(self, wallet_name): return make_request( .format(self.url, wallet_name), method=, timeout=self.timeout, client=self._client)
Delete a wallet. @param the name of the wallet. @return a success string from the plans server. @raise ServerError via make_request.
13,892
def get_element_by_name(self, el_name, el_idx=0): el_list = self.get_element_list_by_name(el_name) try: return el_list[el_idx] except IndexError: raise SimpleXMLWrapperException( .format(el_name, el_idx, len(el_list)) ...
Args: el_name : str Name of element to get. el_idx : int Index of element to use as base in the event that there are multiple sibling elements with the same name. Returns: element : The selected element.
13,893
def p_string_literal(self, p): p[0] = self.asttypes.String(p[1]) p[0].setpos(p)
string_literal : STRING
13,894
def format_csv(self, delim=, qu=): res = qu + self.name + qu + delim if self.data: for d in self.data: res += qu + str(d) + qu + delim return res +
Prepares the data in CSV format
13,895
def set_config(self, config): with self._conn: self._conn.execute("DELETE FROM config") self._conn.execute(, (serialize_config(config),))
Set (replace) the configuration for the session. Args: config: Configuration object
13,896
def joint_sfs(dac1, dac2, n1=None, n2=None): dac1, n1 = _check_dac_n(dac1, n1) dac2, n2 = _check_dac_n(dac2, n2) x = n1 + 1 y = n2 + 1 tmp = (dac1 * y + dac2).astype(int, copy=False) s = np.bincount(tmp) s.resize(x, y) return s
Compute the joint site frequency spectrum between two populations. Parameters ---------- dac1 : array_like, int, shape (n_variants,) Derived allele counts for the first population. dac2 : array_like, int, shape (n_variants,) Derived allele counts for the second population. n1, n2 : ...
13,897
def store_disorder(self, sc=None, force_rerun=False): log.info() from random import shuffle g_ids = [g.id for g in self.reference_gempro.functional_genes] shuffle(g_ids) def _store_disorder_sc(g_id, outdir=self.sequences_by_gene_dir, g_to_...
Wrapper for _store_disorder
13,898
def MultimodeCombine(pupils): fluxes=[np.vdot(pupils[i],pupils[i]).real for i in range(len(pupils))] coherentFluxes=[np.vdot(pupils[i],pupils[j]) for i in range(1,len(pupils)) for j in range(i)] return fluxes,coherentFluxes
Return the instantaneous coherent fluxes and photometric fluxes for a multiway multimode combiner (no spatial filtering)
13,899
def parse_val(cfg,section,option): vals = parse_vals(cfg,section,option) if len(vals)==0: return else: assert len(vals)==1, (section, option, vals, type(vals)) return vals[0]
extract a single value from .cfg