_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q239300
ListTree.list
train
def list(self) -> Iterable[ListEntry]: """Return all the entries in the list tree.""" for entry in self._iter(self._root, ''): yield entry
python
{ "resource": "" }
q239301
ListTree.list_matching
train
def list_matching(self, ref_name: str, filter_: str) \ -> Iterable[ListEntry]: """Return all the entries in the list tree that match the given query. Args: ref_name: Mailbox reference name. filter_: Mailbox name with possible wildcards. """ canonical...
python
{ "resource": "" }
q239302
SynchronizedMessages.get
train
def get(self, uid: int) -> Optional[CachedMessage]: """Return the given cached message. Args: uid: The message UID. """ return self._cache.get(uid)
python
{ "resource": "" }
q239303
SynchronizedMessages.get_all
train
def get_all(self, seq_set: SequenceSet) \ -> Sequence[Tuple[int, CachedMessage]]: """Return the cached messages, and their sequence numbers, for the given sequence set. Args: seq_set: The message sequence set. """ if seq_set.uid: all_uids = s...
python
{ "resource": "" }
q239304
SelectedMailbox.add_updates
train
def add_updates(self, messages: Iterable[CachedMessage], expunged: Iterable[int]) -> None: """Update the messages in the selected mailboxes. The ``messages`` should include non-expunged messages in the mailbox that should be checked for updates. The ``expunged`` argument is t...
python
{ "resource": "" }
q239305
SelectedMailbox.silence
train
def silence(self, seq_set: SequenceSet, flag_set: AbstractSet[Flag], flag_op: FlagOp) -> None: """Runs the flags update against the cached flags, to prevent untagged FETCH responses unless other updates have occurred. For example, if a session adds ``\\Deleted`` and calls this m...
python
{ "resource": "" }
q239306
SelectedMailbox.fork
train
def fork(self, command: Command) \ -> Tuple['SelectedMailbox', Iterable[Response]]: """Compares the state of the current object to that of the last fork, returning the untagged responses that reflect any changes. A new copy of the object is also returned, ready for the next command. ...
python
{ "resource": "" }
q239307
IdleCommand.parse_done
train
def parse_done(self, buf: memoryview) -> Tuple[bool, memoryview]: """Parse the continuation line sent by the client to end the ``IDLE`` command. Args: buf: The continuation line to parse. """ match = self._pattern.match(buf) if not match: raise N...
python
{ "resource": "" }
q239308
Subscriptions.set
train
def set(self, folder: str, subscribed: bool) -> None: """Set the subscribed status of a folder.""" if subscribed: self.add(folder) else: self.remove(folder)
python
{ "resource": "" }
q239309
MailboxSnapshot.new_uid_validity
train
def new_uid_validity(cls) -> int: """Generate a new UID validity value for a mailbox, where the first two bytes are time-based and the second two bytes are random. """ time_part = int(time.time()) % 4096 rand_part = random.randint(0, 1048576) return (time_part << 20) + r...
python
{ "resource": "" }
q239310
MaildirFlags.to_maildir
train
def to_maildir(self, flags: Iterable[Union[bytes, Flag]]) -> str: """Return the string of letter codes that are used to map to defined IMAP flags and keywords. Args: flags: The flags and keywords to map. """ codes = [] for flag in flags: if isins...
python
{ "resource": "" }
q239311
MaildirFlags.from_maildir
train
def from_maildir(self, codes: str) -> FrozenSet[Flag]: """Return the set of IMAP flags that correspond to the letter codes. Args: codes: The letter codes to map. """ flags = set() for code in codes: if code == ',': break to_sy...
python
{ "resource": "" }
q239312
Session.login
train
async def login(cls, credentials: AuthenticationCredentials, config: Config) -> 'Session': """Checks the given credentials for a valid login and returns a new session. The mailbox data is shared between concurrent and future sessions, but only for the lifetime of the process....
python
{ "resource": "" }
q239313
MessageDecoder.of
train
def of(cls, msg_header: MessageHeader) -> 'MessageDecoder': """Return a decoder from the message header object. See Also: :meth:`.of_cte` Args: msg_header: The message header object. """ cte_hdr = msg_header.parsed.content_transfer_encoding retu...
python
{ "resource": "" }
q239314
MessageDecoder.of_cte
train
def of_cte(cls, header: Optional[ContentTransferEncodingHeader]) \ -> 'MessageDecoder': """Return a decoder from the CTE header value. There is built-in support for ``7bit``, ``8bit``, ``quoted-printable``, and ``base64`` CTE header values. Decoders can be added or overridden ...
python
{ "resource": "" }
q239315
Session.find_user
train
async def find_user(cls, config: Config, user: str) \ -> Tuple[str, str]: """If the given user ID exists, return its expected password and mailbox path. Override this method to implement custom login logic. Args: config: The maildir config object. user: The e...
python
{ "resource": "" }
q239316
modutf7_encode
train
def modutf7_encode(data: str) -> bytes: """Encode the string using modified UTF-7. Args: data: The input string to encode. """ ret = bytearray() is_usascii = True encode_start = None for i, symbol in enumerate(data): charpoint = ord(symbol) if is_usascii: ...
python
{ "resource": "" }
q239317
modutf7_decode
train
def modutf7_decode(data: bytes) -> str: """Decode the bytestring using modified UTF-7. Args: data: The encoded bytestring to decode. """ parts = [] is_usascii = True buf = memoryview(data) while buf: byte = buf[0] if is_usascii: if buf[0:2] == b'&-': ...
python
{ "resource": "" }
q239318
BytesFormat.format
train
def format(self, data: Iterable[_FormatArg]) -> bytes: """String interpolation into the format string. Args: data: The data interpolated into the format string. Examples: :: BytesFormat(b'Hello, %b!') % b'World' BytesFormat(b'%b, %b!') %...
python
{ "resource": "" }
q239319
BytesFormat.join
train
def join(self, *data: Iterable[MaybeBytes]) -> bytes: """Iterable join on a delimiter. Args: data: Iterable of items to join. Examples: :: BytesFormat(b' ').join([b'one', b'two', b'three']) """ return self.how.join([bytes(item) for item...
python
{ "resource": "" }
q239320
FilterInterface.apply
train
async def apply(self, sender: str, recipient: str, mailbox: str, append_msg: AppendMessage) \ -> Tuple[Optional[str], AppendMessage]: """Run the filter and return the mailbox where it should be appended, or None to discard, and the message to be appended, which is usually...
python
{ "resource": "" }
q239321
SessionInterface.list_mailboxes
train
async def list_mailboxes(self, ref_name: str, filter_: str, subscribed: bool = False, selected: SelectedMailbox = None) \ -> Tuple[Iterable[Tuple[str, Optional[str], Sequence[bytes]]], Optional[SelectedMailbox]]: """List ...
python
{ "resource": "" }
q239322
SessionInterface.rename_mailbox
train
async def rename_mailbox(self, before_name: str, after_name: str, selected: SelectedMailbox = None) \ -> Optional[SelectedMailbox]: """Renames the mailbox owned by the user. See Also: `RFC 3501 6.3.5. <https://tools.ietf.org/html/rfc3501#...
python
{ "resource": "" }
q239323
SessionInterface.append_messages
train
async def append_messages(self, name: str, messages: Sequence[AppendMessage], selected: SelectedMailbox = None) \ -> Tuple[AppendUid, Optional[SelectedMailbox]]: """Appends a message to the end of the mailbox. See Also: ...
python
{ "resource": "" }
q239324
SessionInterface.select_mailbox
train
async def select_mailbox(self, name: str, readonly: bool = False) \ -> Tuple[MailboxInterface, SelectedMailbox]: """Selects an existing mailbox owned by the user. The returned session is then used as the ``selected`` argument to other methods to fetch mailbox updates. See Al...
python
{ "resource": "" }
q239325
SessionInterface.check_mailbox
train
async def check_mailbox(self, selected: SelectedMailbox, *, wait_on: Event = None, housekeeping: bool = False) -> SelectedMailbox: """Checks for any updates in the mailbox. If ``wait_on`` is given, this method should block until either this ...
python
{ "resource": "" }
q239326
SessionInterface.fetch_messages
train
async def fetch_messages(self, selected: SelectedMailbox, sequence_set: SequenceSet, attributes: FrozenSet[FetchAttribute]) \ -> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]: """Get a list of loaded message objects correspon...
python
{ "resource": "" }
q239327
SessionInterface.search_mailbox
train
async def search_mailbox(self, selected: SelectedMailbox, keys: FrozenSet[SearchKey]) \ -> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]: """Get the messages in the current mailbox that meet all of the given search criteria. See Also: ...
python
{ "resource": "" }
q239328
SessionInterface.copy_messages
train
async def copy_messages(self, selected: SelectedMailbox, sequence_set: SequenceSet, mailbox: str) \ -> Tuple[Optional[CopyUid], SelectedMailbox]: """Copy a set of messages into the given mailbox. See Also: `RFC 3501 6.4.7. ...
python
{ "resource": "" }
q239329
SessionInterface.update_flags
train
async def update_flags(self, selected: SelectedMailbox, sequence_set: SequenceSet, flag_set: FrozenSet[Flag], mode: FlagOp = FlagOp.REPLACE) \ -> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]: """Update...
python
{ "resource": "" }
q239330
FetchRequirement.reduce
train
def reduce(cls, requirements: Iterable['FetchRequirement']) \ -> 'FetchRequirement': """Reduce a set of fetch requirements into a single requirement. Args: requirements: The set of fetch requirements. """ return reduce(lambda x, y: x | y, requirements, cls.NONE)
python
{ "resource": "" }
q239331
SearchKey.requirement
train
def requirement(self) -> FetchRequirement: """Indicates the data required to fulfill this search key.""" key_name = self.key if key_name == b'ALL': return FetchRequirement.NONE elif key_name == b'KEYSET': keyset_reqs = {key.requirement for key in self.filter_key_s...
python
{ "resource": "" }
q239332
Maildir.claim_new
train
def claim_new(self) -> Iterable[str]: """Checks for messages in the ``new`` subdirectory, moving them to ``cur`` and returning their keys. """ new_subdir = self._paths['new'] cur_subdir = self._paths['cur'] for name in os.listdir(new_subdir): new_path = os.pa...
python
{ "resource": "" }
q239333
AdminHandlers.Append
train
async def Append(self, stream) -> None: """Append a message directly to a user's mailbox. If the backend session defines a :attr:`~pymap.interfaces.session.SessionInterface.filter_set`, the active filter implementation will be applied to the appended message, such that the messa...
python
{ "resource": "" }
q239334
FlagOp.apply
train
def apply(self, flag_set: AbstractSet[Flag], operand: AbstractSet[Flag]) \ -> FrozenSet[Flag]: """Apply the flag operation on the two sets, returning the result. Args: flag_set: The flag set being operated on. operand: The flags to use as the operand. """ ...
python
{ "resource": "" }
q239335
SessionFlags.get
train
def get(self, uid: int) -> FrozenSet[Flag]: """Return the session flags for the mailbox session. Args: uid: The message UID value. """ recent = _recent_set if uid in self._recent else frozenset() flags = self._flags.get(uid) return recent if flags is None el...
python
{ "resource": "" }
q239336
SessionFlags.remove
train
def remove(self, uids: Iterable[int]) -> None: """Remove any session flags for the given message. Args: uids: The message UID values. """ for uid in uids: self._recent.discard(uid) self._flags.pop(uid, None)
python
{ "resource": "" }
q239337
SessionFlags.update
train
def update(self, uid: int, flag_set: Iterable[Flag], op: FlagOp = FlagOp.REPLACE) -> FrozenSet[Flag]: """Update the flags for the session, returning the resulting flags. Args: uid: The message UID value. flag_set: The set of flags for the update operation. ...
python
{ "resource": "" }
q239338
get_system_flags
train
def get_system_flags() -> FrozenSet[Flag]: """Return the set of implemented system flags.""" return frozenset({Seen, Recent, Deleted, Flagged, Answered, Draft})
python
{ "resource": "" }
q239339
Commands.register
train
def register(self, cmd: Type[Command]) -> None: """Register a new IMAP command. Args: cmd: The new command type. """ self.commands[cmd.command] = cmd
python
{ "resource": "" }
q239340
ListP.get_as
train
def get_as(self, cls: Type[MaybeBytesT]) -> Sequence[MaybeBytesT]: """Return the list of parsed objects.""" _ = cls # noqa return cast(Sequence[MaybeBytesT], self.items)
python
{ "resource": "" }
q239341
MessageAttributes.get_all
train
def get_all(self, attrs: Iterable[FetchAttribute]) \ -> Sequence[Tuple[FetchAttribute, MaybeBytes]]: """Return a list of tuples containing the attribute iself and the bytes representation of that attribute from the message. Args: attrs: The fetch attributes. """...
python
{ "resource": "" }
q239342
MessageAttributes.get
train
def get(self, attr: FetchAttribute) -> MaybeBytes: """Return the bytes representation of the given message attribue. Args: attr: The fetch attribute. Raises: :class:`NotFetchable` """ attr_name = attr.value.decode('ascii') method = getattr(self,...
python
{ "resource": "" }
q239343
SearchCriteriaSet.sequence_set
train
def sequence_set(self) -> SequenceSet: """The sequence set to use when finding the messages to match against. This will default to all messages unless the search criteria set contains a sequence set. """ try: seqset_crit = next(crit for crit in self.all_criteria ...
python
{ "resource": "" }
q239344
SearchCriteriaSet.matches
train
def matches(self, msg_seq: int, msg: MessageInterface) -> bool: """The message matches if all the defined search key criteria match. Args: msg_seq: The message sequence ID. msg: The message object. """ return all(crit.matches(msg_seq, msg) for crit in self.all_c...
python
{ "resource": "" }
q239345
MessageContent.walk
train
def walk(self) -> Iterable['MessageContent']: """Iterate through the message and all its nested sub-parts in the order they occur. """ if self.body.has_nested: return chain([self], *(part.walk() for part in self.body.nested)) else: return [self]
python
{ "resource": "" }
q239346
MessageContent.parse
train
def parse(cls, data: bytes) -> 'MessageContent': """Parse the bytestring into message content. Args: data: The bytestring to parse. """ lines = cls._find_lines(data) view = memoryview(data) return cls._parse(data, view, lines)
python
{ "resource": "" }
q239347
MessageContent.parse_split
train
def parse_split(cls, header: bytes, body: bytes) -> 'MessageContent': """Parse the header and body bytestrings into message content. Args: header: The header bytestring to parse. body: The body bytestring to parse. """ header_lines = cls._find_lines(header) ...
python
{ "resource": "" }
q239348
UidList.get_all
train
def get_all(self, uids: Iterable[int]) -> Mapping[int, Record]: """Get records by a set of UIDs. Args: uids: The message UIDs. """ return {uid: self._records[uid] for uid in uids if uid in self._records}
python
{ "resource": "" }
q239349
spell
train
def spell(word): """most likely correction for everything up to a double typo""" w = Word(word) candidates = (common([word]) or exact([word]) or known([word]) or known(w.typos()) or common(w.double_typos()) or [word]) correction = max(candidates, key=NLP_COUNTS.get) ...
python
{ "resource": "" }
q239350
words_from_archive
train
def words_from_archive(filename, include_dups=False, map_case=False): """extract words from a text file in the archive""" bz2 = os.path.join(PATH, BZ2) tar_path = '{}/{}'.format('words', filename) with closing(tarfile.open(bz2, 'r:bz2')) as t: with closing(t.extractfile(tar_path)) as f: ...
python
{ "resource": "" }
q239351
parse
train
def parse(lang_sample): """tally word popularity using novel extracts, etc""" words = words_from_archive(lang_sample, include_dups=True) counts = zero_default_dict() for word in words: counts[word] += 1 return set(words), counts
python
{ "resource": "" }
q239352
get_case
train
def get_case(word, correction): """ Best guess of intended case. manchester => manchester chilton => Chilton AAvTech => AAvTech THe => The imho => IMHO """ if word.istitle(): return correction.title() if word.isupper(): return correction.upper() if correctio...
python
{ "resource": "" }
q239353
Word.typos
train
def typos(self): """letter combinations one typo away from word""" return (self._deletes() | self._transposes() | self._replaces() | self._inserts())
python
{ "resource": "" }
q239354
Word.double_typos
train
def double_typos(self): """letter combinations two typos away from word""" return {e2 for e1 in self.typos() for e2 in Word(e1).typos()}
python
{ "resource": "" }
q239355
register
train
def register(lib_name: str, cbl: Callable[[_AsyncLib], None]): ''' Registers a new library function with the current manager. ''' return manager.register(lib_name, cbl)
python
{ "resource": "" }
q239356
init
train
def init(library: typing.Union[str, types.ModuleType]) -> None: ''' Must be called at some point after import and before your event loop is run. Populates the asynclib instance of _AsyncLib with methods relevant to the async library you are using. The supported libraries at the moment are: ...
python
{ "resource": "" }
q239357
run
train
def run(*args, **kwargs): ''' Runs the appropriate library run function. ''' lib = sys.modules[asynclib.lib_name] lib.run(*args, **kwargs)
python
{ "resource": "" }
q239358
SocketWrapper.recv
train
async def recv(self, nbytes: int = -1, **kwargs) -> bytes: ''' Receives some data on the socket. ''' return await asynclib.recv(self.sock, nbytes, **kwargs)
python
{ "resource": "" }
q239359
SocketWrapper.sendall
train
async def sendall(self, data: bytes, *args, **kwargs): ''' Sends some data on the socket. ''' return await asynclib.sendall(self.sock, data, *args, **kwargs)
python
{ "resource": "" }
q239360
SocketWrapper.wrap
train
def wrap(cls, meth): ''' Wraps a connection opening method in this class. ''' async def inner(*args, **kwargs): sock = await meth(*args, **kwargs) return cls(sock) return inner
python
{ "resource": "" }
q239361
Event.set
train
async def set(self, *args, **kwargs): ''' Sets the value of the event. ''' return await _maybe_await(self.event.set(*args, **kwargs))
python
{ "resource": "" }
q239362
_AsyncLibManager.register
train
def register(self, library: str, cbl: Callable[['_AsyncLib'], None]): ''' Registers a callable to set up a library. ''' self._handlers[library] = cbl
python
{ "resource": "" }
q239363
trio_open_connection
train
async def trio_open_connection(host, port, *, ssl=False, **kwargs): ''' Allows connections to be made that may or may not require ssl. Somewhat surprisingly trio doesn't have an abstraction for this like curio even though it's fairly trivial to write. Down the line hopefully. Args: host (st...
python
{ "resource": "" }
q239364
agent
train
def agent(state, host, server=None, port=None): """ Run puppet agent + server: master server URL + port: puppet master port """ args = [] if server: args.append('--server=%s' % server) if port: args.append('--masterport=%s' % port) yield 'puppet agent -t %s' % ' '...
python
{ "resource": "" }
q239365
load_config
train
def load_config(deploy_dir): ''' Loads any local config.py file. ''' config = Config() config_filename = path.join(deploy_dir, 'config.py') if path.exists(config_filename): extract_file_config(config_filename, config) # Now execute the file to trigger loading of any hooks ...
python
{ "resource": "" }
q239366
load_deploy_config
train
def load_deploy_config(deploy_filename, config=None): ''' Loads any local config overrides in the deploy file. ''' if not config: config = Config() if not deploy_filename: return if path.exists(deploy_filename): extract_file_config(deploy_filename, config) return ...
python
{ "resource": "" }
q239367
parse_iptables_rule
train
def parse_iptables_rule(line): ''' Parse one iptables rule. Returns a dict where each iptables code argument is mapped to a name using IPTABLES_ARGS. ''' bits = line.split() definition = {} key = None args = [] not_arg = False def add_args(): arg_string = ' '.join(arg...
python
{ "resource": "" }
q239368
add_op
train
def add_op(state, op_func, *args, **kwargs): ''' Prepare & add an operation to ``pyinfra.state`` by executing it on all hosts. Args: state (``pyinfra.api.State`` obj): the deploy state to add the operation to op_func (function): the operation function from one of the modules, ie ``s...
python
{ "resource": "" }
q239369
add_deploy
train
def add_deploy(state, deploy_func, *args, **kwargs): ''' Prepare & add an deploy to pyinfra.state by executing it on all hosts. Args: state (``pyinfra.api.State`` obj): the deploy state to add the operation deploy_func (function): the operation function from one of the modules, ie `...
python
{ "resource": "" }
q239370
setup_arguments
train
def setup_arguments(arguments): ''' Prepares argumnents output by docopt. ''' # Ensure parallel/port are numbers for key in ('--parallel', '--port', '--fail-percent'): if arguments[key]: try: arguments[key] = int(arguments[key]) except ValueError: ...
python
{ "resource": "" }
q239371
sql
train
def sql( state, host, sql, database=None, # Details for speaking to MySQL via `mysql` CLI mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=None, ): ''' Execute arbitrary SQL against MySQL. + sql: SQL command(s) to execute + database: optional database to open the co...
python
{ "resource": "" }
q239372
dump
train
def dump( state, host, remote_filename, database=None, # Details for speaking to MySQL via `mysql` CLI mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=None, ): ''' Dump a MySQL database into a ``.sql`` file. Requires ``mysqldump``. + database: name of the database to d...
python
{ "resource": "" }
q239373
Inventory.get_host
train
def get_host(self, name, default=NoHostError): ''' Get a single host by name. ''' if name in self.hosts: return self.hosts[name] if default is NoHostError: raise NoHostError('No such host: {0}'.format(name)) return default
python
{ "resource": "" }
q239374
Inventory.get_group
train
def get_group(self, name, default=NoGroupError): ''' Get a list of hosts belonging to a group. ''' if name in self.groups: return self.groups[name] if default is NoGroupError: raise NoGroupError('No such group: {0}'.format(name)) return default
python
{ "resource": "" }
q239375
Inventory.get_groups_data
train
def get_groups_data(self, groups): ''' Gets aggregated data from a list of groups. Vars are collected in order so, for any groups which define the same var twice, the last group's value will hold. ''' data = {} for group in groups: data.update(self.get_group...
python
{ "resource": "" }
q239376
Inventory.get_deploy_data
train
def get_deploy_data(self): ''' Gets any default data attached to the current deploy, if any. ''' if self.state and self.state.deploy_data: return self.state.deploy_data return {}
python
{ "resource": "" }
q239377
config
train
def config( state, host, key, value, repo=None, ): ''' Manage git config for a repository or globally. + key: the key of the config to ensure + value: the value this key should have + repo: specify the git repo path to edit local config (defaults to global) ''' existing_config = ho...
python
{ "resource": "" }
q239378
include
train
def include(filename, hosts=False, when=True): ''' Executes a local python file within the ``pyinfra.pseudo_state.deploy_dir`` directory. Args: hosts (string, list): group name or list of hosts to limit this include to when (bool): indicate whether to trigger operations in this include ...
python
{ "resource": "" }
q239379
GistAPI.send
train
def send(self, request, stem=None): """Prepare and send a request Arguments: request: a Request object that is not yet prepared stem: a path to append to the root URL Returns: The response to the request """ if stem is not None: ...
python
{ "resource": "" }
q239380
GistAPI.list
train
def list(self): """Returns a list of the users gists as GistInfo objects Returns: a list of GistInfo objects """ # Define the basic request. The per_page parameter is set to 100, which # is the maximum github allows. If the user has more than one page of # g...
python
{ "resource": "" }
q239381
GistAPI.create
train
def create(self, request, desc, files, public=False): """Creates a gist Arguments: request: an initial request object desc: the gist description files: a list of files to add to the gist public: a flag to indicate whether the gist is public or not ...
python
{ "resource": "" }
q239382
GistAPI.files
train
def files(self, request, id): """Returns a list of files in the gist Arguments: request: an initial request object id: the gist identifier Returns: A list of the files """ gist = self.send(request, id).json() return gist['files'...
python
{ "resource": "" }
q239383
GistAPI.content
train
def content(self, request, id): """Returns the content of the gist Arguments: request: an initial request object id: the gist identifier Returns: A dict containing the contents of each file in the gist """ gist = self.send(request, id)....
python
{ "resource": "" }
q239384
GistAPI.archive
train
def archive(self, request, id): """Create an archive of a gist The files in the gist are downloaded and added to a compressed archive (tarball). If the ID of the gist was c78d925546e964b4b1df, the resulting archive would be, c78d925546e964b4b1df.tar.gz The archive ...
python
{ "resource": "" }
q239385
GistAPI.edit
train
def edit(self, request, id): """Edit a gist The files in the gist a cloned to a temporary directory and passed to the default editor (defined by the EDITOR environmental variable). When the user exits the editor, they will be provided with a prompt to commit the changes, which w...
python
{ "resource": "" }
q239386
GistAPI.description
train
def description(self, request, id, description): """Updates the description of a gist Arguments: request: an initial request object id: the id of the gist we want to edit the description for description: the new description """ request.d...
python
{ "resource": "" }
q239387
GistAPI.clone
train
def clone(self, id, name=None): """Clone a gist Arguments: id: the gist identifier name: the name to give the cloned repo """ url = 'git@gist.github.com:/{}'.format(id) if name is None: os.system('git clone {}'.format(url)) else: ...
python
{ "resource": "" }
q239388
command
train
def command(state, host, hostname, command, ssh_user=None): ''' Execute commands on other servers over SSH. + hostname: the hostname to connect to + command: the command to execute + ssh_user: connect with this user ''' connection_target = hostname if ssh_user: connection_targe...
python
{ "resource": "" }
q239389
upload
train
def upload( state, host, hostname, filename, remote_filename=None, use_remote_sudo=False, ssh_keyscan=False, ssh_user=None, ): ''' Upload files to other servers using ``scp``. + hostname: hostname to upload to + filename: file to upload + remote_filename: where to upload the file to (de...
python
{ "resource": "" }
q239390
download
train
def download( state, host, hostname, filename, local_filename=None, force=False, ssh_keyscan=False, ssh_user=None, ): ''' Download files from other servers using ``scp``. + hostname: hostname to upload to + filename: file to download + local_filename: where to download the file to (defa...
python
{ "resource": "" }
q239391
pop_op_kwargs
train
def pop_op_kwargs(state, kwargs): ''' Pop and return operation global keyword arguments. ''' meta_kwargs = state.deploy_kwargs or {} def get_kwarg(key, default=None): return kwargs.pop(key, meta_kwargs.get(key, default)) # Get the env for this host: config env followed by command-leve...
python
{ "resource": "" }
q239392
get_template
train
def get_template(filename_or_string, is_string=False): ''' Gets a jinja2 ``Template`` object for the input filename or string, with caching based on the filename of the template, or the SHA1 of the input string. ''' # Cache against string sha or just the filename cache_key = sha1_hash(filename_...
python
{ "resource": "" }
q239393
underscore
train
def underscore(name): ''' Transform CamelCase -> snake_case. ''' s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
python
{ "resource": "" }
q239394
sha1_hash
train
def sha1_hash(string): ''' Return the SHA1 of the input string. ''' hasher = sha1() hasher.update(string.encode()) return hasher.hexdigest()
python
{ "resource": "" }
q239395
make_command
train
def make_command( command, env=None, su_user=None, sudo=False, sudo_user=None, preserve_sudo_env=False, ): ''' Builds a shell command with various kwargs. ''' debug_meta = {} for key, value in ( ('sudo', sudo), ('sudo_user', sudo_user), ('su_user', s...
python
{ "resource": "" }
q239396
make_hash
train
def make_hash(obj): ''' Make a hash from an arbitrary nested dictionary, list, tuple or set, used to generate ID's for operations based on their name & arguments. ''' if isinstance(obj, (set, tuple, list)): hash_string = ''.join([make_hash(e) for e in obj]) elif isinstance(obj, dict): ...
python
{ "resource": "" }
q239397
get_file_sha1
train
def get_file_sha1(filename_or_io): ''' Calculates the SHA1 of a file or file object using a buffer to handle larger files. ''' file_data = get_file_io(filename_or_io) cache_key = file_data.cache_key if cache_key and cache_key in FILE_SHAS: return FILE_SHAS[cache_key] with file_dat...
python
{ "resource": "" }
q239398
read_buffer
train
def read_buffer(io, print_output=False, print_func=None): ''' Reads a file-like buffer object into lines and optionally prints the output. ''' # TODO: research this further - some steps towards handling stdin (ie password requests # from programs that don't notice there's no TTY to accept passwords...
python
{ "resource": "" }
q239399
start
train
def start(state, host, ctid, force=False): ''' Start OpenVZ containers. + ctid: CTID of the container to start + force: whether to force container start ''' args = ['{0}'.format(ctid)] if force: args.append('--force') yield 'vzctl start {0}'.format(' '.join(args))
python
{ "resource": "" }