code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def cli_main(): """Render mustache templates using json files""" import argparse import os def is_file_or_pipe(arg): if not os.path.exists(arg) or os.path.isdir(arg): parser.error('The file {0} does not exist!'.format(arg)) else: return arg def is_dir(arg): ...
Render mustache templates using json files
def checkin_boardingpass(self, code, passenger_name, seat_class, etkt_bnr, seat='', gate='', boarding_time=None, is_cancel=False, qrcode_data=None, card_id=None): """ 飞机票接口 """ data = { 'code': code, 'passe...
飞机票接口
def _import_bin(filename): """Read a .bin file generated by the IRIS Instruments Syscal Pro System Parameters ---------- filename : string Path to input filename Returns ------- metadata : dict General information on the measurement df : :py:class:`pandas.DataFrame` ...
Read a .bin file generated by the IRIS Instruments Syscal Pro System Parameters ---------- filename : string Path to input filename Returns ------- metadata : dict General information on the measurement df : :py:class:`pandas.DataFrame` dataframe containing all meas...
def refresh_db(root=None): ''' Force a repository refresh by calling ``zypper refresh --force``, return a dict:: {'<database name>': Bool} root operate on a different root directory. CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' # Remove rtag file...
Force a repository refresh by calling ``zypper refresh --force``, return a dict:: {'<database name>': Bool} root operate on a different root directory. CLI Example: .. code-block:: bash salt '*' pkg.refresh_db
def create_db_schema(cls, cur, schema_name): """ Create Postgres schema script and execute it on cursor """ create_schema_script = "CREATE SCHEMA {0} ;\n".format(schema_name) cur.execute(create_schema_script)
Create Postgres schema script and execute it on cursor
def hello_user(api_client): """Use an authorized client to fetch and print profile information. Parameters api_client (UberRidesClient) An UberRidesClient with OAuth 2.0 credentials. """ try: response = api_client.get_user_profile() except (ClientError, ServerError) as...
Use an authorized client to fetch and print profile information. Parameters api_client (UberRidesClient) An UberRidesClient with OAuth 2.0 credentials.
def rc4_encrypt(key, data): """ Encrypts plaintext using RC4 with a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :raises: ValueError - when any of the parameters contain an invalid value Ty...
Encrypts plaintext using RC4 with a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are...
def read_char(self, c: str) -> bool: """ Consume the c head byte, increment current index and return True else return False. It use peekchar and it's the same as '' in BNF. """ if self.read_eof(): return False self._stream.save_context() if c == self._...
Consume the c head byte, increment current index and return True else return False. It use peekchar and it's the same as '' in BNF.
def get_absolute(self, points): """Given a set of points geo referenced to this instance, return the points as absolute values. """ # remember if we got a list is_list = isinstance(points, list) points = ensure_numeric(points, num.float) if len(points.shape) == ...
Given a set of points geo referenced to this instance, return the points as absolute values.
def FMErrorByNum( num ): """This function raises an error based on the specified error code.""" if not num in FMErrorNum.keys(): raise FMServerError, (num, FMErrorNum[-1]) elif num == 102: raise FMFieldError, (num, FMErrorNum[num]) else: raise FMServerError, (num, FMErrorNum[num...
This function raises an error based on the specified error code.
async def send_media_group(self, chat_id: typing.Union[base.Integer, base.String], media: typing.Union[types.MediaGroup, typing.List], disable_notification: typing.Union[base.Boolean, None] = None, reply_to_message_id: typing.U...
Use this method to send a group of photos or videos as an album. Source: https://core.telegram.org/bots/api#sendmediagroup :param chat_id: Unique identifier for the target chat or username of the target channel :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :param media:...
def diff_config(jaide, second_host, mode): """ Perform a show | compare with some set commands. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param second_host: The device IP or hostname of the second host to | compare with. @type second_ho...
Perform a show | compare with some set commands. @param jaide: The jaide connection to the device. @type jaide: jaide.Jaide object @param second_host: The device IP or hostname of the second host to | compare with. @type second_host: str @param mode: How to compare the configu...
def rerun(client, revision, roots, siblings, inputs, paths): """Recreate files generated by a sequence of ``run`` commands.""" graph = Graph(client) outputs = graph.build(paths=paths, revision=revision) # Check or extend siblings of outputs. outputs = siblings(graph, outputs) output_paths = {no...
Recreate files generated by a sequence of ``run`` commands.
def load_keypair(keypair_file): '''load a keypair from a keypair file. We add attributes key (the raw key) and public_key (the url prepared public key) to the client. Parameters ========== keypair_file: the pem file to load. ''' from Crypto.PublicKey import RSA # Load key ...
load a keypair from a keypair file. We add attributes key (the raw key) and public_key (the url prepared public key) to the client. Parameters ========== keypair_file: the pem file to load.
def delete_group(self, group_id): """DeleteGroup. :param str group_id: """ route_values = {} if group_id is not None: route_values['groupId'] = self._serialize.url('group_id', group_id, 'str') self._send(http_method='DELETE', location_id='59...
DeleteGroup. :param str group_id:
def content(): """Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.2 :returns: A message object without brand element. :rtype: safe.messaging.message.Message """ message = m.Message() ...
Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.2 :returns: A message object without brand element. :rtype: safe.messaging.message.Message
def compare(self, origin, pattern): """ Args: origin (:obj:`str`): original string pattern (:obj:`str`): Regexp pattern string Returns: bool: True if matches otherwise False. """ if origin is None or pattern is None: return False ...
Args: origin (:obj:`str`): original string pattern (:obj:`str`): Regexp pattern string Returns: bool: True if matches otherwise False.
def compute_pscale(self,cd11,cd21): """ Compute the pixel scale based on active WCS values. """ return N.sqrt(N.power(cd11,2)+N.power(cd21,2)) * 3600.
Compute the pixel scale based on active WCS values.
def _convert_to_folder(self, packages): """ Silverstripe's page contains a list of composer packages. This function converts those to folder names. These may be different due to installer-name. Implemented exponential backoff in order to prevent packager from ...
Silverstripe's page contains a list of composer packages. This function converts those to folder names. These may be different due to installer-name. Implemented exponential backoff in order to prevent packager from being overly sensitive about the number of requests I w...
def to_unitary_matrix( self, qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, qubits_that_should_be_present: Iterable[ops.Qid] = (), ignore_terminal_measurements: bool = True, dtype: Type[np.number] = np.complex128) -> np.ndarray: """Convert...
Converts the circuit into a unitary matrix, if possible. Args: qubit_order: Determines how qubits are ordered when passing matrices into np.kron. qubits_that_should_be_present: Qubits that may or may not appear in operations within the circuit, but that s...
def curve_to(self, x1, y1, x2, y2, x3, y3): """Adds a cubic Bézier spline to the path from the current point to position ``(x3, y3)`` in user-space coordinates, using ``(x1, y1)`` and ``(x2, y2)`` as the control points. After this call the current point will be ``(x3, y3)``. ...
Adds a cubic Bézier spline to the path from the current point to position ``(x3, y3)`` in user-space coordinates, using ``(x1, y1)`` and ``(x2, y2)`` as the control points. After this call the current point will be ``(x3, y3)``. If there is no current point before the call to :m...
def _check_operator(self, operator): """ Check Set-Up This method checks algorithm operator against the expected parent classes Parameters ---------- operator : str Algorithm operator to check """ if not isinstance(operator, type(None)): ...
Check Set-Up This method checks algorithm operator against the expected parent classes Parameters ---------- operator : str Algorithm operator to check
def _get_NTLMv2_response(user_name, password, domain_name, server_challenge, client_challenge, timestamp, target_info): """ [MS-NLMP] v28.0 2016-07-14 2.2.2.8 NTLM V2 Response: NTLMv2_RESPONSE The NTLMv2_RESPONSE strucutre define...
[MS-NLMP] v28.0 2016-07-14 2.2.2.8 NTLM V2 Response: NTLMv2_RESPONSE The NTLMv2_RESPONSE strucutre defines the NTLMv2 authentication NtChallengeResponse in the AUTHENTICATE_MESSAGE. This response is used only when NTLMv2 authentication is configured. The guide on how this is co...
def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'): """ Returns a text object representing 's' -- unicode on Python 2 and str on Python 3. Treats bytestrings using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstanc...
Returns a text object representing 's' -- unicode on Python 2 and str on Python 3. Treats bytestrings using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects.
def transfer_multiple(self, destinations, priority=prio.NORMAL, payment_id=None, unlock_time=0, relay=True): """ Sends a batch of transfers. Returns a list of resulting transactions. :param destinations: a list of destination and amount pairs: [(:clas...
Sends a batch of transfers. Returns a list of resulting transactions. :param destinations: a list of destination and amount pairs: [(:class:`Address <monero.address.Address>`, `Decimal`), ...] :param priority: transaction priority, implies fee. The priority can be a number ...
def OnShiftVideo(self, event): """Shifts through the video""" length = self.player.get_length() time = self.player.get_time() if event.GetWheelRotation() < 0: target_time = max(0, time-length/100.0) elif event.GetWheelRotation() > 0: target_time = min(le...
Shifts through the video
def tob32(val): """Return provided 32 bit value as a string of four bytes.""" ret = bytearray(4) ret[0] = (val>>24)&M8 ret[1] = (val>>16)&M8 ret[2] = (val>>8)&M8 ret[3] = val&M8 return ret
Return provided 32 bit value as a string of four bytes.
def map(self, fn, *iterables, timeout=None, chunksize=1, prefetch=None): """ Collects iterables lazily, rather than immediately. Docstring same as parent: https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor Implmentation taken from this PR: https://githu...
Collects iterables lazily, rather than immediately. Docstring same as parent: https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor Implmentation taken from this PR: https://github.com/python/cpython/pull/707
def loadInstance(self): """ Loads the plugin from the proxy information that was created from the registry file. """ if self._loaded: return self._loaded = True module_path = self.modulePath() package = projex.packageFromPath(module_path) ...
Loads the plugin from the proxy information that was created from the registry file.
def read_excel_file(inputfile, sheet_name): """ Return a matrix containing all the information present in the excel sheet of the specified excel document. :arg inputfile: excel document to read :arg sheetname: the name of the excel sheet to return """ workbook = xlrd.open_workbook(inputfile) ...
Return a matrix containing all the information present in the excel sheet of the specified excel document. :arg inputfile: excel document to read :arg sheetname: the name of the excel sheet to return
def _set_up_pool_config(self): ''' Helper to configure pool options during DatabaseWrapper initialization. ''' self._max_conns = self.settings_dict['OPTIONS'].get('MAX_CONNS', pool_config_defaults['MAX_CONNS']) self._min_conns = self.settings_dict['OPTIONS'].get('MIN_CONNS', self._max_conns) ...
Helper to configure pool options during DatabaseWrapper initialization.
def _as_symbol(value, is_symbol_value=True): """Converts the input to a :class:`SymbolToken` suitable for being emitted as part of a :class:`IonEvent`. If the input has an `as_symbol` method (e.g. :class:`CodePointArray`), it will be converted using that method. Otherwise, it must already be a `SymbolToken...
Converts the input to a :class:`SymbolToken` suitable for being emitted as part of a :class:`IonEvent`. If the input has an `as_symbol` method (e.g. :class:`CodePointArray`), it will be converted using that method. Otherwise, it must already be a `SymbolToken`. In this case, there is nothing to do unless the i...
def i2c_slave_read(self): """Read the bytes from an I2C slave reception. The bytes are returned as a string object. """ data = array.array('B', (0,) * self.BUFFER_SIZE) status, addr, rx_len = api.py_aa_i2c_slave_read_ext(self.handle, self.BUFFER_SIZE, data) ...
Read the bytes from an I2C slave reception. The bytes are returned as a string object.
def _get_pdf_filenames_at(source_directory): """Find all PDF files in the specified directory. Args: source_directory (str): The source directory. Returns: list(str): Filepaths to all PDF files in the specified directory. Raises: ValueError """ if not os.path.isdir(sou...
Find all PDF files in the specified directory. Args: source_directory (str): The source directory. Returns: list(str): Filepaths to all PDF files in the specified directory. Raises: ValueError
def parse_changes(json): """ Gets price changes from JSON Args: json: JSON data as a list of dict dates, where the keys are the raw market statistics. Returns: List of floats of price changes between entries in JSON. """ changes = [] dates = len(json) for date i...
Gets price changes from JSON Args: json: JSON data as a list of dict dates, where the keys are the raw market statistics. Returns: List of floats of price changes between entries in JSON.
def find_by_task(self, task, params={}, **options): """Returns the compact records for all attachments on the task. Parameters ---------- task : {Id} Globally unique identifier for the task. [params] : {Object} Parameters for the request """ path = "/tasks/%s/at...
Returns the compact records for all attachments on the task. Parameters ---------- task : {Id} Globally unique identifier for the task. [params] : {Object} Parameters for the request
def getionimage(p, mz_value, tol=0.1, z=1, reduce_func=sum): """ Get an image representation of the intensity distribution of the ion with specified m/z value. By default, the intensity values within the tolerance region are summed. :param p: the ImzMLParser (or anything else with similar ...
Get an image representation of the intensity distribution of the ion with specified m/z value. By default, the intensity values within the tolerance region are summed. :param p: the ImzMLParser (or anything else with similar attributes) for the desired dataset :param mz_value: m/z valu...
def dispatch(self, *args, **kwargs) -> Awaitable[bool]: """ Create and dispatch an event. This method constructs an event object and then passes it to :meth:`dispatch_event` for the actual dispatching. :param args: positional arguments to the constructor of the associated event...
Create and dispatch an event. This method constructs an event object and then passes it to :meth:`dispatch_event` for the actual dispatching. :param args: positional arguments to the constructor of the associated event class :param kwargs: keyword arguments to the constructor of the as...
def load(self, config, file_object, prefer=None): """ An abstract method that loads from a given file object. :param class config: The config class to load into :param file file_object: The file object to load from :param str prefer: The preferred serialization module name :retu...
An abstract method that loads from a given file object. :param class config: The config class to load into :param file file_object: The file object to load from :param str prefer: The preferred serialization module name :returns: A dictionary converted from the content of the given file...
def func_load(code, defaults=None, closure=None, globs=None): '''Deserialize user defined function.''' if isinstance(code, (tuple, list)): # unpack previous dump code, defaults, closure = code code = marshal.loads(code.encode('raw_unicode_escape')) if globs is None: globs = globals() ...
Deserialize user defined function.
def get_context(self, template): """Get the context for a template. If no matching value is found, an empty context is returned. Otherwise, this returns either the matching value if the value is dictionary-like or the dictionary returned by calling it with *template* if the valu...
Get the context for a template. If no matching value is found, an empty context is returned. Otherwise, this returns either the matching value if the value is dictionary-like or the dictionary returned by calling it with *template* if the value is a function. If several matchin...
async def get_target(config, url): """ Given a URL, get the webmention endpoint """ previous = config.cache.get( 'target', url, schema_version=SCHEMA_VERSION) if config.cache else None headers = previous.caching if previous else None request = await utils.retry_get(config, url, headers=header...
Given a URL, get the webmention endpoint
def call(self, method, args={}, retry=False, retry_policy=None, ticket=None, **props): """Send message to the same actor and return :class:`AsyncResult`.""" ticket = ticket or uuid() reply_q = self.get_reply_queue(ticket) self.cast(method, args, declare=[reply_q], reply_to=t...
Send message to the same actor and return :class:`AsyncResult`.
def _sift_and_init_configs(self, input_dict): """ Removes all key/v for keys that exist in the overall config and activates them. Used to weed out config keys from tokens in a given input. """ configs = {} for k, v in iteritems(input_dict): if (k not in map(str.lo...
Removes all key/v for keys that exist in the overall config and activates them. Used to weed out config keys from tokens in a given input.
def chunk(seq: ActualIterable[T]) -> ActualIterable[ActualIterable[T]]: """ >>> from Redy.Collections import Traversal, Flow >>> x = [1, 1, 2] >>> assert Flow(x)[Traversal.chunk][list].unbox == [[1, 1], [2]] >>> assert Flow([])[Traversal.chunk][list].unbox == [] """ seq = iter(seq) try: ...
>>> from Redy.Collections import Traversal, Flow >>> x = [1, 1, 2] >>> assert Flow(x)[Traversal.chunk][list].unbox == [[1, 1], [2]] >>> assert Flow([])[Traversal.chunk][list].unbox == []
def plotting_context(context=None, font_scale=1, rc=None): """Return a parameter dict to scale elements of the figure. This affects things like the size of the labels, lines, and other elements of the plot, but not the overall style. The base context is "notebook", and the other contexts are "paper", "t...
Return a parameter dict to scale elements of the figure. This affects things like the size of the labels, lines, and other elements of the plot, but not the overall style. The base context is "notebook", and the other contexts are "paper", "talk", and "poster", which are version of the notebook paramete...
def get_namespace_statistics(self, namespace, start_offset, end_offset): """Get namespace statistics for the period between start_offset and end_offset (inclusive)""" cursor = self.cursor cursor.execute('SELECT SUM(data_points), SUM(byte_count) ' 'FROM gauged_stati...
Get namespace statistics for the period between start_offset and end_offset (inclusive)
def init_account(self): """Setup a new GitHub account.""" ghuser = self.api.me() # Setup local access tokens to be used by the webhooks hook_token = ProviderToken.create_personal( 'github-webhook', self.user_id, scopes=['webhooks:event'], i...
Setup a new GitHub account.
def netspeed_by_name(self, hostname): """ Returns NetSpeed name from hostname. Can be Unknown, Dial-up, Cable, or Corporate. :arg hostname: Hostname (e.g. example.com) """ addr = self._gethostbyname(hostname) return self.netspeed_by_addr(addr)
Returns NetSpeed name from hostname. Can be Unknown, Dial-up, Cable, or Corporate. :arg hostname: Hostname (e.g. example.com)
def from_array(array): """ Deserialize a new ReplyKeyboardMarkup from a given dictionary. :return: new ReplyKeyboardMarkup instance. :rtype: ReplyKeyboardMarkup """ if array is None or not array: return None # end if assert_type_or_raise(array...
Deserialize a new ReplyKeyboardMarkup from a given dictionary. :return: new ReplyKeyboardMarkup instance. :rtype: ReplyKeyboardMarkup
def get_command(self, ctx, cmd_name): """Map some aliases to their 'real' names.""" cmd_name = self.MAP.get(cmd_name, cmd_name) return super(AliasedGroup, self).get_command(ctx, cmd_name)
Map some aliases to their 'real' names.
def imagetransformer_sep_channels(): """separate rgb embeddings.""" hparams = imagetransformer_base() hparams.num_heads = 4 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.hidden_size = 256 hparams.filter_size = 512 hparams.num_hidden_layers = 6 return hparams
separate rgb embeddings.
def _GenerateFleetspeakConfig(self, template_dir, rpm_build_dir): """Generates a Fleetspeak config for GRR.""" source_config = os.path.join( template_dir, "fleetspeak", os.path.basename( config.CONFIG.Get( "ClientBuilder.fleetspeak_config_path", context=self.context))...
Generates a Fleetspeak config for GRR.
def do_json_set_many(self, params): """ \x1b[1mNAME\x1b[0m json_set_many - like `json_set`, but for multiple key/value pairs \x1b[1mSYNOPSIS\x1b[0m json_set_many <path> <keys> <value> <value_type> <keys1> <value1> <value_type1> ... \x1b[1mDESCRIPTION\x1b[0m If the key exists and the va...
\x1b[1mNAME\x1b[0m json_set_many - like `json_set`, but for multiple key/value pairs \x1b[1mSYNOPSIS\x1b[0m json_set_many <path> <keys> <value> <value_type> <keys1> <value1> <value_type1> ... \x1b[1mDESCRIPTION\x1b[0m If the key exists and the value is different, the znode will be updated with...
def main(): """This is run if file is directly executed, but not if imported as module. Having this in a separate function allows importing the file into interactive python, and still able to execute the function for testing""" parser = argparse.ArgumentParser() parser.add_argument("-f", "--fil...
This is run if file is directly executed, but not if imported as module. Having this in a separate function allows importing the file into interactive python, and still able to execute the function for testing
def version(): """Return version string.""" with open(os.path.join('curtsies', '__init__.py')) as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
Return version string.
def retract_project_bid(session, bid_id): """ Retract a bid on a project """ headers = { 'Content-Type': 'application/x-www-form-urlencoded' } bid_data = { 'action': 'retract' } # POST /api/projects/0.1/bids/{bid_id}/?action=revoke endpoint = 'bids/{}'.format(bid_id) ...
Retract a bid on a project
def custom_code(self, mask: str = '@###', char: str = '@', digit: str = '#') -> str: """Generate custom code using ascii uppercase and random integers. :param mask: Mask of code. :param char: Placeholder for characters. :param digit: Placeholder for digits. :...
Generate custom code using ascii uppercase and random integers. :param mask: Mask of code. :param char: Placeholder for characters. :param digit: Placeholder for digits. :return: Custom code.
def process(self, event): """Put and process tasks in queue. """ logger.info(f"{self}: put {event.src_path}") self.queue.put(os.path.basename(event.src_path))
Put and process tasks in queue.
def retrieveJsonResponseFromServer(url): """Retrieves a JSON response from the server. Input parameters ---------------- url : url to call for retrieving the JSON response Return ------ A dictionary Exception --------- SIT...
Retrieves a JSON response from the server. Input parameters ---------------- url : url to call for retrieving the JSON response Return ------ A dictionary Exception --------- SITools2Exception when a problem during the download or...
def read_tcp(self, length): """Read Transmission Control Protocol (TCP). Structure of TCP header [RFC 793]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
Read Transmission Control Protocol (TCP). Structure of TCP header [RFC 793]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ...
def build_schema(self, fields): """ Build the schema from fields. :param fields: A list of fields in the index :returns: list of dictionaries Each dictionary has the keys field_name: The name of the field index type: what type of value it is 'multi_va...
Build the schema from fields. :param fields: A list of fields in the index :returns: list of dictionaries Each dictionary has the keys field_name: The name of the field index type: what type of value it is 'multi_valued': if it allows more than one value 'co...
def reflection_matrix_pow(reflection_matrix: np.ndarray, exponent: float): """Raises a matrix with two opposing eigenvalues to a power. Args: reflection_matrix: The matrix to raise to a power. exponent: The power to raise the matrix to. Returns: The given matrix raised to the given...
Raises a matrix with two opposing eigenvalues to a power. Args: reflection_matrix: The matrix to raise to a power. exponent: The power to raise the matrix to. Returns: The given matrix raised to the given power.
def get_app(self, app_id, embed_tasks=False, embed_counts=False, embed_deployments=False, embed_readiness=False, embed_last_task_failure=False, embed_failures=False, embed_task_stats=False): """Get a single app. :param str app_id: application ID :...
Get a single app. :param str app_id: application ID :param bool embed_tasks: embed tasks in result :param bool embed_counts: embed all task counts :param bool embed_deployments: embed all deployment identifier :param bool embed_readiness: embed all readiness check results ...
def disassemble(co, lasti=-1): """Disassemble a code object.""" # Taken from dis.disassemble, returns disassembled code instead of printing # it (the fuck python ?). # Also, unicodified. # Also, use % operator instead of string operations. # Also, one statement per line. out = StringIO() ...
Disassemble a code object.
def log_y_cb(self, w, val): """Toggle linear/log scale for Y-axis.""" self.tab_plot.logy = val self.plot_two_columns()
Toggle linear/log scale for Y-axis.
def changelist_view(self, request, extra_context=None): """Add advanced_filters form to changelist context""" if extra_context is None: extra_context = {} response = self.adv_filters_handle(request, extra_context=extra_context) if re...
Add advanced_filters form to changelist context
def _encode(s, encoding=None, errors=None): """Encodes *s*.""" if encoding is None: encoding = ENCODING if errors is None: errors = ENCODING_ERRORS return s.encode(encoding, errors) if isinstance(s, unicode) else s
Encodes *s*.
def ExtractConfig(self): """This installer extracts a config file from the .pkg file.""" logging.info("Extracting config file from .pkg.") pkg_path = os.environ.get("PACKAGE_PATH", None) if pkg_path is None: logging.error("Could not locate package, giving up.") return zf = zipfile.ZipFi...
This installer extracts a config file from the .pkg file.
def get_params(self): """ returns a list """ value = self._get_lookup(self.operator, self.value) self.params.append(self.value) return self.params
returns a list
def get_instance(self, payload): """ Build an instance of StreamMessageInstance :param dict payload: Payload response from the API :returns: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance :rtype: twilio.rest.sync.v1.service.sync_stream.stream_messa...
Build an instance of StreamMessageInstance :param dict payload: Payload response from the API :returns: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance :rtype: twilio.rest.sync.v1.service.sync_stream.stream_message.StreamMessageInstance
def update_webhook(self, webhook, name=None, metadata=None): """ Updates the specified webhook. One or more of the parameters may be specified. """ return self.manager.update_webhook(self.scaling_group, policy=self, webhook=webhook, name=name, metadata=metadata)
Updates the specified webhook. One or more of the parameters may be specified.
def create(self, name, targetUrl, resource, event, filter=None, secret=None, **request_parameters): """Create a webhook. Args: name(basestring): A user-friendly name for this webhook. targetUrl(basestring): The URL that receives POST requests for e...
Create a webhook. Args: name(basestring): A user-friendly name for this webhook. targetUrl(basestring): The URL that receives POST requests for each event. resource(basestring): The resource type for the webhook. event(basestring): The event type ...
def main(): """ NAME irmaq_magic.py DESCRIPTION plots IRM acquisition curves from measurements file SYNTAX irmaq_magic [command line options] INPUT takes magic formatted magic_measurements.txt files OPTIONS -h prints help message and quits -f FIL...
NAME irmaq_magic.py DESCRIPTION plots IRM acquisition curves from measurements file SYNTAX irmaq_magic [command line options] INPUT takes magic formatted magic_measurements.txt files OPTIONS -h prints help message and quits -f FILE: specify input file, d...
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(Tri...
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict
def add_children(self, *children, **kwargs): """Conveniience function: Adds objects as children in the scene graph.""" for child in children: self.add_child(child, **kwargs)
Conveniience function: Adds objects as children in the scene graph.
def saveSettings(self, settings): """ Records the current structure of the view widget to the inputed \ settings instance. :param settings | <QSettings> """ # record the profile profile = self.saveProfile() key = self.objectName() ...
Records the current structure of the view widget to the inputed \ settings instance. :param settings | <QSettings>
def get_requirements(lookup=None): '''get_requirements reads in requirements and versions from the lookup obtained with get_lookup''' if lookup == None: lookup = get_lookup() install_requires = [] for module in lookup['INSTALL_REQUIRES']: module_name = module[0] module_meta...
get_requirements reads in requirements and versions from the lookup obtained with get_lookup
def _set_exception(self): """Called by a Job object to tell that an exception occured during the processing of the function. The object will become ready but not successful. The collector's notify_ready() method will be called, but NOT the callback method""" assert not self.ready...
Called by a Job object to tell that an exception occured during the processing of the function. The object will become ready but not successful. The collector's notify_ready() method will be called, but NOT the callback method
def load_sbml(filename): """ Load a model from a SBML file. Parameters ---------- filename : str The input SBML filename. Returns ------- model : NetworkModel y0 : dict Initial condition. volume : Real or Real3, optional A size of the simulation volume. ...
Load a model from a SBML file. Parameters ---------- filename : str The input SBML filename. Returns ------- model : NetworkModel y0 : dict Initial condition. volume : Real or Real3, optional A size of the simulation volume.
def fdr(p, q=.05): """ Determine FDR threshold given a p value array and desired false discovery rate q. """ s = np.sort(p) nvox = p.shape[0] null = np.array(range(1, nvox + 1), dtype='float') * q / nvox below = np.where(s <= null)[0] return s[max(below)] if len(below) else -1
Determine FDR threshold given a p value array and desired false discovery rate q.
def send(self, request, ordered=False): """ This method enqueues the given request to be sent. Its send state will be saved until a response arrives, and a ``Future`` that will be resolved when the response arrives will be returned: .. code-block:: python async def ...
This method enqueues the given request to be sent. Its send state will be saved until a response arrives, and a ``Future`` that will be resolved when the response arrives will be returned: .. code-block:: python async def method(): # Sending (enqueued for the send l...
def frequent_signups(self): """Return a QuerySet of activity id's and counts for the activities that a given user has signed up for more than `settings.SIMILAR_THRESHOLD` times""" key = "{}:frequent_signups".format(self.username) cached = cache.get(key) if cached: ret...
Return a QuerySet of activity id's and counts for the activities that a given user has signed up for more than `settings.SIMILAR_THRESHOLD` times
def set_prompt(self, prompt_command="", position=0): """ writes the prompt line """ self.description_docs = u'{}'.format(prompt_command) self.cli.current_buffer.reset( initial_document=Document( self.description_docs, cursor_position=position)) ...
writes the prompt line
def scan_in_memory(node, env, path=()): """ "Scans" a Node.FS.Dir for its in-memory entries. """ try: entries = node.entries except AttributeError: # It's not a Node.FS.Dir (or doesn't look enough like one for # our purposes), which can happen if a target list containing ...
"Scans" a Node.FS.Dir for its in-memory entries.
def symmetrize_compact_force_constants(force_constants, primitive, level=1): """Symmetry force constants by translational and permutation symmetries Parameters ---------- force_constants: ndarray Compact force constan...
Symmetry force constants by translational and permutation symmetries Parameters ---------- force_constants: ndarray Compact force constants. Symmetrized force constants are overwritten. dtype=double shape=(n_patom,n_satom,3,3) primitive: Primitive Primitive cell leve...
def marvcli_comment_list(datasets): """Lists comments for datasets. Output: setid comment_id date time author message """ app = create_app() ids = parse_setids(datasets, dbids=True) comments = db.session.query(Comment)\ .options(db.joinedload(Comment.dataset))\ ...
Lists comments for datasets. Output: setid comment_id date time author message
def add_membership(self, subject_descriptor, container_descriptor): """AddMembership. [Preview API] Create a new membership between a container and subject. :param str subject_descriptor: A descriptor to a group or user that can be the child subject in the relationship. :param str contai...
AddMembership. [Preview API] Create a new membership between a container and subject. :param str subject_descriptor: A descriptor to a group or user that can be the child subject in the relationship. :param str container_descriptor: A descriptor to a group that can be the container in the relati...
def fftconv(a, b, axes=(0, 1)): """ Compute a multi-dimensional convolution via the Discrete Fourier Transform. Note that the output has a phase shift relative to the output of :func:`scipy.ndimage.convolve` with the default ``origin`` parameter. Parameters ---------- a : array_like ...
Compute a multi-dimensional convolution via the Discrete Fourier Transform. Note that the output has a phase shift relative to the output of :func:`scipy.ndimage.convolve` with the default ``origin`` parameter. Parameters ---------- a : array_like Input array b : array_like Inpu...
def mendelian_check(tp1, tp2, tpp, is_xlinked=False): """ Compare TRED calls for Parent1, Parent2 and Proband. """ call_to_ints = lambda x: tuple(int(_) for _ in x.split("|") if _ != ".") tp1_sex, tp1_call = tp1[:2] tp2_sex, tp2_call = tp2[:2] tpp_sex, tpp_call = tpp[:2] # tp1_evidence =...
Compare TRED calls for Parent1, Parent2 and Proband.
def __set_components(self, requisite=True): """ Sets the Components. :param requisite: Set only requisite Components. :type requisite: bool """ components = self.__components_manager.list_components() candidate_components = \ getattr(set(components),...
Sets the Components. :param requisite: Set only requisite Components. :type requisite: bool
def from_lambda(cls, name, lambda_): """Make a :class:`SassFunction` object from the given ``lambda_`` function. Since lambda functions don't have their name, it need its ``name`` as well. Arguments are automatically inspected. :param name: the function name :type name: :class...
Make a :class:`SassFunction` object from the given ``lambda_`` function. Since lambda functions don't have their name, it need its ``name`` as well. Arguments are automatically inspected. :param name: the function name :type name: :class:`str` :param lambda_: the actual lambda...
def version_binary(self): ''' Return version number which is stored in binary format. Returns: str: <major 0-255>.<minior 0-255>.<build 0-65535> or None if not found ''' # Under MSI 'Version' is a 'REG_DWORD' which then sets other registry # values like Displ...
Return version number which is stored in binary format. Returns: str: <major 0-255>.<minior 0-255>.<build 0-65535> or None if not found
def delete_migration(connection, basename): """ Delete a migration in `migrations_applied` table """ # Prepare query sql = "DELETE FROM migrations_applied WHERE name = %s" # Run with connection.cursor() as cursor: cursor.execute(sql, (basename,)) connection.commit() return Tru...
Delete a migration in `migrations_applied` table
def _structure_default(self, obj, cl): """This is the fallthrough case. Everything is a subclass of `Any`. A special condition here handles ``attrs`` classes. Bare optionals end here too (optionals with arguments are unions.) We treat bare optionals as Any. """ if cl is...
This is the fallthrough case. Everything is a subclass of `Any`. A special condition here handles ``attrs`` classes. Bare optionals end here too (optionals with arguments are unions.) We treat bare optionals as Any.
def stop(self): """Stop the timer.""" dd = time() - self._start self.ms = int(round(1000 * dd))
Stop the timer.
def get_(key, recurse=False, profile=None, **kwargs): ''' .. versionadded:: 2014.7.0 Get a value from etcd, by direct path. Returns None on failure. CLI Examples: .. code-block:: bash salt myminion etcd.get /path/to/key salt myminion etcd.get /path/to/key profile=my_etcd_config ...
.. versionadded:: 2014.7.0 Get a value from etcd, by direct path. Returns None on failure. CLI Examples: .. code-block:: bash salt myminion etcd.get /path/to/key salt myminion etcd.get /path/to/key profile=my_etcd_config salt myminion etcd.get /path/to/key recurse=True profile=m...
def update_form_labels(self, request=None, obj=None, form=None): """Returns a form obj after modifying form labels referred to in custom_form_labels. """ for form_label in self.custom_form_labels: if form_label.field in form.base_fields: label = form_label.get...
Returns a form obj after modifying form labels referred to in custom_form_labels.
def load(pathtovector, wordlist=(), num_to_load=None, truncate_embeddings=None, unk_word=None, sep=" "): r""" Read a file in word2vec .txt format. The load function will raise a ValueError when trying to load items which d...
r""" Read a file in word2vec .txt format. The load function will raise a ValueError when trying to load items which do not conform to line lengths. Parameters ---------- pathtovector : string The path to the vector file. header : bool Whe...
def set_actuator_control_target_encode(self, time_usec, group_mlx, target_system, target_component, controls): ''' Set the vehicle attitude and body angular rates. time_usec : Timestamp (micros since boot or Unix epoch) (uint64_t) group_ml...
Set the vehicle attitude and body angular rates. time_usec : Timestamp (micros since boot or Unix epoch) (uint64_t) group_mlx : Actuator group. The "_mlx" indicates this is a multi-instance message and a MAVLink parser should use this field to difference ...