Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
8,600
def on_button_release(self, event): affected_models = {} for inmotion in self._movable_items: inmotion.move((event.x, event.y)) rel_pos = gap_helper.calc_rel_pos_to_parent(self.view.canvas, inmotion.item, inmotion....
Write back changes If one or more items have been moved, the new position are stored in the corresponding meta data and a signal notifying the change is emitted. :param event: The button event
8,601
def attribute_exists(self, attribute, section): if foundations.namespace.remove_namespace(attribute, root_only=True) in self.get_attributes(section, strip_namespaces=True): LOGGER.debug("> ...
Checks if given attribute exists. Usage:: >>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \ "[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"] >>> sections_file_parser = SectionsFileParser() >>> sections_file_parser.content = cont...
8,602
def preShear(self, h, v): a, b = self.a, self.b self.a += v * self.c self.b += v * self.d self.c += h * a self.d += h * b return self
Calculate pre shearing and replace current matrix.
8,603
def add_target(self, name=None): def deco(func): def nestfunc(control): destdir = os.path.join(self.dest_dir, control[]) return [func(destdir, control)] key = name or func.__name__ self.nest.add(key, nestfunc, create_dir=False) ...
Add an SCons target to this nest. The function decorated will be immediately called with each of the output directories and current control dictionaries. Each result will be added to the respective control dictionary for later nests to access. :param name: Name for the target i...
8,604
def logstop(self): if self.logfile is not None: self.logfile.close() self.logfile = None else: print "Logging hadn't been started." self.log_active = False
Fully stop logging and close log file. In order to start logging again, a new logstart() call needs to be made, possibly (though not necessarily) with a new filename, mode and other options.
8,605
def update_ip(self, ip, record_type=, domains=None, subdomains=None): if domains is None: domains = self.get_domains() elif sys.version_info < (3, 0): if isinstance(domains, (str, unicode)): domains = [domains] elif sys.version_info >= (3, 0): ...
Update the IP address in all records, specified by type, to the value of ip. Returns True if no exceptions occurred during the update. If no domains are provided, all domains returned from self.get_domains() will be updated. By default, only A records are updated. :param record_type: The typ...
8,606
def initialize(self, runtime=None): if self._runtime is not None: raise IllegalState() self._runtime = runtime config = runtime.get_configuration() parameter_id = Id() host = config.get_value_by_parameter(parameter_id).get_string_value() if host is no...
Initializes this manager. A manager is initialized once at the time of creation. arg: runtime (osid.OsidRuntimeManager): the runtime environment raise: CONFIGURATION_ERROR - an error with implementation configuration raise: ILLEGAL_STATE - this manage...
8,607
def _encrypt(self, archive): arc_name = archive.replace("sosreport-", "secured-sosreport-") arc_name += ".gpg" enc_cmd = "gpg --batch -o %s " % arc_name env = None if self.enc_opts["key"]: enc_cmd += "--trust-model always -e -r %s " ...
Encrypts the compressed archive using GPG. If encryption fails for any reason, it should be logged by sos but not cause execution to stop. The assumption is that the unencrypted archive would still be of use to the user, and/or that the end user has another means of securing the archive...
8,608
def request( self, url: str, method: str, raise_for_status: bool = True, path_to_errors: tuple = None, *args, **kwargs ) -> tuple: session = kwargs.get("session", requests.Session()) log.debug( "sending a %s request to %s w...
A wrapper method for :meth:`~requests.Session.request``, which adds some defaults and logging :param url: The URL to send the reply to :param method: The method to use :param raise_for_status: Should an exception be raised for a failed response. Default is **True** :param args: Addition...
8,609
def p_bound_terminal(self, p): if p[1][0].literal in [, ]: p[0] = [_Segment(_BINDING, % self.binding_var_count), p[1][0], _Segment(_END_BINDING, )] self.binding_var_count += 1 else: p[0] = p[1]
bound_terminal : unbound_terminal
8,610
def prepare_video_params(self, title=None, tags=, description=, copyright_type=, public_type=, category=None, watch_password=None, latitude=None, longitude=None, shoot_time=None ): params...
util method for create video params to upload. Only need to provide a minimum of two essential parameters: title and tags, other video params are optional. All params spec see: http://cloud.youku.com/docs?id=110#create . Args: title: string, 2-50 characters. tag...
8,611
def detect_fts(conn, table): "Detect if table has a corresponding FTS virtual table and return it" rows = conn.execute(detect_fts_sql(table)).fetchall() if len(rows) == 0: return None else: return rows[0][0]
Detect if table has a corresponding FTS virtual table and return it
8,612
def generate(self): sampled_arr = np.zeros((self.__batch_size, self.__channel, self.__seq_len, self.__dim)) for batch in range(self.__batch_size): for i in range(len(self.__program_list)): program_key = self.__program_list[i] key = np.random.r...
Generate noise samples. Returns: `np.ndarray` of samples.
8,613
def fields(cls): if not isclass(cls): raise TypeError("Passed object must be a class.") attrs = getattr(cls, "__attrs_attrs__", None) if attrs is None: raise NotAnAttrsClassError( "{cls!r} is not an attrs-decorated class.".format(cls=cls) ) return attrs
Return the tuple of ``attrs`` attributes for a class. The tuple also allows accessing the fields by their names (see below for examples). :param type cls: Class to introspect. :raise TypeError: If *cls* is not a class. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` ...
8,614
def fix_music(file_name): .mp3 setup() if not Py3: file_name = file_name.encode() tags = File(file_name) log.log(file_name) log.log() try: artist, album, song_name, lyrics, match_bool, score = get_details_spotify( file_name) except Exception: a...
Searches for '.mp3' files in directory (optionally recursive) and checks whether they already contain album art and album name tags or not.
8,615
def wait_until_finished( self, refresh_period=DEFAULT_TASK_INSTANCE_WAIT_REFRESH_PERIOD ): return self.manager.wait_until_finished( uuid=self.uuid, refresh_period=refresh_period )
Wait until a task instance with the given UUID is finished. Args: refresh_period (int, optional): How many seconds to wait before checking the task's status. Defaults to 5 seconds. Returns: :class:`saltant.models.base_task_instance.BaseTaskInstan...
8,616
def refresh(self): logger.debug("refresh user interface") try: with self.refresh_lock: self.draw_screen() except AssertionError: logger.warning("application is not running") pass
explicitely refresh user interface; useful when changing widgets dynamically
8,617
def from_path(cls, path, suffix=): def _get_filepath(filename, warning, path=path, suffix=suffix): paths = glob.glob(os.path.join(path, filename + suffix + )) if not paths: warnings.warn(warning) return None if len(paths) > 1: ...
Convenience method to run critic2 analysis on a folder containing typical VASP output files. This method will: 1. Look for files CHGCAR, AECAR0, AECAR2, POTCAR or their gzipped counterparts. 2. If AECCAR* files are present, constructs a temporary reference file as AECCAR0...
8,618
def close_event(self, id, **kwargs): kwargs[] = True if kwargs.get(): return self.close_event_with_http_info(id, **kwargs) else: (data) = self.close_event_with_http_info(id, **kwargs) return data
Close a specific event # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.close_event(id, async_req=True) >>> result = thread.get() :param async_req bool...
8,619
def get_binary_property(value, is_bytes=False): obj = unidata.ascii_binary if is_bytes else unidata.unicode_binary if value.startswith(): negated = value[1:] value = + unidata.unicode_alias[].get(negated, negated) else: value = unidata.unicode_alias[].get(value, value) r...
Get `BINARY` property.
8,620
def outgoing_args(self, nodeid): _vars = self._vars _hcons = self._hcons args = self.args(nodeid) for arg, val in list(args.items()): if not (val in _hcons or IVARG_ROLE in refs or in refs): del args[arg] return args
Return the arguments going from *nodeid* to other predications. Valid arguments include regular variable arguments and scopal (label-selecting or HCONS) arguments. MOD/EQ links, intrinsic arguments, and constant arguments are not included. Args: nodeid: the nodeid o...
8,621
def console_get_char(con: tcod.console.Console, x: int, y: int) -> int: return lib.TCOD_console_get_char(_console(con), x, y)
Return the character at the x,y of this console. .. deprecated:: 8.4 Array access performs significantly faster than using this function. See :any:`Console.ch`.
8,622
def gtd7(Input, flags, output): mn3 = 5 zn3 = [32.5,20.0,15.0,10.0,0.0] mn2 = 4 zn2 = [72.5,55.0,45.0,32.5] zmix = 62.5 soutput = nrlmsise_output() tselec(flags); xlat=Input.g_lat; if (flags.sw[2]==0): xlat=45.0; glatf(xlat, gsurf, re); xmm = pdm[2][4]; ...
The standard model subroutine (GTD7) always computes the ‘‘thermospheric’’ mass density by explicitly summing the masses of the species in equilibrium at the thermospheric temperature T(z).
8,623
def calculate_sunrise_sunset(self, month, day, depression=0.833, is_solar_time=False): datetime = DateTime(month, day, hour=12, leap_year=self.is_leap_year) return self.calculate_sunrise_sunset_from_datetime(datetime, ...
Calculate sunrise, noon and sunset. Return: A dictionary. Keys are ("sunrise", "noon", "sunset")
8,624
def parse_pattern(pattern): if isinstance(pattern, NumberPattern): return pattern def _match_number(pattern): rv = number_re.search(pattern) if rv is None: raise ValueError( % pattern) return rv.groups() pos_pattern = pattern if in pattern: ...
Parse number format patterns
8,625
def enviar_dados_venda(self, dados_venda): resp = self._http_post(, dados_venda=dados_venda.documento()) conteudo = resp.json() return RespostaEnviarDadosVenda.analisar(conteudo.get())
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.enviar_dados_venda`. :return: Uma resposta SAT especializada em ``EnviarDadosVenda``. :rtype: satcfe.resposta.enviardadosvenda.RespostaEnviarDadosVenda
8,626
def customCompute(self, recordNum, patternNZ, classification): if not hasattr(self, "_computeFlag"): self._computeFlag = False if self._computeFlag: warnings.simplefilter(, DeprecationWarning) warnings.warn("The customCompute() method should not be " ...
Just return the inference value from one input sample. The actual learning happens in compute() -- if, and only if learning is enabled -- which is called when you run the network. .. warning:: This method is deprecated and exists only to maintain backward compatibility. This method is deprecated, a...
8,627
def clear(self): self.reg = np.zeros((self.m,), dtype=np.int8)
Reset the current HyperLogLog to empty.
8,628
def enable_cloud_integration(self, id, **kwargs): kwargs[] = True if kwargs.get(): return self.enable_cloud_integration_with_http_info(id, **kwargs) else: (data) = self.enable_cloud_integration_with_http_info(id, **kwargs) return data
Enable a specific cloud integration # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.enable_cloud_integration(id, async_req=True) >>> result = thread.get() ...
8,629
def get_paths(folder): folder = pathlib.Path(folder).resolve() files = folder.rglob("*_phase.txt") return sorted(files)
Return *_phase.txt files in `folder`
8,630
def get_cube(self, name): return Cube(self.get_engine(), name, self.get_cube_model(name))
Given a cube name, construct that cube and return it. Do not overwrite this method unless you need to.
8,631
def load_if(s): is_data_file = s.endswith() or s.endswith() return load(s) if is_data_file else loads(s)
Load either a filename, or a string representation of yml/json.
8,632
def __download_from_s3(self, key, dest_dir): log = logging.getLogger(self.cls_logger + ) filename = key.split()[-1] if filename is None: log.error(, key) return None destination = dest_dir + + filename log.info(, key, self.bucket...
Private method for downloading from S3 This private helper method takes a key and the full path to the destination directory, assumes that the args have been validated by the public caller methods, and attempts to download the specified key to the dest_dir. :param key: (str) S3...
8,633
def plot_projected_dos(self, pdos_indices=None, legend=None): import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.xaxis.set_ticks_position() ax.yaxis.set_ticks_position() ax.xaxis.set_tick_params(which=, direction=) ax.yaxis.set_tick_params(which=, dire...
Plot projected DOS Parameters ---------- pdos_indices : list of list, optional Sets of indices of atoms whose projected DOS are summed over. The indices start with 0. An example is as follwos: pdos_indices=[[0, 1], [2, 3, 4, 5]] Default is No...
8,634
def delete_terms_indexes(es, index_name: str = "terms_*"): try: es.indices.delete(index=index_name) except Exception as e: log.error(f"Could not delete all terms indices: {e}")
Delete all terms indexes
8,635
def header_little_endian(self): if not self._ptr: raise BfdException("BFD not initialized") return _bfd.get_bfd_attribute( self._ptr, BfdAttributes.HEADER_LITTLE_ENDIAN)
Return the header_little_endian attribute of the BFD file being processed.
8,636
def drop(self): if self.is_root: raise ValueError("Cannot drop root node!") parent = self.parent for child in self.children: child.parent = parent parent.children.add(child) self.children = set() parent.sequence_ids.update(self.seque...
Remove this node from the taxonomy, maintaining child subtrees by adding them to the node's parent, and moving sequences at this node to the parent. Not valid for root node.
8,637
def returner(load): serial = salt.payload.Serial(__opts__) if load[] == : load[] = prep_jid(nocache=load.get(, False)) jid_dir = salt.utils.jid.jid_dir(load[], _job_dir(), __opts__[]) if os.path.exists(os.path.join(jid_dir, )): return hn_dir = os.path.join(jid_dir, load[...
Return data to the local job cache
8,638
def merge_dicts(dict_a, dict_b): obj = {} for key, value in iteritems(dict_a): if key in dict_b: if isinstance(dict_b[key], dict): obj[key] = merge_dicts(value, dict_b.pop(key)) else: obj[key] = value for key, value in iteritems(dict_b): ...
Deep merge of two dicts
8,639
def calcSMAfromT(self, epsilon=0.7): return eq.MeanPlanetTemp(self.albedo(), self.star.T, self.star.R, epsilon, self.T).a
Calculates the semi-major axis based on planet temperature
8,640
def click_text(self, text, exact_match=False): self._element_find_by_text(text,exact_match).click()
Click text identified by ``text``. By default tries to click first text involves given ``text``, if you would like to click exactly matching text, then set ``exact_match`` to `True`. If there are multiple use of ``text`` and you do not want first one, use `locator` with `Get Web...
8,641
def xor_key(first, second, trafaret): trafaret = t.Trafaret._trafaret(trafaret) def check_(value): if (first in value) ^ (second in value): key = first if first in value else second yield first, t.catch_error(trafaret, value[key]), (key,) elif first in value and sec...
xor_key - takes `first` and `second` key names and `trafaret`. Checks if we have only `first` or only `second` in data, not both, and at least one. Then checks key value against trafaret.
8,642
def create_inputs(inspecs): ret = [] for i in inspecs: v = nn.Variable(i.shape, need_grad=i.need_grad) v.d = i.init(v.shape) ret.append(v) return ret
Create input :obj:`nnabla.Variable` from :obj:`Inspec`. Args: inspecs (:obj:`list` of :obj:`Inspec`): A list of ``Inspec``. Returns: :obj:`list` of :obj:`nnabla.Variable`: Input variables.
8,643
def and_join(strings): last = len(strings) - 1 if last == 0: return strings[0] elif last < 0: return iterator = enumerate(strings) return .join( + s if i == last else s for i, s in iterator)
Join the given ``strings`` by commas with last `' and '` conjuction. >>> and_join(['Korea', 'Japan', 'China', 'Taiwan']) 'Korea, Japan, China, and Taiwan' :param strings: a list of words to join :type string: :class:`collections.abc.Sequence` :returns: a joined string :rtype: :class:`str`, :cl...
8,644
def add_missing_price_information_message(request, item): messages.warning( request, _( ).format( item=item, em_start=, em_end=, link_start=.format( support_link=get_configuration_valu...
Add a message to the Django messages store indicating that we failed to retrieve price information about an item. :param request: The current request. :param item: The item for which price information is missing. Example: a program title, or a course.
8,645
def new_address(self, sender=None, nonce=None): if sender is not None and nonce is None: nonce = self.get_nonce(sender) new_address = self.calculate_new_address(sender, nonce) if sender is None and new_address in self: return self.new_address(sender, nonce) ...
Create a fresh 160bit address
8,646
def animate_correlation_matrix(sync_output_dynamic, animation_velocity = 75, colormap = , save_movie = None): figure = plt.figure() correlation_matrix = sync_output_dynamic.allocate_correlation_matrix(0) artist = plt.imshow(correlation_matrix, cmap = plt.get_cmap...
! @brief Shows animation of correlation matrix between oscillators during simulation. @param[in] sync_output_dynamic (sync_dynamic): Output dynamic of the Sync network. @param[in] animation_velocity (uint): Interval between frames in milliseconds. @param[in] colormap (strin...
8,647
async def wasSet(self, node, oldv): for func in self.onsets: try: await s_coro.ornot(func, node, oldv) except asyncio.CancelledError: raise except Exception: logger.exception( % (self.full,))
Fire the onset() handlers for this property. Args: node (synapse.lib.node.Node): The node whose property was set. oldv (obj): The previous value of the property.
8,648
def _make_cache_key(key_prefix): if callable(key_prefix): cache_key = key_prefix() elif in key_prefix: cache_key = key_prefix % request.path else: cache_key = key_prefix cache_key = cache_key.encode() return cache_key
Make cache key from prefix Borrowed from Flask-Cache extension
8,649
def fig_kernel_lfp_EITN_II(savefolders, params, transient=200, T=[800., 1000.], X=, lags=[20, 20], channels=[0,3,7,11,13]): zvec = np.r_[params.electrodeParams[]] alphabet = ana_params.set_PLOS_2column_fig_style(ratio=0.5) fig = plt.figure() fig.subplots_adju...
This function calculates the STA of LFP, extracts kernels and recontructs the LFP from kernels. Arguments :: transient : the time in milliseconds, after which the analysis should begin so as to avoid any starting transients X : id of presynaptic trigger population
8,650
def log_to_ganttplot(execution_history_items): import matplotlib.pyplot as plt import matplotlib.dates as dates import numpy as np d = log_to_DataFrame(execution_history_items) unique_states, idx = np.unique(d.path_by_name, return_index=True) ordered_unique_states = np.array(d.path_b...
Example how to use the DataFrame representation
8,651
def AddArg(self, arg): self.args.append(arg) if len(self.args) > self.number_of_args: raise ParseError("Too many args for this expression.") elif len(self.args) == self.number_of_args: return True return False
Adds a new arg to this expression. Args: arg: The argument to add (string). Returns: True if this arg is the last arg, False otherwise. Raises: ParseError: If there are too many args.
8,652
def get_area(self): mesh = self.mesh _, _, _, area = mesh.get_cell_dimensions() return numpy.sum(area)
Compute area as the sum of the mesh cells area values.
8,653
def find_prefix(self, iri: Union[URIRef, Literal, str]) -> Union[None, str]: iri = str(iri) max_iri_len = 0 max_prefix = None for prefix, uri in common_namespaces.items(): if uri in iri and max_iri_len < len(uri): max_prefix = prefix ...
Finds if uri is in common_namespaces Auto adds prefix if incoming iri has a uri in common_namespaces. If its not in the local library, then it will just be spit out as the iri and not saved/condensed into qualified names. The reason for the maxes is find the longest string match. This ...
8,654
def replace(self, name, newname): if not re.match("[a-zA-Z]\w*", name): return None if not re.match("[a-zA-Z]\w*", newname): return None def _replace(match): return match.group(0).replace(match.group(), newname) pattern = re.compile("(\W|^)(...
Replace all occurrences of name with newname
8,655
def columns_used(self): return list(tz.unique(tz.concatv( util.columns_in_filters(self.fit_filters), util.columns_in_filters(self.predict_filters), util.columns_in_formula(self.model_expression))))
Returns all the columns used in this model for filtering and in the model expression.
8,656
def register_on_serial_port_changed(self, callback): event_type = library.VBoxEventType.on_serial_port_changed return self.event_source.register_callback(callback, event_type)
Set the callback function to consume on serial port changed events. Callback receives a ISerialPortChangedEvent object. Returns the callback_id
8,657
def decode(s, cls=PENMANCodec, **kwargs): codec = cls(**kwargs) return codec.decode(s)
Deserialize PENMAN-serialized *s* into its Graph object Args: s: a string containing a single PENMAN-serialized graph cls: serialization codec class kwargs: keyword arguments passed to the constructor of *cls* Returns: the Graph object described by *s* Example: >>> ...
8,658
def all( self, count=500, offset=0, type=None, inactive=None, emailFilter=None, tag=None, messageID=None, fromdate=None, todate=None, ): responses = self.call_many( "GET", "/bounces/", ...
Returns many bounces. :param int count: Number of bounces to return per request. :param int offset: Number of bounces to skip. :param str type: Filter by type of bounce. :param bool inactive: Filter by emails that were deactivated by Postmark due to the bounce. :param str emailF...
8,659
def _get_menu_width(self, max_width, complete_state): return min(max_width, max(self.MIN_WIDTH, max(get_cwidth(c.display) for c in complete_state.current_completions) + 2))
Return the width of the main column.
8,660
def info_factory(name, libnames, headers, frameworks=None, section=None, classname=None): if not classname: classname = % name if not section: section = name if not frameworks: framesworks = [] class _ret(system_info): def __init__(self): ...
Create a system_info class. Parameters ---------- name : str name of the library libnames : seq list of libraries to look for headers : seq list of headers to look for classname : str name of the returned class section : st...
8,661
def add_hookcall_monitoring(self, before, after): return _tracing._TracedHookExecution(self, before, after).undo
add before/after tracing functions for all hooks and return an undo function which, when called, will remove the added tracers. ``before(hook_name, hook_impls, kwargs)`` will be called ahead of all hook calls and receive a hookcaller instance, a list of HookImpl instances and th...
8,662
def create_geoms(self, gdefs, plot): new_gdefs = [] for gdef in gdefs: gdef = gdef.create_geoms(plot) if gdef: new_gdefs.append(gdef) return new_gdefs
Add geoms to the guide definitions
8,663
def unmarshal(self, values, bind_client=None): if values is not None: return [super(EntityCollection, self).unmarshal(v, bind_client=bind_client) for v in values]
Cast the list.
8,664
def openidf(fname, idd=None, epw=None): import eppy.easyopen as easyopen return easyopen.easyopen(fname, idd=idd, epw=epw)
automatically set idd and open idf file. Uses version from idf to set correct idd It will work under the following circumstances: - the IDF file should have the VERSION object. - Needs the version of EnergyPlus installed that matches the IDF version. - Energyplus should be installed in the default...
8,665
def get_subparser(self, name): if self._subparsers_action is None: raise ValueError("%s has no subparsers defined!" % self) return self._subparsers_action.choices[name]
Convenience method to get a certain subparser Parameters ---------- name: str The name of the subparser Returns ------- FuncArgParser The subparsers corresponding to `name`
8,666
def map_value(self, value, gid): base_gid = self.base_gid_pattern.search(gid).group(1) if self.anonymyze: try: if value in self._maps[base_gid]: return self._maps[base_gid][value] else: k = (len(self._maps[base_...
Return the value for a group id, applying requested mapping. Map only groups related to a filter, ie when the basename of the group is identical to the name of a filter.
8,667
def request(self, hash_, quickkey, doc_type, page=None, output=None, size_id=None, metadata=None, request_conversion_only=None): if len(hash_) > 4: hash_ = hash_[:4] query = QueryParams({ : quickkey, : doc_type, :...
Query conversion server hash_: 4 characters of file hash quickkey: File quickkey doc_type: "i" for image, "d" for documents page: The page to convert. If page is set to 'initial', the first 10 pages of the document will be provided. (document) output: "pdf", "img",...
8,668
def queryset(self, request, queryset): if self.value() is None: return queryset.all() else: return queryset.filter(subscriptions__status=self.value()).distinct()
Return the filtered queryset based on the value provided in the query string. source: https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter
8,669
def _map_update( self, prior_mean, prior_cov, global_cov_scaled, new_observation): common = np.linalg.inv(prior_cov + global_cov_scaled) observation_mean = np.mean(new_observation, axis=1) posterior_mean = prior_cov.dot(common....
Maximum A Posterior (MAP) update of a parameter Parameters ---------- prior_mean : float or 1D array Prior mean of parameters. prior_cov : float or 1D array Prior variance of scalar parameter, or prior covariance of multivariate parameter g...
8,670
def coord2healpix(coords, frame, nside, nest=True): if coords.frame.name != frame: c = coords.transform_to(frame) else: c = coords if hasattr(c, ): phi = c.ra.rad theta = 0.5*np.pi - c.dec.rad return hp.pixelfunc.ang2pix(nside, theta, phi, nest=nest) elif ha...
Calculate HEALPix indices from an astropy SkyCoord. Assume the HEALPix system is defined on the coordinate frame ``frame``. Args: coords (:obj:`astropy.coordinates.SkyCoord`): The input coordinates. frame (:obj:`str`): The frame in which the HEALPix system is defined. nside (:obj:`int`)...
8,671
def lookup(self, host_value): try: host_object = self._host_factory(host_value) except InvalidHostError: return None result = self._get_match_and_classification( host_object ) host_item, classification = result if host_item is ...
Get a host value matching the given value. :param host_value: a value of the host of a type that can be listed by the service :returns: an instance of AddressListItem representing a matched value :raises InvalidHostError: if the argument is not a valid host string
8,672
def _hide_column(self, column): __\ column = _ensure_string_from_expression(column) new_name = self._find_valid_name( + column) self._rename(column, new_name)
Hides a column by prefixing the name with \'__\
8,673
def create_question_dialog(self, text, second_text): dialog = self.create_message_dialog( text, buttons=Gtk.ButtonsType.YES_NO, icon=Gtk.MessageType.QUESTION ) dialog.format_secondary_text(second_text) response = dialog.run() dialog.destroy() return r...
Function creates a question dialog with title text and second_text
8,674
def recv_sub(self, id_, name, params): self.api.sub(id_, name, *params)
DDP sub handler.
8,675
def vpc_peering_connection_present(name, requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, conn_name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None,...
name Name of the state requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC tp crete VPC peering connection with. This can be a VPC in ...
8,676
def list_required(self, type=None, service=None): from burlap.common import ( required_system_packages, required_python_packages, required_ruby_packages, ) service = (service or ).strip().upper() type = (type or ).lower().strip() asse...
Displays all packages required by the current role based on the documented services provided.
8,677
async def on_raw_kick(self, message): kicker, kickermeta = self._parse_user(message.source) self._sync_user(kicker, kickermeta) if len(message.params) > 2: channels, targets, reason = message.params else: channels, targets = message.params re...
KICK command.
8,678
def _derive_temporalnetwork(self, f, i, tag, params, confounds_exist, confound_files): data = load_tabular_file(f, index_col=True, header=True) fs, _ = drop_bids_suffix(f) save_name, save_dir, _ = self._save_namepaths_bids_derivatives( fs, tag, , ) if in params.key...
Funciton called by TenetoBIDS.derive_temporalnetwork for concurrent processing.
8,679
def from_settings(cls, settings): if not in settings or not in settings or \ settings[] == or settings[] == : raise Exception( "Erroneous mongodb settings, " "needs a collection and mongodb setting", settings) cx_ur...
Read Mongodb Source configuration from the provided settings
8,680
def assign(var, new_val, assign_fn=assign_slice): if isinstance(var, Tensor): var = var.operation if not isinstance(var, Variable): raise ValueError("var must be a mtf.Variable or its output Tensor.") return Assign([var], [new_val], assign_fn=assign_fn)
Assign a new value to a variable. Args: var: either a Variable operation or its output Tensor. new_val: a Tensor assign_fn: a function from (mtf.Variable, tf.Variable, tf.Tensor) -> tf.Operation Returns: an Operation Raises: ValueError: if var is not a Variable and var.operation is no...
8,681
def date_between(self, start_date=, end_date=): start_date = self._parse_date(start_date) end_date = self._parse_date(end_date) return self.date_between_dates(date_start=start_date, date_end=end_date)
Get a Date object based on a random date between two given dates. Accepts date strings that can be recognized by strtotime(). :param start_date Defaults to 30 years ago :param end_date Defaults to "today" :example Date('1999-02-02') :return Date
8,682
def heating_degree_days(T, T_base=F2K(65), truncate=True): r dd = T - T_base if truncate and dd < 0.0: dd = 0.0 return dd
r'''Calculates the heating degree days for a period of time. .. math:: \text{heating degree days} = max(T - T_{base}, 0) Parameters ---------- T : float Measured temperature; sometimes an average over a length of time is used, other times the average of the lowest and highest t...
8,683
def setHeight(self, vehID, height): self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_HEIGHT, vehID, height)
setHeight(string, double) -> None Sets the height in m for this vehicle.
8,684
def get_apex(self, lat, height=None): lat = helpers.checklat(lat, name=) if height is None: height = self.refh cos_lat_squared = np.cos(np.radians(lat))**2 apex_height = (self.RE + height) / cos_lat_squared - self.RE return apex_height
Calculate apex height Parameters ----------- lat : (float) Latitude in degrees height : (float or NoneType) Height above the surface of the earth in km or NoneType to use reference height (default=None) Returns ---------- apex...
8,685
def navigate(self): tic = datetime.now() lons40km = self._data["pos"][:, :, 1] * 1e-4 lats40km = self._data["pos"][:, :, 0] * 1e-4 try: from geotiepoints import SatelliteInterpolator except ImportError: logger.warning("Could not interpolate lon/l...
Return the longitudes and latitudes of the scene.
8,686
def app_token(vault_client, app_id, user_id): resp = vault_client.auth_app_id(app_id, user_id) if in resp and in resp[]: return resp[][] else: raise aomi.exceptions.AomiCredentials()
Returns a vault token based on the app and user id.
8,687
def delete(self, hdfs_path, recursive=False): return self.client.delete(hdfs_path, recursive=recursive)
Delete a file located at `hdfs_path`.
8,688
def linearBlend(img1, img2, overlap, backgroundColor=None): (sizex, sizey) = img1.shape[:2] overlapping = True if overlap < 0: overlapping = False overlap = -overlap alpha = np.tile(np.expand_dims(np.linspace(1, 0, overlap), 1), sizey) if len(img2.shape) == 3: ...
Stitch 2 images vertically together. Smooth the overlap area of both images with a linear fade from img1 to img2 @param img1: numpy.2dArray @param img2: numpy.2dArray of the same shape[1,2] as img1 @param overlap: number of pixels both images overlap @returns: stitched-image
8,689
def set_level(logger=None, log_level=None): log_level = logging.getLevelName(os.getenv(, )) logging.getLogger(logger).setLevel(log_level)
Set logging levels using logger names. :param logger: Name of the logger :type logger: String :param log_level: A string or integer corresponding to a Python logging level :type log_level: String :rtype: None
8,690
def get_dated_items(self): self.date_list, self.object_list, extra_context = super( EntryWeek, self).get_dated_items() self.date_list = self.get_date_list(self.object_list, ) extra_context[] = extra_context[ ] + datetime.timedelta(days=6) return self.date...
Override get_dated_items to add a useful 'week_end_day' variable in the extra context of the view.
8,691
def check_text(self, text): if to_text_string(text) == u: self.button_ok.setEnabled(False) else: self.button_ok.setEnabled(True)
Disable empty layout name possibility
8,692
def find_fields(self, classname=".*", fieldname=".*", fieldtype=".*", accessflags=".*"): for cname, c in self.classes.items(): if re.match(classname, cname): for f in c.get_fields(): z = f.get_field() if re.match(fieldname, z.get_name(...
find fields by regex :param classname: regular expression of the classname :param fieldname: regular expression of the fieldname :param fieldtype: regular expression of the fieldtype :param accessflags: regular expression of the access flags :rtype: generator of `FieldClassAnaly...
8,693
def distribution_to_markdown(distribution): text_template = if "field" in distribution: fields = "- " + \ "\n- ".join(map(field_to_markdown, distribution["field"])) else: fields = "" text = text_template.format( title=distribution["title"], description...
Genera texto en markdown a partir de los metadatos de una `distribution`. Args: distribution (dict): Diccionario con metadatos de una `distribution`. Returns: str: Texto que describe una `distribution`.
8,694
def from_rational( cls, value, to_base, precision=None, method=RoundingMethods.ROUND_DOWN ): if to_base < 2: raise BasesValueError(to_base, "to_base", "must be at least 2") if precision is not None and precision < 0: raise...
Convert rational value to a base. :param Rational value: the value to convert :param int to_base: base of result, must be at least 2 :param precision: number of digits in total or None :type precision: int or NoneType :param method: rounding method :type method: element ...
8,695
def url(**attributes): def check_url(value): validate(text, value) parsed = urlparse(value) if not parsed.netloc: raise ValueError(" is not a valid URL".format(value)) for name, schema in attributes.items(): if not _hasattr(parsed, name): ...
Parses an URL and validates its attributes.
8,696
def deleteQueue(destinationRoot, queueArk, debug=False): url = urlparse.urljoin(destinationRoot, "APP/queue/" + queueArk + "/") response, content = doWaitWebRequest(url, "DELETE") if response.getcode() != 200: raise Exception( "Error updating queue %s to url %s. Response code is %...
Delete an entry from the queue
8,697
def get_variants(self, arch=None, types=None, recursive=False): types = types or [] result = [] if "self" in types: result.append(self) for variant in six.itervalues(self.variants): if types and variant.type not in types: continue ...
Return all variants of given arch and types. Supported variant types: self - include the top-level ("self") variant as well addon variant optional
8,698
def times_update(self, factor): if factor < 0: raise ValueError("The factor must not be negative.") elif factor == 0: self.clear() else: _elements = self._elements for element in _elements: _elements[element] *= factor ...
Update each this multiset by multiplying each element's multiplicity with the given scalar factor. >>> ms = Multiset('aab') >>> ms.times_update(2) >>> sorted(ms) ['a', 'a', 'a', 'a', 'b', 'b'] You can also use the ``*=`` operator for the same effect: >>> ms = Multiset(...
8,699
def get_session_id(self): max_session = try: with open(self.log_folder + os.sep + , ) as f: for _ in f: txt = f.readline() if txt.strip() != : max_session = txt except Exception: max...
get a unique id (shortish string) to allow simple aggregation of log records from multiple sources. This id is used for the life of the running program to allow extraction from all logs. WARING - this can give duplicate sessions when 2 apps hit it at the same time.