positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def main(): """Main entry point for script.""" parser = argparse.ArgumentParser( description='Auto-generate a RESTful API service ' 'from an existing database.' ) parser.add_argument( 'URI', help='Database URI in the format ' 'postgresql+psycopg2://user:p...
Main entry point for script.
def __parse_direct_mention(self, message_text): """ Finds a direct mention (a mention that is at the beginning) in message text and returns the user ID which was mentioned. If there is no direct mention, returns None """ matches = re.search(MENTION_REGEX, message_text) ...
Finds a direct mention (a mention that is at the beginning) in message text and returns the user ID which was mentioned. If there is no direct mention, returns None
def create_activity(self, activity_name, desc=None, started_on=None, ended_on=None): """ Send POST to /activities creating a new activity with the specified name and desc. Raises DataServiceError on error. :param activity_name: str name of the activity :param desc: str descriptio...
Send POST to /activities creating a new activity with the specified name and desc. Raises DataServiceError on error. :param activity_name: str name of the activity :param desc: str description of the activity (optional) :param started_on: str datetime when the activity started (optional)...
def next_turn(self, *args): """Advance time by one turn, if it's not blocked. Block time by setting ``engine.universal['block'] = True``""" if self.tmp_block: return eng = self.app.engine dial = self.dialoglayout if eng.universal.get('block'): Log...
Advance time by one turn, if it's not blocked. Block time by setting ``engine.universal['block'] = True``
def get_control(self, right=None, left=None): """ Returns joint velocities to control the robot after the target end effector positions and orientations are updated from arguments @left and @right. If no arguments are provided, joint velocities will be computed based on the prev...
Returns joint velocities to control the robot after the target end effector positions and orientations are updated from arguments @left and @right. If no arguments are provided, joint velocities will be computed based on the previously recorded target. Args: left (dict): A ...
def intersperse(lis, value): """Put value between each existing item in list. Parameters ---------- lis : list List to intersperse. value : object Value to insert. Returns ------- list interspersed list """ out = [value] * (len(lis) * 2 - 1) out[0::2...
Put value between each existing item in list. Parameters ---------- lis : list List to intersperse. value : object Value to insert. Returns ------- list interspersed list
def start(cls, ev=None): """ Start the analysis. """ ViewController.log_view.add("Beginning AnalysisRunner request..") # reset all inputs ViewController.reset_bars() # read the urlbox url = ViewController.url.strip() # make sure, that `url` was ...
Start the analysis.
def _policy_loss( self, old_policy, policy, action, advantage, length): """Compute the policy loss composed of multiple components. 1. The policy gradient loss is importance sampled from the data-collecting policy at the beginning of training. 2. The second term is a KL penalty between the pol...
Compute the policy loss composed of multiple components. 1. The policy gradient loss is importance sampled from the data-collecting policy at the beginning of training. 2. The second term is a KL penalty between the policy at the beginning of training and the current policy. 3. Additionally, ...
def peekuntil(self, token, size=0): """ Peeks for token into the FIFO. Performs the same function as readuntil() without removing data from the FIFO. See readuntil() for further information. """ self.__append() i = self.buf.find(token, self.pos) if i < 0...
Peeks for token into the FIFO. Performs the same function as readuntil() without removing data from the FIFO. See readuntil() for further information.
def _create(self): """Creates a new and empty database.""" from .tools import makedirs_safe # create directory for sql database makedirs_safe(os.path.dirname(self._database)) # create all the tables Base.metadata.create_all(self._engine) logger.debug("Created new empty database '%s'" % sel...
Creates a new and empty database.
def kwargs(self): """Returns a dict of the kwargs for this Struct which were not interpreted by the baseclass. This excludes fields like `extends`, `merges`, and `abstract`, which are consumed by SerializableFactory.create and Validatable.validate. """ return {k: v for k, v in self._kwargs.items() ...
Returns a dict of the kwargs for this Struct which were not interpreted by the baseclass. This excludes fields like `extends`, `merges`, and `abstract`, which are consumed by SerializableFactory.create and Validatable.validate.
def _propagate(self, path, val): """ Propagate the value up to the root node. """ if val == '_DELETE': if path in self.data: del self.data[path] else: items = [(key, v) for key, v in self.data.items() if not...
Propagate the value up to the root node.
def _set_ipv6_address(self, v, load=False): """ Setter method for ipv6_address, mapped from YANG variable /interface/fortygigabitethernet/ipv6/ipv6_config/address/ipv6_address (list) If this variable is read-only (config: false) in the source YANG file, then _set_ipv6_address is considered as a private ...
Setter method for ipv6_address, mapped from YANG variable /interface/fortygigabitethernet/ipv6/ipv6_config/address/ipv6_address (list) If this variable is read-only (config: false) in the source YANG file, then _set_ipv6_address is considered as a private method. Backends looking to populate this variable s...
def setObsoletedBy(self, pid, obsoletedByPid, serialVersion, vendorSpecific=None): """See Also: setObsoletedByResponse() Args: pid: obsoletedByPid: serialVersion: vendorSpecific: Returns: """ response = self.setObsoletedByResponse( ...
See Also: setObsoletedByResponse() Args: pid: obsoletedByPid: serialVersion: vendorSpecific: Returns:
def entrance_beveled(Di, l, angle, method='Rennels'): r'''Returns loss coefficient for a beveled or chamfered entrance to a pipe flush with the wall of a reservoir. This calculation has two methods available. The 'Rennels' and 'Idelchik' methods have similar trends, but the 'Rennels' formulatio...
r'''Returns loss coefficient for a beveled or chamfered entrance to a pipe flush with the wall of a reservoir. This calculation has two methods available. The 'Rennels' and 'Idelchik' methods have similar trends, but the 'Rennels' formulation is centered around a straight loss coefficient of 0.57, ...
def get_waveform_end_frequency(template=None, **kwargs): """Return the stop frequency of a template """ input_params = props(template,**kwargs) approximant = kwargs['approximant'] if approximant in _filter_ends: return _filter_ends[approximant](**input_params) else: return None
Return the stop frequency of a template
def logstream_policy(): """Policy needed for logspout -> kinesis log streaming.""" p = Policy( Statement=[ Statement( Effect=Allow, Resource=["*"], Action=[ kinesis.CreateStream, kinesis.DescribeStream, A...
Policy needed for logspout -> kinesis log streaming.
def qteAbort(self, msgObj): """ Restore the original cursor position because the user hit abort. """ self.qteWidget.setCursorPosition(*self.cursorPosOrig) self.qteMain.qtesigAbort.disconnect(self.qteAbort)
Restore the original cursor position because the user hit abort.
def separate(polylines, f_mx_dist=2, mn_group_len=4): """ split polylines wherever crinkles are found """ s = [] for n in range(len(polylines) - 1, -1, -1): c = polylines[n] separated = False start = 0 for m in range(mn_group_len, len(c) - 1): if m - sta...
split polylines wherever crinkles are found
def mac2eui64(mac, prefix=None): ''' Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address ''' # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r'[.:-]', '', mac).lower() eui64 = eui64[0:6] + 'fffe' + eui64[6:] eui64 = hex(int(eui64[0:...
Convert a MAC address to a EUI64 identifier or, with prefix provided, a full IPv6 address
def get_source_files(target, build_context) -> list: """Return list of source files for `target`.""" all_sources = list(target.props.sources) for proto_dep_name in target.props.protos: proto_dep = build_context.targets[proto_dep_name] all_sources.extend(proto_dep.artifacts.get(AT.gen_cc).key...
Return list of source files for `target`.
def registerWebAdaptor(self, webAdaptorURL, machineName, machineIP, isAdminEnabled, description, httpPort, httpsPort): """ You can use this operation to register the ArcGIS Web Adaptor from your ArcGIS Server. By registering the Web Adaptor with the server, yo...
You can use this operation to register the ArcGIS Web Adaptor from your ArcGIS Server. By registering the Web Adaptor with the server, you are telling the server to trust requests (including security credentials) that have been submitted through this Web Adaptor. Inputs: w...
def active_link(context, viewnames, css_class=None, strict=None, *args, **kwargs): """ Renders the given CSS class if the request path matches the path of the view. :param context: The context where the tag was called. Used to access the request object. :param viewnames: The name of the view or views se...
Renders the given CSS class if the request path matches the path of the view. :param context: The context where the tag was called. Used to access the request object. :param viewnames: The name of the view or views separated by || (include namespaces if any). :param css_class: The CSS class to render. :...
def files_rm(self, path, recursive=False, **kwargs): """Removes a file from the MFS. .. code-block:: python >>> c.files_rm("/bla/file") b'' Parameters ---------- path : str Filepath within the MFS recursive : bool Recursi...
Removes a file from the MFS. .. code-block:: python >>> c.files_rm("/bla/file") b'' Parameters ---------- path : str Filepath within the MFS recursive : bool Recursively remove directories?
def next(self): """ (internal) returns the next result from the ``itertools.tee`` object for the wrapped ``Piper`` instance or re-raises an ``Exception``. """ # do not acquire lock if NuMap is not finished. if self.finished: raise StopIteration ...
(internal) returns the next result from the ``itertools.tee`` object for the wrapped ``Piper`` instance or re-raises an ``Exception``.
def _get_src(tree_base, source, saltenv='base'): ''' Get the named sources and place them into the tree_base ''' parsed = _urlparse(source) sbase = os.path.basename(source) dest = os.path.join(tree_base, sbase) if parsed.scheme: __salt__['cp.get_url'](source, dest, saltenv=saltenv) ...
Get the named sources and place them into the tree_base
def initialize_logging(args): """Configure the root logger with some sensible defaults.""" log_handler = logging.StreamHandler() log_formatter = logging.Formatter( "%(levelname)s %(asctime)s %(name)s:%(lineno)04d - %(message)s") log_handler.setFormatter(log_formatter) root_logger = logging....
Configure the root logger with some sensible defaults.
def _add_partial_key_entity_pb(self): """Adds a new mutation for an entity with a partial key. :rtype: :class:`.entity_pb2.Entity` :returns: The newly created entity protobuf that will be updated and sent with a commit. """ new_mutation = _datastore_pb2.Mutatio...
Adds a new mutation for an entity with a partial key. :rtype: :class:`.entity_pb2.Entity` :returns: The newly created entity protobuf that will be updated and sent with a commit.
def parse_map_Ks(self): """Specular color map""" Kd = os.path.join(self.dir, " ".join(self.values[1:])) self.this_material.set_texture_specular_color(Kd)
Specular color map
def grab_selenium_driver(driver_name=None): """ pip install selenium -U """ from selenium import webdriver if driver_name is None: driver_name = 'firefox' if driver_name.lower() == 'chrome': grab_selenium_chromedriver() return webdriver.Chrome() elif driver_name.lower...
pip install selenium -U
def _set_security_profile(self, v, load=False): """ Setter method for security_profile, mapped from YANG variable /port_profile/security_profile (container) If this variable is read-only (config: false) in the source YANG file, then _set_security_profile is considered as a private method. Backends l...
Setter method for security_profile, mapped from YANG variable /port_profile/security_profile (container) If this variable is read-only (config: false) in the source YANG file, then _set_security_profile is considered as a private method. Backends looking to populate this variable should do so via callin...
def iterkeys(self, key_type=None, return_all_keys=False): """ Returns an iterator over the dictionary's keys. @param key_type if specified, iterator for a dictionary of this type will be used. Otherwise (if not specified) tuples containing all (multiple) keys ...
Returns an iterator over the dictionary's keys. @param key_type if specified, iterator for a dictionary of this type will be used. Otherwise (if not specified) tuples containing all (multiple) keys for this dictionary will be generated. @param return_al...
def encode(self, data: mx.sym.Symbol, data_length: Optional[mx.sym.Symbol], seq_len: int) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, int]: """ Encodes data given sequence lengths of individual examples and maximum sequence length. :param data: Input data...
Encodes data given sequence lengths of individual examples and maximum sequence length. :param data: Input data. :param data_length: Vector with sequence lengths. :param seq_len: Maximum sequence length. :return: Encoded versions of input data (data, data_length, seq_len).
def errors(self): """ Get the errors of the tag. If invalid then the list will consist of errors containing each a code and message explaining the error. Each error also refers to the respective (sub)tag(s). :return: list of errors of the tag. If the tag is valid, it returns an ...
Get the errors of the tag. If invalid then the list will consist of errors containing each a code and message explaining the error. Each error also refers to the respective (sub)tag(s). :return: list of errors of the tag. If the tag is valid, it returns an empty list.
def createHeadingPointer(self): '''Creates the pointer for the current heading.''' self.headingTri = patches.RegularPolygon((0.0,0.80),3,0.05,color='k',zorder=4) self.axes.add_patch(self.headingTri) self.headingText = self.axes.text(0.0,0.675,'0',color='k',size=self.fontSize,horizontalal...
Creates the pointer for the current heading.
def register_multi_flags_validator(flag_names, multi_flags_checker, message='Flags validation failed', flag_values=FLAGS): """Adds a constraint to multiple flags. The constraint is validated when flags are init...
Adds a constraint to multiple flags. The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value. Args: flag_names: [str], a list of the flag names to be checked. multi_flags_checker: callable, a function to validate the flag. input - dict...
def hid_device_path_exists(device_path, guid = None): """Test if required device_path is still valid (HID device connected to host) """ # expecing HID devices if not guid: guid = winapi.GetHidGuid() info_data = winapi.SP_DEVINFO_DATA() info_data.cb_size = sizeof(win...
Test if required device_path is still valid (HID device connected to host)
def pick_cert_for_twisted(netloc, possible): """ Pick the right client key/certificate to use for the given server and return it in the form Twisted wants. :param NetLocation netloc: The location of the server to consider. :param dict[TLSCredentials] possible: The available credentials from which ...
Pick the right client key/certificate to use for the given server and return it in the form Twisted wants. :param NetLocation netloc: The location of the server to consider. :param dict[TLSCredentials] possible: The available credentials from which to choose. :return: A two-tuple. If no crede...
def get_data(): """Retrieve static data from the game.""" run_config = run_configs.get() with run_config.start(want_rgb=False) as controller: m = maps.get("Sequencer") # Arbitrary ladder map. create = sc_pb.RequestCreateGame(local_map=sc_pb.LocalMap( map_path=m.path, map_data=m.data(run_config))...
Retrieve static data from the game.
def identity_to_string(identity_dict): """Dump Identity dictionary into its string representation.""" result = [] if identity_dict.get('proto'): result.append(identity_dict['proto'] + '://') if identity_dict.get('user'): result.append(identity_dict['user'] + '@') result.append(identi...
Dump Identity dictionary into its string representation.
def _state_stopped(self): """ The service is not running. This is the initial state, and the state after L{stopService} was called. To get out of this state, call L{startService}. If there is a current connection, we disconnect. """ if self._reconnectDelayedCall:...
The service is not running. This is the initial state, and the state after L{stopService} was called. To get out of this state, call L{startService}. If there is a current connection, we disconnect.
def log(args, number=None, oneline=False, quiet=False): """Run a "git log ..." command, and return stdout args is anything which can be added after a normal "git log ..." it can be blank number, if true-ish, will be added as a "-n" option oneline, if true-ish, will add the "--oneline" option ...
Run a "git log ..." command, and return stdout args is anything which can be added after a normal "git log ..." it can be blank number, if true-ish, will be added as a "-n" option oneline, if true-ish, will add the "--oneline" option
def update(self, update_cameras=False, update_base_station=False): """Refresh object.""" self._authenticate() # update attributes in all cameras to avoid duped queries if update_cameras: url = DEVICES_ENDPOINT response = self.query(url) if not respons...
Refresh object.
def end_of_month(val): """ Return a new datetime.datetime object with values that represent a end of a month. :param val: Date to ... :type val: datetime.datetime | datetime.date :rtype: datetime.datetime """ if type(val) == date: val = datetime.fromordinal(val.toordinal()) i...
Return a new datetime.datetime object with values that represent a end of a month. :param val: Date to ... :type val: datetime.datetime | datetime.date :rtype: datetime.datetime
def set(self, mode, disable): """ create logger object, enable or disable logging """ global logger try: if logger: if disable: logger.disabled = True else: if mode in ('STREAM', 'FILE'): logger = log...
create logger object, enable or disable logging
def _init_metadata(self): """stub""" self._files_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'files'), 'element_label': 'Files', 'instructions': 'ente...
stub
def computePCsPlink(plink_path,k,out_dir,bfile,ffile): """ computing the covariance matrix via plink """ print("Using plink to compute principal components") cmd = '%s --bfile %s --pca %d '%(plink_path,bfile,k) cmd+= '--out %s'%(os.path.join(out_dir,'plink')) subprocess.call(cmd,shell=True) ...
computing the covariance matrix via plink
def hpforest(self, data: ['SASdata', str] = None, freq: str = None, id: str = None, input: [str, list, dict] = None, save: str = None, score: [str, bool, 'SASdata'] = True, target: [str, list, dict] = None, ...
Python method to call the HPFOREST procedure Documentation link: https://support.sas.com/documentation/solutions/miner/emhp/14.1/emhpprcref.pdf :param data: SASdata object or string. This parameter is required. :parm freq: The freq variable can only be a string type. :parm id: ...
def _thumbnail_s3(self, original_filename, thumb_filename, thumb_size, thumb_url, bucket_name, crop=None, bg=None, quality=85): """Finds or creates a thumbnail for the specified image on Amazon S3.""" scheme = self.app.config.get('THUMBNAIL_S3_USE_HTTPS') and...
Finds or creates a thumbnail for the specified image on Amazon S3.
def remove(self, builder, model): """ Remove the scope from a given query builder. :param builder: The query builder :type builder: eloquent.orm.builder.Builder :param model: The model :type model: eloquent.orm.Model """ column = model.get_qualified_dele...
Remove the scope from a given query builder. :param builder: The query builder :type builder: eloquent.orm.builder.Builder :param model: The model :type model: eloquent.orm.Model
def replace(self, left=None, lower=None, upper=None, right=None, ignore_inf=True): """ Create a new interval based on the current one and the provided values. Callable can be passed instead of values. In that case, it is called with the current corresponding value except if ignore_inf i...
Create a new interval based on the current one and the provided values. Callable can be passed instead of values. In that case, it is called with the current corresponding value except if ignore_inf if set (default) and the corresponding bound is an infinity. :param left: (a function o...
def addPharLapPaths(env): """This function adds the path to the Phar Lap binaries, includes, and libraries, if they are not already there.""" ph_path = getPharLapPath() try: env_dict = env['ENV'] except KeyError: env_dict = {} env['ENV'] = env_dict SCons.Util.AddPathIfNo...
This function adds the path to the Phar Lap binaries, includes, and libraries, if they are not already there.
def generalize_sql(sql): """ Removes most variables from an SQL query and replaces them with X or N for numbers. Based on Mediawiki's DatabaseBase::generalizeSQL :type sql str|None :rtype: str """ if sql is None: return None # multiple spaces sql = re.sub(r'\s{2,}', ' ', s...
Removes most variables from an SQL query and replaces them with X or N for numbers. Based on Mediawiki's DatabaseBase::generalizeSQL :type sql str|None :rtype: str
def analyze(self, handle, filename): """Submit a file for analysis. :type handle: File handle :param handle: Handle to file to upload for analysis. :type filename: str :param filename: File name. :rtype: str :return: File hash as a string """ ...
Submit a file for analysis. :type handle: File handle :param handle: Handle to file to upload for analysis. :type filename: str :param filename: File name. :rtype: str :return: File hash as a string
def rotateImage(image, angle): """ rotates a 2d array to a multiple of 90 deg. 0 = default 1 = 90 deg. cw 2 = 180 deg. 3 = 90 deg. ccw """ image = [list(row) for row in image] for n in range(angle % 4): image = list(zip(*image[::-1])) return image
rotates a 2d array to a multiple of 90 deg. 0 = default 1 = 90 deg. cw 2 = 180 deg. 3 = 90 deg. ccw
def extract_chunks(blob): """Splits the blob into chucks grouped by kind.""" chunks = [] stream = BytesIO(blob.bytes) current_pos = stream.tell() stream.seek(0, 2) length = stream.tell() stream.seek(current_pos, 0) while stream.tell() < length: chunks.append(read_chunk(stream)) ...
Splits the blob into chucks grouped by kind.
def getExtensions(self): """returns objects for all map service extensions""" extensions = [] if isinstance(self.supportedExtensions, list): for ext in self.supportedExtensions: extensionURL = self._url + "/exts/%s" % ext if ext == "SchematicsServer": ...
returns objects for all map service extensions
def sync_out(self, file_name=None, force=False): """Synchronize from objects to records""" self.log('---- Sync Out ----') from ambry.bundle.files import BuildSourceFile self.dstate = self.STATES.BUILDING for f in self.build_source_files.list_records(): if (f.sync_d...
Synchronize from objects to records
def reset(self): """Resets the internal evaluation result to initial state.""" self.num_inst = 0 self.sum_metric = 0.0 self.global_num_inst = 0 self.global_sum_metric = 0.0
Resets the internal evaluation result to initial state.
def register_dn(self): """Called by WorkerThread objects to register themselves. Acquire the condition variable for the WorkerThread objects. Decrement the running-thread count. If we are the last thread to start, release the ThreadPool thread, which is stuck in start() """ ...
Called by WorkerThread objects to register themselves. Acquire the condition variable for the WorkerThread objects. Decrement the running-thread count. If we are the last thread to start, release the ThreadPool thread, which is stuck in start()
def get_result_category(expected_results, result, properties): ''' This function determines the relation between actual result and expected result for the given file and properties. @param filename: The file name of the input file. @param result: The result given by the tool (needs to be one of the ...
This function determines the relation between actual result and expected result for the given file and properties. @param filename: The file name of the input file. @param result: The result given by the tool (needs to be one of the RESULT_* strings to be recognized). @param properties: The list of prop...
def listify(value): """ Wrap the given value into a list, with the below provisions: * If the value is a list or a tuple, it's coerced into a new list. * If the value is None, an empty list is returned. * Otherwise, a single-element list is returned, containing the value. :param value: A value...
Wrap the given value into a list, with the below provisions: * If the value is a list or a tuple, it's coerced into a new list. * If the value is None, an empty list is returned. * Otherwise, a single-element list is returned, containing the value. :param value: A value. :return: a list! :rtyp...
def name(self, new_name): """ Sets the name of this node. :param new_name: name """ log.info("{module}: {name} [{id}] renamed to {new_name}".format(module=self.manager.module_name, name=self.name, ...
Sets the name of this node. :param new_name: name
def find_candidates(candidates): """ Find candidate addresses using LCS algorithm perform a scoring based on how often a candidate appears in a longer candidate Input is something like ------------------------ ['1b6033', '1b6033fd57', '701b603378e289', '20701b603378e2890...
Find candidate addresses using LCS algorithm perform a scoring based on how often a candidate appears in a longer candidate Input is something like ------------------------ ['1b6033', '1b6033fd57', '701b603378e289', '20701b603378e289000c62', '1b603300', '78e289757e', '7078e2891b...
def convert(self, string): """Return a copy of string converted to case. Parameters ---------- string : `str` Returns ------- `str` Examples -------- >>> CharCase.LOWER.convert('sTr InG') 'str ing' >>> CharCase.UPPER.conv...
Return a copy of string converted to case. Parameters ---------- string : `str` Returns ------- `str` Examples -------- >>> CharCase.LOWER.convert('sTr InG') 'str ing' >>> CharCase.UPPER.convert('sTr InG') 'STR ING' ...
def _compute_f5(self, C, pga_rock): """ Compute f5 term (non-linear soil response) """ return C['a10'] + C['a11'] * np.log(pga_rock + C['c5'])
Compute f5 term (non-linear soil response)
def stop(self): """Stop Modis and log it out of Discord.""" self.button_toggle_text.set("Start Modis") self.state = "off" logger.info("Stopping Discord Modis") from ._client import client asyncio.run_coroutine_threadsafe(client.logout(), client.loop) self.status...
Stop Modis and log it out of Discord.
def slice_cardinal(self, key): """ Slice the container according to its (primary) cardinal axis. The "cardinal" axis can have any name so long as the name matches a data object attached to the container. The index name for this object should also match the value of the cardinal ...
Slice the container according to its (primary) cardinal axis. The "cardinal" axis can have any name so long as the name matches a data object attached to the container. The index name for this object should also match the value of the cardinal axis. The algorithm builds a network graph...
def _get_component(self, component_type: Type[C]) -> Iterable[Tuple[int, C]]: """Get an iterator for Entity, Component pairs. :param component_type: The Component type to retrieve. :return: An iterator for (Entity, Component) tuples. """ entity_db = self._entities for e...
Get an iterator for Entity, Component pairs. :param component_type: The Component type to retrieve. :return: An iterator for (Entity, Component) tuples.
def rebuild(self): """ Rebuilds the widget based on the position and current size/location of its parent. """ if not self.isVisible(): return self.raise_() max_size = self.maximumPixmapSize() min_size = self.minimum...
Rebuilds the widget based on the position and current size/location of its parent.
def inc(self, exception=None): # type: (Optional[ParseError.__class__]) -> bool """ Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance. """ try: self._idx, self._current = next(self._chars) r...
Increments the parser if the end of the input has not been reached. Returns whether or not it was able to advance.
def manager(self, obj): """Returns the :class:`AttachmentsManager` instance for this object.""" manager = getattr(obj, _MANAGER_ATTR, None) if manager is None: manager = AttachmentsManager() setattr(obj.__class__, _MANAGER_ATTR, manager) return manager
Returns the :class:`AttachmentsManager` instance for this object.
def find_api_id(self): """Given API name, find API ID.""" allapis = self.client.get_rest_apis() api_name = self.trigger_settings['api_name'] api_id = None for api in allapis['items']: if api['name'] == api_name: api_id = api['id'] self....
Given API name, find API ID.
def to_css(self): ''' Generate the CSS representation of this RGB color. Returns: str, ``"rgb(...)"`` or ``"rgba(...)"`` ''' if self.a == 1.0: return "rgb(%d, %d, %d)" % (self.r, self.g, self.b) else: return "rgba(%d, %d, %d, %s)" % (self.r, ...
Generate the CSS representation of this RGB color. Returns: str, ``"rgb(...)"`` or ``"rgba(...)"``
def get_all_keys(tweet, parent_key=''): """ Takes a tweet object and recursively returns a list of all keys contained in this level and all nexstted levels of the tweet. Args: tweet (Tweet): the tweet dict parent_key (str): key from which this process will start, e.g., you can ...
Takes a tweet object and recursively returns a list of all keys contained in this level and all nexstted levels of the tweet. Args: tweet (Tweet): the tweet dict parent_key (str): key from which this process will start, e.g., you can get keys only under some key that i...
def _check_and_apply_deprecations(self, scope, values): """Checks whether a ScopeInfo has options specified in a deprecated scope. There are two related cases here. Either: 1) The ScopeInfo has an associated deprecated_scope that was replaced with a non-deprecated scope, meaning that the options...
Checks whether a ScopeInfo has options specified in a deprecated scope. There are two related cases here. Either: 1) The ScopeInfo has an associated deprecated_scope that was replaced with a non-deprecated scope, meaning that the options temporarily live in two locations. 2) The entire ScopeIn...
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: WorkspaceStatisticsContext for this WorkspaceStatisticsInstance :rtype: twilio.rest.taskrouter.v1...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: WorkspaceStatisticsContext for this WorkspaceStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.workspace_statistics.Worksp...
def get_resources(minify=False): """Find all resources which subclass ResourceBase. Keyword arguments: minify -- select minified resources if available. Returns: Dictionary of available resources. Keys are resource names (part of the config variable names), values are dicts with css and js key...
Find all resources which subclass ResourceBase. Keyword arguments: minify -- select minified resources if available. Returns: Dictionary of available resources. Keys are resource names (part of the config variable names), values are dicts with css and js keys, and tuples of resources as values.
def get_desc2nts(self, **kws_usr): """Return grouped, sorted namedtuples in either format: flat, sections.""" # desc2nts contains: (sections hdrgo_prt sortobj) or (flat hdrgo_prt sortobj) # keys_nts: hdrgo_prt section_prt top_n use_sections kws_nts = {k:v for k, v in kws_usr.items() if k...
Return grouped, sorted namedtuples in either format: flat, sections.
def ping(): ''' Is the marathon api responding? ''' try: response = salt.utils.http.query( "{0}/ping".format(CONFIG[CONFIG_BASE_URL]), decode_type='plain', decode=True, ) log.debug( 'marathon.info returned successfully: %s', ...
Is the marathon api responding?
def minimum_spanning_tree_kruskal(self, display = None, components = None): ''' API: minimum_spanning_tree_kruskal(self, display = None, components = None) Description: Determines a minimum spanning tree using Kruskal's Algorithm. Input:...
API: minimum_spanning_tree_kruskal(self, display = None, components = None) Description: Determines a minimum spanning tree using Kruskal's Algorithm. Input: display: Display method. component: component number. Post: ...
def clean_dataframes(dfs): """Fill NaNs with the previous value, the next value or if all are NaN then 1.0 TODO: Linear interpolation and extrapolation Arguments: dfs (list of dataframes): list of dataframes that contain NaNs to be removed Returns: list of dataframes: list of datafr...
Fill NaNs with the previous value, the next value or if all are NaN then 1.0 TODO: Linear interpolation and extrapolation Arguments: dfs (list of dataframes): list of dataframes that contain NaNs to be removed Returns: list of dataframes: list of dataframes with NaNs replaced by interpo...
def _fetch(self, statement, commit, max_attempts=5): """ Execute a SQL query and return a result. Recursively disconnect and reconnect to the database if an error occurs. """ if self._auto_reconnect: attempts = 0 while attempts < max_attempts: ...
Execute a SQL query and return a result. Recursively disconnect and reconnect to the database if an error occurs.
def process_config(config, config_data): """ Populates config with data from the configuration data dict. It handles components, data, log, management and session sections from the configuration data. :param config: The config reference of the object that will hold the configuration data from the c...
Populates config with data from the configuration data dict. It handles components, data, log, management and session sections from the configuration data. :param config: The config reference of the object that will hold the configuration data from the config_data. :param config_data: The configura...
def make_symlink(source, link_path): """ Create a symlink at `link_path` referring to `source`. """ if not supports_symlinks(): dbt.exceptions.system_error('create a symbolic link') return os.symlink(source, link_path)
Create a symlink at `link_path` referring to `source`.
def uninstall_package_and_data( package_name, service_name=None, role=None, principal=None, zk_node=None, timeout_sec=600): """ Uninstall a package via the DC/OS library, wait for completion, and delete any persistent data :param package_name: name of the pac...
Uninstall a package via the DC/OS library, wait for completion, and delete any persistent data :param package_name: name of the package :type package_name: str :param service_name: unique service name for the package :type service_name: str :param role: role to use when deleting...
def get_element_type(_list, dimens): """ Given the dimensions of a nested list and the list, returns the type of the elements in the inner list. """ elem = _list for _ in range(len(dimens)): elem = elem[0] return type(elem)
Given the dimensions of a nested list and the list, returns the type of the elements in the inner list.
def query(self, coords, mode='random_sample', return_flags=False, pct=None): """ Returns reddening at the requested coordinates. There are several different query modes, which handle the probabilistic nature of the map differently. Args: coords (:obj:`astropy.coordin...
Returns reddening at the requested coordinates. There are several different query modes, which handle the probabilistic nature of the map differently. Args: coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query. mode (Optional[:obj:`str`]): Seven differe...
def checkSetSaveChildren(self, doSave=True): """Check, then set, then save the parameter settings for all child (pset) windows. Prompts if any problems are found. Returns None on success, list of bad entries on failure. """ if self.isChild: return #...
Check, then set, then save the parameter settings for all child (pset) windows. Prompts if any problems are found. Returns None on success, list of bad entries on failure.
def add_path(tdict, path): """ Create or extend an argument tree `tdict` from `path`. :param tdict: a dictionary representing a argument tree :param path: a path list :return: a dictionary Convert a list of items in a 'path' into a nested dict, where the second to last item becomes the key...
Create or extend an argument tree `tdict` from `path`. :param tdict: a dictionary representing a argument tree :param path: a path list :return: a dictionary Convert a list of items in a 'path' into a nested dict, where the second to last item becomes the key for the final item. The remaining ...
def complex_mult(A, B, shifts, start): """ Generate shift-and-add multiplier that can shift and add multiple bits per clock cycle. Uses substantially more space than `simple_mult()` but is much faster. :param WireVector A, B: two input wires for the multiplication :param int shifts: number of spaces Re...
Generate shift-and-add multiplier that can shift and add multiple bits per clock cycle. Uses substantially more space than `simple_mult()` but is much faster. :param WireVector A, B: two input wires for the multiplication :param int shifts: number of spaces Register is to be shifted per clk cycle (...
def main(args): ''' surface_to_rubbon.main(args) can be given a list of arguments, such as sys.argv[1:]; these arguments may include any options and must include exactly one subject id and one output filename. Additionally one or two surface input filenames must be given. The surface files are proje...
surface_to_rubbon.main(args) can be given a list of arguments, such as sys.argv[1:]; these arguments may include any options and must include exactly one subject id and one output filename. Additionally one or two surface input filenames must be given. The surface files are projected into the ribbon and wri...
def find_one(self, *args, **kwargs): """ Get a single document from the database. """ doc = self._collection_with_options(kwargs).find_one(*args, **kwargs) if doc is None: return None return doc
Get a single document from the database.
def main(self) -> None: """The main function for generating the config file""" path = ask_path("where should the config be stored?", ".snekrc") conf = configobj.ConfigObj() tools = self.get_tools() for tool in tools: conf[tool] = getattr(self, tool)() # pylint: dis...
The main function for generating the config file
def _assert_sframe_equal(sf1, sf2, check_column_names=True, check_column_order=True, check_row_order=True, float_column_delta=None): """ Assert the two SFrames are equal. The default...
Assert the two SFrames are equal. The default behavior of this function uses the strictest possible definition of equality, where all columns must be in the same order, with the same names and have the same data in the same order. Each of these stipulations can be relaxed individually and in concert w...
def _copy(self, other, copy_func): """ Copies the contents of another Asn1Value object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and o...
Copies the contents of another Asn1Value object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects
def execute_builtin_action(self, p_action_str, p_size=None): """ Executes built-in action specified in p_action_str. Currently supported actions are: 'up', 'down', 'home', 'end', 'first_column', 'last_column', 'prev_column', 'next_column', 'append_column', 'insert_column', 'edit...
Executes built-in action specified in p_action_str. Currently supported actions are: 'up', 'down', 'home', 'end', 'first_column', 'last_column', 'prev_column', 'next_column', 'append_column', 'insert_column', 'edit_column', 'delete_column', 'copy_column', swap_right', 'swap_left', 'post...
def add_webhook(self, name, url, key, **attrs): """ Add a new Webhook and return a :class:`Webhook` object. :param name: name of the :class:`Webhook` :param url: payload url of the :class:`Webhook` :param key: secret key of the :class:`Webhook` :param attrs: optional att...
Add a new Webhook and return a :class:`Webhook` object. :param name: name of the :class:`Webhook` :param url: payload url of the :class:`Webhook` :param key: secret key of the :class:`Webhook` :param attrs: optional attributes for :class:`Webhook`
def extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None): ''' .. versionchanged:: 2016.3.5 Prior to this version, only the ``file_name`` argument was considered for filename matches in the ha...
.. versionchanged:: 2016.3.5 Prior to this version, only the ``file_name`` argument was considered for filename matches in the hash file. This would be problematic for cases in which the user was relying on a remote checksum file that they do not control, and they wished to use a differe...
def convert(self, expr): """ EXPAND INSTANCES OF name TO value """ if expr is True or expr == None or expr is False: return expr elif is_number(expr): return expr elif expr == ".": return "." elif is_variable_name(expr): ...
EXPAND INSTANCES OF name TO value