Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
6,400
def section(node): title = if node.first_child is not None: if node.first_child.t == u: title = node.first_child.first_child.literal o = nodes.section(ids=[title], names=[title]) for n in MarkDown(node): o += n return o
A section in reStructuredText, which needs a title (the first child) This is a custom type
6,401
def data(self, column, role): return self.columns[column](self._atype, role)
Return the data for the specified column and role The column addresses one attribute of the data. :param column: the data column :type column: int :param role: the data role :type role: QtCore.Qt.ItemDataRole :returns: data depending on the role :rtype: ...
6,402
def cookies(self, url): part = urlparse(url) _domain = part.hostname cookie_dict = {} now = utc_now() for _, a in list(self.cookiejar._cookies.items()): for _, b in a.items(): for cookie in list(b.values()): ...
Return cookies that are matching the path and are still valid :param url: :return:
6,403
def get_or_create_stream(self, stream_id, try_create=True): stream_id = get_stream_id(stream_id) if stream_id in self.streams: logging.debug("found {}".format(stream_id)) return self.streams[stream_id] elif try_create: logging.debug("crea...
Helper function to get a stream or create one if it's not already defined :param stream_id: The stream id :param try_create: Whether to try to create the stream if not found :return: The stream object
6,404
def _fill_role_cache(self, principal, overwrite=False): if not self.app_state.use_cache: return None if not self._has_role_cache(principal) or overwrite: self._set_role_cache(principal, self._all_roles(principal)) return self._role_cache(principal)
Fill role cache for `principal` (User or Group), in order to avoid too many queries when checking role access with 'has_role'. Return role_cache of `principal`
6,405
def authenticate_client_id(self, client_id, request, *args, **kwargs): if client_id is None: client_id, _ = self._get_client_creds_from_request(request) log.debug(, client_id) client = request.client or self._clientgetter(client_id) if not client: log.de...
Authenticate a non-confidential client. :param client_id: Client ID of the non-confidential client :param request: The Request object passed by oauthlib
6,406
def select_template_from_string(arg): if in arg: tpl = loader.select_template( [tn.strip() for tn in arg.split()]) else: tpl = loader.get_template(arg) return tpl
Select a template from a string, which can include multiple template paths separated by commas.
6,407
def unshare_me(self, keys=None, auto_update=False, draw=None, update_other=True): auto_update = auto_update or not self.no_auto_update keys = self._set_sharing_keys(keys) to_update = [] for key in keys: fmto = getattr(self, key) try: ...
Close the sharing connection of this plotter with others This method undoes the sharing connections made by the :meth:`share` method and release this plotter again. Parameters ---------- keys: string or iterable of strings The formatoptions to unshare, or group name...
6,408
def load_plugins(self): from dyndnsc.plugins.builtin import PLUGINS for plugin in PLUGINS: self.add_plugin(plugin()) super(BuiltinPluginManager, self).load_plugins()
Load plugins from `dyndnsc.plugins.builtin`.
6,409
def get_authenticated_user(self, callback): args = dict((k, v) for k, v in request.args.items()) args["openid.mode"] = u"check_authentication" r = requests.post(self._OPENID_ENDPOINT, data=args) return self._on_authentication_verified(callback, r)
Fetches the authenticated user data upon redirect. This method should be called by the handler that receives the redirect from the authenticate_redirect() or authorize_redirect() methods.
6,410
def visit_literal_block(self, node): language = node.get(, None) is_code_node = False if not language: is_code_node = True classes = node.get() if in classes: language = classes[-1] else: ...
Check syntax of code block.
6,411
def check_model_permission(self, app, model): if self.apps_dict.get(app, False) and model in self.apps_dict[app][]: return True return False
Checks if model is listed in apps_dict Since apps_dict is derived from the app_list given by django admin, it lists only the apps and models the user can view
6,412
def mergeAllLayers(self): start = time.time() while(len(self.layers)>1): self.mergeBottomLayers() print(+str(time.time()-start)) return self.layers[0]
Merge all the layers together. :rtype: The result :py:class:`Layer` object.
6,413
def addObject(self, object, name=None): if name is None: name = len(self.objects) self.objects[name] = object
Adds an object to the Machine. Objects should be PhysicalObjects.
6,414
def eval_in_new(cls, expr, *args, **kwargs): ctx = cls(*args, **kwargs) ctx.env.rec_new(expr) return ctx.eval(expr)
:meth:`eval` an expression in a new, temporary :class:`Context`. This should be safe to use directly on user input. Args: expr (LispVal): The expression to evaluate. *args: Args for the :class:`Context` constructor. **kwargs: Kwargs for the :class:`Context` construc...
6,415
def _on_merge(self, other): self._inputs.extend(other._inputs) self._outputs.extend(other._outputs) if self._sensitivity is not None: self._sensitivity.extend(other._sensitivity) else: assert other._sensitivity is None if self._enclosed_for is n...
After merging statements update IO, sensitivity and context :attention: rank is not updated
6,416
def systematic_resample(weights): N = len(weights) positions = (random() + np.arange(N)) / N indexes = np.zeros(N, ) cumulative_sum = np.cumsum(weights) i, j = 0, 0 while i < N: if positions[i] < cumulative_sum[j]: indexes[i] = j i += 1 else: ...
Performs the systemic resampling algorithm used by particle filters. This algorithm separates the sample space into N divisions. A single random offset is used to to choose where to sample from for all divisions. This guarantees that every sample is exactly 1/N apart. Parameters ---------- wei...
6,417
def mass_enclosed_3d(self, r, kwargs_profile): kwargs = copy.deepcopy(kwargs_profile) try: del kwargs[] del kwargs[] except: pass out = integrate.quad(lambda x: self._profile.density(x, **kwargs)*4*np.pi*x**2, 0, r) return out...
computes the mass enclosed within a sphere of radius r :param r: radius (arcsec) :param kwargs_profile: keyword argument list with lens model parameters :return: 3d mass enclosed of r
6,418
async def try_sending(self,msg,timeout_secs, max_attempts): if timeout_secs is None: timeout_secs = self.timeout if max_attempts is None: max_attempts = self.retry_count attempts = 0 while attempts < max_attempts: if msg.seq_num not in self.m...
Coroutine used to send message to the device when a response or ack is needed. This coroutine will try to send up to max_attempts time the message, waiting timeout_secs for an answer. If no answer is received, it will consider that the device is no longer accessible and will unregister it. ...
6,419
def case(*, to, **kwargs): if len(kwargs) != 1: raise ValueError("expect exactly one source string argument") [(typ, string)] = kwargs.items() types = {, , , } if typ not in types: raise ValueError(f"source string keyword must be one of {types}") if to not in types: r...
Converts an identifier from one case type to another. An identifier is an ASCII string consisting of letters, digits and underscores, not starting with a digit. The supported case types are camelCase, PascalCase, snake_case, and CONSTANT_CASE, identified as camel, pascal, snake, and constant. The input ...
6,420
def next_listing(self, limit=None): if self.after: return self._reddit._limit_get(self._path, params={: self.after}, limit=limit or self._limit) elif self._has_literally_more: more = self[-1] data = dict( link_id=self[0].parent_id, ...
GETs next :class:`Listing` directed to by this :class:`Listing`. Returns :class:`Listing` object. :param limit: max number of entries to get :raise UnsupportedError: raised when trying to load more comments
6,421
def set_element(self, index, e): r if index > len(self._chain): raise IndexError("tried to access element %i, but chain has only %i" " elements" % (index, len(self._chain))) if type(index) is not int: raise ValueError( "index ...
r""" Replaces a pipeline stage. Replace an element in chain and return replaced element.
6,422
def exec_args(args, in_data=, chdir=None, shell=None, emulate_tty=False): LOG.debug(, args, chdir) assert isinstance(args, list) if emulate_tty: stderr = subprocess.STDOUT else: stderr = subprocess.PIPE proc = subprocess.Popen( args=args, stdout=subprocess.PIPE...
Run a command in a subprocess, emulating the argument handling behaviour of SSH. :param list[str]: Argument vector. :param bytes in_data: Optional standard input for the command. :param bool emulate_tty: If :data:`True`, arrange for stdout and stderr to be merged into the ...
6,423
def model_ids(self, protocol=None, groups=None): return [client.subid for client in self.models(protocol, groups)]
Returns a list of model ids for the specific query by the user. Models correspond to Clients for the XM2VTS database (At most one model per identity). Keyword Parameters: protocol Ignored. groups The groups to which the subjects attached to the models belong ('dev', 'eval', 'world') ...
6,424
def melt(expr, id_vars=None, value_vars=None, var_name=, value_name=, ignore_nan=False): id_vars = id_vars or [] id_vars = [expr._get_field(r) for r in utils.to_list(id_vars)] if not value_vars: id_names = set([c.name for c in id_vars]) value_vars = [expr._get_field(c) for c in expr.sch...
“Unpivots” a DataFrame from wide format to long format, optionally leaving identifier variables set. This function is useful to massage a DataFrame into a format where one or more columns are identifier variables (id_vars), while all other columns, considered measured variables (value_vars), are “unpivoted” ...
6,425
def _convert_agg_to_wx_image(agg, bbox): if bbox is None: image = wx.EmptyImage(int(agg.width), int(agg.height)) image.SetData(agg.tostring_rgb()) return image else: return wx.ImageFromBitmap(_WX28_clipped_agg_as_bitmap(agg, bbox))
Convert the region of the agg buffer bounded by bbox to a wx.Image. If bbox is None, the entire buffer is converted. Note: agg must be a backend_agg.RendererAgg instance.
6,426
def one(self): result, count = self._get_buffered_response() if count == 0: raise NoResults("No records found") elif count > 1: raise MultipleResults("Expected single-record result, got multiple") return result[0]
Return exactly one record or raise an exception. :return: - Dictionary containing the only item in the response content :raise: - MultipleResults: If more than one records are present in the content - NoResults: If the result is empty
6,427
def on_ok(self): def popup(thr, add_type, title): thr.start() tool_str = if add_type == : tool_str = npyscreen.notify_wait(tool_str, title=title) while thr.is_alive(): time.sleep(1) re...
Add the repository
6,428
def quantiles(self, k=5): arr = self.array() q = list(np.linspace(0, 100, k)) return np.percentile(arr.compressed(), q)
Returns an ndarray of quantile breaks.
6,429
def getattr(self, key): if key in _MethodFactoryMeta[self.classId]: return self.__dict__[key] else: return None
This method gets the attribute value of external method object.
6,430
def cfn_viz(template, parameters={}, outputs={}, out=sys.stdout): known_sg, open_sg = _analyze_sg(template[]) (graph, edges) = _extract_graph(template.get(, ), template[], known_sg, open_sg) graph[].extend(edges) _handle_terminals(template, graph, , , parameters)...
Render dot output for cloudformation.template in json format.
6,431
def users(store): user_objs = list(store.users()) total_events = store.user_events().count() for user_obj in user_objs: if user_obj.get(): user_obj[] = [store.institute(inst_id) for inst_id in user_obj.get()] else: user_obj[] = [] user_obj[] = store.user_...
Display a list of all users and which institutes they belong to.
6,432
def _inner_join(left, right, left_key_fn, right_key_fn, join_fn=union_join): joiner = defaultdict(list) for ele in right: joiner[right_key_fn(ele)].append(ele) joined = [] for ele in left: for other in joiner[left_key_fn(ele)]: joined.append(join_fn(ele, other)) retu...
Inner join using left and right key functions :param left: left iterable to be joined :param right: right iterable to be joined :param function left_key_fn: function that produces hashable value from left objects :param function right_key_fn: function that produces hashable value from right objects ...
6,433
def absent(name, force=False): ret = {: name, : {}, : False, : } if name not in __salt__[](all=True): ret[] = True ret[] = {0}\.format(name) return ret pre_state = __salt__[](name) if pre_state != and not force: ret[] = ( ...
Ensure that a container is absent name Name of the container force : False Set to ``True`` to remove the container even if it is running Usage Examples: .. code-block:: yaml mycontainer: docker_container.absent multiple_containers: docker_contain...
6,434
def is_all_field_none(self): if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._name is not None: return False if self._status is not N...
:rtype: bool
6,435
def fromSearch(text): terms = [] for term in nstr(text).split():
Generates a regular expression from 'simple' search terms. :param text | <str> :usage |>>> import projex.regex |>>> projex.regex.fromSearch('*cool*') |'^.*cool.*$' |>>> projex.projex.fromSearch('*cool*,*test*') |'^.*cool.*$|^.*t...
6,436
def delete(gandi, resource, force, background): output_keys = [, , , ] if not force: proceed = click.confirm( % resource) if not proceed: return opers = gandi.vhost.delete(resource, background) if background: for oper in opers: ...
Delete a vhost.
6,437
def dedicate(rh): rh.printSysLog("Enter changeVM.dedicate") parms = [ "-T", rh.userid, "-v", rh.parms[], "-r", rh.parms[], "-R", rh.parms[]] hideList = [] results = invokeSMCLI(rh, "Image_Device_Dedicate_DM", parm...
Dedicate device. Input: Request Handle with the following properties: function - 'CHANGEVM' subfunction - 'DEDICATEDM' userid - userid of the virtual machine parms['vaddr'] - Virtual address parms['raddr'] - Real address parms['mo...
6,438
def describe_file_extensions(self): (extensions, types) = self._call("describeFileExtensions") types = [DeviceType(a) for a in types] return (extensions, types)
Returns two arrays describing the supported file extensions. The first array contains the supported extensions and the seconds one the type each extension supports. Both have the same size. Note that some backends do not work on files, so this array may be empty. ...
6,439
def _config(key, mandatory=True, opts=None): name try: if opts: value = opts[.format(key)] else: value = __opts__[.format(key)] except KeyError: try: value = __defopts__[.format(key)] except KeyError: if mandatory: ...
Return a value for 'name' from master config file options or defaults.
6,440
def get_proficiency_search_session_for_objective_bank(self, objective_bank_id, proxy): if not objective_bank_id: raise NullArgument if not self.supports_proficiency_search(): raise Unimplemented() try: from . import sessions except ImportError...
Gets the ``OsidSession`` associated with the proficiency search service for the given objective bank. :param objective_bank_id: the ``Id`` of the ``ObjectiveBank`` :type objective_bank_id: ``osid.id.Id`` :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: a ``Profic...
6,441
def create(cls, card_id, type_=None, custom_headers=None): if custom_headers is None: custom_headers = {} request_map = { cls.FIELD_TYPE: type_ } request_map_string = converter.class_to_json(request_map) request_map_string = cls._remove_field_fo...
Generate a new CVC2 code for a card. :type user_id: int :type card_id: int :param type_: The type of generated cvc2. Can be STATIC or GENERATED. :type type_: str :type custom_headers: dict[str, str]|None :rtype: BunqResponseInt
6,442
def _op_generic_StoU_saturation(self, value, min_value, max_value): return claripy.If( claripy.SGT(value, max_value), max_value, claripy.If(claripy.SLT(value, min_value), min_value, value))
Return unsigned saturated BV from signed BV. Min and max value should be unsigned.
6,443
def error(self, session=None): self.log.error("Recording the task instance as FAILED") self.state = State.FAILED session.merge(self) session.commit()
Forces the task instance's state to FAILED in the database.
6,444
def mute(self): response = self.rendering_control.GetMute(InstanceID=1, Channel=1) return response.CurrentMute == 1
get/set the current mute state
6,445
def greenlet_admin(self): if self.config["processes"] > 1: self.log.debug( "Admin server disabled because of multiple processes.") return class Devnull(object): def write(self, *_): pass from gevent import pywsgi ...
This greenlet is used to get status information about the worker when --admin_port was given
6,446
def seed_aws_data(ctx, data): swag = create_swag_from_ctx(ctx) for k, v in json.loads(data.read()).items(): for account in v[]: data = { : .format(k), : account[], : [], : , : , ...
Seeds SWAG from a list of known AWS accounts.
6,447
def plot_raster(self, ax, xlim, x, y, pop_names=False, markersize=20., alpha=1., legend=True, marker=, rasterized=True): yoffset = [sum(self.N_X) if X== else 0 for X in self.X] for i, X in enumerate(self.X): if y[X].size > 0: a...
Plot network raster plot in subplot object. Parameters ---------- ax : `matplotlib.axes.AxesSubplot` object plot axes xlim : list List of floats. Spike time interval, e.g., [0., 1000.]. x : dict Key-value entries are populatio...
6,448
def remove_my_api_key_from_groups(self, body, **kwargs): kwargs[] = True if kwargs.get(): return self.remove_my_api_key_from_groups_with_http_info(body, **kwargs) else: (data) = self.remove_my_api_key_from_groups_with_http_info(body, **kwargs) r...
Remove API key from groups. # noqa: E501 An endpoint for removing API key from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/me/groups -d '[0162056a9a1586f30242590700000000,0117056a9a1586f30242590700000000]' -H 'content-type: application/json' -H 'Authorization: ...
6,449
def enable(self, identifier, exclude_children=False): import_path = self._identifier2import_path(identifier=identifier) if import_path in self._disabled: self._enable_path(import_path) self._disabled.remove(import_path) if not exclude_children and import_path in ...
Enable a previously disabled include type :param identifier: module or name of the include type :param exclude_children: disable the include type only for child processes, not the current process The ``identifier`` can be specified in multiple ways to disable an include type. See :py:m...
6,450
def _make_single_run(self): self._is_run = False self._new_nodes = OrderedDict() self._new_links = OrderedDict() self._is_run = True return self
Modifies the trajectory for single runs executed by the environment
6,451
def load_collection_from_url(resource, url, content_type=None): coll = create_staging_collection(resource) load_into_collection_from_url(coll, url, content_type=content_type) return coll
Creates a new collection for the registered resource and calls `load_into_collection_from_url` with it.
6,452
def close(self, force=True): if not self.closed: self.flush() self.fileobj.close() time.sleep(self.delayafterclose) if self.isalive(): if not self.terminate(force): raise PtyProcessError() self...
This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGHUP and SIGINT).
6,453
def shutdown_host(kwargs=None, call=None): if call != : raise SaltCloudSystemExit( ) host_name = kwargs.get() if kwargs and in kwargs else None force = _str_to_bool(kwargs.get()) if kwargs and in kwargs else False if not host_name: raise SaltClo...
Shut down the specified host system in this VMware environment .. note:: If the host system is not in maintenance mode, it will not be shut down. If you want to shut down the host system regardless of whether it is in maintenance mode, set ``force=True``. Default is ``force=False``. C...
6,454
def update_counter(self, key, value, **kwargs): return self._client.update_counter(self, key, value, **kwargs)
Updates the value of a counter stored in this bucket. Positive values increment the counter, negative values decrement. See :meth:`RiakClient.update_counter() <riak.client.RiakClient.update_counter>` for options. .. deprecated:: 2.1.0 (Riak 2.0) Riak 1.4-style counters are de...
6,455
def CopyFromDateTimeString(self, time_string): date_time_values = self._CopyDateTimeFromString(time_string) year = date_time_values.get(, 0) month = date_time_values.get(, 0) day_of_month = date_time_values.get(, 0) hours = date_time_values.get(, 0) minutes = date_time_values.get(, 0) ...
Copies a POSIX timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. The time of day, seconds ...
6,456
def parse(self): try: data = toml.loads(self.obj.content, _dict=OrderedDict) if data: for package_type in [, ]: if package_type in data: for name, specs in data[package_type].items(): ...
Parse a Pipfile (as seen in pipenv) :return:
6,457
def competition_submit(self, file_name, message, competition, quiet=False): if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print( + competition) if competition is None: ...
submit a competition! Parameters ========== file_name: the competition metadata file message: the submission description competition: the competition name quiet: suppress verbose output (default is False)
6,458
def _compute_asset_ids(cls, inputs, marker_output_index, outputs, asset_quantities): if len(asset_quantities) > len(outputs) - 1: return None if len(inputs) == 0: return None result = [] issuance_asset_id = cls.hash_...
Computes the asset IDs of every output in a transaction. :param list[TransactionOutput] inputs: The outputs referenced by the inputs of the transaction. :param int marker_output_index: The position of the marker output in the transaction. :param list[CTxOut] outputs: The outputs of the transact...
6,459
async def connect(self): request = stun.Message(message_method=stun.Method.ALLOCATE, message_class=stun.Class.REQUEST) request.attributes[] = self.lifetime request.attributes[] = UDP_TRANSPORT try: response, _ = await self.request(requ...
Create a TURN allocation.
6,460
def set(self, r, g, b, intensity=None): self.r = r self.g = g self.b = b if intensity: self.intensity = intensity
Set the R/G/B and optionally intensity in one call
6,461
def json_worker(self, mask, cache_id=None, cache_method="string", cache_section="www"): use_cache = cache_id is not None def wrapper(fun): lock = threading.RLock() tasks = {} cargo = {} cargo_cleaner = [None] def ...
A function annotation that adds a worker request. A worker request is a POST request that is computed asynchronously. That is, the actual task is performed in a different thread and the network request returns immediately. The client side uses polling to fetch the result and ...
6,462
def get_bits_from_int(val_int, val_size=16): bits = [None] * val_size for i, item in enumerate(bits): bits[i] = bool((val_int >> i) & 0x01) return bits
Get the list of bits of val_int integer (default size is 16 bits) Return bits list, least significant bit first. Use list.reverse() if need. :param val_int: integer value :type val_int: int :param val_size: bit size of integer (word = 16, long = 32) (optional) :type val...
6,463
def generate_session_key(hmac_secret=b): session_key = random_bytes(32) encrypted_session_key = PKCS1_OAEP.new(UniverseKey.Public, SHA1)\ .encrypt(session_key + hmac_secret) return (session_key, encrypted_session_key)
:param hmac_secret: optional HMAC :type hmac_secret: :class:`bytes` :return: (session_key, encrypted_session_key) tuple :rtype: :class:`tuple`
6,464
def reconcile_extend(self, high): errors = [] if not in high: return high, errors ext = high.pop() for ext_chunk in ext: for name, body in six.iteritems(ext_chunk): if name not in high: state_type = next( ...
Pull the extend data and add it to the respective high data
6,465
async def container_size( self, container_len=None, container_type=None, params=None ): if hasattr(container_type, "serialize_archive"): raise ValueError("not supported") if self.writing: return await self._dump_container_size( self.iobj,...
Container size :param container_len: :param container_type: :param params: :return:
6,466
def get_flair_choices(self, subreddit, link=None): data = {: six.text_type(subreddit), : link} return self.request_json(self.config[], data=data)
Return available flair choices and current flair. :param link: If link is given, return the flair options for this submission. Not normally given directly, but instead set by calling the flair_choices method for Submission objects. Use the default for the session's user. ...
6,467
def reorientate(self, override_exif=True): orientation = self.get_orientation() if orientation is None: return if orientation == 2: self.flip_horizontally() elif orientation == 3: self.rotate(180) elif orientation == 4: s...
Rotates the image in the buffer so that it is oriented correctly. If override_exif is True (default) then the metadata orientation is adjusted as well. :param override_exif: If the metadata should be adjusted as well. :type override_exif: Boolean
6,468
def get_pool_context(self): context = {self.current.lane_id: self.current.role, : self.current.role} for lane_id, role_id in self.current.pool.items(): if role_id: context[lane_id] = lazy_object_proxy.Proxy( lambda: self.role_model(super_...
Builds context for the WF pool. Returns: Context dict.
6,469
def zpopmax(self, name, count=None): args = (count is not None) and [count] or [] options = { : True } return self.execute_command(, name, *args, **options)
Remove and return up to ``count`` members with the highest scores from the sorted set ``name``.
6,470
def perceptual_weighting(S, frequencies, **kwargs): A1A1A1cqt_hzLog CQT power%+2.0f dBcqt_hzA1timePerceptually weighted log CQT%+2.0f dB offset = time_frequency.A_weighting(frequencies).reshape((-1, 1)) return offset + power_to_db(S, **kwargs)
Perceptual weighting of a power spectrogram: `S_p[f] = A_weighting(f) + 10*log(S[f] / ref)` Parameters ---------- S : np.ndarray [shape=(d, t)] Power spectrogram frequencies : np.ndarray [shape=(d,)] Center frequency for each row of `S` kwargs : additional keyword arguments ...
6,471
def visit_Assign(self, node): self.generic_visit(node) if node.value not in self.fixed_size_list: return node node.value = self.convert(node.value) return node
Replace list calls by static_list calls when possible >>> import gast as ast >>> from pythran import passmanager, backend >>> node = ast.parse("def foo(n): x = __builtin__.list(n); x[0] = 0; return __builtin__.tuple(x)") >>> pm = passmanager.PassManager("test") >>> _, node = pm....
6,472
def start(self, priority_queue, resource_queue): self._kill_event = threading.Event() self._priority_queue_pull_thread = threading.Thread(target=self._migrate_logs_to_internal, args=( ...
maintain a set to track the tasks that are already INSERTED into database to prevent race condition that the first resource message (indicate 'running' state) arrives before the first task message. If race condition happens, add to left_messages and operate them later
6,473
def params_size(event_size, num_components, name=None): with tf.compat.v1.name_scope( name, , [event_size, num_components]): return MixtureSameFamily.params_size( num_components, OneHotCategorical.params_size(event_size, name=name), name=name)
The number of `params` needed to create a single distribution.
6,474
def create_table(self, names=None): scan_shape = (1,) for src in self._srcs: scan_shape = max(scan_shape, src[].shape) tab = create_source_table(scan_shape) for s in self._srcs: if names is not None and s.name not in names: continue ...
Create an astropy Table object with the contents of the ROI model.
6,475
def get_preferred_path(self): if self.path in ("", "/"): return "/" if self.is_collection and not self.path.endswith("/"): return self.path + "/" return self.path
Return preferred mapping for a resource mapping. Different URLs may map to the same resource, e.g.: '/a/b' == '/A/b' == '/a/b/' get_preferred_path() returns the same value for all these variants, e.g.: '/a/b/' (assuming resource names considered case insensitive) @par...
6,476
def _prepare_facet_field_spies(self, facets): spies = [] for facet in facets: slot = self.column[facet] spy = xapian.ValueCountMatchSpy(slot) spy.slot = slot spies.append(spy) return spies
Returns a list of spies based on the facets used to count frequencies.
6,477
def java_potential_term(mesh, instructions): s description, not a series of descriptions. ' faces = to_java_ints(mesh.indexed_faces) edges = to_java_ints(mesh.indexed_edges) coords = to_java_doubles(mesh.coordinates) return _parse_field_arguments([instructions], faces, edges, coords)
java_potential_term(mesh, instructions) yields a Java object that implements the potential field described in the given list of instructions. Generally, this should not be invoked directly and should only be called by mesh_register. Note: this expects a single term's description, not a series of descr...
6,478
def scan(self, pattern): if self.eos: raise EndOfText() if pattern not in self._re_cache: self._re_cache[pattern] = re.compile(pattern, self.flags) self.last = self.match m = self._re_cache[pattern].match(self.data, self.pos) if m is None: ...
Scan the text for the given pattern and update pos/match and related fields. The return value is a boolen that indicates if the pattern matched. The matched value is stored on the instance as ``match``, the last value is stored as ``last``. ``start_pos`` is the position of the po...
6,479
def use_dev_config_dir(use_dev_config_dir=USE_DEV_CONFIG_DIR): if use_dev_config_dir is not None: if use_dev_config_dir.lower() in {, }: use_dev_config_dir = False else: use_dev_config_dir = DEV or not is_stable_version(__version__) return use_dev_config_dir
Return whether the dev configuration directory should used.
6,480
def get_sequence_rules_for_assessment(self, assessment_id): def get_all_children_part_ids(part): child_ids = [] if part.has_children(): child_ids = list(part.get_child_assessment_part_ids()) for child in part.get_child_assessment_parts():...
Gets a ``SequenceRuleList`` for an entire assessment. arg: assessment_id (osid.id.Id): an assessment ``Id`` return: (osid.assessment.authoring.SequenceRuleList) - the returned ``SequenceRule`` list raise: NullArgument - ``assessment_id`` is ``null`` raise: Operation...
6,481
def configure(self, user_dn, group_dn, url=, case_sensitive_names=False, starttls=False, tls_min_version=, tls_max_version=, insecure_tls=False, certificate=None, bind_dn=None, bind_pass=None, user_attr=, discover_dn=False, deny_null_bind=True, upn_domain=None, grou...
Configure the LDAP auth method. Supported methods: POST: /auth/{mount_point}/config. Produces: 204 (empty body) :param user_dn: Base DN under which to perform user search. Example: ou=Users,dc=example,dc=com :type user_dn: str | unicode :param group_dn: LDAP search base to ...
6,482
def allowed_domains(self): if self._allowed_domains is None: uri = "/loadbalancers/alloweddomains" resp, body = self.method_get(uri) dom_list = body["allowedDomains"] self._allowed_domains = [itm["allowedDomain"]["name"] for itm in dom...
This property lists the allowed domains for a load balancer. The allowed domains are restrictions set for the allowed domain names used for adding load balancer nodes. In order to submit a domain name as an address for the load balancer node to add, the user must verify that the domain ...
6,483
def rate_limit(self, name, limit=5, per=60, debug=False): return RateLimit(self, name, limit, per, debug)
Rate limit implementation. Allows up to `limit` of events every `per` seconds. See :ref:`rate-limit` for more information.
6,484
def Issue(self, state, results): result = CheckResult() if results and all(isinstance(r, CheckResult) for r in results): result.ExtendAnomalies(results) else: result.anomaly = [ rdf_anomaly.Anomaly( type=anomaly_pb2.Anomaly.AnomalyType.Name( ...
Collect anomalous findings into a CheckResult. Comparisons with anomalous conditions collect anomalies into a single CheckResult message. The contents of the result varies depending on whether the method making the comparison is a Check, Method or Probe. - Probes evaluate raw host data and generate Ano...
6,485
def print_runs(query): if query is None: return for tup in query: print(("{0} @ {1} - {2} id: {3} group: {4}".format( tup.end, tup.experiment_name, tup.project_name, tup.experiment_group, tup.run_group)))
Print all rows in this result query.
6,486
def render_source(self): return SOURCE_TABLE_HTML % u.join(line.render() for line in self.get_annotated_lines())
Render the sourcecode.
6,487
def get_accessible_time(self, plugin_override=True): vals = self._hook_manager.call_hook(, course=self.get_course(), task=self, default=self._accessible) return vals[0] if len(vals) and plugin_override else self._accessible
Get the accessible time of this task
6,488
def _try_get_state_scope(name, mark_name_scope_used=True): tmp_scope_name = tf_v1.get_variable_scope().name if tmp_scope_name: tmp_scope_name += "/" with tf.name_scope(tmp_scope_name): with tf_v1.variable_scope( None, default_name=name, auxiliary_name_scope=False) as vs: abs_state_sc...
Returns a fresh variable/name scope for a module's state. In order to import a module into a given scope without major complications we require the scope to be empty. This function deals with deciding an unused scope where to define the module state. This is non trivial in cases where name_scope and variable_s...
6,489
def tmp_configuration_copy(chmod=0o600): cfg_dict = conf.as_dict(display_sensitive=True, raw=True) temp_fd, cfg_path = mkstemp() with os.fdopen(temp_fd, ) as temp_file: if chmod is not None: os.fchmod(temp_fd, chmod) json.dump(cfg_dict, temp_file) return cfg_path
Returns a path for a temporary file including a full copy of the configuration settings. :return: a path to a temporary file
6,490
def add_advisor(self, name, ids=None, degree_type=None, record=None, curated=False): new_advisor = {} new_advisor[] = normalize_name(name) if ids: new_advisor[] = force_list(ids) if degree_type: new_advisor[] = degree_type if record: n...
Add an advisor. Args: :param name: full name of the advisor. :type name: string :param ids: list with the IDs of the advisor. :type ids: list :param degree_type: one of the allowed types of degree the advisor helped with. :type degree_ty...
6,491
def parse_metadata(section): metadata = {} metadata_lines = section.split() for line in metadata_lines: colon_index = line.find() if colon_index != -1: key = line[:colon_index].strip() val = line[colon_index + 1:].strip() metadata[key] = val return metadata
Given the first part of a slide, returns metadata associated with it.
6,492
def take_while(self, predicate): if self.closed(): raise ValueError("Attempt to call take_while() on a closed " "Queryable.") if not is_callable(predicate): raise TypeError("take_while() parameter predicate={0} is " ...
Returns elements from the start while the predicate is True. Note: This method uses deferred execution. Args: predicate: A function returning True or False with which elements will be tested. Returns: A Queryable over the elements from the beginning of ...
6,493
def _ignore_path(cls, path, ignore_list=None, white_list=None): ignore_list = ignore_list or [] white_list = white_list or [] return (cls._matches_patterns(path, ignore_list) and not cls._matches_patterns(path, white_list))
Returns a whether a path should be ignored or not.
6,494
def split_cl_function(cl_str): class Semantics: def __init__(self): self._return_type = self._function_name = self._parameter_list = [] self._cl_body = def result(self, ast): return self._return_type, self._function_name, self._pa...
Split an CL function into a return type, function name, parameters list and the body. Args: cl_str (str): the CL code to parse and plit into components Returns: tuple: string elements for the return type, function name, parameter list and the body
6,495
def ListField(field): original_get_from_instance = field.get_from_instance def get_from_instance(self, instance): for value in original_get_from_instance(instance): yield value field.get_from_instance = MethodType(get_from_instance, field) return field
This wraps a field so that when get_from_instance is called, the field's values are iterated over
6,496
def _get_from_c_api(): from ctypes import pythonapi, py_object PyDictProxy_New = pythonapi.PyDictProxy_New PyDictProxy_New.argtypes = (py_object,) PyDictProxy_New.restype = py_object class dictproxy(object): def __new__(cls, d): if n...
dictproxy does exist in previous versions, but the Python constructor refuses to create new objects, so we must be underhanded and sneaky with ctypes.
6,497
def group_variant(self): v_mapping = {symdata.index: symdata.variant for symdata in self._symboldata_list} return v_mapping[self.group_num] or ""
Current group variant (get-only). :getter: Returns current group variant :type: str
6,498
def savetofile(self, filelike, sortkey = True): filelike.writelines(k + + repr(v) + for k,v in self.config_items(sortkey))
Save configurations to a file-like object which supports `writelines`
6,499
def _prep_vcf(in_file, region_bed, sample, new_sample, stats, work_dir, data): in_file = vcfutils.bgzip_and_index(in_file, data, remove_orig=False) out_file = os.path.join(work_dir, "%s-vprep.vcf.gz" % utils.splitext_plus(os.path.basename(in_file))[0]) if not utils.file_uptodate(out_file, in_file): ...
Prepare VCF for SV validation: - Subset to passing variants - Subset to genotyped variants -- removes reference and no calls - Selects and names samples - Subset to callable regions - Remove larger annotations which slow down VCF processing