code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def check_basic_auth(user, passwd): """Checks user authentication using HTTP Basic Auth.""" auth = request.authorization return auth and auth.username == user and auth.password == passwd
Checks user authentication using HTTP Basic Auth.
def register(cls): """Register an :class:`Entity` as a commentable class. Can be used as a class decorator: .. code-block:: python @comment.register class MyContent(Entity): ... """ if not issubclass(cls, Entity): raise ValueError("Class must be a subclass of abilian...
Register an :class:`Entity` as a commentable class. Can be used as a class decorator: .. code-block:: python @comment.register class MyContent(Entity): ...
def p_stop_raise(p): """ statement : STOP expr | STOP """ q = make_number(9, lineno=p.lineno(1)) if len(p) == 2 else p[2] z = make_number(1, lineno=p.lineno(1)) r = make_binary(p.lineno(1), 'MINUS', make_typecast(TYPE.ubyte, q, p.lineno(1)), z, ...
statement : STOP expr | STOP
def _prepare_headers(self, additional_headers=None, **kwargs): """Prepare headers for http communication. Return dict of header to be used in requests. Args: .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used wit...
Prepare headers for http communication. Return dict of header to be used in requests. Args: .. versionadded:: 0.3.2 **additional_headers**: (optional) Additional headers to be used with request Returns: Headers dict. Key and values are s...
def run(*args, **kwargs): # type: (...) -> None """Run cwltool.""" signal.signal(signal.SIGTERM, _signal_handler) try: sys.exit(main(*args, **kwargs)) finally: _terminate_processes()
Run cwltool.
def new(cls, signatures: [Signature]) -> 'MultiSignature': """ Creates and returns BLS multi signature that corresponds to the given signatures list. :param: signature - List of signatures :return: BLS multi signature """ logger = logging.getLogger(__name__) logge...
Creates and returns BLS multi signature that corresponds to the given signatures list. :param: signature - List of signatures :return: BLS multi signature
def predict_steadystate(self, u=0, B=None): """ Predict state (prior) using the Kalman filter state propagation equations. Only x is updated, P is left unchanged. See update_steadstate() for a longer explanation of when to use this method. Parameters ---------- ...
Predict state (prior) using the Kalman filter state propagation equations. Only x is updated, P is left unchanged. See update_steadstate() for a longer explanation of when to use this method. Parameters ---------- u : np.array Optional control vector. If non...
def _controller(self): """ This method runs in a dedicated thread, calling self.eval_command(). :return: """ while self.running: try: cmd = self._controller_q.get(timeout=1) except (TimeoutError, Empty): continue ...
This method runs in a dedicated thread, calling self.eval_command(). :return:
def _setup_rpc(self): """Setup the RPC client for the current agent.""" self._plugin_rpc = agent_rpc.PluginApi(topics.PLUGIN) self._state_rpc = agent_rpc.PluginReportStateAPI(topics.PLUGIN) self._client = n_rpc.get_client(self.target) self._consumers.extend([ [topics...
Setup the RPC client for the current agent.
def toggle_create_button(self): """Enable or disable Create Mask button based on drawn objects.""" if len(self._drawn_tags) > 0: self.w.create_mask.set_enabled(True) else: self.w.create_mask.set_enabled(False)
Enable or disable Create Mask button based on drawn objects.
def project(ctx, project): # pylint:disable=redefined-outer-name """Commands for projects.""" if ctx.invoked_subcommand not in ['create', 'list']: ctx.obj = ctx.obj or {} ctx.obj['project'] = project
Commands for projects.
def select_one(self, tag): """Select a single tag.""" tags = self.select(tag, limit=1) return tags[0] if tags else None
Select a single tag.
def get_sns_topic_arn(topic_name, account, region): """Get SNS topic ARN. Args: topic_name (str): Name of the topic to lookup. account (str): Environment, e.g. dev region (str): Region name, e.g. us-east-1 Returns: str: ARN for requested topic name """ if topic_nam...
Get SNS topic ARN. Args: topic_name (str): Name of the topic to lookup. account (str): Environment, e.g. dev region (str): Region name, e.g. us-east-1 Returns: str: ARN for requested topic name
def _dnsname_to_stdlib(name): """ Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and ...
Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to conve...
def reset_image_attribute(self, image_id, attribute='launchPermission'): """ Resets an attribute of an AMI to its default value. :type image_id: string :param image_id: ID of the AMI for which an attribute will be described :type attribute: string :param attribute: The ...
Resets an attribute of an AMI to its default value. :type image_id: string :param image_id: ID of the AMI for which an attribute will be described :type attribute: string :param attribute: The attribute to reset :rtype: bool :return: Whether the operation succeeded or ...
def setpassword(self, password): """Sets the password to use when extracting. """ self._password = password if self._file_parser: if self._file_parser.has_header_encryption(): self._file_parser = None if not self._file_parser: self._parse()...
Sets the password to use when extracting.
def check_ip(addr): ''' Check if address is a valid IP. returns True if valid, otherwise False. CLI Example: .. code-block:: bash salt ns1 dig.check_ip 127.0.0.1 salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888 ''' try: addr = addr.rsplit('/', 1) exce...
Check if address is a valid IP. returns True if valid, otherwise False. CLI Example: .. code-block:: bash salt ns1 dig.check_ip 127.0.0.1 salt ns1 dig.check_ip 1111:2222:3333:4444:5555:6666:7777:8888
def mount_status_encode(self, target_system, target_component, pointing_a, pointing_b, pointing_c): ''' Message with some status from APM to GCS about camera or antenna mount target_system : System ID (uint8_t) target_component : Comp...
Message with some status from APM to GCS about camera or antenna mount target_system : System ID (uint8_t) target_component : Component ID (uint8_t) pointing_a : pitch(deg*100) (int32_t) pointing_b : roll...
def _scan(self, type): """ Returns the matched text, and moves to the next token """ tok = self._scanner.token(self._pos, frozenset([type])) self._char_pos = tok[0] if tok[2] != type: raise SyntaxError("SyntaxError[@ char %s: %s]" % (repr(tok[0]), "Trying to f...
Returns the matched text, and moves to the next token
def start_polling(dispatcher, *, loop=None, skip_updates=False, reset_webhook=True, on_startup=None, on_shutdown=None, timeout=20, fast=True): """ Start bot in long-polling mode :param dispatcher: :param loop: :param skip_updates: :param reset_webhook: :param on_startup: ...
Start bot in long-polling mode :param dispatcher: :param loop: :param skip_updates: :param reset_webhook: :param on_startup: :param on_shutdown: :param timeout:
def semester_feature(catalog, soup): """The year and semester information that this xml file hold courses for. """ raw = soup.coursedb['semesternumber'] catalog.year = int(raw[:4]) month_mapping = {1: 'Spring', 5: 'Summer', 9: 'Fall'} catalog.month = int(raw[4:]) catalog.semester = month_ma...
The year and semester information that this xml file hold courses for.
def _convert_xml_to_service_properties(response): ''' <?xml version="1.0" encoding="utf-8"?> <StorageServiceProperties> <Logging> <Version>version-number</Version> <Delete>true|false</Delete> <Read>true|false</Read> <Write>true|false</Write> ...
<?xml version="1.0" encoding="utf-8"?> <StorageServiceProperties> <Logging> <Version>version-number</Version> <Delete>true|false</Delete> <Read>true|false</Read> <Write>true|false</Write> <RetentionPolicy> <Enabled>true|false</Enabl...
def rotate(self, clat, clon, coord_degrees=True, dj_matrix=None, nwinrot=None): """" Rotate the spherical-cap windows centered on the North pole to clat and clon, and save the spherical harmonic coefficients in the attribute coeffs. Usage ----- x.r...
Rotate the spherical-cap windows centered on the North pole to clat and clon, and save the spherical harmonic coefficients in the attribute coeffs. Usage ----- x.rotate(clat, clon [coord_degrees, dj_matrix, nwinrot]) Parameters ---------- clat, clon : fl...
def add_device(self, device, container): """Add a device to a group. Wraps JSSObject.add_object_to_path. Args: device: A JSSObject to add (as list data), to this object. location: Element or a string path argument to find() """ # There is a size tag which the JSS...
Add a device to a group. Wraps JSSObject.add_object_to_path. Args: device: A JSSObject to add (as list data), to this object. location: Element or a string path argument to find()
def is_modifier(key): """ Returns True if `key` is a scan code or name of a modifier key. """ if _is_str(key): return key in all_modifiers else: if not _modifier_scan_codes: scan_codes = (key_to_scan_codes(name, False) for name in all_modifiers) _modifier_sca...
Returns True if `key` is a scan code or name of a modifier key.
def _filter(self, query, **kwargs): """ Filter a query with user-supplied arguments. """ query = self._auto_filter(query, **kwargs) return query
Filter a query with user-supplied arguments.
def decrypt(self, data, pad=None, padmode=None): """decrypt(data, [pad], [padmode]) -> bytes data : bytes to be encrypted pad : Optional argument for decryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be dec...
decrypt(data, [pad], [padmode]) -> bytes data : bytes to be encrypted pad : Optional argument for decryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be decrypted with the already specified key. In PAD_NORMAL...
def ensure_dir_does_not_exist(*args): """Ensures that the given directory does not exist.""" path = os.path.join(*args) if os.path.isdir(path): shutil.rmtree(path)
Ensures that the given directory does not exist.
def deregister(self, subscriber): """Stop publishing to a subscriber.""" try: logger.debug('Subscriber left') self.subscribers.remove(subscriber) except KeyError: logger.debug( 'Error removing subscriber: ' + str(subscri...
Stop publishing to a subscriber.
def import_jwks_as_json(self, jwks, issuer): """ Imports all the keys that are represented in a JWKS expressed as a JSON object :param jwks: JSON representation of a JWKS :param issuer: Who 'owns' the JWKS """ return self.import_jwks(json.loads(jwks), issuer)
Imports all the keys that are represented in a JWKS expressed as a JSON object :param jwks: JSON representation of a JWKS :param issuer: Who 'owns' the JWKS
def mult_masses(mA, f_binary=0.4, f_triple=0.12, minmass=0.11, qmin=0.1, n=1e5): """Returns m1, m2, and m3 appropriate for TripleStarPopulation, given "primary" mass (most massive of system) and binary/triple fractions. star with m1 orbits (m2 + m3). This means that the primary mass mA will c...
Returns m1, m2, and m3 appropriate for TripleStarPopulation, given "primary" mass (most massive of system) and binary/triple fractions. star with m1 orbits (m2 + m3). This means that the primary mass mA will correspond either to m1 or m2. Any mass set to 0 means that component does not exist.
def add_cache_tier(self, cache_pool, mode): """ Adds a new cache tier to an existing pool. :param cache_pool: six.string_types. The cache tier pool name to add. :param mode: six.string_types. The caching mode to use for this pool. valid range = ["readonly", "writeback"] :return...
Adds a new cache tier to an existing pool. :param cache_pool: six.string_types. The cache tier pool name to add. :param mode: six.string_types. The caching mode to use for this pool. valid range = ["readonly", "writeback"] :return: None
def build_job_configs(self, args): """Hook to build job configurations """ job_configs = {} components = Component.build_from_yamlfile(args['comp']) NAME_FACTORY.update_base_dict(args['data']) mktime = args['mktimefilter'] for comp in components: zc...
Hook to build job configurations
def ProcessEntry(self, responses): """Process the responses from the client.""" if not responses.success: return # The Find client action does not return a StatEntry but a # FindSpec. Normalize to a StatEntry. stat_responses = [ r.hit if isinstance(r, rdf_client_fs.FindSpec) else r fo...
Process the responses from the client.
def get(self, test_id): ''' get report by the test id :param test_id: test id :return: Report object ''' self.select('*', 'test_id=?', [test_id]) row = self._cursor.fetchone() if not row: raise KeyError('No report with test id %s in the DB' % ...
get report by the test id :param test_id: test id :return: Report object
def is_defined(self, obj, force_import=False): """Return True if object is defined in current namespace""" from spyder_kernels.utils.dochelpers import isdefined ns = self._get_current_namespace(with_magics=True) return isdefined(obj, force_import=force_import, namespace=ns)
Return True if object is defined in current namespace
def create_dialog(obj, obj_name): """Creates the editor dialog and returns a tuple (dialog, func) where func is the function to be called with the dialog instance as argument, after quitting the dialog box The role of this intermediate function is to allow easy monkey-patching. (uschmitt...
Creates the editor dialog and returns a tuple (dialog, func) where func is the function to be called with the dialog instance as argument, after quitting the dialog box The role of this intermediate function is to allow easy monkey-patching. (uschmitt suggested this indirection here so that h...
def list_logstores(self, request): """ List all logstores of requested project. Unsuccessful opertaion will cause an LogException. :type request: ListLogstoresRequest :param request: the ListLogstores request parameters class. :return: ListLogStoresRespon...
List all logstores of requested project. Unsuccessful opertaion will cause an LogException. :type request: ListLogstoresRequest :param request: the ListLogstores request parameters class. :return: ListLogStoresResponse :raise: LogException
def update(self, force=False): """Fetch new posts from the server. Arguments: force (bool): Force a thread update, even if thread has 404'd. Returns: int: How many new posts have been fetched. """ # The thread has already 404'ed, this function shouldn't...
Fetch new posts from the server. Arguments: force (bool): Force a thread update, even if thread has 404'd. Returns: int: How many new posts have been fetched.
def reftrick(iseq, consdict): """ Returns the most common base at each site in order. """ altrefs = np.zeros((iseq.shape[1], 4), dtype=np.uint8) altrefs[:, 1] = 46 for col in xrange(iseq.shape[1]): ## expand colums with ambigs and remove N- fcounts = np.zeros(111, dtype=np.int64) ...
Returns the most common base at each site in order.
def _validate_type_scalar(self, value): """ Is not a list or a dict """ if isinstance( value, _int_types + (_str_type, float, date, datetime, bool) ): return True
Is not a list or a dict
def make_control_flow_handlers(self, cont_n, status_n, expected_return, has_cont, has_break): ''' Create the statements in charge of gathering control flow information for the static_if result, and executes the expected control flow instruction ...
Create the statements in charge of gathering control flow information for the static_if result, and executes the expected control flow instruction
def _parse_values(s): '''(INTERNAL) Split a line into a list of values''' if not _RE_NONTRIVIAL_DATA.search(s): # Fast path for trivial cases (unfortunately we have to handle missing # values because of the empty string case :(.) return [None if s in ('?', '') else s for ...
(INTERNAL) Split a line into a list of values
def random_adjspecies(sep='', maxlen=8, prevent_stutter=True): """ Return a random adjective/species, separated by `sep`. The keyword arguments `maxlen` and `prevent_stutter` are the same as for `random_adjspecies_pair`, but note that the maximum length argument is not affected by the separator. ...
Return a random adjective/species, separated by `sep`. The keyword arguments `maxlen` and `prevent_stutter` are the same as for `random_adjspecies_pair`, but note that the maximum length argument is not affected by the separator.
def applymap(self, func, **kwargs): """Return a new PRDD by applying a function to each element of each pandas DataFrame.""" return self.from_rdd( self._rdd.map(lambda data: data.applymap(func), **kwargs))
Return a new PRDD by applying a function to each element of each pandas DataFrame.
def show_multi_buffer(self): """Show the multi buffer tool.""" from safe.gui.tools.multi_buffer_dialog import ( MultiBufferDialog) dialog = MultiBufferDialog( self.iface.mainWindow(), self.iface, self.dock_widget) dialog.exec_()
Show the multi buffer tool.
def genes_with_a_representative_structure(self): """DictList: All genes with a representative protein structure.""" tmp = DictList(x for x in self.genes if x.protein.representative_structure) return DictList(y for y in tmp if y.protein.representative_structure.structure_file)
DictList: All genes with a representative protein structure.
def get_free_udp_port(): ''' Get a free UDP port. Note this is vlunerable to race conditions. ''' import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 0)) addr = sock.getsockname() sock.close() return addr[1]
Get a free UDP port. Note this is vlunerable to race conditions.
def BitField(value, length, signed=False, min_value=None, max_value=None, encoder=ENC_INT_DEFAULT, fuzzable=True, name=None, full_range=False): ''' Returns an instance of some BitField class .. note:: Since BitField is frequently used in binary format, multiple aliases were created for it. See alia...
Returns an instance of some BitField class .. note:: Since BitField is frequently used in binary format, multiple aliases were created for it. See aliases.py for more details.
def translate_array(array, lval, obj_count=1, arr_count=1): """array has to be any js array for example [1,2,3] lval has to be name of this array. Returns python code that adds lval to the PY scope it should be put before lval""" array = array[1:-1] array, obj_rep, obj_count = remove_objects(a...
array has to be any js array for example [1,2,3] lval has to be name of this array. Returns python code that adds lval to the PY scope it should be put before lval
def cf_string_to_unicode(value): """ Creates a python unicode string from a CFString object :param value: The CFString to convert :return: A python unicode string """ string_ptr = CoreFoundation.CFStringGetCStringPtr( value, ...
Creates a python unicode string from a CFString object :param value: The CFString to convert :return: A python unicode string
def model_attr(attr_name): """ Creates a getter that will drop the current value and retrieve the model's attribute with specified name. @param attr_name: the name of an attribute belonging to the model. @type attr_name: str """ def model_attr(_value, context, **_params): value = ge...
Creates a getter that will drop the current value and retrieve the model's attribute with specified name. @param attr_name: the name of an attribute belonging to the model. @type attr_name: str
def error_bars(self, n_bins, d_min, d_max): """ Error Bars create bars and error bars to plot Inputs : n_bins : number of bins plot_range : (shape) = (number of dimensions, 2) matrix which contain the min and max for each dimension as rows Outputs :...
Error Bars create bars and error bars to plot Inputs : n_bins : number of bins plot_range : (shape) = (number of dimensions, 2) matrix which contain the min and max for each dimension as rows Outputs : x : domain p_x : ...
def primary_xi(mass1, mass2, spin1x, spin1y, spin2x, spin2y): """Returns the effective precession spin argument for the larger mass. """ spinx = primary_spin(mass1, mass2, spin1x, spin2x) spiny = primary_spin(mass1, mass2, spin1y, spin2y) return chi_perp_from_spinx_spiny(spinx, spiny)
Returns the effective precession spin argument for the larger mass.
def navigate(self, inst, kind, rel_id, phrase=''): ''' Navigate across a link with some *rel_id* and *phrase* that yields instances of some *kind*. ''' key = (kind.upper(), rel_id, phrase) if key in self.links: link = self.links[key] return link.na...
Navigate across a link with some *rel_id* and *phrase* that yields instances of some *kind*.
def _axis_properties(self, axis, title_size, title_offset, label_angle, label_align, color): """Assign axis properties""" if self.axes: axis = [a for a in self.axes if a.scale == axis][0] self._set_axis_properties(axis) self._set_all_axis_colo...
Assign axis properties
def get_relationship_family_assignment_session(self, proxy=None): """Gets the ``OsidSession`` associated with assigning relationships to families. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.RelationshipFamilyAssignmentSession) - a ``RelationshipFamilyAs...
Gets the ``OsidSession`` associated with assigning relationships to families. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.RelationshipFamilyAssignmentSession) - a ``RelationshipFamilyAssignmentSession`` raise: NullArgument - ``proxy`` is ``null`` ...
def open_url(absolute_or_relative_url): """ Loads a web page in the current browser session. :param absolgenerateute_or_relative_url: an absolute url to web page in case of config.base_url is not specified, otherwise - relative url correspondingly :Usage: open_url('http://mydoma...
Loads a web page in the current browser session. :param absolgenerateute_or_relative_url: an absolute url to web page in case of config.base_url is not specified, otherwise - relative url correspondingly :Usage: open_url('http://mydomain.com/subpage1') open_url('http://mydomain....
def collect(self, step, content): '''given a name of a configuration key and the provided content, collect the required metadata from the user. Parameters ========== step: the key in the configuration. Can be one of: user_message_<name> ...
given a name of a configuration key and the provided content, collect the required metadata from the user. Parameters ========== step: the key in the configuration. Can be one of: user_message_<name> runtime_arg_<name> ...
def _increment(sign, integer_part, non_repeating_part, base): """ Return an increment radix. :param int sign: -1, 0, or 1 as appropriate :param integer_part: the integer part :type integer_part: list of int :param non_repeating_part: the fractional part :type non...
Return an increment radix. :param int sign: -1, 0, or 1 as appropriate :param integer_part: the integer part :type integer_part: list of int :param non_repeating_part: the fractional part :type non_repeating_part: list of int :param int base: the base :returns: ...
def emit(self, *args, **kwargs): """ Calls all the connected slots with the provided args and kwargs unless block is activated """ if self._block: return for slot in self._slots: if not slot: continue elif isinstance(slot, par...
Calls all the connected slots with the provided args and kwargs unless block is activated
def simple_mean_function(max_iters=100, optimize=True, plot=True): """ The simplest possible mean function. No parameters, just a simple Sinusoid. """ #create simple mean function mf = GPy.core.Mapping(1,1) mf.f = np.sin mf.update_gradients = lambda a,b: None X = np.linspace(0,10,50).r...
The simplest possible mean function. No parameters, just a simple Sinusoid.
def _loop_wrapper_func(func, args, shared_mem_run, shared_mem_pause, interval, sigint, sigterm, name, logging_level, conn_send, func_running, log_queue): """ to be executed as a separate process (that's why this functions is declared static) """ prefix = get_identifier(name) +...
to be executed as a separate process (that's why this functions is declared static)
def reindex(self, new_index=None, index_conf=None): '''Rebuilt the current index This function could be useful in the case you want to change some index settings/mappings and you don't want to loose all the entries belonging to that index. This function is built in such a way ...
Rebuilt the current index This function could be useful in the case you want to change some index settings/mappings and you don't want to loose all the entries belonging to that index. This function is built in such a way that you can continue to use the old index name, thi...
def update(self, key=values.unset, value=values.unset): """ Update the VariableInstance :param unicode key: The key :param unicode value: The value :returns: Updated VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance ...
Update the VariableInstance :param unicode key: The key :param unicode value: The value :returns: Updated VariableInstance :rtype: twilio.rest.serverless.v1.service.environment.variable.VariableInstance
def read_config_environment(self, config_data=None, quiet=False): """read_config_environment is the second effort to get a username and key to authenticate to the Kaggle API. The environment keys are equivalent to the kaggle.json file, but with "KAGGLE_" prefix to define a uniqu...
read_config_environment is the second effort to get a username and key to authenticate to the Kaggle API. The environment keys are equivalent to the kaggle.json file, but with "KAGGLE_" prefix to define a unique namespace. Parameters ========== config_d...
def check_blank_before_after_class(self, class_, docstring): """D20{3,4}: Class docstring should have 1 blank line around them. Insert a blank line before and after all docstrings (one-line or multi-line) that document a class -- generally speaking, the class's methods are separated fro...
D20{3,4}: Class docstring should have 1 blank line around them. Insert a blank line before and after all docstrings (one-line or multi-line) that document a class -- generally speaking, the class's methods are separated from each other by a single blank line, and the docstring needs to ...
def home(request): "Simple homepage view." context = {} if request.user.is_authenticated(): try: access = request.user.accountaccess_set.all()[0] except IndexError: access = None else: client = access.api_client context['info'] = client...
Simple homepage view.
def draw(graph, fname): """Draw a graph and save it into a file""" ag = networkx.nx_agraph.to_agraph(graph) ag.draw(fname, prog='dot')
Draw a graph and save it into a file
def _make_attachment(self, attachment, str_encoding=None): """Returns EmailMessage.attachments item formatted for sending with Mailjet Returns mailjet_dict, is_inline_image """ is_inline_image = False if isinstance(attachment, MIMEBase): name = attachment.get_filenam...
Returns EmailMessage.attachments item formatted for sending with Mailjet Returns mailjet_dict, is_inline_image
def _update_vdr_vxrheadtail(self, f, vdr_offset, VXRoffset): ''' This sets a VXR to be the first and last VXR in the VDR ''' # VDR's VXRhead self._update_offset_value(f, vdr_offset+28, 8, VXRoffset) # VDR's VXRtail self._update_offset_value(f, vdr_offset+36, 8, VX...
This sets a VXR to be the first and last VXR in the VDR
def derive_data(data): """ Based on the data derive additional data """ for s_name, values in data.items(): # setup holding variable # Sum all variants that have been called total_called_variants = 0 for value_name in ['TOTAL_SNPS', 'TOTAL_COMPLEX_INDELS', 'TOTAL_MULTIALLELIC_S...
Based on the data derive additional data
def _generate_routes(self, namespace): """ Generates Python methods that correspond to routes in the namespace. """ # Hack: needed for _docf() self.cur_namespace = namespace # list of auth_types supported in this base class. # this is passed with the new -w flag ...
Generates Python methods that correspond to routes in the namespace.
def run_decider_state(self, decider_state, child_errors, final_outcomes_dict): """ Runs the decider state of the barrier concurrency state. The decider state decides on which outcome the barrier concurrency is left. :param decider_state: the decider state of the barrier concurrency state ...
Runs the decider state of the barrier concurrency state. The decider state decides on which outcome the barrier concurrency is left. :param decider_state: the decider state of the barrier concurrency state :param child_errors: error of the concurrent branches :param final_outcomes_dict:...
def find_or_new(self, id, columns=None): """ Find a model by its primary key or return new instance of the related model. :param id: The primary key :type id: mixed :param columns: The columns to retrieve :type columns: list :rtype: Collection or Model ...
Find a model by its primary key or return new instance of the related model. :param id: The primary key :type id: mixed :param columns: The columns to retrieve :type columns: list :rtype: Collection or Model
def circle(radius=None, center=None, **kwargs): """ Create a Path2D containing a single or multiple rectangles with the specified bounds. Parameters -------------- bounds : (2, 2) float, or (m, 2, 2) float Minimum XY, Maximum XY Returns ------------- rect : Path2D Path ...
Create a Path2D containing a single or multiple rectangles with the specified bounds. Parameters -------------- bounds : (2, 2) float, or (m, 2, 2) float Minimum XY, Maximum XY Returns ------------- rect : Path2D Path containing specified rectangles
def apply_order(self): '''Naively apply query orders.''' self._ensure_modification_is_safe() if len(self.query.orders) > 0: self._iterable = Order.sorted(self._iterable, self.query.orders)
Naively apply query orders.
def set_position(self, resource_id, to_position, db_session=None, *args, **kwargs): """ Sets node position for new node in the tree :param resource_id: resource to move :param to_position: new position :param db_session: :return:def count_children(cls, resource_id, db_se...
Sets node position for new node in the tree :param resource_id: resource to move :param to_position: new position :param db_session: :return:def count_children(cls, resource_id, db_session=None):
def _dispense_plunger_position(self, ul): """Calculate axis position for a given liquid volume. Translates the passed liquid volume to absolute coordinates on the axis associated with this pipette. Calibration of the pipette motor's ul-to-mm conversion is required """ m...
Calculate axis position for a given liquid volume. Translates the passed liquid volume to absolute coordinates on the axis associated with this pipette. Calibration of the pipette motor's ul-to-mm conversion is required
def piprot(): """Parse the command line arguments and jump into the piprot() function (unless the user just wants the post request hook). """ cli_parser = argparse.ArgumentParser( epilog="Here's hoping your requirements are nice and fresh!" ) cli_parser.add_argument( '-v', '--ver...
Parse the command line arguments and jump into the piprot() function (unless the user just wants the post request hook).
def setsockopt(self, *sockopts): """Add socket options to set""" if type(sockopts[0]) in (list, tuple): for sock_opt in sockopts[0]: level, option, value = sock_opt self.connection.sockopts.add((level, option, value)) else: level, option, v...
Add socket options to set
def check_int_param(self, param, low, high, name): """ Check if the value of the given parameter is in the given range and an int. Designed for testing parameters like `mu` and `eps`. To pass this function the variable `param` must be able to be converted into a float wit...
Check if the value of the given parameter is in the given range and an int. Designed for testing parameters like `mu` and `eps`. To pass this function the variable `param` must be able to be converted into a float with a value between `low` and `high`. **Args:** * `para...
def set_references(references, components): """ Sets references to multiple components. To set references components must implement [[IReferenceable]] interface. If they don't the call to this method has no effect. :param references: the references to be set. :param co...
Sets references to multiple components. To set references components must implement [[IReferenceable]] interface. If they don't the call to this method has no effect. :param references: the references to be set. :param components: a list of components to set the references to.
def clear_task_instances(tis, session, activate_dag_runs=True, dag=None, ): """ Clears a set of task instances, but makes sure the running ones get killed. :param tis: a list of task instances :param...
Clears a set of task instances, but makes sure the running ones get killed. :param tis: a list of task instances :param session: current session :param activate_dag_runs: flag to check for active dag run :param dag: DAG object
def printActiveIndices(self, state, andValues=False): """ Print the list of ``[column, cellIdx]`` indices for each of the active cells in state. :param state: TODO: document :param andValues: TODO: document """ if len(state.shape) == 2: (cols, cellIdxs) = state.nonzero() else: ...
Print the list of ``[column, cellIdx]`` indices for each of the active cells in state. :param state: TODO: document :param andValues: TODO: document
def _rmv_deps_answer(self): """Remove dependencies answer """ if self.meta.remove_deps_answer in ["y", "Y"]: remove_dep = self.meta.remove_deps_answer else: try: remove_dep = raw_input( "\nRemove dependencies (maybe used by " ...
Remove dependencies answer
def available_discounts(cls, user, categories, products): ''' Returns all discounts available to this user for the given categories and products. The discounts also list the available quantity for this user, not including products that are pending purchase. ''' filtered_clauses = cls._f...
Returns all discounts available to this user for the given categories and products. The discounts also list the available quantity for this user, not including products that are pending purchase.
def __access(self, ts): """ Record an API access. """ with self.connection: self.connection.execute("INSERT OR REPLACE INTO access_timestamp (timestamp, domain) VALUES (?, ?)", (ts, self.domain))
Record an API access.
def list_tags(self, pattern: str = None) -> typing.List[str]: """ Returns list of tags, optionally matching "pattern" :param pattern: optional pattern to filter results :type pattern: str :return: existing tags :rtype: list of str """ tags: typing.List[st...
Returns list of tags, optionally matching "pattern" :param pattern: optional pattern to filter results :type pattern: str :return: existing tags :rtype: list of str
def register(self, *model_list, **options): """ Registers the given model(s) with the given databrowse site. The model(s) should be Model classes, not instances. If a databrowse class isn't given, it will use DefaultModelDatabrowse (the default databrowse options). If ...
Registers the given model(s) with the given databrowse site. The model(s) should be Model classes, not instances. If a databrowse class isn't given, it will use DefaultModelDatabrowse (the default databrowse options). If a model is already registered, this will raise AlreadyRegistered...
def get_pdf_from_html(html: str, header_html: str = None, footer_html: str = None, wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME, wkhtmltopdf_options: Dict[str, Any] = None, file_encoding: str = "utf-8", ...
Takes HTML and returns a PDF. See the arguments to :func:`make_pdf_from_html` (except ``on_disk``). Returns: the PDF binary as a ``bytes`` object
def get(self): """ *get the conesearch object* **Return:** - ``conesearch`` .. todo:: - @review: when complete, clean get method - @review: when complete add logging """ self.log.info('starting the ``get`` method') # SEARCH ...
*get the conesearch object* **Return:** - ``conesearch`` .. todo:: - @review: when complete, clean get method - @review: when complete add logging
def syllable_split(string): '''Split 'string' into (stressed) syllables and punctuation/whitespace.''' p = r'\'[%s]+|`[%s]+|[%s]+|[^%s\'`\.]+|[^\.]{1}' % (A, A, A, A) return re.findall(p, string, flags=FLAGS)
Split 'string' into (stressed) syllables and punctuation/whitespace.
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes. """ try: # trap blank fields here if not self.blank or value: v = int(value) ...
Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes.
def _has_data(self): """Check if there is any data""" return any([ len([ v for a in (s[0] if is_list_like(s) else [s]) for v in (a if is_list_like(a) else [a]) if v is not None ]) for s in self.raw_series ])
Check if there is any data
def set_maintext(self, index): """Set the maintext_lb to display text information about the given reftrack :param index: the index :type index: :class:`QtGui.QModelIndex` :returns: None :rtype: None :raises: None """ dr = QtCore.Qt.DisplayRole tex...
Set the maintext_lb to display text information about the given reftrack :param index: the index :type index: :class:`QtGui.QModelIndex` :returns: None :rtype: None :raises: None
def t_PLUS(self, t): r"\+" t.endlexpos = t.lexpos + len(t.value) return t
r"\+
def get_blocks_overview(block_representation_list, coin_symbol='btc', txn_limit=None, api_key=None): ''' Batch request version of get_blocks_overview ''' for block_representation in block_representation_list: assert is_valid_block_representation( block_representation=block_repres...
Batch request version of get_blocks_overview
def match_http_version(entry, http_version, regex=True): """ Helper function that returns entries with a request type matching the given `request_type` argument. :param entry: entry object to analyze :param request_type: ``str`` of request type to match :param regex: ``b...
Helper function that returns entries with a request type matching the given `request_type` argument. :param entry: entry object to analyze :param request_type: ``str`` of request type to match :param regex: ``bool`` indicating whether to use a regex or string match
def url_builder(self, endpoint, *, root=None, params=None, url_params=None): """Create a URL for the specified endpoint. Arguments: endpoint (:py:class:`str`): The API endpoint to access. root: (:py:class:`str`, optional): The root URL for the service API. para...
Create a URL for the specified endpoint. Arguments: endpoint (:py:class:`str`): The API endpoint to access. root: (:py:class:`str`, optional): The root URL for the service API. params: (:py:class:`dict`, optional): The values for format into the created URL...