Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
PublicKey.load_pkcs1_openssl_pem
(cls, keyfile)
Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL. These files can be recognised in that they start with BEGIN PUBLIC KEY rather than BEGIN RSA PUBLIC KEY. The contents of the file before the "-----BEGIN PUBLIC KEY-----" and after the "-----END PUBLIC KEY-----" lines is ignored...
Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL.
def load_pkcs1_openssl_pem(cls, keyfile): """Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL. These files can be recognised in that they start with BEGIN PUBLIC KEY rather than BEGIN RSA PUBLIC KEY. The contents of the file before the "-----BEGIN PUBLIC KEY-----" and ...
[ "def", "load_pkcs1_openssl_pem", "(", "cls", ",", "keyfile", ")", ":", "der", "=", "rsa", ".", "pem", ".", "load_pem", "(", "keyfile", ",", "'PUBLIC KEY'", ")", "return", "cls", ".", "load_pkcs1_openssl_der", "(", "der", ")" ]
[ 305, 4 ]
[ 321, 46 ]
python
en
['en', 'fy', 'en']
True
PublicKey.load_pkcs1_openssl_der
(cls, keyfile)
Loads a PKCS#1 DER-encoded public key file from OpenSSL. :param keyfile: contents of a DER-encoded file that contains the public key, from OpenSSL. :return: a PublicKey object :rtype: bytes
Loads a PKCS#1 DER-encoded public key file from OpenSSL.
def load_pkcs1_openssl_der(cls, keyfile): """Loads a PKCS#1 DER-encoded public key file from OpenSSL. :param keyfile: contents of a DER-encoded file that contains the public key, from OpenSSL. :return: a PublicKey object :rtype: bytes """ from rsa.asn1 impo...
[ "def", "load_pkcs1_openssl_der", "(", "cls", ",", "keyfile", ")", ":", "from", "rsa", ".", "asn1", "import", "OpenSSLPubKey", "from", "pyasn1", ".", "codec", ".", "der", "import", "decoder", "from", "pyasn1", ".", "type", "import", "univ", "(", "keyinfo", ...
[ 324, 4 ]
[ 343, 54 ]
python
en
['en', 'fy', 'en']
True
PrivateKey.__getstate__
(self)
Returns the key as tuple for pickling.
Returns the key as tuple for pickling.
def __getstate__(self): """Returns the key as tuple for pickling.""" return self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef
[ "def", "__getstate__", "(", "self", ")", ":", "return", "self", ".", "n", ",", "self", ".", "e", ",", "self", ".", "d", ",", "self", ".", "p", ",", "self", ".", "q", ",", "self", ".", "exp1", ",", "self", ".", "exp2", ",", "self", ".", "coef"...
[ 389, 4 ]
[ 391, 86 ]
python
en
['en', 'en', 'en']
True
PrivateKey.__setstate__
(self, state)
Sets the key from tuple.
Sets the key from tuple.
def __setstate__(self, state): """Sets the key from tuple.""" self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef = state
[ "def", "__setstate__", "(", "self", ",", "state", ")", ":", "self", ".", "n", ",", "self", ".", "e", ",", "self", ".", "d", ",", "self", ".", "p", ",", "self", ".", "q", ",", "self", ".", "exp1", ",", "self", ".", "exp2", ",", "self", ".", ...
[ 393, 4 ]
[ 395, 87 ]
python
en
['en', 'en', 'en']
True
PrivateKey.blinded_decrypt
(self, encrypted)
Decrypts the message using blinding to prevent side-channel attacks. :param encrypted: the encrypted message :type encrypted: int :returns: the decrypted message :rtype: int
Decrypts the message using blinding to prevent side-channel attacks.
def blinded_decrypt(self, encrypted): """Decrypts the message using blinding to prevent side-channel attacks. :param encrypted: the encrypted message :type encrypted: int :returns: the decrypted message :rtype: int """ blind_r = rsa.randnum.randint(self.n - 1) ...
[ "def", "blinded_decrypt", "(", "self", ",", "encrypted", ")", ":", "blind_r", "=", "rsa", ".", "randnum", ".", "randint", "(", "self", ".", "n", "-", "1", ")", "blinded", "=", "self", ".", "blind", "(", "encrypted", ",", "blind_r", ")", "# blind before...
[ 419, 4 ]
[ 433, 47 ]
python
en
['en', 'en', 'en']
True
PrivateKey.blinded_encrypt
(self, message)
Encrypts the message using blinding to prevent side-channel attacks. :param message: the message to encrypt :type message: int :returns: the encrypted message :rtype: int
Encrypts the message using blinding to prevent side-channel attacks.
def blinded_encrypt(self, message): """Encrypts the message using blinding to prevent side-channel attacks. :param message: the message to encrypt :type message: int :returns: the encrypted message :rtype: int """ blind_r = rsa.randnum.randint(self.n - 1) ...
[ "def", "blinded_encrypt", "(", "self", ",", "message", ")", ":", "blind_r", "=", "rsa", ".", "randnum", ".", "randint", "(", "self", ".", "n", "-", "1", ")", "blinded", "=", "self", ".", "blind", "(", "message", ",", "blind_r", ")", "# blind before enc...
[ 435, 4 ]
[ 448, 47 ]
python
en
['en', 'en', 'en']
True
PrivateKey._load_pkcs1_der
(cls, keyfile)
Loads a key in PKCS#1 DER format. :param keyfile: contents of a DER-encoded file that contains the private key. :type keyfile: bytes :return: a PrivateKey object First let's construct a DER encoded key: >>> import base64 >>> b64der = 'MC4CAQACBQDeKYlRAgMBAA...
Loads a key in PKCS#1 DER format.
def _load_pkcs1_der(cls, keyfile): """Loads a key in PKCS#1 DER format. :param keyfile: contents of a DER-encoded file that contains the private key. :type keyfile: bytes :return: a PrivateKey object First let's construct a DER encoded key: >>> import base6...
[ "def", "_load_pkcs1_der", "(", "cls", ",", "keyfile", ")", ":", "from", "pyasn1", ".", "codec", ".", "der", "import", "decoder", "(", "priv", ",", "_", ")", "=", "decoder", ".", "decode", "(", "keyfile", ")", "# ASN.1 contents of DER encoded private key:", "...
[ 451, 4 ]
[ 506, 18 ]
python
en
['en', 'fy', 'en']
True
PrivateKey._save_pkcs1_der
(self)
Saves the private key in PKCS#1 DER format. :returns: the DER-encoded private key. :rtype: bytes
Saves the private key in PKCS#1 DER format.
def _save_pkcs1_der(self): """Saves the private key in PKCS#1 DER format. :returns: the DER-encoded private key. :rtype: bytes """ from pyasn1.type import univ, namedtype from pyasn1.codec.der import encoder class AsnPrivKey(univ.Sequence): componen...
[ "def", "_save_pkcs1_der", "(", "self", ")", ":", "from", "pyasn1", ".", "type", "import", "univ", ",", "namedtype", "from", "pyasn1", ".", "codec", ".", "der", "import", "encoder", "class", "AsnPrivKey", "(", "univ", ".", "Sequence", ")", ":", "componentTy...
[ 508, 4 ]
[ 543, 38 ]
python
en
['en', 'en', 'en']
True
PrivateKey._load_pkcs1_pem
(cls, keyfile)
Loads a PKCS#1 PEM-encoded private key file. The contents of the file before the "-----BEGIN RSA PRIVATE KEY-----" and after the "-----END RSA PRIVATE KEY-----" lines is ignored. :param keyfile: contents of a PEM-encoded file that contains the private key. :type keyfile: by...
Loads a PKCS#1 PEM-encoded private key file.
def _load_pkcs1_pem(cls, keyfile): """Loads a PKCS#1 PEM-encoded private key file. The contents of the file before the "-----BEGIN RSA PRIVATE KEY-----" and after the "-----END RSA PRIVATE KEY-----" lines is ignored. :param keyfile: contents of a PEM-encoded file that contains the priv...
[ "def", "_load_pkcs1_pem", "(", "cls", ",", "keyfile", ")", ":", "der", "=", "rsa", ".", "pem", ".", "load_pem", "(", "keyfile", ",", "b'RSA PRIVATE KEY'", ")", "return", "cls", ".", "_load_pkcs1_der", "(", "der", ")" ]
[ 546, 4 ]
[ 559, 39 ]
python
en
['en', 'sq', 'en']
True
PrivateKey._save_pkcs1_pem
(self)
Saves a PKCS#1 PEM-encoded private key file. :return: contents of a PEM-encoded file that contains the private key. :rtype: bytes
Saves a PKCS#1 PEM-encoded private key file.
def _save_pkcs1_pem(self): """Saves a PKCS#1 PEM-encoded private key file. :return: contents of a PEM-encoded file that contains the private key. :rtype: bytes """ der = self._save_pkcs1_der() return rsa.pem.save_pem(der, b'RSA PRIVATE KEY')
[ "def", "_save_pkcs1_pem", "(", "self", ")", ":", "der", "=", "self", ".", "_save_pkcs1_der", "(", ")", "return", "rsa", ".", "pem", ".", "save_pem", "(", "der", ",", "b'RSA PRIVATE KEY'", ")" ]
[ 561, 4 ]
[ 569, 56 ]
python
en
['en', 'hi-Latn', 'en']
True
create_jwt
(project_id, private_key_file, algorithm)
Creates a JWT (https://jwt.io) to establish an MQTT connection. Args: project_id: The cloud project ID this device belongs to private_key_file: A path to a file containing either an RSA256 or ES256 private key. algorithm: The encryption algorithm to use. Either 'RS256...
Creates a JWT (https://jwt.io) to establish an MQTT connection. Args: project_id: The cloud project ID this device belongs to private_key_file: A path to a file containing either an RSA256 or ES256 private key. algorithm: The encryption algorithm to use. Either 'RS256...
def create_jwt(project_id, private_key_file, algorithm): """Creates a JWT (https://jwt.io) to establish an MQTT connection. Args: project_id: The cloud project ID this device belongs to private_key_file: A path to a file containing either an RSA256 or ES256 private key. ...
[ "def", "create_jwt", "(", "project_id", ",", "private_key_file", ",", "algorithm", ")", ":", "token", "=", "{", "# The time that the token was issued at", "'iat'", ":", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ",", "# The time the token expires.", "'exp...
[ 33, 0 ]
[ 64, 62 ]
python
en
['en', 'gd', 'en']
True
error_str
(rc)
Convert a Paho error to a human readable string.
Convert a Paho error to a human readable string.
def error_str(rc): """Convert a Paho error to a human readable string.""" return '{}: {}'.format(rc, mqtt.error_string(rc))
[ "def", "error_str", "(", "rc", ")", ":", "return", "'{}: {}'", ".", "format", "(", "rc", ",", "mqtt", ".", "error_string", "(", "rc", ")", ")" ]
[ 67, 0 ]
[ 69, 53 ]
python
en
['en', 'gd', 'en']
True
on_connect
(unused_client, unused_userdata, unused_flags, rc)
Callback for when a device connects.
Callback for when a device connects.
def on_connect(unused_client, unused_userdata, unused_flags, rc): """Callback for when a device connects.""" print('on_connect', error_str(rc))
[ "def", "on_connect", "(", "unused_client", ",", "unused_userdata", ",", "unused_flags", ",", "rc", ")", ":", "print", "(", "'on_connect'", ",", "error_str", "(", "rc", ")", ")" ]
[ 72, 0 ]
[ 74, 38 ]
python
en
['en', 'en', 'en']
True
on_disconnect
(unused_client, unused_userdata, rc)
Paho callback for when a device disconnects.
Paho callback for when a device disconnects.
def on_disconnect(unused_client, unused_userdata, rc): """Paho callback for when a device disconnects.""" print('on_disconnect', error_str(rc))
[ "def", "on_disconnect", "(", "unused_client", ",", "unused_userdata", ",", "rc", ")", ":", "print", "(", "'on_disconnect'", ",", "error_str", "(", "rc", ")", ")" ]
[ 77, 0 ]
[ 79, 41 ]
python
en
['en', 'en', 'en']
True
on_publish
(unused_client, unused_userdata, unused_mid)
Paho callback when a message is sent to the broker.
Paho callback when a message is sent to the broker.
def on_publish(unused_client, unused_userdata, unused_mid): """Paho callback when a message is sent to the broker.""" print('on_publish')
[ "def", "on_publish", "(", "unused_client", ",", "unused_userdata", ",", "unused_mid", ")", ":", "print", "(", "'on_publish'", ")" ]
[ 82, 0 ]
[ 84, 23 ]
python
en
['en', 'en', 'en']
True
parse_command_line_args
()
Parse command line arguments.
Parse command line arguments.
def parse_command_line_args(): """Parse command line arguments.""" parser = argparse.ArgumentParser(description=( 'Example Google Cloud IoT Core MQTT device connection code.')) parser.add_argument( '--project_id', default=os.environ.get('GOOGLE_CLOUD_PROJECT'), ...
[ "def", "parse_command_line_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "(", "'Example Google Cloud IoT Core MQTT device connection code.'", ")", ")", "parser", ".", "add_argument", "(", "'--project_id'", ",", "default...
[ 87, 0 ]
[ 135, 30 ]
python
en
['en', 'fr', 'en']
True
KMLSitemap._build_kml_sources
(self, sources)
Go through the given sources and return a 3-tuple of the application label, module name, and field name of every GeometryField encountered in the sources. If no sources are provided, then all models.
Go through the given sources and return a 3-tuple of the application label, module name, and field name of every GeometryField encountered in the sources.
def _build_kml_sources(self, sources): """ Go through the given sources and return a 3-tuple of the application label, module name, and field name of every GeometryField encountered in the sources. If no sources are provided, then all models. """ kml_sources = []...
[ "def", "_build_kml_sources", "(", "self", ",", "sources", ")", ":", "kml_sources", "=", "[", "]", "if", "sources", "is", "None", ":", "sources", "=", "apps", ".", "get_models", "(", ")", "for", "source", "in", "sources", ":", "if", "isinstance", "(", "...
[ 18, 4 ]
[ 42, 26 ]
python
en
['en', 'error', 'th']
False
KMLSitemap.get_urls
(self, page=1, site=None, protocol=None)
This method is overridden so the appropriate `geo_format` attribute is placed on each URL element.
This method is overridden so the appropriate `geo_format` attribute is placed on each URL element.
def get_urls(self, page=1, site=None, protocol=None): """ This method is overridden so the appropriate `geo_format` attribute is placed on each URL element. """ urls = Sitemap.get_urls(self, page=page, site=site, protocol=protocol) for url in urls: url['geo_fo...
[ "def", "get_urls", "(", "self", ",", "page", "=", "1", ",", "site", "=", "None", ",", "protocol", "=", "None", ")", ":", "urls", "=", "Sitemap", ".", "get_urls", "(", "self", ",", "page", "=", "page", ",", "site", "=", "site", ",", "protocol", "=...
[ 44, 4 ]
[ 52, 19 ]
python
en
['en', 'error', 'th']
False
get_args
()
Argument parser. Returns: Dictionary of arguments.
Argument parser.
def get_args(): """Argument parser. Returns: Dictionary of arguments. """ parser = argparse.ArgumentParser() parser.add_argument( '--job-dir', type=str, required=True, help='local or GCS location for writing checkpoints and exporting ' 'models') ...
[ "def", "get_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'--job-dir'", ",", "type", "=", "str", ",", "required", "=", "True", ",", "help", "=", "'local or GCS location for writing checkp...
[ 28, 0 ]
[ 61, 15 ]
python
da
['fr', 'da', 'pt']
False
train_and_evaluate
(args)
Trains and evaluates the Keras model. Uses the Keras model defined in model.py and trains on data loaded and preprocessed in util.py. Saves the trained model in TensorFlow SavedModel format to the path defined in part by the --job-dir argument. Args: args: dictionary of arguments - see get_args(...
Trains and evaluates the Keras model.
def train_and_evaluate(args): """Trains and evaluates the Keras model. Uses the Keras model defined in model.py and trains on data loaded and preprocessed in util.py. Saves the trained model in TensorFlow SavedModel format to the path defined in part by the --job-dir argument. Args: args: di...
[ "def", "train_and_evaluate", "(", "args", ")", ":", "train_x", ",", "train_y", ",", "eval_x", ",", "eval_y", "=", "util", ".", "load_data", "(", ")", "# dimensions", "num_train_examples", ",", "input_dim", "=", "train_x", ".", "shape", "num_eval_examples", "="...
[ 64, 0 ]
[ 123, 54 ]
python
en
['en', 'en', 'en']
True
FileBasedCache._cull
(self)
Remove random cache entries if max_entries is reached at a ratio of num_entries / cull_frequency. A value of 0 for CULL_FREQUENCY means that the entire cache will be purged.
Remove random cache entries if max_entries is reached at a ratio of num_entries / cull_frequency. A value of 0 for CULL_FREQUENCY means that the entire cache will be purged.
def _cull(self): """ Remove random cache entries if max_entries is reached at a ratio of num_entries / cull_frequency. A value of 0 for CULL_FREQUENCY means that the entire cache will be purged. """ filelist = self._list_cache_files() num_entries = len(filelist) ...
[ "def", "_cull", "(", "self", ")", ":", "filelist", "=", "self", ".", "_list_cache_files", "(", ")", "num_entries", "=", "len", "(", "filelist", ")", "if", "num_entries", "<", "self", ".", "_max_entries", ":", "return", "# return early if no culling is required",...
[ 97, 4 ]
[ 113, 31 ]
python
en
['en', 'error', 'th']
False
FileBasedCache._key_to_file
(self, key, version=None)
Convert a key into a cache file path. Basically this is the root cache path joined with the md5sum of the key and a suffix.
Convert a key into a cache file path. Basically this is the root cache path joined with the md5sum of the key and a suffix.
def _key_to_file(self, key, version=None): """ Convert a key into a cache file path. Basically this is the root cache path joined with the md5sum of the key and a suffix. """ key = self.make_key(key, version=version) self.validate_key(key) return os.path.join(self...
[ "def", "_key_to_file", "(", "self", ",", "key", ",", "version", "=", "None", ")", ":", "key", "=", "self", ".", "make_key", "(", "key", ",", "version", "=", "version", ")", "self", ".", "validate_key", "(", "key", ")", "return", "os", ".", "path", ...
[ 124, 4 ]
[ 132, 72 ]
python
en
['en', 'error', 'th']
False
FileBasedCache.clear
(self)
Remove all the cache files.
Remove all the cache files.
def clear(self): """ Remove all the cache files. """ for fname in self._list_cache_files(): self._delete(fname)
[ "def", "clear", "(", "self", ")", ":", "for", "fname", "in", "self", ".", "_list_cache_files", "(", ")", ":", "self", ".", "_delete", "(", "fname", ")" ]
[ 134, 4 ]
[ 139, 31 ]
python
en
['en', 'error', 'th']
False
FileBasedCache._is_expired
(self, f)
Take an open cache file `f` and delete it if it's expired.
Take an open cache file `f` and delete it if it's expired.
def _is_expired(self, f): """ Take an open cache file `f` and delete it if it's expired. """ try: exp = pickle.load(f) except EOFError: exp = 0 # An empty file is considered expired. if exp is not None and exp < time.time(): f.close() ...
[ "def", "_is_expired", "(", "self", ",", "f", ")", ":", "try", ":", "exp", "=", "pickle", ".", "load", "(", "f", ")", "except", "EOFError", ":", "exp", "=", "0", "# An empty file is considered expired.", "if", "exp", "is", "not", "None", "and", "exp", "...
[ 141, 4 ]
[ 153, 20 ]
python
en
['en', 'error', 'th']
False
FileBasedCache._list_cache_files
(self)
Get a list of paths to all the cache files. These are all the files in the root cache dir that end on the cache_suffix.
Get a list of paths to all the cache files. These are all the files in the root cache dir that end on the cache_suffix.
def _list_cache_files(self): """ Get a list of paths to all the cache files. These are all the files in the root cache dir that end on the cache_suffix. """ return [ os.path.join(self._dir, fname) for fname in glob.glob1(self._dir, '*%s' % self.cache_suffi...
[ "def", "_list_cache_files", "(", "self", ")", ":", "return", "[", "os", ".", "path", ".", "join", "(", "self", ".", "_dir", ",", "fname", ")", "for", "fname", "in", "glob", ".", "glob1", "(", "self", ".", "_dir", ",", "'*%s'", "%", "self", ".", "...
[ 155, 4 ]
[ 163, 9 ]
python
en
['en', 'error', 'th']
False
copyfileobj
(fsrc, fdst, length=16*1024)
copy data from file-like object fsrc to file-like object fdst
copy data from file-like object fsrc to file-like object fdst
def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf)
[ "def", "copyfileobj", "(", "fsrc", ",", "fdst", ",", "length", "=", "16", "*", "1024", ")", ":", "while", "1", ":", "buf", "=", "fsrc", ".", "read", "(", "length", ")", "if", "not", "buf", ":", "break", "fdst", ".", "write", "(", "buf", ")" ]
[ 69, 0 ]
[ 75, 23 ]
python
en
['en', 'en', 'en']
True
copyfile
(src, dst)
Copy data from src to dst
Copy data from src to dst
def copyfile(src, dst): """Copy data from src to dst""" if _samefile(src, dst): raise Error("`%s` and `%s` are the same file" % (src, dst)) for fn in [src, dst]: try: st = os.stat(fn) except OSError: # File most likely does not exist pass ...
[ "def", "copyfile", "(", "src", ",", "dst", ")", ":", "if", "_samefile", "(", "src", ",", "dst", ")", ":", "raise", "Error", "(", "\"`%s` and `%s` are the same file\"", "%", "(", "src", ",", "dst", ")", ")", "for", "fn", "in", "[", "src", ",", "dst", ...
[ 89, 0 ]
[ 107, 35 ]
python
en
['en', 'en', 'en']
True
copymode
(src, dst)
Copy mode bits from src to dst
Copy mode bits from src to dst
def copymode(src, dst): """Copy mode bits from src to dst""" if hasattr(os, 'chmod'): st = os.stat(src) mode = stat.S_IMODE(st.st_mode) os.chmod(dst, mode)
[ "def", "copymode", "(", "src", ",", "dst", ")", ":", "if", "hasattr", "(", "os", ",", "'chmod'", ")", ":", "st", "=", "os", ".", "stat", "(", "src", ")", "mode", "=", "stat", ".", "S_IMODE", "(", "st", ".", "st_mode", ")", "os", ".", "chmod", ...
[ 109, 0 ]
[ 114, 27 ]
python
en
['en', 'en', 'en']
True
copystat
(src, dst)
Copy all stat info (mode bits, atime, mtime, flags) from src to dst
Copy all stat info (mode bits, atime, mtime, flags) from src to dst
def copystat(src, dst): """Copy all stat info (mode bits, atime, mtime, flags) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) if hasattr(os, 'chfl...
[ "def", "copystat", "(", "src", ",", "dst", ")", ":", "st", "=", "os", ".", "stat", "(", "src", ")", "mode", "=", "stat", ".", "S_IMODE", "(", "st", ".", "st_mode", ")", "if", "hasattr", "(", "os", ",", "'utime'", ")", ":", "os", ".", "utime", ...
[ 116, 0 ]
[ 130, 21 ]
python
en
['en', 'en', 'en']
True
copy
(src, dst)
Copy data and mode bits ("cp src dst"). The destination may be a directory.
Copy data and mode bits ("cp src dst").
def copy(src, dst): """Copy data and mode bits ("cp src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copymode(src, dst)
[ "def", "copy", "(", "src", ",", "dst", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "dst", ")", ":", "dst", "=", "os", ".", "path", ".", "join", "(", "dst", ",", "os", ".", "path", ".", "basename", "(", "src", ")", ")", "copyfile", ...
[ 132, 0 ]
[ 141, 22 ]
python
en
['en', 'en', 'en']
True
copy2
(src, dst)
Copy data and all stat info ("cp -p src dst"). The destination may be a directory.
Copy data and all stat info ("cp -p src dst").
def copy2(src, dst): """Copy data and all stat info ("cp -p src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copystat(src, dst)
[ "def", "copy2", "(", "src", ",", "dst", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "dst", ")", ":", "dst", "=", "os", ".", "path", ".", "join", "(", "dst", ",", "os", ".", "path", ".", "basename", "(", "src", ")", ")", "copyfile", ...
[ 143, 0 ]
[ 152, 22 ]
python
en
['en', 'en', 'en']
True
ignore_patterns
(*patterns)
Function that can be used as copytree() ignore parameter. Patterns is a sequence of glob-style patterns that are used to exclude files
Function that can be used as copytree() ignore parameter.
def ignore_patterns(*patterns): """Function that can be used as copytree() ignore parameter. Patterns is a sequence of glob-style patterns that are used to exclude files""" def _ignore_patterns(path, names): ignored_names = [] for pattern in patterns: ignored_names.extend(fn...
[ "def", "ignore_patterns", "(", "*", "patterns", ")", ":", "def", "_ignore_patterns", "(", "path", ",", "names", ")", ":", "ignored_names", "=", "[", "]", "for", "pattern", "in", "patterns", ":", "ignored_names", ".", "extend", "(", "fnmatch", ".", "filter"...
[ 154, 0 ]
[ 164, 27 ]
python
en
['en', 'en', 'en']
True
copytree
(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)
Recursively copy a directory tree. The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the cont...
Recursively copy a directory tree.
def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False): """Recursively copy a directory tree. The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag...
[ "def", "copytree", "(", "src", ",", "dst", ",", "symlinks", "=", "False", ",", "ignore", "=", "None", ",", "copy_function", "=", "copy2", ",", "ignore_dangling_symlinks", "=", "False", ")", ":", "names", "=", "os", ".", "listdir", "(", "src", ")", "if"...
[ 166, 0 ]
[ 246, 27 ]
python
en
['en', 'en', 'en']
True
rmtree
(path, ignore_errors=False, onerror=None)
Recursively delete a directory tree. If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and ...
Recursively delete a directory tree.
def rmtree(path, ignore_errors=False, onerror=None): """Recursively delete a directory tree. If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is th...
[ "def", "rmtree", "(", "path", ",", "ignore_errors", "=", "False", ",", "onerror", "=", "None", ")", ":", "if", "ignore_errors", ":", "def", "onerror", "(", "*", "args", ")", ":", "pass", "elif", "onerror", "is", "None", ":", "def", "onerror", "(", "*...
[ 248, 0 ]
[ 294, 47 ]
python
en
['en', 'en', 'en']
True
move
(src, dst)
Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination already exists but is not a d...
Recursively move a file or directory to another location. This is similar to the Unix "mv" command.
def move(src, dst): """Recursively move a file or directory to another location. This is similar to the Unix "mv" command. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist. If the destination al...
[ "def", "move", "(", "src", ",", "dst", ")", ":", "real_dst", "=", "dst", "if", "os", ".", "path", ".", "isdir", "(", "dst", ")", ":", "if", "_samefile", "(", "src", ",", "dst", ")", ":", "# We might be on a case insensitive filesystem,", "# perform the ren...
[ 302, 0 ]
[ 340, 26 ]
python
en
['en', 'en', 'en']
True
_get_gid
(name)
Returns a gid, given a group name.
Returns a gid, given a group name.
def _get_gid(name): """Returns a gid, given a group name.""" if getgrnam is None or name is None: return None try: result = getgrnam(name) except KeyError: result = None if result is not None: return result[2] return None
[ "def", "_get_gid", "(", "name", ")", ":", "if", "getgrnam", "is", "None", "or", "name", "is", "None", ":", "return", "None", "try", ":", "result", "=", "getgrnam", "(", "name", ")", "except", "KeyError", ":", "result", "=", "None", "if", "result", "i...
[ 351, 0 ]
[ 361, 15 ]
python
en
['en', 'en', 'en']
True
_get_uid
(name)
Returns an uid, given a user name.
Returns an uid, given a user name.
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
[ "def", "_get_uid", "(", "name", ")", ":", "if", "getpwnam", "is", "None", "or", "name", "is", "None", ":", "return", "None", "try", ":", "result", "=", "getpwnam", "(", "name", ")", "except", "KeyError", ":", "result", "=", "None", "if", "result", "i...
[ 363, 0 ]
[ 373, 15 ]
python
en
['en', 'en', 'en']
True
_make_tarball
(base_name, base_dir, compress="gzip", verbose=0, dry_run=0, owner=None, group=None, logger=None)
Create a (possibly compressed) tar file from all the files under 'base_dir'. 'compress' must be "gzip" (the default), "bzip2", or None. 'owner' and 'group' can be used to define an owner and a group for the archive that is being built. If not provided, the current owner and group will be used. ...
Create a (possibly compressed) tar file from all the files under 'base_dir'.
def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create a (possibly compressed) tar file from all the files under 'base_dir'. 'compress' must be "gzip" (the default), "bzip2", or None. 'owner' and 'group' can be us...
[ "def", "_make_tarball", "(", "base_name", ",", "base_dir", ",", "compress", "=", "\"gzip\"", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "owner", "=", "None", ",", "group", "=", "None", ",", "logger", "=", "None", ")", ":", "tar_compressio...
[ 375, 0 ]
[ 435, 23 ]
python
en
['en', 'en', 'en']
True
_make_zipfile
(base_name, base_dir, verbose=0, dry_run=0, logger=None)
Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default search path). If neither tool is available, raises ExecError. Retu...
Create a zip file from all the files under 'base_dir'.
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_name' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on th...
[ "def", "_make_zipfile", "(", "base_name", ",", "base_dir", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "logger", "=", "None", ")", ":", "zip_filename", "=", "base_name", "+", "\".zip\"", "archive_dir", "=", "os", ".", "path", ".", "dirname",...
[ 454, 0 ]
[ 499, 23 ]
python
en
['en', 'en', 'en']
True
get_archive_formats
()
Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description)
Returns a list of supported formats for archiving and unarchiving.
def get_archive_formats(): """Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) """ formats = [(name, registry[2]) for name, registry in _ARCHIVE_FORMATS.items()] formats.sort() return formats
[ "def", "get_archive_formats", "(", ")", ":", "formats", "=", "[", "(", "name", ",", "registry", "[", "2", "]", ")", "for", "name", ",", "registry", "in", "_ARCHIVE_FORMATS", ".", "items", "(", ")", "]", "formats", ".", "sort", "(", ")", "return", "fo...
[ 512, 0 ]
[ 520, 18 ]
python
en
['en', 'en', 'en']
True
register_archive_format
(name, function, extra_args=None, description='')
Registers an archive format. name is the name of the format. function is the callable that will be used to create archives. If provided, extra_args is a sequence of (name, value) tuples that will be passed as arguments to the callable. description can be provided to describe the format, and will be ret...
Registers an archive format.
def register_archive_format(name, function, extra_args=None, description=''): """Registers an archive format. name is the name of the format. function is the callable that will be used to create archives. If provided, extra_args is a sequence of (name, value) tuples that will be passed as arguments to ...
[ "def", "register_archive_format", "(", "name", ",", "function", ",", "extra_args", "=", "None", ",", "description", "=", "''", ")", ":", "if", "extra_args", "is", "None", ":", "extra_args", "=", "[", "]", "if", "not", "isinstance", "(", "function", ",", ...
[ 522, 0 ]
[ 541, 64 ]
python
en
['en', 'en', 'en']
True
make_archive
(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None)
Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", "bztar" or "gztar". 'root_dir' is a directory that will be the root directory of the archive; ie. we typically chdir int...
Create an archive file (eg. zip or tar).
def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None): """Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one ...
[ "def", "make_archive", "(", "base_name", ",", "format", ",", "root_dir", "=", "None", ",", "base_dir", "=", "None", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "owner", "=", "None", ",", "group", "=", "None", ",", "logger", "=", "None", ...
[ 546, 0 ]
[ 598, 19 ]
python
en
['en', 'gd', 'en']
True
get_unpack_formats
()
Returns a list of supported formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description)
Returns a list of supported formats for unpacking.
def get_unpack_formats(): """Returns a list of supported formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description) """ formats = [(name, info[0], info[3]) for name, info in _UNPACK_FORMATS.items()] formats.sort() return formats
[ "def", "get_unpack_formats", "(", ")", ":", "formats", "=", "[", "(", "name", ",", "info", "[", "0", "]", ",", "info", "[", "3", "]", ")", "for", "name", ",", "info", "in", "_UNPACK_FORMATS", ".", "items", "(", ")", "]", "formats", ".", "sort", "...
[ 601, 0 ]
[ 610, 18 ]
python
en
['en', 'en', 'en']
True
_check_unpack_options
(extensions, function, extra_args)
Checks what gets registered as an unpacker.
Checks what gets registered as an unpacker.
def _check_unpack_options(extensions, function, extra_args): """Checks what gets registered as an unpacker.""" # first make sure no other unpacker is registered for this extension existing_extensions = {} for name, info in _UNPACK_FORMATS.items(): for ext in info[0]: existing_extensi...
[ "def", "_check_unpack_options", "(", "extensions", ",", "function", ",", "extra_args", ")", ":", "# first make sure no other unpacker is registered for this extension", "existing_extensions", "=", "{", "}", "for", "name", ",", "info", "in", "_UNPACK_FORMATS", ".", "items"...
[ 612, 0 ]
[ 627, 69 ]
python
en
['en', 'en', 'en']
True
register_unpack_format
(name, extensions, function, extra_args=None, description='')
Registers an unpack format. `name` is the name of the format. `extensions` is a list of extensions corresponding to the format. `function` is the callable that will be used to unpack archives. The callable will receive archives to unpack. If it's unable to handle an archive, it needs to raise a Re...
Registers an unpack format.
def register_unpack_format(name, extensions, function, extra_args=None, description=''): """Registers an unpack format. `name` is the name of the format. `extensions` is a list of extensions corresponding to the format. `function` is the callable that will be used to unp...
[ "def", "register_unpack_format", "(", "name", ",", "extensions", ",", "function", ",", "extra_args", "=", "None", ",", "description", "=", "''", ")", ":", "if", "extra_args", "is", "None", ":", "extra_args", "=", "[", "]", "_check_unpack_options", "(", "exte...
[ 630, 0 ]
[ 650, 73 ]
python
en
['en', 'fr', 'en']
True
unregister_unpack_format
(name)
Removes the pack format from the registry.
Removes the pack format from the registry.
def unregister_unpack_format(name): """Removes the pack format from the registry.""" del _UNPACK_FORMATS[name]
[ "def", "unregister_unpack_format", "(", "name", ")", ":", "del", "_UNPACK_FORMATS", "[", "name", "]" ]
[ 652, 0 ]
[ 654, 29 ]
python
en
['en', 'en', 'en']
True
_ensure_directory
(path)
Ensure that the parent directory of `path` exists
Ensure that the parent directory of `path` exists
def _ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) if not os.path.isdir(dirname): os.makedirs(dirname)
[ "def", "_ensure_directory", "(", "path", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")" ]
[ 656, 0 ]
[ 660, 28 ]
python
en
['en', 'en', 'en']
True
_unpack_zipfile
(filename, extract_dir)
Unpack zip `filename` to `extract_dir`
Unpack zip `filename` to `extract_dir`
def _unpack_zipfile(filename, extract_dir): """Unpack zip `filename` to `extract_dir` """ try: import zipfile except ImportError: raise ReadError('zlib not supported, cannot unpack this archive.') if not zipfile.is_zipfile(filename): raise ReadError("%s is not a zip file" % ...
[ "def", "_unpack_zipfile", "(", "filename", ",", "extract_dir", ")", ":", "try", ":", "import", "zipfile", "except", "ImportError", ":", "raise", "ReadError", "(", "'zlib not supported, cannot unpack this archive.'", ")", "if", "not", "zipfile", ".", "is_zipfile", "(...
[ 662, 0 ]
[ 697, 19 ]
python
en
['en', 'nl', 'ur']
False
_unpack_tarfile
(filename, extract_dir)
Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`
def _unpack_tarfile(filename, extract_dir): """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` """ try: tarobj = tarfile.open(filename) except tarfile.TarError: raise ReadError( "%s is not a compressed or uncompressed tar file" % filename) try: tarobj.extrac...
[ "def", "_unpack_tarfile", "(", "filename", ",", "extract_dir", ")", ":", "try", ":", "tarobj", "=", "tarfile", ".", "open", "(", "filename", ")", "except", "tarfile", ".", "TarError", ":", "raise", "ReadError", "(", "\"%s is not a compressed or uncompressed tar fi...
[ 699, 0 ]
[ 710, 22 ]
python
en
['en', 'id', 'hi']
False
unpack_archive
(filename, extract_dir=None, format=None)
Unpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive is unpacked. If not provided, the current working directory is used. `format` is the archive format: one of "zip", "tar", or "gztar". Or any other registered format. If n...
Unpack an archive.
def unpack_archive(filename, extract_dir=None, format=None): """Unpack an archive. `filename` is the name of the archive. `extract_dir` is the name of the target directory, where the archive is unpacked. If not provided, the current working directory is used. `format` is the archive format: one o...
[ "def", "unpack_archive", "(", "filename", ",", "extract_dir", "=", "None", ",", "format", "=", "None", ")", ":", "if", "extract_dir", "is", "None", ":", "extract_dir", "=", "os", ".", "getcwd", "(", ")", "if", "format", "is", "not", "None", ":", "try",...
[ 729, 0 ]
[ 763, 45 ]
python
de
['en', 'fr', 'de']
False
hello_monkey
()
Respond to incoming calls with a simple text message.
Respond to incoming calls with a simple text message.
def hello_monkey(): """Respond to incoming calls with a simple text message.""" resp = MessagingResponse() resp.message("Hello, Mobile Monkey") return str(resp)
[ "def", "hello_monkey", "(", ")", ":", "resp", "=", "MessagingResponse", "(", ")", "resp", ".", "message", "(", "\"Hello, Mobile Monkey\"", ")", "return", "str", "(", "resp", ")" ]
[ 8, 0 ]
[ 13, 20 ]
python
en
['en', 'en', 'en']
True
BaseMemcachedCache._cache
(self)
Implement transparent thread-safe access to a memcached client.
Implement transparent thread-safe access to a memcached client.
def _cache(self): """ Implement transparent thread-safe access to a memcached client. """ return self._class(self.client_servers, **self._options)
[ "def", "_cache", "(", "self", ")", ":", "return", "self", ".", "_class", "(", "self", ".", "client_servers", ",", "*", "*", "self", ".", "_options", ")" ]
[ 35, 4 ]
[ 39, 64 ]
python
en
['en', 'error', 'th']
False
BaseMemcachedCache.get_backend_timeout
(self, timeout=DEFAULT_TIMEOUT)
Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout.
Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout.
def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): """ Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout. """ if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout if timeo...
[ "def", "get_backend_timeout", "(", "self", ",", "timeout", "=", "DEFAULT_TIMEOUT", ")", ":", "if", "timeout", "==", "DEFAULT_TIMEOUT", ":", "timeout", "=", "self", ".", "default_timeout", "if", "timeout", "is", "None", ":", "# Using 0 in memcache sets a non-expiring...
[ 41, 4 ]
[ 66, 27 ]
python
en
['en', 'error', 'th']
False
FilesystemTables.create
(self: "FilesystemTables", schema: Schema, table_identifier: str, spec: PartitionSpec = None, properties: dict = None, location: str = None)
Create a new table on the filesystem. Note: it is expected that the filesystem has atomic operations to ensure consistency for metadata updates. Filesystems that don't have this guarantee could lead to data loss. Location should always be None as the table location on disk is taken fr...
Create a new table on the filesystem.
def create(self: "FilesystemTables", schema: Schema, table_identifier: str, spec: PartitionSpec = None, properties: dict = None, location: str = None) -> Table: """ Create a new table on the filesystem. Note: it is expected that the filesystem has atomic operations to ensure cons...
[ "def", "create", "(", "self", ":", "\"FilesystemTables\"", ",", "schema", ":", "Schema", ",", "table_identifier", ":", "str", ",", "spec", ":", "PartitionSpec", "=", "None", ",", "properties", ":", "dict", "=", "None", ",", "location", ":", "str", "=", "...
[ 37, 4 ]
[ 58, 47 ]
python
en
['en', 'error', 'th']
False
load_cdll
(name, macos10_16_path)
Loads a CDLL by name, falling back to known path on 10.16+
Loads a CDLL by name, falling back to known path on 10.16+
def load_cdll(name, macos10_16_path): """Loads a CDLL by name, falling back to known path on 10.16+""" try: # Big Sur is technically 11 but we use 10.16 due to the Big Sur # beta being labeled as 10.16. if version_info >= (10, 16): path = macos10_16_path else: ...
[ "def", "load_cdll", "(", "name", ",", "macos10_16_path", ")", ":", "try", ":", "# Big Sur is technically 11 but we use 10.16 due to the Big Sur", "# beta being labeled as 10.16.", "if", "version_info", ">=", "(", "10", ",", "16", ")", ":", "path", "=", "macos10_16_path"...
[ 64, 0 ]
[ 77, 77 ]
python
en
['en', 'en', 'en']
True
handle_userJoined
(bot, user, channel)
Automatically give operator status to admins
Automatically give operator status to admins
def handle_userJoined(bot, user, channel): "Automatically give operator status to admins" if permissions(user) >= 10: bot.mode(channel, True, 'o', user=get_nick(user))
[ "def", "handle_userJoined", "(", "bot", ",", "user", ",", "channel", ")", ":", "if", "permissions", "(", "user", ")", ">=", "10", ":", "bot", ".", "mode", "(", "channel", ",", "True", ",", "'o'", ",", "user", "=", "get_nick", "(", "user", ")", ")" ...
[ 1, 0 ]
[ 4, 57 ]
python
en
['en', 'en', 'en']
True
_get_all_permissions
(opts)
Return (codename, name) for all permissions in the given opts.
Return (codename, name) for all permissions in the given opts.
def _get_all_permissions(opts): """ Return (codename, name) for all permissions in the given opts. """ return [*_get_builtin_permissions(opts), *opts.permissions]
[ "def", "_get_all_permissions", "(", "opts", ")", ":", "return", "[", "*", "_get_builtin_permissions", "(", "opts", ")", ",", "*", "opts", ".", "permissions", "]" ]
[ 13, 0 ]
[ 17, 63 ]
python
en
['en', 'error', 'th']
False
_get_builtin_permissions
(opts)
Return (codename, name) for all autogenerated permissions. By default, this is ('add', 'change', 'delete', 'view')
Return (codename, name) for all autogenerated permissions. By default, this is ('add', 'change', 'delete', 'view')
def _get_builtin_permissions(opts): """ Return (codename, name) for all autogenerated permissions. By default, this is ('add', 'change', 'delete', 'view') """ perms = [] for action in opts.default_permissions: perms.append(( get_permission_codename(action, opts), ...
[ "def", "_get_builtin_permissions", "(", "opts", ")", ":", "perms", "=", "[", "]", "for", "action", "in", "opts", ".", "default_permissions", ":", "perms", ".", "append", "(", "(", "get_permission_codename", "(", "action", ",", "opts", ")", ",", "'Can %s %s'"...
[ 20, 0 ]
[ 31, 16 ]
python
en
['en', 'error', 'th']
False
get_system_username
()
Return the current system user's username, or an empty string if the username could not be determined.
Return the current system user's username, or an empty string if the username could not be determined.
def get_system_username(): """ Return the current system user's username, or an empty string if the username could not be determined. """ try: result = getpass.getuser() except (ImportError, KeyError): # KeyError will be raised by os.getpwuid() (called by getuser()) # if ...
[ "def", "get_system_username", "(", ")", ":", "try", ":", "result", "=", "getpass", ".", "getuser", "(", ")", "except", "(", "ImportError", ",", "KeyError", ")", ":", "# KeyError will be raised by os.getpwuid() (called by getuser())", "# if there is no corresponding entry ...
[ 88, 0 ]
[ 100, 17 ]
python
en
['en', 'error', 'th']
False
get_default_username
(check_db=True, database=DEFAULT_DB_ALIAS)
Try to determine the current system user's username to use as a default. :param check_db: If ``True``, requires that the username does not match an existing ``auth.User`` (otherwise returns an empty string). :param database: The database where the unique check will be performed. :returns: The ...
Try to determine the current system user's username to use as a default.
def get_default_username(check_db=True, database=DEFAULT_DB_ALIAS): """ Try to determine the current system user's username to use as a default. :param check_db: If ``True``, requires that the username does not match an existing ``auth.User`` (otherwise returns an empty string). :param database...
[ "def", "get_default_username", "(", "check_db", "=", "True", ",", "database", "=", "DEFAULT_DB_ALIAS", ")", ":", "# This file is used in apps.py, it should not trigger models import.", "from", "django", ".", "contrib", ".", "auth", "import", "models", "as", "auth_app", ...
[ 103, 0 ]
[ 147, 27 ]
python
en
['en', 'error', 'th']
False
init_logger
(logdir, loglevel, nologs, quiet)
Initializes the logger for system messages.
Initializes the logger for system messages.
def init_logger(logdir, loglevel, nologs, quiet): "Initializes the logger for system messages." logger = logging.getLogger() # Set the loglevel. if loglevel > 3: # Cap at 3, incase someone likes their v-key too much. loglevel = 3 levels = [logging.ERROR, logging.WARN, logging.INFO, logging...
[ "def", "init_logger", "(", "logdir", ",", "loglevel", ",", "nologs", ",", "quiet", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", ")", "# Set the loglevel.", "if", "loglevel", ">", "3", ":", "# Cap at 3, incase someone likes their v-key too much.", "lo...
[ 77, 0 ]
[ 108, 55 ]
python
en
['en', 'en', 'en']
True
ChatLogger.log
(self, msg, channel)
Write a log line with a time stamp to the logfile of the channel
Write a log line with a time stamp to the logfile of the channel
def log(self, msg, channel): "Write a log line with a time stamp to the logfile of the channel" timestamp = time.strftime("%H:%M:%S", time.localtime(time.time())) try: self.logfiles[channel].write("[{}] {}\n".format(timestamp, msg)) self.logfiles[channel].flush() ...
[ "def", "log", "(", "self", ",", "msg", ",", "channel", ")", ":", "timestamp", "=", "time", ".", "strftime", "(", "\"%H:%M:%S\"", ",", "time", ".", "localtime", "(", "time", ".", "time", "(", ")", ")", ")", "try", ":", "self", ".", "logfiles", "[", ...
[ 18, 4 ]
[ 27, 49 ]
python
en
['en', 'en', 'en']
True
ChatLogger.log_url
(self, msg, channel)
Messages that contain urls are logged separately. Why not?
Messages that contain urls are logged separately. Why not?
def log_url(self, msg, channel): "Messages that contain urls are logged separately. Why not?" timestamp = time.strftime("%H:%M:%S", time.localtime(time.time())) self.logfiles["urls"].write("[{}] ({}) {}\n".format(timestamp, channel, msg...
[ "def", "log_url", "(", "self", ",", "msg", ",", "channel", ")", ":", "timestamp", "=", "time", ".", "strftime", "(", "\"%H:%M:%S\"", ",", "time", ".", "localtime", "(", "time", ".", "time", "(", ")", ")", ")", "self", ".", "logfiles", "[", "\"urls\""...
[ 29, 4 ]
[ 34, 37 ]
python
en
['en', 'en', 'en']
True
ChatLogger.del_channel
(self, channel)
Removes a channel from the logfiles dictionary
Removes a channel from the logfiles dictionary
def del_channel(self, channel): "Removes a channel from the logfiles dictionary" # To avoid a keyerror, pop will return None if the key is not found. self.logfiles.pop(channel, None)
[ "def", "del_channel", "(", "self", ",", "channel", ")", ":", "# To avoid a keyerror, pop will return None if the key is not found.", "self", ".", "logfiles", ".", "pop", "(", "channel", ",", "None", ")" ]
[ 52, 4 ]
[ 55, 40 ]
python
en
['en', 'en', 'en']
True
ChatLogger.open_logs
(self, channels)
Creates the file handles and opens them.
Creates the file handles and opens them.
def open_logs(self, channels): "Creates the file handles and opens them." for channel in channels: self.add_channel(channel) try: self.logfiles["urls"] = open("{}/urls-{}{}".format(self.prefix, self.server, self.suffix), "a") ...
[ "def", "open_logs", "(", "self", ",", "channels", ")", ":", "for", "channel", "in", "channels", ":", "self", ".", "add_channel", "(", "channel", ")", "try", ":", "self", ".", "logfiles", "[", "\"urls\"", "]", "=", "open", "(", "\"{}/urls-{}{}\"", ".", ...
[ 57, 4 ]
[ 69, 47 ]
python
en
['en', 'en', 'en']
True
TargetPython.__init__
( self, platforms: Optional[List[str]] = None, py_version_info: Optional[Tuple[int, ...]] = None, abis: Optional[List[str]] = None, implementation: Optional[str] = None, )
:param platforms: A list of strings or None. If None, searches for packages that are supported by the current system. Otherwise, will find packages that can be built on the platforms passed in. These packages will only be downloaded for distribution: they will no...
:param platforms: A list of strings or None. If None, searches for packages that are supported by the current system. Otherwise, will find packages that can be built on the platforms passed in. These packages will only be downloaded for distribution: they will no...
def __init__( self, platforms: Optional[List[str]] = None, py_version_info: Optional[Tuple[int, ...]] = None, abis: Optional[List[str]] = None, implementation: Optional[str] = None, ) -> None: """ :param platforms: A list of strings or None. If None, searches ...
[ "def", "__init__", "(", "self", ",", "platforms", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", "py_version_info", ":", "Optional", "[", "Tuple", "[", "int", ",", "...", "]", "]", "=", "None", ",", "abis", ":", "Optional", "...
[ 26, 4 ]
[ 64, 52 ]
python
en
['en', 'error', 'th']
False
TargetPython.format_given
(self)
Format the given, non-None attributes for display.
Format the given, non-None attributes for display.
def format_given(self) -> str: """ Format the given, non-None attributes for display. """ display_version = None if self._given_py_version_info is not None: display_version = '.'.join( str(part) for part in self._given_py_version_info ) ...
[ "def", "format_given", "(", "self", ")", "->", "str", ":", "display_version", "=", "None", "if", "self", ".", "_given_py_version_info", "is", "not", "None", ":", "display_version", "=", "'.'", ".", "join", "(", "str", "(", "part", ")", "for", "part", "in...
[ 66, 4 ]
[ 85, 9 ]
python
en
['en', 'error', 'th']
False
TargetPython.get_tags
(self)
Return the supported PEP 425 tags to check wheel candidates against. The tags are returned in order of preference (most preferred first).
Return the supported PEP 425 tags to check wheel candidates against.
def get_tags(self) -> List[Tag]: """ Return the supported PEP 425 tags to check wheel candidates against. The tags are returned in order of preference (most preferred first). """ if self._valid_tags is None: # Pass versions=None if no py_version_info was given since ...
[ "def", "get_tags", "(", "self", ")", "->", "List", "[", "Tag", "]", ":", "if", "self", ".", "_valid_tags", "is", "None", ":", "# Pass versions=None if no py_version_info was given since", "# versions=None uses special default logic.", "py_version_info", "=", "self", "."...
[ 87, 4 ]
[ 110, 31 ]
python
en
['en', 'error', 'th']
False
fix_method_name
(name)
Fix method names to avoid reserved word conflicts. Args: name: string, method name. Returns: The name with a '_' prefixed if the name is a reserved word.
Fix method names to avoid reserved word conflicts.
def fix_method_name(name): """Fix method names to avoid reserved word conflicts. Args: name: string, method name. Returns: The name with a '_' prefixed if the name is a reserved word. """ if keyword.iskeyword(name) or name in RESERVED_WORDS: return name + '_' else: return name
[ "def", "fix_method_name", "(", "name", ")", ":", "if", "keyword", ".", "iskeyword", "(", "name", ")", "or", "name", "in", "RESERVED_WORDS", ":", "return", "name", "+", "'_'", "else", ":", "return", "name" ]
[ 133, 0 ]
[ 145, 15 ]
python
en
['en', 'en', 'en']
True
key2param
(key)
Converts key names into parameter names. For example, converting "max-results" -> "max_results" Args: key: string, the method key name. Returns: A safe method name based on the key name.
Converts key names into parameter names.
def key2param(key): """Converts key names into parameter names. For example, converting "max-results" -> "max_results" Args: key: string, the method key name. Returns: A safe method name based on the key name. """ result = [] key = list(key) if not key[0].isalpha(): result.append('x') f...
[ "def", "key2param", "(", "key", ")", ":", "result", "=", "[", "]", "key", "=", "list", "(", "key", ")", "if", "not", "key", "[", "0", "]", ".", "isalpha", "(", ")", ":", "result", ".", "append", "(", "'x'", ")", "for", "c", "in", "key", ":", ...
[ 148, 0 ]
[ 169, 24 ]
python
en
['en', 'fil', 'en']
True
build
(serviceName, version, http=None, discoveryServiceUrl=DISCOVERY_URI, developerKey=None, model=None, requestBuilder=HttpRequest, credentials=None, cache_discovery=True, cache=None)
Construct a Resource for interacting with an API. Construct a Resource object for interacting with an API. The serviceName and version are the names from the Discovery service. Args: serviceName: string, name of the service. version: string, the version of the service. http: httplib2.Http, An instan...
Construct a Resource for interacting with an API.
def build(serviceName, version, http=None, discoveryServiceUrl=DISCOVERY_URI, developerKey=None, model=None, requestBuilder=HttpRequest, credentials=None, cache_discovery=True, cache=None): """Construct a Resource for interactin...
[ "def", "build", "(", "serviceName", ",", "version", ",", "http", "=", "None", ",", "discoveryServiceUrl", "=", "DISCOVERY_URI", ",", "developerKey", "=", "None", ",", "model", "=", "None", ",", "requestBuilder", "=", "HttpRequest", ",", "credentials", "=", "...
[ 173, 0 ]
[ 238, 57 ]
python
en
['en', 'en', 'en']
True
_retrieve_discovery_doc
(url, http, cache_discovery, cache=None)
Retrieves the discovery_doc from cache or the internet. Args: url: string, the URL of the discovery document. http: httplib2.Http, An instance of httplib2.Http or something that acts like it through which HTTP requests will be made. cache_discovery: Boolean, whether or not to cache the discovery do...
Retrieves the discovery_doc from cache or the internet.
def _retrieve_discovery_doc(url, http, cache_discovery, cache=None): """Retrieves the discovery_doc from cache or the internet. Args: url: string, the URL of the discovery document. http: httplib2.Http, An instance of httplib2.Http or something that acts like it through which HTTP requests will be ma...
[ "def", "_retrieve_discovery_doc", "(", "url", ",", "http", ",", "cache_discovery", ",", "cache", "=", "None", ")", ":", "if", "cache_discovery", ":", "from", ".", "import", "discovery_cache", "from", ".", "discovery_cache", "import", "base", "if", "cache", "is...
[ 241, 0 ]
[ 291, 16 ]
python
en
['en', 'en', 'en']
True
build_from_document
( service, base=None, future=None, http=None, developerKey=None, model=None, requestBuilder=HttpRequest, credentials=None)
Create a Resource for interacting with an API. Same as `build()`, but constructs the Resource object from a discovery document that is it given, as opposed to retrieving one over HTTP. Args: service: string or object, the JSON discovery document describing the API. The value passed in may either be th...
Create a Resource for interacting with an API.
def build_from_document( service, base=None, future=None, http=None, developerKey=None, model=None, requestBuilder=HttpRequest, credentials=None): """Create a Resource for interacting with an API. Same as `build()`, but constructs the Resource object from a discovery document that...
[ "def", "build_from_document", "(", "service", ",", "base", "=", "None", ",", "future", "=", "None", ",", "http", "=", "None", ",", "developerKey", "=", "None", ",", "model", "=", "None", ",", "requestBuilder", "=", "HttpRequest", ",", "credentials", "=", ...
[ 295, 0 ]
[ 382, 72 ]
python
en
['en', 'en', 'en']
True
_cast
(value, schema_type)
Convert value to a string based on JSON Schema type. See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on JSON Schema. Args: value: any, the value to convert schema_type: string, the type that value should be interpreted as Returns: A string representation of 'value' based ...
Convert value to a string based on JSON Schema type.
def _cast(value, schema_type): """Convert value to a string based on JSON Schema type. See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on JSON Schema. Args: value: any, the value to convert schema_type: string, the type that value should be interpreted as Returns: A str...
[ "def", "_cast", "(", "value", ",", "schema_type", ")", ":", "if", "schema_type", "==", "'string'", ":", "if", "type", "(", "value", ")", "==", "type", "(", "''", ")", "or", "type", "(", "value", ")", "==", "type", "(", "u''", ")", ":", "return", ...
[ 385, 0 ]
[ 413, 23 ]
python
en
['en', 'en', 'en']
True
_media_size_to_long
(maxSize)
Convert a string media size, such as 10GB or 3TB into an integer. Args: maxSize: string, size as a string, such as 2MB or 7GB. Returns: The size as an integer value.
Convert a string media size, such as 10GB or 3TB into an integer.
def _media_size_to_long(maxSize): """Convert a string media size, such as 10GB or 3TB into an integer. Args: maxSize: string, size as a string, such as 2MB or 7GB. Returns: The size as an integer value. """ if len(maxSize) < 2: return 0 units = maxSize[-2:].upper() bit_shift = _MEDIA_SIZE_BI...
[ "def", "_media_size_to_long", "(", "maxSize", ")", ":", "if", "len", "(", "maxSize", ")", "<", "2", ":", "return", "0", "units", "=", "maxSize", "[", "-", "2", ":", "]", ".", "upper", "(", ")", "bit_shift", "=", "_MEDIA_SIZE_BIT_SHIFTS", ".", "get", ...
[ 416, 0 ]
[ 432, 23 ]
python
en
['en', 'en', 'en']
True
_media_path_url_from_info
(root_desc, path_url)
Creates an absolute media path URL. Constructed using the API root URI and service path from the discovery document and the relative path for the API method. Args: root_desc: Dictionary; the entire original deserialized discovery document. path_url: String; the relative URL for the API method. Relative ...
Creates an absolute media path URL.
def _media_path_url_from_info(root_desc, path_url): """Creates an absolute media path URL. Constructed using the API root URI and service path from the discovery document and the relative path for the API method. Args: root_desc: Dictionary; the entire original deserialized discovery document. path_ur...
[ "def", "_media_path_url_from_info", "(", "root_desc", ",", "path_url", ")", ":", "return", "'%(root)supload/%(service_path)s%(path)s'", "%", "{", "'root'", ":", "root_desc", "[", "'rootUrl'", "]", ",", "'service_path'", ":", "root_desc", "[", "'servicePath'", "]", "...
[ 435, 0 ]
[ 453, 3 ]
python
en
['en', 'gd', 'en']
True
_fix_up_parameters
(method_desc, root_desc, http_method)
Updates parameters of an API method with values specific to this library. Specifically, adds whatever global parameters are specified by the API to the parameters for the individual method. Also adds parameters which don't appear in the discovery document, but are available to all discovery based APIs (these a...
Updates parameters of an API method with values specific to this library.
def _fix_up_parameters(method_desc, root_desc, http_method): """Updates parameters of an API method with values specific to this library. Specifically, adds whatever global parameters are specified by the API to the parameters for the individual method. Also adds parameters which don't appear in the discovery ...
[ "def", "_fix_up_parameters", "(", "method_desc", ",", "root_desc", ",", "http_method", ")", ":", "parameters", "=", "method_desc", ".", "setdefault", "(", "'parameters'", ",", "{", "}", ")", "# Add in the parameters common to all methods.", "for", "name", ",", "desc...
[ 456, 0 ]
[ 496, 19 ]
python
en
['en', 'en', 'en']
True
_fix_up_media_upload
(method_desc, root_desc, path_url, parameters)
Adds 'media_body' and 'media_mime_type' parameters if supported by method. SIDE EFFECTS: If the method supports media upload and has a required body, sets body to be optional (required=False) instead. Also, if there is a 'mediaUpload' in the method description, adds 'media_upload' key to parameters. Args: ...
Adds 'media_body' and 'media_mime_type' parameters if supported by method.
def _fix_up_media_upload(method_desc, root_desc, path_url, parameters): """Adds 'media_body' and 'media_mime_type' parameters if supported by method. SIDE EFFECTS: If the method supports media upload and has a required body, sets body to be optional (required=False) instead. Also, if there is a 'mediaUpload' i...
[ "def", "_fix_up_media_upload", "(", "method_desc", ",", "root_desc", ",", "path_url", ",", "parameters", ")", ":", "media_upload", "=", "method_desc", ".", "get", "(", "'mediaUpload'", ",", "{", "}", ")", "accept", "=", "media_upload", ".", "get", "(", "'acc...
[ 499, 0 ]
[ 541, 41 ]
python
en
['en', 'en', 'en']
True
_fix_up_method_description
(method_desc, root_desc)
Updates a method description in a discovery document. SIDE EFFECTS: Changes the parameters dictionary in the method description with extra parameters which are used locally. Args: method_desc: Dictionary with metadata describing an API method. Value comes from the dictionary of methods stored in the...
Updates a method description in a discovery document.
def _fix_up_method_description(method_desc, root_desc): """Updates a method description in a discovery document. SIDE EFFECTS: Changes the parameters dictionary in the method description with extra parameters which are used locally. Args: method_desc: Dictionary with metadata describing an API method. Val...
[ "def", "_fix_up_method_description", "(", "method_desc", ",", "root_desc", ")", ":", "path_url", "=", "method_desc", "[", "'path'", "]", "http_method", "=", "method_desc", "[", "'httpMethod'", "]", "method_id", "=", "method_desc", "[", "'id'", "]", "parameters", ...
[ 544, 0 ]
[ 586, 75 ]
python
en
['en', 'en', 'en']
True
_urljoin
(base, url)
Custom urljoin replacement supporting : before / in url.
Custom urljoin replacement supporting : before / in url.
def _urljoin(base, url): """Custom urljoin replacement supporting : before / in url.""" # In general, it's unsafe to simply join base and url. However, for # the case of discovery documents, we know: # * base will never contain params, query, or fragment # * url will never contain a scheme or net_loc. # I...
[ "def", "_urljoin", "(", "base", ",", "url", ")", ":", "# In general, it's unsafe to simply join base and url. However, for", "# the case of discovery documents, we know:", "# * base will never contain params, query, or fragment", "# * url will never contain a scheme or net_loc.", "# In gen...
[ 589, 0 ]
[ 603, 27 ]
python
en
['en', 'en', 'en']
True
createMethod
(methodName, methodDesc, rootDesc, schema)
Creates a method for attaching to a Resource. Args: methodName: string, name of the method to use. methodDesc: object, fragment of deserialized discovery document that describes the method. rootDesc: object, the entire deserialized discovery document. schema: object, mapping of schema names to ...
Creates a method for attaching to a Resource.
def createMethod(methodName, methodDesc, rootDesc, schema): """Creates a method for attaching to a Resource. Args: methodName: string, name of the method to use. methodDesc: object, fragment of deserialized discovery document that describes the method. rootDesc: object, the entire deserialized di...
[ "def", "createMethod", "(", "methodName", ",", "methodDesc", ",", "rootDesc", ",", "schema", ")", ":", "methodName", "=", "fix_method_name", "(", "methodName", ")", "(", "pathUrl", ",", "httpMethod", ",", "methodId", ",", "accept", ",", "maxSize", ",", "medi...
[ 695, 0 ]
[ 926, 29 ]
python
en
['en', 'en', 'en']
True
createNextMethod
(methodName)
Creates any _next methods for attaching to a Resource. The _next methods allow for easy iteration through list() responses. Args: methodName: string, name of the method to use.
Creates any _next methods for attaching to a Resource.
def createNextMethod(methodName): """Creates any _next methods for attaching to a Resource. The _next methods allow for easy iteration through list() responses. Args: methodName: string, name of the method to use. """ methodName = fix_method_name(methodName) def methodNext(self, previous_request, pre...
[ "def", "createNextMethod", "(", "methodName", ")", ":", "methodName", "=", "fix_method_name", "(", "methodName", ")", "def", "methodNext", "(", "self", ",", "previous_request", ",", "previous_response", ")", ":", "\"\"\"Retrieves the next page of results.\n\nArgs:\n prev...
[ 929, 0 ]
[ 974, 33 ]
python
en
['en', 'en', 'en']
True
ResourceMethodParameters.__init__
(self, method_desc)
Constructor for ResourceMethodParameters. Sets default values and defers to set_parameters to populate. Args: method_desc: Dictionary with metadata describing an API method. Value comes from the dictionary of methods stored in the 'methods' key in the deserialized discovery document....
Constructor for ResourceMethodParameters.
def __init__(self, method_desc): """Constructor for ResourceMethodParameters. Sets default values and defers to set_parameters to populate. Args: method_desc: Dictionary with metadata describing an API method. Value comes from the dictionary of methods stored in the 'methods' key in ...
[ "def", "__init__", "(", "self", ",", "method_desc", ")", ":", "self", ".", "argmap", "=", "{", "}", "self", ".", "required_params", "=", "[", "]", "self", ".", "repeated_params", "=", "[", "]", "self", ".", "pattern_params", "=", "{", "}", "self", "....
[ 632, 2 ]
[ 653, 36 ]
python
en
['da', 'en', 'en']
True
ResourceMethodParameters.set_parameters
(self, method_desc)
Populates maps and lists based on method description. Iterates through each parameter for the method and parses the values from the parameter dictionary. Args: method_desc: Dictionary with metadata describing an API method. Value comes from the dictionary of methods stored in the 'methods'...
Populates maps and lists based on method description.
def set_parameters(self, method_desc): """Populates maps and lists based on method description. Iterates through each parameter for the method and parses the values from the parameter dictionary. Args: method_desc: Dictionary with metadata describing an API method. Value comes from the...
[ "def", "set_parameters", "(", "self", ",", "method_desc", ")", ":", "for", "arg", ",", "desc", "in", "six", ".", "iteritems", "(", "method_desc", ".", "get", "(", "'parameters'", ",", "{", "}", ")", ")", ":", "param", "=", "key2param", "(", "arg", ")...
[ 655, 2 ]
[ 692, 40 ]
python
en
['en', 'en', 'en']
True
Resource.__init__
(self, http, baseUrl, model, requestBuilder, developerKey, resourceDesc, rootDesc, schema)
Build a Resource from the API description. Args: http: httplib2.Http, Object to make http requests with. baseUrl: string, base URL for the API. All requests are relative to this URI. model: googleapiclient.Model, converts to and from the wire format. requestBuilder: class or calla...
Build a Resource from the API description.
def __init__(self, http, baseUrl, model, requestBuilder, developerKey, resourceDesc, rootDesc, schema): """Build a Resource from the API description. Args: http: httplib2.Http, Object to make http requests with. baseUrl: string, base URL for the API. All requests are relative to this...
[ "def", "__init__", "(", "self", ",", "http", ",", "baseUrl", ",", "model", ",", "requestBuilder", ",", "developerKey", ",", "resourceDesc", ",", "rootDesc", ",", "schema", ")", ":", "self", ".", "_dynamic_attrs", "=", "[", "]", "self", ".", "_http", "=",...
[ 980, 2 ]
[ 1010, 31 ]
python
en
['en', 'en', 'en']
True
Resource._set_dynamic_attr
(self, attr_name, value)
Sets an instance attribute and tracks it in a list of dynamic attributes. Args: attr_name: string; The name of the attribute to be set value: The value being set on the object and tracked in the dynamic cache.
Sets an instance attribute and tracks it in a list of dynamic attributes.
def _set_dynamic_attr(self, attr_name, value): """Sets an instance attribute and tracks it in a list of dynamic attributes. Args: attr_name: string; The name of the attribute to be set value: The value being set on the object and tracked in the dynamic cache. """ self._dynamic_attrs.append(...
[ "def", "_set_dynamic_attr", "(", "self", ",", "attr_name", ",", "value", ")", ":", "self", ".", "_dynamic_attrs", ".", "append", "(", "attr_name", ")", "self", ".", "__dict__", "[", "attr_name", "]", "=", "value" ]
[ 1012, 2 ]
[ 1020, 36 ]
python
en
['en', 'en', 'en']
True
Resource.__getstate__
(self)
Trim the state down to something that can be pickled. Uses the fact that the instance variable _dynamic_attrs holds attrs that will be wiped and restored on pickle serialization.
Trim the state down to something that can be pickled.
def __getstate__(self): """Trim the state down to something that can be pickled. Uses the fact that the instance variable _dynamic_attrs holds attrs that will be wiped and restored on pickle serialization. """ state_dict = copy.copy(self.__dict__) for dynamic_attr in self._dynamic_attrs: ...
[ "def", "__getstate__", "(", "self", ")", ":", "state_dict", "=", "copy", ".", "copy", "(", "self", ".", "__dict__", ")", "for", "dynamic_attr", "in", "self", ".", "_dynamic_attrs", ":", "del", "state_dict", "[", "dynamic_attr", "]", "del", "state_dict", "[...
[ 1022, 2 ]
[ 1032, 21 ]
python
en
['en', 'en', 'en']
True
Resource.__setstate__
(self, state)
Reconstitute the state of the object from being pickled. Uses the fact that the instance variable _dynamic_attrs holds attrs that will be wiped and restored on pickle serialization.
Reconstitute the state of the object from being pickled.
def __setstate__(self, state): """Reconstitute the state of the object from being pickled. Uses the fact that the instance variable _dynamic_attrs holds attrs that will be wiped and restored on pickle serialization. """ self.__dict__.update(state) self._dynamic_attrs = [] self._set_service_...
[ "def", "__setstate__", "(", "self", ",", "state", ")", ":", "self", ".", "__dict__", ".", "update", "(", "state", ")", "self", ".", "_dynamic_attrs", "=", "[", "]", "self", ".", "_set_service_methods", "(", ")" ]
[ 1034, 2 ]
[ 1042, 31 ]
python
en
['en', 'en', 'en']
True
is_text_serializer
(serializer)
Checks whether a serializer generates text or binary.
Checks whether a serializer generates text or binary.
def is_text_serializer(serializer): """Checks whether a serializer generates text or binary.""" return isinstance(serializer.dumps({}), text_type)
[ "def", "is_text_serializer", "(", "serializer", ")", ":", "return", "isinstance", "(", "serializer", ".", "dumps", "(", "{", "}", ")", ",", "text_type", ")" ]
[ 10, 0 ]
[ 12, 54 ]
python
en
['en', 'en', 'en']
True
Serializer.load_payload
(self, payload, serializer=None)
Loads the encoded object. This function raises :class:`.BadPayload` if the payload is not valid. The ``serializer`` parameter can be used to override the serializer stored on the class. The encoded ``payload`` should always be bytes.
Loads the encoded object. This function raises :class:`.BadPayload` if the payload is not valid. The ``serializer`` parameter can be used to override the serializer stored on the class. The encoded ``payload`` should always be bytes.
def load_payload(self, payload, serializer=None): """Loads the encoded object. This function raises :class:`.BadPayload` if the payload is not valid. The ``serializer`` parameter can be used to override the serializer stored on the class. The encoded ``payload`` should always be ...
[ "def", "load_payload", "(", "self", ",", "payload", ",", "serializer", "=", "None", ")", ":", "if", "serializer", "is", "None", ":", "serializer", "=", "self", ".", "serializer", "is_text", "=", "self", ".", "is_text_serializer", "else", ":", "is_text", "=...
[ 104, 4 ]
[ 125, 13 ]
python
en
['en', 'en', 'en']
True
Serializer.dump_payload
(self, obj)
Dumps the encoded object. The return value is always bytes. If the internal serializer returns text, the value will be encoded as UTF-8.
Dumps the encoded object. The return value is always bytes. If the internal serializer returns text, the value will be encoded as UTF-8.
def dump_payload(self, obj): """Dumps the encoded object. The return value is always bytes. If the internal serializer returns text, the value will be encoded as UTF-8. """ return want_bytes(self.serializer.dumps(obj, **self.serializer_kwargs))
[ "def", "dump_payload", "(", "self", ",", "obj", ")", ":", "return", "want_bytes", "(", "self", ".", "serializer", ".", "dumps", "(", "obj", ",", "*", "*", "self", ".", "serializer_kwargs", ")", ")" ]
[ 127, 4 ]
[ 132, 79 ]
python
en
['en', 'en', 'en']
True
Serializer.make_signer
(self, salt=None)
Creates a new instance of the signer to be used. The default implementation uses the :class:`.Signer` base class.
Creates a new instance of the signer to be used. The default implementation uses the :class:`.Signer` base class.
def make_signer(self, salt=None): """Creates a new instance of the signer to be used. The default implementation uses the :class:`.Signer` base class. """ if salt is None: salt = self.salt return self.signer(self.secret_key, salt=salt, **self.signer_kwargs)
[ "def", "make_signer", "(", "self", ",", "salt", "=", "None", ")", ":", "if", "salt", "is", "None", ":", "salt", "=", "self", ".", "salt", "return", "self", ".", "signer", "(", "self", ".", "secret_key", ",", "salt", "=", "salt", ",", "*", "*", "s...
[ 134, 4 ]
[ 140, 76 ]
python
en
['en', 'en', 'en']
True
Serializer.iter_unsigners
(self, salt=None)
Iterates over all signers to be tried for unsigning. Starts with the configured signer, then constructs each signer specified in ``fallback_signers``.
Iterates over all signers to be tried for unsigning. Starts with the configured signer, then constructs each signer specified in ``fallback_signers``.
def iter_unsigners(self, salt=None): """Iterates over all signers to be tried for unsigning. Starts with the configured signer, then constructs each signer specified in ``fallback_signers``. """ if salt is None: salt = self.salt yield self.make_signer(salt) ...
[ "def", "iter_unsigners", "(", "self", ",", "salt", "=", "None", ")", ":", "if", "salt", "is", "None", ":", "salt", "=", "self", ".", "salt", "yield", "self", ".", "make_signer", "(", "salt", ")", "for", "fallback", "in", "self", ".", "fallback_signers"...
[ 142, 4 ]
[ 158, 64 ]
python
en
['en', 'en', 'en']
True
Serializer.dumps
(self, obj, salt=None)
Returns a signed string serialized with the internal serializer. The return value can be either a byte or unicode string depending on the format of the internal serializer.
Returns a signed string serialized with the internal serializer. The return value can be either a byte or unicode string depending on the format of the internal serializer.
def dumps(self, obj, salt=None): """Returns a signed string serialized with the internal serializer. The return value can be either a byte or unicode string depending on the format of the internal serializer. """ payload = want_bytes(self.dump_payload(obj)) rv = self.make...
[ "def", "dumps", "(", "self", ",", "obj", ",", "salt", "=", "None", ")", ":", "payload", "=", "want_bytes", "(", "self", ".", "dump_payload", "(", "obj", ")", ")", "rv", "=", "self", ".", "make_signer", "(", "salt", ")", ".", "sign", "(", "payload",...
[ 160, 4 ]
[ 169, 17 ]
python
en
['en', 'en', 'en']
True
Serializer.dump
(self, obj, f, salt=None)
Like :meth:`dumps` but dumps into a file. The file handle has to be compatible with what the internal serializer expects.
Like :meth:`dumps` but dumps into a file. The file handle has to be compatible with what the internal serializer expects.
def dump(self, obj, f, salt=None): """Like :meth:`dumps` but dumps into a file. The file handle has to be compatible with what the internal serializer expects. """ f.write(self.dumps(obj, salt))
[ "def", "dump", "(", "self", ",", "obj", ",", "f", ",", "salt", "=", "None", ")", ":", "f", ".", "write", "(", "self", ".", "dumps", "(", "obj", ",", "salt", ")", ")" ]
[ 171, 4 ]
[ 175, 38 ]
python
en
['en', 'en', 'en']
True
Serializer.loads
(self, s, salt=None)
Reverse of :meth:`dumps`. Raises :exc:`.BadSignature` if the signature validation fails.
Reverse of :meth:`dumps`. Raises :exc:`.BadSignature` if the signature validation fails.
def loads(self, s, salt=None): """Reverse of :meth:`dumps`. Raises :exc:`.BadSignature` if the signature validation fails. """ s = want_bytes(s) last_exception = None for signer in self.iter_unsigners(salt): try: return self.load_payload(signer...
[ "def", "loads", "(", "self", ",", "s", ",", "salt", "=", "None", ")", ":", "s", "=", "want_bytes", "(", "s", ")", "last_exception", "=", "None", "for", "signer", "in", "self", ".", "iter_unsigners", "(", "salt", ")", ":", "try", ":", "return", "sel...
[ 177, 4 ]
[ 188, 28 ]
python
en
['en', 'la', 'en']
True
Serializer.load
(self, f, salt=None)
Like :meth:`loads` but loads from a file.
Like :meth:`loads` but loads from a file.
def load(self, f, salt=None): """Like :meth:`loads` but loads from a file.""" return self.loads(f.read(), salt)
[ "def", "load", "(", "self", ",", "f", ",", "salt", "=", "None", ")", ":", "return", "self", ".", "loads", "(", "f", ".", "read", "(", ")", ",", "salt", ")" ]
[ 190, 4 ]
[ 192, 41 ]
python
en
['en', 'en', 'en']
True
Serializer.loads_unsafe
(self, s, salt=None)
Like :meth:`loads` but without verifying the signature. This is potentially very dangerous to use depending on how your serializer works. The return value is ``(signature_valid, payload)`` instead of just the payload. The first item will be a boolean that indicates if the signature is va...
Like :meth:`loads` but without verifying the signature. This is potentially very dangerous to use depending on how your serializer works. The return value is ``(signature_valid, payload)`` instead of just the payload. The first item will be a boolean that indicates if the signature is va...
def loads_unsafe(self, s, salt=None): """Like :meth:`loads` but without verifying the signature. This is potentially very dangerous to use depending on how your serializer works. The return value is ``(signature_valid, payload)`` instead of just the payload. The first item will be a ...
[ "def", "loads_unsafe", "(", "self", ",", "s", ",", "salt", "=", "None", ")", ":", "return", "self", ".", "_loads_unsafe_impl", "(", "s", ",", "salt", ")" ]
[ 194, 4 ]
[ 208, 47 ]
python
en
['en', 'en', 'en']
True
Serializer._loads_unsafe_impl
(self, s, salt, load_kwargs=None, load_payload_kwargs=None)
Low level helper function to implement :meth:`loads_unsafe` in serializer subclasses.
Low level helper function to implement :meth:`loads_unsafe` in serializer subclasses.
def _loads_unsafe_impl(self, s, salt, load_kwargs=None, load_payload_kwargs=None): """Low level helper function to implement :meth:`loads_unsafe` in serializer subclasses. """ try: return True, self.loads(s, salt=salt, **(load_kwargs or {})) except BadSignature as e: ...
[ "def", "_loads_unsafe_impl", "(", "self", ",", "s", ",", "salt", ",", "load_kwargs", "=", "None", ",", "load_payload_kwargs", "=", "None", ")", ":", "try", ":", "return", "True", ",", "self", ".", "loads", "(", "s", ",", "salt", "=", "salt", ",", "*"...
[ 210, 4 ]
[ 225, 34 ]
python
en
['en', 'en', 'en']
True
Serializer.load_unsafe
(self, f, *args, **kwargs)
Like :meth:`loads_unsafe` but loads from a file. .. versionadded:: 0.15
Like :meth:`loads_unsafe` but loads from a file.
def load_unsafe(self, f, *args, **kwargs): """Like :meth:`loads_unsafe` but loads from a file. .. versionadded:: 0.15 """ return self.loads_unsafe(f.read(), *args, **kwargs)
[ "def", "load_unsafe", "(", "self", ",", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "loads_unsafe", "(", "f", ".", "read", "(", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
[ 227, 4 ]
[ 232, 59 ]
python
en
['en', 'en', 'en']
True