Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
348,000
def _reduced2physical_deflection(self, alpha_reduced, idex_lens): factor = self._reduced2physical_factor[idex_lens] return alpha_reduced * factor
alpha_reduced = D_ds/Ds alpha_physical :param alpha_reduced: reduced deflection angle :param z_lens: lens redshift :param z_source: source redshift :return: physical deflection angle
348,001
def distort_matrix_Y(Z, Y, f, new_ymin, new_ymax, subsample=3): new_Z, new_Y = distort_matrix_X(Z.transpose(), Y, f, new_ymin, new_ymax, subsample) return new_Z.transpose(), new_Y
Applies a distortion (remapping) to the matrix Z (and y-values Y) using function f. returns new_Z, new_Y f is a function old_y(new_y) Z is a matrix. Y is an array where Y[n] is the y-value associated with the array Z[:,n]. new_ymin, new_ymax is the range of the distorted x-variable for generating Z ...
348,002
def align_times(times, frames): dist = np.minimum.outer(times, frames) bound_frames = np.argmax(np.maximum(0, dist), axis=1) aligned_times = np.unique(bound_frames) return aligned_times
Aligns the times to the closest frame times (e.g. beats). Parameters ---------- times: np.ndarray Times in seconds to be aligned. frames: np.ndarray Frame times in seconds. Returns ------- aligned_times: np.ndarray Aligned times.
348,003
def empty(self): for k in list(self.children.keys()): self.remove_child(self.children[k])
remove all children from the widget
348,004
def make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs_fn=None, frame_stack_size=None, rollout_agent_type=None, batch_size=None, inner_batch_size=None, env_type=None, **planner_kwargs ): if batch_size is None: batch_size = env.batch_size return { "random"...
Factory function for Agents.
348,005
def encode_alphanumeric(self): self.data = self.data.upper() ascii = [] for char in self.data: if isinstance(char, int): ascii.append(tables.ascii_codes[chr(char)]) else: ascii.append(tables.ascii_codes[char]) ...
This method encodes the QR code's data if its mode is alphanumeric. It returns the data encoded as a binary string.
348,006
def reset_group_subscription(self): if self._user_assignment: raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE) assert self.subscription is not None, self._group_subscription.intersection_update(self.subscription)
Reset the group's subscription to only contain topics subscribed by this consumer.
348,007
def calculate(self, where, calcExpression, sqlFormat="standard"): url = self._url + "/calculate" params = { "f" : "json", "where" : where, } if isinstance(calcExpression, dict): params["calcExpression"] = json.dumps([calcExpression], ...
The calculate operation is performed on a feature service layer resource. It updates the values of one or more fields in an existing feature service layer based on SQL expressions or scalar values. The calculate operation can only be used if the supportsCalculate property of the layer is...
348,008
def _list_releases(): if is_linux(): base_path = else: base_path = years = range(2050,1990,-1) release_letters = (, , , , , , , ) for year in years: for letter in release_letters: release = % (year, letter) matlab_path = base_path % (y...
Tries to guess matlab process release version and location path on osx machines. The paths we will search are in the format: /Applications/MATLAB_R[YEAR][VERSION].app/bin/matlab We will try the latest version first. If no path is found, None is reutrned.
348,009
def add(self, watch_key, tensor_value): if watch_key not in self._tensor_data: self._tensor_data[watch_key] = _WatchStore( watch_key, mem_bytes_limit=self._watch_mem_bytes_limit) self._tensor_data[watch_key].add(tensor_value)
Add a tensor value. Args: watch_key: A string representing the debugger tensor watch, e.g., 'Dense_1/BiasAdd:0:DebugIdentity'. tensor_value: The value of the tensor as a numpy.ndarray.
348,010
def iter_genotypes(self): for variant in self.df.columns: genotypes = self.df.loc[:, variant].values info = self.map_info.loc[variant, :] yield Genotypes( Variant(info.name, info.chrom, info.pos, [info.a1, info.a2]), genotype...
Iterates on available markers. Returns: Genotypes instances.
348,011
def date(self, pattern=, end_datetime=None): return self.date_time(end_datetime=end_datetime).strftime(pattern)
Get a date string between January 1, 1970 and now :param pattern format :example '2008-11-27'
348,012
def _parse_queue_list(list_output): queues = dict((q.split()[-1], q) for q in list_output[]) return queues
Parse the queue to get a dict of name -> URL
348,013
def find_occurrences(self, resource=None, pymodule=None): tools = _OccurrenceToolsCreator(self.project, resource=resource, pymodule=pymodule, docs=self.docs) for offset in self._textual_finder.find_offsets(tools.source_code): occurrence = Occu...
Generate `Occurrence` instances
348,014
def add_component_definition(self, definition): if definition.identity not in self._components.keys(): self._components[definition.identity] = definition else: raise ValueError("{} has already been defined".format(definition.identity))
Add a ComponentDefinition to the document
348,015
def relaxNGValidatePushElement(self, doc, elem): if doc is None: doc__o = None else: doc__o = doc._o if elem is None: elem__o = None else: elem__o = elem._o ret = libxml2mod.xmlRelaxNGValidatePushElement(self._o, doc__o, elem__o) return ret
Push a new element start on the RelaxNG validation stack.
348,016
async def send(self, data): self.writer.write(data) await self.writer.drain()
Add data to send queue.
348,017
def _validate_handler(column_name, value, predicate_refs): )) return value
handle predicate's return value
348,018
def _initialize_non_fluents(self): non_fluents = self.rddl.domain.non_fluents initializer = self.rddl.non_fluents.init_non_fluent self.non_fluents = self._initialize_pvariables( non_fluents, self.rddl.domain.non_fluent_ordering, initializer) r...
Returns the non-fluents instantiated.
348,019
def _get_contrast(self, con_id): for contrasts in list(self.contrasts.values()): for contrast in contrasts: if contrast.estimation.id == con_id: return contrast raise Exception("Contrast activity with id: " + str(con_id) + ...
Retreive contrast with identifier 'con_id' from the list of contrast objects stored in self.contrasts
348,020
def tune(self): if self._node.get(): tune = self._node[].get() if type(tune) is collections.OrderedDict: return tune elif type(tune) is list: return tune[0] return tune return None
XML node representing tune.
348,021
def crescent_data(model_type=, num_inducing=10, seed=default_seed, kernel=None, optimize=True, plot=True): try:import pods except ImportError:print() data = pods.datasets.crescent_data(seed=seed) Y = data[] Y[Y.flatten()==-1] = 0 if model_type == : m = GPy.models.GPClassification(d...
Run a Gaussian process classification on the crescent data. The demonstration calls the basic GP classification model and uses EP to approximate the likelihood. :param model_type: type of model to fit ['Full', 'FITC', 'DTC']. :param inducing: number of inducing variables (only used for 'FITC' or 'DTC'). :t...
348,022
def WriteClientSnapshot(self, snapshot, cursor=None): insert_history_query = ( "INSERT INTO client_snapshot_history(client_id, timestamp, " "client_snapshot) VALUES (%s, FROM_UNIXTIME(%s), %s)") insert_startup_query = ( "INSERT INTO client_startup_history(client_id, timestamp, " ...
Write new client snapshot.
348,023
def emitSortingChanged( self, index ): if not self.signalsBlocked() and self.isSortingEnabled(): self.sortingChanged.emit(index, self.header().sortIndicatorOrder())
Emits the sorting changed signal if the user clicks on a sorting column. :param index | <int>
348,024
def p_statement_foreach(p): if p[6] is None: p[0] = ast.Foreach(p[3], None, p[5], p[8], lineno=p.lineno(1)) else: p[0] = ast.Foreach(p[3], p[5], p[6], p[8], lineno=p.lineno(1))
statement : FOREACH LPAREN expr AS foreach_variable foreach_optional_arg RPAREN foreach_statement
348,025
def write(self, fp): if self._defaults: fp.write("[%s]\n" % DEFAULTSECT) for (key, value) in self._defaults.items(): fp.write("%s = %s\n" % (key, str(value).replace(, ))) fp.write("\n") for section in self._sections: fp.write("[%s]...
Write an .ini-format representation of the configuration state.
348,026
def get_port_profile_status_input_port_profile_name(self, **kwargs): config = ET.Element("config") get_port_profile_status = ET.Element("get_port_profile_status") config = get_port_profile_status input = ET.SubElement(get_port_profile_status, "input") port_profile_name =...
Auto Generated Code
348,027
def get_root_gradebooks(self): if self._catalog_session is not None: return self._catalog_session.get_root_catalogs() return GradebookLookupSession( self._proxy, self._runtime).get_gradebooks_by_ids(list(self.get_root_gradebook_ids()))
Gets the root gradebooks in this gradebook hierarchy. return: (osid.grading.GradebookList) - the root gradebooks raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method is must be implemented.*
348,028
def copy(self, fitness_function=None, decode_function=None, fitness_args=None, decode_args=None, fitness_kwargs=None, decode_kwargs=None): if fitness_function is None: fitness_function = self._fitness_function ...
Return a copy of this problem. Optionally replace this problems arguments with those passed in.
348,029
def weld_cast_array(array, weld_type, to_weld_type): if not is_numeric(weld_type) or not is_numeric(to_weld_type): raise TypeError(.format(weld_type, to_weld_type)) obj_id, weld_obj = create_weld_object(array) weld_template = weld_obj.weld_code = weld_template.format(array=obj_id, ...
Cast array to a different type. Parameters ---------- array : numpy.ndarray or WeldObject Input data. weld_type : WeldType Type of each element in the input array. to_weld_type : WeldType Desired type. Returns ------- WeldObject Representation of this co...
348,030
def method_id(self, api_info): if api_info.resource_name: resource_part = % self.__safe_name(api_info.resource_name) else: resource_part = return % (self.__safe_name(api_info.name), resource_part, self.__safe_name(self.name))
Computed method name.
348,031
def _set_port_to_port_profile_associations(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("port_to_port_profile_association",port_to_port_profile_associations.port_to_port_profile_associations, yang_name="port-to-port-profile-association...
Setter method for port_to_port_profile_associations, mapped from YANG variable /interface/port_channel/port_profile_to_interface_associations/port_profile_port/port_to_port_profile_associations (list) If this variable is read-only (config: false) in the source YANG file, then _set_port_to_port_profile_associati...
348,032
def to_dates(param): pos = param.find() lower, upper = (None, None) if pos == -1: lower, upper = (param, param) else: lower, upper = param.split() ret = (expand_date_param(lower, ), expand_date_param(upper, )) return ret
This function takes a date string in various formats and converts it to a normalized and validated date range. A list with two elements is returned, lower and upper date boundary. Valid inputs are, for example: 2012 => Jan 1 20012 - Dec 31 2012 (whole year) 201201 => Jan 1 2...
348,033
def inverse_jacobian(self, maps): m1 = maps[parameters.mass1] m2 = maps[parameters.mass2] return conversions.mchirp_from_mass1_mass2(m1, m2)/m2**2.
Returns the Jacobian for transforming mass1 and mass2 to mchirp and q.
348,034
def message_iter(evt): iter = evt.CreateMessageIterator() while iter.Next(): msg = iter.Message if DEBUG: print msg.Print if msg.AsElement.HasElement(): raise Exception(msg.AsElement.GetValue()) yield msg
provide a message iterator which checks for a response error prior to returning
348,035
def validate_ex(expected_schema, datum, identifiers=None, strict=False, foreign_properties=None, raise_ex=True, ...
Determine if a python datum is an instance of a schema.
348,036
def remove_unused_resources(issues, app_dir, ignore_layouts): for issue in issues: filepath = os.path.join(app_dir, issue.filepath) if issue.remove_file: remove_resource_file(issue, filepath, ignore_layouts) else: remove_resource_value(issue, filepath)
Remove the file or the value inside the file depending if the whole file is unused or not.
348,037
def _warn_key_unknown(cls, cls_context, key): context_name = cls_context.__name__ warnings.warn(cls._WARNING_KEY_UNKNOWN.format(key, context_name))
:type cls_context: type :type key: str :rtype: None
348,038
def ask_yes_no(message=, default=0, title=): return backend_api.opendialog("ask_yes_no", dict(message=message, default=default, title=title))
Display a message with choices of Yes and No. returned value: Yes -> True No -> False :ref:`screenshots<ask_yes_no>` :param message: message to be displayed. :param title: window title :param default: default button as boolean (YES=True, NO=False) :rtype: bool
348,039
def azure_firewall_fqdn_tags(self): api_version = self._get_api_version() if api_version == : from .v2018_08_01.operations import AzureFirewallFqdnTagsOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version...
Instance depends on the API version: * 2018-08-01: :class:`AzureFirewallFqdnTagsOperations<azure.mgmt.network.v2018_08_01.operations.AzureFirewallFqdnTagsOperations>`
348,040
def disable_scanners(self, scanners): scanner_ids = [] for scanner in scanners: if scanner in self.scanner_groups: self.disable_scanners_by_group(scanner) elif scanner.isdigit(): scanner_ids.append(scanner) else: ...
Enable the provided scanners by group and/or IDs.
348,041
def can_lookup_assets(self): url_path = construct_url(, bank_id=self._catalog_idstr) return self._get_request(url_path)[][]
Tests if this user can perform ``Asset`` lookups. A return of true does not guarantee successful authorization. A return of false indicates that it is known all methods in this session will result in a ``PermissionDenied``. This is intended as a hint to an application that may opt not t...
348,042
def load_rules(root=): module = __import__(root, fromlist=[root.split()[0]]) hinting_helpers = fmn.lib.hinting.__dict__.values() rules = {} for name in dir(module): obj = getattr(module, name) if not callable(obj): continue if obj in hintin...
Load the big list of allowed callable rules.
348,043
def init_app(self, app): self.init_config(app) if hasattr(app, ): app.cli.add_command(files_cmd) app.extensions[] = _FilesRESTState(app)
Flask application initialization.
348,044
def is_unix_like(platform=None): platform = platform or sys.platform platform = platform.lower() return platform.startswith("linux") or platform.startswith("darwin") or \ platform.startswith("cygwin")
Returns whether the given platform is a Unix-like platform with the usual Unix filesystem. When the parameter is omitted, it defaults to ``sys.platform``
348,045
async def publish(self, subject, payload, ack_handler=None, ack_wait=DEFAULT_ACK_WAIT, ): stan_subject = .join([self._pub_prefix, , subject]) guid = new_guid() pe = protocol.PubMsg() pe.clientID = self._client_id ...
Publishes a payload onto a subject. By default, it will block until the message which has been published has been acked back. An optional async handler can be publi :param subject: Subject of the message. :param payload: Payload of the message which wil be published. :param ack...
348,046
def option_decorator(name, greeting, yell): say = % (greeting, name) if yell: print % say.upper() else: print % say
Same as mix_and_match, but using the @option decorator.
348,047
def http_get(self, request_url): try: headers = {: } response = requests.get(request_url, headers=headers) except requests.exceptions.Timeout as ext: log.error(, ext) except requests.exceptions.TooManyRedirects as extmr: log.error(, extmr)...
This function recieves the request url and it is used internally to get the information via http. Returns the response content. Raises Timeout, TooManyRedirects, RequestException. Raises KeyError if headers are not present. Raises HTTPError if responde code is not 200.
348,048
def plot(self, column_for_xticks=None, select=None, overlay=True, width=6, height=4, **vargs): options = self.default_options.copy() options.update(vargs) if column_for_xticks is not None: x_data, y_labels = self._split_column_and_labels(column_for_xticks) x_lab...
Plot line charts for the table. Args: column_for_xticks (``str/array``): A column containing x-axis labels Kwargs: overlay (bool): create a chart with one color per data column; if False, each plot will be displayed separately. vargs: Additional arg...
348,049
def update_security_of_password(self, ID, data): log.info( % (ID, data)) self.put( % ID, data)
Update security of a password.
348,050
def _laplace_approximation_newton(self, tol=1e-6, stepsz=0.9, verbose=False): from pylds.util import solve_symm_block_tridiag, scipy_solve_symm_block_tridiag scale = self.T * self.D_emission def newton_step(x, stepsz): assert 0 <= stepsz <= 1 g = self.gradient_l...
Solve a block tridiagonal system with message passing.
348,051
def cli(parser): parser.add_argument(, , action=, help=) opts = parser.parse_args() for sitedir in site.getsitepackages(): cleanup(sitedir, execute=not opts.dry_run, verbose=opts.verbose or opts.dry_run)
Uninstall inactive Python packages from all accessible site-packages directories. Inactive Python packages when multiple packages with the same name are installed
348,052
def compute_video_metrics_from_predictions(predictions, decode_hparams): all_results = {} ssim_all_decodes, psnr_all_decodes = [], [] for single_decode in predictions: args = get_zipped_dataset_from_predictions(single_decode) psnr_single, ssim_single = compute_one_decoding_video_metrics(*args) ps...
Computes metrics from predictions. Args: predictions: list of list of dicts. outer length: num_decodes, inner_length: num_samples decode_hparams: Decode hparams. instance of HParams. Returns: statistics: dict of Tensors, key being the metric with each Tensor having the ...
348,053
def save_df_state( df_state: pd.DataFrame, site: str = , path_dir_save: Path = Path(),)->Path: . file_state_save = .format(site=site) file_state_save = file_state_save.replace(, ) path_state_save = path_dir_save/file_state_save print(.format(path_out=path_state_save)) ...
save `df_state` to a csv file Parameters ---------- df_state : pd.DataFrame a dataframe of model states produced by a supy run site : str, optional site identifier (the default is '', which indicates an empty site code) path_dir_save : Path, optional path to directory to sav...
348,054
def update_if_client(fctn): @functools.wraps(fctn) def _update_if_client(self, *args, **kwargs): b = self._bundle if b is None or not hasattr(b, ): return fctn(self, *args, **kwargs) elif b.is_client and \ (b._last_client_update is None or ...
Intercept and check updates from server if bundle is in client mode.
348,055
def get_mesh(self, var, coords=None): mesh = var.attrs.get() if mesh is None: return None if coords is None: coords = self.ds.coords return coords.get(mesh, self.ds.coords.get(mesh))
Get the mesh variable for the given `var` Parameters ---------- var: xarray.Variable The data source whith the ``'mesh'`` attribute coords: dict The coordinates to use. If None, the coordinates of the dataset of this decoder is used Returns ...
348,056
def get_partitions(self, database_name, table_name, expression=, page_size=None, max_items=None): config = { : page_size, : max_items, } paginator ...
Retrieves the partition values for a table. :param database_name: The name of the catalog database where the partitions reside. :type database_name: str :param table_name: The name of the partitions' table. :type table_name: str :param expression: An expression filtering the par...
348,057
def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4, start_index=0): position = tf.to_float(tf.range(length) + start_index) num_timescales = channels // 2 log_timescale_increment = ...
Gets a bunch of sinusoids of different frequencies. Each channel of the input Tensor is incremented by a sinusoid of a different frequency and phase. This allows attention to learn to use absolute and relative positions. Timing signals should be added to some precursors of both the query and the memory inpu...
348,058
def find_store_dirs(cls): store_dirs = [default_store_location()] extra_dirs_str = os.getenv() if extra_dirs_str: store_dirs.extend(extra_dirs_str.split()) return store_dirs
Returns the primary package directory and any additional ones from QUILT_PACKAGE_DIRS.
348,059
def lookup_by_latlon(lat,lon): logger.info("Looking up %s/%s via google"%(lat,lon)) results = Geocoder.reverse_geocode(float(lat),float(lon)) addrs=results.data[0][] d={} d[]=str(results) for addr in addrs: if addr[][0]==: d[]=addr[] elif addr[][0]==: ...
Looks up location given lat,lon returns dictionary with address: d['street number'] : 1925 d['route'] : Illinois Dr d['city'] : South Pasadena d['admin area 2'] : Los Angeles County d['admin area 1'] : California d['country'] : USA d['postal_code'] : 910...
348,060
def make_calibration_row_widget(ui, calibration_observable, label: str=None): calibration_row = ui.create_row_widget() row_label = ui.create_label_widget(label, properties={"width": 60}) row_label.widget_id = "label" offset_field = ui.create_line_edit_widget(properties={"width": 60}) offset_fie...
Called when an item (calibration_observable) is inserted into the list widget. Returns a widget.
348,061
def remove(self, objs_to_remove): if not self.children: return if not hasattr(objs_to_remove, ): objs_to_remove = [objs_to_remove] objs_to_remove = set(objs_to_remove) if len(objs_to_remove) == 0: return remove_from_here = objs_to_r...
Remove children from the Compound. Parameters ---------- objs_to_remove : mb.Compound or list of mb.Compound The Compound(s) to be removed from self
348,062
def load_module(self, module_name, path=None): self.ensure_started() if path is None: path = sys.path mod = self.client.call(_load_module, module_name, path) mod.__isolation_context__ = self return mod
Import a module into this isolation context and return a proxy for it.
348,063
def comparelist_view(self, request, object_id, extra_context=None): opts = self.model._meta object_id = unquote(object_id) current = get_object_or_404(self.model, pk=object_id) action_list = [ { "revision": version.revision, "...
Allow selecting versions to compare.
348,064
def inspect(self): if not self.client_config.features[]: raise ValueError("Client does not support volume configuration.", self.client_name) config_id = self.config_id parent_name = config_id.config_name if self.container_map.use_attached_parent_name else None volume...
Inspects the network state.
348,065
def getFullPathToSnapshot(self, n): return os.path.join(self.snapDir, str(n))
Get the full path to snapshot n.
348,066
def get_providers_info(pronac): df = data.providers_info grouped = df.groupby() return grouped.get_group(pronac)
Return all info about providers of a project with the given pronac.
348,067
def updateDraftThingType(self, thingTypeId, name, description, schemaId, metadata = None): draftThingTypeUrl = ApiClient.draftThingTypeUrl % (self.host, thingTypeId) draftThingTypeUpdate = { : name, : description, : schemaId, : metadata} r = requests.put(draftThingTypeUrl, auth=self....
Updates a thing type. It accepts thingTypeId (string), name (string), description (string), schemaId (string) and metadata(JSON) as the parameters In case of failure it throws APIException
348,068
def get_owner(gh, owner): try: u = gh.user(owner) name = u.name or u.login company = u.company or return [dict(name=name, affiliation=company)] except Exception: return None
Get owner of repository as a creator.
348,069
def program_detail(self, request, pk, program_uuid): enterprise_customer_catalog = self.get_object() program = enterprise_customer_catalog.get_program(program_uuid) if not program: raise Http404 context = self.get_serializer_context() context[] = enterpris...
Return the metadata for the specified program. The program needs to be included in the specified EnterpriseCustomerCatalog in order for metadata to be returned from this endpoint.
348,070
def _lemmatise_contractions(self, f, *args, **kwargs): fd = f for contraction, decontraction in self._contractions.items(): if fd.endswith(contraction): fd = f[:-len(contraction)] if "v" in fd or "V" in fd: fd += decontraction ...
Lemmatise un mot f avec sa contraction :param f: Mot à lemmatiser :yield: Match formated like in _lemmatise()
348,071
def _removeReceiver(receiver): if not sendersBack: return False backKey = id(receiver) try: backSet = sendersBack.pop(backKey) except KeyError: return False else: for senderkey in backSet: try: signals = list(connections[send...
Remove receiver from connections.
348,072
def _get_tough_method(self, name): def tough_method(*args, **kwargs): execute = name.startswith() con = self._con transaction = con._transaction if not transaction: con._ping_check(4) try: if con._maxusage: ...
Return a "tough" version of the given cursor method.
348,073
def normalize_header(name, existing=[]): name = re.sub(, , name, flags=re.UNICODE).lower() return name
Try to emulate the way in which Google does normalization on the column names to transform them into headers.
348,074
def set_position(self, pos, which=): self._polar.set_position(pos, which) if self._overlay_axes is not None: self._overlay_axes.set_position(pos, which) LambertAxes.set_position(self, pos, which)
Identical to Axes.set_position (This docstring is overwritten).
348,075
def _polling_iteration(self): scheduled_tasks = self.__sources_registry.check() has_postponed_tasks = self.__postponed_record_registry.has_records() maximum_tasks = self.maximum_running_records() if scheduled_tasks is not None or has_postponed_tasks is not None: running_tasks = len(self.__running_record_...
Poll for different scheduler events like: there are tasks to run, there are tasks to postpone there are postponed tasks that should be running :return: None
348,076
def breakup(self, state, recp): recp = recipient.IRecipient(recp) partner = self.find_partner(recp) if partner: return state.partners.breakup(partner) else: self.warning( , recp)
Order the agent to break the partnership with the given recipient
348,077
def kill(self, exc_info=None): if self._being_killed: _log.debug(, self) try: self._died.wait() except: pass safely_kill_extensions(self.entrypoints.all) self._kill_worker_threa...
Kill the container in a semi-graceful way. Entrypoints are killed, followed by any active worker threads. Next, dependencies are killed. Finally, any remaining managed threads are killed. If ``exc_info`` is provided, the exception will be raised by :meth:`~wait``.
348,078
def get_unique_counter(self, redis_conn=None, host=, port=6379, key=, cycle_time=5, start_time=None, window=SECONDS_1_HOUR, roll=True, keep_max=12): counter = UniqueCounter(key=key, cycle_time=cycle_time, start_time=s...
Generate a new UniqueCounter. Useful for exactly counting unique objects @param redis_conn: A premade redis connection (overrides host and port) @param host: the redis host @param port: the redis port @param key: the key for your stats collection @param cycle_time: how o...
348,079
def export_to_cytoscapejs(self): def _create_edge_data_dict(e): if e[3].get(): tooltip = e[3][][0] if tooltip.get(): del tooltip[] else: tooltip = None edge_data_dict = { ...
Return CAG in format readable by CytoscapeJS. Return ------ dict A JSON-like dict representing the graph for use with CytoscapeJS.
348,080
def filter_list(lst, takeout, case_sensitive=True): takeout = force_list(takeout) if not case_sensitive: lst = [x.lower() for x in lst] takeout = [y.lower() for y in takeout] return [x for x in lst if x not in takeout]
Return a modified list removing items specified. Args: lst: Original list of values takeout: Object or objects to remove from lst case_sensitive: if the search should be case sensitive Returns: list: Filtered list of values
348,081
def initializePage(self): tree = self.uiStructureTREE tree.blockSignals(True) tree.setUpdatesEnabled(False) self.uiStructureTREE.clear() xstruct = self.scaffold().structure() self._structure = xstruct for xentry in xstruct: ...
Initializes the page based on the current structure information.
348,082
def _set_service_policy(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("direction policy_map_name",service_policy.service_policy, yang_name="service-policy", rest_name="service-policy", parent=self, is_container=, user_ordered=False, pat...
Setter method for service_policy, mapped from YANG variable /system_qos/qos/service_policy (list) If this variable is read-only (config: false) in the source YANG file, then _set_service_policy is considered as a private method. Backends looking to populate this variable should do so via calling thisObj...
348,083
def add_trunk_ports(self): ports = self.attributes.get("{}Enable Full Trunk Ports".format(self.namespace_prefix), None) return self._parse_ports(ports=ports)
SDN Controller enable trunk ports :rtype: list[tuple[str, str]]
348,084
def API_GET(self, courseid, taskid=None): try: course = self.course_factory.get_course(courseid) except: raise APINotFound("Course not found") if not self.user_manager.course_is_open_to_user(course, lti=False): raise APIForbidden("You are not regi...
List tasks available to the connected client. Returns a dict in the form :: { "taskid1": { "name": "Name of the course", #the name of the course "authors": [], "deadline": ""...
348,085
def select(self, cursor, qstring, vals=()): "careful: dons from decorator)" cursor.execute(qstring, vals) return cursor.fetchall()
careful: don't pass cursor (it's from decorator)
348,086
def multiupload(self, filename, hosts): manager = Manager() successful_uploads = manager.list([]) def f(host): if len(successful_uploads) / float(len(hosts)) < \ settings.MIN_FILE_REDUNDANCY: result = self.upload_to_host(...
Upload file to multiple hosts simultaneously The upload will be attempted for each host until the optimal file redundancy is achieved (a percentage of successful uploads) or the host list is depleted. :param filename: The filename of the file to upload. :type filename: str ...
348,087
def view_fields(self, *attributes, **options): items = OrderedDict() if attributes: field_getter = attrgetter(*attributes) else: field_getter = attrgetter() if len(attributes) > 1: for key, value in zip(attributes, field_getter(self...
Returns an :class:`ordered dictionary <collections.OrderedDict>` which contains the selected field *attributes* of the `Pointer` field itself extended with a ``['data']`` key which contains the selected field *attribute* or the dictionaries of the selected field *attributes* for each :class:`Fie...
348,088
def _prepare_polib_files(files_dict, filename, languages, locale_root, po_files_path, header): files_dict[filename] = {} for lang in languages: file_path = os.path.join(locale_root, lang, po_files_path) if not os.path.exists(file_path): os.makedirs(file_...
Prepare polib file object for writing/reading from them. Create directories and write header if needed. For each language, ensure there's a translation file named "filename" in the correct place. Assumes (and creates) a directory structure: <locale_root>/<lang>/<po_files_path>/<filename>.
348,089
def _encrypt_xor(a, b, aes): a = unhexlify("%0.32x" % (int((a), 16) ^ int(hexlify(b), 16))) return aes.encrypt(a)
Returns encrypt(a ^ b).
348,090
def _request(self, path, method="GET", query=None, body=None, headers=None): assert path.startswith(), "bogus path: %r" % path if not isinstance(path, bytes): spath = path.encode(...
Make a Manta request ... @returns (res, content)
348,091
def dedent(lines): if len(lines) != 0: first_lstrip = lines[0].lstrip() strip_len = len(lines[0]) - len(first_lstrip) for line in lines: if len(line[:strip_len].strip()) != 0: raise ValueError( + line) else: ...
De-indent based on the first line's indentation.
348,092
def _cast_tuple(self, values): result = [] for i, value in enumerate(values): if i < len(self.field_types): result.append(self._cast_field(self.field_types[i], value)) else: result.append(self._cast_field(self.field_types[-1], value)) ...
Convert values of the tuple from raw bytes to native python types :param values: tuple of the raw database values :type value: tuple of bytes :return: converted tuple value :rtype: value of native python types (bytes, int, unicode (or str for py3k))
348,093
def send(self, data): start = time.time() try: scgi_resp = .join(self.transport.send(_encode_payload(data))) finally: self.latency = time.time() - start resp, self.resp_headers = _parse_response(scgi_resp) return resp
Send data over scgi to URL and get response.
348,094
def get_network_by_name(self, nwk_name): ret_net_lst = [] try: body = {} net_list = self.neutronclient.list_networks(body=body) net_list = net_list.get() for net in net_list: if net.get() == nwk_name: ret_net_ls...
Search for a openstack network by name.
348,095
def clear_line(mode=2): forwardrightbackwardleftfull text = sc.erase_line(_mode_map.get(mode, mode)) _write(text) return text
Clear the current line. Arguments: mode: | 0 | 'forward' | 'right' - Clear cursor to end of line. | 1 | 'backward' | 'left' - Clear cursor to beginning of line. | 2 | 'full' - Clear entire line. Note: Cursor position does ...
348,096
def H10(self): "Difference variance." c = (self.rlevels * self.p_xminusy).sum(1) c1 = np.tile(c, (self.nlevels,1)).transpose() e = self.rlevels - c1 return (self.p_xminusy * e ** 2).sum(1)
Difference variance.
348,097
def decode_value(stream): length = decode_length(stream) (value,) = unpack_value(">{:d}s".format(length), stream) return value
Decode the contents of a value from a serialized stream. :param stream: Source data stream :type stream: io.BytesIO :returns: Decoded value :rtype: bytes
348,098
def CheckDependencies(verbose_output=True): print() check_result = True for module_name, version_tuple in sorted(PYTHON_DEPENDENCIES.items()): if not _CheckPythonModule( module_name, version_tuple[0], version_tuple[1], is_required=version_tuple[3], maximum_version=version_tuple[2], ...
Checks the availability of the dependencies. Args: verbose_output (Optional[bool]): True if output should be verbose. Returns: bool: True if the dependencies are available, False otherwise.
348,099
def load_input_reader(input_params, readonly=False): logger.debug("find input reader with params %s", input_params) if not isinstance(input_params, dict): raise TypeError("input_params must be a dictionary") if "abstract" in input_params: driver_name = input_params["abstract"]["format"]...
Return input class of driver. Returns ------- input_params : ``InputData`` input parameters