Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
360,900
def getOrphanParticleInfos(self, swarmId, genIdx): entryIdxs = range(len(self._allResults)) if len(entryIdxs) == 0: return ([], [], [], [], []) particleStates = [] modelIds = [] errScores = [] completedFlags = [] maturedFlags = [] for idx in entryIdxs: ent...
Return a list of particleStates for all particles in the given swarm generation that have been orphaned. Parameters: --------------------------------------------------------------------- swarmId: A string representation of the sorted list of encoders in this swarm. For example '__addr...
360,901
def has_any(): "Returns the best available proactor implementation for the current platform." return get_first(has_ctypes_iocp, has_iocp, has_stdlib_kqueue, has_kqueue, has_stdlib_epoll, has_epoll, has_poll, has_select)
Returns the best available proactor implementation for the current platform.
360,902
def getReliableListeners(self): for rellist in self.store.query(_ReliableListener, _ReliableListener.processor == self): yield rellist.listener
Return an iterable of the listeners which have been added to this batch processor.
360,903
def v1_label_put(request, response, visid_to_dbid, config, label_hooks, label_store, cid1, cid2, annotator_id): t know if they are coreferent" and ``1`` for coreferent. Optionally, the query parameters ``subtopic_id1`` and ``subtopic_id2`` may be specified. Neither, both or either may ...
Store a single label. The route for this endpoint is: ``PUT /dossier/v1/labels/<content_id1>/<content_id2>/<annotator_id>``. ``content_id`` are the ids of the feature collections to associate. ``annotator_id`` is a string that identifies the human that created the label. The value of the label sho...
360,904
def array_item_type(type_): if is_array(type_): type_ = remove_alias(type_) type_ = remove_cv(type_) return type_.base elif is_pointer(type_): return remove_pointer(type_) else: raise RuntimeError( "array_item_type functions takes as argument array or...
returns array item type
360,905
def up(self): ifreq = struct.pack(, self.name, 0) flags = struct.unpack(, fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1] flags = flags | IFF_UP ifreq = struct.pack(, self.name, flags) fcntl.ioctl(sockfd, SIOCSIFFLAGS, ifreq)
Bring up the bridge interface. Equivalent to ifconfig [iface] up.
360,906
def context_path(cls, project, session, context): return google.api_core.path_template.expand( , project=project, session=session, context=context, )
Return a fully-qualified context string.
360,907
def node_copy(node, nodefactory=Node): return nodefactory(node.tag, node.attrib.copy(), node.text, [node_copy(n, nodefactory) for n in node])
Make a deep copy of the node
360,908
def convert(self, value, param, ctx): matches = MEMORY_RE.match(value.lower()) if matches is None: self.fail( % value, param, ctx) amount_str, unit = matches.groups() amount = int(amount_str) if unit in [None, , ]: if amount < 1024:...
Validate memory argument. Returns the memory value in megabytes.
360,909
def get(self, event): self.log("Schemarequest for", event.data, "from", event.user, lvl=debug) if event.data in schemastore: response = { : , : , : l10n_schemastore[event.client.language][event.data] } ...
Return a single schema
360,910
def comparable(self): string_parts = [] if self.data_stream: string_parts.append(.format(self.data_stream)) if self.location is not None: string_parts.append(.format(self.location)) if self.mft_attribute is not None: string_parts.append(.format(self.mft_attribute)) if self.mf...
str: comparable representation of the path specification.
360,911
def gts7(Input, flags, output): zn1 = [120.0, 110.0, 100.0, 90.0, 72.5] mn1 = 5 dgtr=1.74533E-2; dr=1.72142E-2; alpha = [-0.38, 0.0, 0.0, 0.0, 0.17, 0.0, -0.38, 0.0, 0.0] altl = [200.0, 300.0, 160.0, 250.0, 240.0, 450.0, 320.0, 450.0] za = pdl[1][15]; zn1[0] = za; for j in rang...
/* Thermospheric portion of NRLMSISE-00 * See GTD7 for more extensive comments * alt > 72.5 km! */
360,912
def notification_factory(code, subcode): notification = BGPNotification(code, subcode) if not notification.reason: raise ValueError() return notification
Returns a `Notification` message corresponding to given codes. Parameters: - `code`: (int) BGP error code - `subcode`: (int) BGP error sub-code
360,913
def of(jvalue, bigdl_type="float"): def get_py_name(jclass_name): if jclass_name == "StaticGraph" or jclass_name == "DynamicGraph": return "Model" elif jclass_name == "Input": return "Layer" else: return jclass_name ...
Create a Python Layer base on the given java value and the real type. :param jvalue: Java object create by Py4j :return: A Python Layer
360,914
def marshal(self, obj, as_map_key, cache): handler = self.handlers[obj] tag = handler.tag(obj) f = marshal_dispatch.get(tag) if f: f(self, obj, handler.string_rep(obj) if as_map_key else handler.rep(obj), as_map_key, cache) else: self.emit_encode...
Marshal an individual obj, potentially as part of another container object (like a list/dictionary/etc). Specify if this object is a key to a map/dict, and pass in the current cache being used. This method should only be called by a top-level marshalling call and should not be considere...
360,915
def make_server(application, conf_dir=None): if conf_dir: load_config(conf_dir) configure_syslog() log_config() if options.use_ssl: ssl_options = ssl_server_options() server = tornado.httpserver.HTTPServer( application, ssl_options=ssl_options) genera...
Configure the server return the server instance
360,916
def bb_get_instr_max_width(basic_block): asm_mnemonic_max_width = 0 for instr in basic_block: if len(instr.mnemonic) > asm_mnemonic_max_width: asm_mnemonic_max_width = len(instr.mnemonic) return asm_mnemonic_max_width
Get maximum instruction mnemonic width
360,917
def get_next_step(self): layer_purpose = self.parent.step_kw_purpose.selected_purpose() if layer_purpose != layer_purpose_aggregation: subcategory = self.parent.step_kw_subcategory.\ selected_subcategory() else: subcategory = {: None} ...
Find the proper step when user clicks the Next button. :returns: The step to be switched to :rtype: WizardStep
360,918
def lookup(alias): if alias in matchers: return matchers[alias] else: norm = normalize(alias) if norm in normalized: alias = normalized[norm] return matchers[alias] if -1 != alias.find(): norm = normalize(alias).replace(, ) return l...
Tries to find a matcher callable associated to the given alias. If an exact match does not exists it will try normalizing it and even removing underscores to find one.
360,919
def from_other_new_params_by_name(cls, ori, par_subs, new_par_names=(), **kwargs): if not ori.dep_by_name: warnings.warn() if not ori.par_by_name: warnings.warn() dep = dict(zip(ori.names, ori.dep)) new_pars = ori.be.real_symarray( , len(ori.p...
Creates a new instance with an existing one as a template (with new parameters) Calls ``.from_other_new_params`` but first it creates the new instances from user provided callbacks generating the expressions the parameter substitutions. Parameters ---------- ori : SymbolicSys i...
360,920
def list_registered_stateful_ops_without_inputs(): return set([ name for name, op in op_def_registry.get_registered_ops().items() if op.is_stateful and not op.input_arg ])
Returns set of registered stateful ops that do not expect inputs. This list is used to identify the ops to be included in the state-graph and that are subsequently fed into the apply-graphs. Returns: A set of strings.
360,921
def format_rpc(data): address, rpc_id, args, resp, _status = data name = rpc_name(rpc_id) if isinstance(args, (bytes, bytearray)): arg_str = hexlify(args) else: arg_str = repr(args) if isinstance(resp, (bytes, bytearray)): resp_str = hexlify(resp) else: r...
Format an RPC call and response. Args: data (tuple): A tuple containing the address, rpc_id, argument and response payloads and any error code. Returns: str: The formated RPC string.
360,922
def getTargetFnDef(node,path,fdefs,cdefs,imp_funcs,imp_mods,imp_classes): if isinstance(node.func,ast.Name): if path in fdefs: for x in fdefs[path]: if node.func.id == x.name: return x if path in imp_funcs: ...
Return the function node that the input call node targets. Note that cases 2b and 2c might make false matches. If two classes are imported by the same program and they both have a method with an identical name, then class.method() will be associated with the first class in imp_classes.
360,923
def render_to_string(template, object, params=None): xsl_path = find_template_path(template) xml = xmltree.xml(object) result = transform(xml, str(xsl_path), params) return result
``object`` will be converted to xml using :func:`easymode.tree.xml`. The resulting xml will be transformed using ``template``. The result is a unicode string containing the transformed xml. :param template: an xslt template name. :param object: an object that has an ``__xml__`` method. (See :func:...
360,924
def stop(self=None): if not self: instance = getattr(Runner.instance(), , None) self = instance and instance() if not self: return self._runner.stop() if self.project: self.project.stop() self.project = None
Stop the builder if it's running.
360,925
def userBrowser(self, request, tag): f = LocalUserBrowserFragment(self.browser) f.docFactory = webtheme.getLoader(f.fragmentName) f.setFragmentParent(self) return f
Render a TDB of local users.
360,926
def new_notebook(metadata=None, worksheets=None): nb = NotebookNode() nb.nbformat = 2 if worksheets is None: nb.worksheets = [] else: nb.worksheets = list(worksheets) if metadata is None: nb.metadata = new_metadata() else: nb.metadata = NotebookNode(metadata)...
Create a notebook by name, id and a list of worksheets.
360,927
def get_var(script_path, var): if path.isfile(script_path): input = % (script_path, var) pipe = Popen(["bash"], stdout=PIPE, stdin=PIPE, stderr=PIPE) stdout_data, stderr_data = pipe.communicate(input=input) if stderr_data: raise ShellScriptException(script_path, std...
Given a script, and the name of an environment variable, returns the value of the environment variable. :param script_path: Path the a shell script :type script_path: str or unicode :param var: environment variable name :type var: str or unicode :return: str
360,928
def _copy_and_clean_up_expectation(self, expectation, discard_result_format_kwargs=True, discard_include_configs_kwargs=True, discard_catch_exceptions_kwargs=True, ...
Returns copy of `expectation` without `success_on_last_run` and other specified key-value pairs removed Returns a copy of specified expectation will not have `success_on_last_run` key-value. The other key-value \ pairs will be removed by default but will remain in the copy if specified. ...
360,929
def fetch_request_ids(item_ids, cls, attr_name, verification_list=None): if not item_ids: return [] items = [] for item_id in item_ids: item = cls.fetch_by_id(item_id) if not item or (verification_list is not None and item not in verification_list): ...
Return a list of cls instances for all the ids provided in item_ids. :param item_ids: The list of ids to fetch objects for :param cls: The class to fetch the ids from :param attr_name: The name of the attribute for exception purposes :param verification_list: If provided, a list of acceptable instances...
360,930
def _get_moment_tensor_from_ndk_string(self, ndk_string): moment_tensor = GCMTMomentTensor() tensor_data = _read_moment_tensor_from_ndk_string(ndk_string, ) moment_tensor.tensor = tensor_data[0] moment_tensor.tensor_sigma = tensor_data[1] moment_tensor.exponent = tensor_...
Reads the moment tensor from the ndk_string and returns an instance of the GCMTMomentTensor class. By default the ndk format uses the Up, South, East (USE) reference system.
360,931
def execNetstatCmd(self, *args): out = util.exec_command([netstatCmd,] + list(args)) return out.splitlines()
Execute ps command with positional params args and return result as list of lines. @param *args: Positional params for netstat command. @return: List of output lines
360,932
def _build_hline(self, is_header=False): horiz = self._char_horiz if (is_header): horiz = self._char_header s = "%s%s%s" % (horiz, [horiz, self._char_corner][self._has_vlines()], horiz) l = s.join([horiz * n for n in self._width]) ...
Return a string used to separated rows or separate header from rows
360,933
def has_api_scopes(self, *api_scopes): if self._authorized_api_scopes is None: return None return all((x in self._authorized_api_scopes) for x in api_scopes)
Test if all given API scopes are authorized. :type api_scopes: list[str] :param api_scopes: The API scopes to test :rtype: bool|None :return: True or False, if the API Token has the API scopes field set, otherwise None
360,934
def load_plugins(config, plugin_kwargs): installed_plugins = _gather_installed_plugins() metrics_plugin = _get_metrics_plugin(config, installed_plugins) if metrics_plugin: plugin_kwargs[] = metrics_plugin active_plugins = _get_activated_plugins(config, installed_plugins) if not active_...
Discover and instantiate plugins. Args: config (dict): loaded configuration for the Gordon service. plugin_kwargs (dict): keyword arguments to give to plugins during instantiation. Returns: Tuple of 3 lists: list of names of plugins, list of instantiated plugin objec...
360,935
def levelorder(self): current_nodes = [self] result = [] while len(current_nodes) > 0: next_nodes = [] for node in current_nodes: result.append(node) if node.left is not None: next_nodes.append(node.left) ...
Return the nodes in the binary tree using level-order_ traversal. A level-order_ traversal visits nodes left to right, level by level. .. _level-order: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search :return: List of nodes. :rtype: [binarytree.Node] ...
360,936
def remove_object(self, name): if name in self._objs: self._manager.unregisterObject(self._objs[name][]) self._manager.update(self._objs[name][]) geom_id = id(self._objs.pop(name)[]) self._names.pop(geom_id) else: ...
Delete an object from the collision manager. Parameters ---------- name : str The identifier for the object
360,937
def get_all_interface_details(auth, url, devid=None, devip=None): if devip is not None: devid = get_dev_details(devip, auth, url)[] get_all_interface_details_url = "/imcrs/plat/res/device/" + str( devid) + "/interface/?start=0&size=1000&desc=false&total=false" f_url = url + get_all_inte...
function takes the devId of a specific device and the ifindex value assigned to a specific interface and issues a RESTFUL call to get the interface details file as known by the HP IMC Base Platform ICC module for the target device. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.au...
360,938
def saturation(self, value): value = clean_float(value) if value is None: return try: unit_moisture_weight = self.unit_moist_weight - self.unit_dry_weight unit_moisture_volume = unit_moisture_weight / self._pw saturation = unit_moisture_vo...
Volume of water to volume of voids
360,939
def get_section_by_offset(self, offset): sections = [s for s in self.sections if s.contains_offset(offset)] if sections: return sections[0] return None
Get the section containing the given file offset.
360,940
def requirements(fname): packages = Setup.read(fname, fail_silently=True).split() packages = (p.strip() for p in packages) packages = (p for p in packages if p and not p.startswith()) return list(packages)
Utility function to create a list of requirements from the output of the pip freeze command saved in a text file.
360,941
def connect(self): try: if S3Handler.S3_KEYS: self.s3 = BotoClient(self.opt, S3Handler.S3_KEYS[0], S3Handler.S3_KEYS[1]) else: self.s3 = BotoClient(self.opt) except Exception as e: raise RetryFailure( % e)
Connect to S3 storage
360,942
def save(self, *args, **kwargs): if self.name == : raise FieldError else: return super(CrossRefDB, self).save(*args, **kwargs)
Extends save() method of Django models to check that the database name is not left blank. Note: 'blank=False' is only checked at a form-validation-stage. A test using Fixtureless that tries to randomly create a CrossRefDB with an empty string name would unintentionally break the test.
360,943
def system_exit_exception_handler(*args): reporter = Reporter() reporter.Footer_label.setText( "The severity of this exception is critical, <b>{0}</b> cannot continue and will now close!".format( Constants.application_name)) base_exception_handler(*args) foundations.core.exit...
Provides a system exit exception handler. :param \*args: Arguments. :type \*args: \* :return: Definition success. :rtype: bool
360,944
def hdf5_storable(type_or_storable, *args, **kwargs): if not isinstance(type_or_storable, Storable): type_or_storable = default_storable(type_or_storable) hdf5_service.registerStorable(type_or_storable, *args, **kwargs)
Registers a `Storable` instance in the global service.
360,945
def StartElement(self,name,attributes): element = Element(name.encode(),attributes) if len(self.nodeStack) > 0: parent = self.nodeStack[-1] parent.AddChild(element) else: self.root = element self.nodeStack.append(element)
SAX start element even handler
360,946
def doublewell_eigs(n_grid, lag_time=1): return _brownian_eigs(n_grid, lag_time, DOUBLEWELL_GRAD_POTENTIAL, -np.pi, np.pi, reflect_bc=True)
Analytic eigenvalues/eigenvectors for the doublwell system TODO: DOCUMENT ME
360,947
def Slot(self, slotnum): self.assertNested() self.current_vtable[slotnum] = self.Offset()
Slot sets the vtable key `voffset` to the current location in the buffer.
360,948
def stop(self): if not self.running: return self._logger.debug("sending stop signal to task") self._task.cancel()
Send a signal to the main broker task to terminate. You have to check :attr:`running` and possibly wait for it to become :data:`False` --- the task takes at least one loop through the event loop to terminate. It is guarenteed that the task will not attempt to send stanzas over the exist...
360,949
def publish_command_start(self, command, database_name, request_id, connection_id, op_id=None): if op_id is None: op_id = request_id event = CommandStartedEvent( command, database_name, request_id, connection_id, op_id) for subscribe...
Publish a CommandStartedEvent to all command listeners. :Parameters: - `command`: The command document. - `database_name`: The name of the database this command was run against. - `request_id`: The request id for this operation. - `connection_id`: The address...
360,950
def print_all_devices(): print("Printing information about all devices paired to the Gateway") if len(devices) == 0: exit(bold("No devices paired")) container = [] for dev in devices: container.append(dev.raw) print(jsonify(container))
Print all devices as JSON
360,951
def call( cls, service, endpoint, method=None, path_kwargs=None, session=None, params=None, data=None, json=None, headers=None, cookies=None, auth=None, encoding=None, retry_spec=DEFAULT_RETRY, timeou...
:param Service service: The service that hosts the endpoint being called :param Endpoint endpoint: The endpoint being called :param str method: The HTTP method to use for the call :param dict path_kwargs: Arguments to be formatted into the ``endpoi...
360,952
def extract_feed( inpath: str, outpath: str, view: View, config: nx.DiGraph = None ) -> str: config = default_config() if config is None else config config = remove_node_attributes(config, "converters") feed = load_feed(inpath, view, config) return write_feed_dangerously(feed, outpath)
Extract a subset of a GTFS zip into a new file
360,953
def enter_room(self, sid, room, namespace=None): namespace = namespace or self.logger.info(, sid, room, namespace) self.manager.enter_room(sid, namespace, room)
Enter a room. This function adds the client to a room. The :func:`emit` and :func:`send` functions can optionally broadcast events to all the clients in a room. :param sid: Session ID of the client. :param room: Room name. If the room does not exist it is created. :para...
360,954
def eval_proxop(self, V): return sp.prox_l1(V, (self.lmbda / self.L) * self.wl1)
Compute proximal operator of :math:`g`.
360,955
def pos_branch(incl, chi): if incl == 0: chi_eff = chi else: rISSO = PG_ISSO_solver(chi,incl) chi_eff = scipy.optimize.fsolve(ISCO_eq_chi_first, 1.0, args=(rISSO)) return chi_eff
Determines the effective [as defined in Stone, Loeb, Berger, PRD 87, 084053 (2013)] aligned dimensionless spin parameter of a NS-BH binary with tilted BH spin. This means finding the root chi_eff of ISCO_eq_chi_first(chi_eff, PG_ISSO_solver(chi,incl)). The result returned by this function belongs to...
360,956
def addPendingResult( self, ps, jobid ): k = self._parametersAsIndex(ps) if k in self._results.keys(): rs = self._results[k] else: rs = [] self._results[k] = rs rs.insert(0, jobid) self._pending[jobid] = k
Add a "pending" result that we expect to get results for. :param ps: the parameters for the result :param jobid: an identifier for the pending result
360,957
def calc_qma_v1(self): der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess for idx in range(der.nmb): flu.qma[idx] = 0. for jdx in range(der.ma_order[idx]): flu.qma[idx] += der.ma_coefs[idx, jdx] * log.logi...
Calculate the discharge responses of the different MA processes. Required derived parameters: |Nmb| |MA_Order| |MA_Coefs| Required log sequence: |LogIn| Calculated flux sequence: |QMA| Examples: Assume there are three response functions, involving one, two and ...
360,958
def parseConfig(cls, value): if in value: value[] = bool(value[]) if in value: value[] = [n.strip() for n in ast.literal_eval(value[])] return value
Parse the config values Args: value (dict): Dictionary which contains the checker config Returns: dict: The checker config with parsed values
360,959
def queue(self, *args, **kwargs): queue_name = kwargs.pop(, self.queue_name) timeout = kwargs.pop(, self.timeout) result_ttl = kwargs.pop(, self.result_ttl) ttl = kwargs.pop(, self.ttl) depends_on = kwargs.pop(, self._depends_on) job_id = kwargs.pop(, None) ...
A function to queue a RQ job, e.g.:: @rq.job(timeout=60) def add(x, y): return x + y add.queue(1, 2, timeout=30) :param \\*args: The positional arguments to pass to the queued job. :param \\*\\*kwargs: The keyword arguments to pass to the queued jo...
360,960
def get_ports(self): ports = [] container_ports = self.inspect(refresh=True)["NetworkSettings"]["Ports"] if not container_ports: return ports for p in container_ports: ports.append(p.split("/")[0]) return ports
get ports specified in container metadata :return: list of str
360,961
def list_group_maintainers(self, name): return self.service.list_group_maintainers( name, self.url_prefix, self.auth, self.session, self.session_send_opts)
Get the maintainers of a group. Args: name (string): Name of group to query. Returns: (list[string]): List of maintainer names.
360,962
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types) C = self.COEFFS[imt] delta_R, delta_S, delta_V, delta_I = self._get_...
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
360,963
def get(self, key, *val): data = self.get_data() if data is not None: return data.get(key, *val) if val: return val[0] raise KeyError(key)
Get value stored for current running task. Optionally you may provide the default value. Raises `KeyError` when can't get the value and no default one is provided.
360,964
def save_metadata(hparams): output_dir = os.path.expanduser(FLAGS.output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) if hasattr(FLAGS, "flags_into_string"): flags_str = FLAGS.flags_into_string() t2t_flags_str = "\n".join([ "--%s=%s" % (f.name, f.value) ...
Saves FLAGS and hparams to output_dir.
360,965
def unaligned_get_dimension(text): xmax = 0 ymax = 0 ymax = 0 angle = None halign = None valign = None itr = text_iterator(None) for line in str(text).split(): cur_height = 0 cur_width = 0 itr.reset(line) while 1: elem = next(itr) ...
Return the bounding box of the text, assuming that the left-bottom corner of the first letter of the text is at (0, 0). This procedure ignores /h, /v, and /a directives when calculating the BB; it just returns the alignment specifiers as a part of the return value. The return value is a tuple (width, he...
360,966
def jsonmget(self, path, *args): pieces = [] pieces.extend(args) pieces.append(str_path(path)) return self.execute_command(, *pieces)
Gets the objects stored as a JSON values under ``path`` from keys ``args``
360,967
def run_samblaster(job, sam): work_dir = job.fileStore.getLocalTempDir() job.fileStore.readGlobalFile(sam, os.path.join(work_dir, )) command = [, , , , , ] start_time = time.time() dockerCall(job=job, workDir=work_dir, parameters=comm...
Marks reads as PCR duplicates using SAMBLASTER :param JobFunctionWrappingJob job: passed automatically by Toil :param str sam: FileStoreID for SAM file :return: FileStoreID for deduped SAM file :rtype: str
360,968
def handle_starttag(self, tag, attrs): self.log.debug( u.format(tag, attrs) ) if tag in self.sanitizelist: self.level += 1 return if self.isNotPurify or tag in self.whitelist_keys: attrs = self.__attrs_str(tag, attrs) attrs = + attrs if a...
Handler of starting tag processing (overrided, private)
360,969
def plot_bs_dists(run, fthetas, axes, **kwargs): ftheta_lims = kwargs.pop(, [[-1, 1]] * len(fthetas)) n_simulate = kwargs.pop(, 100) colormap = kwargs.pop(, plt.get_cmap()) mean_color = kwargs.pop(, None) nx = kwargs.pop(, 100) ny = kwargs.pop(, nx) cache_in = kwargs.pop(, None) par...
Helper function for plotting uncertainties on posterior distributions using bootstrap resamples and the fgivenx module. Used by bs_param_dists and param_logx_diagram. Parameters ---------- run: dict Nested sampling run to plot. fthetas: list of functions Quantities to plot. Each...
360,970
def register_jvm_tool(cls, register, key, classpath_spec=None, main=None, custom_rules=None, fingerprint=True, classpath=None, h...
Registers a jvm tool under `key` for lazy classpath resolution. Classpaths can be retrieved in `execute` scope via `tool_classpath_from_products`. NB: If the tool's `main` class name is supplied the tool classpath will be shaded. :param register: A function that can register options with the option syste...
360,971
def config_logging(level): logger = logging.getLogger() logger.setLevel(level) if level < logging.DEBUG: log_format = "%(asctime)s %(message)s" else: log_format = "%(asctime)s %(module)s : %(lineno)d %(message)s" sh = logging.StreamHandler() sh.formatter = logging.Formatte...
Configure the logging given the level desired
360,972
def create_status_sentinel_file(self, fail): logName = if fail else localLog = os.path.join(os.getcwd(), logName) open(localLog, ).close() self.jobStore.importFile( + localLog, logName, hardlink=True) if os.path.exists(localLog): os.remove(localLog)
Create a file in the jobstore indicating failure or success.
360,973
def decorate(self, pos, widget, is_first=True): line = None if pos is not None: original_widget = widget cols = self._construct_spacer(pos, []) if self._indent > 0: if is_first: indent = self._con...
builds a list element for given position in the tree. It consists of the original widget taken from the Tree and some decoration columns depending on the existence of parent and sibling positions. The result is a urwid.Columns widget.
360,974
def is_function_variadic(self): assert self.kind == TypeKind.FUNCTIONPROTO return conf.lib.clang_isFunctionTypeVariadic(self)
Determine whether this function Type is a variadic function type.
360,975
def fromdict(cls, datadict): new_datatable = cls() for field, column in datadict.items(): new_datatable[field] = column return new_datatable
Constructs a new DataTable using a dictionary of the format: {field1: [a,b,c], field2: [d,e,f], field3: [g,h,i]} ... which most closely matches the internal representation of the DataTable. If it is an OrderedDict, the key order will be preserved.
360,976
def truncate_selection(self, position_from): position_from = self.get_position(position_from) cursor = self.textCursor() start, end = cursor.selectionStart(), cursor.selectionEnd() if start < end: start = max([position_from, start]) else: ...
Unselect read-only parts in shell, like prompt
360,977
def tag(*tags): def dfn(fn): _tags = getattr(fn, , set()) _tags.update(tags) fn.tags = _tags return fn return dfn
Constructs a decorator that tags a function with specified strings (@tags). The tags on the decorated function are available via fn.tags
360,978
def _rm_dr_link(self, rec): if not rec.is_file(): raise pycdlibexception.PyCdlibInvalidInput() num_bytes_to_remove = 0 logical_block_size = rec.vd.logical_block_size() done = False while not done: num_bytes_to_remove += self._remove_ch...
An internal method to remove a Directory Record link given the record. Parameters: rec - The Directory Record to remove. Returns: The number of bytes to remove from the ISO.
360,979
def all_to_annot(self, annot, names=[, , , ]): self.to_annot(annot, , names[0]) self.to_annot(annot, , names[1]) self.to_annot(annot, , names[2]) self.to_annot(annot, , names[3])
Convenience function to write all events to XML by category, showing overlapping TP detection and TP standard.
360,980
def _clean_output(v): out = copy.deepcopy(v) outb = out.pop("outputBinding", {}) if "secondaryFiles" in outb: out["secondaryFiles"] = outb["secondaryFiles"] return out
Remove output specific variables to allow variables to be inputs to next steps.
360,981
def zrevrange_with_int_score(self, key, max_score, min_score): self._prune_penalty_box() if len(self.active_clients) == 0: raise ClusterEmptyError("All clients are down.") element__score = defaultdict(int) for client in self.active_clients: revrange = c...
Get the zrevrangebyscore across the cluster. Highest score for duplicate element is returned. A faster method should be written if scores are not needed.
360,982
def _get_link(self, peer): assert isinstance(peer, beans.Peer) for router in self._routers: link = router.get_link(peer) if link: return link raise ValueError("No link to peer {0}".format(peer))
Returns a link to the given peer :return: A Link object :raise ValueError: Unknown peer
360,983
def _strip_datetime(self, sub_line): try: begin = sub_line.index() except ValueError: return sub_line else: sub = sub_line[begin + 1:] return sub
Strip datetime and other parts so that there is no redundancy.
360,984
def pformat(obj, verbose=False): try: from pretty import pretty return pretty(obj, verbose=verbose) except ImportError: from pprint import pformat return pformat(obj)
Prettyprint an object. Either use the `pretty` library or the builtin `pprint`.
360,985
def parse_failed_targets(test_registry, junit_xml_path, error_handler): failed_targets = defaultdict(set) def parse_junit_xml_file(path): try: xml = XmlParser.from_file(path) failures = int(xml.get_attribute(, )) errors = int(xml.get_attribute(, )) if failures or errors: for ...
Parses junit xml reports and maps targets to the set of individual tests that failed. Targets with no failed tests are omitted from the returned mapping and failed tests with no identifiable owning target are keyed under `None`. :param test_registry: A registry of tests that were run. :type test_registry: :cl...
360,986
def parent_site(self, site): self._parent_site = site if sharedcontent_appsettings.FLUENT_SHARED_CONTENT_ENABLE_CROSS_SITE: return self.filter(Q(parent_site=site) | Q(is_cross_site=True)) else: return self.filter(parent_site=site)
Filter to the given site, only give content relevant for that site.
360,987
def _apply_secure(self, func, permission=None): self._handle_api_doc(func, {: }) @wraps(func) def wrapper(*args, **kwargs): if not current_user.is_authenticated: self.abort(401) if permission is not None: with permission.require(...
Enforce authentication on a given method/verb
360,988
def translate_to_english_phonetic_alphabet(self, hide_stress_mark=False): translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else "" for phoneme in self._phoneme_list: translations += phoneme.english return translations
转换成英音。只要一个元音的时候需要隐藏重音标识 :param hide_stress_mark: :return:
360,989
def reorder_parents(self, new_order, inplace=True): if (len(self.variables) <= 1 or (set(new_order) - set(self.variables)) or (set(self.variables[1:]) - set(new_order))): raise ValueError("New order either has missing or extra arguments") else: if new_ord...
Returns a new cpd table according to provided order. Parameters ---------- new_order: list list of new ordering of variables inplace: boolean If inplace == True it will modify the CPD itself otherwise new value will be returned without affecting old ...
360,990
def download_raw(url, local_path, callback): log.debug(.format(url=url, local_path=local_path)) raw_progress = RawDownloadProgress(callback) reporthook = raw_progress.get_report_hook() try: log.debug(.format(url=url, local_path=local_path)) urlretrieve(url=url, filename=local_path, ...
Download an url to a local file. :param url: url of the file to download :param local_path: path where the downloaded file should be saved :param callback: instance of ProgressCallback :return: True is succeeded
360,991
def _match_value_filter(self, p, value): return self._VALUE_FILTER_MAP[p[0]](value[p[1]], p[2])
Returns True of False if value in the pattern p matches the filter.
360,992
def options(self, *args, **kwargs): self.set_header(, .join(self.ALLOW)) self.set_status(204) self.finish()
Implement the HTTP OPTIONS method :param list args: Positional arguments :param dict kwargs: Keyword arguments
360,993
def _walk_all_files(): record_dirs = set() result_set = set() for filename in Settings.paths: filename_full = os.path.abspath(filename) if Settings.recurse and os.path.isdir(filename_full): record_dirs.add(filename_full) walk_after = timestamp.get_wal...
Optimize the files from the arugments list in two batches. One for absolute paths which are probably outside the current working directory tree and one for relative files.
360,994
def emit(self, record): future = asyncio.ensure_future(send_manager_command( ExecutorProtocol.LOG, extra_fields={ ExecutorProtocol.LOG_MESSAGE: self.format(record), }, expect_reply=False )) self.emit_list.append(future)
Send log message to the listener.
360,995
def dump_conf(self, config_pathname=None): if not config_pathname: config_pathname = self._get_option().value opener = functools.partial(open, config_pathname, ) config_file_type = os.path.splitext(config_pathname)[1][1:] skip_keys = [ k for (k, v) ...
write a config file to the pathname specified in the parameter. The file extention determines the type of file written and must match a registered type. parameters: config_pathname - the full path and filename of the target config file.
360,996
def tail(self, bytes): self.io.seek(max(0, self.size() - bytes)) return self.io.read()
Returns the number of given bytes from the tail of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number of bytes to return.
360,997
def configure(service, key, auth, use_syslog): add_key(service, key) create_key_file(service, key) hosts = get_ceph_nodes() with open(, ) as ceph_conf: ceph_conf.write(CEPH_CONF.format(auth=auth, keyring=_keyring_path(service), ...
Perform basic configuration of Ceph.
360,998
def send(sms_to, sms_body, **kwargs): headers = { "User-Agent": "DBMail/%s" % get_version(), : % b64encode( "%s:%s" % ( settings.IQSMS_API_LOGIN, settings.IQSMS_API_PASSWORD )).decode("ascii") } kwargs.update({ : sms_to, : from_u...
Site: http://iqsms.ru/ API: http://iqsms.ru/api/
360,999
def is_variable(tup): name, item = tup if callable(item): return False if isinstance(item, types.ModuleType): return False if name.startswith("_"): return False return True
Takes (name, object) tuple, returns True if it is a variable.