Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
366,200
def one_version(self, index=0): def prep(df): start = sorted(df._start.tolist())[index] return df[df._start == start] return pd.concat([prep(df) for _, df in self.groupby(self._oid)])
Leaves only one version for each object. :param index: List-like index of the version. 0 == first; -1 == last
366,201
def items(self): for key in sorted(self.attrs): yield key, self.attrs[key]
A generator yielding ``(key, value)`` attribute pairs, sorted by key name.
366,202
def expandPath(self, path): iiPath = self.model().findItemAndIndexPath(path) for (item, index) in iiPath[1:]: assert index.isValid(), "Sanity check: invalid index in path for item: {}".format(item) self.expand(index) leaf = iiPath[-1] return leaf
Follows the path and expand all nodes along the way. Returns (item, index) tuple of the last node in the path (the leaf node). This can be reused e.g. to select it.
366,203
def __init_object(self): if self.init_function is not None: new_obj = self.init_function() self.__enqueue(new_obj) else: raise TypeError("The Pool must have a non None function to fill the pool.")
Create a new object for the pool.
366,204
def manage_subscription(): subscription = processor.create_parameter_subscription([ ]) sleep(5) print() subscription.add([ , , , ]) sleep(5) print() subscription.remove() print() subscription.cancel() print() print(subscript...
Shows how to interact with a parameter subscription.
366,205
def main(): conf.init(), db.init(conf.DbPath) inqueue = LineQueue(sys.stdin).queue outqueue = type("", (), {"put": lambda self, x: print("\r%s" % x, end=" ")})() if "--quiet" in sys.argv: outqueue = None if conf.MouseEnabled: inqueue.put("mouse_start") if conf.KeyboardEnabled: inq...
Entry point for stand-alone execution.
366,206
def cycle_complexity(self, cycle=): cycle = str(cycle).upper() nnz = [level.A.nnz for level in self.levels] def V(level): if len(self.levels) == 1: return nnz[0] elif level == len(self.levels) - 2: return 2 * nnz[level] + nnz[lev...
Cycle complexity of V, W, AMLI, and F(1,1) cycle with simple relaxation. Cycle complexity is an approximate measure of the number of floating point operations (FLOPs) required to perform a single multigrid cycle relative to the cost a single smoothing operation. Parameters ----...
366,207
def read(self, length=-1): _complain_ifclosed(self.closed) if length < 0: length = self.size chunks = [] while 1: if length <= 0: break c = self.f.read(min(self.buff_size, length)) if c == b"": ...
Read ``length`` bytes from the file. If ``length`` is negative or omitted, read all data until EOF. :type length: int :param length: the number of bytes to read :rtype: string :return: the chunk of data read from the file
366,208
def get_normalization_min_max(array, norm_min, norm_max): if norm_min is None: norm_min = array.min() if norm_max is None: norm_max = array.max() return norm_min, norm_max
Get the minimum and maximum of the normalization of the array, which sets the lower and upper limits of the \ colormap. If norm_min / norm_max are not supplied, the minimum / maximum values of the array of data are used. Parameters ----------- array : data.array.scaled_array.ScaledArray Th...
366,209
def work_request(self, worker_name, md5, subkeys=None): work_results = self._recursive_work_resolver(worker_name, md5) if subkeys: if isinstance(subkeys, str): subkeys = [subkeys] try: sub_results = {} f...
Make a work request for an existing stored sample. Args: worker_name: 'strings', 'pe_features', whatever md5: the md5 of the sample (or sample_set!) subkeys: just get a subkey of the output: 'foo' or 'foo.bar' (None for all) Returns: ...
366,210
def find_err_pattern(self, pattern): if self.wdir != : stderr = "%s/%s"%(self.wdir, self.stderr) else: stderr = self.stderr response = [] if os.path.exists(stderr): with open_(stderr, ) as f: for line in f: if pattern in line: ...
This function will read the standard error of the program and return a matching pattern if found. EG. prog_obj.FindErrPattern("Update of mySQL failed")
366,211
def delete_one(self, filter, collation=None): with self._socket_for_writes() as sock_info: return DeleteResult(self._delete(sock_info, filter, False, collation=collation), self.write_concern.acknowledged)
Delete a single document matching the filter. >>> db.test.count({'x': 1}) 3 >>> result = db.test.delete_one({'x': 1}) >>> result.deleted_count 1 >>> db.test.count({'x': 1}) 2 :Parameters: - `filter`: A query that matches the docum...
366,212
def set_debug(self, debug): self.make_request( NodeCommandFailed, method=, resource=, json=debug.serialize())
Set the debug settings for this node. This should be a modified :class:`~Debug` instance. This will take effect immediately on the specified node. :param Debug debug: debug object with specified settings :raises NodeCommandFailed: fail to communicate with node :return: N...
366,213
async def AddToUnit(self, storages): _params = dict() msg = dict(type=, request=, version=4, params=_params) _params[] = storages reply = await self.rpc(msg) return reply
storages : typing.Sequence[~StorageAddParams] Returns -> typing.Sequence[~AddStorageResult]
366,214
def get_all_pattern_variables(self, patternnumber): _checkPatternNumber(patternnumber) outputstring = for stepnumber in range(8): outputstring += .format(stepnumber, \ self.get_pattern_step_setpoint( patternnumber, stepnumber), \ sel...
Get all variables for a given pattern at one time. Args: patternnumber (integer): 0-7 Returns: A descriptive multiline string.
366,215
def parse_code(url): result = urlparse(url) query = parse_qs(result.query) return query[]
Parse the code parameter from the a URL :param str url: URL to parse :return: code query parameter :rtype: str
366,216
def list_snapshots(connection, volume): logger.info( ) logger.info( .format( snapshot=, snapshot_name=, created=)) logger.info( ) vid = get_volume_id(connection, volume) if vid: ...
List all snapshots for the volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type volume: str :param volume: Volume ID or Volume Name :returns: None
366,217
def stream_to_packet(data): if len(data) < 6: return None pktlen = struct.unpack(">H", data[4:6])[0] + 6 if (len(data) < pktlen): return None return (data[:pktlen], data[pktlen:])
Chop a stream of data into MODBUS packets. :param data: stream of data :returns: a tuple of the data that is a packet with the remaining data, or ``None``
366,218
def on_message(self, message): change = tornado.escape.json_decode(message) ref = change.get() if not ref: return node = self.view.xpath(.format(ref), first=True) if node is None: return ...
When enaml.js sends a message
366,219
def _function_contents(func): contents = [_code_contents(func.__code__, func.__doc__)] if func.__defaults__: function_defaults_contents = [_object_contents(cc) for cc in func.__defaults__] defaults = bytearray(b) defaults.extend(bytearray(b).join(function_defaults_contents)...
The signature is as follows (should be byte/chars): < _code_contents (see above) from func.__code__ > ,( comma separated _object_contents for function argument defaults) ,( comma separated _object_contents for any closure contents ) See also: https://docs.python.org/3/reference/datamodel.html - ...
366,220
def getchar(self): u Cevent = INPUT_RECORD() count = DWORD(0) while 1: status = self.ReadConsoleInputW(self.hin, byref(Cevent), 1, byref(count)) if (status and (count.value == 1) and ...
u'''Get next character from queue.
366,221
def add_event(self, event): self._events.append(event) self._events_by_name[event.get_name] = event
Adds an IEvent event to this command set. :param event: an event instance to be added
366,222
def calc_nearest_point(bus1, network): bus1_index = network.buses.index[network.buses.index == bus1] forbidden_buses = np.append( bus1_index.values, network.lines.bus1[ network.lines.bus0 == bus1].values) forbidden_buses = np.append( forbidden_buses, network.lines.bus...
Function that finds the geographical nearest point in a network from a given bus. Parameters ----- bus1: float id of bus network: Pypsa network container network including the comparable buses Returns ------ bus0 : float bus_id of nearest point
366,223
def coarsegrain(P, n): M = pcca(P, n) W = np.linalg.inv(np.dot(M.T, M)) A = np.dot(np.dot(M.T, P), M) P_coarse = np.dot(W, A) from msmtools.analysis import stationary_distribution pi_coarse = np.dot(M.T, stationary_distribution(P)) X = np.dot(np.diag(pi_coarse), P_coarse) ...
Coarse-grains transition matrix P to n sets using PCCA Coarse-grains transition matrix P such that the dominant eigenvalues are preserved, using: ..math: \tilde{P} = M^T P M (M^T M)^{-1} See [2]_ for the derivation of this form from the coarse-graining method first derived in [1]_. Reference...
366,224
def delete_replication(Bucket, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_bucket_replication(Bucket=Bucket) return {: True, : Bucket} except ClientError as e: return {:...
Delete the replication config from the given bucket Returns {deleted: true} if replication configuration was deleted and returns {deleted: False} if replication configuration was not deleted. CLI Example: .. code-block:: bash salt myminion boto_s3_bucket.delete_replication my_bucket
366,225
def isfinite(data: mx.nd.NDArray) -> mx.nd.NDArray: is_data_not_nan = data == data is_data_not_infinite = data.abs() != np.inf return mx.nd.logical_and(is_data_not_infinite, is_data_not_nan)
Performs an element-wise check to determine if the NDArray contains an infinite element or not. TODO: remove this funciton after upgrade to MXNet 1.4.* in favor of mx.ndarray.contrib.isfinite()
366,226
def _socket_readlines(self, blocking=False): try: self.sock.setblocking(0) except socket.error as e: self.logger.error("socket error when setblocking(0): %s" % str(e)) raise ConnectionDrop("connection dropped") while True: short_buf = b ...
Generator for complete lines, received from the server
366,227
def modify_parameters(self, modifier_function): baseline_parameters = self.baseline.parameters baseline_parameters_copy = copy.deepcopy(baseline_parameters) reform_parameters = modifier_function(baseline_parameters_copy) if not isinstance(reform_parameters, ParameterNode): ...
Make modifications on the parameters of the legislation Call this function in `apply()` if the reform asks for legislation parameter modifications. :param modifier_function: A function that takes an object of type :any:`ParameterNode` and should return an object of the same type.
366,228
def to_dict(self): res = self.serialize(private=True) res.update(self.extra_args) return res
A wrapper for to_dict the makes sure that all the private information as well as extra arguments are included. This method should *not* be used for exporting information about the key. :return: A dictionary representation of the JSON Web key
366,229
def database_to_intermediary(database_uri, schema=None): from sqlalchemy.ext.automap import automap_base from sqlalchemy import create_engine Base = automap_base() engine = create_engine(database_uri) if schema is not None: Base.metadata.schema = schema Base.prepare(engine, r...
Introspect from the database (given the database_uri) to create the intermediary representation.
366,230
def atc(jobid): * return output
Print the at(1) script that will run for the passed job id. This is mostly for debugging so the output will just be text. CLI Example: .. code-block:: bash salt '*' at.atc <jobid>
366,231
def ssh_authorized_key_exists(public_key, application_name, user=None): with open(authorized_keys(application_name, user)) as keys: return ( % public_key) in keys.read()
Check if given key is in the authorized_key file. :param public_key: Public key. :type public_key: str :param application_name: Name of application eg nova-compute-something :type application_name: str :param user: The user that the ssh asserts are for. :type user: str :returns: Whether giv...
366,232
def alphas(shape, alpha_value, name=None): with ops.name_scope(name, "alphas", [shape]) as name: alpha_tensor = convert_to_tensor(alpha_value) alpha_dtype = dtypes.as_dtype(alpha_tensor.dtype).base_dtype if not isinstance(shape, ops.Tensor): try: shape = co...
Creates a tensor with all elements set to `alpha_value`. This operation returns a tensor of type `dtype` with shape `shape` and all elements set to alpha. Parameters ---------- shape: A list of integers, a tuple of integers, or a 1-D `Tensor` of type `int32`. The shape of the desired tensor...
366,233
def set_log_level(self): if self.options.debug: self.logger.setLevel(logging.DEBUG) elif self.options.quiet: self.logger.setLevel(logging.ERROR) else: self.logger.setLevel(logging.INFO) self.logger.addHandler(logging.StreamHandler()) ...
Set log level according to command-line options @returns: logger object
366,234
def get_next_step(self): if is_raster_layer(self.parent.layer): new_step = self.parent.step_kw_band_selector else: new_step = self.parent.step_kw_layermode return new_step
Find the proper step when user clicks the Next button. :returns: The step to be switched to :rtype: WizardStep instance or None
366,235
def dict_of_sets_add(dictionary, key, value): set_objs = dictionary.get(key, set()) set_objs.add(value) dictionary[key] = set_objs
Add value to a set in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to set in dictionary Returns: None
366,236
def start_ray_process(command, process_type, env_updates=None, cwd=None, use_valgrind=False, use_gdb=False, use_valgrind_profiler=False, use_perftools_profiler=False,...
Start one of the Ray processes. TODO(rkn): We need to figure out how these commands interact. For example, it may only make sense to start a process in gdb if we also start it in tmux. Similarly, certain combinations probably don't make sense, like simultaneously running the process in valgrind and the...
366,237
def BHI(self, params): label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) def BHI_func(): if self.is_C_set() and not self.is_Z_set(): self.register[] = self.labels[label] return BHI_func
BHI label Branch to the instruction at label if the C flag is set and the Z flag is not set
366,238
def modify_environment(self, environment_id, **kwargs): request_data = {: environment_id} request_data.update(**kwargs) return self._call_rest_api(, , data=request_data, error=)
modify_environment(self, environment_id, **kwargs) Modifies an existing environment :Parameters: * *environment_id* (`string`) -- The environment identifier Keywords args: The variables to change in the environment :return: id of the created environment
366,239
def delete_external_feed_courses(self, course_id, external_feed_id): path = {} data = {} params = {} path["course_id"] = course_id path["external_feed_id"] = external_feed_id self.logger.debug("DELETE /api/v1/cou...
Delete an external feed. Deletes the external feed.
366,240
def static2dplot(var, time): names = list(pytplot.data_quants.keys()) if valid_variables: labels = tplot_utilities.get_labels_axis_types(names) data = {} for name in valid_variables: bins = tplot_utilities.get_bins(name) time_val...
If the static option is set in tplot, and is supplied with a time, then the spectrogram plot(s) for which it is set will have another window pop up, with y and z values plotted at the specified time.
366,241
def optimization_at(self, circuit: Circuit, index: int, op: ops.Operation ) -> Optional[PointOptimizationSummary]:
Describes how to change operations near the given location. For example, this method could realize that the given operation is an X gate and that in the very next moment there is a Z gate. It would indicate that they should be combined into a Y gate by returning PointOptimizationSummary...
366,242
async def send_api(container, targetname, name, params = {}): handle = object() apiEvent = ModuleAPICall(handle, targetname, name, params = params) await container.wait_for_send(apiEvent)
Send API and discard the result
366,243
def output(self, filename): if filename == : filename = if not filename.endswith(): filename += ".dot" info = + filename self.info(info) with open(filename, , encoding=) as f: f.write() for c in self.contracts: ...
Output the graph in filename Args: filename(string)
366,244
def add_edge_end_unused(intersection, duplicates, intersections): found = None for other in intersections: if ( intersection.index_first == other.index_first and intersection.index_second == other.index_second ): if intersection.s == 0.0 and other.s == 0....
Add intersection that is ``COINCIDENT_UNUSED`` but on an edge end. This is a helper for :func:`~._surface_intersection.add_intersection`. It assumes that * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0`` * A "misclassified" intersection in ``intersections`` that matches `...
366,245
def if_running(meth): @wraps(meth) def check_running(self, *args, **kwargs): if not self.running: return return meth(self, *args, **kwargs) return check_running
Decorator for service methods that must be ran only if service is in running state.
366,246
def session_id(self): if self._session_id is None: req = self.request("POST /4/sessions") self._session_id = req.get("session_key") or req.get("session_id") return CallableString(self._session_id)
Return the session id of the current connection. The session id is issued (through an API request) the first time it is requested, but no sooner. This is because generating a session id puts it into the DKV on the server, which effectively locks the cluster. Once issued, the session id will sta...
366,247
def get_file_path_validator(default_file_param=None): def validator(namespace): if not hasattr(namespace, ): return path = namespace.path dir_name, file_name = os.path.split(path) if path else (None, ) if default_file_param and not in file_name: dir_n...
Creates a namespace validator that splits out 'path' into 'directory_name' and 'file_name'. Allows another path-type parameter to be named which can supply a default filename.
366,248
def qos_map_dscp_cos_mark_dscp_in_values(self, **kwargs): config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") map = ET.SubElement(qos, "map") dscp_cos = ET.SubElement(map, "dscp-cos") dscp_cos_map_name_key = ET.SubEl...
Auto Generated Code
366,249
def prevention(): tpm = np.array([ [0.5, 0.5, 1], [0.5, 0.5, 0], [0.5, 0.5, 1], [0.5, 0.5, 1], [0.5, 0.5, 1], [0.5, 0.5, 0], [0.5, 0.5, 1], [0.5, 0.5, 1] ]) cm = np.array([ [0, 0, 1], [0, 0, 1], [0, 0, 0] ]) ...
The |Transition| for the prevention example from Actual Causation Figure 5D.
366,250
def ngrok_url(): try: ngrok_resp = requests.get("http://localhost:4040/api/tunnels") except requests.ConnectionError: return None ngrok_data = ngrok_resp.json() secure_urls = [ tunnel["public_url"] for tunnel in ngrok_data["tunnels"] if tunnel["proto...
If ngrok is running, it exposes an API on port 4040. We can use that to figure out what URL it has assigned, and suggest that to the user. https://ngrok.com/docs#list-tunnels
366,251
def search(self, query, options): query["query_format"] = "advanced" log.debug("Search query:") log.debug(pretty(query)) try: result = self.server.query(query) except xmlrpclib.Fault as error: if "not a valid use...
Perform Bugzilla search
366,252
def set_until(self, frame, lineno=None): self.state = Until(frame, frame.f_lineno)
Stop on the next line number.
366,253
def set_led_brightness(self, brightness): set_cmd = self._create_set_property_msg("_led_brightness", 0x07, brightness) self._send_method(set_cmd, self._property_set)
Set the LED brightness for the current group/button.
366,254
def randomToggle(self, randomize): if randomize: self._stim.setReorderFunc(order_function(), ) else: self._stim.reorder = None
Sets the reorder function on this StimulusModel to a randomizer or none, alternately
366,255
def fetch(self): params = values.of({}) payload = self._version.fetch( , self._uri, params=params, ) return StepInstance( self._version, payload, flow_sid=self._solution[], engagement_sid=self....
Fetch a StepInstance :returns: Fetched StepInstance :rtype: twilio.rest.studio.v1.flow.engagement.step.StepInstance
366,256
def NewFile(self, filename, encoding, options): ret = libxml2mod.xmlReaderNewFile(self._o, filename, encoding, options) return ret
parse an XML file from the filesystem or the network. The parsing flags @options are a combination of xmlParserOption. This reuses the existing @reader xmlTextReader.
366,257
def intern_atom(self, name, only_if_exists = 0): r = request.InternAtom(display = self.display, name = name, only_if_exists = only_if_exists) return r.atom
Intern the string name, returning its atom number. If only_if_exists is true and the atom does not already exist, it will not be created and X.NONE is returned.
366,258
def memo_Y(f): sub = {} def Yf(*args): hashable_args = tuple([repr(x) for x in args]) if args: if hashable_args not in sub: ret = sub[hashable_args] = f(Yf)(*args) else: ret = sub[hashable_args] return ret return f...
Memoized Y combinator. .. testsetup:: from proso.func import memo_Y .. testcode:: @memo_Y def fib(f): def inner_fib(n): if n > 1: return f(n - 1) + f(n - 2) else: return n return inner_fib...
366,259
def pluralize(word) : rules = [ [ , ], [ , ], [ , ], [ , ], [ , ], [ , ], [ , ], [ , ], [ , ], [ , ], [ , ], [ , ], [ , ], [ , ], ...
Pluralize an English noun.
366,260
def cli(env, storage_type, size, iops, tier, location, snapshot_size, service_offering, billing): file_manager = SoftLayer.FileStorageManager(env.client) storage_type = storage_type.lower() hourly_billing_flag = False if billing.lower() == "hourly": hourly_billing_flag = True ...
Order a file storage volume. Valid size and iops options can be found here: https://console.bluemix.net/docs/infrastructure/FileStorage/index.html#provisioning
366,261
def _parse_weights(weight_args, default_weight=0.6): weights_dict = {} r_group_weight = default_weight for weight_arg in weight_args: for weight_assignment in weight_arg.split(): if not in weight_assignment: raise ValueError( .format(weight_assig...
Parse list of weight assignments.
366,262
def ReadCronJobRun(self, job_id, run_id): for run in itervalues(self.cronjob_runs): if run.cron_job_id == job_id and run.run_id == run_id: return run raise db.UnknownCronJobRunError( "Run with job id %s and run id %s not found." % (job_id, run_id))
Reads a single cron job run from the db.
366,263
def search(self, **kwargs): return super(ApiPool, self).get(self.prepare_url(, kwargs))
Method to search pool's based on extends search. :param search: Dict containing QuerySets to find pool's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override d...
366,264
def is_choked_turbulent_g(x, Fgamma, xT=None, xTP=None): r if xT: return x >= Fgamma*xT elif xTP: return x >= Fgamma*xTP else: raise Exception()
r'''Calculates if a gas flow in IEC 60534 calculations is critical or not, for use in IEC 60534 gas valve sizing calculations. Either xT or xTP must be provided, depending on the calculation process. .. math:: x \ge F_\gamma x_T .. math:: x \ge F_\gamma x_{TP} Parameters -----...
366,265
def get_template_names(self): names = super(EasyUIDeleteView, self).get_template_names() names.append() return names
datagrid的默认模板
366,266
def draw(self, mode=, indices=None, check_error=True): self._buffer = None mode = check_enum(mode) if mode not in [, , , , , , ]: raise ValueError( % mode) for name in self._pendin...
Draw the attribute arrays in the specified mode. Parameters ---------- mode : str | GL_ENUM 'points', 'lines', 'line_strip', 'line_loop', 'triangles', 'triangle_strip', or 'triangle_fan'. indices : array Array of indices to draw. check_error: ...
366,267
def cdr(ol,**kwargs): if( in kwargs): mode = kwargs[] else: mode = "new" if(mode == "new"): cpol = copy.deepcopy(ol) return(cpol[1:]) else: ol.pop(0) return(ol)
from elist.elist import * ol=[1,2,3,4] id(ol) new = cdr(ol) new id(new) #### ol=[1,2,3,4] id(ol) rslt = cdr(ol,mode="original") rslt id(rslt)
366,268
def get_encapsulated_payload_class(self): try: return TZSP.ENCAPSULATED_PROTOCOL_CLASSES[self.encapsulated_protocol] except KeyError: warning( % self.encapsulated_protocol) return Raw
get the class that holds the encapsulated payload of the TZSP packet :return: class representing the payload, Raw() on error
366,269
def create_wordpress(self, service_id, version_number, name, path, comment=None): body = self._formdata({ "name": name, "path": path, "comment": comment, }, FastlyWordpress.FIELDS) content = self._fetch("/service/%s/version/%d/wordpress" % (service_id, version_number), method="POST", body=bo...
Create a wordpress for the specified service and version.
366,270
def get_unique_ajps( benchmark_runs ): br_ajps = {} for br in benchmark_runs: for ajp in br.additional_join_parameters: if ajp not in br_ajps: br_ajps[ajp] = set() br_ajps[ajp].add( br.additional_join_parameters[ajp][] ) un...
Determines which join parameters are unique
366,271
def roundClosestValid(val, res, decimals=None): if decimals is None and "." in str(res): decimals = len(str(res).split()[1]) return round(round(val / res) * res, decimals)
round to closest resolution
366,272
def revoke_cert( ca_name, CN, cacert_path=None, ca_filename=None, cert_path=None, cert_filename=None, crl_file=None, digest=, ): sha256*kojica/etc/openvpn/team1/crl.pem set_ca_path(cacert_path) ca_dir = .format(cert_base_path(), ca_nam...
Revoke a certificate. .. versionadded:: 2015.8.0 ca_name Name of the CA. CN Common name matching the certificate signing request. cacert_path Absolute path to ca certificates root directory. ca_filename Alternative filename for the CA. cert_path Path...
366,273
def set_save_directory(base, source): root = os.path.join(base, source) if not os.path.isdir(root): os.makedirs(root) world.screenshot_root = root
Sets the root save directory for saving screenshots. Screenshots will be saved in subdirectories under this directory by browser window size.
366,274
def getDateFields(fc): if arcpyFound == False: raise Exception("ArcPy is required to use this function") return [field.name for field in arcpy.ListFields(fc, field_type="Date")]
Returns a list of fields that are of type DATE Input: fc - feature class or table path Output: List of date field names as strings
366,275
def natural_neighbor_point(xp, yp, variable, grid_loc, tri, neighbors, triangle_info): r edges = geometry.find_local_boundary(tri, neighbors) edge_vertices = [segment[0] for segment in geometry.order_edges(edges)] num_vertices = len(edge_vertices) p1 = edge_vertices[0] p2 = edge_vertices[1] ...
r"""Generate a natural neighbor interpolation of the observations to the given point. This uses the Liang and Hale approach [Liang2010]_. The interpolation will fail if the grid point has no natural neighbors. Parameters ---------- xp: (N, ) ndarray x-coordinates of observations yp: (N...
366,276
def dumps(obj, **kwargs): try: return json.dumps(obj, **kwargs) except Exception as e: raise JSONLibraryException(e)
Serialize `obj` to a JSON formatted `str`. Accepts the same arguments as `json` module in stdlib. :param obj: a JSON serializable Python object. :param kwargs: all the arguments that `json.dumps <http://docs.python.org/ 2/library/json.html#json.dumps>`_ accepts. :raises: commentjson....
366,277
def insert_column(self, name, data, colnum=None): if name in self._colnames: raise ValueError("column already exists" % name) if IS_PY3 and data.dtype.char == : descr = numpy.empty(1).astype(data.dtype)....
Insert a new column. parameters ---------- name: string The column name data: The data to write into the new column. colnum: int, optional The column number for the new column, zero-offset. Default is to add the new column after t...
366,278
def process_pem(self, data, name): try: ret = [] data = to_string(data) parts = re.split(r, data) if len(parts) == 0: return None if len(parts[0]) == 0: parts.pop(0) crt_arr = [ + x for x in parts]...
PEM processing - splitting further by the type of the records :param data: :param name: :return:
366,279
def __substitute_replace_pairs(self): self._set_magic_constants() routine_source = [] i = 0 for line in self._routine_source_code_lines: self._replace[] = "" % (i + 1) for search, replace in self._replace.items(): tmp = re.findall(search,...
Substitutes all replace pairs in the source of the stored routine.
366,280
def get_sorted_structure(self, key=None, reverse=False): sites = sorted(self, key=key, reverse=reverse) return self.__class__.from_sites(sites, charge=self._charge)
Get a sorted copy of the structure. The parameters have the same meaning as in list.sort. By default, sites are sorted by the electronegativity of the species. Args: key: Specifies a function of one argument that is used to extract a comparison key from each list ele...
366,281
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken, knowledge_base): _ = stderr, time_taken, args, knowledge_base self.CheckReturn(cmd, return_val) result = rdf_protodict.AttributedDict() for k, v in iteritems(self.lexer.ParseToOrderedDict(stdout)): key ...
Parse the sysctl output.
366,282
def get_orderbook_ticker(self, **params): return self._get(, data=params, version=self.PRIVATE_API_VERSION)
Latest price for a symbol or symbols. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#symbol-order-book-ticker :param symbol: :type symbol: str :returns: API response .. code-block:: python { "symbol": "LTCBTC...
366,283
def align(expnums, ccd, version=, dry_run=False): pos = {} apcor = {} mags = {} zmag = {} mjdates = {} for expnum in expnums: filename = storage.get_image(expnum, ccd=ccd, version=version) zmag[expnum] = storage.get_zeropoint(expnum, ccd, prefix=None, ...
Create a 'shifts' file that transforms the space/flux/time scale of all images to the first image. This function relies on the .fwhm, .trans.jmp, .phot and .zeropoint.used files for inputs. The scaling we are computing here is for use in planting sources into the image at the same sky/flux locations while ...
366,284
def mkdummy(name, **attrs): return type( name, (), dict(__repr__=(lambda self: "<%s>" % name), **attrs) )()
Make a placeholder object that uses its own name for its repr
366,285
def average(numbers, averagetype=): try: statistics.mean(numbers) except RuntimeError: raise ValueError() if averagetype.lower() == : return statistics.mean(numbers) elif averagetype.lower() == : return statistics.mod...
Find the average of a list of numbers :type numbers: list :param numbers: The list of numbers to find the average of. :type averagetype: string :param averagetype: The type of average to find. >>> average([1, 2, 3, 4, 5], 'median') 3
366,286
def add(self, *args): self._constrs.extend(self._moma._prob.add_linear_constraints(*args))
Add constraints to the model.
366,287
def number_of_changes(slots, events, original_schedule, X, **kwargs): changes = 0 original_array = schedule_to_array(original_schedule, events=events, slots=slots) for row, event in enumerate(original_array): for col, slot in enumerate(event): ...
A function that counts the number of changes between a given schedule and an array (either numpy array of lp array).
366,288
def set_attrs(self): self.attrs.encoding = self.encoding self.attrs.errors = self.errors
set our object attributes
366,289
def _call_java(sc, java_obj, name, *args): m = getattr(java_obj, name) java_args = [_py2java(sc, arg) for arg in args] return _java2py(sc, m(*java_args))
Method copied from pyspark.ml.wrapper. Uses private Spark APIs.
366,290
def get_param_doc(doc, param): arg_doc = docstrings.keep_params_s(doc, [param]) or \ docstrings.keep_types_s(doc, [param]) dtype = None if arg_doc: lines = arg_doc.splitlines() arg_doc = dedents( + .join(lines[1:])) param_desc = lines[0].s...
Get the documentation and datatype for a parameter This function returns the documentation and the argument for a napoleon like structured docstring `doc` Parameters ---------- doc: str The base docstring to use param: str The argument to use ...
366,291
def get_vcenter_data_model(self, api, vcenter_name): if not vcenter_name: raise ValueError() vcenter_instance = api.GetResourceDetails(vcenter_name) vcenter_resource_model = self.resource_model_parser.convert_to_vcenter_model(vcenter_instance) return vcenter_resource...
:param api: :param str vcenter_name: :rtype: VMwarevCenterResourceModel
366,292
def postChunked(host, selector, fields, files): params = urllib.urlencode(fields) url = % (host, selector, params) u = urllib2.urlopen(url, files) result = u.read() [fp.close() for (key, fp) in files] return result
Attempt to replace postMultipart() with nearly-identical interface. (The files tuple no longer requires the filename, and we only return the response body.) Uses the urllib2_file.py originally from http://fabien.seisen.org which was also drawn heavily from http://code.activestate.com/recipes/1463...
366,293
def customer_discount_webhook_handler(event): crud_type = CrudType.determine(event=event) discount_data = event.data.get("object", {}) coupon_data = discount_data.get("coupon", {}) customer = event.customer if crud_type.created or crud_type.updated: coupon, _ = _handle_crud_like_event( target_cls=models.C...
Handle updates to customer discount objects. Docs: https://stripe.com/docs/api#discounts Because there is no concept of a "Discount" model in dj-stripe (due to the lack of a stripe id on them), this is a little different to the other handlers.
366,294
def executemany(self, command, params=None, max_attempts=5): attempts = 0 while attempts < max_attempts: try: self._cursor.executemany(command, params) self._commit() return True except Exception as e: ...
Execute multiple SQL queries without returning a result.
366,295
def handle_oauth2_response(self, args): client = self.make_client() remote_args = { : args.get(), : self.consumer_secret, : session.get( % self.name) } log.debug(, remote_args) remote_args.update(self.access_token_params) head...
Handles an oauth2 authorization response.
366,296
def change_generated_target_suffix (type, properties, suffix): assert isinstance(type, basestring) assert is_iterable_typed(properties, basestring) assert isinstance(suffix, basestring) change_generated_target_ps(1, type, properties, suffix)
Change the suffix previously registered for this type/properties combination. If suffix is not yet specified, sets it.
366,297
def email_message( self, recipient, subject_template, body_template, sender=None, message_class=EmailMessage, **kwargs ): from_email = "%s %s <%s>" % ( sender.first_name, sender.last_name, email.util...
Returns an invitation email message. This can be easily overridden. For instance, to send an HTML message, use the EmailMultiAlternatives message_class and attach the additional conent.
366,298
def framework_find(fn, executable_path=None, env=None): try: return dyld_find(fn, executable_path=executable_path, env=env) except ValueError: pass fmwk_index = fn.rfind() if fmwk_index == -1: fmwk_index = len(fn) fn += fn = os.path.join(fn, os.path.basename(fn[...
Find a framework using dyld semantics in a very loose manner. Will take input such as: Python Python.framework Python.framework/Versions/Current
366,299
def get_job_model(self): if not self.job: raise Exception() return JobModel(self.job_id, self.job, self.home_config[])
Returns a new JobModel instance with current loaded job data attached. :return: JobModel