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
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
rename_for_jekyll
(nb_path: Path, warnings: Set[Tuple[str, str]]=None)
Return a Path's filename string appended with its modified time in YYYY-MM-DD format.
Return a Path's filename string appended with its modified time in YYYY-MM-DD format.
def rename_for_jekyll(nb_path: Path, warnings: Set[Tuple[str, str]]=None) -> str: """ Return a Path's filename string appended with its modified time in YYYY-MM-DD format. """ assert nb_path.exists(), f'{nb_path} could not be found.' # Checks if filename is compliant with Jekyll blog posts if _re_blog_date.match(nb_path.name): return nb_path.with_suffix('.md').name.replace(' ', '-') else: clean_name = _re_numdash.sub('', nb_path.with_suffix('.md').name).replace(' ', '-') # Gets the file's last modified time and and append YYYY-MM-DD- to the beginning of the filename mdate = os.path.getmtime(nb_path) - 86400 # subtract one day b/c dates in the future break Jekyll dtnm = datetime.fromtimestamp(mdate).strftime("%Y-%m-%d-") + clean_name assert _re_blog_date.match(dtnm), f'{dtnm} is not a valid name, filename must be pre-pended with YYYY-MM-DD-' # push this into a set b/c _nb2htmlfname gets called multiple times per conversion if warnings: warnings.add((nb_path, dtnm)) return dtnm
[ "def", "rename_for_jekyll", "(", "nb_path", ":", "Path", ",", "warnings", ":", "Set", "[", "Tuple", "[", "str", ",", "str", "]", "]", "=", "None", ")", "->", "str", ":", "assert", "nb_path", ".", "exists", "(", ")", ",", "f'{nb_path} could not be found.'", "# Checks if filename is compliant with Jekyll blog posts", "if", "_re_blog_date", ".", "match", "(", "nb_path", ".", "name", ")", ":", "return", "nb_path", ".", "with_suffix", "(", "'.md'", ")", ".", "name", ".", "replace", "(", "' '", ",", "'-'", ")", "else", ":", "clean_name", "=", "_re_numdash", ".", "sub", "(", "''", ",", "nb_path", ".", "with_suffix", "(", "'.md'", ")", ".", "name", ")", ".", "replace", "(", "' '", ",", "'-'", ")", "# Gets the file's last modified time and and append YYYY-MM-DD- to the beginning of the filename", "mdate", "=", "os", ".", "path", ".", "getmtime", "(", "nb_path", ")", "-", "86400", "# subtract one day b/c dates in the future break Jekyll", "dtnm", "=", "datetime", ".", "fromtimestamp", "(", "mdate", ")", ".", "strftime", "(", "\"%Y-%m-%d-\"", ")", "+", "clean_name", "assert", "_re_blog_date", ".", "match", "(", "dtnm", ")", ",", "f'{dtnm} is not a valid name, filename must be pre-pended with YYYY-MM-DD-'", "# push this into a set b/c _nb2htmlfname gets called multiple times per conversion", "if", "warnings", ":", "warnings", ".", "add", "(", "(", "nb_path", ",", "dtnm", ")", ")", "return", "dtnm" ]
[ 10, 0 ]
[ 28, 19 ]
python
en
['en', 'error', 'th']
False
is_ascii_encoding
(encoding)
Checks if a given encoding is ascii.
Checks if a given encoding is ascii.
def is_ascii_encoding(encoding): """Checks if a given encoding is ascii.""" try: return codecs.lookup(encoding).name == 'ascii' except LookupError: return False
[ "def", "is_ascii_encoding", "(", "encoding", ")", ":", "try", ":", "return", "codecs", ".", "lookup", "(", "encoding", ")", ".", "name", "==", "'ascii'", "except", "LookupError", ":", "return", "False" ]
[ 36, 0 ]
[ 41, 20 ]
python
en
['en', 'en', 'en']
True
get_best_encoding
(stream)
Returns the default stream encoding if not found.
Returns the default stream encoding if not found.
def get_best_encoding(stream): """Returns the default stream encoding if not found.""" rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding() if is_ascii_encoding(rv): return 'utf-8' return rv
[ "def", "get_best_encoding", "(", "stream", ")", ":", "rv", "=", "getattr", "(", "stream", ",", "'encoding'", ",", "None", ")", "or", "sys", ".", "getdefaultencoding", "(", ")", "if", "is_ascii_encoding", "(", "rv", ")", ":", "return", "'utf-8'", "return", "rv" ]
[ 44, 0 ]
[ 49, 13 ]
python
en
['en', 'en', 'en']
True
build_iter_view
(matches)
Build an iterable view from the value returned by `find_matches()`.
Build an iterable view from the value returned by `find_matches()`.
def build_iter_view(matches): """Build an iterable view from the value returned by `find_matches()`.""" if callable(matches): return _FactoryIterableView(matches) if not isinstance(matches, collections_abc.Sequence): matches = list(matches) return _SequenceIterableView(matches)
[ "def", "build_iter_view", "(", "matches", ")", ":", "if", "callable", "(", "matches", ")", ":", "return", "_FactoryIterableView", "(", "matches", ")", "if", "not", "isinstance", "(", "matches", ",", "collections_abc", ".", "Sequence", ")", ":", "matches", "=", "list", "(", "matches", ")", "return", "_SequenceIterableView", "(", "matches", ")" ]
[ 158, 0 ]
[ 164, 41 ]
python
en
['en', 'en', 'en']
True
DirectedGraph.copy
(self)
Return a shallow copy of this graph.
Return a shallow copy of this graph.
def copy(self): """Return a shallow copy of this graph.""" other = DirectedGraph() other._vertices = set(self._vertices) other._forwards = {k: set(v) for k, v in self._forwards.items()} other._backwards = {k: set(v) for k, v in self._backwards.items()} return other
[ "def", "copy", "(", "self", ")", ":", "other", "=", "DirectedGraph", "(", ")", "other", ".", "_vertices", "=", "set", "(", "self", ".", "_vertices", ")", "other", ".", "_forwards", "=", "{", "k", ":", "set", "(", "v", ")", "for", "k", ",", "v", "in", "self", ".", "_forwards", ".", "items", "(", ")", "}", "other", ".", "_backwards", "=", "{", "k", ":", "set", "(", "v", ")", "for", "k", ",", "v", "in", "self", ".", "_backwards", ".", "items", "(", ")", "}", "return", "other" ]
[ 22, 4 ]
[ 28, 20 ]
python
en
['en', 'en', 'en']
True
DirectedGraph.add
(self, key)
Add a new vertex to the graph.
Add a new vertex to the graph.
def add(self, key): """Add a new vertex to the graph.""" if key in self._vertices: raise ValueError("vertex exists") self._vertices.add(key) self._forwards[key] = set() self._backwards[key] = set()
[ "def", "add", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "_vertices", ":", "raise", "ValueError", "(", "\"vertex exists\"", ")", "self", ".", "_vertices", ".", "add", "(", "key", ")", "self", ".", "_forwards", "[", "key", "]", "=", "set", "(", ")", "self", ".", "_backwards", "[", "key", "]", "=", "set", "(", ")" ]
[ 30, 4 ]
[ 36, 36 ]
python
en
['en', 'en', 'en']
True
DirectedGraph.remove
(self, key)
Remove a vertex from the graph, disconnecting all edges from/to it.
Remove a vertex from the graph, disconnecting all edges from/to it.
def remove(self, key): """Remove a vertex from the graph, disconnecting all edges from/to it.""" self._vertices.remove(key) for f in self._forwards.pop(key): self._backwards[f].remove(key) for t in self._backwards.pop(key): self._forwards[t].remove(key)
[ "def", "remove", "(", "self", ",", "key", ")", ":", "self", ".", "_vertices", ".", "remove", "(", "key", ")", "for", "f", "in", "self", ".", "_forwards", ".", "pop", "(", "key", ")", ":", "self", ".", "_backwards", "[", "f", "]", ".", "remove", "(", "key", ")", "for", "t", "in", "self", ".", "_backwards", ".", "pop", "(", "key", ")", ":", "self", ".", "_forwards", "[", "t", "]", ".", "remove", "(", "key", ")" ]
[ 38, 4 ]
[ 44, 41 ]
python
en
['en', 'en', 'en']
True
DirectedGraph.connect
(self, f, t)
Connect two existing vertices. Nothing happens if the vertices are already connected.
Connect two existing vertices.
def connect(self, f, t): """Connect two existing vertices. Nothing happens if the vertices are already connected. """ if t not in self._vertices: raise KeyError(t) self._forwards[f].add(t) self._backwards[t].add(f)
[ "def", "connect", "(", "self", ",", "f", ",", "t", ")", ":", "if", "t", "not", "in", "self", ".", "_vertices", ":", "raise", "KeyError", "(", "t", ")", "self", ".", "_forwards", "[", "f", "]", ".", "add", "(", "t", ")", "self", ".", "_backwards", "[", "t", "]", ".", "add", "(", "f", ")" ]
[ 49, 4 ]
[ 57, 33 ]
python
en
['nl', 'en', 'en']
True
flag_anomalies_by_thresholding
( cur_batch_size, mahalanobis_dist, anom_thresh_var)
Flags anomalies by thresholding. Given current batch size, mahalanobis distance, and anomaly threshold variable, return predicted anomaly flags. Args: cur_batch_size: Current batch size, could be partially filled. mahalanobis_dist: Mahalanobis distance. anom_thresh_var: Anomaly threshold variable. Returns: anomaly_flags: tf.int64 vector of current batch size elements of 0's and 1's indicating if each sequence is anomalous or not.
Flags anomalies by thresholding.
def flag_anomalies_by_thresholding( cur_batch_size, mahalanobis_dist, anom_thresh_var): """Flags anomalies by thresholding. Given current batch size, mahalanobis distance, and anomaly threshold variable, return predicted anomaly flags. Args: cur_batch_size: Current batch size, could be partially filled. mahalanobis_dist: Mahalanobis distance. anom_thresh_var: Anomaly threshold variable. Returns: anomaly_flags: tf.int64 vector of current batch size elements of 0's and 1's indicating if each sequence is anomalous or not. """ anom_flags = tf.where( condition=tf.reduce_any( input_tensor=tf.greater( x=tf.abs(x=mahalanobis_dist), y=anom_thresh_var), axis=1), x=tf.ones(shape=[cur_batch_size], dtype=tf.int64), y=tf.zeros(shape=[cur_batch_size], dtype=tf.int64)) return anom_flags
[ "def", "flag_anomalies_by_thresholding", "(", "cur_batch_size", ",", "mahalanobis_dist", ",", "anom_thresh_var", ")", ":", "anom_flags", "=", "tf", ".", "where", "(", "condition", "=", "tf", ".", "reduce_any", "(", "input_tensor", "=", "tf", ".", "greater", "(", "x", "=", "tf", ".", "abs", "(", "x", "=", "mahalanobis_dist", ")", ",", "y", "=", "anom_thresh_var", ")", ",", "axis", "=", "1", ")", ",", "x", "=", "tf", ".", "ones", "(", "shape", "=", "[", "cur_batch_size", "]", ",", "dtype", "=", "tf", ".", "int64", ")", ",", "y", "=", "tf", ".", "zeros", "(", "shape", "=", "[", "cur_batch_size", "]", ",", "dtype", "=", "tf", ".", "int64", ")", ")", "return", "anom_flags" ]
[ 3, 0 ]
[ 28, 19 ]
python
en
['en', 'en', 'en']
True
anomaly_detection_predictions
( cur_batch_size, seq_len, num_feat, mahalanobis_dist_time, mahalanobis_dist_feat, time_anom_thresh_var, feat_anom_thresh_var, X_time_abs_recon_err, X_feat_abs_recon_err)
Creates Estimator predictions and export outputs. Given dimensions of inputs, mahalanobis distances and their respective thresholds, and reconstructed inputs' absolute errors, returns Estimator's predictions and export outputs. Args: cur_batch_size: Current batch size, could be partially filled. seq_len: Number of timesteps in sequence. num_feat: Number of features. mahalanobis_dist_time: Mahalanobis distance, time major. mahalanobis_dist_feat: Mahalanobis distance, features major. time_anom_thresh_var: Time anomaly threshold variable. feat_anom_thresh_var: Features anomaly threshold variable. X_time_abs_recon_err: Time major reconstructed input data's absolute reconstruction error. X_feat_abs_recon_err: Features major reconstructed input data's absolute reconstruction error. Returns: predictions_dict: Dictionary of predictions to output for local prediction. export_outputs: Dictionary to output from exported model for serving.
Creates Estimator predictions and export outputs.
def anomaly_detection_predictions( cur_batch_size, seq_len, num_feat, mahalanobis_dist_time, mahalanobis_dist_feat, time_anom_thresh_var, feat_anom_thresh_var, X_time_abs_recon_err, X_feat_abs_recon_err): """Creates Estimator predictions and export outputs. Given dimensions of inputs, mahalanobis distances and their respective thresholds, and reconstructed inputs' absolute errors, returns Estimator's predictions and export outputs. Args: cur_batch_size: Current batch size, could be partially filled. seq_len: Number of timesteps in sequence. num_feat: Number of features. mahalanobis_dist_time: Mahalanobis distance, time major. mahalanobis_dist_feat: Mahalanobis distance, features major. time_anom_thresh_var: Time anomaly threshold variable. feat_anom_thresh_var: Features anomaly threshold variable. X_time_abs_recon_err: Time major reconstructed input data's absolute reconstruction error. X_feat_abs_recon_err: Features major reconstructed input data's absolute reconstruction error. Returns: predictions_dict: Dictionary of predictions to output for local prediction. export_outputs: Dictionary to output from exported model for serving. """ # Flag predictions as either normal or anomalous # shape = (cur_batch_size,) time_anom_flags = flag_anomalies_by_thresholding( cur_batch_size, mahalanobis_dist_time, time_anom_thresh_var) # shape = (cur_batch_size,) feat_anom_flags = flag_anomalies_by_thresholding( cur_batch_size, mahalanobis_dist_feat, feat_anom_thresh_var) # Create predictions dictionary predictions_dict = { "X_time_abs_recon_err": tf.reshape( tensor=X_time_abs_recon_err, shape=[cur_batch_size, seq_len, num_feat]), "X_feat_abs_recon_err": tf.transpose( a=tf.reshape( tensor=X_feat_abs_recon_err, shape=[cur_batch_size, num_feat, seq_len]), perm=[0, 2, 1]), "mahalanobis_dist_time": mahalanobis_dist_time, "mahalanobis_dist_feat": mahalanobis_dist_feat, "time_anom_thresh_var": tf.fill( dims=[cur_batch_size], value=time_anom_thresh_var), "feat_anom_thresh_var": tf.fill( dims=[cur_batch_size], value=feat_anom_thresh_var), "time_anom_flags": time_anom_flags, "feat_anom_flags": feat_anom_flags} # Create export outputs export_outputs = { "predict_export_outputs": tf.estimator.export.PredictOutput( outputs=predictions_dict) } return predictions_dict, export_outputs
[ "def", "anomaly_detection_predictions", "(", "cur_batch_size", ",", "seq_len", ",", "num_feat", ",", "mahalanobis_dist_time", ",", "mahalanobis_dist_feat", ",", "time_anom_thresh_var", ",", "feat_anom_thresh_var", ",", "X_time_abs_recon_err", ",", "X_feat_abs_recon_err", ")", ":", "# Flag predictions as either normal or anomalous", "# shape = (cur_batch_size,)", "time_anom_flags", "=", "flag_anomalies_by_thresholding", "(", "cur_batch_size", ",", "mahalanobis_dist_time", ",", "time_anom_thresh_var", ")", "# shape = (cur_batch_size,)", "feat_anom_flags", "=", "flag_anomalies_by_thresholding", "(", "cur_batch_size", ",", "mahalanobis_dist_feat", ",", "feat_anom_thresh_var", ")", "# Create predictions dictionary", "predictions_dict", "=", "{", "\"X_time_abs_recon_err\"", ":", "tf", ".", "reshape", "(", "tensor", "=", "X_time_abs_recon_err", ",", "shape", "=", "[", "cur_batch_size", ",", "seq_len", ",", "num_feat", "]", ")", ",", "\"X_feat_abs_recon_err\"", ":", "tf", ".", "transpose", "(", "a", "=", "tf", ".", "reshape", "(", "tensor", "=", "X_feat_abs_recon_err", ",", "shape", "=", "[", "cur_batch_size", ",", "num_feat", ",", "seq_len", "]", ")", ",", "perm", "=", "[", "0", ",", "2", ",", "1", "]", ")", ",", "\"mahalanobis_dist_time\"", ":", "mahalanobis_dist_time", ",", "\"mahalanobis_dist_feat\"", ":", "mahalanobis_dist_feat", ",", "\"time_anom_thresh_var\"", ":", "tf", ".", "fill", "(", "dims", "=", "[", "cur_batch_size", "]", ",", "value", "=", "time_anom_thresh_var", ")", ",", "\"feat_anom_thresh_var\"", ":", "tf", ".", "fill", "(", "dims", "=", "[", "cur_batch_size", "]", ",", "value", "=", "feat_anom_thresh_var", ")", ",", "\"time_anom_flags\"", ":", "time_anom_flags", ",", "\"feat_anom_flags\"", ":", "feat_anom_flags", "}", "# Create export outputs", "export_outputs", "=", "{", "\"predict_export_outputs\"", ":", "tf", ".", "estimator", ".", "export", ".", "PredictOutput", "(", "outputs", "=", "predictions_dict", ")", "}", "return", "predictions_dict", ",", "export_outputs" ]
[ 31, 0 ]
[ 98, 41 ]
python
en
['en', 'en', 'en']
True
register_json
(conn_or_curs=None, globally=False, loads=None, oid=None, array_oid=None, name='json')
Create and register typecasters converting :sql:`json` type to Python objects. :param conn_or_curs: a connection or cursor used to find the :sql:`json` and :sql:`json[]` oids; the typecasters are registered in a scope limited to this object, unless *globally* is set to `!True`. It can be `!None` if the oids are provided :param globally: if `!False` register the typecasters only on *conn_or_curs*, otherwise register them globally :param loads: the function used to parse the data into a Python object. If `!None` use `!json.loads()`, where `!json` is the module chosen according to the Python version (see above) :param oid: the OID of the :sql:`json` type if known; If not, it will be queried on *conn_or_curs* :param array_oid: the OID of the :sql:`json[]` array type if known; if not, it will be queried on *conn_or_curs* :param name: the name of the data type to look for in *conn_or_curs* The connection or cursor passed to the function will be used to query the database and look for the OID of the :sql:`json` type (or an alternative type if *name* if provided). No query is performed if *oid* and *array_oid* are provided. Raise `~psycopg2.ProgrammingError` if the type is not found.
Create and register typecasters converting :sql:`json` type to Python objects.
def register_json(conn_or_curs=None, globally=False, loads=None, oid=None, array_oid=None, name='json'): """Create and register typecasters converting :sql:`json` type to Python objects. :param conn_or_curs: a connection or cursor used to find the :sql:`json` and :sql:`json[]` oids; the typecasters are registered in a scope limited to this object, unless *globally* is set to `!True`. It can be `!None` if the oids are provided :param globally: if `!False` register the typecasters only on *conn_or_curs*, otherwise register them globally :param loads: the function used to parse the data into a Python object. If `!None` use `!json.loads()`, where `!json` is the module chosen according to the Python version (see above) :param oid: the OID of the :sql:`json` type if known; If not, it will be queried on *conn_or_curs* :param array_oid: the OID of the :sql:`json[]` array type if known; if not, it will be queried on *conn_or_curs* :param name: the name of the data type to look for in *conn_or_curs* The connection or cursor passed to the function will be used to query the database and look for the OID of the :sql:`json` type (or an alternative type if *name* if provided). No query is performed if *oid* and *array_oid* are provided. Raise `~psycopg2.ProgrammingError` if the type is not found. """ if oid is None: oid, array_oid = _get_json_oids(conn_or_curs, name) JSON, JSONARRAY = _create_json_typecasters( oid, array_oid, loads=loads, name=name.upper()) register_type(JSON, not globally and conn_or_curs or None) if JSONARRAY is not None: register_type(JSONARRAY, not globally and conn_or_curs or None) return JSON, JSONARRAY
[ "def", "register_json", "(", "conn_or_curs", "=", "None", ",", "globally", "=", "False", ",", "loads", "=", "None", ",", "oid", "=", "None", ",", "array_oid", "=", "None", ",", "name", "=", "'json'", ")", ":", "if", "oid", "is", "None", ":", "oid", ",", "array_oid", "=", "_get_json_oids", "(", "conn_or_curs", ",", "name", ")", "JSON", ",", "JSONARRAY", "=", "_create_json_typecasters", "(", "oid", ",", "array_oid", ",", "loads", "=", "loads", ",", "name", "=", "name", ".", "upper", "(", ")", ")", "register_type", "(", "JSON", ",", "not", "globally", "and", "conn_or_curs", "or", "None", ")", "if", "JSONARRAY", "is", "not", "None", ":", "register_type", "(", "JSONARRAY", ",", "not", "globally", "and", "conn_or_curs", "or", "None", ")", "return", "JSON", ",", "JSONARRAY" ]
[ 88, 0 ]
[ 124, 26 ]
python
en
['en', 'en', 'en']
True
register_default_json
(conn_or_curs=None, globally=False, loads=None)
Create and register :sql:`json` typecasters for PostgreSQL 9.2 and following. Since PostgreSQL 9.2 :sql:`json` is a builtin type, hence its oid is known and fixed. This function allows specifying a customized *loads* function for the default :sql:`json` type without querying the database. All the parameters have the same meaning of `register_json()`.
Create and register :sql:`json` typecasters for PostgreSQL 9.2 and following.
def register_default_json(conn_or_curs=None, globally=False, loads=None): """ Create and register :sql:`json` typecasters for PostgreSQL 9.2 and following. Since PostgreSQL 9.2 :sql:`json` is a builtin type, hence its oid is known and fixed. This function allows specifying a customized *loads* function for the default :sql:`json` type without querying the database. All the parameters have the same meaning of `register_json()`. """ return register_json(conn_or_curs=conn_or_curs, globally=globally, loads=loads, oid=JSON_OID, array_oid=JSONARRAY_OID)
[ "def", "register_default_json", "(", "conn_or_curs", "=", "None", ",", "globally", "=", "False", ",", "loads", "=", "None", ")", ":", "return", "register_json", "(", "conn_or_curs", "=", "conn_or_curs", ",", "globally", "=", "globally", ",", "loads", "=", "loads", ",", "oid", "=", "JSON_OID", ",", "array_oid", "=", "JSONARRAY_OID", ")" ]
[ 127, 0 ]
[ 137, 59 ]
python
en
['en', 'error', 'th']
False
register_default_jsonb
(conn_or_curs=None, globally=False, loads=None)
Create and register :sql:`jsonb` typecasters for PostgreSQL 9.4 and following. As in `register_default_json()`, the function allows to register a customized *loads* function for the :sql:`jsonb` type at its known oid for PostgreSQL 9.4 and following versions. All the parameters have the same meaning of `register_json()`.
Create and register :sql:`jsonb` typecasters for PostgreSQL 9.4 and following.
def register_default_jsonb(conn_or_curs=None, globally=False, loads=None): """ Create and register :sql:`jsonb` typecasters for PostgreSQL 9.4 and following. As in `register_default_json()`, the function allows to register a customized *loads* function for the :sql:`jsonb` type at its known oid for PostgreSQL 9.4 and following versions. All the parameters have the same meaning of `register_json()`. """ return register_json(conn_or_curs=conn_or_curs, globally=globally, loads=loads, oid=JSONB_OID, array_oid=JSONBARRAY_OID, name='jsonb')
[ "def", "register_default_jsonb", "(", "conn_or_curs", "=", "None", ",", "globally", "=", "False", ",", "loads", "=", "None", ")", ":", "return", "register_json", "(", "conn_or_curs", "=", "conn_or_curs", ",", "globally", "=", "globally", ",", "loads", "=", "loads", ",", "oid", "=", "JSONB_OID", ",", "array_oid", "=", "JSONBARRAY_OID", ",", "name", "=", "'jsonb'", ")" ]
[ 140, 0 ]
[ 150, 75 ]
python
en
['en', 'error', 'th']
False
_create_json_typecasters
(oid, array_oid, loads=None, name='JSON')
Create typecasters for json data type.
Create typecasters for json data type.
def _create_json_typecasters(oid, array_oid, loads=None, name='JSON'): """Create typecasters for json data type.""" if loads is None: loads = json.loads def typecast_json(s, cur): if s is None: return None return loads(s) JSON = new_type((oid, ), name, typecast_json) if array_oid is not None: JSONARRAY = new_array_type((array_oid, ), f"{name}ARRAY", JSON) else: JSONARRAY = None return JSON, JSONARRAY
[ "def", "_create_json_typecasters", "(", "oid", ",", "array_oid", ",", "loads", "=", "None", ",", "name", "=", "'JSON'", ")", ":", "if", "loads", "is", "None", ":", "loads", "=", "json", ".", "loads", "def", "typecast_json", "(", "s", ",", "cur", ")", ":", "if", "s", "is", "None", ":", "return", "None", "return", "loads", "(", "s", ")", "JSON", "=", "new_type", "(", "(", "oid", ",", ")", ",", "name", ",", "typecast_json", ")", "if", "array_oid", "is", "not", "None", ":", "JSONARRAY", "=", "new_array_type", "(", "(", "array_oid", ",", ")", ",", "f\"{name}ARRAY\"", ",", "JSON", ")", "else", ":", "JSONARRAY", "=", "None", "return", "JSON", ",", "JSONARRAY" ]
[ 153, 0 ]
[ 169, 26 ]
python
en
['en', 'en', 'en']
True
Json.dumps
(self, obj)
Serialize *obj* in JSON format. The default is to call `!json.dumps()` or the *dumps* function provided in the constructor. You can override this method to create a customized JSON wrapper.
Serialize *obj* in JSON format.
def dumps(self, obj): """Serialize *obj* in JSON format. The default is to call `!json.dumps()` or the *dumps* function provided in the constructor. You can override this method to create a customized JSON wrapper. """ return self._dumps(obj)
[ "def", "dumps", "(", "self", ",", "obj", ")", ":", "return", "self", ".", "_dumps", "(", "obj", ")" ]
[ 64, 4 ]
[ 71, 31 ]
python
en
['en', 'fy', 'it']
False
develop._resolve_setup_path
(egg_base, install_dir, egg_path)
Generate a path from egg_base back to '.' where the setup script resides and ensure that path points to the setup path from $install_dir/$egg_path.
Generate a path from egg_base back to '.' where the setup script resides and ensure that path points to the setup path from $install_dir/$egg_path.
def _resolve_setup_path(egg_base, install_dir, egg_path): """ Generate a path from egg_base back to '.' where the setup script resides and ensure that path points to the setup path from $install_dir/$egg_path. """ path_to_setup = egg_base.replace(os.sep, '/').rstrip('/') if path_to_setup != os.curdir: path_to_setup = '../' * (path_to_setup.count('/') + 1) resolved = normalize_path( os.path.join(install_dir, egg_path, path_to_setup) ) if resolved != normalize_path(os.curdir): raise DistutilsOptionError( "Can't get a consistent path to setup script from" " installation directory", resolved, normalize_path(os.curdir)) return path_to_setup
[ "def", "_resolve_setup_path", "(", "egg_base", ",", "install_dir", ",", "egg_path", ")", ":", "path_to_setup", "=", "egg_base", ".", "replace", "(", "os", ".", "sep", ",", "'/'", ")", ".", "rstrip", "(", "'/'", ")", "if", "path_to_setup", "!=", "os", ".", "curdir", ":", "path_to_setup", "=", "'../'", "*", "(", "path_to_setup", ".", "count", "(", "'/'", ")", "+", "1", ")", "resolved", "=", "normalize_path", "(", "os", ".", "path", ".", "join", "(", "install_dir", ",", "egg_path", ",", "path_to_setup", ")", ")", "if", "resolved", "!=", "normalize_path", "(", "os", ".", "curdir", ")", ":", "raise", "DistutilsOptionError", "(", "\"Can't get a consistent path to setup script from\"", "\" installation directory\"", ",", "resolved", ",", "normalize_path", "(", "os", ".", "curdir", ")", ")", "return", "path_to_setup" ]
[ 88, 4 ]
[ 104, 28 ]
python
en
['en', 'error', 'th']
False
_overload_dummy
(*args, **kwds)
Helper for @overload to raise when called.
Helper for
def _overload_dummy(*args, **kwds): """Helper for @overload to raise when called.""" raise NotImplementedError( "You should not call an overloaded function. " "A series of @overload-decorated functions " "outside a stub module should always be followed " "by an implementation that is not @overload-ed.")
[ "def", "_overload_dummy", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "raise", "NotImplementedError", "(", "\"You should not call an overloaded function. \"", "\"A series of @overload-decorated functions \"", "\"outside a stub module should always be followed \"", "\"by an implementation that is not @overload-ed.\"", ")" ]
[ 684, 0 ]
[ 690, 57 ]
python
en
['en', 'en', 'en']
True
overload
(func)
Decorator for overloaded functions/methods. In a stub file, place two or more stub definitions for the same function in a row, each decorated with @overload. For example: @overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ... In a non-stub file (i.e. a regular .py file), do the same but follow it with an implementation. The implementation should *not* be decorated with @overload. For example: @overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ... def utf8(value): # implementation goes here
Decorator for overloaded functions/methods.
def overload(func): """Decorator for overloaded functions/methods. In a stub file, place two or more stub definitions for the same function in a row, each decorated with @overload. For example: @overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ... In a non-stub file (i.e. a regular .py file), do the same but follow it with an implementation. The implementation should *not* be decorated with @overload. For example: @overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ... def utf8(value): # implementation goes here """ return _overload_dummy
[ "def", "overload", "(", "func", ")", ":", "return", "_overload_dummy" ]
[ 693, 0 ]
[ 719, 26 ]
python
en
['en', 'en', 'en']
True
_define_guard
(type_name)
Returns True if the given type isn't defined in typing but is defined in collections_abc. Adds the type to __all__ if the collection is found in either typing or collection_abc.
Returns True if the given type isn't defined in typing but is defined in collections_abc.
def _define_guard(type_name): """ Returns True if the given type isn't defined in typing but is defined in collections_abc. Adds the type to __all__ if the collection is found in either typing or collection_abc. """ if hasattr(typing, type_name): __all__.append(type_name) globals()[type_name] = getattr(typing, type_name) return False elif hasattr(collections_abc, type_name): __all__.append(type_name) return True else: return False
[ "def", "_define_guard", "(", "type_name", ")", ":", "if", "hasattr", "(", "typing", ",", "type_name", ")", ":", "__all__", ".", "append", "(", "type_name", ")", "globals", "(", ")", "[", "type_name", "]", "=", "getattr", "(", "typing", ",", "type_name", ")", "return", "False", "elif", "hasattr", "(", "collections_abc", ",", "type_name", ")", ":", "__all__", ".", "append", "(", "type_name", ")", "return", "True", "else", ":", "return", "False" ]
[ 758, 0 ]
[ 774, 20 ]
python
en
['en', 'error', 'th']
False
_gorg
(cls)
This function exists for compatibility with old typing versions.
This function exists for compatibility with old typing versions.
def _gorg(cls): """This function exists for compatibility with old typing versions.""" assert isinstance(cls, GenericMeta) if hasattr(cls, '_gorg'): return cls._gorg while cls.__origin__ is not None: cls = cls.__origin__ return cls
[ "def", "_gorg", "(", "cls", ")", ":", "assert", "isinstance", "(", "cls", ",", "GenericMeta", ")", "if", "hasattr", "(", "cls", ",", "'_gorg'", ")", ":", "return", "cls", ".", "_gorg", "while", "cls", ".", "__origin__", "is", "not", "None", ":", "cls", "=", "cls", ".", "__origin__", "return", "cls" ]
[ 1103, 0 ]
[ 1110, 14 ]
python
en
['en', 'en', 'en']
True
_ExtensionsGenericMeta.__subclasscheck__
(self, subclass)
This mimics a more modern GenericMeta.__subclasscheck__() logic (that does not have problems with recursion) to work around interactions between collections, typing, and typing_extensions on older versions of Python, see https://github.com/python/typing/issues/501.
This mimics a more modern GenericMeta.__subclasscheck__() logic (that does not have problems with recursion) to work around interactions between collections, typing, and typing_extensions on older versions of Python, see https://github.com/python/typing/issues/501.
def __subclasscheck__(self, subclass): """This mimics a more modern GenericMeta.__subclasscheck__() logic (that does not have problems with recursion) to work around interactions between collections, typing, and typing_extensions on older versions of Python, see https://github.com/python/typing/issues/501. """ if sys.version_info[:3] >= (3, 5, 3) or sys.version_info[:3] < (3, 5, 0): if self.__origin__ is not None: if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']: raise TypeError("Parameterized generics cannot be used with class " "or instance checks") return False if not self.__extra__: return super().__subclasscheck__(subclass) res = self.__extra__.__subclasshook__(subclass) if res is not NotImplemented: return res if self.__extra__ in subclass.__mro__: return True for scls in self.__extra__.__subclasses__(): if isinstance(scls, GenericMeta): continue if issubclass(subclass, scls): return True return False
[ "def", "__subclasscheck__", "(", "self", ",", "subclass", ")", ":", "if", "sys", ".", "version_info", "[", ":", "3", "]", ">=", "(", "3", ",", "5", ",", "3", ")", "or", "sys", ".", "version_info", "[", ":", "3", "]", "<", "(", "3", ",", "5", ",", "0", ")", ":", "if", "self", ".", "__origin__", "is", "not", "None", ":", "if", "sys", ".", "_getframe", "(", "1", ")", ".", "f_globals", "[", "'__name__'", "]", "not", "in", "[", "'abc'", ",", "'functools'", "]", ":", "raise", "TypeError", "(", "\"Parameterized generics cannot be used with class \"", "\"or instance checks\"", ")", "return", "False", "if", "not", "self", ".", "__extra__", ":", "return", "super", "(", ")", ".", "__subclasscheck__", "(", "subclass", ")", "res", "=", "self", ".", "__extra__", ".", "__subclasshook__", "(", "subclass", ")", "if", "res", "is", "not", "NotImplemented", ":", "return", "res", "if", "self", ".", "__extra__", "in", "subclass", ".", "__mro__", ":", "return", "True", "for", "scls", "in", "self", ".", "__extra__", ".", "__subclasses__", "(", ")", ":", "if", "isinstance", "(", "scls", ",", "GenericMeta", ")", ":", "continue", "if", "issubclass", "(", "subclass", ",", "scls", ")", ":", "return", "True", "return", "False" ]
[ 778, 4 ]
[ 802, 20 ]
python
en
['en', 'ca', 'en']
True
forbid_multi_line_headers
(name, val, encoding)
Forbid multi-line headers to prevent header injection.
Forbid multi-line headers to prevent header injection.
def forbid_multi_line_headers(name, val, encoding): """Forbid multi-line headers to prevent header injection.""" encoding = encoding or settings.DEFAULT_CHARSET val = str(val) # val may be lazy if '\n' in val or '\r' in val: raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name)) try: val.encode('ascii') except UnicodeEncodeError: if name.lower() in ADDRESS_HEADERS: val = ', '.join(sanitize_address(addr, encoding) for addr in getaddresses((val,))) else: val = Header(val, encoding).encode() else: if name.lower() == 'subject': val = Header(val).encode() return name, val
[ "def", "forbid_multi_line_headers", "(", "name", ",", "val", ",", "encoding", ")", ":", "encoding", "=", "encoding", "or", "settings", ".", "DEFAULT_CHARSET", "val", "=", "str", "(", "val", ")", "# val may be lazy", "if", "'\\n'", "in", "val", "or", "'\\r'", "in", "val", ":", "raise", "BadHeaderError", "(", "\"Header values can't contain newlines (got %r for header %r)\"", "%", "(", "val", ",", "name", ")", ")", "try", ":", "val", ".", "encode", "(", "'ascii'", ")", "except", "UnicodeEncodeError", ":", "if", "name", ".", "lower", "(", ")", "in", "ADDRESS_HEADERS", ":", "val", "=", "', '", ".", "join", "(", "sanitize_address", "(", "addr", ",", "encoding", ")", "for", "addr", "in", "getaddresses", "(", "(", "val", ",", ")", ")", ")", "else", ":", "val", "=", "Header", "(", "val", ",", "encoding", ")", ".", "encode", "(", ")", "else", ":", "if", "name", ".", "lower", "(", ")", "==", "'subject'", ":", "val", "=", "Header", "(", "val", ")", ".", "encode", "(", ")", "return", "name", ",", "val" ]
[ 54, 0 ]
[ 70, 20 ]
python
en
['en', 'en', 'en']
True
sanitize_address
(addr, encoding)
Format a pair of (name, address) or an email address string.
Format a pair of (name, address) or an email address string.
def sanitize_address(addr, encoding): """ Format a pair of (name, address) or an email address string. """ address = None if not isinstance(addr, tuple): addr = force_str(addr) try: token, rest = parser.get_mailbox(addr) except (HeaderParseError, ValueError, IndexError): raise ValueError('Invalid address "%s"' % addr) else: if rest: # The entire email address must be parsed. raise ValueError( 'Invalid address; only %s could be parsed from "%s"' % (token, addr) ) nm = token.display_name or '' localpart = token.local_part domain = token.domain or '' else: nm, address = addr localpart, domain = address.rsplit('@', 1) address_parts = nm + localpart + domain if '\n' in address_parts or '\r' in address_parts: raise ValueError('Invalid address; address parts cannot contain newlines.') # Avoid UTF-8 encode, if it's possible. try: nm.encode('ascii') nm = Header(nm).encode() except UnicodeEncodeError: nm = Header(nm, encoding).encode() try: localpart.encode('ascii') except UnicodeEncodeError: localpart = Header(localpart, encoding).encode() domain = punycode(domain) parsed_address = Address(username=localpart, domain=domain) return formataddr((nm, parsed_address.addr_spec))
[ "def", "sanitize_address", "(", "addr", ",", "encoding", ")", ":", "address", "=", "None", "if", "not", "isinstance", "(", "addr", ",", "tuple", ")", ":", "addr", "=", "force_str", "(", "addr", ")", "try", ":", "token", ",", "rest", "=", "parser", ".", "get_mailbox", "(", "addr", ")", "except", "(", "HeaderParseError", ",", "ValueError", ",", "IndexError", ")", ":", "raise", "ValueError", "(", "'Invalid address \"%s\"'", "%", "addr", ")", "else", ":", "if", "rest", ":", "# The entire email address must be parsed.", "raise", "ValueError", "(", "'Invalid address; only %s could be parsed from \"%s\"'", "%", "(", "token", ",", "addr", ")", ")", "nm", "=", "token", ".", "display_name", "or", "''", "localpart", "=", "token", ".", "local_part", "domain", "=", "token", ".", "domain", "or", "''", "else", ":", "nm", ",", "address", "=", "addr", "localpart", ",", "domain", "=", "address", ".", "rsplit", "(", "'@'", ",", "1", ")", "address_parts", "=", "nm", "+", "localpart", "+", "domain", "if", "'\\n'", "in", "address_parts", "or", "'\\r'", "in", "address_parts", ":", "raise", "ValueError", "(", "'Invalid address; address parts cannot contain newlines.'", ")", "# Avoid UTF-8 encode, if it's possible.", "try", ":", "nm", ".", "encode", "(", "'ascii'", ")", "nm", "=", "Header", "(", "nm", ")", ".", "encode", "(", ")", "except", "UnicodeEncodeError", ":", "nm", "=", "Header", "(", "nm", ",", "encoding", ")", ".", "encode", "(", ")", "try", ":", "localpart", ".", "encode", "(", "'ascii'", ")", "except", "UnicodeEncodeError", ":", "localpart", "=", "Header", "(", "localpart", ",", "encoding", ")", ".", "encode", "(", ")", "domain", "=", "punycode", "(", "domain", ")", "parsed_address", "=", "Address", "(", "username", "=", "localpart", ",", "domain", "=", "domain", ")", "return", "formataddr", "(", "(", "nm", ",", "parsed_address", ".", "addr_spec", ")", ")" ]
[ 73, 0 ]
[ 115, 53 ]
python
en
['en', 'error', 'th']
False
MIMEMixin.as_string
(self, unixfrom=False, linesep='\n')
Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_string() implementation to not mangle lines that begin with 'From '. See bug #13433 for details.
Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header.
def as_string(self, unixfrom=False, linesep='\n'): """Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_string() implementation to not mangle lines that begin with 'From '. See bug #13433 for details. """ fp = StringIO() g = generator.Generator(fp, mangle_from_=False) g.flatten(self, unixfrom=unixfrom, linesep=linesep) return fp.getvalue()
[ "def", "as_string", "(", "self", ",", "unixfrom", "=", "False", ",", "linesep", "=", "'\\n'", ")", ":", "fp", "=", "StringIO", "(", ")", "g", "=", "generator", ".", "Generator", "(", "fp", ",", "mangle_from_", "=", "False", ")", "g", ".", "flatten", "(", "self", ",", "unixfrom", "=", "unixfrom", ",", "linesep", "=", "linesep", ")", "return", "fp", ".", "getvalue", "(", ")" ]
[ 119, 4 ]
[ 130, 28 ]
python
en
['en', 'en', 'en']
True
MIMEMixin.as_bytes
(self, unixfrom=False, linesep='\n')
Return the entire formatted message as bytes. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_bytes() implementation to not mangle lines that begin with 'From '. See bug #13433 for details.
Return the entire formatted message as bytes. Optional `unixfrom' when True, means include the Unix From_ envelope header.
def as_bytes(self, unixfrom=False, linesep='\n'): """Return the entire formatted message as bytes. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_bytes() implementation to not mangle lines that begin with 'From '. See bug #13433 for details. """ fp = BytesIO() g = generator.BytesGenerator(fp, mangle_from_=False) g.flatten(self, unixfrom=unixfrom, linesep=linesep) return fp.getvalue()
[ "def", "as_bytes", "(", "self", ",", "unixfrom", "=", "False", ",", "linesep", "=", "'\\n'", ")", ":", "fp", "=", "BytesIO", "(", ")", "g", "=", "generator", ".", "BytesGenerator", "(", "fp", ",", "mangle_from_", "=", "False", ")", "g", ".", "flatten", "(", "self", ",", "unixfrom", "=", "unixfrom", ",", "linesep", "=", "linesep", ")", "return", "fp", ".", "getvalue", "(", ")" ]
[ 132, 4 ]
[ 143, 28 ]
python
en
['en', 'en', 'en']
True
EmailMessage.__init__
(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, cc=None, reply_to=None)
Initialize a single email message (which can be sent to multiple recipients).
Initialize a single email message (which can be sent to multiple recipients).
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, cc=None, reply_to=None): """ Initialize a single email message (which can be sent to multiple recipients). """ if to: if isinstance(to, str): raise TypeError('"to" argument must be a list or tuple') self.to = list(to) else: self.to = [] if cc: if isinstance(cc, str): raise TypeError('"cc" argument must be a list or tuple') self.cc = list(cc) else: self.cc = [] if bcc: if isinstance(bcc, str): raise TypeError('"bcc" argument must be a list or tuple') self.bcc = list(bcc) else: self.bcc = [] if reply_to: if isinstance(reply_to, str): raise TypeError('"reply_to" argument must be a list or tuple') self.reply_to = list(reply_to) else: self.reply_to = [] self.from_email = from_email or settings.DEFAULT_FROM_EMAIL self.subject = subject self.body = body or '' self.attachments = [] if attachments: for attachment in attachments: if isinstance(attachment, MIMEBase): self.attach(attachment) else: self.attach(*attachment) self.extra_headers = headers or {} self.connection = connection
[ "def", "__init__", "(", "self", ",", "subject", "=", "''", ",", "body", "=", "''", ",", "from_email", "=", "None", ",", "to", "=", "None", ",", "bcc", "=", "None", ",", "connection", "=", "None", ",", "attachments", "=", "None", ",", "headers", "=", "None", ",", "cc", "=", "None", ",", "reply_to", "=", "None", ")", ":", "if", "to", ":", "if", "isinstance", "(", "to", ",", "str", ")", ":", "raise", "TypeError", "(", "'\"to\" argument must be a list or tuple'", ")", "self", ".", "to", "=", "list", "(", "to", ")", "else", ":", "self", ".", "to", "=", "[", "]", "if", "cc", ":", "if", "isinstance", "(", "cc", ",", "str", ")", ":", "raise", "TypeError", "(", "'\"cc\" argument must be a list or tuple'", ")", "self", ".", "cc", "=", "list", "(", "cc", ")", "else", ":", "self", ".", "cc", "=", "[", "]", "if", "bcc", ":", "if", "isinstance", "(", "bcc", ",", "str", ")", ":", "raise", "TypeError", "(", "'\"bcc\" argument must be a list or tuple'", ")", "self", ".", "bcc", "=", "list", "(", "bcc", ")", "else", ":", "self", ".", "bcc", "=", "[", "]", "if", "reply_to", ":", "if", "isinstance", "(", "reply_to", ",", "str", ")", ":", "raise", "TypeError", "(", "'\"reply_to\" argument must be a list or tuple'", ")", "self", ".", "reply_to", "=", "list", "(", "reply_to", ")", "else", ":", "self", ".", "reply_to", "=", "[", "]", "self", ".", "from_email", "=", "from_email", "or", "settings", ".", "DEFAULT_FROM_EMAIL", "self", ".", "subject", "=", "subject", "self", ".", "body", "=", "body", "or", "''", "self", ".", "attachments", "=", "[", "]", "if", "attachments", ":", "for", "attachment", "in", "attachments", ":", "if", "isinstance", "(", "attachment", ",", "MIMEBase", ")", ":", "self", ".", "attach", "(", "attachment", ")", "else", ":", "self", ".", "attach", "(", "*", "attachment", ")", "self", ".", "extra_headers", "=", "headers", "or", "{", "}", "self", ".", "connection", "=", "connection" ]
[ 193, 4 ]
[ 235, 36 ]
python
en
['en', 'error', 'th']
False
EmailMessage.recipients
(self)
Return a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries).
Return a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries).
def recipients(self): """ Return a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries). """ return [email for email in (self.to + self.cc + self.bcc) if email]
[ "def", "recipients", "(", "self", ")", ":", "return", "[", "email", "for", "email", "in", "(", "self", ".", "to", "+", "self", ".", "cc", "+", "self", ".", "bcc", ")", "if", "email", "]" ]
[ 270, 4 ]
[ 275, 75 ]
python
en
['en', 'error', 'th']
False
EmailMessage.send
(self, fail_silently=False)
Send the email message.
Send the email message.
def send(self, fail_silently=False): """Send the email message.""" if not self.recipients(): # Don't bother creating the network connection if there's nobody to # send to. return 0 return self.get_connection(fail_silently).send_messages([self])
[ "def", "send", "(", "self", ",", "fail_silently", "=", "False", ")", ":", "if", "not", "self", ".", "recipients", "(", ")", ":", "# Don't bother creating the network connection if there's nobody to", "# send to.", "return", "0", "return", "self", ".", "get_connection", "(", "fail_silently", ")", ".", "send_messages", "(", "[", "self", "]", ")" ]
[ 277, 4 ]
[ 283, 71 ]
python
en
['en', 'en', 'en']
True
EmailMessage.attach
(self, filename=None, content=None, mimetype=None)
Attach a file with the given filename and content. The filename can be omitted and the mimetype is guessed, if not provided. If the first parameter is a MIMEBase subclass, insert it directly into the resulting message attachments. For a text/* mimetype (guessed or specified), when a bytes object is specified as content, decode it as UTF-8. If that fails, set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content.
Attach a file with the given filename and content. The filename can be omitted and the mimetype is guessed, if not provided.
def attach(self, filename=None, content=None, mimetype=None): """ Attach a file with the given filename and content. The filename can be omitted and the mimetype is guessed, if not provided. If the first parameter is a MIMEBase subclass, insert it directly into the resulting message attachments. For a text/* mimetype (guessed or specified), when a bytes object is specified as content, decode it as UTF-8. If that fails, set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content. """ if isinstance(filename, MIMEBase): assert content is None assert mimetype is None self.attachments.append(filename) else: assert content is not None mimetype = mimetype or mimetypes.guess_type(filename)[0] or DEFAULT_ATTACHMENT_MIME_TYPE basetype, subtype = mimetype.split('/', 1) if basetype == 'text': if isinstance(content, bytes): try: content = content.decode() except UnicodeDecodeError: # If mimetype suggests the file is text but it's # actually binary, read() raises a UnicodeDecodeError. mimetype = DEFAULT_ATTACHMENT_MIME_TYPE self.attachments.append((filename, content, mimetype))
[ "def", "attach", "(", "self", ",", "filename", "=", "None", ",", "content", "=", "None", ",", "mimetype", "=", "None", ")", ":", "if", "isinstance", "(", "filename", ",", "MIMEBase", ")", ":", "assert", "content", "is", "None", "assert", "mimetype", "is", "None", "self", ".", "attachments", ".", "append", "(", "filename", ")", "else", ":", "assert", "content", "is", "not", "None", "mimetype", "=", "mimetype", "or", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "0", "]", "or", "DEFAULT_ATTACHMENT_MIME_TYPE", "basetype", ",", "subtype", "=", "mimetype", ".", "split", "(", "'/'", ",", "1", ")", "if", "basetype", "==", "'text'", ":", "if", "isinstance", "(", "content", ",", "bytes", ")", ":", "try", ":", "content", "=", "content", ".", "decode", "(", ")", "except", "UnicodeDecodeError", ":", "# If mimetype suggests the file is text but it's", "# actually binary, read() raises a UnicodeDecodeError.", "mimetype", "=", "DEFAULT_ATTACHMENT_MIME_TYPE", "self", ".", "attachments", ".", "append", "(", "(", "filename", ",", "content", ",", "mimetype", ")", ")" ]
[ 285, 4 ]
[ 315, 66 ]
python
en
['en', 'error', 'th']
False
EmailMessage.attach_file
(self, path, mimetype=None)
Attach a file from the filesystem. Set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE if it isn't specified and cannot be guessed. For a text/* mimetype (guessed or specified), decode the file's content as UTF-8. If that fails, set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content.
Attach a file from the filesystem.
def attach_file(self, path, mimetype=None): """ Attach a file from the filesystem. Set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE if it isn't specified and cannot be guessed. For a text/* mimetype (guessed or specified), decode the file's content as UTF-8. If that fails, set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content. """ path = Path(path) with path.open('rb') as file: content = file.read() self.attach(path.name, content, mimetype)
[ "def", "attach_file", "(", "self", ",", "path", ",", "mimetype", "=", "None", ")", ":", "path", "=", "Path", "(", "path", ")", "with", "path", ".", "open", "(", "'rb'", ")", "as", "file", ":", "content", "=", "file", ".", "read", "(", ")", "self", ".", "attach", "(", "path", ".", "name", ",", "content", ",", "mimetype", ")" ]
[ 317, 4 ]
[ 331, 53 ]
python
en
['en', 'error', 'th']
False
EmailMessage._create_mime_attachment
(self, content, mimetype)
Convert the content, mimetype pair into a MIME attachment object. If the mimetype is message/rfc822, content may be an email.Message or EmailMessage object, as well as a str.
Convert the content, mimetype pair into a MIME attachment object.
def _create_mime_attachment(self, content, mimetype): """ Convert the content, mimetype pair into a MIME attachment object. If the mimetype is message/rfc822, content may be an email.Message or EmailMessage object, as well as a str. """ basetype, subtype = mimetype.split('/', 1) if basetype == 'text': encoding = self.encoding or settings.DEFAULT_CHARSET attachment = SafeMIMEText(content, subtype, encoding) elif basetype == 'message' and subtype == 'rfc822': # Bug #18967: per RFC2046 s5.2.1, message/rfc822 attachments # must not be base64 encoded. if isinstance(content, EmailMessage): # convert content into an email.Message first content = content.message() elif not isinstance(content, Message): # For compatibility with existing code, parse the message # into an email.Message object if it is not one already. content = message_from_string(force_str(content)) attachment = SafeMIMEMessage(content, subtype) else: # Encode non-text attachments with base64. attachment = MIMEBase(basetype, subtype) attachment.set_payload(content) Encoders.encode_base64(attachment) return attachment
[ "def", "_create_mime_attachment", "(", "self", ",", "content", ",", "mimetype", ")", ":", "basetype", ",", "subtype", "=", "mimetype", ".", "split", "(", "'/'", ",", "1", ")", "if", "basetype", "==", "'text'", ":", "encoding", "=", "self", ".", "encoding", "or", "settings", ".", "DEFAULT_CHARSET", "attachment", "=", "SafeMIMEText", "(", "content", ",", "subtype", ",", "encoding", ")", "elif", "basetype", "==", "'message'", "and", "subtype", "==", "'rfc822'", ":", "# Bug #18967: per RFC2046 s5.2.1, message/rfc822 attachments", "# must not be base64 encoded.", "if", "isinstance", "(", "content", ",", "EmailMessage", ")", ":", "# convert content into an email.Message first", "content", "=", "content", ".", "message", "(", ")", "elif", "not", "isinstance", "(", "content", ",", "Message", ")", ":", "# For compatibility with existing code, parse the message", "# into an email.Message object if it is not one already.", "content", "=", "message_from_string", "(", "force_str", "(", "content", ")", ")", "attachment", "=", "SafeMIMEMessage", "(", "content", ",", "subtype", ")", "else", ":", "# Encode non-text attachments with base64.", "attachment", "=", "MIMEBase", "(", "basetype", ",", "subtype", ")", "attachment", ".", "set_payload", "(", "content", ")", "Encoders", ".", "encode_base64", "(", "attachment", ")", "return", "attachment" ]
[ 350, 4 ]
[ 378, 25 ]
python
en
['en', 'error', 'th']
False
EmailMessage._create_attachment
(self, filename, content, mimetype=None)
Convert the filename, content, mimetype triple into a MIME attachment object.
Convert the filename, content, mimetype triple into a MIME attachment object.
def _create_attachment(self, filename, content, mimetype=None): """ Convert the filename, content, mimetype triple into a MIME attachment object. """ attachment = self._create_mime_attachment(content, mimetype) if filename: try: filename.encode('ascii') except UnicodeEncodeError: filename = ('utf-8', '', filename) attachment.add_header('Content-Disposition', 'attachment', filename=filename) return attachment
[ "def", "_create_attachment", "(", "self", ",", "filename", ",", "content", ",", "mimetype", "=", "None", ")", ":", "attachment", "=", "self", ".", "_create_mime_attachment", "(", "content", ",", "mimetype", ")", "if", "filename", ":", "try", ":", "filename", ".", "encode", "(", "'ascii'", ")", "except", "UnicodeEncodeError", ":", "filename", "=", "(", "'utf-8'", ",", "''", ",", "filename", ")", "attachment", ".", "add_header", "(", "'Content-Disposition'", ",", "'attachment'", ",", "filename", "=", "filename", ")", "return", "attachment" ]
[ 380, 4 ]
[ 392, 25 ]
python
en
['en', 'error', 'th']
False
EmailMessage._set_list_header_if_not_empty
(self, msg, header, values)
Set msg's header, either from self.extra_headers, if present, or from the values argument.
Set msg's header, either from self.extra_headers, if present, or from the values argument.
def _set_list_header_if_not_empty(self, msg, header, values): """ Set msg's header, either from self.extra_headers, if present, or from the values argument. """ if values: try: value = self.extra_headers[header] except KeyError: value = ', '.join(str(v) for v in values) msg[header] = value
[ "def", "_set_list_header_if_not_empty", "(", "self", ",", "msg", ",", "header", ",", "values", ")", ":", "if", "values", ":", "try", ":", "value", "=", "self", ".", "extra_headers", "[", "header", "]", "except", "KeyError", ":", "value", "=", "', '", ".", "join", "(", "str", "(", "v", ")", "for", "v", "in", "values", ")", "msg", "[", "header", "]", "=", "value" ]
[ 394, 4 ]
[ 404, 31 ]
python
en
['en', 'error', 'th']
False
EmailMultiAlternatives.__init__
(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, alternatives=None, cc=None, reply_to=None)
Initialize a single email message (which can be sent to multiple recipients).
Initialize a single email message (which can be sent to multiple recipients).
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None, connection=None, attachments=None, headers=None, alternatives=None, cc=None, reply_to=None): """ Initialize a single email message (which can be sent to multiple recipients). """ super().__init__( subject, body, from_email, to, bcc, connection, attachments, headers, cc, reply_to, ) self.alternatives = alternatives or []
[ "def", "__init__", "(", "self", ",", "subject", "=", "''", ",", "body", "=", "''", ",", "from_email", "=", "None", ",", "to", "=", "None", ",", "bcc", "=", "None", ",", "connection", "=", "None", ",", "attachments", "=", "None", ",", "headers", "=", "None", ",", "alternatives", "=", "None", ",", "cc", "=", "None", ",", "reply_to", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", "subject", ",", "body", ",", "from_email", ",", "to", ",", "bcc", ",", "connection", ",", "attachments", ",", "headers", ",", "cc", ",", "reply_to", ",", ")", "self", ".", "alternatives", "=", "alternatives", "or", "[", "]" ]
[ 415, 4 ]
[ 426, 46 ]
python
en
['en', 'error', 'th']
False
EmailMultiAlternatives.attach_alternative
(self, content, mimetype)
Attach an alternative content representation.
Attach an alternative content representation.
def attach_alternative(self, content, mimetype): """Attach an alternative content representation.""" assert content is not None assert mimetype is not None self.alternatives.append((content, mimetype))
[ "def", "attach_alternative", "(", "self", ",", "content", ",", "mimetype", ")", ":", "assert", "content", "is", "not", "None", "assert", "mimetype", "is", "not", "None", "self", ".", "alternatives", ".", "append", "(", "(", "content", ",", "mimetype", ")", ")" ]
[ 428, 4 ]
[ 432, 53 ]
python
en
['en', 'lb', 'en']
True
Subversion.get_revision
(cls, location)
Return the maximum revision for all files under a given location
Return the maximum revision for all files under a given location
def get_revision(cls, location): # type: (str) -> str """ Return the maximum revision for all files under a given location """ # Note: taken from setuptools.command.egg_info revision = 0 for base, dirs, _ in os.walk(location): if cls.dirname not in dirs: dirs[:] = [] continue # no sense walking uncontrolled subdirs dirs.remove(cls.dirname) entries_fn = os.path.join(base, cls.dirname, 'entries') if not os.path.exists(entries_fn): # FIXME: should we warn? continue dirurl, localrev = cls._get_svn_url_rev(base) if base == location: assert dirurl is not None base = dirurl + '/' # save the root url elif not dirurl or not dirurl.startswith(base): dirs[:] = [] continue # not part of the same svn tree, skip it revision = max(revision, localrev) return str(revision)
[ "def", "get_revision", "(", "cls", ",", "location", ")", ":", "# type: (str) -> str", "# Note: taken from setuptools.command.egg_info", "revision", "=", "0", "for", "base", ",", "dirs", ",", "_", "in", "os", ".", "walk", "(", "location", ")", ":", "if", "cls", ".", "dirname", "not", "in", "dirs", ":", "dirs", "[", ":", "]", "=", "[", "]", "continue", "# no sense walking uncontrolled subdirs", "dirs", ".", "remove", "(", "cls", ".", "dirname", ")", "entries_fn", "=", "os", ".", "path", ".", "join", "(", "base", ",", "cls", ".", "dirname", ",", "'entries'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "entries_fn", ")", ":", "# FIXME: should we warn?", "continue", "dirurl", ",", "localrev", "=", "cls", ".", "_get_svn_url_rev", "(", "base", ")", "if", "base", "==", "location", ":", "assert", "dirurl", "is", "not", "None", "base", "=", "dirurl", "+", "'/'", "# save the root url", "elif", "not", "dirurl", "or", "not", "dirurl", ".", "startswith", "(", "base", ")", ":", "dirs", "[", ":", "]", "=", "[", "]", "continue", "# not part of the same svn tree, skip it", "revision", "=", "max", "(", "revision", ",", "localrev", ")", "return", "str", "(", "revision", ")" ]
[ 48, 4 ]
[ 75, 28 ]
python
en
['en', 'error', 'th']
False
Subversion.get_netloc_and_auth
(cls, netloc, scheme)
This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL.
This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL.
def get_netloc_and_auth(cls, netloc, scheme): # type: (str, str) -> Tuple[str, Tuple[Optional[str], Optional[str]]] """ This override allows the auth information to be passed to svn via the --username and --password options instead of via the URL. """ if scheme == 'ssh': # The --username and --password options can't be used for # svn+ssh URLs, so keep the auth information in the URL. return super().get_netloc_and_auth(netloc, scheme) return split_auth_from_netloc(netloc)
[ "def", "get_netloc_and_auth", "(", "cls", ",", "netloc", ",", "scheme", ")", ":", "# type: (str, str) -> Tuple[str, Tuple[Optional[str], Optional[str]]]", "if", "scheme", "==", "'ssh'", ":", "# The --username and --password options can't be used for", "# svn+ssh URLs, so keep the auth information in the URL.", "return", "super", "(", ")", ".", "get_netloc_and_auth", "(", "netloc", ",", "scheme", ")", "return", "split_auth_from_netloc", "(", "netloc", ")" ]
[ 78, 4 ]
[ 89, 45 ]
python
en
['en', 'error', 'th']
False
Subversion.is_commit_id_equal
(cls, dest, name)
Always assume the versions don't match
Always assume the versions don't match
def is_commit_id_equal(cls, dest, name): # type: (str, Optional[str]) -> bool """Always assume the versions don't match""" return False
[ "def", "is_commit_id_equal", "(", "cls", ",", "dest", ",", "name", ")", ":", "# type: (str, Optional[str]) -> bool", "return", "False" ]
[ 192, 4 ]
[ 195, 20 ]
python
en
['en', 'en', 'en']
True
Subversion.call_vcs_version
(self)
Query the version of the currently installed Subversion client. :return: A tuple containing the parts of the version information or ``()`` if the version returned from ``svn`` could not be parsed. :raises: BadCommand: If ``svn`` is not installed.
Query the version of the currently installed Subversion client.
def call_vcs_version(self): # type: () -> Tuple[int, ...] """Query the version of the currently installed Subversion client. :return: A tuple containing the parts of the version information or ``()`` if the version returned from ``svn`` could not be parsed. :raises: BadCommand: If ``svn`` is not installed. """ # Example versions: # svn, version 1.10.3 (r1842928) # compiled Feb 25 2019, 14:20:39 on x86_64-apple-darwin17.0.0 # svn, version 1.7.14 (r1542130) # compiled Mar 28 2018, 08:49:13 on x86_64-pc-linux-gnu # svn, version 1.12.0-SlikSvn (SlikSvn/1.12.0) # compiled May 28 2019, 13:44:56 on x86_64-microsoft-windows6.2 version_prefix = 'svn, version ' version = self.run_command( ['--version'], show_stdout=False, stdout_only=True ) if not version.startswith(version_prefix): return () version = version[len(version_prefix):].split()[0] version_list = version.partition('-')[0].split('.') try: parsed_version = tuple(map(int, version_list)) except ValueError: return () return parsed_version
[ "def", "call_vcs_version", "(", "self", ")", ":", "# type: () -> Tuple[int, ...]", "# Example versions:", "# svn, version 1.10.3 (r1842928)", "# compiled Feb 25 2019, 14:20:39 on x86_64-apple-darwin17.0.0", "# svn, version 1.7.14 (r1542130)", "# compiled Mar 28 2018, 08:49:13 on x86_64-pc-linux-gnu", "# svn, version 1.12.0-SlikSvn (SlikSvn/1.12.0)", "# compiled May 28 2019, 13:44:56 on x86_64-microsoft-windows6.2", "version_prefix", "=", "'svn, version '", "version", "=", "self", ".", "run_command", "(", "[", "'--version'", "]", ",", "show_stdout", "=", "False", ",", "stdout_only", "=", "True", ")", "if", "not", "version", ".", "startswith", "(", "version_prefix", ")", ":", "return", "(", ")", "version", "=", "version", "[", "len", "(", "version_prefix", ")", ":", "]", ".", "split", "(", ")", "[", "0", "]", "version_list", "=", "version", ".", "partition", "(", "'-'", ")", "[", "0", "]", ".", "split", "(", "'.'", ")", "try", ":", "parsed_version", "=", "tuple", "(", "map", "(", "int", ",", "version_list", ")", ")", "except", "ValueError", ":", "return", "(", ")", "return", "parsed_version" ]
[ 212, 4 ]
[ 241, 29 ]
python
en
['en', 'en', 'en']
True
Subversion.get_vcs_version
(self)
Return the version of the currently installed Subversion client. If the version of the Subversion client has already been queried, a cached value will be used. :return: A tuple containing the parts of the version information or ``()`` if the version returned from ``svn`` could not be parsed. :raises: BadCommand: If ``svn`` is not installed.
Return the version of the currently installed Subversion client.
def get_vcs_version(self): # type: () -> Tuple[int, ...] """Return the version of the currently installed Subversion client. If the version of the Subversion client has already been queried, a cached value will be used. :return: A tuple containing the parts of the version information or ``()`` if the version returned from ``svn`` could not be parsed. :raises: BadCommand: If ``svn`` is not installed. """ if self._vcs_version is not None: # Use cached version, if available. # If parsing the version failed previously (empty tuple), # do not attempt to parse it again. return self._vcs_version vcs_version = self.call_vcs_version() self._vcs_version = vcs_version return vcs_version
[ "def", "get_vcs_version", "(", "self", ")", ":", "# type: () -> Tuple[int, ...]", "if", "self", ".", "_vcs_version", "is", "not", "None", ":", "# Use cached version, if available.", "# If parsing the version failed previously (empty tuple),", "# do not attempt to parse it again.", "return", "self", ".", "_vcs_version", "vcs_version", "=", "self", ".", "call_vcs_version", "(", ")", "self", ".", "_vcs_version", "=", "vcs_version", "return", "vcs_version" ]
[ 243, 4 ]
[ 262, 26 ]
python
en
['en', 'en', 'en']
True
Subversion.get_remote_call_options
(self)
Return options to be used on calls to Subversion that contact the server. These options are applicable for the following ``svn`` subcommands used in this class. - checkout - switch - update :return: A list of command line arguments to pass to ``svn``.
Return options to be used on calls to Subversion that contact the server.
def get_remote_call_options(self): # type: () -> CommandArgs """Return options to be used on calls to Subversion that contact the server. These options are applicable for the following ``svn`` subcommands used in this class. - checkout - switch - update :return: A list of command line arguments to pass to ``svn``. """ if not self.use_interactive: # --non-interactive switch is available since Subversion 0.14.4. # Subversion < 1.8 runs in interactive mode by default. return ['--non-interactive'] svn_version = self.get_vcs_version() # By default, Subversion >= 1.8 runs in non-interactive mode if # stdin is not a TTY. Since that is how pip invokes SVN, in # call_subprocess(), pip must pass --force-interactive to ensure # the user can be prompted for a password, if required. # SVN added the --force-interactive option in SVN 1.8. Since # e.g. RHEL/CentOS 7, which is supported until 2024, ships with # SVN 1.7, pip should continue to support SVN 1.7. Therefore, pip # can't safely add the option if the SVN version is < 1.8 (or unknown). if svn_version >= (1, 8): return ['--force-interactive'] return []
[ "def", "get_remote_call_options", "(", "self", ")", ":", "# type: () -> CommandArgs", "if", "not", "self", ".", "use_interactive", ":", "# --non-interactive switch is available since Subversion 0.14.4.", "# Subversion < 1.8 runs in interactive mode by default.", "return", "[", "'--non-interactive'", "]", "svn_version", "=", "self", ".", "get_vcs_version", "(", ")", "# By default, Subversion >= 1.8 runs in non-interactive mode if", "# stdin is not a TTY. Since that is how pip invokes SVN, in", "# call_subprocess(), pip must pass --force-interactive to ensure", "# the user can be prompted for a password, if required.", "# SVN added the --force-interactive option in SVN 1.8. Since", "# e.g. RHEL/CentOS 7, which is supported until 2024, ships with", "# SVN 1.7, pip should continue to support SVN 1.7. Therefore, pip", "# can't safely add the option if the SVN version is < 1.8 (or unknown).", "if", "svn_version", ">=", "(", "1", ",", "8", ")", ":", "return", "[", "'--force-interactive'", "]", "return", "[", "]" ]
[ 264, 4 ]
[ 294, 17 ]
python
en
['en', 'en', 'en']
True
Node.__init__
(self, name)
Creates a Node :arg name: The tag name associated with the node
Creates a Node
def __init__(self, name): """Creates a Node :arg name: The tag name associated with the node """ # The tag name associated with the node self.name = name # The parent of the current node (or None for the document node) self.parent = None # The value of the current node (applies to text nodes and comments) self.value = None # A dict holding name -> value pairs for attributes of the node self.attributes = {} # A list of child nodes of the current node. This must include all # elements but not necessarily other node types. self.childNodes = [] # A list of miscellaneous flags that can be set on the node. self._flags = []
[ "def", "__init__", "(", "self", ",", "name", ")", ":", "# The tag name associated with the node", "self", ".", "name", "=", "name", "# The parent of the current node (or None for the document node)", "self", ".", "parent", "=", "None", "# The value of the current node (applies to text nodes and comments)", "self", ".", "value", "=", "None", "# A dict holding name -> value pairs for attributes of the node", "self", ".", "attributes", "=", "{", "}", "# A list of child nodes of the current node. This must include all", "# elements but not necessarily other node types.", "self", ".", "childNodes", "=", "[", "]", "# A list of miscellaneous flags that can be set on the node.", "self", ".", "_flags", "=", "[", "]" ]
[ 24, 4 ]
[ 42, 24 ]
python
en
['en', 'gl', 'en']
True
Node.appendChild
(self, node)
Insert node as a child of the current node :arg node: the node to insert
Insert node as a child of the current node
def appendChild(self, node): """Insert node as a child of the current node :arg node: the node to insert """ raise NotImplementedError
[ "def", "appendChild", "(", "self", ",", "node", ")", ":", "raise", "NotImplementedError" ]
[ 56, 4 ]
[ 62, 33 ]
python
en
['en', 'en', 'en']
True
Node.insertText
(self, data, insertBefore=None)
Insert data as text in the current node, positioned before the start of node insertBefore or to the end of the node's text. :arg data: the data to insert :arg insertBefore: True if you want to insert the text before the node and False if you want to insert it after the node
Insert data as text in the current node, positioned before the start of node insertBefore or to the end of the node's text.
def insertText(self, data, insertBefore=None): """Insert data as text in the current node, positioned before the start of node insertBefore or to the end of the node's text. :arg data: the data to insert :arg insertBefore: True if you want to insert the text before the node and False if you want to insert it after the node """ raise NotImplementedError
[ "def", "insertText", "(", "self", ",", "data", ",", "insertBefore", "=", "None", ")", ":", "raise", "NotImplementedError" ]
[ 64, 4 ]
[ 74, 33 ]
python
en
['en', 'en', 'en']
True
Node.insertBefore
(self, node, refNode)
Insert node as a child of the current node, before refNode in the list of child nodes. Raises ValueError if refNode is not a child of the current node :arg node: the node to insert :arg refNode: the child node to insert the node before
Insert node as a child of the current node, before refNode in the list of child nodes. Raises ValueError if refNode is not a child of the current node
def insertBefore(self, node, refNode): """Insert node as a child of the current node, before refNode in the list of child nodes. Raises ValueError if refNode is not a child of the current node :arg node: the node to insert :arg refNode: the child node to insert the node before """ raise NotImplementedError
[ "def", "insertBefore", "(", "self", ",", "node", ",", "refNode", ")", ":", "raise", "NotImplementedError" ]
[ 76, 4 ]
[ 86, 33 ]
python
en
['en', 'en', 'en']
True
Node.removeChild
(self, node)
Remove node from the children of the current node :arg node: the child node to remove
Remove node from the children of the current node
def removeChild(self, node): """Remove node from the children of the current node :arg node: the child node to remove """ raise NotImplementedError
[ "def", "removeChild", "(", "self", ",", "node", ")", ":", "raise", "NotImplementedError" ]
[ 88, 4 ]
[ 94, 33 ]
python
en
['en', 'en', 'en']
True
Node.reparentChildren
(self, newParent)
Move all the children of the current node to newParent. This is needed so that trees that don't store text as nodes move the text in the correct way :arg newParent: the node to move all this node's children to
Move all the children of the current node to newParent. This is needed so that trees that don't store text as nodes move the text in the correct way
def reparentChildren(self, newParent): """Move all the children of the current node to newParent. This is needed so that trees that don't store text as nodes move the text in the correct way :arg newParent: the node to move all this node's children to """ # XXX - should this method be made more general? for child in self.childNodes: newParent.appendChild(child) self.childNodes = []
[ "def", "reparentChildren", "(", "self", ",", "newParent", ")", ":", "# XXX - should this method be made more general?", "for", "child", "in", "self", ".", "childNodes", ":", "newParent", ".", "appendChild", "(", "child", ")", "self", ".", "childNodes", "=", "[", "]" ]
[ 96, 4 ]
[ 107, 28 ]
python
en
['en', 'en', 'en']
True
Node.cloneNode
(self)
Return a shallow copy of the current node i.e. a node with the same name and attributes but with no parent or child nodes
Return a shallow copy of the current node i.e. a node with the same name and attributes but with no parent or child nodes
def cloneNode(self): """Return a shallow copy of the current node i.e. a node with the same name and attributes but with no parent or child nodes """ raise NotImplementedError
[ "def", "cloneNode", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 109, 4 ]
[ 113, 33 ]
python
en
['en', 'pt', 'en']
True
Node.hasContent
(self)
Return true if the node has children or text, false otherwise
Return true if the node has children or text, false otherwise
def hasContent(self): """Return true if the node has children or text, false otherwise """ raise NotImplementedError
[ "def", "hasContent", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 115, 4 ]
[ 118, 33 ]
python
en
['en', 'en', 'en']
True
TreeBuilder.__init__
(self, namespaceHTMLElements)
Create a TreeBuilder :arg namespaceHTMLElements: whether or not to namespace HTML elements
Create a TreeBuilder
def __init__(self, namespaceHTMLElements): """Create a TreeBuilder :arg namespaceHTMLElements: whether or not to namespace HTML elements """ if namespaceHTMLElements: self.defaultNamespace = "http://www.w3.org/1999/xhtml" else: self.defaultNamespace = None self.reset()
[ "def", "__init__", "(", "self", ",", "namespaceHTMLElements", ")", ":", "if", "namespaceHTMLElements", ":", "self", ".", "defaultNamespace", "=", "\"http://www.w3.org/1999/xhtml\"", "else", ":", "self", ".", "defaultNamespace", "=", "None", "self", ".", "reset", "(", ")" ]
[ 171, 4 ]
[ 181, 20 ]
python
en
['en', 'ro', 'en']
True
TreeBuilder.elementInActiveFormattingElements
(self, name)
Check if an element exists between the end of the active formatting elements and the last marker. If it does, return it, else return false
Check if an element exists between the end of the active formatting elements and the last marker. If it does, return it, else return false
def elementInActiveFormattingElements(self, name): """Check if an element exists between the end of the active formatting elements and the last marker. If it does, return it, else return false""" for item in self.activeFormattingElements[::-1]: # Check for Marker first because if it's a Marker it doesn't have a # name attribute. if item == Marker: break elif item.name == name: return item return False
[ "def", "elementInActiveFormattingElements", "(", "self", ",", "name", ")", ":", "for", "item", "in", "self", ".", "activeFormattingElements", "[", ":", ":", "-", "1", "]", ":", "# Check for Marker first because if it's a Marker it doesn't have a", "# name attribute.", "if", "item", "==", "Marker", ":", "break", "elif", "item", ".", "name", "==", "name", ":", "return", "item", "return", "False" ]
[ 268, 4 ]
[ 280, 20 ]
python
en
['en', 'en', 'en']
True
TreeBuilder.createElement
(self, token)
Create an element but don't insert it anywhere
Create an element but don't insert it anywhere
def createElement(self, token): """Create an element but don't insert it anywhere""" name = token["name"] namespace = token.get("namespace", self.defaultNamespace) element = self.elementClass(name, namespace) element.attributes = token["data"] return element
[ "def", "createElement", "(", "self", ",", "token", ")", ":", "name", "=", "token", "[", "\"name\"", "]", "namespace", "=", "token", ".", "get", "(", "\"namespace\"", ",", "self", ".", "defaultNamespace", ")", "element", "=", "self", ".", "elementClass", "(", "name", ",", "namespace", ")", "element", ".", "attributes", "=", "token", "[", "\"data\"", "]", "return", "element" ]
[ 300, 4 ]
[ 306, 22 ]
python
en
['en', 'en', 'en']
True
TreeBuilder._setInsertFromTable
(self, value)
Switch the function used to insert an element from the normal one to the misnested table one and back again
Switch the function used to insert an element from the normal one to the misnested table one and back again
def _setInsertFromTable(self, value): """Switch the function used to insert an element from the normal one to the misnested table one and back again""" self._insertFromTable = value if value: self.insertElement = self.insertElementTable else: self.insertElement = self.insertElementNormal
[ "def", "_setInsertFromTable", "(", "self", ",", "value", ")", ":", "self", ".", "_insertFromTable", "=", "value", "if", "value", ":", "self", ".", "insertElement", "=", "self", ".", "insertElementTable", "else", ":", "self", ".", "insertElement", "=", "self", ".", "insertElementNormal" ]
[ 311, 4 ]
[ 318, 57 ]
python
en
['en', 'en', 'en']
True
TreeBuilder.insertElementTable
(self, token)
Create an element and insert it into the tree
Create an element and insert it into the tree
def insertElementTable(self, token): """Create an element and insert it into the tree""" element = self.createElement(token) if self.openElements[-1].name not in tableInsertModeElements: return self.insertElementNormal(token) else: # We should be in the InTable mode. This means we want to do # special magic element rearranging parent, insertBefore = self.getTableMisnestedNodePosition() if insertBefore is None: parent.appendChild(element) else: parent.insertBefore(element, insertBefore) self.openElements.append(element) return element
[ "def", "insertElementTable", "(", "self", ",", "token", ")", ":", "element", "=", "self", ".", "createElement", "(", "token", ")", "if", "self", ".", "openElements", "[", "-", "1", "]", ".", "name", "not", "in", "tableInsertModeElements", ":", "return", "self", ".", "insertElementNormal", "(", "token", ")", "else", ":", "# We should be in the InTable mode. This means we want to do", "# special magic element rearranging", "parent", ",", "insertBefore", "=", "self", ".", "getTableMisnestedNodePosition", "(", ")", "if", "insertBefore", "is", "None", ":", "parent", ".", "appendChild", "(", "element", ")", "else", ":", "parent", ".", "insertBefore", "(", "element", ",", "insertBefore", ")", "self", ".", "openElements", ".", "append", "(", "element", ")", "return", "element" ]
[ 332, 4 ]
[ 346, 22 ]
python
en
['en', 'en', 'en']
True
TreeBuilder.insertText
(self, data, parent=None)
Insert text data.
Insert text data.
def insertText(self, data, parent=None): """Insert text data.""" if parent is None: parent = self.openElements[-1] if (not self.insertFromTable or (self.insertFromTable and self.openElements[-1].name not in tableInsertModeElements)): parent.insertText(data) else: # We should be in the InTable mode. This means we want to do # special magic element rearranging parent, insertBefore = self.getTableMisnestedNodePosition() parent.insertText(data, insertBefore)
[ "def", "insertText", "(", "self", ",", "data", ",", "parent", "=", "None", ")", ":", "if", "parent", "is", "None", ":", "parent", "=", "self", ".", "openElements", "[", "-", "1", "]", "if", "(", "not", "self", ".", "insertFromTable", "or", "(", "self", ".", "insertFromTable", "and", "self", ".", "openElements", "[", "-", "1", "]", ".", "name", "not", "in", "tableInsertModeElements", ")", ")", ":", "parent", ".", "insertText", "(", "data", ")", "else", ":", "# We should be in the InTable mode. This means we want to do", "# special magic element rearranging", "parent", ",", "insertBefore", "=", "self", ".", "getTableMisnestedNodePosition", "(", ")", "parent", ".", "insertText", "(", "data", ",", "insertBefore", ")" ]
[ 348, 4 ]
[ 361, 49 ]
python
en
['fr', 'lb', 'en']
False
TreeBuilder.getTableMisnestedNodePosition
(self)
Get the foster parent element, and sibling to insert before (or None) when inserting a misnested table node
Get the foster parent element, and sibling to insert before (or None) when inserting a misnested table node
def getTableMisnestedNodePosition(self): """Get the foster parent element, and sibling to insert before (or None) when inserting a misnested table node""" # The foster parent element is the one which comes before the most # recently opened table element # XXX - this is really inelegant lastTable = None fosterParent = None insertBefore = None for elm in self.openElements[::-1]: if elm.name == "table": lastTable = elm break if lastTable: # XXX - we should really check that this parent is actually a # node here if lastTable.parent: fosterParent = lastTable.parent insertBefore = lastTable else: fosterParent = self.openElements[ self.openElements.index(lastTable) - 1] else: fosterParent = self.openElements[0] return fosterParent, insertBefore
[ "def", "getTableMisnestedNodePosition", "(", "self", ")", ":", "# The foster parent element is the one which comes before the most", "# recently opened table element", "# XXX - this is really inelegant", "lastTable", "=", "None", "fosterParent", "=", "None", "insertBefore", "=", "None", "for", "elm", "in", "self", ".", "openElements", "[", ":", ":", "-", "1", "]", ":", "if", "elm", ".", "name", "==", "\"table\"", ":", "lastTable", "=", "elm", "break", "if", "lastTable", ":", "# XXX - we should really check that this parent is actually a", "# node here", "if", "lastTable", ".", "parent", ":", "fosterParent", "=", "lastTable", ".", "parent", "insertBefore", "=", "lastTable", "else", ":", "fosterParent", "=", "self", ".", "openElements", "[", "self", ".", "openElements", ".", "index", "(", "lastTable", ")", "-", "1", "]", "else", ":", "fosterParent", "=", "self", ".", "openElements", "[", "0", "]", "return", "fosterParent", ",", "insertBefore" ]
[ 363, 4 ]
[ 387, 41 ]
python
en
['en', 'en', 'en']
True
TreeBuilder.getDocument
(self)
Return the final tree
Return the final tree
def getDocument(self): """Return the final tree""" return self.document
[ "def", "getDocument", "(", "self", ")", ":", "return", "self", ".", "document" ]
[ 399, 4 ]
[ 401, 28 ]
python
en
['en', 'mt', 'en']
True
TreeBuilder.getFragment
(self)
Return the final fragment
Return the final fragment
def getFragment(self): """Return the final fragment""" # assert self.innerHTML fragment = self.fragmentClass() self.openElements[0].reparentChildren(fragment) return fragment
[ "def", "getFragment", "(", "self", ")", ":", "# assert self.innerHTML", "fragment", "=", "self", ".", "fragmentClass", "(", ")", "self", ".", "openElements", "[", "0", "]", ".", "reparentChildren", "(", "fragment", ")", "return", "fragment" ]
[ 403, 4 ]
[ 408, 23 ]
python
en
['en', 'no', 'en']
True
TreeBuilder.testSerializer
(self, node)
Serialize the subtree of node in the format required by unit tests :arg node: the node from which to start serializing
Serialize the subtree of node in the format required by unit tests
def testSerializer(self, node): """Serialize the subtree of node in the format required by unit tests :arg node: the node from which to start serializing """ raise NotImplementedError
[ "def", "testSerializer", "(", "self", ",", "node", ")", ":", "raise", "NotImplementedError" ]
[ 410, 4 ]
[ 416, 33 ]
python
en
['en', 'en', 'en']
True
command_date
(bot, user, channel, args)
Shows date information. Usage: date [now|epoch]
Shows date information. Usage: date [now|epoch]
def command_date(bot, user, channel, args): "Shows date information. Usage: date [now|epoch]" days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] d = datetime.datetime.now(tzlocal()) tomorrow = days[d.weekday() + 1] n = d.strftime("%Z/UTC%z: %H:%M:%S, %Y-%m-%d (%A, %j/%U)") if args == "now": bot.say(channel, n) elif args == "epoch": bot.say(channel, "{}".format(d.strftime("%ss since 01.01.1970"))) else: bot.say(channel, "Tomorrow is {}.".format(tomorrow))
[ "def", "command_date", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "days", "=", "[", "\"Monday\"", ",", "\"Tuesday\"", ",", "\"Wednesday\"", ",", "\"Thursday\"", ",", "\"Friday\"", ",", "\"Saturday\"", ",", "\"Sunday\"", "]", "d", "=", "datetime", ".", "datetime", ".", "now", "(", "tzlocal", "(", ")", ")", "tomorrow", "=", "days", "[", "d", ".", "weekday", "(", ")", "+", "1", "]", "n", "=", "d", ".", "strftime", "(", "\"%Z/UTC%z: %H:%M:%S, %Y-%m-%d (%A, %j/%U)\"", ")", "if", "args", "==", "\"now\"", ":", "bot", ".", "say", "(", "channel", ",", "n", ")", "elif", "args", "==", "\"epoch\"", ":", "bot", ".", "say", "(", "channel", ",", "\"{}\"", ".", "format", "(", "d", ".", "strftime", "(", "\"%ss since 01.01.1970\"", ")", ")", ")", "else", ":", "bot", ".", "say", "(", "channel", ",", "\"Tomorrow is {}.\"", ".", "format", "(", "tomorrow", ")", ")" ]
[ 13, 0 ]
[ 27, 60 ]
python
en
['fr', 'en', 'en']
True
infix
(bp, func)
Create an infix operator, given a binding power and a function that evaluates the node.
Create an infix operator, given a binding power and a function that evaluates the node.
def infix(bp, func): """ Create an infix operator, given a binding power and a function that evaluates the node. """ class Operator(TokenBase): lbp = bp def led(self, left, parser): self.first = left self.second = parser.expression(bp) return self def eval(self, context): try: return func(context, self.first, self.second) except Exception: # Templates shouldn't throw exceptions when rendering. We are # most likely to get exceptions for things like {% if foo in bar # %} where 'bar' does not support 'in', so default to False return False return Operator
[ "def", "infix", "(", "bp", ",", "func", ")", ":", "class", "Operator", "(", "TokenBase", ")", ":", "lbp", "=", "bp", "def", "led", "(", "self", ",", "left", ",", "parser", ")", ":", "self", ".", "first", "=", "left", "self", ".", "second", "=", "parser", ".", "expression", "(", "bp", ")", "return", "self", "def", "eval", "(", "self", ",", "context", ")", ":", "try", ":", "return", "func", "(", "context", ",", "self", ".", "first", ",", "self", ".", "second", ")", "except", "Exception", ":", "# Templates shouldn't throw exceptions when rendering. We are", "# most likely to get exceptions for things like {% if foo in bar", "# %} where 'bar' does not support 'in', so default to False", "return", "False", "return", "Operator" ]
[ 42, 0 ]
[ 64, 19 ]
python
en
['en', 'error', 'th']
False
prefix
(bp, func)
Create a prefix operator, given a binding power and a function that evaluates the node.
Create a prefix operator, given a binding power and a function that evaluates the node.
def prefix(bp, func): """ Create a prefix operator, given a binding power and a function that evaluates the node. """ class Operator(TokenBase): lbp = bp def nud(self, parser): self.first = parser.expression(bp) self.second = None return self def eval(self, context): try: return func(context, self.first) except Exception: return False return Operator
[ "def", "prefix", "(", "bp", ",", "func", ")", ":", "class", "Operator", "(", "TokenBase", ")", ":", "lbp", "=", "bp", "def", "nud", "(", "self", ",", "parser", ")", ":", "self", ".", "first", "=", "parser", ".", "expression", "(", "bp", ")", "self", ".", "second", "=", "None", "return", "self", "def", "eval", "(", "self", ",", "context", ")", ":", "try", ":", "return", "func", "(", "context", ",", "self", ".", "first", ")", "except", "Exception", ":", "return", "False", "return", "Operator" ]
[ 67, 0 ]
[ 86, 19 ]
python
en
['en', 'error', 'th']
False
TokenBase.display
(self)
Return what to display in error messages for this node
Return what to display in error messages for this node
def display(self): """ Return what to display in error messages for this node """ return self.id
[ "def", "display", "(", "self", ")", ":", "return", "self", ".", "id" ]
[ 31, 4 ]
[ 35, 22 ]
python
en
['en', 'error', 'th']
False
COP_fn_mdot
(L, transmissivity, mdot,dT)
Calculates COP as a function of mass flow rate. L is the well spacing [m] transmissivity is the transmissivity [m^3] mdot is the mass flow rate [kg/s] dT is the difference in temperature between T_CV and T_DH, which depends on depth
Calculates COP as a function of mass flow rate.
def COP_fn_mdot(L, transmissivity, mdot,dT): """ Calculates COP as a function of mass flow rate. L is the well spacing [m] transmissivity is the transmissivity [m^3] mdot is the mass flow rate [kg/s] dT is the difference in temperature between T_CV and T_DH, which depends on depth """ import global_vars as GV import numpy as np # import pudb; pudb.set_trace() COP = (GV.rho_w**2*GV.Cpw*dT*np.pi*transmissivity) / \ (mdot*GV.viscosity*np.log(L/GV.D)) return COP
[ "def", "COP_fn_mdot", "(", "L", ",", "transmissivity", ",", "mdot", ",", "dT", ")", ":", "import", "global_vars", "as", "GV", "import", "numpy", "as", "np", "# import pudb; pudb.set_trace()", "COP", "=", "(", "GV", ".", "rho_w", "**", "2", "*", "GV", ".", "Cpw", "*", "dT", "*", "np", ".", "pi", "*", "transmissivity", ")", "/", "(", "mdot", "*", "GV", ".", "viscosity", "*", "np", ".", "log", "(", "L", "/", "GV", ".", "D", ")", ")", "return", "COP" ]
[ 4, 0 ]
[ 20, 14 ]
python
en
['en', 'error', 'th']
False
m_max_ResVol
(L, b)
Defines the maximum mass flow rate [kg/s] based on the amount of heat the reservoir volume can hold. The reservoir volume is approximated as L^2*b. This is Constraint I in Birdsell paper. L is the well spacing [m]. b is the aquifer thickness [m].
Defines the maximum mass flow rate [kg/s] based on the amount of heat the reservoir volume can hold. The reservoir volume is approximated as L^2*b. This is Constraint I in Birdsell paper.
def m_max_ResVol(L, b): """ Defines the maximum mass flow rate [kg/s] based on the amount of heat the reservoir volume can hold. The reservoir volume is approximated as L^2*b. This is Constraint I in Birdsell paper. L is the well spacing [m]. b is the aquifer thickness [m]. """ import global_vars as GV mdot = (GV.rho_w*GV.Cpw*GV.porosity + GV.rho_r*GV.Cpr*(1.0-GV.porosity)) * \ (GV.alphaI**2 * L**2 * b) / (GV.Cpw*GV.t_inj); return mdot
[ "def", "m_max_ResVol", "(", "L", ",", "b", ")", ":", "import", "global_vars", "as", "GV", "mdot", "=", "(", "GV", ".", "rho_w", "*", "GV", ".", "Cpw", "*", "GV", ".", "porosity", "+", "GV", ".", "rho_r", "*", "GV", ".", "Cpr", "*", "(", "1.0", "-", "GV", ".", "porosity", ")", ")", "*", "(", "GV", ".", "alphaI", "**", "2", "*", "L", "**", "2", "*", "b", ")", "/", "(", "GV", ".", "Cpw", "*", "GV", ".", "t_inj", ")", "return", "mdot" ]
[ 22, 0 ]
[ 35, 15 ]
python
en
['en', 'error', 'th']
False
COP_HF
(L, dT, reservoir_depth = None)
Defines the maximum mass flow rate [kg/s] to avoid hydraulic fracuting. This is Constraint II in Birdsell paper. L is the distance between the wells [m]. reservoir_depth is the depth of the reservoir [m]. Note - if it is changing within the script, it should be provided a value. Otherwise it will default to the value in the global_vars.py dT is the difference in temperature between T_CV and T_DH, which depends on depth
Defines the maximum mass flow rate [kg/s] to avoid hydraulic fracuting. This is Constraint II in Birdsell paper.
def COP_HF(L, dT, reservoir_depth = None): """ Defines the maximum mass flow rate [kg/s] to avoid hydraulic fracuting. This is Constraint II in Birdsell paper. L is the distance between the wells [m]. reservoir_depth is the depth of the reservoir [m]. Note - if it is changing within the script, it should be provided a value. Otherwise it will default to the value in the global_vars.py dT is the difference in temperature between T_CV and T_DH, which depends on depth """ import global_vars as GV if reservoir_depth is None: print('Warning - you are using the default reservoir_depth') reservoir_depth = GV.reservoir_depth; # import pudb; pudb.set_trace() COP_II = (GV.rho_w*GV.Cpw*dT)/2.0/(GV.alphaII*GV.rho_r - GV.rho_w)/ \ GV.gravity/reservoir_depth return COP_II
[ "def", "COP_HF", "(", "L", ",", "dT", ",", "reservoir_depth", "=", "None", ")", ":", "import", "global_vars", "as", "GV", "if", "reservoir_depth", "is", "None", ":", "print", "(", "'Warning - you are using the default reservoir_depth'", ")", "reservoir_depth", "=", "GV", ".", "reservoir_depth", "# import pudb; pudb.set_trace()", "COP_II", "=", "(", "GV", ".", "rho_w", "*", "GV", ".", "Cpw", "*", "dT", ")", "/", "2.0", "/", "(", "GV", ".", "alphaII", "*", "GV", ".", "rho_r", "-", "GV", ".", "rho_w", ")", "/", "GV", ".", "gravity", "/", "reservoir_depth", "return", "COP_II" ]
[ 37, 0 ]
[ 57, 17 ]
python
en
['en', 'error', 'th']
False
mdot_minLCOH
(well_cost, transmissivity, Lstar)
Calculates the flow rate that gives the minimum LCOH, from d(LCOH)/d(mdot) well_cost is the construction cost of one well [$]. The capital cost are 4 times the cost of a single well because there are two wells and the capital cost is assumed to double. transmissivity is the reservoir transmissivity [m3] Lstar is the optimal well spacing
Calculates the flow rate that gives the minimum LCOH, from d(LCOH)/d(mdot)
def mdot_minLCOH(well_cost, transmissivity, Lstar): """ Calculates the flow rate that gives the minimum LCOH, from d(LCOH)/d(mdot) well_cost is the construction cost of one well [$]. The capital cost are 4 times the cost of a single well because there are two wells and the capital cost is assumed to double. transmissivity is the reservoir transmissivity [m3] Lstar is the optimal well spacing """ import global_vars as GV import numpy as np capital_cost = 4.0*well_cost cap_cost = capital_cost CRF = (GV.r*(1.0+GV.r)**GV.lifetime) / ((1.0+GV.r)**GV.lifetime-1.0) mdot_max_val = np.sqrt(capital_cost*CRF*GV.rho_w**2 *np.pi*transmissivity/ \ (2.0*GV.joule_to_kWh * GV.dollars_per_kWhth* \ GV.t_inj*GV.viscosity*np.log(Lstar/GV.D))) return mdot_max_val
[ "def", "mdot_minLCOH", "(", "well_cost", ",", "transmissivity", ",", "Lstar", ")", ":", "import", "global_vars", "as", "GV", "import", "numpy", "as", "np", "capital_cost", "=", "4.0", "*", "well_cost", "cap_cost", "=", "capital_cost", "CRF", "=", "(", "GV", ".", "r", "*", "(", "1.0", "+", "GV", ".", "r", ")", "**", "GV", ".", "lifetime", ")", "/", "(", "(", "1.0", "+", "GV", ".", "r", ")", "**", "GV", ".", "lifetime", "-", "1.0", ")", "mdot_max_val", "=", "np", ".", "sqrt", "(", "capital_cost", "*", "CRF", "*", "GV", ".", "rho_w", "**", "2", "*", "np", ".", "pi", "*", "transmissivity", "/", "(", "2.0", "*", "GV", ".", "joule_to_kWh", "*", "GV", ".", "dollars_per_kWhth", "*", "GV", ".", "t_inj", "*", "GV", ".", "viscosity", "*", "np", ".", "log", "(", "Lstar", "/", "GV", ".", "D", ")", ")", ")", "return", "mdot_max_val" ]
[ 59, 0 ]
[ 78, 23 ]
python
en
['en', 'error', 'th']
False
m_max_COP
(L, b, k, dT)
Defines the maximum mass flow rate (kg/s) based on the COP>1 constraint. This is not L is the distance between the wells. b is the aquifer thickness k is the permeability dT is the difference in temperature between T_CV and T_DH, which depends on depth
Defines the maximum mass flow rate (kg/s) based on the COP>1 constraint. This is not
def m_max_COP(L, b, k, dT): """ Defines the maximum mass flow rate (kg/s) based on the COP>1 constraint. This is not L is the distance between the wells. b is the aquifer thickness k is the permeability dT is the difference in temperature between T_CV and T_DH, which depends on depth """ import global_vars as GV import numpy as np # import pudb; pudb.set_trace() mdot = (GV.rho_w*GV.Cpw*dT)*(GV.rho_w*k*b*np.pi)/(2.0*GV.viscosity * \ np.log(L/GV.D)) return mdot
[ "def", "m_max_COP", "(", "L", ",", "b", ",", "k", ",", "dT", ")", ":", "import", "global_vars", "as", "GV", "import", "numpy", "as", "np", "# import pudb; pudb.set_trace()", "mdot", "=", "(", "GV", ".", "rho_w", "*", "GV", ".", "Cpw", "*", "dT", ")", "*", "(", "GV", ".", "rho_w", "*", "k", "*", "b", "*", "np", ".", "pi", ")", "/", "(", "2.0", "*", "GV", ".", "viscosity", "*", "np", ".", "log", "(", "L", "/", "GV", ".", "D", ")", ")", "return", "mdot" ]
[ 80, 0 ]
[ 97, 15 ]
python
en
['en', 'error', 'th']
False
m_max_HF
(L , b , k, reservoir_depth = None)
defines the maximum mass flow rate (kg/s) to avoid hydraulic fracuting. this assumes that pore pressure should be less than 80% of lithostatic stress. L is half the distance between the wells. b is the aquifer thickness k is the permeability
defines the maximum mass flow rate (kg/s) to avoid hydraulic fracuting. this assumes that pore pressure should be less than 80% of lithostatic stress.
def m_max_HF(L , b , k, reservoir_depth = None): """ defines the maximum mass flow rate (kg/s) to avoid hydraulic fracuting. this assumes that pore pressure should be less than 80% of lithostatic stress. L is half the distance between the wells. b is the aquifer thickness k is the permeability """ import global_vars as GV import numpy as np if reservoir_depth is None: reservoir_depth = GV.reservoir_depth print('Warning: m_max_HF used GV definition of reservoir_volume') max_dP_allowed = ((GV.alphaII*GV.rho_r) - GV.rho_w) * GV.gravity*reservoir_depth; #Pa mdot =(((GV.alphaII*GV.rho_r) - GV.rho_w) * GV.gravity*reservoir_depth) * \ (2.0*np.pi*GV.rho_w*k*b) / (GV.viscosity*np.log(L/GV.D)) return mdot
[ "def", "m_max_HF", "(", "L", ",", "b", ",", "k", ",", "reservoir_depth", "=", "None", ")", ":", "import", "global_vars", "as", "GV", "import", "numpy", "as", "np", "if", "reservoir_depth", "is", "None", ":", "reservoir_depth", "=", "GV", ".", "reservoir_depth", "print", "(", "'Warning: m_max_HF used GV definition of reservoir_volume'", ")", "max_dP_allowed", "=", "(", "(", "GV", ".", "alphaII", "*", "GV", ".", "rho_r", ")", "-", "GV", ".", "rho_w", ")", "*", "GV", ".", "gravity", "*", "reservoir_depth", "#Pa", "mdot", "=", "(", "(", "(", "GV", ".", "alphaII", "*", "GV", ".", "rho_r", ")", "-", "GV", ".", "rho_w", ")", "*", "GV", ".", "gravity", "*", "reservoir_depth", ")", "*", "(", "2.0", "*", "np", ".", "pi", "*", "GV", ".", "rho_w", "*", "k", "*", "b", ")", "/", "(", "GV", ".", "viscosity", "*", "np", ".", "log", "(", "L", "/", "GV", ".", "D", ")", ")", "return", "mdot" ]
[ 99, 0 ]
[ 119, 15 ]
python
en
['en', 'error', 'th']
False
thermal_radius
(mdot , b, t_inj = None )
Calculates the thermal radius mdot is the flow rate [kg/s] t_inj is the duration of the injection [s] b is the reservoir thickness
Calculates the thermal radius
def thermal_radius(mdot , b, t_inj = None ): """ Calculates the thermal radius mdot is the flow rate [kg/s] t_inj is the duration of the injection [s] b is the reservoir thickness """ import global_vars as GV import numpy as np if t_inj is None: t_inj = GV.t_inj print("Warning t_inj in RF.thermal_radius takes default") R_th = np.sqrt(GV.Cpw*mdot*t_inj/((GV.Cpw*GV.porosity*GV.rho_w + \ GV.Cpr*(1.0-GV.porosity)*GV.rho_r)*np.pi*b)) return R_th
[ "def", "thermal_radius", "(", "mdot", ",", "b", ",", "t_inj", "=", "None", ")", ":", "import", "global_vars", "as", "GV", "import", "numpy", "as", "np", "if", "t_inj", "is", "None", ":", "t_inj", "=", "GV", ".", "t_inj", "print", "(", "\"Warning t_inj in RF.thermal_radius takes default\"", ")", "R_th", "=", "np", ".", "sqrt", "(", "GV", ".", "Cpw", "*", "mdot", "*", "t_inj", "/", "(", "(", "GV", ".", "Cpw", "*", "GV", ".", "porosity", "*", "GV", ".", "rho_w", "+", "GV", ".", "Cpr", "*", "(", "1.0", "-", "GV", ".", "porosity", ")", "*", "GV", ".", "rho_r", ")", "*", "np", ".", "pi", "*", "b", ")", ")", "return", "R_th" ]
[ 121, 0 ]
[ 137, 15 ]
python
en
['en', 'error', 'th']
False
dP_inj_fn
(mdot, transmissivity , L )
Calculates the change in pressure for a single well from Darcy's equation. See Schaetlze (1980). mdot is flow rate [kg/s] transmissivity is reservoir transmissivity [m3] L is the well spacing [m]
Calculates the change in pressure for a single well from Darcy's equation. See Schaetlze (1980).
def dP_inj_fn(mdot, transmissivity , L ): """ Calculates the change in pressure for a single well from Darcy's equation. See Schaetlze (1980). mdot is flow rate [kg/s] transmissivity is reservoir transmissivity [m3] L is the well spacing [m] """ import global_vars as GV import numpy as np dP_inj = mdot*GV.viscosity*np.log(L/GV.D)/(2.0*np.pi*GV.rho_w*transmissivity) return dP_inj
[ "def", "dP_inj_fn", "(", "mdot", ",", "transmissivity", ",", "L", ")", ":", "import", "global_vars", "as", "GV", "import", "numpy", "as", "np", "dP_inj", "=", "mdot", "*", "GV", ".", "viscosity", "*", "np", ".", "log", "(", "L", "/", "GV", ".", "D", ")", "/", "(", "2.0", "*", "np", ".", "pi", "*", "GV", ".", "rho_w", "*", "transmissivity", ")", "return", "dP_inj" ]
[ 139, 0 ]
[ 152, 17 ]
python
en
['en', 'error', 'th']
False
heat_loss_fn
(depth, Rth, b, T_WH = None, T_DH = None, T_surf = None, geothermal_gradient = None,Lstar = None)
depth = reservoir depth [m] Rth = thermal radius [m] b = reservoir thickness [m] T_WH is the waste heat temperature T_DH is the district heating rejection temperature T_surf is the average surface temperature geothermal_gradient [C/m] is the geothermal gradient Lstar is well spacing (only used if heat loss area is based on well spacing).
depth = reservoir depth [m] Rth = thermal radius [m] b = reservoir thickness [m] T_WH is the waste heat temperature T_DH is the district heating rejection temperature T_surf is the average surface temperature geothermal_gradient [C/m] is the geothermal gradient Lstar is well spacing (only used if heat loss area is based on well spacing).
def heat_loss_fn(depth, Rth, b, T_WH = None, T_DH = None, T_surf = None, geothermal_gradient = None,Lstar = None): """ depth = reservoir depth [m] Rth = thermal radius [m] b = reservoir thickness [m] T_WH is the waste heat temperature T_DH is the district heating rejection temperature T_surf is the average surface temperature geothermal_gradient [C/m] is the geothermal gradient Lstar is well spacing (only used if heat loss area is based on well spacing). """ import global_vars as GV import numpy as np if T_WH is None: T_WH = GV.T_WH if T_DH is None: T_DH = GV.T_DH if T_surf is None: T_surf = GV.T_surf if geothermal_gradient is None: geothermal_gradient = GV.geothermal_gradient t_rest = GV.t_inj #assumes that the resting period is 1/4 year. T_G = T_surf + geothermal_gradient*depth thermal_radius = True if thermal_radius: interfacial_area = 2.0*np.pi*Rth**2 reservoir_volume = np.pi*Rth**2*b else: ## based on reservoir volume, probably wont use interfacial_area = 2.0*(alphaI*Lstar)**2 reservoir_volume = Lstar**2*b C1 = (GV.rho_w*GV.Cpw*GV.porosity + GV.rho_r*GV.Cpr*(1.0-GV.porosity))*reservoir_volume #J/C C2 = GV.lambda_eff*interfacial_area/GV.DeltaL Tcv = (T_WH-T_G)*np.exp(-C2/C1*t_rest)+T_G #temperature after rest heat_loss = (T_WH - Tcv)*C1 #joules final_recovery = (Tcv - T_DH)*C1 #joules efficiency = (Tcv-T_DH)/(T_WH-T_DH) # Eout/Ein. Eout = mCpf*(Tcv-TDH). Ein = m*Cpf*(Twh-Tdh) return [Tcv, T_G, heat_loss, final_recovery, efficiency]
[ "def", "heat_loss_fn", "(", "depth", ",", "Rth", ",", "b", ",", "T_WH", "=", "None", ",", "T_DH", "=", "None", ",", "T_surf", "=", "None", ",", "geothermal_gradient", "=", "None", ",", "Lstar", "=", "None", ")", ":", "import", "global_vars", "as", "GV", "import", "numpy", "as", "np", "if", "T_WH", "is", "None", ":", "T_WH", "=", "GV", ".", "T_WH", "if", "T_DH", "is", "None", ":", "T_DH", "=", "GV", ".", "T_DH", "if", "T_surf", "is", "None", ":", "T_surf", "=", "GV", ".", "T_surf", "if", "geothermal_gradient", "is", "None", ":", "geothermal_gradient", "=", "GV", ".", "geothermal_gradient", "t_rest", "=", "GV", ".", "t_inj", "#assumes that the resting period is 1/4 year.", "T_G", "=", "T_surf", "+", "geothermal_gradient", "*", "depth", "thermal_radius", "=", "True", "if", "thermal_radius", ":", "interfacial_area", "=", "2.0", "*", "np", ".", "pi", "*", "Rth", "**", "2", "reservoir_volume", "=", "np", ".", "pi", "*", "Rth", "**", "2", "*", "b", "else", ":", "## based on reservoir volume, probably wont use", "interfacial_area", "=", "2.0", "*", "(", "alphaI", "*", "Lstar", ")", "**", "2", "reservoir_volume", "=", "Lstar", "**", "2", "*", "b", "C1", "=", "(", "GV", ".", "rho_w", "*", "GV", ".", "Cpw", "*", "GV", ".", "porosity", "+", "GV", ".", "rho_r", "*", "GV", ".", "Cpr", "*", "(", "1.0", "-", "GV", ".", "porosity", ")", ")", "*", "reservoir_volume", "#J/C", "C2", "=", "GV", ".", "lambda_eff", "*", "interfacial_area", "/", "GV", ".", "DeltaL", "Tcv", "=", "(", "T_WH", "-", "T_G", ")", "*", "np", ".", "exp", "(", "-", "C2", "/", "C1", "*", "t_rest", ")", "+", "T_G", "#temperature after rest", "heat_loss", "=", "(", "T_WH", "-", "Tcv", ")", "*", "C1", "#joules", "final_recovery", "=", "(", "Tcv", "-", "T_DH", ")", "*", "C1", "#joules", "efficiency", "=", "(", "Tcv", "-", "T_DH", ")", "/", "(", "T_WH", "-", "T_DH", ")", "# Eout/Ein. Eout = mCpf*(Tcv-TDH). Ein = m*Cpf*(Twh-Tdh)", "return", "[", "Tcv", ",", "T_G", ",", "heat_loss", ",", "final_recovery", ",", "efficiency", "]" ]
[ 155, 0 ]
[ 194, 60 ]
python
en
['en', 'error', 'th']
False
Deserializer
(stream_or_string, **options)
Deserialize a stream or string of YAML data.
Deserialize a stream or string of YAML data.
def Deserializer(stream_or_string, **options): """Deserialize a stream or string of YAML data.""" if isinstance(stream_or_string, bytes): stream_or_string = stream_or_string.decode() if isinstance(stream_or_string, str): stream = StringIO(stream_or_string) else: stream = stream_or_string try: yield from PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options) except (GeneratorExit, DeserializationError): raise except Exception as exc: raise DeserializationError() from exc
[ "def", "Deserializer", "(", "stream_or_string", ",", "*", "*", "options", ")", ":", "if", "isinstance", "(", "stream_or_string", ",", "bytes", ")", ":", "stream_or_string", "=", "stream_or_string", ".", "decode", "(", ")", "if", "isinstance", "(", "stream_or_string", ",", "str", ")", ":", "stream", "=", "StringIO", "(", "stream_or_string", ")", "else", ":", "stream", "=", "stream_or_string", "try", ":", "yield", "from", "PythonDeserializer", "(", "yaml", ".", "load", "(", "stream", ",", "Loader", "=", "SafeLoader", ")", ",", "*", "*", "options", ")", "except", "(", "GeneratorExit", ",", "DeserializationError", ")", ":", "raise", "except", "Exception", "as", "exc", ":", "raise", "DeserializationError", "(", ")", "from", "exc" ]
[ 66, 0 ]
[ 79, 45 ]
python
en
['en', 'en', 'en']
True
SeleniumTestCaseBase.__new__
(cls, name, bases, attrs)
Dynamically create new classes and add them to the test module when multiple browsers specs are provided (e.g. --selenium=firefox,chrome).
Dynamically create new classes and add them to the test module when multiple browsers specs are provided (e.g. --selenium=firefox,chrome).
def __new__(cls, name, bases, attrs): """ Dynamically create new classes and add them to the test module when multiple browsers specs are provided (e.g. --selenium=firefox,chrome). """ test_class = super().__new__(cls, name, bases, attrs) # If the test class is either browser-specific or a test base, return it. if test_class.browser or not any(name.startswith('test') and callable(value) for name, value in attrs.items()): return test_class elif test_class.browsers: # Reuse the created test class to make it browser-specific. # We can't rename it to include the browser name or create a # subclass like we do with the remaining browsers as it would # either duplicate tests or prevent pickling of its instances. first_browser = test_class.browsers[0] test_class.browser = first_browser # Listen on an external interface if using a selenium hub. host = test_class.host if not test_class.selenium_hub else '0.0.0.0' test_class.host = host test_class.external_host = cls.external_host # Create subclasses for each of the remaining browsers and expose # them through the test's module namespace. module = sys.modules[test_class.__module__] for browser in test_class.browsers[1:]: browser_test_class = cls.__new__( cls, "%s%s" % (capfirst(browser), name), (test_class,), { 'browser': browser, 'host': host, 'external_host': cls.external_host, '__module__': test_class.__module__, } ) setattr(module, browser_test_class.__name__, browser_test_class) return test_class # If no browsers were specified, skip this class (it'll still be discovered). return unittest.skip('No browsers specified.')(test_class)
[ "def", "__new__", "(", "cls", ",", "name", ",", "bases", ",", "attrs", ")", ":", "test_class", "=", "super", "(", ")", ".", "__new__", "(", "cls", ",", "name", ",", "bases", ",", "attrs", ")", "# If the test class is either browser-specific or a test base, return it.", "if", "test_class", ".", "browser", "or", "not", "any", "(", "name", ".", "startswith", "(", "'test'", ")", "and", "callable", "(", "value", ")", "for", "name", ",", "value", "in", "attrs", ".", "items", "(", ")", ")", ":", "return", "test_class", "elif", "test_class", ".", "browsers", ":", "# Reuse the created test class to make it browser-specific.", "# We can't rename it to include the browser name or create a", "# subclass like we do with the remaining browsers as it would", "# either duplicate tests or prevent pickling of its instances.", "first_browser", "=", "test_class", ".", "browsers", "[", "0", "]", "test_class", ".", "browser", "=", "first_browser", "# Listen on an external interface if using a selenium hub.", "host", "=", "test_class", ".", "host", "if", "not", "test_class", ".", "selenium_hub", "else", "'0.0.0.0'", "test_class", ".", "host", "=", "host", "test_class", ".", "external_host", "=", "cls", ".", "external_host", "# Create subclasses for each of the remaining browsers and expose", "# them through the test's module namespace.", "module", "=", "sys", ".", "modules", "[", "test_class", ".", "__module__", "]", "for", "browser", "in", "test_class", ".", "browsers", "[", "1", ":", "]", ":", "browser_test_class", "=", "cls", ".", "__new__", "(", "cls", ",", "\"%s%s\"", "%", "(", "capfirst", "(", "browser", ")", ",", "name", ")", ",", "(", "test_class", ",", ")", ",", "{", "'browser'", ":", "browser", ",", "'host'", ":", "host", ",", "'external_host'", ":", "cls", ".", "external_host", ",", "'__module__'", ":", "test_class", ".", "__module__", ",", "}", ")", "setattr", "(", "module", ",", "browser_test_class", ".", "__name__", ",", "browser_test_class", ")", "return", "test_class", "# If no browsers were specified, skip this class (it'll still be discovered).", "return", "unittest", ".", "skip", "(", "'No browsers specified.'", ")", "(", "test_class", ")" ]
[ 22, 4 ]
[ 60, 66 ]
python
en
['en', 'error', 'th']
False
UpdateCacheMiddleware.process_response
(self, request, response)
Set the cache, if needed.
Set the cache, if needed.
def process_response(self, request, response): """Set the cache, if needed.""" if not self._should_update_cache(request, response): # We don't need to update the cache, just return. return response if response.streaming or response.status_code not in (200, 304): return response # Don't cache responses that set a user-specific (and maybe security # sensitive) cookie in response to a cookie-less request. if not request.COOKIES and response.cookies and has_vary_header(response, 'Cookie'): return response # Don't cache a response with 'Cache-Control: private' if 'private' in response.get('Cache-Control', ()): return response # Page timeout takes precedence over the "max-age" and the default # cache timeout. timeout = self.page_timeout if timeout is None: # The timeout from the "max-age" section of the "Cache-Control" # header takes precedence over the default cache timeout. timeout = get_max_age(response) if timeout is None: timeout = self.cache_timeout elif timeout == 0: # max-age was set to 0, don't cache. return response patch_response_headers(response, timeout) if timeout and response.status_code == 200: cache_key = learn_cache_key(request, response, timeout, self.key_prefix, cache=self.cache) if hasattr(response, 'render') and callable(response.render): response.add_post_render_callback( lambda r: self.cache.set(cache_key, r, timeout) ) else: self.cache.set(cache_key, response, timeout) return response
[ "def", "process_response", "(", "self", ",", "request", ",", "response", ")", ":", "if", "not", "self", ".", "_should_update_cache", "(", "request", ",", "response", ")", ":", "# We don't need to update the cache, just return.", "return", "response", "if", "response", ".", "streaming", "or", "response", ".", "status_code", "not", "in", "(", "200", ",", "304", ")", ":", "return", "response", "# Don't cache responses that set a user-specific (and maybe security", "# sensitive) cookie in response to a cookie-less request.", "if", "not", "request", ".", "COOKIES", "and", "response", ".", "cookies", "and", "has_vary_header", "(", "response", ",", "'Cookie'", ")", ":", "return", "response", "# Don't cache a response with 'Cache-Control: private'", "if", "'private'", "in", "response", ".", "get", "(", "'Cache-Control'", ",", "(", ")", ")", ":", "return", "response", "# Page timeout takes precedence over the \"max-age\" and the default", "# cache timeout.", "timeout", "=", "self", ".", "page_timeout", "if", "timeout", "is", "None", ":", "# The timeout from the \"max-age\" section of the \"Cache-Control\"", "# header takes precedence over the default cache timeout.", "timeout", "=", "get_max_age", "(", "response", ")", "if", "timeout", "is", "None", ":", "timeout", "=", "self", ".", "cache_timeout", "elif", "timeout", "==", "0", ":", "# max-age was set to 0, don't cache.", "return", "response", "patch_response_headers", "(", "response", ",", "timeout", ")", "if", "timeout", "and", "response", ".", "status_code", "==", "200", ":", "cache_key", "=", "learn_cache_key", "(", "request", ",", "response", ",", "timeout", ",", "self", ".", "key_prefix", ",", "cache", "=", "self", ".", "cache", ")", "if", "hasattr", "(", "response", ",", "'render'", ")", "and", "callable", "(", "response", ".", "render", ")", ":", "response", ".", "add_post_render_callback", "(", "lambda", "r", ":", "self", ".", "cache", ".", "set", "(", "cache_key", ",", "r", ",", "timeout", ")", ")", "else", ":", "self", ".", "cache", ".", "set", "(", "cache_key", ",", "response", ",", "timeout", ")", "return", "response" ]
[ 76, 4 ]
[ 115, 23 ]
python
en
['en', 'en', 'en']
True
FetchFromCacheMiddleware.process_request
(self, request)
Check whether the page is already cached and return the cached version if available.
Check whether the page is already cached and return the cached version if available.
def process_request(self, request): """ Check whether the page is already cached and return the cached version if available. """ if request.method not in ('GET', 'HEAD'): request._cache_update_cache = False return None # Don't bother checking the cache. # try and get the cached GET response cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = self.cache.get(cache_key) # if it wasn't found and we are looking for a HEAD, try looking just for that if response is None and request.method == 'HEAD': cache_key = get_cache_key(request, self.key_prefix, 'HEAD', cache=self.cache) response = self.cache.get(cache_key) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. # hit, return cached response request._cache_update_cache = False return response
[ "def", "process_request", "(", "self", ",", "request", ")", ":", "if", "request", ".", "method", "not", "in", "(", "'GET'", ",", "'HEAD'", ")", ":", "request", ".", "_cache_update_cache", "=", "False", "return", "None", "# Don't bother checking the cache.", "# try and get the cached GET response", "cache_key", "=", "get_cache_key", "(", "request", ",", "self", ".", "key_prefix", ",", "'GET'", ",", "cache", "=", "self", ".", "cache", ")", "if", "cache_key", "is", "None", ":", "request", ".", "_cache_update_cache", "=", "True", "return", "None", "# No cache information available, need to rebuild.", "response", "=", "self", ".", "cache", ".", "get", "(", "cache_key", ")", "# if it wasn't found and we are looking for a HEAD, try looking just for that", "if", "response", "is", "None", "and", "request", ".", "method", "==", "'HEAD'", ":", "cache_key", "=", "get_cache_key", "(", "request", ",", "self", ".", "key_prefix", ",", "'HEAD'", ",", "cache", "=", "self", ".", "cache", ")", "response", "=", "self", ".", "cache", ".", "get", "(", "cache_key", ")", "if", "response", "is", "None", ":", "request", ".", "_cache_update_cache", "=", "True", "return", "None", "# No cache information available, need to rebuild.", "# hit, return cached response", "request", ".", "_cache_update_cache", "=", "False", "return", "response" ]
[ 134, 4 ]
[ 160, 23 ]
python
en
['en', 'error', 'th']
False
HTTPResponse__getheaders
(self)
Return list of (header, value) tuples.
Return list of (header, value) tuples.
def HTTPResponse__getheaders(self): """Return list of (header, value) tuples.""" if self.msg is None: raise httplib.ResponseNotReady() return self.msg.items()
[ "def", "HTTPResponse__getheaders", "(", "self", ")", ":", "if", "self", ".", "msg", "is", "None", ":", "raise", "httplib", ".", "ResponseNotReady", "(", ")", "return", "self", ".", "msg", ".", "items", "(", ")" ]
[ 166, 0 ]
[ 170, 27 ]
python
en
['en', 'et', 'en']
True
parse_uri
(uri)
Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri)
Parses a URI using the regex given in Appendix B of RFC 3986.
def parse_uri(uri): """Parses a URI using the regex given in Appendix B of RFC 3986. (scheme, authority, path, query, fragment) = parse_uri(uri) """ groups = URI.match(uri).groups() return (groups[1], groups[3], groups[4], groups[6], groups[8])
[ "def", "parse_uri", "(", "uri", ")", ":", "groups", "=", "URI", ".", "match", "(", "uri", ")", ".", "groups", "(", ")", "return", "(", "groups", "[", "1", "]", ",", "groups", "[", "3", "]", ",", "groups", "[", "4", "]", ",", "groups", "[", "6", "]", ",", "groups", "[", "8", "]", ")" ]
[ 296, 0 ]
[ 302, 66 ]
python
en
['en', 'en', 'en']
True
safename
(filename)
Return a filename suitable for the cache. Strips dangerous and common characters to create a filename we can use to store the cache in.
Return a filename suitable for the cache. Strips dangerous and common characters to create a filename we can use to store the cache in.
def safename(filename): """Return a filename suitable for the cache. Strips dangerous and common characters to create a filename we can use to store the cache in. """ if isinstance(filename, str): filename_bytes = filename filename = filename.decode("utf-8") else: filename_bytes = filename.encode("utf-8") filemd5 = _md5(filename_bytes).hexdigest() filename = re_url_scheme.sub("", filename) filename = re_unsafe.sub("", filename) # limit length of filename (vital for Windows) # https://github.com/httplib2/httplib2/pull/74 # C:\Users\ <username> \AppData\Local\Temp\ <safe_filename> , <md5> # 9 chars + max 104 chars + 20 chars + x + 1 + 32 = max 259 chars # Thus max safe filename x = 93 chars. Let it be 90 to make a round sum: filename = filename[:90] return ",".join((filename, filemd5))
[ "def", "safename", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "str", ")", ":", "filename_bytes", "=", "filename", "filename", "=", "filename", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "filename_bytes", "=", "filename", ".", "encode", "(", "\"utf-8\"", ")", "filemd5", "=", "_md5", "(", "filename_bytes", ")", ".", "hexdigest", "(", ")", "filename", "=", "re_url_scheme", ".", "sub", "(", "\"\"", ",", "filename", ")", "filename", "=", "re_unsafe", ".", "sub", "(", "\"\"", ",", "filename", ")", "# limit length of filename (vital for Windows)", "# https://github.com/httplib2/httplib2/pull/74", "# C:\\Users\\ <username> \\AppData\\Local\\Temp\\ <safe_filename> , <md5>", "# 9 chars + max 104 chars + 20 chars + x + 1 + 32 = max 259 chars", "# Thus max safe filename x = 93 chars. Let it be 90 to make a round sum:", "filename", "=", "filename", "[", ":", "90", "]", "return", "\",\"", ".", "join", "(", "(", "filename", ",", "filemd5", ")", ")" ]
[ 326, 0 ]
[ 347, 40 ]
python
en
['en', 'en', 'en']
True
_parse_www_authenticate
(headers, headername="www-authenticate")
Returns a dictionary of dictionaries, one dict per auth_scheme.
Returns a dictionary of dictionaries, one dict per auth_scheme.
def _parse_www_authenticate(headers, headername="www-authenticate"): """Returns a dictionary of dictionaries, one dict per auth_scheme.""" retval = {} if headername in headers: try: authenticate = headers[headername].strip() www_auth = ( USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED ) while authenticate: # Break off the scheme at the beginning of the line if headername == "authentication-info": (auth_scheme, the_rest) = ("digest", authenticate) else: (auth_scheme, the_rest) = authenticate.split(" ", 1) # Now loop over all the key value pairs that come after the scheme, # being careful not to roll into the next scheme match = www_auth.search(the_rest) auth_params = {} while match: if match and len(match.groups()) == 3: (key, value, the_rest) = match.groups() auth_params[key.lower()] = UNQUOTE_PAIRS.sub( r"\1", value ) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')]) match = www_auth.search(the_rest) retval[auth_scheme.lower()] = auth_params authenticate = the_rest.strip() except ValueError: raise MalformedHeader("WWW-Authenticate") return retval
[ "def", "_parse_www_authenticate", "(", "headers", ",", "headername", "=", "\"www-authenticate\"", ")", ":", "retval", "=", "{", "}", "if", "headername", "in", "headers", ":", "try", ":", "authenticate", "=", "headers", "[", "headername", "]", ".", "strip", "(", ")", "www_auth", "=", "(", "USE_WWW_AUTH_STRICT_PARSING", "and", "WWW_AUTH_STRICT", "or", "WWW_AUTH_RELAXED", ")", "while", "authenticate", ":", "# Break off the scheme at the beginning of the line", "if", "headername", "==", "\"authentication-info\"", ":", "(", "auth_scheme", ",", "the_rest", ")", "=", "(", "\"digest\"", ",", "authenticate", ")", "else", ":", "(", "auth_scheme", ",", "the_rest", ")", "=", "authenticate", ".", "split", "(", "\" \"", ",", "1", ")", "# Now loop over all the key value pairs that come after the scheme,", "# being careful not to roll into the next scheme", "match", "=", "www_auth", ".", "search", "(", "the_rest", ")", "auth_params", "=", "{", "}", "while", "match", ":", "if", "match", "and", "len", "(", "match", ".", "groups", "(", ")", ")", "==", "3", ":", "(", "key", ",", "value", ",", "the_rest", ")", "=", "match", ".", "groups", "(", ")", "auth_params", "[", "key", ".", "lower", "(", ")", "]", "=", "UNQUOTE_PAIRS", ".", "sub", "(", "r\"\\1\"", ",", "value", ")", "# '\\\\'.join([x.replace('\\\\', '') for x in value.split('\\\\\\\\')])", "match", "=", "www_auth", ".", "search", "(", "the_rest", ")", "retval", "[", "auth_scheme", ".", "lower", "(", ")", "]", "=", "auth_params", "authenticate", "=", "the_rest", ".", "strip", "(", ")", "except", "ValueError", ":", "raise", "MalformedHeader", "(", "\"WWW-Authenticate\"", ")", "return", "retval" ]
[ 398, 0 ]
[ 431, 17 ]
python
en
['en', 'en', 'en']
True
_entry_disposition
(response_headers, request_headers)
Determine freshness from the Date, Expires and Cache-Control headers. We don't handle the following: 1. Cache-Control: max-stale 2. Age: headers are not used in the calculations. Not that this algorithm is simpler than you might think because we are operating as a private (non-shared) cache. This lets us ignore 's-maxage'. We can also ignore 'proxy-invalidate' since we aren't a proxy. We will never return a stale document as fresh as a design decision, and thus the non-implementation of 'max-stale'. This also lets us safely ignore 'must-revalidate' since we operate as if every server has sent 'must-revalidate'. Since we are private we get to ignore both 'public' and 'private' parameters. We also ignore 'no-transform' since we don't do any transformations. The 'no-store' parameter is handled at a higher level. So the only Cache-Control parameters we look at are: no-cache only-if-cached max-age min-fresh
Determine freshness from the Date, Expires and Cache-Control headers.
def _entry_disposition(response_headers, request_headers): """Determine freshness from the Date, Expires and Cache-Control headers. We don't handle the following: 1. Cache-Control: max-stale 2. Age: headers are not used in the calculations. Not that this algorithm is simpler than you might think because we are operating as a private (non-shared) cache. This lets us ignore 's-maxage'. We can also ignore 'proxy-invalidate' since we aren't a proxy. We will never return a stale document as fresh as a design decision, and thus the non-implementation of 'max-stale'. This also lets us safely ignore 'must-revalidate' since we operate as if every server has sent 'must-revalidate'. Since we are private we get to ignore both 'public' and 'private' parameters. We also ignore 'no-transform' since we don't do any transformations. The 'no-store' parameter is handled at a higher level. So the only Cache-Control parameters we look at are: no-cache only-if-cached max-age min-fresh """ retval = "STALE" cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if ( "pragma" in request_headers and request_headers["pragma"].lower().find("no-cache") != -1 ): retval = "TRANSPARENT" if "cache-control" not in request_headers: request_headers["cache-control"] = "no-cache" elif "no-cache" in cc: retval = "TRANSPARENT" elif "no-cache" in cc_response: retval = "STALE" elif "only-if-cached" in cc: retval = "FRESH" elif "date" in response_headers: date = calendar.timegm(email.Utils.parsedate_tz(response_headers["date"])) now = time.time() current_age = max(0, now - date) if "max-age" in cc_response: try: freshness_lifetime = int(cc_response["max-age"]) except ValueError: freshness_lifetime = 0 elif "expires" in response_headers: expires = email.Utils.parsedate_tz(response_headers["expires"]) if None == expires: freshness_lifetime = 0 else: freshness_lifetime = max(0, calendar.timegm(expires) - date) else: freshness_lifetime = 0 if "max-age" in cc: try: freshness_lifetime = int(cc["max-age"]) except ValueError: freshness_lifetime = 0 if "min-fresh" in cc: try: min_fresh = int(cc["min-fresh"]) except ValueError: min_fresh = 0 current_age += min_fresh if freshness_lifetime > current_age: retval = "FRESH" return retval
[ "def", "_entry_disposition", "(", "response_headers", ",", "request_headers", ")", ":", "retval", "=", "\"STALE\"", "cc", "=", "_parse_cache_control", "(", "request_headers", ")", "cc_response", "=", "_parse_cache_control", "(", "response_headers", ")", "if", "(", "\"pragma\"", "in", "request_headers", "and", "request_headers", "[", "\"pragma\"", "]", ".", "lower", "(", ")", ".", "find", "(", "\"no-cache\"", ")", "!=", "-", "1", ")", ":", "retval", "=", "\"TRANSPARENT\"", "if", "\"cache-control\"", "not", "in", "request_headers", ":", "request_headers", "[", "\"cache-control\"", "]", "=", "\"no-cache\"", "elif", "\"no-cache\"", "in", "cc", ":", "retval", "=", "\"TRANSPARENT\"", "elif", "\"no-cache\"", "in", "cc_response", ":", "retval", "=", "\"STALE\"", "elif", "\"only-if-cached\"", "in", "cc", ":", "retval", "=", "\"FRESH\"", "elif", "\"date\"", "in", "response_headers", ":", "date", "=", "calendar", ".", "timegm", "(", "email", ".", "Utils", ".", "parsedate_tz", "(", "response_headers", "[", "\"date\"", "]", ")", ")", "now", "=", "time", ".", "time", "(", ")", "current_age", "=", "max", "(", "0", ",", "now", "-", "date", ")", "if", "\"max-age\"", "in", "cc_response", ":", "try", ":", "freshness_lifetime", "=", "int", "(", "cc_response", "[", "\"max-age\"", "]", ")", "except", "ValueError", ":", "freshness_lifetime", "=", "0", "elif", "\"expires\"", "in", "response_headers", ":", "expires", "=", "email", ".", "Utils", ".", "parsedate_tz", "(", "response_headers", "[", "\"expires\"", "]", ")", "if", "None", "==", "expires", ":", "freshness_lifetime", "=", "0", "else", ":", "freshness_lifetime", "=", "max", "(", "0", ",", "calendar", ".", "timegm", "(", "expires", ")", "-", "date", ")", "else", ":", "freshness_lifetime", "=", "0", "if", "\"max-age\"", "in", "cc", ":", "try", ":", "freshness_lifetime", "=", "int", "(", "cc", "[", "\"max-age\"", "]", ")", "except", "ValueError", ":", "freshness_lifetime", "=", "0", "if", "\"min-fresh\"", "in", "cc", ":", "try", ":", "min_fresh", "=", "int", "(", "cc", "[", "\"min-fresh\"", "]", ")", "except", "ValueError", ":", "min_fresh", "=", "0", "current_age", "+=", "min_fresh", "if", "freshness_lifetime", ">", "current_age", ":", "retval", "=", "\"FRESH\"", "return", "retval" ]
[ 435, 0 ]
[ 510, 17 ]
python
en
['en', 'en', 'en']
True
proxy_info_from_environment
(method="http")
Read proxy info from the environment variables.
Read proxy info from the environment variables.
def proxy_info_from_environment(method="http"): """Read proxy info from the environment variables. """ if method not in ["http", "https"]: return env_var = method + "_proxy" url = os.environ.get(env_var, os.environ.get(env_var.upper())) if not url: return return proxy_info_from_url(url, method, None)
[ "def", "proxy_info_from_environment", "(", "method", "=", "\"http\"", ")", ":", "if", "method", "not", "in", "[", "\"http\"", ",", "\"https\"", "]", ":", "return", "env_var", "=", "method", "+", "\"_proxy\"", "url", "=", "os", ".", "environ", ".", "get", "(", "env_var", ",", "os", ".", "environ", ".", "get", "(", "env_var", ".", "upper", "(", ")", ")", ")", "if", "not", "url", ":", "return", "return", "proxy_info_from_url", "(", "url", ",", "method", ",", "None", ")" ]
[ 1068, 0 ]
[ 1078, 49 ]
python
en
['en', 'en', 'en']
True
proxy_info_from_url
(url, method="http", noproxy=None)
Construct a ProxyInfo from a URL (such as http_proxy env var)
Construct a ProxyInfo from a URL (such as http_proxy env var)
def proxy_info_from_url(url, method="http", noproxy=None): """Construct a ProxyInfo from a URL (such as http_proxy env var) """ url = urlparse.urlparse(url) username = None password = None port = None if "@" in url[1]: ident, host_port = url[1].split("@", 1) if ":" in ident: username, password = ident.split(":", 1) else: password = ident else: host_port = url[1] if ":" in host_port: host, port = host_port.split(":", 1) else: host = host_port if port: port = int(port) else: port = dict(https=443, http=80)[method] proxy_type = 3 # socks.PROXY_TYPE_HTTP pi = ProxyInfo( proxy_type=proxy_type, proxy_host=host, proxy_port=port, proxy_user=username or None, proxy_pass=password or None, proxy_headers=None, ) bypass_hosts = [] # If not given an explicit noproxy value, respect values in env vars. if noproxy is None: noproxy = os.environ.get("no_proxy", os.environ.get("NO_PROXY", "")) # Special case: A single '*' character means all hosts should be bypassed. if noproxy == "*": bypass_hosts = AllHosts elif noproxy.strip(): bypass_hosts = noproxy.split(",") bypass_hosts = filter(bool, bypass_hosts) # To exclude empty string. pi.bypass_hosts = bypass_hosts return pi
[ "def", "proxy_info_from_url", "(", "url", ",", "method", "=", "\"http\"", ",", "noproxy", "=", "None", ")", ":", "url", "=", "urlparse", ".", "urlparse", "(", "url", ")", "username", "=", "None", "password", "=", "None", "port", "=", "None", "if", "\"@\"", "in", "url", "[", "1", "]", ":", "ident", ",", "host_port", "=", "url", "[", "1", "]", ".", "split", "(", "\"@\"", ",", "1", ")", "if", "\":\"", "in", "ident", ":", "username", ",", "password", "=", "ident", ".", "split", "(", "\":\"", ",", "1", ")", "else", ":", "password", "=", "ident", "else", ":", "host_port", "=", "url", "[", "1", "]", "if", "\":\"", "in", "host_port", ":", "host", ",", "port", "=", "host_port", ".", "split", "(", "\":\"", ",", "1", ")", "else", ":", "host", "=", "host_port", "if", "port", ":", "port", "=", "int", "(", "port", ")", "else", ":", "port", "=", "dict", "(", "https", "=", "443", ",", "http", "=", "80", ")", "[", "method", "]", "proxy_type", "=", "3", "# socks.PROXY_TYPE_HTTP", "pi", "=", "ProxyInfo", "(", "proxy_type", "=", "proxy_type", ",", "proxy_host", "=", "host", ",", "proxy_port", "=", "port", ",", "proxy_user", "=", "username", "or", "None", ",", "proxy_pass", "=", "password", "or", "None", ",", "proxy_headers", "=", "None", ",", ")", "bypass_hosts", "=", "[", "]", "# If not given an explicit noproxy value, respect values in env vars.", "if", "noproxy", "is", "None", ":", "noproxy", "=", "os", ".", "environ", ".", "get", "(", "\"no_proxy\"", ",", "os", ".", "environ", ".", "get", "(", "\"NO_PROXY\"", ",", "\"\"", ")", ")", "# Special case: A single '*' character means all hosts should be bypassed.", "if", "noproxy", "==", "\"*\"", ":", "bypass_hosts", "=", "AllHosts", "elif", "noproxy", ".", "strip", "(", ")", ":", "bypass_hosts", "=", "noproxy", ".", "split", "(", "\",\"", ")", "bypass_hosts", "=", "filter", "(", "bool", ",", "bypass_hosts", ")", "# To exclude empty string.", "pi", ".", "bypass_hosts", "=", "bypass_hosts", "return", "pi" ]
[ 1081, 0 ]
[ 1128, 13 ]
python
en
['en', 'en', 'en']
True
Authentication.request
(self, method, request_uri, headers, content)
Modify the request headers to add the appropriate Authorization header. Over-ride this in sub-classes.
Modify the request headers to add the appropriate Authorization header. Over-ride this in sub-classes.
def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header. Over-ride this in sub-classes.""" pass
[ "def", "request", "(", "self", ",", "method", ",", "request_uri", ",", "headers", ",", "content", ")", ":", "pass" ]
[ 617, 4 ]
[ 620, 12 ]
python
en
['en', 'en', 'en']
True
Authentication.response
(self, response, content)
Gives us a chance to update with new nonces or such returned from the last authorized response. Over-rise this in sub-classes if necessary. Return TRUE is the request is to be retried, for example Digest may return stale=true.
Gives us a chance to update with new nonces or such returned from the last authorized response. Over-rise this in sub-classes if necessary.
def response(self, response, content): """Gives us a chance to update with new nonces or such returned from the last authorized response. Over-rise this in sub-classes if necessary. Return TRUE is the request is to be retried, for example Digest may return stale=true. """ return False
[ "def", "response", "(", "self", ",", "response", ",", "content", ")", ":", "return", "False" ]
[ 622, 4 ]
[ 630, 20 ]
python
en
['en', 'en', 'en']
True
BasicAuthentication.request
(self, method, request_uri, headers, content)
Modify the request headers to add the appropriate Authorization header.
Modify the request headers to add the appropriate Authorization header.
def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers["authorization"] = ( "Basic " + base64.b64encode("%s:%s" % self.credentials).strip() )
[ "def", "request", "(", "self", ",", "method", ",", "request_uri", ",", "headers", ",", "content", ")", ":", "headers", "[", "\"authorization\"", "]", "=", "(", "\"Basic \"", "+", "base64", ".", "b64encode", "(", "\"%s:%s\"", "%", "self", ".", "credentials", ")", ".", "strip", "(", ")", ")" ]
[ 641, 4 ]
[ 646, 9 ]
python
en
['en', 'en', 'en']
True
DigestAuthentication.request
(self, method, request_uri, headers, content, cnonce=None)
Modify the request headers
Modify the request headers
def request(self, method, request_uri, headers, content, cnonce=None): """Modify the request headers""" H = lambda x: _md5(x).hexdigest() KD = lambda s, d: H("%s:%s" % (s, d)) A2 = "".join([method, ":", request_uri]) self.challenge["cnonce"] = cnonce or _cnonce() request_digest = '"%s"' % KD( H(self.A1), "%s:%s:%s:%s:%s" % ( self.challenge["nonce"], "%08x" % self.challenge["nc"], self.challenge["cnonce"], self.challenge["qop"], H(A2), ), ) headers["authorization"] = ( 'Digest username="%s", realm="%s", nonce="%s", ' 'uri="%s", algorithm=%s, response=%s, qop=%s, ' 'nc=%08x, cnonce="%s"' ) % ( self.credentials[0], self.challenge["realm"], self.challenge["nonce"], request_uri, self.challenge["algorithm"], request_digest, self.challenge["qop"], self.challenge["nc"], self.challenge["cnonce"], ) if self.challenge.get("opaque"): headers["authorization"] += ', opaque="%s"' % self.challenge["opaque"] self.challenge["nc"] += 1
[ "def", "request", "(", "self", ",", "method", ",", "request_uri", ",", "headers", ",", "content", ",", "cnonce", "=", "None", ")", ":", "H", "=", "lambda", "x", ":", "_md5", "(", "x", ")", ".", "hexdigest", "(", ")", "KD", "=", "lambda", "s", ",", "d", ":", "H", "(", "\"%s:%s\"", "%", "(", "s", ",", "d", ")", ")", "A2", "=", "\"\"", ".", "join", "(", "[", "method", ",", "\":\"", ",", "request_uri", "]", ")", "self", ".", "challenge", "[", "\"cnonce\"", "]", "=", "cnonce", "or", "_cnonce", "(", ")", "request_digest", "=", "'\"%s\"'", "%", "KD", "(", "H", "(", "self", ".", "A1", ")", ",", "\"%s:%s:%s:%s:%s\"", "%", "(", "self", ".", "challenge", "[", "\"nonce\"", "]", ",", "\"%08x\"", "%", "self", ".", "challenge", "[", "\"nc\"", "]", ",", "self", ".", "challenge", "[", "\"cnonce\"", "]", ",", "self", ".", "challenge", "[", "\"qop\"", "]", ",", "H", "(", "A2", ")", ",", ")", ",", ")", "headers", "[", "\"authorization\"", "]", "=", "(", "'Digest username=\"%s\", realm=\"%s\", nonce=\"%s\", '", "'uri=\"%s\", algorithm=%s, response=%s, qop=%s, '", "'nc=%08x, cnonce=\"%s\"'", ")", "%", "(", "self", ".", "credentials", "[", "0", "]", ",", "self", ".", "challenge", "[", "\"realm\"", "]", ",", "self", ".", "challenge", "[", "\"nonce\"", "]", ",", "request_uri", ",", "self", ".", "challenge", "[", "\"algorithm\"", "]", ",", "request_digest", ",", "self", ".", "challenge", "[", "\"qop\"", "]", ",", "self", ".", "challenge", "[", "\"nc\"", "]", ",", "self", ".", "challenge", "[", "\"cnonce\"", "]", ",", ")", "if", "self", ".", "challenge", ".", "get", "(", "\"opaque\"", ")", ":", "headers", "[", "\"authorization\"", "]", "+=", "', opaque=\"%s\"'", "%", "self", ".", "challenge", "[", "\"opaque\"", "]", "self", ".", "challenge", "[", "\"nc\"", "]", "+=", "1" ]
[ 685, 4 ]
[ 719, 33 ]
python
en
['en', 'en', 'en']
True
HmacDigestAuthentication.request
(self, method, request_uri, headers, content)
Modify the request headers
Modify the request headers
def request(self, method, request_uri, headers, content): """Modify the request headers""" keys = _get_end2end_headers(headers) keylist = "".join(["%s " % k for k in keys]) headers_val = "".join([headers[k] for k in keys]) created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % ( method, request_uri, cnonce, self.challenge["snonce"], headers_val, ) request_digest = ( hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower() ) headers["authorization"] = ( 'HMACDigest username="%s", realm="%s", snonce="%s",' ' cnonce="%s", uri="%s", created="%s", ' 'response="%s", headers="%s"' ) % ( self.credentials[0], self.challenge["realm"], self.challenge["snonce"], cnonce, request_uri, created, request_digest, keylist, )
[ "def", "request", "(", "self", ",", "method", ",", "request_uri", ",", "headers", ",", "content", ")", ":", "keys", "=", "_get_end2end_headers", "(", "headers", ")", "keylist", "=", "\"\"", ".", "join", "(", "[", "\"%s \"", "%", "k", "for", "k", "in", "keys", "]", ")", "headers_val", "=", "\"\"", ".", "join", "(", "[", "headers", "[", "k", "]", "for", "k", "in", "keys", "]", ")", "created", "=", "time", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M:%SZ\"", ",", "time", ".", "gmtime", "(", ")", ")", "cnonce", "=", "_cnonce", "(", ")", "request_digest", "=", "\"%s:%s:%s:%s:%s\"", "%", "(", "method", ",", "request_uri", ",", "cnonce", ",", "self", ".", "challenge", "[", "\"snonce\"", "]", ",", "headers_val", ",", ")", "request_digest", "=", "(", "hmac", ".", "new", "(", "self", ".", "key", ",", "request_digest", ",", "self", ".", "hashmod", ")", ".", "hexdigest", "(", ")", ".", "lower", "(", ")", ")", "headers", "[", "\"authorization\"", "]", "=", "(", "'HMACDigest username=\"%s\", realm=\"%s\", snonce=\"%s\",'", "' cnonce=\"%s\", uri=\"%s\", created=\"%s\", '", "'response=\"%s\", headers=\"%s\"'", ")", "%", "(", "self", ".", "credentials", "[", "0", "]", ",", "self", ".", "challenge", "[", "\"realm\"", "]", ",", "self", ".", "challenge", "[", "\"snonce\"", "]", ",", "cnonce", ",", "request_uri", ",", "created", ",", "request_digest", ",", "keylist", ",", ")" ]
[ 799, 4 ]
[ 829, 9 ]
python
en
['en', 'en', 'en']
True
WsseAuthentication.request
(self, method, request_uri, headers, content)
Modify the request headers to add the appropriate Authorization header.
Modify the request headers to add the appropriate Authorization header.
def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers["authorization"] = 'WSSE profile="UsernameToken"' iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1]) headers["X-WSSE"] = ( 'UsernameToken Username="%s", PasswordDigest="%s", ' 'Nonce="%s", Created="%s"' ) % (self.credentials[0], password_digest, cnonce, iso_now)
[ "def", "request", "(", "self", ",", "method", ",", "request_uri", ",", "headers", ",", "content", ")", ":", "headers", "[", "\"authorization\"", "]", "=", "'WSSE profile=\"UsernameToken\"'", "iso_now", "=", "time", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M:%SZ\"", ",", "time", ".", "gmtime", "(", ")", ")", "cnonce", "=", "_cnonce", "(", ")", "password_digest", "=", "_wsse_username_token", "(", "cnonce", ",", "iso_now", ",", "self", ".", "credentials", "[", "1", "]", ")", "headers", "[", "\"X-WSSE\"", "]", "=", "(", "'UsernameToken Username=\"%s\", PasswordDigest=\"%s\", '", "'Nonce=\"%s\", Created=\"%s\"'", ")", "%", "(", "self", ".", "credentials", "[", "0", "]", ",", "password_digest", ",", "cnonce", ",", "iso_now", ")" ]
[ 856, 4 ]
[ 866, 67 ]
python
en
['en', 'en', 'en']
True
GoogleLoginAuthentication.request
(self, method, request_uri, headers, content)
Modify the request headers to add the appropriate Authorization header.
Modify the request headers to add the appropriate Authorization header.
def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers["authorization"] = "GoogleLogin Auth=" + self.Auth
[ "def", "request", "(", "self", ",", "method", ",", "request_uri", ",", "headers", ",", "content", ")", ":", "headers", "[", "\"authorization\"", "]", "=", "\"GoogleLogin Auth=\"", "+", "self", ".", "Auth" ]
[ 907, 4 ]
[ 910, 66 ]
python
en
['en', 'en', 'en']
True
ProxyInfo.__init__
( self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None, )
Args: proxy_type: The type of proxy server. This must be set to one of socks.PROXY_TYPE_XXX constants. For example: p = ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost', proxy_port=8000) proxy_host: The hostname or IP address of the proxy server. proxy_port: The port that the proxy server is running on. proxy_rdns: If True (default), DNS queries will not be performed locally, and instead, handed to the proxy to resolve. This is useful if the network does not allow resolution of non-local names. In httplib2 0.9 and earlier, this defaulted to False. proxy_user: The username used to authenticate with the proxy server. proxy_pass: The password used to authenticate with the proxy server. proxy_headers: Additional or modified headers for the proxy connect request.
Args:
def __init__( self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None, ): """Args: proxy_type: The type of proxy server. This must be set to one of socks.PROXY_TYPE_XXX constants. For example: p = ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost', proxy_port=8000) proxy_host: The hostname or IP address of the proxy server. proxy_port: The port that the proxy server is running on. proxy_rdns: If True (default), DNS queries will not be performed locally, and instead, handed to the proxy to resolve. This is useful if the network does not allow resolution of non-local names. In httplib2 0.9 and earlier, this defaulted to False. proxy_user: The username used to authenticate with the proxy server. proxy_pass: The password used to authenticate with the proxy server. proxy_headers: Additional or modified headers for the proxy connect request. """ self.proxy_type = proxy_type self.proxy_host = proxy_host self.proxy_port = proxy_port self.proxy_rdns = proxy_rdns self.proxy_user = proxy_user self.proxy_pass = proxy_pass self.proxy_headers = proxy_headers
[ "def", "__init__", "(", "self", ",", "proxy_type", ",", "proxy_host", ",", "proxy_port", ",", "proxy_rdns", "=", "True", ",", "proxy_user", "=", "None", ",", "proxy_pass", "=", "None", ",", "proxy_headers", "=", "None", ",", ")", ":", "self", ".", "proxy_type", "=", "proxy_type", "self", ".", "proxy_host", "=", "proxy_host", "self", ".", "proxy_port", "=", "proxy_port", "self", ".", "proxy_rdns", "=", "proxy_rdns", "self", ".", "proxy_user", "=", "proxy_user", "self", ".", "proxy_pass", "=", "proxy_pass", "self", ".", "proxy_headers", "=", "proxy_headers" ]
[ 993, 4 ]
[ 1026, 42 ]
python
en
['en', 'gl', 'ur']
False
ProxyInfo.bypass_host
(self, hostname)
Has this host been excluded from the proxy config
Has this host been excluded from the proxy config
def bypass_host(self, hostname): """Has this host been excluded from the proxy config""" if self.bypass_hosts is AllHosts: return True hostname = "." + hostname.lstrip(".") for skip_name in self.bypass_hosts: # *.suffix if skip_name.startswith(".") and hostname.endswith(skip_name): return True # exact match if hostname == "." + skip_name: return True return False
[ "def", "bypass_host", "(", "self", ",", "hostname", ")", ":", "if", "self", ".", "bypass_hosts", "is", "AllHosts", ":", "return", "True", "hostname", "=", "\".\"", "+", "hostname", ".", "lstrip", "(", "\".\"", ")", "for", "skip_name", "in", "self", ".", "bypass_hosts", ":", "# *.suffix", "if", "skip_name", ".", "startswith", "(", "\".\"", ")", "and", "hostname", ".", "endswith", "(", "skip_name", ")", ":", "return", "True", "# exact match", "if", "hostname", "==", "\".\"", "+", "skip_name", ":", "return", "True", "return", "False" ]
[ 1045, 4 ]
[ 1058, 20 ]
python
en
['en', 'en', 'en']
True
HTTPConnectionWithTimeout.connect
(self)
Connect to the host and port specified in __init__.
Connect to the host and port specified in __init__.
def connect(self): """Connect to the host and port specified in __init__.""" # Mostly verbatim from httplib.py. if self.proxy_info and socks is None: raise ProxiesUnavailableError( "Proxy support missing but proxy use was requested!" ) msg = "getaddrinfo returns an empty list" if self.proxy_info and self.proxy_info.isgood(): use_proxy = True proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = ( self.proxy_info.astuple() ) host = proxy_host port = proxy_port else: use_proxy = False host = self.host port = self.port for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: if use_proxy: self.sock = socks.socksocket(af, socktype, proto) self.sock.setproxy( proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers, ) else: self.sock = socket.socket(af, socktype, proto) self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Different from httplib: support timeouts. if has_timeout(self.timeout): self.sock.settimeout(self.timeout) # End of difference from httplib. if self.debuglevel > 0: print("connect: (%s, %s) ************" % (self.host, self.port)) if use_proxy: print( "proxy: %s ************" % str( ( proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers, ) ) ) if use_proxy: self.sock.connect((self.host, self.port) + sa[2:]) else: self.sock.connect(sa) except socket.error as msg: if self.debuglevel > 0: print("connect fail: (%s, %s)" % (self.host, self.port)) if use_proxy: print( "proxy: %s" % str( ( proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers, ) ) ) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error(msg)
[ "def", "connect", "(", "self", ")", ":", "# Mostly verbatim from httplib.py.", "if", "self", ".", "proxy_info", "and", "socks", "is", "None", ":", "raise", "ProxiesUnavailableError", "(", "\"Proxy support missing but proxy use was requested!\"", ")", "msg", "=", "\"getaddrinfo returns an empty list\"", "if", "self", ".", "proxy_info", "and", "self", ".", "proxy_info", ".", "isgood", "(", ")", ":", "use_proxy", "=", "True", "proxy_type", ",", "proxy_host", ",", "proxy_port", ",", "proxy_rdns", ",", "proxy_user", ",", "proxy_pass", ",", "proxy_headers", "=", "(", "self", ".", "proxy_info", ".", "astuple", "(", ")", ")", "host", "=", "proxy_host", "port", "=", "proxy_port", "else", ":", "use_proxy", "=", "False", "host", "=", "self", ".", "host", "port", "=", "self", ".", "port", "for", "res", "in", "socket", ".", "getaddrinfo", "(", "host", ",", "port", ",", "0", ",", "socket", ".", "SOCK_STREAM", ")", ":", "af", ",", "socktype", ",", "proto", ",", "canonname", ",", "sa", "=", "res", "try", ":", "if", "use_proxy", ":", "self", ".", "sock", "=", "socks", ".", "socksocket", "(", "af", ",", "socktype", ",", "proto", ")", "self", ".", "sock", ".", "setproxy", "(", "proxy_type", ",", "proxy_host", ",", "proxy_port", ",", "proxy_rdns", ",", "proxy_user", ",", "proxy_pass", ",", "proxy_headers", ",", ")", "else", ":", "self", ".", "sock", "=", "socket", ".", "socket", "(", "af", ",", "socktype", ",", "proto", ")", "self", ".", "sock", ".", "setsockopt", "(", "socket", ".", "IPPROTO_TCP", ",", "socket", ".", "TCP_NODELAY", ",", "1", ")", "# Different from httplib: support timeouts.", "if", "has_timeout", "(", "self", ".", "timeout", ")", ":", "self", ".", "sock", ".", "settimeout", "(", "self", ".", "timeout", ")", "# End of difference from httplib.", "if", "self", ".", "debuglevel", ">", "0", ":", "print", "(", "\"connect: (%s, %s) ************\"", "%", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")", "if", "use_proxy", ":", "print", "(", "\"proxy: %s ************\"", "%", "str", "(", "(", "proxy_host", ",", "proxy_port", ",", "proxy_rdns", ",", "proxy_user", ",", "proxy_pass", ",", "proxy_headers", ",", ")", ")", ")", "if", "use_proxy", ":", "self", ".", "sock", ".", "connect", "(", "(", "self", ".", "host", ",", "self", ".", "port", ")", "+", "sa", "[", "2", ":", "]", ")", "else", ":", "self", ".", "sock", ".", "connect", "(", "sa", ")", "except", "socket", ".", "error", "as", "msg", ":", "if", "self", ".", "debuglevel", ">", "0", ":", "print", "(", "\"connect fail: (%s, %s)\"", "%", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")", "if", "use_proxy", ":", "print", "(", "\"proxy: %s\"", "%", "str", "(", "(", "proxy_host", ",", "proxy_port", ",", "proxy_rdns", ",", "proxy_user", ",", "proxy_pass", ",", "proxy_headers", ",", ")", ")", ")", "if", "self", ".", "sock", ":", "self", ".", "sock", ".", "close", "(", ")", "self", ".", "sock", "=", "None", "continue", "break", "if", "not", "self", ".", "sock", ":", "raise", "socket", ".", "error", "(", "msg", ")" ]
[ 1145, 4 ]
[ 1231, 35 ]
python
en
['en', 'en', 'en']
True
HTTPSConnectionWithTimeout._GetValidHostsForCert
(self, cert)
Returns a list of valid host globs for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. Returns: list: A list of valid host globs.
Returns a list of valid host globs for an SSL certificate.
def _GetValidHostsForCert(self, cert): """Returns a list of valid host globs for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. Returns: list: A list of valid host globs. """ if "subjectAltName" in cert: return [x[1] for x in cert["subjectAltName"] if x[0].lower() == "dns"] else: return [x[0][1] for x in cert["subject"] if x[0][0].lower() == "commonname"]
[ "def", "_GetValidHostsForCert", "(", "self", ",", "cert", ")", ":", "if", "\"subjectAltName\"", "in", "cert", ":", "return", "[", "x", "[", "1", "]", "for", "x", "in", "cert", "[", "\"subjectAltName\"", "]", "if", "x", "[", "0", "]", ".", "lower", "(", ")", "==", "\"dns\"", "]", "else", ":", "return", "[", "x", "[", "0", "]", "[", "1", "]", "for", "x", "in", "cert", "[", "\"subject\"", "]", "if", "x", "[", "0", "]", "[", "0", "]", ".", "lower", "(", ")", "==", "\"commonname\"", "]" ]
[ 1287, 4 ]
[ 1298, 88 ]
python
en
['en', 'lb', 'en']
True
HTTPSConnectionWithTimeout._ValidateCertificateHostname
(self, cert, hostname)
Validates that a given hostname is valid for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. hostname: The hostname to test. Returns: bool: Whether or not the hostname is valid for this certificate.
Validates that a given hostname is valid for an SSL certificate.
def _ValidateCertificateHostname(self, cert, hostname): """Validates that a given hostname is valid for an SSL certificate. Args: cert: A dictionary representing an SSL certificate. hostname: The hostname to test. Returns: bool: Whether or not the hostname is valid for this certificate. """ hosts = self._GetValidHostsForCert(cert) for host in hosts: host_re = host.replace(".", "\.").replace("*", "[^.]*") if re.search("^%s$" % (host_re,), hostname, re.I): return True return False
[ "def", "_ValidateCertificateHostname", "(", "self", ",", "cert", ",", "hostname", ")", ":", "hosts", "=", "self", ".", "_GetValidHostsForCert", "(", "cert", ")", "for", "host", "in", "hosts", ":", "host_re", "=", "host", ".", "replace", "(", "\".\"", ",", "\"\\.\"", ")", ".", "replace", "(", "\"*\"", ",", "\"[^.]*\"", ")", "if", "re", ".", "search", "(", "\"^%s$\"", "%", "(", "host_re", ",", ")", ",", "hostname", ",", "re", ".", "I", ")", ":", "return", "True", "return", "False" ]
[ 1300, 4 ]
[ 1314, 20 ]
python
en
['en', 'en', 'en']
True
HTTPSConnectionWithTimeout.connect
(self)
Connect to a host on a given (SSL) port.
Connect to a host on a given (SSL) port.
def connect(self): "Connect to a host on a given (SSL) port." msg = "getaddrinfo returns an empty list" if self.proxy_info and self.proxy_info.isgood(): use_proxy = True proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = ( self.proxy_info.astuple() ) host = proxy_host port = proxy_port else: use_proxy = False host = self.host port = self.port address_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM) for family, socktype, proto, canonname, sockaddr in address_info: try: if use_proxy: sock = socks.socksocket(family, socktype, proto) sock.setproxy( proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers, ) else: sock = socket.socket(family, socktype, proto) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if has_timeout(self.timeout): sock.settimeout(self.timeout) if use_proxy: sock.connect((self.host, self.port) + sockaddr[:2]) else: sock.connect(sockaddr) self.sock = _ssl_wrap_socket( sock, self.key_file, self.cert_file, self.disable_ssl_certificate_validation, self.ca_certs, self.ssl_version, self.host, ) if self.debuglevel > 0: print("connect: (%s, %s)" % (self.host, self.port)) if use_proxy: print( "proxy: %s" % str( ( proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers, ) ) ) if not self.disable_ssl_certificate_validation: cert = self.sock.getpeercert() hostname = self.host.split(":", 0)[0] if not self._ValidateCertificateHostname(cert, hostname): raise CertificateHostnameMismatch( "Server presented certificate that does not match " "host %s: %s" % (hostname, cert), hostname, cert, ) except ( ssl_SSLError, ssl_CertificateError, CertificateHostnameMismatch, ) as e: if sock: sock.close() if self.sock: self.sock.close() self.sock = None # Unfortunately the ssl module doesn't seem to provide any way # to get at more detailed error information, in particular # whether the error is due to certificate validation or # something else (such as SSL protocol mismatch). if getattr(e, "errno", None) == ssl.SSL_ERROR_SSL: raise SSLHandshakeError(e) else: raise except (socket.timeout, socket.gaierror): raise except socket.error as msg: if self.debuglevel > 0: print("connect fail: (%s, %s)" % (self.host, self.port)) if use_proxy: print( "proxy: %s" % str( ( proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers, ) ) ) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error(msg)
[ "def", "connect", "(", "self", ")", ":", "msg", "=", "\"getaddrinfo returns an empty list\"", "if", "self", ".", "proxy_info", "and", "self", ".", "proxy_info", ".", "isgood", "(", ")", ":", "use_proxy", "=", "True", "proxy_type", ",", "proxy_host", ",", "proxy_port", ",", "proxy_rdns", ",", "proxy_user", ",", "proxy_pass", ",", "proxy_headers", "=", "(", "self", ".", "proxy_info", ".", "astuple", "(", ")", ")", "host", "=", "proxy_host", "port", "=", "proxy_port", "else", ":", "use_proxy", "=", "False", "host", "=", "self", ".", "host", "port", "=", "self", ".", "port", "address_info", "=", "socket", ".", "getaddrinfo", "(", "host", ",", "port", ",", "0", ",", "socket", ".", "SOCK_STREAM", ")", "for", "family", ",", "socktype", ",", "proto", ",", "canonname", ",", "sockaddr", "in", "address_info", ":", "try", ":", "if", "use_proxy", ":", "sock", "=", "socks", ".", "socksocket", "(", "family", ",", "socktype", ",", "proto", ")", "sock", ".", "setproxy", "(", "proxy_type", ",", "proxy_host", ",", "proxy_port", ",", "proxy_rdns", ",", "proxy_user", ",", "proxy_pass", ",", "proxy_headers", ",", ")", "else", ":", "sock", "=", "socket", ".", "socket", "(", "family", ",", "socktype", ",", "proto", ")", "sock", ".", "setsockopt", "(", "socket", ".", "IPPROTO_TCP", ",", "socket", ".", "TCP_NODELAY", ",", "1", ")", "if", "has_timeout", "(", "self", ".", "timeout", ")", ":", "sock", ".", "settimeout", "(", "self", ".", "timeout", ")", "if", "use_proxy", ":", "sock", ".", "connect", "(", "(", "self", ".", "host", ",", "self", ".", "port", ")", "+", "sockaddr", "[", ":", "2", "]", ")", "else", ":", "sock", ".", "connect", "(", "sockaddr", ")", "self", ".", "sock", "=", "_ssl_wrap_socket", "(", "sock", ",", "self", ".", "key_file", ",", "self", ".", "cert_file", ",", "self", ".", "disable_ssl_certificate_validation", ",", "self", ".", "ca_certs", ",", "self", ".", "ssl_version", ",", "self", ".", "host", ",", ")", "if", "self", ".", "debuglevel", ">", "0", ":", "print", "(", "\"connect: (%s, %s)\"", "%", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")", "if", "use_proxy", ":", "print", "(", "\"proxy: %s\"", "%", "str", "(", "(", "proxy_host", ",", "proxy_port", ",", "proxy_rdns", ",", "proxy_user", ",", "proxy_pass", ",", "proxy_headers", ",", ")", ")", ")", "if", "not", "self", ".", "disable_ssl_certificate_validation", ":", "cert", "=", "self", ".", "sock", ".", "getpeercert", "(", ")", "hostname", "=", "self", ".", "host", ".", "split", "(", "\":\"", ",", "0", ")", "[", "0", "]", "if", "not", "self", ".", "_ValidateCertificateHostname", "(", "cert", ",", "hostname", ")", ":", "raise", "CertificateHostnameMismatch", "(", "\"Server presented certificate that does not match \"", "\"host %s: %s\"", "%", "(", "hostname", ",", "cert", ")", ",", "hostname", ",", "cert", ",", ")", "except", "(", "ssl_SSLError", ",", "ssl_CertificateError", ",", "CertificateHostnameMismatch", ",", ")", "as", "e", ":", "if", "sock", ":", "sock", ".", "close", "(", ")", "if", "self", ".", "sock", ":", "self", ".", "sock", ".", "close", "(", ")", "self", ".", "sock", "=", "None", "# Unfortunately the ssl module doesn't seem to provide any way", "# to get at more detailed error information, in particular", "# whether the error is due to certificate validation or", "# something else (such as SSL protocol mismatch).", "if", "getattr", "(", "e", ",", "\"errno\"", ",", "None", ")", "==", "ssl", ".", "SSL_ERROR_SSL", ":", "raise", "SSLHandshakeError", "(", "e", ")", "else", ":", "raise", "except", "(", "socket", ".", "timeout", ",", "socket", ".", "gaierror", ")", ":", "raise", "except", "socket", ".", "error", "as", "msg", ":", "if", "self", ".", "debuglevel", ">", "0", ":", "print", "(", "\"connect fail: (%s, %s)\"", "%", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")", "if", "use_proxy", ":", "print", "(", "\"proxy: %s\"", "%", "str", "(", "(", "proxy_host", ",", "proxy_port", ",", "proxy_rdns", ",", "proxy_user", ",", "proxy_pass", ",", "proxy_headers", ",", ")", ")", ")", "if", "self", ".", "sock", ":", "self", ".", "sock", ".", "close", "(", ")", "self", ".", "sock", "=", "None", "continue", "break", "if", "not", "self", ".", "sock", ":", "raise", "socket", ".", "error", "(", "msg", ")" ]
[ 1316, 4 ]
[ 1438, 35 ]
python
en
['en', 'en', 'en']
True
Http.__init__
( self, cache=None, timeout=None, proxy_info=proxy_info_from_environment, ca_certs=None, disable_ssl_certificate_validation=False, ssl_version=None, )
If 'cache' is a string then it is used as a directory name for a disk cache. Otherwise it must be an object that supports the same interface as FileCache. All timeouts are in seconds. If None is passed for timeout then Python's default timeout for sockets will be used. See for example the docs of socket.setdefaulttimeout(): http://docs.python.org/library/socket.html#socket.setdefaulttimeout `proxy_info` may be: - a callable that takes the http scheme ('http' or 'https') and returns a ProxyInfo instance per request. By default, uses proxy_nfo_from_environment. - a ProxyInfo instance (static proxy config). - None (proxy disabled). ca_certs is the path of a file containing root CA certificates for SSL server certificate validation. By default, a CA cert file bundled with httplib2 is used. If disable_ssl_certificate_validation is true, SSL cert validation will not be performed. By default, ssl.PROTOCOL_SSLv23 will be used for the ssl version.
If 'cache' is a string then it is used as a directory name for a disk cache. Otherwise it must be an object that supports the same interface as FileCache.
def __init__( self, cache=None, timeout=None, proxy_info=proxy_info_from_environment, ca_certs=None, disable_ssl_certificate_validation=False, ssl_version=None, ): """If 'cache' is a string then it is used as a directory name for a disk cache. Otherwise it must be an object that supports the same interface as FileCache. All timeouts are in seconds. If None is passed for timeout then Python's default timeout for sockets will be used. See for example the docs of socket.setdefaulttimeout(): http://docs.python.org/library/socket.html#socket.setdefaulttimeout `proxy_info` may be: - a callable that takes the http scheme ('http' or 'https') and returns a ProxyInfo instance per request. By default, uses proxy_nfo_from_environment. - a ProxyInfo instance (static proxy config). - None (proxy disabled). ca_certs is the path of a file containing root CA certificates for SSL server certificate validation. By default, a CA cert file bundled with httplib2 is used. If disable_ssl_certificate_validation is true, SSL cert validation will not be performed. By default, ssl.PROTOCOL_SSLv23 will be used for the ssl version. """ self.proxy_info = proxy_info self.ca_certs = ca_certs self.disable_ssl_certificate_validation = disable_ssl_certificate_validation self.ssl_version = ssl_version # Map domain name to an httplib connection self.connections = {} # The location of the cache, for now a directory # where cached responses are held. if cache and isinstance(cache, basestring): self.cache = FileCache(cache) else: self.cache = cache # Name/password self.credentials = Credentials() # Key/cert self.certificates = KeyCerts() # authorization objects self.authorizations = [] # If set to False then no redirects are followed, even safe ones. self.follow_redirects = True # Which HTTP methods do we apply optimistic concurrency to, i.e. # which methods get an "if-match:" etag header added to them. self.optimistic_concurrency_methods = ["PUT", "PATCH"] # If 'follow_redirects' is True, and this is set to True then # all redirecs are followed, including unsafe ones. self.follow_all_redirects = False self.ignore_etag = False self.force_exception_to_status_code = False self.timeout = timeout # Keep Authorization: headers on a redirect. self.forward_authorization_headers = False
[ "def", "__init__", "(", "self", ",", "cache", "=", "None", ",", "timeout", "=", "None", ",", "proxy_info", "=", "proxy_info_from_environment", ",", "ca_certs", "=", "None", ",", "disable_ssl_certificate_validation", "=", "False", ",", "ssl_version", "=", "None", ",", ")", ":", "self", ".", "proxy_info", "=", "proxy_info", "self", ".", "ca_certs", "=", "ca_certs", "self", ".", "disable_ssl_certificate_validation", "=", "disable_ssl_certificate_validation", "self", ".", "ssl_version", "=", "ssl_version", "# Map domain name to an httplib connection", "self", ".", "connections", "=", "{", "}", "# The location of the cache, for now a directory", "# where cached responses are held.", "if", "cache", "and", "isinstance", "(", "cache", ",", "basestring", ")", ":", "self", ".", "cache", "=", "FileCache", "(", "cache", ")", "else", ":", "self", ".", "cache", "=", "cache", "# Name/password", "self", ".", "credentials", "=", "Credentials", "(", ")", "# Key/cert", "self", ".", "certificates", "=", "KeyCerts", "(", ")", "# authorization objects", "self", ".", "authorizations", "=", "[", "]", "# If set to False then no redirects are followed, even safe ones.", "self", ".", "follow_redirects", "=", "True", "# Which HTTP methods do we apply optimistic concurrency to, i.e.", "# which methods get an \"if-match:\" etag header added to them.", "self", ".", "optimistic_concurrency_methods", "=", "[", "\"PUT\"", ",", "\"PATCH\"", "]", "# If 'follow_redirects' is True, and this is set to True then", "# all redirecs are followed, including unsafe ones.", "self", ".", "follow_all_redirects", "=", "False", "self", ".", "ignore_etag", "=", "False", "self", ".", "force_exception_to_status_code", "=", "False", "self", ".", "timeout", "=", "timeout", "# Keep Authorization: headers on a redirect.", "self", ".", "forward_authorization_headers", "=", "False" ]
[ 1574, 4 ]
[ 1649, 50 ]
python
en
['en', 'en', 'en']
True
Http._auth_from_challenge
(self, host, request_uri, headers, response, content)
A generator that creates Authorization objects that can be applied to requests.
A generator that creates Authorization objects that can be applied to requests.
def _auth_from_challenge(self, host, request_uri, headers, response, content): """A generator that creates Authorization objects that can be applied to requests. """ challenges = _parse_www_authenticate(response, "www-authenticate") for cred in self.credentials.iter(host): for scheme in AUTH_SCHEME_ORDER: if scheme in challenges: yield AUTH_SCHEME_CLASSES[scheme]( cred, host, request_uri, headers, response, content, self )
[ "def", "_auth_from_challenge", "(", "self", ",", "host", ",", "request_uri", ",", "headers", ",", "response", ",", "content", ")", ":", "challenges", "=", "_parse_www_authenticate", "(", "response", ",", "\"www-authenticate\"", ")", "for", "cred", "in", "self", ".", "credentials", ".", "iter", "(", "host", ")", ":", "for", "scheme", "in", "AUTH_SCHEME_ORDER", ":", "if", "scheme", "in", "challenges", ":", "yield", "AUTH_SCHEME_CLASSES", "[", "scheme", "]", "(", "cred", ",", "host", ",", "request_uri", ",", "headers", ",", "response", ",", "content", ",", "self", ")" ]
[ 1665, 4 ]
[ 1675, 21 ]
python
en
['en', 'en', 'en']
True
Http.add_credentials
(self, name, password, domain="")
Add a name and password that will be used any time a request requires authentication.
Add a name and password that will be used any time a request requires authentication.
def add_credentials(self, name, password, domain=""): """Add a name and password that will be used any time a request requires authentication.""" self.credentials.add(name, password, domain)
[ "def", "add_credentials", "(", "self", ",", "name", ",", "password", ",", "domain", "=", "\"\"", ")", ":", "self", ".", "credentials", ".", "add", "(", "name", ",", "password", ",", "domain", ")" ]
[ 1677, 4 ]
[ 1680, 52 ]
python
en
['en', 'en', 'en']
True
Http.add_certificate
(self, key, cert, domain)
Add a key and cert that will be used any time a request requires authentication.
Add a key and cert that will be used any time a request requires authentication.
def add_certificate(self, key, cert, domain): """Add a key and cert that will be used any time a request requires authentication.""" self.certificates.add(key, cert, domain)
[ "def", "add_certificate", "(", "self", ",", "key", ",", "cert", ",", "domain", ")", ":", "self", ".", "certificates", ".", "add", "(", "key", ",", "cert", ",", "domain", ")" ]
[ 1682, 4 ]
[ 1685, 48 ]
python
en
['en', 'en', 'en']
True