_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q244600
get_source_url
train
def get_source_url(obj): """Get the source url for a Trust object. Args: obj (ChainOfTrust or LinkOfTrust): the trust object to inspect Raises: CoTError: if repo and source are defined and don't match Returns: str: the source url. """ source_env_prefix = obj.context.c...
python
{ "resource": "" }
q244601
trace_back_to_tree
train
async def trace_back_to_tree(chain): """Trace the chain back to the tree. task.metadata.source: "https://hg.mozilla.org/projects/date//file/a80373508881bfbff67a2a49297c328ff8052572/taskcluster/ci/build" task.payload.env.GECKO_HEAD_REPOSITORY "https://hg.mozilla.org/projects/date/" Args: chain ...
python
{ "resource": "" }
q244602
verify_chain_of_trust
train
async def verify_chain_of_trust(chain): """Build and verify the chain of trust. Args: chain (ChainOfTrust): the chain we're operating on Raises: CoTError: on failure """ log_path = os.path.join(chain.context.config["task_log_dir"], "chain_of_trust.log") scriptworker_log = logg...
python
{ "resource": "" }
q244603
ChainOfTrust.is_try_or_pull_request
train
async def is_try_or_pull_request(self): """Determine if any task in the chain is a try task. Returns: bool: True if a task is a try task. """ tasks = [asyncio.ensure_future(link.is_try_or_pull_request()) for link in self.links]
python
{ "resource": "" }
q244604
ChainOfTrust.get_link
train
def get_link(self, task_id): """Get a ``LinkOfTrust`` by task id. Args: task_id (str): the task id to find. Returns: LinkOfTrust: the link matching the task id.
python
{ "resource": "" }
q244605
ChainOfTrust.get_all_links_in_chain
train
def get_all_links_in_chain(self): """Return all links in the chain of trust, including the target task. By default, we're checking a task and all its dependencies back to the tree, so the full chain is ``self.links`` + ``self``. However, we also support checking the decision task itself...
python
{ "resource": "" }
q244606
AuditLogFormatter.format
train
def format(self, record): """Space debug messages for more legibility.""" if record.levelno ==
python
{ "resource": "" }
q244607
get_version_string
train
def get_version_string(version): """Translate a version tuple into a string. Specify the __version__ as a tuple for more precise comparisons, and translate it to __version_string__ for when that's needed. This function exists primarily for easier unit testing. Args: version (Tuple[int, int,...
python
{ "resource": "" }
q244608
get_unfrozen_copy
train
def get_unfrozen_copy(values): """Recursively convert `value`'s tuple values into lists, and frozendicts into dicts. Args: values (frozendict/tuple): the frozendict/tuple. Returns: values (dict/list): the
python
{ "resource": "" }
q244609
read_worker_creds
train
def read_worker_creds(key="credentials"): """Get credentials from CREDS_FILES or the environment. This looks at the CREDS_FILES in order, and falls back to the environment. Args: key (str, optional): each CREDS_FILE is a json dict. This key's value contains the credentials. Defaults ...
python
{ "resource": "" }
q244610
check_config
train
def check_config(config, path): """Validate the config against DEFAULT_CONFIG. Any unknown keys or wrong types will add error messages. Args: config (dict): the running config. path (str): the path to the config file, used in error messages. Returns: list: the error messages f...
python
{ "resource": "" }
q244611
apply_product_config
train
def apply_product_config(config): """Apply config values that are keyed by `cot_product`. This modifies the passed in configuration. Args: config dict: the config to apply cot_product keying too Returns: dict """ cot_product = config['cot_product'] for key in config: if ...
python
{ "resource": "" }
q244612
create_config
train
def create_config(config_path="scriptworker.yaml"): """Create a config from DEFAULT_CONFIG, arguments, and config file. Then validate it and freeze it. Args: config_path (str, optional): the path to the config file. Defaults to "scriptworker.yaml" Returns: tuple: (config ...
python
{ "resource": "" }
q244613
get_context_from_cmdln
train
def get_context_from_cmdln(args, desc="Run scriptworker"): """Create a Context object from args. Args: args (list): the commandline args. Generally sys.argv Returns: tuple: ``scriptworker.context.Context`` with populated config, and credentials frozendict """ context ...
python
{ "resource": "" }
q244614
get_cot_artifacts
train
def get_cot_artifacts(context): """Generate the artifact relative paths and shas for the chain of trust. Args: context (scriptworker.context.Context): the scriptworker context. Returns: dict: a dictionary of {"path/to/artifact": {"hash_alg": "..."}, ...} """ artifacts = {} fil...
python
{ "resource": "" }
q244615
generate_cot_body
train
def generate_cot_body(context): """Generate the chain of trust dictionary. This is the unsigned and unformatted chain of trust artifact contents. Args: context (scriptworker.context.Context): the scriptworker context. Returns: dict: the unsignd and unformatted chain of trust artifact ...
python
{ "resource": "" }
q244616
generate_cot
train
def generate_cot(context, parent_path=None): """Format and sign the cot body, and write to disk. Args: context (scriptworker.context.Context): the scriptworker context. parent_path (str, optional): The directory to write the chain of trust artifacts to. If None, this is ``artifact_...
python
{ "resource": "" }
q244617
is_github_repo_owner_the_official_one
train
def is_github_repo_owner_the_official_one(context, repo_owner): """Given a repo_owner, check if it matches the one configured to be the official one. Args: context (scriptworker.context.Context): the scriptworker context. repo_owner (str): the repo_owner to verify Raises: scriptwor...
python
{ "resource": "" }
q244618
GitHubRepository.get_tag_hash
train
def get_tag_hash(self, tag_name): """Fetch the commit hash that was tagged with ``tag_name``. Args: tag_name (str): the name of the tag Returns: str: the commit hash linked by the tag """ tag_object = get_single_item_from_sequence( sequence=...
python
{ "resource": "" }
q244619
GitHubRepository.has_commit_landed_on_repository
train
async def has_commit_landed_on_repository(self, context, revision): """Tell if a commit was landed on the repository or if it just comes from a pull request. Args: context (scriptworker.context.Context): the scriptworker context. revision (str): the commit hash or the tag name. ...
python
{ "resource": "" }
q244620
update_logging_config
train
def update_logging_config(context, log_name=None, file_name='worker.log'): """Update python logging settings from config. By default, this sets the ``scriptworker`` log settings, but this will change if some other package calls this function or specifies the ``log_name``. * Use formatting from config ...
python
{ "resource": "" }
q244621
pipe_to_log
train
async def pipe_to_log(pipe, filehandles=(), level=logging.INFO): """Log from a subprocess PIPE. Args: pipe (filehandle): subprocess process STDOUT or STDERR filehandles (list of filehandles, optional): the filehandle(s) to write to. If empty, don't write to a
python
{ "resource": "" }
q244622
get_log_filehandle
train
def get_log_filehandle(context): """Open the log and error filehandles. Args: context (scriptworker.context.Context): the scriptworker context.
python
{ "resource": "" }
q244623
contextual_log_handler
train
def contextual_log_handler(context, path, log_obj=None, level=logging.DEBUG, formatter=None): """Add a short-lived log with a contextmanager for cleanup. Args: context (scriptworker.context.Context): the scriptworker context path (str): the path to the log file to cre...
python
{ "resource": "" }
q244624
upload_artifacts
train
async def upload_artifacts(context, files): """Compress and upload the requested files from ``artifact_dir``, preserving relative paths. Compression only occurs with files known to be supported. This function expects the directory structure in ``artifact_dir`` to remain the same. So if we want the fi...
python
{ "resource": "" }
q244625
compress_artifact_if_supported
train
def compress_artifact_if_supported(artifact_path): """Compress artifacts with GZip if they're known to be supported. This replaces the artifact given by a gzip binary. Args: artifact_path (str): the path to compress Returns: content_type, content_encoding (tuple): Type and encoding o...
python
{ "resource": "" }
q244626
guess_content_type_and_encoding
train
def guess_content_type_and_encoding(path): """Guess the content type of a path, using ``mimetypes``. Falls back to "application/binary" if no content type is found. Args: path (str): the path to guess the mimetype of Returns: str: the content type of the file """ for ext, con...
python
{ "resource": "" }
q244627
create_artifact
train
async def create_artifact(context, path, target_path, content_type, content_encoding, storage_type='s3', expires=None): """Create an artifact and upload it. This should support s3 and azure out of the box; we'll need some tweaking if we want to support redirect/error artifacts. Args: context (...
python
{ "resource": "" }
q244628
get_artifact_url
train
def get_artifact_url(context, task_id, path): """Get a TaskCluster artifact url. Args: context (scriptworker.context.Context): the scriptworker context task_id (str): the task id of the task that published the artifact path (str): the relative path of the artifact
python
{ "resource": "" }
q244629
download_artifacts
train
async def download_artifacts(context, file_urls, parent_dir=None, session=None, download_func=download_file, valid_artifact_task_ids=None): """Download artifacts in parallel after validating their URLs. Valid ``taskId``s for download include the task's dependencies and the ``ta...
python
{ "resource": "" }
q244630
get_upstream_artifacts_full_paths_per_task_id
train
def get_upstream_artifacts_full_paths_per_task_id(context): """List the downloaded upstream artifacts. Args: context (scriptworker.context.Context): the scriptworker context. Returns: dict, dict: lists of the paths to upstream artifacts, sorted by task_id. First dict represents...
python
{ "resource": "" }
q244631
get_and_check_single_upstream_artifact_full_path
train
def get_and_check_single_upstream_artifact_full_path(context, task_id, path): """Return the full path where an upstream artifact is located on disk. Args: context (scriptworker.context.Context): the scriptworker context. task_id (str): the task id of the task that published the artifact ...
python
{ "resource": "" }
q244632
get_single_upstream_artifact_full_path
train
def get_single_upstream_artifact_full_path(context, task_id, path): """Return the full path where an upstream artifact should be located. Artifact may not exist. If you want to be sure if does, use ``get_and_check_single_upstream_artifact_full_path()`` instead. This function is mainly used to move art...
python
{ "resource": "" }
q244633
get_optional_artifacts_per_task_id
train
def get_optional_artifacts_per_task_id(upstream_artifacts): """Return every optional artifact defined in ``upstream_artifacts``, ordered by taskId. Args: upstream_artifacts: the list of upstream artifact definitions Returns: dict: list of paths to downloaded artifacts ordered by taskId ...
python
{ "resource": "" }
q244634
set_chat_description
train
def set_chat_description(chat_id, description, **kwargs): """ Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. :param chat_id: Unique identifier for ...
python
{ "resource": "" }
q244635
send_audio
train
def send_audio(chat_id, audio, caption=None, duration=None, performer=None, title=None, reply_to_message_id=None, reply_markup=None, disable_notification=False, parse_mode=None, **kwargs): """ Use this method to send audio files, if you want Telegram clients to display them in the ...
python
{ "resource": "" }
q244636
unban_chat_member
train
def unban_chat_member(chat_id, user_id, **kwargs): """ Use this method to unban a previously kicked user in a supergroup. The user will not return to the group automatically, but will be able to join via link, etc. The bot must be an administrator in the group for this to work :param chat_id: Unique id...
python
{ "resource": "" }
q244637
get_chat_member
train
def get_chat_member(chat_id, user_id, **kwargs): """ Use this method to get information about a member of a chat :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :param user_id: Unique identifier of the target user :param kwarg...
python
{ "resource": "" }
q244638
get_file
train
def get_file(file_id, **kwargs): """ Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>...
python
{ "resource": "" }
q244639
get_updates
train
def get_updates(offset=None, limit=None, timeout=None, allowed_updates=None, **kwargs): """ Use this method to receive incoming updates using long polling. .. note:: 1. This method will not work if an outgoing webhook is set up. 2. In order to avoid getting duplicate update...
python
{ "resource": "" }
q244640
Client.connect
train
async def connect(self, cluster_id, client_id, nats=None, connect_timeout=DEFAULT_CONNECT_TIMEOUT, max_pub_acks_inflight=DEFAULT_MAX_PUB_ACKS_INFLIGHT, loop=None, ): """ Starts a session with a ...
python
{ "resource": "" }
q244641
Client._process_ack
train
async def _process_ack(self, msg): """ Receives acks from the publishes via the _STAN.acks subscription. """ pub_ack = protocol.PubAck() pub_ack.ParseFromString(msg.data) # Unblock pending acks queue if required. if not
python
{ "resource": "" }
q244642
Client._process_msg
train
async def _process_msg(self, sub): """ Receives the msgs from the STAN subscriptions and replies. By default it will reply back with an ack unless manual acking was specified in one of the subscription options. """ while True: try: raw_msg = aw...
python
{ "resource": "" }
q244643
Client.ack
train
async def ack(self, msg): """ Used to manually acks a message. :param msg: Message which is pending to be acked by client. """ ack_proto = protocol.Ack() ack_proto.subject = msg.proto.subject
python
{ "resource": "" }
q244644
Client.publish
train
async def publish(self, subject, payload, ack_handler=None, ack_wait=DEFAULT_ACK_WAIT, ): """ Publishes a payload onto a subject. By default, it will block until the message which has been published has been acked back. A...
python
{ "resource": "" }
q244645
Client._close
train
async def _close(self): """ Removes any present internal state from the client. """ # Remove the core NATS Streaming subscriptions. try: if self._hb_inbox_sid is not None: await self._nc.unsubscribe(self._hb_inbox_sid) self._hb_inbox =...
python
{ "resource": "" }
q244646
Client.close
train
async def close(self): """ Close terminates a session with NATS Streaming. """ # Remove the core NATS Streaming subscriptions. await self._close() req = protocol.CloseRequest() req.clientID = self._client_id msg = await self._nc.request( self...
python
{ "resource": "" }
q244647
Subscription.unsubscribe
train
async def unsubscribe(self): """ Remove subscription on a topic in this client. """ await self._nc.unsubscribe(self.sid) try: # Stop the processing task for the subscription. sub = self._sc._sub_map[self.inbox] sub._msgs_task.cancel() ...
python
{ "resource": "" }
q244648
datetime_from_ldap
train
def datetime_from_ldap(value): """Convert a LDAP-style datetime to a Python aware object. See https://tools.ietf.org/html/rfc4517#section-3.3.13 for details. Args: value (str): the datetime to parse """ if not value: return None match = LDAP_DATETIME_RE.match(value) if not ...
python
{ "resource": "" }
q244649
LdapFieldMixin.get_db_prep_value
train
def get_db_prep_value(self, value, connection, prepared=False): """Prepare a value for DB interaction. Returns: - list(bytes) if not prepared - list(str) if prepared """ if prepared: return value if value is None: return [] value...
python
{ "resource": "" }
q244650
Model.build_rdn
train
def build_rdn(self): """ Build the Relative Distinguished Name for this entry. """ bits = [] for field in self._meta.fields: if field.db_column and field.primary_key: bits.append("%s=%s" % (field.db_column,
python
{ "resource": "" }
q244651
Model.delete
train
def delete(self, using=None): """ Delete this entry. """ using = using or router.db_for_write(self.__class__, instance=self) connection = connections[using]
python
{ "resource": "" }
q244652
Model._save_table
train
def _save_table(self, raw=False, cls=None, force_insert=None, force_update=None, using=None, update_fields=None): """ Saves the current instance. """ # Connection aliasing connection = connections[using] create = bool(force_insert or not self.dn) # Prepare field...
python
{ "resource": "" }
q244653
Model.scoped
train
def scoped(base_class, base_dn): """ Returns a copy of the current class with a different base_dn. """ class Meta: proxy = True verbose_name = base_class._meta.verbose_name verbose_name_plural = base_class._meta.verbose_name_plural import re ...
python
{ "resource": "" }
q244654
DatabaseWrapper.get_connection_params
train
def get_connection_params(self): """Compute appropriate parameters for establishing a new connection. Computed at system startup. """ return { 'uri': self.settings_dict['NAME'], 'tls': self.settings_dict.get('TLS', False), 'bind_dn': self.settings_dic...
python
{ "resource": "" }
q244655
DatabaseWrapper.get_new_connection
train
def get_new_connection(self, conn_params): """Build a connection from its parameters.""" connection = ldap.ldapobject.ReconnectLDAPObject( uri=conn_params['uri'], retry_max=conn_params['retry_max'], retry_delay=conn_params['retry_delay'], bytes_mode=False)...
python
{ "resource": "" }
q244656
query_as_ldap
train
def query_as_ldap(query, compiler, connection): """Convert a django.db.models.sql.query.Query to a LdapLookup.""" if query.is_empty(): return if query.model._meta.model_name == 'migration' and not hasattr(query.model, 'object_classes'): # FIXME(rbarrois): Support migrations return ...
python
{ "resource": "" }
q244657
where_node_as_ldap
train
def where_node_as_ldap(where, compiler, connection): """Parse a django.db.models.sql.where.WhereNode. Returns: (clause, [params]): the filter clause, with a list of unescaped parameters. """ bits, params = [], [] for item in where.children: if isinstance(item, WhereNode): ...
python
{ "resource": "" }
q244658
SQLCompiler.compile
train
def compile(self, node, *args, **kwargs): """Parse a WhereNode to a LDAP filter string.""" if isinstance(node, WhereNode):
python
{ "resource": "" }
q244659
TreeOperations.to_spans
train
def to_spans(self): "Convert the tree to a set of nonterms and spans." s = set()
python
{ "resource": "" }
q244660
FScore.increment
train
def increment(self, gold_set, test_set): "Add examples from sets." self.gold += len(gold_set) self.test +=
python
{ "resource": "" }
q244661
FScore.output_row
train
def output_row(self, name): "Output a scoring row." print("%10s %4d %0.3f %0.3f %0.3f"%(
python
{ "resource": "" }
q244662
ParseEvaluator.output
train
def output(self): "Print out the f-score table." FScore.output_header() nts = list(self.nt_score.keys())
python
{ "resource": "" }
q244663
invoke
train
def invoke(ctx, data_file): """Invoke the command synchronously""" click.echo('invoking') response = ctx.invoke(data_file.read()) log_data = base64.b64decode(response['LogResult'])
python
{ "resource": "" }
q244664
tail
train
def tail(ctx): """Show the last 10 lines of the log file""" click.echo('tailing logs') for e in ctx.tail()[-10:]: ts
python
{ "resource": "" }
q244665
status
train
def status(ctx): """Print a status of this Lambda function""" status = ctx.status() click.echo(click.style('Policy', bold=True)) if status['policy']: line = ' {} ({})'.format( status['policy']['PolicyName'], status['policy']['Arn']) click.echo(click.style(line,...
python
{ "resource": "" }
q244666
event_sources
train
def event_sources(ctx, command): """List, enable, and disable event sources specified in the config file""" if command == 'list': click.echo('listing event sources') event_sources = ctx.list_event_sources() for es in event_sources: click.echo('arn: {}'.format(es['arn'])) ...
python
{ "resource": "" }
q244667
check_interface_is_subset
train
def check_interface_is_subset(circuit1, circuit2): """ Checks that the interface of circuit1 is a subset of circuit2 Subset is defined as circuit2 contains all the ports of circuit1. Ports are matched by name comparison, then the types are checked to see if one could be converted to another. ""...
python
{ "resource": "" }
q244668
DataTable.CoerceValue
train
def CoerceValue(value, value_type): """Coerces a single value into the type expected for its column. Internal helper method. Args: value: The value which should be converted value_type: One of "string", "number", "boolean", "date", "datetime" or "timeofday". Returns: ...
python
{ "resource": "" }
q244669
DataTable.ColumnTypeParser
train
def ColumnTypeParser(description): """Parses a single column description. Internal helper method. Args: description: a column description in the possible formats: 'id' ('id',) ('id', 'type') ('id', 'type', 'label') ('id', 'type', 'label', {'custom_prop1': 'custom_val1'}...
python
{ "resource": "" }
q244670
DataTable.TableDescriptionParser
train
def TableDescriptionParser(table_description, depth=0): """Parses the table_description object for internal use. Parses the user-submitted table description into an internal format used by the Python DataTable class. Returns the flat list of parsed columns. Args: table_description: A description...
python
{ "resource": "" }
q244671
DataTable.LoadData
train
def LoadData(self, data, custom_properties=None): """Loads new rows to the data table, clearing existing rows. May also set the custom_properties for the added rows. The given custom properties dictionary specifies the dictionary that will be used for *all* given rows. Args: data: The rows t...
python
{ "resource": "" }
q244672
DataTable.AppendData
train
def AppendData(self, data, custom_properties=None): """Appends new data to the table. Data is appended in rows. Data must comply with the table schema passed in to __init__(). See CoerceValue() for a list of acceptable data types. See the class documentation for more information and examples of sch...
python
{ "resource": "" }
q244673
DataTable._InnerAppendData
train
def _InnerAppendData(self, prev_col_values, data, col_index): """Inner function to assist LoadData.""" # We first check that col_index has not exceeded the columns size if col_index >= len(self.__columns): raise DataTableException("The data does not match description, too deep") # Dealing with th...
python
{ "resource": "" }
q244674
DataTable._PreparedData
train
def _PreparedData(self, order_by=()): """Prepares the data for enumeration - sorting it by order_by. Args: order_by: Optional. Specifies the name of the column(s) to sort by, and (optionally) which direction to sort in. Default sort direction is asc. Following formats are ...
python
{ "resource": "" }
q244675
DataTable.ToJSCode
train
def ToJSCode(self, name, columns_order=None, order_by=()): """Writes the data table as a JS code string. This method writes a string of JS code that can be run to generate a DataTable with the specified data. Typically used for debugging only. Args: name: The name of the table. The name woul...
python
{ "resource": "" }
q244676
DataTable.ToHtml
train
def ToHtml(self, columns_order=None, order_by=()): """Writes the data table as an HTML table code string. Args: columns_order: Optional. Specifies the order of columns in the output table. Specify a list of all column IDs in the order in which you want the table ...
python
{ "resource": "" }
q244677
DataTable.ToCsv
train
def ToCsv(self, columns_order=None, order_by=(), separator=","): """Writes the data table as a CSV string. Output is encoded in UTF-8 because the Python "csv" module can't handle Unicode properly according to its documentation. Args: columns_order: Optional. Specifies the order of columns in the...
python
{ "resource": "" }
q244678
DataTable.ToTsvExcel
train
def ToTsvExcel(self, columns_order=None, order_by=()): """Returns a file in tab-separated-format readable by MS Excel. Returns a file in UTF-16 little endian encoding, with tabs separating the values. Args: columns_order: Delegated to ToCsv. order_by: Delegated to ToCsv. Returns: ...
python
{ "resource": "" }
q244679
DataTable._ToJSonObj
train
def _ToJSonObj(self, columns_order=None, order_by=()): """Returns an object suitable to be converted to JSON. Args: columns_order: Optional. A list of all column IDs in the order in which you want them created in the output table. If specified, all column IDs mus...
python
{ "resource": "" }
q244680
DataTable.ToJSon
train
def ToJSon(self, columns_order=None, order_by=()): """Returns a string that can be used in a JS DataTable constructor. This method writes a JSON string that can be passed directly into a Google Visualization API DataTable constructor. Use this output if you are hosting the visualization HTML on your si...
python
{ "resource": "" }
q244681
DataTable.ToJSonResponse
train
def ToJSonResponse(self, columns_order=None, order_by=(), req_id=0, response_handler="google.visualization.Query.setResponse"): """Writes a table as a JSON response that can be returned as-is to a client. This method writes a JSON response to return to a client in response to a Google ...
python
{ "resource": "" }
q244682
DataTable.ToResponse
train
def ToResponse(self, columns_order=None, order_by=(), tqx=""): """Writes the right response according to the request string passed in tqx. This method parses the tqx request string (format of which is defined in the documentation for implementing a data source of Google Visualization), and returns the ...
python
{ "resource": "" }
q244683
AuditLog.copy_fields
train
def copy_fields(self, model): """ Creates copies of the fields we are keeping track of for the provided model, returning a dictionary mapping field name to a copied field object. """ fields = {'__module__' : model.__module__} for field in model._meta.fields: ...
python
{ "resource": "" }
q244684
AuditLog.get_logging_fields
train
def get_logging_fields(self, model): """ Returns a dictionary mapping of the fields that are used for keeping the acutal audit log entries. """ rel_name = '_%s_audit_log_entry'%model._meta.object_name.lower() def entry_instance_to_unicode(log_entry): try: ...
python
{ "resource": "" }
q244685
AuditLog.get_meta_options
train
def get_meta_options(self, model): """ Returns a dictionary of Meta options for the autdit log model. """ result = { 'ordering' : ('-action_date',), 'app_label' : model._meta.app_label, } from django.db.models.options
python
{ "resource": "" }
q244686
AuditLog.create_log_entry_model
train
def create_log_entry_model(self, model): """ Creates a log entry model that will be associated with the model provided. """ attrs = self.copy_fields(model) attrs.update(self.get_logging_fields(model)) attrs.update(Meta
python
{ "resource": "" }
q244687
decode_kempressed
train
def decode_kempressed(bytestring): """subvol not bytestring since numpy conversion is done inside fpzip extension.""" subvol =
python
{ "resource": "" }
q244688
bbox2array
train
def bbox2array(vol, bbox, order='F', readonly=False, lock=None, location=None): """Convenince method for creating a shared memory numpy array based on a CloudVolume and Bbox. c.f. sharedmemory.ndarray for information on the optional lock parameter.""" location = location or vol.shared_memory_id
python
{ "resource": "" }
q244689
ndarray_fs
train
def ndarray_fs(shape, dtype, location, lock, readonly=False, order='F', **kwargs): """Emulate shared memory using the filesystem.""" dbytes = np.dtype(dtype).itemsize nbytes = Vec(*shape).rectVolume() * dbytes directory = mkdir(EMULATED_SHM_DIRECTORY) filename = os.path.join(directory, location) if lock: ...
python
{ "resource": "" }
q244690
cutout
train
def cutout(vol, requested_bbox, steps, channel_slice=slice(None), parallel=1, shared_memory_location=None, output_to_shared_memory=False): """Cutout a requested bounding box from storage and return it as a numpy array.""" global fs_lock cloudpath_bbox = requested_bbox.expand_to_chunk_size(vol.underlying, offs...
python
{ "resource": "" }
q244691
decode
train
def decode(vol, filename, content): """Decode content according to settings in a cloudvolume instance.""" bbox = Bbox.from_filename(filename) content_len = len(content) if content is not None else 0 if not content: if vol.fill_missing: content = '' else: raise EmptyVolumeException(filename)...
python
{ "resource": "" }
q244692
shade
train
def shade(renderbuffer, bufferbbox, img3d, bbox): """Shade a renderbuffer with a downloaded chunk. The buffer will only be painted in the overlapping region of the content.""" if not Bbox.intersects(bufferbbox, bbox): return spt = max2(bbox.minpt, bufferbbox.minpt) ept = min2(bbox.maxpt, bufferbb...
python
{ "resource": "" }
q244693
cdn_cache_control
train
def cdn_cache_control(val): """Translate cdn_cache into a Cache-Control HTTP header.""" if val is None: return 'max-age=3600, s-max-age=3600' elif type(val) is str: return val elif type(val) is bool: if val: return 'max-age=3600, s-max-age=3600' else: return 'no-cache' elif type(va...
python
{ "resource": "" }
q244694
upload_image
train
def upload_image(vol, img, offset, parallel=1, manual_shared_memory_id=None, manual_shared_memory_bbox=None, manual_shared_memory_order='F'): """Upload img to vol with offset. This is the primary entry point for uploads.""" global NON_ALIGNED_WRITE if not np.issubdtype(img.dtype, np.dtype(vol.dtype).type): ...
python
{ "resource": "" }
q244695
decompress
train
def decompress(content, encoding, filename='N/A'): """ Decompress file content. Required: content (bytes): a file to be compressed encoding: None (no compression) or 'gzip' Optional: filename (str:default:'N/A'): Used for debugging messages Raises: NotImplementedError if an unsupported ...
python
{ "resource": "" }
q244696
compress
train
def compress(content, method='gzip'): """ Compresses file content. Required: content (bytes): The information to be compressed method (str, default: 'gzip'): None or gzip Raises: NotImplementedError if an unsupported codec is specified. compression.DecodeError if the encoder has an issue R...
python
{ "resource": "" }
q244697
gunzip
train
def gunzip(content): """ Decompression is applied if the first to bytes matches with the gzip magic numbers. There is once chance in 65536 that a file that is not gzipped will be ungzipped. """ gzip_magic_numbers = [ 0x1f, 0x8b ] first_two_bytes = [ byte for byte in bytearray(content)[:2] ] if first...
python
{ "resource": "" }
q244698
CacheService.flush
train
def flush(self, preserve=None): """ Delete the cache for this dataset. Optionally preserve a region. Helpful when working with overlaping volumes. Warning: the preserve option is not multi-process safe. You're liable to end up deleting the entire cache. Optional: preserve (Bbox: None): P...
python
{ "resource": "" }
q244699
CacheService.flush_region
train
def flush_region(self, region, mips=None): """ Delete a cache region at one or more mip levels bounded by a Bbox for this dataset. Bbox coordinates should be specified in mip 0 coordinates. Required: region (Bbox): Delete cached chunks located partially or entirely within this boundi...
python
{ "resource": "" }