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
UserKNN.predict_scores
(self, user, user_id, unpredicted_items)
Method to predict a rank for each user. In this implementation, for each unknown item, which will be predicted, we first look for users that seen that item and calculate the similarity between them and the user. Then we sort these similarities and get the most similar k's. Finally, the score of the unknown item will be the sum of the similarities.
Method to predict a rank for each user. In this implementation, for each unknown item, which will be predicted, we first look for users that seen that item and calculate the similarity between them and the user. Then we sort these similarities and get the most similar k's. Finally, the score of the unknown item will be the sum of the similarities.
def predict_scores(self, user, user_id, unpredicted_items): """ Method to predict a rank for each user. In this implementation, for each unknown item, which will be predicted, we first look for users that seen that item and calculate the similarity between them and the user. Then we sort these similarities and get the most similar k's. Finally, the score of the unknown item will be the sum of the similarities. """ predictions = [] for item_id in unpredicted_items: item = self.items[item_id] sim_sum = [] for user_v in self.users_id_viewed_item.get(item, []): sim_sum.append(self.su_matrix[user_id, user_v]) sim_sum = sorted(sim_sum, reverse=True) predictions.append((user, item, sum(sim_sum[:self.k_neighbors]))) return sorted(predictions, key=lambda x: -x[2])[:self.rank_length]
[ "def", "predict_scores", "(", "self", ",", "user", ",", "user_id", ",", "unpredicted_items", ")", ":", "predictions", "=", "[", "]", "for", "item_id", "in", "unpredicted_items", ":", "item", "=", "self", ".", "items", "[", "item_id", "]", "sim_sum", "=", "[", "]", "for", "user_v", "in", "self", ".", "users_id_viewed_item", ".", "get", "(", "item", ",", "[", "]", ")", ":", "sim_sum", ".", "append", "(", "self", ".", "su_matrix", "[", "user_id", ",", "user_v", "]", ")", "sim_sum", "=", "sorted", "(", "sim_sum", ",", "reverse", "=", "True", ")", "predictions", ".", "append", "(", "(", "user", ",", "item", ",", "sum", "(", "sim_sum", "[", ":", "self", ".", "k_neighbors", "]", ")", ")", ")", "return", "sorted", "(", "predictions", ",", "key", "=", "lambda", "x", ":", "-", "x", "[", "2", "]", ")", "[", ":", "self", ".", "rank_length", "]" ]
[ 119, 4 ]
[ 138, 74 ]
python
en
['en', 'error', 'th']
False
UserKNN.predict_similar_first_scores
(self, user, user_id, unpredicted_items)
Method to predict a rank for each user. In this implementation, for each unknown item, which will be predicted, we first look for its k most similar users and then take the intersection with the users that seen that item. Finally, the score of the unknown item will be the sum of the similarities.
Method to predict a rank for each user. In this implementation, for each unknown item, which will be predicted, we first look for its k most similar users and then take the intersection with the users that seen that item. Finally, the score of the unknown item will be the sum of the similarities.
def predict_similar_first_scores(self, user, user_id, unpredicted_items): """ Method to predict a rank for each user. In this implementation, for each unknown item, which will be predicted, we first look for its k most similar users and then take the intersection with the users that seen that item. Finally, the score of the unknown item will be the sum of the similarities. """ predictions = [] # Select user neighbors, sorting user similarity vector. Returns a list with index of sorting values neighbors = sorted(range(len(self.su_matrix[user_id])), key=lambda m: -self.su_matrix[user_id][m]) for item_id in unpredicted_items: item = self.items[item_id] # Intersection bt. the neighbors closest to the user and the users who accessed the unknown item. common_users = list(set(self.users_id_viewed_item.get(item, [])). intersection(neighbors[1:self.k_neighbors])) sim_sum = 0 for user_v in common_users: sim_sum += self.su_matrix[user_id, user_v] predictions.append((user, item, sim_sum)) return sorted(predictions, key=lambda x: -x[2])[:self.rank_length]
[ "def", "predict_similar_first_scores", "(", "self", ",", "user", ",", "user_id", ",", "unpredicted_items", ")", ":", "predictions", "=", "[", "]", "# Select user neighbors, sorting user similarity vector. Returns a list with index of sorting values", "neighbors", "=", "sorted", "(", "range", "(", "len", "(", "self", ".", "su_matrix", "[", "user_id", "]", ")", ")", ",", "key", "=", "lambda", "m", ":", "-", "self", ".", "su_matrix", "[", "user_id", "]", "[", "m", "]", ")", "for", "item_id", "in", "unpredicted_items", ":", "item", "=", "self", ".", "items", "[", "item_id", "]", "# Intersection bt. the neighbors closest to the user and the users who accessed the unknown item.", "common_users", "=", "list", "(", "set", "(", "self", ".", "users_id_viewed_item", ".", "get", "(", "item", ",", "[", "]", ")", ")", ".", "intersection", "(", "neighbors", "[", "1", ":", "self", ".", "k_neighbors", "]", ")", ")", "sim_sum", "=", "0", "for", "user_v", "in", "common_users", ":", "sim_sum", "+=", "self", ".", "su_matrix", "[", "user_id", ",", "user_v", "]", "predictions", ".", "append", "(", "(", "user", ",", "item", ",", "sim_sum", ")", ")", "return", "sorted", "(", "predictions", ",", "key", "=", "lambda", "x", ":", "-", "x", "[", "2", "]", ")", "[", ":", "self", ".", "rank_length", "]" ]
[ 140, 4 ]
[ 165, 74 ]
python
en
['en', 'error', 'th']
False
UserKNN.compute
(self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t')
Extends compute method from BaseItemRecommendation. Method to run recommender algorithm :param verbose: Print recommender and database information :type verbose: bool, default True :param metrics: List of evaluation metrics :type metrics: list, default None :param verbose_evaluation: Print the evaluation results :type verbose_evaluation: bool, default True :param as_table: Print the evaluation results as table :type as_table: bool, default False :param table_sep: Delimiter for print results (only work with verbose=True and as_table=True) :type table_sep: str, default '\t'
Extends compute method from BaseItemRecommendation. Method to run recommender algorithm
def compute(self, verbose=True, metrics=None, verbose_evaluation=True, as_table=False, table_sep='\t'): """ Extends compute method from BaseItemRecommendation. Method to run recommender algorithm :param verbose: Print recommender and database information :type verbose: bool, default True :param metrics: List of evaluation metrics :type metrics: list, default None :param verbose_evaluation: Print the evaluation results :type verbose_evaluation: bool, default True :param as_table: Print the evaluation results as table :type as_table: bool, default False :param table_sep: Delimiter for print results (only work with verbose=True and as_table=True) :type table_sep: str, default '\t' """ super(UserKNN, self).compute(verbose=verbose) if verbose: print("training_time:: %4f sec" % timed(self.init_model)) if self.extra_info_header is not None: print(self.extra_info_header) print("prediction_time:: %4f sec" % timed(self.predict)) print('\n') else: # Execute all in silence without prints self.extra_info_header = None self.init_model() self.predict() self.write_ranking() if self.test_file is not None: self.evaluate(metrics, verbose_evaluation, as_table=as_table, table_sep=table_sep)
[ "def", "compute", "(", "self", ",", "verbose", "=", "True", ",", "metrics", "=", "None", ",", "verbose_evaluation", "=", "True", ",", "as_table", "=", "False", ",", "table_sep", "=", "'\\t'", ")", ":", "super", "(", "UserKNN", ",", "self", ")", ".", "compute", "(", "verbose", "=", "verbose", ")", "if", "verbose", ":", "print", "(", "\"training_time:: %4f sec\"", "%", "timed", "(", "self", ".", "init_model", ")", ")", "if", "self", ".", "extra_info_header", "is", "not", "None", ":", "print", "(", "self", ".", "extra_info_header", ")", "print", "(", "\"prediction_time:: %4f sec\"", "%", "timed", "(", "self", ".", "predict", ")", ")", "print", "(", "'\\n'", ")", "else", ":", "# Execute all in silence without prints", "self", ".", "extra_info_header", "=", "None", "self", ".", "init_model", "(", ")", "self", ".", "predict", "(", ")", "self", ".", "write_ranking", "(", ")", "if", "self", ".", "test_file", "is", "not", "None", ":", "self", ".", "evaluate", "(", "metrics", ",", "verbose_evaluation", ",", "as_table", "=", "as_table", ",", "table_sep", "=", "table_sep", ")" ]
[ 167, 4 ]
[ 207, 94 ]
python
en
['en', 'error', 'th']
False
SpatialProxy.__init__
(self, klass, field, load_func=None)
Initialize on the given Geometry or Raster class (not an instance) and the corresponding field.
Initialize on the given Geometry or Raster class (not an instance) and the corresponding field.
def __init__(self, klass, field, load_func=None): """ Initialize on the given Geometry or Raster class (not an instance) and the corresponding field. """ self._klass = klass self._load_func = load_func or klass super().__init__(field)
[ "def", "__init__", "(", "self", ",", "klass", ",", "field", ",", "load_func", "=", "None", ")", ":", "self", ".", "_klass", "=", "klass", "self", ".", "_load_func", "=", "load_func", "or", "klass", "super", "(", ")", ".", "__init__", "(", "field", ")" ]
[ 11, 4 ]
[ 18, 31 ]
python
en
['en', 'error', 'th']
False
SpatialProxy.__get__
(self, instance, cls=None)
Retrieve the geometry or raster, initializing it using the corresponding class specified during initialization and the value of the field. Currently, GEOS or OGR geometries as well as GDALRasters are supported.
Retrieve the geometry or raster, initializing it using the corresponding class specified during initialization and the value of the field. Currently, GEOS or OGR geometries as well as GDALRasters are supported.
def __get__(self, instance, cls=None): """ Retrieve the geometry or raster, initializing it using the corresponding class specified during initialization and the value of the field. Currently, GEOS or OGR geometries as well as GDALRasters are supported. """ if instance is None: # Accessed on a class, not an instance return self # Getting the value of the field. try: geo_value = instance.__dict__[self.field.attname] except KeyError: geo_value = super().__get__(instance, cls) if isinstance(geo_value, self._klass): geo_obj = geo_value elif (geo_value is None) or (geo_value == ''): geo_obj = None else: # Otherwise, a geometry or raster object is built using the field's # contents, and the model's corresponding attribute is set. geo_obj = self._load_func(geo_value) setattr(instance, self.field.attname, geo_obj) return geo_obj
[ "def", "__get__", "(", "self", ",", "instance", ",", "cls", "=", "None", ")", ":", "if", "instance", "is", "None", ":", "# Accessed on a class, not an instance", "return", "self", "# Getting the value of the field.", "try", ":", "geo_value", "=", "instance", ".", "__dict__", "[", "self", ".", "field", ".", "attname", "]", "except", "KeyError", ":", "geo_value", "=", "super", "(", ")", ".", "__get__", "(", "instance", ",", "cls", ")", "if", "isinstance", "(", "geo_value", ",", "self", ".", "_klass", ")", ":", "geo_obj", "=", "geo_value", "elif", "(", "geo_value", "is", "None", ")", "or", "(", "geo_value", "==", "''", ")", ":", "geo_obj", "=", "None", "else", ":", "# Otherwise, a geometry or raster object is built using the field's", "# contents, and the model's corresponding attribute is set.", "geo_obj", "=", "self", ".", "_load_func", "(", "geo_value", ")", "setattr", "(", "instance", ",", "self", ".", "field", ".", "attname", ",", "geo_obj", ")", "return", "geo_obj" ]
[ 20, 4 ]
[ 46, 22 ]
python
en
['en', 'error', 'th']
False
SpatialProxy.__set__
(self, instance, value)
Retrieve the proxied geometry or raster with the corresponding class specified during initialization. To set geometries, use values of None, HEXEWKB, or WKT. To set rasters, use JSON or dict values.
Retrieve the proxied geometry or raster with the corresponding class specified during initialization.
def __set__(self, instance, value): """ Retrieve the proxied geometry or raster with the corresponding class specified during initialization. To set geometries, use values of None, HEXEWKB, or WKT. To set rasters, use JSON or dict values. """ # The geographic type of the field. gtype = self.field.geom_type if gtype == 'RASTER' and (value is None or isinstance(value, (str, dict, self._klass))): # For raster fields, assure input is None or a string, dict, or # raster instance. pass elif isinstance(value, self._klass): # The geometry type must match that of the field -- unless the # general GeometryField is used. if value.srid is None: # Assigning the field SRID if the geometry has no SRID. value.srid = self.field.srid elif value is None or isinstance(value, (str, memoryview)): # Set geometries with None, WKT, HEX, or WKB pass else: raise TypeError('Cannot set %s SpatialProxy (%s) with value of type: %s' % ( instance.__class__.__name__, gtype, type(value))) # Setting the objects dictionary with the value, and returning. instance.__dict__[self.field.attname] = value return value
[ "def", "__set__", "(", "self", ",", "instance", ",", "value", ")", ":", "# The geographic type of the field.", "gtype", "=", "self", ".", "field", ".", "geom_type", "if", "gtype", "==", "'RASTER'", "and", "(", "value", "is", "None", "or", "isinstance", "(", "value", ",", "(", "str", ",", "dict", ",", "self", ".", "_klass", ")", ")", ")", ":", "# For raster fields, assure input is None or a string, dict, or", "# raster instance.", "pass", "elif", "isinstance", "(", "value", ",", "self", ".", "_klass", ")", ":", "# The geometry type must match that of the field -- unless the", "# general GeometryField is used.", "if", "value", ".", "srid", "is", "None", ":", "# Assigning the field SRID if the geometry has no SRID.", "value", ".", "srid", "=", "self", ".", "field", ".", "srid", "elif", "value", "is", "None", "or", "isinstance", "(", "value", ",", "(", "str", ",", "memoryview", ")", ")", ":", "# Set geometries with None, WKT, HEX, or WKB", "pass", "else", ":", "raise", "TypeError", "(", "'Cannot set %s SpatialProxy (%s) with value of type: %s'", "%", "(", "instance", ".", "__class__", ".", "__name__", ",", "gtype", ",", "type", "(", "value", ")", ")", ")", "# Setting the objects dictionary with the value, and returning.", "instance", ".", "__dict__", "[", "self", ".", "field", ".", "attname", "]", "=", "value", "return", "value" ]
[ 48, 4 ]
[ 78, 20 ]
python
en
['en', 'error', 'th']
False
command_randomname
(bot, user, channel, args)
Generates a random name of the specified type from BehindTheName.com. See country codes at: http://www.behindthename.com/api/appendix2.php Usage: randomname <country> [<gender>].
Generates a random name of the specified type from BehindTheName.com. See country codes at: http://www.behindthename.com/api/appendix2.php Usage: randomname <country> [<gender>].
def command_randomname(bot, user, channel, args): """Generates a random name of the specified type from BehindTheName.com. See country codes at: http://www.behindthename.com/api/appendix2.php Usage: randomname <country> [<gender>].""" if args == "help": return bot.say(channel, "Usage: randomname <country> [<gender>].") countries = { "African": "afr", "Akan": "aka", "Albanian": "alb", "Algonquin": "alg", "Native American": "ame", "Amharic": "amh", "Ancient": "anci", "Apache": "apa", "Arabic": "ara", "Armenian": "arm", "Astronomy": "astr", "Indigenous Australian": "aus", "Aymara": "aym", "Azerbaijani": "aze", "Basque": "bas", "Bengali": "ben", "Berber": "ber", "Biblical": "bibl", "Bosnian": "bos", "Breton": "bre", "Bulgarian": "bul", "Catalan": "cat", "Ancient Celtic": "cela", "Celtic Mythology": "celm", "Chinese": "chi", "Choctaw": "cht", "Comanche": "com", "Coptic": "cop", "Cornish": "cor", "Cree": "cre", "Croatian": "cro", "Corsican": "crs", "Czech": "cze", "Danish": "dan", "Dutch": "dut", "English": "eng", "Esperanto": "esp", "Estonian": "est", "Ewe": "ewe", "Fairy": "fairy", "Filipino": "fil", "Finnish": "fin", "Flemish": "fle", "French": "fre", "Frisian": "fri", "Galician": "gal", "Ganda": "gan", "Georgian": "geo", "German": "ger", "Goth": "goth", "Greek": "gre", "Ancient Greek": "grea", "Greek Mythology": "grem", "Greenlandic": "grn", "Hawaiian": "haw", "Hillbilly": "hb", "Hippy": "hippy", "History": "hist", "Hungarian": "hun", "Ibibio": "ibi", "Icelandic": "ice", "Igbo": "igb", "Indian": "ind", "Indian Mythology": "indm", "Indonesian": "ins", "Inuit": "inu", "Iranian": "ira", "Irish": "iri", "Iroquois": "iro", "Italian": "ita", "Japanese": "jap", "Jewish": "jew", "Kazakh": "kaz", "Khmer": "khm", "Kikuyu": "kik", "Kreatyve": "kk", "Korean": "kor", "Kurdish": "kur", "Kyrgyz": "kyr", "Latvian": "lat", "Limburgish": "lim", "Literature": "lite", "Lithuanian": "lth", "Luhya": "luh", "Luo": "luo", "Macedonian": "mac", "Maltese": "mal", "Manx": "man", "Maori": "mao", "Mapuche": "map", "Mayan": "may", "Medieval": "medi", "Mongolian": "mon", "Mormon": "morm", "Mwera": "mwe", "Mythology": "myth", "Nahuatl": "nah", "Navajo": "nav", "Ndebele": "nde", "Norwegian": "nor", "Nuu-chah-nulth": "nuu", "Occitan": "occ", "Ojibwe": "oji", "Pacific/Polynesian": "pac", "Pakistani": "pak", "Pet": "pets", "Polish": "pol", "Popular Culture": "popu", "Portuguese": "por", "Punjabi": "pun", "Quechua": "que", "Rapper": "rap", "Romanian": "rmn", "Ancient Roman": "roma", "Roman Mythology": "romm", "Russian": "rus", "Sami": "sam", "Norse Mythology": "scam", "Scottish": "sco", "Serbian": "ser", "Shawnee": "sha", "Shona": "sho", "Sioux": "sio", "Norse Mythology": "slam", "Slovak": "slk", "Slovene": "sln", "Sotho": "sot", "Spanish": "spa", "Swahili": "swa", "Swedish": "swe", "Tagalog": "tag", "Tamil": "tam", "Telugu": "tel", "Ancient Germanic": "teua", "Thai": "tha", "Theology": "theo", "Tibetan": "tib", "Transformer": "trans", "Tswana": "tsw", "Tumbuka": "tum", "Turkish": "tur", "Ukrainian": "ukr", "?": "unkn", "Urdu": "urd", "American": "usa", "Various": "vari", "Vietnamese": "vie", "Welsh": "wel", "Witch": "witch", "Wrestler": "wrest", "Xhosa": "xho", "Yao": "yao", "Yoruba": "yor", "Zapotec": "zap", "Zulu": "zul", } args = args.split() if len(args) > 2: return bot.say(channel, "Usage: randomname <country> [<gender>].") elif len(args) == 2: gender = args[1] else: gender = "both" genders = ["m", "f", "both"] if gender not in genders: return bot.say(channel, "Valid genders are m, f or both.") if not args: country, gender = choice(countries.keys()).lower(), choice(genders) else: country = args[0].lower() match_found = False for long, short in countries.items(): long, short = long.lower(), short.lower() # We use very lose matching. if country in long or country in short: country_code = short country_text = long match_found = True break if not match_found: return bot.say(channel, "No match found for '{}'".format(country)) if gender == "m": gender_text = "a man" elif gender == "f": gender_text = "a woman" else: gender_text = "both genders" data = urllib.urlopen(api % (country_code, gender)) parsed = bs4(data, "xml") return bot.say(channel, "Random {} name for {}: {}" .format(country_text, gender_text, parsed.get_text().encode('utf8').strip()))
[ "def", "command_randomname", "(", "bot", ",", "user", ",", "channel", ",", "args", ")", ":", "if", "args", "==", "\"help\"", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Usage: randomname <country> [<gender>].\"", ")", "countries", "=", "{", "\"African\"", ":", "\"afr\"", ",", "\"Akan\"", ":", "\"aka\"", ",", "\"Albanian\"", ":", "\"alb\"", ",", "\"Algonquin\"", ":", "\"alg\"", ",", "\"Native American\"", ":", "\"ame\"", ",", "\"Amharic\"", ":", "\"amh\"", ",", "\"Ancient\"", ":", "\"anci\"", ",", "\"Apache\"", ":", "\"apa\"", ",", "\"Arabic\"", ":", "\"ara\"", ",", "\"Armenian\"", ":", "\"arm\"", ",", "\"Astronomy\"", ":", "\"astr\"", ",", "\"Indigenous Australian\"", ":", "\"aus\"", ",", "\"Aymara\"", ":", "\"aym\"", ",", "\"Azerbaijani\"", ":", "\"aze\"", ",", "\"Basque\"", ":", "\"bas\"", ",", "\"Bengali\"", ":", "\"ben\"", ",", "\"Berber\"", ":", "\"ber\"", ",", "\"Biblical\"", ":", "\"bibl\"", ",", "\"Bosnian\"", ":", "\"bos\"", ",", "\"Breton\"", ":", "\"bre\"", ",", "\"Bulgarian\"", ":", "\"bul\"", ",", "\"Catalan\"", ":", "\"cat\"", ",", "\"Ancient Celtic\"", ":", "\"cela\"", ",", "\"Celtic Mythology\"", ":", "\"celm\"", ",", "\"Chinese\"", ":", "\"chi\"", ",", "\"Choctaw\"", ":", "\"cht\"", ",", "\"Comanche\"", ":", "\"com\"", ",", "\"Coptic\"", ":", "\"cop\"", ",", "\"Cornish\"", ":", "\"cor\"", ",", "\"Cree\"", ":", "\"cre\"", ",", "\"Croatian\"", ":", "\"cro\"", ",", "\"Corsican\"", ":", "\"crs\"", ",", "\"Czech\"", ":", "\"cze\"", ",", "\"Danish\"", ":", "\"dan\"", ",", "\"Dutch\"", ":", "\"dut\"", ",", "\"English\"", ":", "\"eng\"", ",", "\"Esperanto\"", ":", "\"esp\"", ",", "\"Estonian\"", ":", "\"est\"", ",", "\"Ewe\"", ":", "\"ewe\"", ",", "\"Fairy\"", ":", "\"fairy\"", ",", "\"Filipino\"", ":", "\"fil\"", ",", "\"Finnish\"", ":", "\"fin\"", ",", "\"Flemish\"", ":", "\"fle\"", ",", "\"French\"", ":", "\"fre\"", ",", "\"Frisian\"", ":", "\"fri\"", ",", "\"Galician\"", ":", "\"gal\"", ",", "\"Ganda\"", ":", "\"gan\"", ",", "\"Georgian\"", ":", "\"geo\"", ",", "\"German\"", ":", "\"ger\"", ",", "\"Goth\"", ":", "\"goth\"", ",", "\"Greek\"", ":", "\"gre\"", ",", "\"Ancient Greek\"", ":", "\"grea\"", ",", "\"Greek Mythology\"", ":", "\"grem\"", ",", "\"Greenlandic\"", ":", "\"grn\"", ",", "\"Hawaiian\"", ":", "\"haw\"", ",", "\"Hillbilly\"", ":", "\"hb\"", ",", "\"Hippy\"", ":", "\"hippy\"", ",", "\"History\"", ":", "\"hist\"", ",", "\"Hungarian\"", ":", "\"hun\"", ",", "\"Ibibio\"", ":", "\"ibi\"", ",", "\"Icelandic\"", ":", "\"ice\"", ",", "\"Igbo\"", ":", "\"igb\"", ",", "\"Indian\"", ":", "\"ind\"", ",", "\"Indian Mythology\"", ":", "\"indm\"", ",", "\"Indonesian\"", ":", "\"ins\"", ",", "\"Inuit\"", ":", "\"inu\"", ",", "\"Iranian\"", ":", "\"ira\"", ",", "\"Irish\"", ":", "\"iri\"", ",", "\"Iroquois\"", ":", "\"iro\"", ",", "\"Italian\"", ":", "\"ita\"", ",", "\"Japanese\"", ":", "\"jap\"", ",", "\"Jewish\"", ":", "\"jew\"", ",", "\"Kazakh\"", ":", "\"kaz\"", ",", "\"Khmer\"", ":", "\"khm\"", ",", "\"Kikuyu\"", ":", "\"kik\"", ",", "\"Kreatyve\"", ":", "\"kk\"", ",", "\"Korean\"", ":", "\"kor\"", ",", "\"Kurdish\"", ":", "\"kur\"", ",", "\"Kyrgyz\"", ":", "\"kyr\"", ",", "\"Latvian\"", ":", "\"lat\"", ",", "\"Limburgish\"", ":", "\"lim\"", ",", "\"Literature\"", ":", "\"lite\"", ",", "\"Lithuanian\"", ":", "\"lth\"", ",", "\"Luhya\"", ":", "\"luh\"", ",", "\"Luo\"", ":", "\"luo\"", ",", "\"Macedonian\"", ":", "\"mac\"", ",", "\"Maltese\"", ":", "\"mal\"", ",", "\"Manx\"", ":", "\"man\"", ",", "\"Maori\"", ":", "\"mao\"", ",", "\"Mapuche\"", ":", "\"map\"", ",", "\"Mayan\"", ":", "\"may\"", ",", "\"Medieval\"", ":", "\"medi\"", ",", "\"Mongolian\"", ":", "\"mon\"", ",", "\"Mormon\"", ":", "\"morm\"", ",", "\"Mwera\"", ":", "\"mwe\"", ",", "\"Mythology\"", ":", "\"myth\"", ",", "\"Nahuatl\"", ":", "\"nah\"", ",", "\"Navajo\"", ":", "\"nav\"", ",", "\"Ndebele\"", ":", "\"nde\"", ",", "\"Norwegian\"", ":", "\"nor\"", ",", "\"Nuu-chah-nulth\"", ":", "\"nuu\"", ",", "\"Occitan\"", ":", "\"occ\"", ",", "\"Ojibwe\"", ":", "\"oji\"", ",", "\"Pacific/Polynesian\"", ":", "\"pac\"", ",", "\"Pakistani\"", ":", "\"pak\"", ",", "\"Pet\"", ":", "\"pets\"", ",", "\"Polish\"", ":", "\"pol\"", ",", "\"Popular Culture\"", ":", "\"popu\"", ",", "\"Portuguese\"", ":", "\"por\"", ",", "\"Punjabi\"", ":", "\"pun\"", ",", "\"Quechua\"", ":", "\"que\"", ",", "\"Rapper\"", ":", "\"rap\"", ",", "\"Romanian\"", ":", "\"rmn\"", ",", "\"Ancient Roman\"", ":", "\"roma\"", ",", "\"Roman Mythology\"", ":", "\"romm\"", ",", "\"Russian\"", ":", "\"rus\"", ",", "\"Sami\"", ":", "\"sam\"", ",", "\"Norse Mythology\"", ":", "\"scam\"", ",", "\"Scottish\"", ":", "\"sco\"", ",", "\"Serbian\"", ":", "\"ser\"", ",", "\"Shawnee\"", ":", "\"sha\"", ",", "\"Shona\"", ":", "\"sho\"", ",", "\"Sioux\"", ":", "\"sio\"", ",", "\"Norse Mythology\"", ":", "\"slam\"", ",", "\"Slovak\"", ":", "\"slk\"", ",", "\"Slovene\"", ":", "\"sln\"", ",", "\"Sotho\"", ":", "\"sot\"", ",", "\"Spanish\"", ":", "\"spa\"", ",", "\"Swahili\"", ":", "\"swa\"", ",", "\"Swedish\"", ":", "\"swe\"", ",", "\"Tagalog\"", ":", "\"tag\"", ",", "\"Tamil\"", ":", "\"tam\"", ",", "\"Telugu\"", ":", "\"tel\"", ",", "\"Ancient Germanic\"", ":", "\"teua\"", ",", "\"Thai\"", ":", "\"tha\"", ",", "\"Theology\"", ":", "\"theo\"", ",", "\"Tibetan\"", ":", "\"tib\"", ",", "\"Transformer\"", ":", "\"trans\"", ",", "\"Tswana\"", ":", "\"tsw\"", ",", "\"Tumbuka\"", ":", "\"tum\"", ",", "\"Turkish\"", ":", "\"tur\"", ",", "\"Ukrainian\"", ":", "\"ukr\"", ",", "\"?\"", ":", "\"unkn\"", ",", "\"Urdu\"", ":", "\"urd\"", ",", "\"American\"", ":", "\"usa\"", ",", "\"Various\"", ":", "\"vari\"", ",", "\"Vietnamese\"", ":", "\"vie\"", ",", "\"Welsh\"", ":", "\"wel\"", ",", "\"Witch\"", ":", "\"witch\"", ",", "\"Wrestler\"", ":", "\"wrest\"", ",", "\"Xhosa\"", ":", "\"xho\"", ",", "\"Yao\"", ":", "\"yao\"", ",", "\"Yoruba\"", ":", "\"yor\"", ",", "\"Zapotec\"", ":", "\"zap\"", ",", "\"Zulu\"", ":", "\"zul\"", ",", "}", "args", "=", "args", ".", "split", "(", ")", "if", "len", "(", "args", ")", ">", "2", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Usage: randomname <country> [<gender>].\"", ")", "elif", "len", "(", "args", ")", "==", "2", ":", "gender", "=", "args", "[", "1", "]", "else", ":", "gender", "=", "\"both\"", "genders", "=", "[", "\"m\"", ",", "\"f\"", ",", "\"both\"", "]", "if", "gender", "not", "in", "genders", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"Valid genders are m, f or both.\"", ")", "if", "not", "args", ":", "country", ",", "gender", "=", "choice", "(", "countries", ".", "keys", "(", ")", ")", ".", "lower", "(", ")", ",", "choice", "(", "genders", ")", "else", ":", "country", "=", "args", "[", "0", "]", ".", "lower", "(", ")", "match_found", "=", "False", "for", "long", ",", "short", "in", "countries", ".", "items", "(", ")", ":", "long", ",", "short", "=", "long", ".", "lower", "(", ")", ",", "short", ".", "lower", "(", ")", "# We use very lose matching.", "if", "country", "in", "long", "or", "country", "in", "short", ":", "country_code", "=", "short", "country_text", "=", "long", "match_found", "=", "True", "break", "if", "not", "match_found", ":", "return", "bot", ".", "say", "(", "channel", ",", "\"No match found for '{}'\"", ".", "format", "(", "country", ")", ")", "if", "gender", "==", "\"m\"", ":", "gender_text", "=", "\"a man\"", "elif", "gender", "==", "\"f\"", ":", "gender_text", "=", "\"a woman\"", "else", ":", "gender_text", "=", "\"both genders\"", "data", "=", "urllib", ".", "urlopen", "(", "api", "%", "(", "country_code", ",", "gender", ")", ")", "parsed", "=", "bs4", "(", "data", ",", "\"xml\"", ")", "return", "bot", ".", "say", "(", "channel", ",", "\"Random {} name for {}: {}\"", ".", "format", "(", "country_text", ",", "gender_text", ",", "parsed", ".", "get_text", "(", ")", ".", "encode", "(", "'utf8'", ")", ".", "strip", "(", ")", ")", ")" ]
[ 18, 0 ]
[ 226, 69 ]
python
en
['en', 'en', 'en']
True
merge_setting
(request_setting, session_setting, dict_class=OrderedDict)
Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class`
Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class`
def merge_setting(request_setting, session_setting, dict_class=OrderedDict): """Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class` """ if session_setting is None: return request_setting if request_setting is None: return session_setting # Bypass if not a dictionary (e.g. verify) if not ( isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping) ): return request_setting merged_setting = dict_class(to_key_val_list(session_setting)) merged_setting.update(to_key_val_list(request_setting)) # Remove keys that are set to None. Extract keys first to avoid altering # the dictionary during iteration. none_keys = [k for (k, v) in merged_setting.items() if v is None] for key in none_keys: del merged_setting[key] return merged_setting
[ "def", "merge_setting", "(", "request_setting", ",", "session_setting", ",", "dict_class", "=", "OrderedDict", ")", ":", "if", "session_setting", "is", "None", ":", "return", "request_setting", "if", "request_setting", "is", "None", ":", "return", "session_setting", "# Bypass if not a dictionary (e.g. verify)", "if", "not", "(", "isinstance", "(", "session_setting", ",", "Mapping", ")", "and", "isinstance", "(", "request_setting", ",", "Mapping", ")", ")", ":", "return", "request_setting", "merged_setting", "=", "dict_class", "(", "to_key_val_list", "(", "session_setting", ")", ")", "merged_setting", ".", "update", "(", "to_key_val_list", "(", "request_setting", ")", ")", "# Remove keys that are set to None. Extract keys first to avoid altering", "# the dictionary during iteration.", "none_keys", "=", "[", "k", "for", "(", "k", ",", "v", ")", "in", "merged_setting", ".", "items", "(", ")", "if", "v", "is", "None", "]", "for", "key", "in", "none_keys", ":", "del", "merged_setting", "[", "key", "]", "return", "merged_setting" ]
[ 49, 0 ]
[ 77, 25 ]
python
en
['en', 'en', 'en']
True
merge_hooks
(request_hooks, session_hooks, dict_class=OrderedDict)
Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely.
Properly merges both requests and session hooks.
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict): """Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. """ if session_hooks is None or session_hooks.get('response') == []: return request_hooks if request_hooks is None or request_hooks.get('response') == []: return session_hooks return merge_setting(request_hooks, session_hooks, dict_class)
[ "def", "merge_hooks", "(", "request_hooks", ",", "session_hooks", ",", "dict_class", "=", "OrderedDict", ")", ":", "if", "session_hooks", "is", "None", "or", "session_hooks", ".", "get", "(", "'response'", ")", "==", "[", "]", ":", "return", "request_hooks", "if", "request_hooks", "is", "None", "or", "request_hooks", ".", "get", "(", "'response'", ")", "==", "[", "]", ":", "return", "session_hooks", "return", "merge_setting", "(", "request_hooks", ",", "session_hooks", ",", "dict_class", ")" ]
[ 80, 0 ]
[ 92, 66 ]
python
en
['en', 'en', 'en']
True
session
()
Returns a :class:`Session` for context-management. .. deprecated:: 1.0.0 This method has been deprecated since version 1.0.0 and is only kept for backwards compatibility. New code should use :class:`~requests.sessions.Session` to create a session. This may be removed at a future date. :rtype: Session
Returns a :class:`Session` for context-management.
def session(): """ Returns a :class:`Session` for context-management. .. deprecated:: 1.0.0 This method has been deprecated since version 1.0.0 and is only kept for backwards compatibility. New code should use :class:`~requests.sessions.Session` to create a session. This may be removed at a future date. :rtype: Session """ return Session()
[ "def", "session", "(", ")", ":", "return", "Session", "(", ")" ]
[ 768, 0 ]
[ 780, 20 ]
python
en
['en', 'error', 'th']
False
SessionRedirectMixin.get_redirect_target
(self, resp)
Receives a Response. Returns a redirect URI or ``None``
Receives a Response. Returns a redirect URI or ``None``
def get_redirect_target(self, resp): """Receives a Response. Returns a redirect URI or ``None``""" # Due to the nature of how requests processes redirects this method will # be called at least once upon the original response and at least twice # on each subsequent redirect response (if any). # If a custom mixin is used to handle this logic, it may be advantageous # to cache the redirect location onto the response object as a private # attribute. if resp.is_redirect: location = resp.headers['location'] # Currently the underlying http module on py3 decode headers # in latin1, but empirical evidence suggests that latin1 is very # rarely used with non-ASCII characters in HTTP headers. # It is more likely to get UTF8 header rather than latin1. # This causes incorrect handling of UTF8 encoded location headers. # To solve this, we re-encode the location in latin1. if is_py3: location = location.encode('latin1') return to_native_string(location, 'utf8') return None
[ "def", "get_redirect_target", "(", "self", ",", "resp", ")", ":", "# Due to the nature of how requests processes redirects this method will", "# be called at least once upon the original response and at least twice", "# on each subsequent redirect response (if any).", "# If a custom mixin is used to handle this logic, it may be advantageous", "# to cache the redirect location onto the response object as a private", "# attribute.", "if", "resp", ".", "is_redirect", ":", "location", "=", "resp", ".", "headers", "[", "'location'", "]", "# Currently the underlying http module on py3 decode headers", "# in latin1, but empirical evidence suggests that latin1 is very", "# rarely used with non-ASCII characters in HTTP headers.", "# It is more likely to get UTF8 header rather than latin1.", "# This causes incorrect handling of UTF8 encoded location headers.", "# To solve this, we re-encode the location in latin1.", "if", "is_py3", ":", "location", "=", "location", ".", "encode", "(", "'latin1'", ")", "return", "to_native_string", "(", "location", ",", "'utf8'", ")", "return", "None" ]
[ 97, 4 ]
[ 116, 19 ]
python
en
['en', 'en', 'en']
True
SessionRedirectMixin.should_strip_auth
(self, old_url, new_url)
Decide whether Authorization header should be removed when redirecting
Decide whether Authorization header should be removed when redirecting
def should_strip_auth(self, old_url, new_url): """Decide whether Authorization header should be removed when redirecting""" old_parsed = urlparse(old_url) new_parsed = urlparse(new_url) if old_parsed.hostname != new_parsed.hostname: return True # Special case: allow http -> https redirect when using the standard # ports. This isn't specified by RFC 7235, but is kept to avoid # breaking backwards compatibility with older versions of requests # that allowed any redirects on the same host. if (old_parsed.scheme == 'http' and old_parsed.port in (80, None) and new_parsed.scheme == 'https' and new_parsed.port in (443, None)): return False # Handle default port usage corresponding to scheme. changed_port = old_parsed.port != new_parsed.port changed_scheme = old_parsed.scheme != new_parsed.scheme default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) if (not changed_scheme and old_parsed.port in default_port and new_parsed.port in default_port): return False # Standard case: root URI must match return changed_port or changed_scheme
[ "def", "should_strip_auth", "(", "self", ",", "old_url", ",", "new_url", ")", ":", "old_parsed", "=", "urlparse", "(", "old_url", ")", "new_parsed", "=", "urlparse", "(", "new_url", ")", "if", "old_parsed", ".", "hostname", "!=", "new_parsed", ".", "hostname", ":", "return", "True", "# Special case: allow http -> https redirect when using the standard", "# ports. This isn't specified by RFC 7235, but is kept to avoid", "# breaking backwards compatibility with older versions of requests", "# that allowed any redirects on the same host.", "if", "(", "old_parsed", ".", "scheme", "==", "'http'", "and", "old_parsed", ".", "port", "in", "(", "80", ",", "None", ")", "and", "new_parsed", ".", "scheme", "==", "'https'", "and", "new_parsed", ".", "port", "in", "(", "443", ",", "None", ")", ")", ":", "return", "False", "# Handle default port usage corresponding to scheme.", "changed_port", "=", "old_parsed", ".", "port", "!=", "new_parsed", ".", "port", "changed_scheme", "=", "old_parsed", ".", "scheme", "!=", "new_parsed", ".", "scheme", "default_port", "=", "(", "DEFAULT_PORTS", ".", "get", "(", "old_parsed", ".", "scheme", ",", "None", ")", ",", "None", ")", "if", "(", "not", "changed_scheme", "and", "old_parsed", ".", "port", "in", "default_port", "and", "new_parsed", ".", "port", "in", "default_port", ")", ":", "return", "False", "# Standard case: root URI must match", "return", "changed_port", "or", "changed_scheme" ]
[ 118, 4 ]
[ 141, 45 ]
python
en
['en', 'en', 'en']
True
SessionRedirectMixin.resolve_redirects
(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs)
Receives a Response. Returns a generator of Responses or Requests.
Receives a Response. Returns a generator of Responses or Requests.
def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs): """Receives a Response. Returns a generator of Responses or Requests.""" hist = [] # keep track of history url = self.get_redirect_target(resp) previous_fragment = urlparse(req.url).fragment while url: prepared_request = req.copy() # Update history and keep track of redirects. # resp.history must ignore the original request in this loop hist.append(resp) resp.history = hist[1:] try: resp.content # Consume socket so it can be released except (ChunkedEncodingError, ContentDecodingError, RuntimeError): resp.raw.read(decode_content=False) if len(resp.history) >= self.max_redirects: raise TooManyRedirects('Exceeded {} redirects.'.format(self.max_redirects), response=resp) # Release the connection back into the pool. resp.close() # Handle redirection without scheme (see: RFC 1808 Section 4) if url.startswith('//'): parsed_rurl = urlparse(resp.url) url = ':'.join([to_native_string(parsed_rurl.scheme), url]) # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2) parsed = urlparse(url) if parsed.fragment == '' and previous_fragment: parsed = parsed._replace(fragment=previous_fragment) elif parsed.fragment: previous_fragment = parsed.fragment url = parsed.geturl() # Facilitate relative 'location' headers, as allowed by RFC 7231. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') # Compliant with RFC3986, we percent encode the url. if not parsed.netloc: url = urljoin(resp.url, requote_uri(url)) else: url = requote_uri(url) prepared_request.url = to_native_string(url) self.rebuild_method(prepared_request, resp) # https://github.com/psf/requests/issues/1084 if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect): # https://github.com/psf/requests/issues/3490 purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding') for header in purged_headers: prepared_request.headers.pop(header, None) prepared_request.body = None headers = prepared_request.headers headers.pop('Cookie', None) # Extract any cookies sent on the response to the cookiejar # in the new request. Because we've mutated our copied prepared # request, use the old one that we haven't yet touched. extract_cookies_to_jar(prepared_request._cookies, req, resp.raw) merge_cookies(prepared_request._cookies, self.cookies) prepared_request.prepare_cookies(prepared_request._cookies) # Rebuild auth and proxy information. proxies = self.rebuild_proxies(prepared_request, proxies) self.rebuild_auth(prepared_request, resp) # A failed tell() sets `_body_position` to `object()`. This non-None # value ensures `rewindable` will be True, allowing us to raise an # UnrewindableBodyError, instead of hanging the connection. rewindable = ( prepared_request._body_position is not None and ('Content-Length' in headers or 'Transfer-Encoding' in headers) ) # Attempt to rewind consumed file-like object. if rewindable: rewind_body(prepared_request) # Override the original request. req = prepared_request if yield_requests: yield req else: resp = self.send( req, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, allow_redirects=False, **adapter_kwargs ) extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) # extract redirect url, if any, for the next loop url = self.get_redirect_target(resp) yield resp
[ "def", "resolve_redirects", "(", "self", ",", "resp", ",", "req", ",", "stream", "=", "False", ",", "timeout", "=", "None", ",", "verify", "=", "True", ",", "cert", "=", "None", ",", "proxies", "=", "None", ",", "yield_requests", "=", "False", ",", "*", "*", "adapter_kwargs", ")", ":", "hist", "=", "[", "]", "# keep track of history", "url", "=", "self", ".", "get_redirect_target", "(", "resp", ")", "previous_fragment", "=", "urlparse", "(", "req", ".", "url", ")", ".", "fragment", "while", "url", ":", "prepared_request", "=", "req", ".", "copy", "(", ")", "# Update history and keep track of redirects.", "# resp.history must ignore the original request in this loop", "hist", ".", "append", "(", "resp", ")", "resp", ".", "history", "=", "hist", "[", "1", ":", "]", "try", ":", "resp", ".", "content", "# Consume socket so it can be released", "except", "(", "ChunkedEncodingError", ",", "ContentDecodingError", ",", "RuntimeError", ")", ":", "resp", ".", "raw", ".", "read", "(", "decode_content", "=", "False", ")", "if", "len", "(", "resp", ".", "history", ")", ">=", "self", ".", "max_redirects", ":", "raise", "TooManyRedirects", "(", "'Exceeded {} redirects.'", ".", "format", "(", "self", ".", "max_redirects", ")", ",", "response", "=", "resp", ")", "# Release the connection back into the pool.", "resp", ".", "close", "(", ")", "# Handle redirection without scheme (see: RFC 1808 Section 4)", "if", "url", ".", "startswith", "(", "'//'", ")", ":", "parsed_rurl", "=", "urlparse", "(", "resp", ".", "url", ")", "url", "=", "':'", ".", "join", "(", "[", "to_native_string", "(", "parsed_rurl", ".", "scheme", ")", ",", "url", "]", ")", "# Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)", "parsed", "=", "urlparse", "(", "url", ")", "if", "parsed", ".", "fragment", "==", "''", "and", "previous_fragment", ":", "parsed", "=", "parsed", ".", "_replace", "(", "fragment", "=", "previous_fragment", ")", "elif", "parsed", ".", "fragment", ":", "previous_fragment", "=", "parsed", ".", "fragment", "url", "=", "parsed", ".", "geturl", "(", ")", "# Facilitate relative 'location' headers, as allowed by RFC 7231.", "# (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')", "# Compliant with RFC3986, we percent encode the url.", "if", "not", "parsed", ".", "netloc", ":", "url", "=", "urljoin", "(", "resp", ".", "url", ",", "requote_uri", "(", "url", ")", ")", "else", ":", "url", "=", "requote_uri", "(", "url", ")", "prepared_request", ".", "url", "=", "to_native_string", "(", "url", ")", "self", ".", "rebuild_method", "(", "prepared_request", ",", "resp", ")", "# https://github.com/psf/requests/issues/1084", "if", "resp", ".", "status_code", "not", "in", "(", "codes", ".", "temporary_redirect", ",", "codes", ".", "permanent_redirect", ")", ":", "# https://github.com/psf/requests/issues/3490", "purged_headers", "=", "(", "'Content-Length'", ",", "'Content-Type'", ",", "'Transfer-Encoding'", ")", "for", "header", "in", "purged_headers", ":", "prepared_request", ".", "headers", ".", "pop", "(", "header", ",", "None", ")", "prepared_request", ".", "body", "=", "None", "headers", "=", "prepared_request", ".", "headers", "headers", ".", "pop", "(", "'Cookie'", ",", "None", ")", "# Extract any cookies sent on the response to the cookiejar", "# in the new request. Because we've mutated our copied prepared", "# request, use the old one that we haven't yet touched.", "extract_cookies_to_jar", "(", "prepared_request", ".", "_cookies", ",", "req", ",", "resp", ".", "raw", ")", "merge_cookies", "(", "prepared_request", ".", "_cookies", ",", "self", ".", "cookies", ")", "prepared_request", ".", "prepare_cookies", "(", "prepared_request", ".", "_cookies", ")", "# Rebuild auth and proxy information.", "proxies", "=", "self", ".", "rebuild_proxies", "(", "prepared_request", ",", "proxies", ")", "self", ".", "rebuild_auth", "(", "prepared_request", ",", "resp", ")", "# A failed tell() sets `_body_position` to `object()`. This non-None", "# value ensures `rewindable` will be True, allowing us to raise an", "# UnrewindableBodyError, instead of hanging the connection.", "rewindable", "=", "(", "prepared_request", ".", "_body_position", "is", "not", "None", "and", "(", "'Content-Length'", "in", "headers", "or", "'Transfer-Encoding'", "in", "headers", ")", ")", "# Attempt to rewind consumed file-like object.", "if", "rewindable", ":", "rewind_body", "(", "prepared_request", ")", "# Override the original request.", "req", "=", "prepared_request", "if", "yield_requests", ":", "yield", "req", "else", ":", "resp", "=", "self", ".", "send", "(", "req", ",", "stream", "=", "stream", ",", "timeout", "=", "timeout", ",", "verify", "=", "verify", ",", "cert", "=", "cert", ",", "proxies", "=", "proxies", ",", "allow_redirects", "=", "False", ",", "*", "*", "adapter_kwargs", ")", "extract_cookies_to_jar", "(", "self", ".", "cookies", ",", "prepared_request", ",", "resp", ".", "raw", ")", "# extract redirect url, if any, for the next loop", "url", "=", "self", ".", "get_redirect_target", "(", "resp", ")", "yield", "resp" ]
[ 143, 4 ]
[ 251, 26 ]
python
en
['en', 'en', 'en']
True
SessionRedirectMixin.rebuild_auth
(self, prepared_request, response)
When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.
When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.
def rebuild_auth(self, prepared_request, response): """When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. """ headers = prepared_request.headers url = prepared_request.url if 'Authorization' in headers and self.should_strip_auth(response.request.url, url): # If we get redirected to a new host, we should strip out any # authentication headers. del headers['Authorization'] # .netrc might have more auth for us on our new host. new_auth = get_netrc_auth(url) if self.trust_env else None if new_auth is not None: prepared_request.prepare_auth(new_auth)
[ "def", "rebuild_auth", "(", "self", ",", "prepared_request", ",", "response", ")", ":", "headers", "=", "prepared_request", ".", "headers", "url", "=", "prepared_request", ".", "url", "if", "'Authorization'", "in", "headers", "and", "self", ".", "should_strip_auth", "(", "response", ".", "request", ".", "url", ",", "url", ")", ":", "# If we get redirected to a new host, we should strip out any", "# authentication headers.", "del", "headers", "[", "'Authorization'", "]", "# .netrc might have more auth for us on our new host.", "new_auth", "=", "get_netrc_auth", "(", "url", ")", "if", "self", ".", "trust_env", "else", "None", "if", "new_auth", "is", "not", "None", ":", "prepared_request", ".", "prepare_auth", "(", "new_auth", ")" ]
[ 253, 4 ]
[ 269, 51 ]
python
en
['en', 'en', 'en']
True
SessionRedirectMixin.rebuild_proxies
(self, prepared_request, proxies)
This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict
This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect).
def rebuild_proxies(self, prepared_request, proxies): """This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict """ proxies = proxies if proxies is not None else {} headers = prepared_request.headers url = prepared_request.url scheme = urlparse(url).scheme new_proxies = proxies.copy() no_proxy = proxies.get('no_proxy') bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy) if self.trust_env and not bypass_proxy: environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) proxy = environ_proxies.get(scheme, environ_proxies.get('all')) if proxy: new_proxies.setdefault(scheme, proxy) if 'Proxy-Authorization' in headers: del headers['Proxy-Authorization'] try: username, password = get_auth_from_url(new_proxies[scheme]) except KeyError: username, password = None, None if username and password: headers['Proxy-Authorization'] = _basic_auth_str(username, password) return new_proxies
[ "def", "rebuild_proxies", "(", "self", ",", "prepared_request", ",", "proxies", ")", ":", "proxies", "=", "proxies", "if", "proxies", "is", "not", "None", "else", "{", "}", "headers", "=", "prepared_request", ".", "headers", "url", "=", "prepared_request", ".", "url", "scheme", "=", "urlparse", "(", "url", ")", ".", "scheme", "new_proxies", "=", "proxies", ".", "copy", "(", ")", "no_proxy", "=", "proxies", ".", "get", "(", "'no_proxy'", ")", "bypass_proxy", "=", "should_bypass_proxies", "(", "url", ",", "no_proxy", "=", "no_proxy", ")", "if", "self", ".", "trust_env", "and", "not", "bypass_proxy", ":", "environ_proxies", "=", "get_environ_proxies", "(", "url", ",", "no_proxy", "=", "no_proxy", ")", "proxy", "=", "environ_proxies", ".", "get", "(", "scheme", ",", "environ_proxies", ".", "get", "(", "'all'", ")", ")", "if", "proxy", ":", "new_proxies", ".", "setdefault", "(", "scheme", ",", "proxy", ")", "if", "'Proxy-Authorization'", "in", "headers", ":", "del", "headers", "[", "'Proxy-Authorization'", "]", "try", ":", "username", ",", "password", "=", "get_auth_from_url", "(", "new_proxies", "[", "scheme", "]", ")", "except", "KeyError", ":", "username", ",", "password", "=", "None", ",", "None", "if", "username", "and", "password", ":", "headers", "[", "'Proxy-Authorization'", "]", "=", "_basic_auth_str", "(", "username", ",", "password", ")", "return", "new_proxies" ]
[ 272, 4 ]
[ 311, 26 ]
python
en
['en', 'en', 'en']
True
SessionRedirectMixin.rebuild_method
(self, prepared_request, response)
When being redirected we may want to change the method of the request based on certain specs or browser behavior.
When being redirected we may want to change the method of the request based on certain specs or browser behavior.
def rebuild_method(self, prepared_request, response): """When being redirected we may want to change the method of the request based on certain specs or browser behavior. """ method = prepared_request.method # https://tools.ietf.org/html/rfc7231#section-6.4.4 if response.status_code == codes.see_other and method != 'HEAD': method = 'GET' # Do what the browsers do, despite standards... # First, turn 302s into GETs. if response.status_code == codes.found and method != 'HEAD': method = 'GET' # Second, if a POST is responded to with a 301, turn it into a GET. # This bizarre behaviour is explained in Issue 1704. if response.status_code == codes.moved and method == 'POST': method = 'GET' prepared_request.method = method
[ "def", "rebuild_method", "(", "self", ",", "prepared_request", ",", "response", ")", ":", "method", "=", "prepared_request", ".", "method", "# https://tools.ietf.org/html/rfc7231#section-6.4.4", "if", "response", ".", "status_code", "==", "codes", ".", "see_other", "and", "method", "!=", "'HEAD'", ":", "method", "=", "'GET'", "# Do what the browsers do, despite standards...", "# First, turn 302s into GETs.", "if", "response", ".", "status_code", "==", "codes", ".", "found", "and", "method", "!=", "'HEAD'", ":", "method", "=", "'GET'", "# Second, if a POST is responded to with a 301, turn it into a GET.", "# This bizarre behaviour is explained in Issue 1704.", "if", "response", ".", "status_code", "==", "codes", ".", "moved", "and", "method", "==", "'POST'", ":", "method", "=", "'GET'", "prepared_request", ".", "method", "=", "method" ]
[ 313, 4 ]
[ 333, 40 ]
python
en
['en', 'en', 'en']
True
Session.prepare_request
(self, request)
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest
Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`.
def prepare_request(self, request): """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest """ cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(request.url) p = PreparedRequest() p.prepare( method=request.method.upper(), url=request.url, files=request.files, data=request.data, json=request.json, headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p
[ "def", "prepare_request", "(", "self", ",", "request", ")", ":", "cookies", "=", "request", ".", "cookies", "or", "{", "}", "# Bootstrap CookieJar.", "if", "not", "isinstance", "(", "cookies", ",", "cookielib", ".", "CookieJar", ")", ":", "cookies", "=", "cookiejar_from_dict", "(", "cookies", ")", "# Merge with session cookies", "merged_cookies", "=", "merge_cookies", "(", "merge_cookies", "(", "RequestsCookieJar", "(", ")", ",", "self", ".", "cookies", ")", ",", "cookies", ")", "# Set environment's basic authentication if not explicitly set.", "auth", "=", "request", ".", "auth", "if", "self", ".", "trust_env", "and", "not", "auth", "and", "not", "self", ".", "auth", ":", "auth", "=", "get_netrc_auth", "(", "request", ".", "url", ")", "p", "=", "PreparedRequest", "(", ")", "p", ".", "prepare", "(", "method", "=", "request", ".", "method", ".", "upper", "(", ")", ",", "url", "=", "request", ".", "url", ",", "files", "=", "request", ".", "files", ",", "data", "=", "request", ".", "data", ",", "json", "=", "request", ".", "json", ",", "headers", "=", "merge_setting", "(", "request", ".", "headers", ",", "self", ".", "headers", ",", "dict_class", "=", "CaseInsensitiveDict", ")", ",", "params", "=", "merge_setting", "(", "request", ".", "params", ",", "self", ".", "params", ")", ",", "auth", "=", "merge_setting", "(", "auth", ",", "self", ".", "auth", ")", ",", "cookies", "=", "merged_cookies", ",", "hooks", "=", "merge_hooks", "(", "request", ".", "hooks", ",", "self", ".", "hooks", ")", ",", ")", "return", "p" ]
[ 429, 4 ]
[ 467, 16 ]
python
en
['en', 'co', 'en']
True
Session.request
(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None)
Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. When set to ``False``, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to ``False`` may be useful during local development or testing. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response
Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object.
def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None): """Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. When set to ``False``, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to ``False`` may be useful during local development or testing. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response """ # Create the Request. req = Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = self.prepare_request(req) proxies = proxies or {} settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) # Send the request. send_kwargs = { 'timeout': timeout, 'allow_redirects': allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "params", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "cookies", "=", "None", ",", "files", "=", "None", ",", "auth", "=", "None", ",", "timeout", "=", "None", ",", "allow_redirects", "=", "True", ",", "proxies", "=", "None", ",", "hooks", "=", "None", ",", "stream", "=", "None", ",", "verify", "=", "None", ",", "cert", "=", "None", ",", "json", "=", "None", ")", ":", "# Create the Request.", "req", "=", "Request", "(", "method", "=", "method", ".", "upper", "(", ")", ",", "url", "=", "url", ",", "headers", "=", "headers", ",", "files", "=", "files", ",", "data", "=", "data", "or", "{", "}", ",", "json", "=", "json", ",", "params", "=", "params", "or", "{", "}", ",", "auth", "=", "auth", ",", "cookies", "=", "cookies", ",", "hooks", "=", "hooks", ",", ")", "prep", "=", "self", ".", "prepare_request", "(", "req", ")", "proxies", "=", "proxies", "or", "{", "}", "settings", "=", "self", ".", "merge_environment_settings", "(", "prep", ".", "url", ",", "proxies", ",", "stream", ",", "verify", ",", "cert", ")", "# Send the request.", "send_kwargs", "=", "{", "'timeout'", ":", "timeout", ",", "'allow_redirects'", ":", "allow_redirects", ",", "}", "send_kwargs", ".", "update", "(", "settings", ")", "resp", "=", "self", ".", "send", "(", "prep", ",", "*", "*", "send_kwargs", ")", "return", "resp" ]
[ 469, 4 ]
[ 543, 19 ]
python
en
['en', 'en', 'en']
True
Session.get
(self, url, **kwargs)
r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a GET request. Returns :class:`Response` object.
def get(self, url, **kwargs): r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('GET', url, **kwargs)
[ "def", "get", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "self", ".", "request", "(", "'GET'", ",", "url", ",", "*", "*", "kwargs", ")" ]
[ 545, 4 ]
[ 554, 49 ]
python
en
['en', 'lb', 'en']
True
Session.options
(self, url, **kwargs)
r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a OPTIONS request. Returns :class:`Response` object.
def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', True) return self.request('OPTIONS', url, **kwargs)
[ "def", "options", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "True", ")", "return", "self", ".", "request", "(", "'OPTIONS'", ",", "url", ",", "*", "*", "kwargs", ")" ]
[ 556, 4 ]
[ 565, 53 ]
python
en
['en', 'en', 'en']
True
Session.head
(self, url, **kwargs)
r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a HEAD request. Returns :class:`Response` object.
def head(self, url, **kwargs): r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_redirects', False) return self.request('HEAD', url, **kwargs)
[ "def", "head", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'allow_redirects'", ",", "False", ")", "return", "self", ".", "request", "(", "'HEAD'", ",", "url", ",", "*", "*", "kwargs", ")" ]
[ 567, 4 ]
[ 576, 50 ]
python
en
['en', 'lb', 'en']
True
Session.post
(self, url, data=None, json=None, **kwargs)
r"""Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a POST request. Returns :class:`Response` object.
def post(self, url, data=None, json=None, **kwargs): r"""Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('POST', url, data=data, json=json, **kwargs)
[ "def", "post", "(", "self", ",", "url", ",", "data", "=", "None", ",", "json", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "request", "(", "'POST'", ",", "url", ",", "data", "=", "data", ",", "json", "=", "json", ",", "*", "*", "kwargs", ")" ]
[ 578, 4 ]
[ 589, 72 ]
python
en
['en', 'lb', 'en']
True
Session.put
(self, url, data=None, **kwargs)
r"""Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a PUT request. Returns :class:`Response` object.
def put(self, url, data=None, **kwargs): r"""Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('PUT', url, data=data, **kwargs)
[ "def", "put", "(", "self", ",", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "request", "(", "'PUT'", ",", "url", ",", "data", "=", "data", ",", "*", "*", "kwargs", ")" ]
[ 591, 4 ]
[ 601, 60 ]
python
en
['en', 'lb', 'en']
True
Session.patch
(self, url, data=None, **kwargs)
r"""Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a PATCH request. Returns :class:`Response` object.
def patch(self, url, data=None, **kwargs): r"""Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('PATCH', url, data=data, **kwargs)
[ "def", "patch", "(", "self", ",", "url", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "request", "(", "'PATCH'", ",", "url", ",", "data", "=", "data", ",", "*", "*", "kwargs", ")" ]
[ 603, 4 ]
[ 613, 62 ]
python
en
['en', 'en', 'en']
True
Session.delete
(self, url, **kwargs)
r"""Sends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
r"""Sends a DELETE request. Returns :class:`Response` object.
def delete(self, url, **kwargs): r"""Sends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ return self.request('DELETE', url, **kwargs)
[ "def", "delete", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "request", "(", "'DELETE'", ",", "url", ",", "*", "*", "kwargs", ")" ]
[ 615, 4 ]
[ 623, 52 ]
python
en
['en', 'en', 'en']
True
Session.send
(self, request, **kwargs)
Send a given PreparedRequest. :rtype: requests.Response
Send a given PreparedRequest.
def send(self, request, **kwargs): """Send a given PreparedRequest. :rtype: requests.Response """ # Set defaults that the hooks can utilize to ensure they always have # the correct parameters to reproduce the previous request. kwargs.setdefault('stream', self.stream) kwargs.setdefault('verify', self.verify) kwargs.setdefault('cert', self.cert) kwargs.setdefault('proxies', self.rebuild_proxies(request, self.proxies)) # It's possible that users might accidentally send a Request object. # Guard against that specific failure case. if isinstance(request, Request): raise ValueError('You can only send PreparedRequests.') # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop('allow_redirects', True) stream = kwargs.get('stream') hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) # Start time (approximately) of the request start = preferred_clock() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) elapsed = preferred_clock() - start r.elapsed = timedelta(seconds=elapsed) # Response manipulation hooks r = dispatch_hook('response', hooks, r, **kwargs) # Persist cookies if r.history: # If the hooks create history then we want those cookies too for resp in r.history: extract_cookies_to_jar(self.cookies, resp.request, resp.raw) extract_cookies_to_jar(self.cookies, request, r.raw) # Resolve redirects if allowed. if allow_redirects: # Redirect resolving generator. gen = self.resolve_redirects(r, request, **kwargs) history = [resp for resp in gen] else: history = [] # Shuffle things around if there's history. if history: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made r = history.pop() r.history = history # If redirects aren't being followed, store the response on the Request for Response.next(). if not allow_redirects: try: r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs)) except StopIteration: pass if not stream: r.content return r
[ "def", "send", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "# Set defaults that the hooks can utilize to ensure they always have", "# the correct parameters to reproduce the previous request.", "kwargs", ".", "setdefault", "(", "'stream'", ",", "self", ".", "stream", ")", "kwargs", ".", "setdefault", "(", "'verify'", ",", "self", ".", "verify", ")", "kwargs", ".", "setdefault", "(", "'cert'", ",", "self", ".", "cert", ")", "kwargs", ".", "setdefault", "(", "'proxies'", ",", "self", ".", "rebuild_proxies", "(", "request", ",", "self", ".", "proxies", ")", ")", "# It's possible that users might accidentally send a Request object.", "# Guard against that specific failure case.", "if", "isinstance", "(", "request", ",", "Request", ")", ":", "raise", "ValueError", "(", "'You can only send PreparedRequests.'", ")", "# Set up variables needed for resolve_redirects and dispatching of hooks", "allow_redirects", "=", "kwargs", ".", "pop", "(", "'allow_redirects'", ",", "True", ")", "stream", "=", "kwargs", ".", "get", "(", "'stream'", ")", "hooks", "=", "request", ".", "hooks", "# Get the appropriate adapter to use", "adapter", "=", "self", ".", "get_adapter", "(", "url", "=", "request", ".", "url", ")", "# Start time (approximately) of the request", "start", "=", "preferred_clock", "(", ")", "# Send the request", "r", "=", "adapter", ".", "send", "(", "request", ",", "*", "*", "kwargs", ")", "# Total elapsed time of the request (approximately)", "elapsed", "=", "preferred_clock", "(", ")", "-", "start", "r", ".", "elapsed", "=", "timedelta", "(", "seconds", "=", "elapsed", ")", "# Response manipulation hooks", "r", "=", "dispatch_hook", "(", "'response'", ",", "hooks", ",", "r", ",", "*", "*", "kwargs", ")", "# Persist cookies", "if", "r", ".", "history", ":", "# If the hooks create history then we want those cookies too", "for", "resp", "in", "r", ".", "history", ":", "extract_cookies_to_jar", "(", "self", ".", "cookies", ",", "resp", ".", "request", ",", "resp", ".", "raw", ")", "extract_cookies_to_jar", "(", "self", ".", "cookies", ",", "request", ",", "r", ".", "raw", ")", "# Resolve redirects if allowed.", "if", "allow_redirects", ":", "# Redirect resolving generator.", "gen", "=", "self", ".", "resolve_redirects", "(", "r", ",", "request", ",", "*", "*", "kwargs", ")", "history", "=", "[", "resp", "for", "resp", "in", "gen", "]", "else", ":", "history", "=", "[", "]", "# Shuffle things around if there's history.", "if", "history", ":", "# Insert the first (original) request at the start", "history", ".", "insert", "(", "0", ",", "r", ")", "# Get the last request made", "r", "=", "history", ".", "pop", "(", ")", "r", ".", "history", "=", "history", "# If redirects aren't being followed, store the response on the Request for Response.next().", "if", "not", "allow_redirects", ":", "try", ":", "r", ".", "_next", "=", "next", "(", "self", ".", "resolve_redirects", "(", "r", ",", "request", ",", "yield_requests", "=", "True", ",", "*", "*", "kwargs", ")", ")", "except", "StopIteration", ":", "pass", "if", "not", "stream", ":", "r", ".", "content", "return", "r" ]
[ 625, 4 ]
[ 698, 16 ]
python
en
['en', 'co', 'en']
True
Session.merge_environment_settings
(self, url, proxies, stream, verify, cert)
Check the environment and merge it with some settings. :rtype: dict
Check the environment and merge it with some settings.
def merge_environment_settings(self, url, proxies, stream, verify, cert): """ Check the environment and merge it with some settings. :rtype: dict """ # Gather clues from the surrounding environment. if self.trust_env: # Set environment's proxies. no_proxy = proxies.get('no_proxy') if proxies is not None else None env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) # Look for requests environment configuration and be compatible # with cURL. if verify is True or verify is None: verify = (os.environ.get('REQUESTS_CA_BUNDLE') or os.environ.get('CURL_CA_BUNDLE')) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {'verify': verify, 'proxies': proxies, 'stream': stream, 'cert': cert}
[ "def", "merge_environment_settings", "(", "self", ",", "url", ",", "proxies", ",", "stream", ",", "verify", ",", "cert", ")", ":", "# Gather clues from the surrounding environment.", "if", "self", ".", "trust_env", ":", "# Set environment's proxies.", "no_proxy", "=", "proxies", ".", "get", "(", "'no_proxy'", ")", "if", "proxies", "is", "not", "None", "else", "None", "env_proxies", "=", "get_environ_proxies", "(", "url", ",", "no_proxy", "=", "no_proxy", ")", "for", "(", "k", ",", "v", ")", "in", "env_proxies", ".", "items", "(", ")", ":", "proxies", ".", "setdefault", "(", "k", ",", "v", ")", "# Look for requests environment configuration and be compatible", "# with cURL.", "if", "verify", "is", "True", "or", "verify", "is", "None", ":", "verify", "=", "(", "os", ".", "environ", ".", "get", "(", "'REQUESTS_CA_BUNDLE'", ")", "or", "os", ".", "environ", ".", "get", "(", "'CURL_CA_BUNDLE'", ")", ")", "# Merge all the kwargs.", "proxies", "=", "merge_setting", "(", "proxies", ",", "self", ".", "proxies", ")", "stream", "=", "merge_setting", "(", "stream", ",", "self", ".", "stream", ")", "verify", "=", "merge_setting", "(", "verify", ",", "self", ".", "verify", ")", "cert", "=", "merge_setting", "(", "cert", ",", "self", ".", "cert", ")", "return", "{", "'verify'", ":", "verify", ",", "'proxies'", ":", "proxies", ",", "'stream'", ":", "stream", ",", "'cert'", ":", "cert", "}" ]
[ 700, 4 ]
[ 727, 29 ]
python
en
['en', 'error', 'th']
False
Session.get_adapter
(self, url)
Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter
Returns the appropriate connection adapter for the given URL.
def get_adapter(self, url): """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema("No connection adapters were found for {!r}".format(url))
[ "def", "get_adapter", "(", "self", ",", "url", ")", ":", "for", "(", "prefix", ",", "adapter", ")", "in", "self", ".", "adapters", ".", "items", "(", ")", ":", "if", "url", ".", "lower", "(", ")", ".", "startswith", "(", "prefix", ".", "lower", "(", ")", ")", ":", "return", "adapter", "# Nothing matches :-/", "raise", "InvalidSchema", "(", "\"No connection adapters were found for {!r}\"", ".", "format", "(", "url", ")", ")" ]
[ 729, 4 ]
[ 741, 85 ]
python
en
['en', 'error', 'th']
False
Session.close
(self)
Closes all adapters and as such the session
Closes all adapters and as such the session
def close(self): """Closes all adapters and as such the session""" for v in self.adapters.values(): v.close()
[ "def", "close", "(", "self", ")", ":", "for", "v", "in", "self", ".", "adapters", ".", "values", "(", ")", ":", "v", ".", "close", "(", ")" ]
[ 743, 4 ]
[ 746, 21 ]
python
en
['en', 'en', 'en']
True
Session.mount
(self, prefix, adapter)
Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length.
Registers a connection adapter to a prefix.
def mount(self, prefix, adapter): """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key)
[ "def", "mount", "(", "self", ",", "prefix", ",", "adapter", ")", ":", "self", ".", "adapters", "[", "prefix", "]", "=", "adapter", "keys_to_move", "=", "[", "k", "for", "k", "in", "self", ".", "adapters", "if", "len", "(", "k", ")", "<", "len", "(", "prefix", ")", "]", "for", "key", "in", "keys_to_move", ":", "self", ".", "adapters", "[", "key", "]", "=", "self", ".", "adapters", ".", "pop", "(", "key", ")" ]
[ 748, 4 ]
[ 757, 55 ]
python
en
['en', 'en', 'en']
True
_calculate_average_value
(values: List[str])
Calculates the average value of a `|` delimited list of values.
Calculates the average value of a `|` delimited list of values.
def _calculate_average_value(values: List[str]) -> float: """ Calculates the average value of a `|` delimited list of values.""" values = [i for i in values if i] try: average = sum(float(i) for i in values) / len(values) except ZeroDivisionError: average = 0 return average
[ "def", "_calculate_average_value", "(", "values", ":", "List", "[", "str", "]", ")", "->", "float", ":", "values", "=", "[", "i", "for", "i", "in", "values", "if", "i", "]", "try", ":", "average", "=", "sum", "(", "float", "(", "i", ")", "for", "i", "in", "values", ")", "/", "len", "(", "values", ")", "except", "ZeroDivisionError", ":", "average", "=", "0", "return", "average" ]
[ 7, 0 ]
[ 14, 15 ]
python
en
['en', 'en', 'en']
True
_extract_string_from_group
(group: pandas.DataFrame, column: str)
Essentially concatenates the annotations for each of the samples in the group. This will typically be the same for all variants, but is assumed otherwise just in case. Parameters ---------- group: pandas.DataFrame Returns -------
Essentially concatenates the annotations for each of the samples in the group. This will typically be the same for all variants, but is assumed otherwise just in case. Parameters ---------- group: pandas.DataFrame
def _extract_string_from_group(group: pandas.DataFrame, column: str) -> str: """ Essentially concatenates the annotations for each of the samples in the group. This will typically be the same for all variants, but is assumed otherwise just in case. Parameters ---------- group: pandas.DataFrame Returns ------- """ annotation_values = group[column].tolist() # Remove duplicate and missing annotations. DataFrames save missing values as math.nan annotation_set = {i for i in annotation_values if isinstance(i, str)} # Combine and merge into a string annotation_string = "|".join(annotation_set) return annotation_string
[ "def", "_extract_string_from_group", "(", "group", ":", "pandas", ".", "DataFrame", ",", "column", ":", "str", ")", "->", "str", ":", "annotation_values", "=", "group", "[", "column", "]", ".", "tolist", "(", ")", "# Remove duplicate and missing annotations. DataFrames save missing values as math.nan", "annotation_set", "=", "{", "i", "for", "i", "in", "annotation_values", "if", "isinstance", "(", "i", ",", "str", ")", "}", "# Combine and merge into a string", "annotation_string", "=", "\"|\"", ".", "join", "(", "annotation_set", ")", "return", "annotation_string" ]
[ 17, 0 ]
[ 34, 25 ]
python
en
['en', 'error', 'th']
False
apply_cds_annotations
(df:pandas.DataFrame)
Genomes downloaded from the ncbi website include a translated_cds file, which can be used to annotated a denovo assembly. The resulting annotations (saved in the 'description' field) include a lot of useful metadata in the form of [`key`=`value`].
Genomes downloaded from the ncbi website include a translated_cds file, which can be used to annotated a denovo assembly. The resulting annotations (saved in the 'description' field) include a lot of useful metadata in the form of [`key`=`value`].
def apply_cds_annotations(df:pandas.DataFrame)->pandas.DataFrame: """ Genomes downloaded from the ncbi website include a translated_cds file, which can be used to annotated a denovo assembly. The resulting annotations (saved in the 'description' field) include a lot of useful metadata in the form of [`key`=`value`]. """ import re def _apply(pattern:str, sequence:Iterable)->List[str]: result = list() for element in sequence: match = re.search(pattern, element) if match: result.append(match.group(1)) else: result.append(element) return result locus_tag_pattern = "locus_tag=([^\]]+)" gene_pattern = "protein=(.+?)\]" new_locus_tags = _apply(locus_tag_pattern, df['description'].tolist()) new_genes = _apply(gene_pattern, df['description'].tolist()) df['geneOld'] = df['gene'].values df['locusTagOld'] = df['locusTag'].values df['locusTag'] = new_locus_tags df['gene'] = new_genes return df
[ "def", "apply_cds_annotations", "(", "df", ":", "pandas", ".", "DataFrame", ")", "->", "pandas", ".", "DataFrame", ":", "import", "re", "def", "_apply", "(", "pattern", ":", "str", ",", "sequence", ":", "Iterable", ")", "->", "List", "[", "str", "]", ":", "result", "=", "list", "(", ")", "for", "element", "in", "sequence", ":", "match", "=", "re", ".", "search", "(", "pattern", ",", "element", ")", "if", "match", ":", "result", ".", "append", "(", "match", ".", "group", "(", "1", ")", ")", "else", ":", "result", ".", "append", "(", "element", ")", "return", "result", "locus_tag_pattern", "=", "\"locus_tag=([^\\]]+)\"", "gene_pattern", "=", "\"protein=(.+?)\\]\"", "new_locus_tags", "=", "_apply", "(", "locus_tag_pattern", ",", "df", "[", "'description'", "]", ".", "tolist", "(", ")", ")", "new_genes", "=", "_apply", "(", "gene_pattern", ",", "df", "[", "'description'", "]", ".", "tolist", "(", ")", ")", "df", "[", "'geneOld'", "]", "=", "df", "[", "'gene'", "]", ".", "values", "df", "[", "'locusTagOld'", "]", "=", "df", "[", "'locusTag'", "]", ".", "values", "df", "[", "'locusTag'", "]", "=", "new_locus_tags", "df", "[", "'gene'", "]", "=", "new_genes", "return", "df" ]
[ 111, 0 ]
[ 141, 10 ]
python
en
['en', 'en', 'en']
True
check_if_population
(table:pandas.DataFrame)
Checks whether the 'frequency' column is non-NaN, indicating that this was a population.
Checks whether the 'frequency' column is non-NaN, indicating that this was a population.
def check_if_population(table:pandas.DataFrame)->bool: """ Checks whether the 'frequency' column is non-NaN, indicating that this was a population.""" freq = table['frequency'] # If the `frequency` column is entirely NaN, then there will only be one unique value. unique = freq.unique() return len(unique) != 1
[ "def", "check_if_population", "(", "table", ":", "pandas", ".", "DataFrame", ")", "->", "bool", ":", "freq", "=", "table", "[", "'frequency'", "]", "# If the `frequency` column is entirely NaN, then there will only be one unique value.", "unique", "=", "freq", ".", "unique", "(", ")", "return", "len", "(", "unique", ")", "!=", "1" ]
[ 143, 0 ]
[ 150, 24 ]
python
en
['en', 'en', 'en']
True
generate_snp_comparison_table
(breseq_table: pandas.DataFrame, by: str,reference_sample: str = None)
Generates a table with sample alt sequences represented by columns. Parameters ---------- breseq_table:pandas.DataFrame The concatenated variant tables for all samples. by: {'base', 'codon', 'amino'} Indicates which reference to use. filter_table: bool Indicates whether to filter out mutations which fail certain filters. reference_sample:str Label of the sample to use as a reference. If given, a new column will be added to the table indicating if the reference sample also contained the variant. Returns ------- pandas.DataFrame
Generates a table with sample alt sequences represented by columns. Parameters ---------- breseq_table:pandas.DataFrame The concatenated variant tables for all samples. by: {'base', 'codon', 'amino'} Indicates which reference to use. filter_table: bool Indicates whether to filter out mutations which fail certain filters.
def generate_snp_comparison_table(breseq_table: pandas.DataFrame, by: str,reference_sample: str = None) -> pandas.DataFrame: """ Generates a table with sample alt sequences represented by columns. Parameters ---------- breseq_table:pandas.DataFrame The concatenated variant tables for all samples. by: {'base', 'codon', 'amino'} Indicates which reference to use. filter_table: bool Indicates whether to filter out mutations which fail certain filters. reference_sample:str Label of the sample to use as a reference. If given, a new column will be added to the table indicating if the reference sample also contained the variant. Returns ------- pandas.DataFrame """ unique_samples = list(breseq_table[IsolateTableColumns.sample_name].unique()) is_population = check_if_population(breseq_table) reference_column, alternate_column = _get_relevant_columns(by, is_population) _group_by = ['seq id', 'position', 'mutationCategory'] position_groups: List[Tuple[str, pandas.DataFrame]] = breseq_table.groupby(by = _group_by) comparison_table = list() for key, group in position_groups: result = parse_mutation_group(group, unique_samples, reference_column, alternate_column) comparison_table.append(result) df = pandas.DataFrame(comparison_table) if df.empty: message = f"The comparison table could not be created, and is empty. This may be due to the `mutationCategory` column being empty." logger.warning(message) # Add a column indicating if the reference sample contained the variant. This only applies if the reference sample is known. if reference_sample and reference_sample in df.columns: df['inReference'] = ((df[reference_sample] != df[reference_column]) & (df[IsolateTableColumns.mutation_category] != "large_deletion")) # Check if the description field came from a translated cds file. #df = apply_cds_annotations(df) return df
[ "def", "generate_snp_comparison_table", "(", "breseq_table", ":", "pandas", ".", "DataFrame", ",", "by", ":", "str", ",", "reference_sample", ":", "str", "=", "None", ")", "->", "pandas", ".", "DataFrame", ":", "unique_samples", "=", "list", "(", "breseq_table", "[", "IsolateTableColumns", ".", "sample_name", "]", ".", "unique", "(", ")", ")", "is_population", "=", "check_if_population", "(", "breseq_table", ")", "reference_column", ",", "alternate_column", "=", "_get_relevant_columns", "(", "by", ",", "is_population", ")", "_group_by", "=", "[", "'seq id'", ",", "'position'", ",", "'mutationCategory'", "]", "position_groups", ":", "List", "[", "Tuple", "[", "str", ",", "pandas", ".", "DataFrame", "]", "]", "=", "breseq_table", ".", "groupby", "(", "by", "=", "_group_by", ")", "comparison_table", "=", "list", "(", ")", "for", "key", ",", "group", "in", "position_groups", ":", "result", "=", "parse_mutation_group", "(", "group", ",", "unique_samples", ",", "reference_column", ",", "alternate_column", ")", "comparison_table", ".", "append", "(", "result", ")", "df", "=", "pandas", ".", "DataFrame", "(", "comparison_table", ")", "if", "df", ".", "empty", ":", "message", "=", "f\"The comparison table could not be created, and is empty. This may be due to the `mutationCategory` column being empty.\"", "logger", ".", "warning", "(", "message", ")", "# Add a column indicating if the reference sample contained the variant. This only applies if the reference sample is known.", "if", "reference_sample", "and", "reference_sample", "in", "df", ".", "columns", ":", "df", "[", "'inReference'", "]", "=", "(", "(", "df", "[", "reference_sample", "]", "!=", "df", "[", "reference_column", "]", ")", "&", "(", "df", "[", "IsolateTableColumns", ".", "mutation_category", "]", "!=", "\"large_deletion\"", ")", ")", "# Check if the description field came from a translated cds file.", "#df = apply_cds_annotations(df)", "return", "df" ]
[ 152, 0 ]
[ 197, 10 ]
python
en
['en', 'error', 'th']
False
kmedoids
(distance_matrix, k, max_interactions=10000, random_seed=None)
k-medoids Usage:: >> sm, c = kmedoids(distance_matrix, k=3) The k-medoids algorithm is a clustering algorithm related to the k-means algorithm and the medoidshift algorithm. Both the k-means and k-medoids algorithms are partitional (breaking the dataset up into groups) and both attempt to minimize the distance between points labeled to be in a cluster and a point designated as the center of that cluster. In contrast to the k-means algorithm, k-medoids chooses datapoints as centers (medoids or exemplars) and works with a generalization of the Manhattan Norm to define distance between datapoints instead of. This method was proposed in 1987[1] for the work with norm and other distances. k-medoid is a classical partitioning technique of clustering that clusters the data set of n objects into k clusters known a priori. A useful tool for determining k is the silhouette. It is more robust to noise and outliers as compared to k-means because it minimizes a sum of pairwise dissimilarities instead of a sum of squared Euclidean distances. A medoid can be defined as the object of a cluster whose average dissimilarity to all the objects in the cluster is minimal. i.e. it is a most centrally located point in the cluster. :param distance_matrix: Matrix with distances between the instances :type distance_matrix: matrix :param k: Number of groups to be generated :type k: int :param max_interactions: Number max of interaction to converge :type max_interactions: int, default 10000 :param random_seed: Seed of random :type random_seed: int, default None :return: Support vector and List of labels (len = number of instances)
k-medoids
def kmedoids(distance_matrix, k, max_interactions=10000, random_seed=None): """ k-medoids Usage:: >> sm, c = kmedoids(distance_matrix, k=3) The k-medoids algorithm is a clustering algorithm related to the k-means algorithm and the medoidshift algorithm. Both the k-means and k-medoids algorithms are partitional (breaking the dataset up into groups) and both attempt to minimize the distance between points labeled to be in a cluster and a point designated as the center of that cluster. In contrast to the k-means algorithm, k-medoids chooses datapoints as centers (medoids or exemplars) and works with a generalization of the Manhattan Norm to define distance between datapoints instead of. This method was proposed in 1987[1] for the work with norm and other distances. k-medoid is a classical partitioning technique of clustering that clusters the data set of n objects into k clusters known a priori. A useful tool for determining k is the silhouette. It is more robust to noise and outliers as compared to k-means because it minimizes a sum of pairwise dissimilarities instead of a sum of squared Euclidean distances. A medoid can be defined as the object of a cluster whose average dissimilarity to all the objects in the cluster is minimal. i.e. it is a most centrally located point in the cluster. :param distance_matrix: Matrix with distances between the instances :type distance_matrix: matrix :param k: Number of groups to be generated :type k: int :param max_interactions: Number max of interaction to converge :type max_interactions: int, default 10000 :param random_seed: Seed of random :type random_seed: int, default None :return: Support vector and List of labels (len = number of instances) """ # Set seed in random if random_seed is not None: np.random.seed(random_seed) # determine dimensions of distance matrix row, col = distance_matrix.shape if k > col: raise Exception("Error:: Too many medoids") # randomly initialize an array of k-medoid indices support_matrix = np.arange(col) np.random.shuffle(support_matrix) support_matrix = np.sort(support_matrix[:k]) # create a copy of the array of medoid indices new_support_matrix = np.copy(support_matrix) # initialize a dictionary to represent clusters clusters = {} for _ in range(max_interactions): # determine clusters, i. e. arrays of data indices j_vector = np.argmin(distance_matrix[:, support_matrix], axis=1) for label in range(k): clusters[label] = np.where(j_vector == label)[0] # update cluster medoids for label in range(k): j_vector = np.mean(distance_matrix[np.ix_(clusters[label], clusters[label])], axis=1) try: j = np.argmin(j_vector) new_support_matrix[label] = clusters[label][j] except ValueError: pass np.sort(new_support_matrix) # check for convergence if np.array_equal(support_matrix, new_support_matrix): break support_matrix = np.copy(new_support_matrix) else: # final update of cluster memberships j_vector = np.argmin(distance_matrix[:, support_matrix], axis=1) for label in range(k): clusters[label] = np.where(j_vector == label)[0] remove_keys = set() for key in clusters: if len(clusters[key]) == 0: remove_keys.add(key) if remove_keys: for key in remove_keys: clusters.pop(key, None) # return results return support_matrix, clusters
[ "def", "kmedoids", "(", "distance_matrix", ",", "k", ",", "max_interactions", "=", "10000", ",", "random_seed", "=", "None", ")", ":", "# Set seed in random", "if", "random_seed", "is", "not", "None", ":", "np", ".", "random", ".", "seed", "(", "random_seed", ")", "# determine dimensions of distance matrix", "row", ",", "col", "=", "distance_matrix", ".", "shape", "if", "k", ">", "col", ":", "raise", "Exception", "(", "\"Error:: Too many medoids\"", ")", "# randomly initialize an array of k-medoid indices", "support_matrix", "=", "np", ".", "arange", "(", "col", ")", "np", ".", "random", ".", "shuffle", "(", "support_matrix", ")", "support_matrix", "=", "np", ".", "sort", "(", "support_matrix", "[", ":", "k", "]", ")", "# create a copy of the array of medoid indices", "new_support_matrix", "=", "np", ".", "copy", "(", "support_matrix", ")", "# initialize a dictionary to represent clusters", "clusters", "=", "{", "}", "for", "_", "in", "range", "(", "max_interactions", ")", ":", "# determine clusters, i. e. arrays of data indices", "j_vector", "=", "np", ".", "argmin", "(", "distance_matrix", "[", ":", ",", "support_matrix", "]", ",", "axis", "=", "1", ")", "for", "label", "in", "range", "(", "k", ")", ":", "clusters", "[", "label", "]", "=", "np", ".", "where", "(", "j_vector", "==", "label", ")", "[", "0", "]", "# update cluster medoids", "for", "label", "in", "range", "(", "k", ")", ":", "j_vector", "=", "np", ".", "mean", "(", "distance_matrix", "[", "np", ".", "ix_", "(", "clusters", "[", "label", "]", ",", "clusters", "[", "label", "]", ")", "]", ",", "axis", "=", "1", ")", "try", ":", "j", "=", "np", ".", "argmin", "(", "j_vector", ")", "new_support_matrix", "[", "label", "]", "=", "clusters", "[", "label", "]", "[", "j", "]", "except", "ValueError", ":", "pass", "np", ".", "sort", "(", "new_support_matrix", ")", "# check for convergence", "if", "np", ".", "array_equal", "(", "support_matrix", ",", "new_support_matrix", ")", ":", "break", "support_matrix", "=", "np", ".", "copy", "(", "new_support_matrix", ")", "else", ":", "# final update of cluster memberships", "j_vector", "=", "np", ".", "argmin", "(", "distance_matrix", "[", ":", ",", "support_matrix", "]", ",", "axis", "=", "1", ")", "for", "label", "in", "range", "(", "k", ")", ":", "clusters", "[", "label", "]", "=", "np", ".", "where", "(", "j_vector", "==", "label", ")", "[", "0", "]", "remove_keys", "=", "set", "(", ")", "for", "key", "in", "clusters", ":", "if", "len", "(", "clusters", "[", "key", "]", ")", "==", "0", ":", "remove_keys", ".", "add", "(", "key", ")", "if", "remove_keys", ":", "for", "key", "in", "remove_keys", ":", "clusters", ".", "pop", "(", "key", ",", "None", ")", "# return results", "return", "support_matrix", ",", "clusters" ]
[ 19, 0 ]
[ 116, 35 ]
python
en
['en', 'error', 'th']
False
Draw
(im, mode=None)
A simple 2D drawing interface for PIL images. :param im: The image to draw in. :param mode: Optional mode to use for color values. For RGB images, this argument can be RGB or RGBA (to blend the drawing into the image). For all other modes, this argument must be the same as the image mode. If omitted, the mode defaults to the mode of the image.
A simple 2D drawing interface for PIL images.
def Draw(im, mode=None): """ A simple 2D drawing interface for PIL images. :param im: The image to draw in. :param mode: Optional mode to use for color values. For RGB images, this argument can be RGB or RGBA (to blend the drawing into the image). For all other modes, this argument must be the same as the image mode. If omitted, the mode defaults to the mode of the image. """ try: return im.getdraw(mode) except AttributeError: return ImageDraw(im, mode)
[ "def", "Draw", "(", "im", ",", "mode", "=", "None", ")", ":", "try", ":", "return", "im", ".", "getdraw", "(", "mode", ")", "except", "AttributeError", ":", "return", "ImageDraw", "(", "im", ",", "mode", ")" ]
[ 755, 0 ]
[ 769, 34 ]
python
en
['en', 'error', 'th']
False
getdraw
(im=None, hints=None)
(Experimental) A more advanced 2D drawing interface for PIL images, based on the WCK interface. :param im: The image to draw in. :param hints: An optional list of hints. :returns: A (drawing context, drawing resource factory) tuple.
(Experimental) A more advanced 2D drawing interface for PIL images, based on the WCK interface.
def getdraw(im=None, hints=None): """ (Experimental) A more advanced 2D drawing interface for PIL images, based on the WCK interface. :param im: The image to draw in. :param hints: An optional list of hints. :returns: A (drawing context, drawing resource factory) tuple. """ # FIXME: this needs more work! # FIXME: come up with a better 'hints' scheme. handler = None if not hints or "nicest" in hints: try: from . import _imagingagg as handler except ImportError: pass if handler is None: from . import ImageDraw2 as handler if im: im = handler.Draw(im) return im, handler
[ "def", "getdraw", "(", "im", "=", "None", ",", "hints", "=", "None", ")", ":", "# FIXME: this needs more work!", "# FIXME: come up with a better 'hints' scheme.", "handler", "=", "None", "if", "not", "hints", "or", "\"nicest\"", "in", "hints", ":", "try", ":", "from", ".", "import", "_imagingagg", "as", "handler", "except", "ImportError", ":", "pass", "if", "handler", "is", "None", ":", "from", ".", "import", "ImageDraw2", "as", "handler", "if", "im", ":", "im", "=", "handler", ".", "Draw", "(", "im", ")", "return", "im", ",", "handler" ]
[ 779, 0 ]
[ 800, 22 ]
python
en
['en', 'error', 'th']
False
floodfill
(image, xy, value, border=None, thresh=0)
(experimental) Fills a bounded region with a given color. :param image: Target image. :param xy: Seed position (a 2-item coordinate tuple). See :ref:`coordinate-system`. :param value: Fill color. :param border: Optional border value. If given, the region consists of pixels with a color different from the border color. If not given, the region consists of pixels having the same color as the seed pixel. :param thresh: Optional threshold value which specifies a maximum tolerable difference of a pixel value from the 'background' in order for it to be replaced. Useful for filling regions of non-homogeneous, but similar, colors.
(experimental) Fills a bounded region with a given color.
def floodfill(image, xy, value, border=None, thresh=0): """ (experimental) Fills a bounded region with a given color. :param image: Target image. :param xy: Seed position (a 2-item coordinate tuple). See :ref:`coordinate-system`. :param value: Fill color. :param border: Optional border value. If given, the region consists of pixels with a color different from the border color. If not given, the region consists of pixels having the same color as the seed pixel. :param thresh: Optional threshold value which specifies a maximum tolerable difference of a pixel value from the 'background' in order for it to be replaced. Useful for filling regions of non-homogeneous, but similar, colors. """ # based on an implementation by Eric S. Raymond # amended by yo1995 @20180806 pixel = image.load() x, y = xy try: background = pixel[x, y] if _color_diff(value, background) <= thresh: return # seed point already has fill color pixel[x, y] = value except (ValueError, IndexError): return # seed point outside image edge = {(x, y)} # use a set to keep record of current and previous edge pixels # to reduce memory consumption full_edge = set() while edge: new_edge = set() for (x, y) in edge: # 4 adjacent method for (s, t) in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): # If already processed, or if a coordinate is negative, skip if (s, t) in full_edge or s < 0 or t < 0: continue try: p = pixel[s, t] except (ValueError, IndexError): pass else: full_edge.add((s, t)) if border is None: fill = _color_diff(p, background) <= thresh else: fill = p != value and p != border if fill: pixel[s, t] = value new_edge.add((s, t)) full_edge = edge # discard pixels processed edge = new_edge
[ "def", "floodfill", "(", "image", ",", "xy", ",", "value", ",", "border", "=", "None", ",", "thresh", "=", "0", ")", ":", "# based on an implementation by Eric S. Raymond", "# amended by yo1995 @20180806", "pixel", "=", "image", ".", "load", "(", ")", "x", ",", "y", "=", "xy", "try", ":", "background", "=", "pixel", "[", "x", ",", "y", "]", "if", "_color_diff", "(", "value", ",", "background", ")", "<=", "thresh", ":", "return", "# seed point already has fill color", "pixel", "[", "x", ",", "y", "]", "=", "value", "except", "(", "ValueError", ",", "IndexError", ")", ":", "return", "# seed point outside image", "edge", "=", "{", "(", "x", ",", "y", ")", "}", "# use a set to keep record of current and previous edge pixels", "# to reduce memory consumption", "full_edge", "=", "set", "(", ")", "while", "edge", ":", "new_edge", "=", "set", "(", ")", "for", "(", "x", ",", "y", ")", "in", "edge", ":", "# 4 adjacent method", "for", "(", "s", ",", "t", ")", "in", "(", "(", "x", "+", "1", ",", "y", ")", ",", "(", "x", "-", "1", ",", "y", ")", ",", "(", "x", ",", "y", "+", "1", ")", ",", "(", "x", ",", "y", "-", "1", ")", ")", ":", "# If already processed, or if a coordinate is negative, skip", "if", "(", "s", ",", "t", ")", "in", "full_edge", "or", "s", "<", "0", "or", "t", "<", "0", ":", "continue", "try", ":", "p", "=", "pixel", "[", "s", ",", "t", "]", "except", "(", "ValueError", ",", "IndexError", ")", ":", "pass", "else", ":", "full_edge", ".", "add", "(", "(", "s", ",", "t", ")", ")", "if", "border", "is", "None", ":", "fill", "=", "_color_diff", "(", "p", ",", "background", ")", "<=", "thresh", "else", ":", "fill", "=", "p", "!=", "value", "and", "p", "!=", "border", "if", "fill", ":", "pixel", "[", "s", ",", "t", "]", "=", "value", "new_edge", ".", "add", "(", "(", "s", ",", "t", ")", ")", "full_edge", "=", "edge", "# discard pixels processed", "edge", "=", "new_edge" ]
[ 803, 0 ]
[ 856, 23 ]
python
en
['en', 'error', 'th']
False
_compute_regular_polygon_vertices
(bounding_circle, n_sides, rotation)
Generate a list of vertices for a 2D regular polygon. :param bounding_circle: The bounding circle is a tuple defined by a point and radius. The polygon is inscribed in this circle. (e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``) :param n_sides: Number of sides (e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon) :param rotation: Apply an arbitrary rotation to the polygon (e.g. ``rotation=90``, applies a 90 degree rotation) :return: List of regular polygon vertices (e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``) How are the vertices computed? 1. Compute the following variables - theta: Angle between the apothem & the nearest polygon vertex - side_length: Length of each polygon edge - centroid: Center of bounding circle (1st, 2nd elements of bounding_circle) - polygon_radius: Polygon radius (last element of bounding_circle) - angles: Location of each polygon vertex in polar grid (e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0]) 2. For each angle in angles, get the polygon vertex at that angle The vertex is computed using the equation below. X= xcos(φ) + ysin(φ) Y= −xsin(φ) + ycos(φ) Note: φ = angle in degrees x = 0 y = polygon_radius The formula above assumes rotation around the origin. In our case, we are rotating around the centroid. To account for this, we use the formula below X = xcos(φ) + ysin(φ) + centroid_x Y = −xsin(φ) + ycos(φ) + centroid_y
Generate a list of vertices for a 2D regular polygon.
def _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation): """ Generate a list of vertices for a 2D regular polygon. :param bounding_circle: The bounding circle is a tuple defined by a point and radius. The polygon is inscribed in this circle. (e.g. ``bounding_circle=(x, y, r)`` or ``((x, y), r)``) :param n_sides: Number of sides (e.g. ``n_sides=3`` for a triangle, ``6`` for a hexagon) :param rotation: Apply an arbitrary rotation to the polygon (e.g. ``rotation=90``, applies a 90 degree rotation) :return: List of regular polygon vertices (e.g. ``[(25, 50), (50, 50), (50, 25), (25, 25)]``) How are the vertices computed? 1. Compute the following variables - theta: Angle between the apothem & the nearest polygon vertex - side_length: Length of each polygon edge - centroid: Center of bounding circle (1st, 2nd elements of bounding_circle) - polygon_radius: Polygon radius (last element of bounding_circle) - angles: Location of each polygon vertex in polar grid (e.g. A square with 0 degree rotation => [225.0, 315.0, 45.0, 135.0]) 2. For each angle in angles, get the polygon vertex at that angle The vertex is computed using the equation below. X= xcos(φ) + ysin(φ) Y= −xsin(φ) + ycos(φ) Note: φ = angle in degrees x = 0 y = polygon_radius The formula above assumes rotation around the origin. In our case, we are rotating around the centroid. To account for this, we use the formula below X = xcos(φ) + ysin(φ) + centroid_x Y = −xsin(φ) + ycos(φ) + centroid_y """ # 1. Error Handling # 1.1 Check `n_sides` has an appropriate value if not isinstance(n_sides, int): raise TypeError("n_sides should be an int") if n_sides < 3: raise ValueError("n_sides should be an int > 2") # 1.2 Check `bounding_circle` has an appropriate value if not isinstance(bounding_circle, (list, tuple)): raise TypeError("bounding_circle should be a tuple") if len(bounding_circle) == 3: *centroid, polygon_radius = bounding_circle elif len(bounding_circle) == 2: centroid, polygon_radius = bounding_circle else: raise ValueError( "bounding_circle should contain 2D coordinates " "and a radius (e.g. (x, y, r) or ((x, y), r) )" ) if not all(isinstance(i, (int, float)) for i in (*centroid, polygon_radius)): raise ValueError("bounding_circle should only contain numeric data") if not len(centroid) == 2: raise ValueError( "bounding_circle centre should contain 2D coordinates (e.g. (x, y))" ) if polygon_radius <= 0: raise ValueError("bounding_circle radius should be > 0") # 1.3 Check `rotation` has an appropriate value if not isinstance(rotation, (int, float)): raise ValueError("rotation should be an int or float") # 2. Define Helper Functions def _apply_rotation(point, degrees, centroid): return ( round( point[0] * math.cos(math.radians(360 - degrees)) - point[1] * math.sin(math.radians(360 - degrees)) + centroid[0], 2, ), round( point[1] * math.cos(math.radians(360 - degrees)) + point[0] * math.sin(math.radians(360 - degrees)) + centroid[1], 2, ), ) def _compute_polygon_vertex(centroid, polygon_radius, angle): start_point = [polygon_radius, 0] return _apply_rotation(start_point, angle, centroid) def _get_angles(n_sides, rotation): angles = [] degrees = 360 / n_sides # Start with the bottom left polygon vertex current_angle = (270 - 0.5 * degrees) + rotation for _ in range(0, n_sides): angles.append(current_angle) current_angle += degrees if current_angle > 360: current_angle -= 360 return angles # 3. Variable Declarations angles = _get_angles(n_sides, rotation) # 4. Compute Vertices return [ _compute_polygon_vertex(centroid, polygon_radius, angle) for angle in angles ]
[ "def", "_compute_regular_polygon_vertices", "(", "bounding_circle", ",", "n_sides", ",", "rotation", ")", ":", "# 1. Error Handling", "# 1.1 Check `n_sides` has an appropriate value", "if", "not", "isinstance", "(", "n_sides", ",", "int", ")", ":", "raise", "TypeError", "(", "\"n_sides should be an int\"", ")", "if", "n_sides", "<", "3", ":", "raise", "ValueError", "(", "\"n_sides should be an int > 2\"", ")", "# 1.2 Check `bounding_circle` has an appropriate value", "if", "not", "isinstance", "(", "bounding_circle", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "\"bounding_circle should be a tuple\"", ")", "if", "len", "(", "bounding_circle", ")", "==", "3", ":", "*", "centroid", ",", "polygon_radius", "=", "bounding_circle", "elif", "len", "(", "bounding_circle", ")", "==", "2", ":", "centroid", ",", "polygon_radius", "=", "bounding_circle", "else", ":", "raise", "ValueError", "(", "\"bounding_circle should contain 2D coordinates \"", "\"and a radius (e.g. (x, y, r) or ((x, y), r) )\"", ")", "if", "not", "all", "(", "isinstance", "(", "i", ",", "(", "int", ",", "float", ")", ")", "for", "i", "in", "(", "*", "centroid", ",", "polygon_radius", ")", ")", ":", "raise", "ValueError", "(", "\"bounding_circle should only contain numeric data\"", ")", "if", "not", "len", "(", "centroid", ")", "==", "2", ":", "raise", "ValueError", "(", "\"bounding_circle centre should contain 2D coordinates (e.g. (x, y))\"", ")", "if", "polygon_radius", "<=", "0", ":", "raise", "ValueError", "(", "\"bounding_circle radius should be > 0\"", ")", "# 1.3 Check `rotation` has an appropriate value", "if", "not", "isinstance", "(", "rotation", ",", "(", "int", ",", "float", ")", ")", ":", "raise", "ValueError", "(", "\"rotation should be an int or float\"", ")", "# 2. Define Helper Functions", "def", "_apply_rotation", "(", "point", ",", "degrees", ",", "centroid", ")", ":", "return", "(", "round", "(", "point", "[", "0", "]", "*", "math", ".", "cos", "(", "math", ".", "radians", "(", "360", "-", "degrees", ")", ")", "-", "point", "[", "1", "]", "*", "math", ".", "sin", "(", "math", ".", "radians", "(", "360", "-", "degrees", ")", ")", "+", "centroid", "[", "0", "]", ",", "2", ",", ")", ",", "round", "(", "point", "[", "1", "]", "*", "math", ".", "cos", "(", "math", ".", "radians", "(", "360", "-", "degrees", ")", ")", "+", "point", "[", "0", "]", "*", "math", ".", "sin", "(", "math", ".", "radians", "(", "360", "-", "degrees", ")", ")", "+", "centroid", "[", "1", "]", ",", "2", ",", ")", ",", ")", "def", "_compute_polygon_vertex", "(", "centroid", ",", "polygon_radius", ",", "angle", ")", ":", "start_point", "=", "[", "polygon_radius", ",", "0", "]", "return", "_apply_rotation", "(", "start_point", ",", "angle", ",", "centroid", ")", "def", "_get_angles", "(", "n_sides", ",", "rotation", ")", ":", "angles", "=", "[", "]", "degrees", "=", "360", "/", "n_sides", "# Start with the bottom left polygon vertex", "current_angle", "=", "(", "270", "-", "0.5", "*", "degrees", ")", "+", "rotation", "for", "_", "in", "range", "(", "0", ",", "n_sides", ")", ":", "angles", ".", "append", "(", "current_angle", ")", "current_angle", "+=", "degrees", "if", "current_angle", ">", "360", ":", "current_angle", "-=", "360", "return", "angles", "# 3. Variable Declarations", "angles", "=", "_get_angles", "(", "n_sides", ",", "rotation", ")", "# 4. Compute Vertices", "return", "[", "_compute_polygon_vertex", "(", "centroid", ",", "polygon_radius", ",", "angle", ")", "for", "angle", "in", "angles", "]" ]
[ 859, 0 ]
[ 973, 5 ]
python
en
['en', 'error', 'th']
False
_color_diff
(color1, color2)
Uses 1-norm distance to calculate difference between two values.
Uses 1-norm distance to calculate difference between two values.
def _color_diff(color1, color2): """ Uses 1-norm distance to calculate difference between two values. """ if isinstance(color2, tuple): return sum([abs(color1[i] - color2[i]) for i in range(0, len(color2))]) else: return abs(color1 - color2)
[ "def", "_color_diff", "(", "color1", ",", "color2", ")", ":", "if", "isinstance", "(", "color2", ",", "tuple", ")", ":", "return", "sum", "(", "[", "abs", "(", "color1", "[", "i", "]", "-", "color2", "[", "i", "]", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "color2", ")", ")", "]", ")", "else", ":", "return", "abs", "(", "color1", "-", "color2", ")" ]
[ 976, 0 ]
[ 983, 35 ]
python
en
['en', 'error', 'th']
False
ImageDraw.__init__
(self, im, mode=None)
Create a drawing instance. :param im: The image to draw in. :param mode: Optional mode to use for color values. For RGB images, this argument can be RGB or RGBA (to blend the drawing into the image). For all other modes, this argument must be the same as the image mode. If omitted, the mode defaults to the mode of the image.
Create a drawing instance.
def __init__(self, im, mode=None): """ Create a drawing instance. :param im: The image to draw in. :param mode: Optional mode to use for color values. For RGB images, this argument can be RGB or RGBA (to blend the drawing into the image). For all other modes, this argument must be the same as the image mode. If omitted, the mode defaults to the mode of the image. """ im.load() if im.readonly: im._copy() # make it writeable blend = 0 if mode is None: mode = im.mode if mode != im.mode: if mode == "RGBA" and im.mode == "RGB": blend = 1 else: raise ValueError("mode mismatch") if mode == "P": self.palette = im.palette else: self.palette = None self._image = im self.im = im.im self.draw = Image.core.draw(self.im, blend) self.mode = mode if mode in ("I", "F"): self.ink = self.draw.draw_ink(1) else: self.ink = self.draw.draw_ink(-1) if mode in ("1", "P", "I", "F"): # FIXME: fix Fill2 to properly support matte for I+F images self.fontmode = "1" else: self.fontmode = "L" # aliasing is okay for other modes self.fill = 0 self.font = None
[ "def", "__init__", "(", "self", ",", "im", ",", "mode", "=", "None", ")", ":", "im", ".", "load", "(", ")", "if", "im", ".", "readonly", ":", "im", ".", "_copy", "(", ")", "# make it writeable", "blend", "=", "0", "if", "mode", "is", "None", ":", "mode", "=", "im", ".", "mode", "if", "mode", "!=", "im", ".", "mode", ":", "if", "mode", "==", "\"RGBA\"", "and", "im", ".", "mode", "==", "\"RGB\"", ":", "blend", "=", "1", "else", ":", "raise", "ValueError", "(", "\"mode mismatch\"", ")", "if", "mode", "==", "\"P\"", ":", "self", ".", "palette", "=", "im", ".", "palette", "else", ":", "self", ".", "palette", "=", "None", "self", ".", "_image", "=", "im", "self", ".", "im", "=", "im", ".", "im", "self", ".", "draw", "=", "Image", ".", "core", ".", "draw", "(", "self", ".", "im", ",", "blend", ")", "self", ".", "mode", "=", "mode", "if", "mode", "in", "(", "\"I\"", ",", "\"F\"", ")", ":", "self", ".", "ink", "=", "self", ".", "draw", ".", "draw_ink", "(", "1", ")", "else", ":", "self", ".", "ink", "=", "self", ".", "draw", ".", "draw_ink", "(", "-", "1", ")", "if", "mode", "in", "(", "\"1\"", ",", "\"P\"", ",", "\"I\"", ",", "\"F\"", ")", ":", "# FIXME: fix Fill2 to properly support matte for I+F images", "self", ".", "fontmode", "=", "\"1\"", "else", ":", "self", ".", "fontmode", "=", "\"L\"", "# aliasing is okay for other modes", "self", ".", "fill", "=", "0", "self", ".", "font", "=", "None" ]
[ 46, 4 ]
[ 86, 24 ]
python
en
['en', 'error', 'th']
False
ImageDraw.getfont
(self)
Get the current default font. :returns: An image font.
Get the current default font.
def getfont(self): """ Get the current default font. :returns: An image font.""" if not self.font: # FIXME: should add a font repository from . import ImageFont self.font = ImageFont.load_default() return self.font
[ "def", "getfont", "(", "self", ")", ":", "if", "not", "self", ".", "font", ":", "# FIXME: should add a font repository", "from", ".", "import", "ImageFont", "self", ".", "font", "=", "ImageFont", ".", "load_default", "(", ")", "return", "self", ".", "font" ]
[ 88, 4 ]
[ 98, 24 ]
python
en
['en', 'error', 'th']
False
ImageDraw.arc
(self, xy, start, end, fill=None, width=1)
Draw an arc.
Draw an arc.
def arc(self, xy, start, end, fill=None, width=1): """Draw an arc.""" ink, fill = self._getink(fill) if ink is not None: self.draw.draw_arc(xy, start, end, ink, width)
[ "def", "arc", "(", "self", ",", "xy", ",", "start", ",", "end", ",", "fill", "=", "None", ",", "width", "=", "1", ")", ":", "ink", ",", "fill", "=", "self", ".", "_getink", "(", "fill", ")", "if", "ink", "is", "not", "None", ":", "self", ".", "draw", ".", "draw_arc", "(", "xy", ",", "start", ",", "end", ",", "ink", ",", "width", ")" ]
[ 121, 4 ]
[ 125, 58 ]
python
en
['en', 'pl', 'en']
True
ImageDraw.bitmap
(self, xy, bitmap, fill=None)
Draw a bitmap.
Draw a bitmap.
def bitmap(self, xy, bitmap, fill=None): """Draw a bitmap.""" bitmap.load() ink, fill = self._getink(fill) if ink is None: ink = fill if ink is not None: self.draw.draw_bitmap(xy, bitmap.im, ink)
[ "def", "bitmap", "(", "self", ",", "xy", ",", "bitmap", ",", "fill", "=", "None", ")", ":", "bitmap", ".", "load", "(", ")", "ink", ",", "fill", "=", "self", ".", "_getink", "(", "fill", ")", "if", "ink", "is", "None", ":", "ink", "=", "fill", "if", "ink", "is", "not", "None", ":", "self", ".", "draw", ".", "draw_bitmap", "(", "xy", ",", "bitmap", ".", "im", ",", "ink", ")" ]
[ 127, 4 ]
[ 134, 53 ]
python
en
['en', 'mt', 'en']
True
ImageDraw.chord
(self, xy, start, end, fill=None, outline=None, width=1)
Draw a chord.
Draw a chord.
def chord(self, xy, start, end, fill=None, outline=None, width=1): """Draw a chord.""" ink, fill = self._getink(outline, fill) if fill is not None: self.draw.draw_chord(xy, start, end, fill, 1) if ink is not None and ink != fill and width != 0: self.draw.draw_chord(xy, start, end, ink, 0, width)
[ "def", "chord", "(", "self", ",", "xy", ",", "start", ",", "end", ",", "fill", "=", "None", ",", "outline", "=", "None", ",", "width", "=", "1", ")", ":", "ink", ",", "fill", "=", "self", ".", "_getink", "(", "outline", ",", "fill", ")", "if", "fill", "is", "not", "None", ":", "self", ".", "draw", ".", "draw_chord", "(", "xy", ",", "start", ",", "end", ",", "fill", ",", "1", ")", "if", "ink", "is", "not", "None", "and", "ink", "!=", "fill", "and", "width", "!=", "0", ":", "self", ".", "draw", ".", "draw_chord", "(", "xy", ",", "start", ",", "end", ",", "ink", ",", "0", ",", "width", ")" ]
[ 136, 4 ]
[ 142, 63 ]
python
cy
['en', 'cy', 'hi']
False
ImageDraw.ellipse
(self, xy, fill=None, outline=None, width=1)
Draw an ellipse.
Draw an ellipse.
def ellipse(self, xy, fill=None, outline=None, width=1): """Draw an ellipse.""" ink, fill = self._getink(outline, fill) if fill is not None: self.draw.draw_ellipse(xy, fill, 1) if ink is not None and ink != fill and width != 0: self.draw.draw_ellipse(xy, ink, 0, width)
[ "def", "ellipse", "(", "self", ",", "xy", ",", "fill", "=", "None", ",", "outline", "=", "None", ",", "width", "=", "1", ")", ":", "ink", ",", "fill", "=", "self", ".", "_getink", "(", "outline", ",", "fill", ")", "if", "fill", "is", "not", "None", ":", "self", ".", "draw", ".", "draw_ellipse", "(", "xy", ",", "fill", ",", "1", ")", "if", "ink", "is", "not", "None", "and", "ink", "!=", "fill", "and", "width", "!=", "0", ":", "self", ".", "draw", ".", "draw_ellipse", "(", "xy", ",", "ink", ",", "0", ",", "width", ")" ]
[ 144, 4 ]
[ 150, 53 ]
python
en
['en', 'fy', 'es']
False
ImageDraw.line
(self, xy, fill=None, width=0, joint=None)
Draw a line, or a connected sequence of line segments.
Draw a line, or a connected sequence of line segments.
def line(self, xy, fill=None, width=0, joint=None): """Draw a line, or a connected sequence of line segments.""" ink = self._getink(fill)[0] if ink is not None: self.draw.draw_lines(xy, ink, width) if joint == "curve" and width > 4: if not isinstance(xy[0], (list, tuple)): xy = [tuple(xy[i : i + 2]) for i in range(0, len(xy), 2)] for i in range(1, len(xy) - 1): point = xy[i] angles = [ math.degrees(math.atan2(end[0] - start[0], start[1] - end[1])) % 360 for start, end in ((xy[i - 1], point), (point, xy[i + 1])) ] if angles[0] == angles[1]: # This is a straight line, so no joint is required continue def coord_at_angle(coord, angle): x, y = coord angle -= 90 distance = width / 2 - 1 return tuple( [ p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d)) for p, p_d in ( (x, distance * math.cos(math.radians(angle))), (y, distance * math.sin(math.radians(angle))), ) ] ) flipped = ( angles[1] > angles[0] and angles[1] - 180 > angles[0] ) or (angles[1] < angles[0] and angles[1] + 180 > angles[0]) coords = [ (point[0] - width / 2 + 1, point[1] - width / 2 + 1), (point[0] + width / 2 - 1, point[1] + width / 2 - 1), ] if flipped: start, end = (angles[1] + 90, angles[0] + 90) else: start, end = (angles[0] - 90, angles[1] - 90) self.pieslice(coords, start - 90, end - 90, fill) if width > 8: # Cover potential gaps between the line and the joint if flipped: gapCoords = [ coord_at_angle(point, angles[0] + 90), point, coord_at_angle(point, angles[1] + 90), ] else: gapCoords = [ coord_at_angle(point, angles[0] - 90), point, coord_at_angle(point, angles[1] - 90), ] self.line(gapCoords, fill, width=3)
[ "def", "line", "(", "self", ",", "xy", ",", "fill", "=", "None", ",", "width", "=", "0", ",", "joint", "=", "None", ")", ":", "ink", "=", "self", ".", "_getink", "(", "fill", ")", "[", "0", "]", "if", "ink", "is", "not", "None", ":", "self", ".", "draw", ".", "draw_lines", "(", "xy", ",", "ink", ",", "width", ")", "if", "joint", "==", "\"curve\"", "and", "width", ">", "4", ":", "if", "not", "isinstance", "(", "xy", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "xy", "=", "[", "tuple", "(", "xy", "[", "i", ":", "i", "+", "2", "]", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "xy", ")", ",", "2", ")", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "xy", ")", "-", "1", ")", ":", "point", "=", "xy", "[", "i", "]", "angles", "=", "[", "math", ".", "degrees", "(", "math", ".", "atan2", "(", "end", "[", "0", "]", "-", "start", "[", "0", "]", ",", "start", "[", "1", "]", "-", "end", "[", "1", "]", ")", ")", "%", "360", "for", "start", ",", "end", "in", "(", "(", "xy", "[", "i", "-", "1", "]", ",", "point", ")", ",", "(", "point", ",", "xy", "[", "i", "+", "1", "]", ")", ")", "]", "if", "angles", "[", "0", "]", "==", "angles", "[", "1", "]", ":", "# This is a straight line, so no joint is required", "continue", "def", "coord_at_angle", "(", "coord", ",", "angle", ")", ":", "x", ",", "y", "=", "coord", "angle", "-=", "90", "distance", "=", "width", "/", "2", "-", "1", "return", "tuple", "(", "[", "p", "+", "(", "math", ".", "floor", "(", "p_d", ")", "if", "p_d", ">", "0", "else", "math", ".", "ceil", "(", "p_d", ")", ")", "for", "p", ",", "p_d", "in", "(", "(", "x", ",", "distance", "*", "math", ".", "cos", "(", "math", ".", "radians", "(", "angle", ")", ")", ")", ",", "(", "y", ",", "distance", "*", "math", ".", "sin", "(", "math", ".", "radians", "(", "angle", ")", ")", ")", ",", ")", "]", ")", "flipped", "=", "(", "angles", "[", "1", "]", ">", "angles", "[", "0", "]", "and", "angles", "[", "1", "]", "-", "180", ">", "angles", "[", "0", "]", ")", "or", "(", "angles", "[", "1", "]", "<", "angles", "[", "0", "]", "and", "angles", "[", "1", "]", "+", "180", ">", "angles", "[", "0", "]", ")", "coords", "=", "[", "(", "point", "[", "0", "]", "-", "width", "/", "2", "+", "1", ",", "point", "[", "1", "]", "-", "width", "/", "2", "+", "1", ")", ",", "(", "point", "[", "0", "]", "+", "width", "/", "2", "-", "1", ",", "point", "[", "1", "]", "+", "width", "/", "2", "-", "1", ")", ",", "]", "if", "flipped", ":", "start", ",", "end", "=", "(", "angles", "[", "1", "]", "+", "90", ",", "angles", "[", "0", "]", "+", "90", ")", "else", ":", "start", ",", "end", "=", "(", "angles", "[", "0", "]", "-", "90", ",", "angles", "[", "1", "]", "-", "90", ")", "self", ".", "pieslice", "(", "coords", ",", "start", "-", "90", ",", "end", "-", "90", ",", "fill", ")", "if", "width", ">", "8", ":", "# Cover potential gaps between the line and the joint", "if", "flipped", ":", "gapCoords", "=", "[", "coord_at_angle", "(", "point", ",", "angles", "[", "0", "]", "+", "90", ")", ",", "point", ",", "coord_at_angle", "(", "point", ",", "angles", "[", "1", "]", "+", "90", ")", ",", "]", "else", ":", "gapCoords", "=", "[", "coord_at_angle", "(", "point", ",", "angles", "[", "0", "]", "-", "90", ")", ",", "point", ",", "coord_at_angle", "(", "point", ",", "angles", "[", "1", "]", "-", "90", ")", ",", "]", "self", ".", "line", "(", "gapCoords", ",", "fill", ",", "width", "=", "3", ")" ]
[ 152, 4 ]
[ 212, 59 ]
python
en
['en', 'en', 'en']
True
ImageDraw.shape
(self, shape, fill=None, outline=None)
(Experimental) Draw a shape.
(Experimental) Draw a shape.
def shape(self, shape, fill=None, outline=None): """(Experimental) Draw a shape.""" shape.close() ink, fill = self._getink(outline, fill) if fill is not None: self.draw.draw_outline(shape, fill, 1) if ink is not None and ink != fill: self.draw.draw_outline(shape, ink, 0)
[ "def", "shape", "(", "self", ",", "shape", ",", "fill", "=", "None", ",", "outline", "=", "None", ")", ":", "shape", ".", "close", "(", ")", "ink", ",", "fill", "=", "self", ".", "_getink", "(", "outline", ",", "fill", ")", "if", "fill", "is", "not", "None", ":", "self", ".", "draw", ".", "draw_outline", "(", "shape", ",", "fill", ",", "1", ")", "if", "ink", "is", "not", "None", "and", "ink", "!=", "fill", ":", "self", ".", "draw", ".", "draw_outline", "(", "shape", ",", "ink", ",", "0", ")" ]
[ 214, 4 ]
[ 221, 49 ]
python
en
['en', 'haw', 'en']
True
ImageDraw.pieslice
(self, xy, start, end, fill=None, outline=None, width=1)
Draw a pieslice.
Draw a pieslice.
def pieslice(self, xy, start, end, fill=None, outline=None, width=1): """Draw a pieslice.""" ink, fill = self._getink(outline, fill) if fill is not None: self.draw.draw_pieslice(xy, start, end, fill, 1) if ink is not None and ink != fill and width != 0: self.draw.draw_pieslice(xy, start, end, ink, 0, width)
[ "def", "pieslice", "(", "self", ",", "xy", ",", "start", ",", "end", ",", "fill", "=", "None", ",", "outline", "=", "None", ",", "width", "=", "1", ")", ":", "ink", ",", "fill", "=", "self", ".", "_getink", "(", "outline", ",", "fill", ")", "if", "fill", "is", "not", "None", ":", "self", ".", "draw", ".", "draw_pieslice", "(", "xy", ",", "start", ",", "end", ",", "fill", ",", "1", ")", "if", "ink", "is", "not", "None", "and", "ink", "!=", "fill", "and", "width", "!=", "0", ":", "self", ".", "draw", ".", "draw_pieslice", "(", "xy", ",", "start", ",", "end", ",", "ink", ",", "0", ",", "width", ")" ]
[ 223, 4 ]
[ 229, 66 ]
python
pl
['en', 'pl', 'pl']
True
ImageDraw.point
(self, xy, fill=None)
Draw one or more individual pixels.
Draw one or more individual pixels.
def point(self, xy, fill=None): """Draw one or more individual pixels.""" ink, fill = self._getink(fill) if ink is not None: self.draw.draw_points(xy, ink)
[ "def", "point", "(", "self", ",", "xy", ",", "fill", "=", "None", ")", ":", "ink", ",", "fill", "=", "self", ".", "_getink", "(", "fill", ")", "if", "ink", "is", "not", "None", ":", "self", ".", "draw", ".", "draw_points", "(", "xy", ",", "ink", ")" ]
[ 231, 4 ]
[ 235, 42 ]
python
en
['en', 'en', 'en']
True
ImageDraw.polygon
(self, xy, fill=None, outline=None)
Draw a polygon.
Draw a polygon.
def polygon(self, xy, fill=None, outline=None): """Draw a polygon.""" ink, fill = self._getink(outline, fill) if fill is not None: self.draw.draw_polygon(xy, fill, 1) if ink is not None and ink != fill: self.draw.draw_polygon(xy, ink, 0)
[ "def", "polygon", "(", "self", ",", "xy", ",", "fill", "=", "None", ",", "outline", "=", "None", ")", ":", "ink", ",", "fill", "=", "self", ".", "_getink", "(", "outline", ",", "fill", ")", "if", "fill", "is", "not", "None", ":", "self", ".", "draw", ".", "draw_polygon", "(", "xy", ",", "fill", ",", "1", ")", "if", "ink", "is", "not", "None", "and", "ink", "!=", "fill", ":", "self", ".", "draw", ".", "draw_polygon", "(", "xy", ",", "ink", ",", "0", ")" ]
[ 237, 4 ]
[ 243, 46 ]
python
en
['en', 'cy', 'en']
True
ImageDraw.regular_polygon
( self, bounding_circle, n_sides, rotation=0, fill=None, outline=None )
Draw a regular polygon.
Draw a regular polygon.
def regular_polygon( self, bounding_circle, n_sides, rotation=0, fill=None, outline=None ): """Draw a regular polygon.""" xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation) self.polygon(xy, fill, outline)
[ "def", "regular_polygon", "(", "self", ",", "bounding_circle", ",", "n_sides", ",", "rotation", "=", "0", ",", "fill", "=", "None", ",", "outline", "=", "None", ")", ":", "xy", "=", "_compute_regular_polygon_vertices", "(", "bounding_circle", ",", "n_sides", ",", "rotation", ")", "self", ".", "polygon", "(", "xy", ",", "fill", ",", "outline", ")" ]
[ 245, 4 ]
[ 250, 39 ]
python
en
['en', 'cy', 'en']
True
ImageDraw.rectangle
(self, xy, fill=None, outline=None, width=1)
Draw a rectangle.
Draw a rectangle.
def rectangle(self, xy, fill=None, outline=None, width=1): """Draw a rectangle.""" ink, fill = self._getink(outline, fill) if fill is not None: self.draw.draw_rectangle(xy, fill, 1) if ink is not None and ink != fill and width != 0: self.draw.draw_rectangle(xy, ink, 0, width)
[ "def", "rectangle", "(", "self", ",", "xy", ",", "fill", "=", "None", ",", "outline", "=", "None", ",", "width", "=", "1", ")", ":", "ink", ",", "fill", "=", "self", ".", "_getink", "(", "outline", ",", "fill", ")", "if", "fill", "is", "not", "None", ":", "self", ".", "draw", ".", "draw_rectangle", "(", "xy", ",", "fill", ",", "1", ")", "if", "ink", "is", "not", "None", "and", "ink", "!=", "fill", "and", "width", "!=", "0", ":", "self", ".", "draw", ".", "draw_rectangle", "(", "xy", ",", "ink", ",", "0", ",", "width", ")" ]
[ 252, 4 ]
[ 258, 55 ]
python
en
['en', 'en', 'pt']
True
ImageDraw.rounded_rectangle
(self, xy, radius=0, fill=None, outline=None, width=1)
Draw a rounded rectangle.
Draw a rounded rectangle.
def rounded_rectangle(self, xy, radius=0, fill=None, outline=None, width=1): """Draw a rounded rectangle.""" if isinstance(xy[0], (list, tuple)): (x0, y0), (x1, y1) = xy else: x0, y0, x1, y1 = xy d = radius * 2 full_x = d >= x1 - x0 if full_x: # The two left and two right corners are joined d = x1 - x0 full_y = d >= y1 - y0 if full_y: # The two top and two bottom corners are joined d = y1 - y0 if full_x and full_y: # If all corners are joined, that is a circle return self.ellipse(xy, fill, outline, width) if d == 0: # If the corners have no curve, that is a rectangle return self.rectangle(xy, fill, outline, width) r = d // 2 ink, fill = self._getink(outline, fill) def draw_corners(pieslice): if full_x: # Draw top and bottom halves parts = ( ((x0, y0, x0 + d, y0 + d), 180, 360), ((x0, y1 - d, x0 + d, y1), 0, 180), ) elif full_y: # Draw left and right halves parts = ( ((x0, y0, x0 + d, y0 + d), 90, 270), ((x1 - d, y0, x1, y0 + d), 270, 90), ) else: # Draw four separate corners parts = ( ((x1 - d, y0, x1, y0 + d), 270, 360), ((x1 - d, y1 - d, x1, y1), 0, 90), ((x0, y1 - d, x0 + d, y1), 90, 180), ((x0, y0, x0 + d, y0 + d), 180, 270), ) for part in parts: if pieslice: self.draw.draw_pieslice(*(part + (fill, 1))) else: self.draw.draw_arc(*(part + (ink, width))) if fill is not None: draw_corners(True) if full_x: self.draw.draw_rectangle((x0, y0 + r + 1, x1, y1 - r - 1), fill, 1) else: self.draw.draw_rectangle((x0 + r + 1, y0, x1 - r - 1, y1), fill, 1) if not full_x and not full_y: self.draw.draw_rectangle((x0, y0 + r + 1, x0 + r, y1 - r - 1), fill, 1) self.draw.draw_rectangle((x1 - r, y0 + r + 1, x1, y1 - r - 1), fill, 1) if ink is not None and ink != fill and width != 0: draw_corners(False) if not full_x: self.draw.draw_rectangle( (x0 + r + 1, y0, x1 - r - 1, y0 + width - 1), ink, 1 ) self.draw.draw_rectangle( (x0 + r + 1, y1 - width + 1, x1 - r - 1, y1), ink, 1 ) if not full_y: self.draw.draw_rectangle( (x0, y0 + r + 1, x0 + width - 1, y1 - r - 1), ink, 1 ) self.draw.draw_rectangle( (x1 - width + 1, y0 + r + 1, x1, y1 - r - 1), ink, 1 )
[ "def", "rounded_rectangle", "(", "self", ",", "xy", ",", "radius", "=", "0", ",", "fill", "=", "None", ",", "outline", "=", "None", ",", "width", "=", "1", ")", ":", "if", "isinstance", "(", "xy", "[", "0", "]", ",", "(", "list", ",", "tuple", ")", ")", ":", "(", "x0", ",", "y0", ")", ",", "(", "x1", ",", "y1", ")", "=", "xy", "else", ":", "x0", ",", "y0", ",", "x1", ",", "y1", "=", "xy", "d", "=", "radius", "*", "2", "full_x", "=", "d", ">=", "x1", "-", "x0", "if", "full_x", ":", "# The two left and two right corners are joined", "d", "=", "x1", "-", "x0", "full_y", "=", "d", ">=", "y1", "-", "y0", "if", "full_y", ":", "# The two top and two bottom corners are joined", "d", "=", "y1", "-", "y0", "if", "full_x", "and", "full_y", ":", "# If all corners are joined, that is a circle", "return", "self", ".", "ellipse", "(", "xy", ",", "fill", ",", "outline", ",", "width", ")", "if", "d", "==", "0", ":", "# If the corners have no curve, that is a rectangle", "return", "self", ".", "rectangle", "(", "xy", ",", "fill", ",", "outline", ",", "width", ")", "r", "=", "d", "//", "2", "ink", ",", "fill", "=", "self", ".", "_getink", "(", "outline", ",", "fill", ")", "def", "draw_corners", "(", "pieslice", ")", ":", "if", "full_x", ":", "# Draw top and bottom halves", "parts", "=", "(", "(", "(", "x0", ",", "y0", ",", "x0", "+", "d", ",", "y0", "+", "d", ")", ",", "180", ",", "360", ")", ",", "(", "(", "x0", ",", "y1", "-", "d", ",", "x0", "+", "d", ",", "y1", ")", ",", "0", ",", "180", ")", ",", ")", "elif", "full_y", ":", "# Draw left and right halves", "parts", "=", "(", "(", "(", "x0", ",", "y0", ",", "x0", "+", "d", ",", "y0", "+", "d", ")", ",", "90", ",", "270", ")", ",", "(", "(", "x1", "-", "d", ",", "y0", ",", "x1", ",", "y0", "+", "d", ")", ",", "270", ",", "90", ")", ",", ")", "else", ":", "# Draw four separate corners", "parts", "=", "(", "(", "(", "x1", "-", "d", ",", "y0", ",", "x1", ",", "y0", "+", "d", ")", ",", "270", ",", "360", ")", ",", "(", "(", "x1", "-", "d", ",", "y1", "-", "d", ",", "x1", ",", "y1", ")", ",", "0", ",", "90", ")", ",", "(", "(", "x0", ",", "y1", "-", "d", ",", "x0", "+", "d", ",", "y1", ")", ",", "90", ",", "180", ")", ",", "(", "(", "x0", ",", "y0", ",", "x0", "+", "d", ",", "y0", "+", "d", ")", ",", "180", ",", "270", ")", ",", ")", "for", "part", "in", "parts", ":", "if", "pieslice", ":", "self", ".", "draw", ".", "draw_pieslice", "(", "*", "(", "part", "+", "(", "fill", ",", "1", ")", ")", ")", "else", ":", "self", ".", "draw", ".", "draw_arc", "(", "*", "(", "part", "+", "(", "ink", ",", "width", ")", ")", ")", "if", "fill", "is", "not", "None", ":", "draw_corners", "(", "True", ")", "if", "full_x", ":", "self", ".", "draw", ".", "draw_rectangle", "(", "(", "x0", ",", "y0", "+", "r", "+", "1", ",", "x1", ",", "y1", "-", "r", "-", "1", ")", ",", "fill", ",", "1", ")", "else", ":", "self", ".", "draw", ".", "draw_rectangle", "(", "(", "x0", "+", "r", "+", "1", ",", "y0", ",", "x1", "-", "r", "-", "1", ",", "y1", ")", ",", "fill", ",", "1", ")", "if", "not", "full_x", "and", "not", "full_y", ":", "self", ".", "draw", ".", "draw_rectangle", "(", "(", "x0", ",", "y0", "+", "r", "+", "1", ",", "x0", "+", "r", ",", "y1", "-", "r", "-", "1", ")", ",", "fill", ",", "1", ")", "self", ".", "draw", ".", "draw_rectangle", "(", "(", "x1", "-", "r", ",", "y0", "+", "r", "+", "1", ",", "x1", ",", "y1", "-", "r", "-", "1", ")", ",", "fill", ",", "1", ")", "if", "ink", "is", "not", "None", "and", "ink", "!=", "fill", "and", "width", "!=", "0", ":", "draw_corners", "(", "False", ")", "if", "not", "full_x", ":", "self", ".", "draw", ".", "draw_rectangle", "(", "(", "x0", "+", "r", "+", "1", ",", "y0", ",", "x1", "-", "r", "-", "1", ",", "y0", "+", "width", "-", "1", ")", ",", "ink", ",", "1", ")", "self", ".", "draw", ".", "draw_rectangle", "(", "(", "x0", "+", "r", "+", "1", ",", "y1", "-", "width", "+", "1", ",", "x1", "-", "r", "-", "1", ",", "y1", ")", ",", "ink", ",", "1", ")", "if", "not", "full_y", ":", "self", ".", "draw", ".", "draw_rectangle", "(", "(", "x0", ",", "y0", "+", "r", "+", "1", ",", "x0", "+", "width", "-", "1", ",", "y1", "-", "r", "-", "1", ")", ",", "ink", ",", "1", ")", "self", ".", "draw", ".", "draw_rectangle", "(", "(", "x1", "-", "width", "+", "1", ",", "y0", "+", "r", "+", "1", ",", "x1", ",", "y1", "-", "r", "-", "1", ")", ",", "ink", ",", "1", ")" ]
[ 260, 4 ]
[ 341, 17 ]
python
en
['en', 'en', 'en']
True
ImageDraw.textsize
( self, text, font=None, spacing=4, direction=None, features=None, language=None, stroke_width=0, )
Get the size of a given string, in pixels.
Get the size of a given string, in pixels.
def textsize( self, text, font=None, spacing=4, direction=None, features=None, language=None, stroke_width=0, ): """Get the size of a given string, in pixels.""" if self._multiline_check(text): return self.multiline_textsize( text, font, spacing, direction, features, language, stroke_width ) if font is None: font = self.getfont() return font.getsize(text, direction, features, language, stroke_width)
[ "def", "textsize", "(", "self", ",", "text", ",", "font", "=", "None", ",", "spacing", "=", "4", ",", "direction", "=", "None", ",", "features", "=", "None", ",", "language", "=", "None", ",", "stroke_width", "=", "0", ",", ")", ":", "if", "self", ".", "_multiline_check", "(", "text", ")", ":", "return", "self", ".", "multiline_textsize", "(", "text", ",", "font", ",", "spacing", ",", "direction", ",", "features", ",", "language", ",", "stroke_width", ")", "if", "font", "is", "None", ":", "font", "=", "self", ".", "getfont", "(", ")", "return", "font", ".", "getsize", "(", "text", ",", "direction", ",", "features", ",", "language", ",", "stroke_width", ")" ]
[ 544, 4 ]
[ 562, 78 ]
python
en
['en', 'en', 'en']
True
ImageDraw.textlength
( self, text, font=None, direction=None, features=None, language=None, embedded_color=False, )
Get the length of a given string, in pixels with 1/64 precision.
Get the length of a given string, in pixels with 1/64 precision.
def textlength( self, text, font=None, direction=None, features=None, language=None, embedded_color=False, ): """Get the length of a given string, in pixels with 1/64 precision.""" if self._multiline_check(text): raise ValueError("can't measure length of multiline text") if embedded_color and self.mode not in ("RGB", "RGBA"): raise ValueError("Embedded color supported only in RGB and RGBA modes") if font is None: font = self.getfont() mode = "RGBA" if embedded_color else self.fontmode try: return font.getlength(text, mode, direction, features, language) except AttributeError: size = self.textsize( text, font, direction=direction, features=features, language=language ) if direction == "ttb": return size[1] return size[0]
[ "def", "textlength", "(", "self", ",", "text", ",", "font", "=", "None", ",", "direction", "=", "None", ",", "features", "=", "None", ",", "language", "=", "None", ",", "embedded_color", "=", "False", ",", ")", ":", "if", "self", ".", "_multiline_check", "(", "text", ")", ":", "raise", "ValueError", "(", "\"can't measure length of multiline text\"", ")", "if", "embedded_color", "and", "self", ".", "mode", "not", "in", "(", "\"RGB\"", ",", "\"RGBA\"", ")", ":", "raise", "ValueError", "(", "\"Embedded color supported only in RGB and RGBA modes\"", ")", "if", "font", "is", "None", ":", "font", "=", "self", ".", "getfont", "(", ")", "mode", "=", "\"RGBA\"", "if", "embedded_color", "else", "self", ".", "fontmode", "try", ":", "return", "font", ".", "getlength", "(", "text", ",", "mode", ",", "direction", ",", "features", ",", "language", ")", "except", "AttributeError", ":", "size", "=", "self", ".", "textsize", "(", "text", ",", "font", ",", "direction", "=", "direction", ",", "features", "=", "features", ",", "language", "=", "language", ")", "if", "direction", "==", "\"ttb\"", ":", "return", "size", "[", "1", "]", "return", "size", "[", "0", "]" ]
[ 586, 4 ]
[ 612, 26 ]
python
en
['en', 'en', 'en']
True
ImageDraw.textbbox
( self, xy, text, font=None, anchor=None, spacing=4, align="left", direction=None, features=None, language=None, stroke_width=0, embedded_color=False, )
Get the bounding box of a given string, in pixels.
Get the bounding box of a given string, in pixels.
def textbbox( self, xy, text, font=None, anchor=None, spacing=4, align="left", direction=None, features=None, language=None, stroke_width=0, embedded_color=False, ): """Get the bounding box of a given string, in pixels.""" if embedded_color and self.mode not in ("RGB", "RGBA"): raise ValueError("Embedded color supported only in RGB and RGBA modes") if self._multiline_check(text): return self.multiline_textbbox( xy, text, font, anchor, spacing, align, direction, features, language, stroke_width, embedded_color, ) if font is None: font = self.getfont() if not isinstance(font, ImageFont.FreeTypeFont): raise ValueError("Only supported for TrueType fonts") mode = "RGBA" if embedded_color else self.fontmode bbox = font.getbbox( text, mode, direction, features, language, stroke_width, anchor ) return bbox[0] + xy[0], bbox[1] + xy[1], bbox[2] + xy[0], bbox[3] + xy[1]
[ "def", "textbbox", "(", "self", ",", "xy", ",", "text", ",", "font", "=", "None", ",", "anchor", "=", "None", ",", "spacing", "=", "4", ",", "align", "=", "\"left\"", ",", "direction", "=", "None", ",", "features", "=", "None", ",", "language", "=", "None", ",", "stroke_width", "=", "0", ",", "embedded_color", "=", "False", ",", ")", ":", "if", "embedded_color", "and", "self", ".", "mode", "not", "in", "(", "\"RGB\"", ",", "\"RGBA\"", ")", ":", "raise", "ValueError", "(", "\"Embedded color supported only in RGB and RGBA modes\"", ")", "if", "self", ".", "_multiline_check", "(", "text", ")", ":", "return", "self", ".", "multiline_textbbox", "(", "xy", ",", "text", ",", "font", ",", "anchor", ",", "spacing", ",", "align", ",", "direction", ",", "features", ",", "language", ",", "stroke_width", ",", "embedded_color", ",", ")", "if", "font", "is", "None", ":", "font", "=", "self", ".", "getfont", "(", ")", "if", "not", "isinstance", "(", "font", ",", "ImageFont", ".", "FreeTypeFont", ")", ":", "raise", "ValueError", "(", "\"Only supported for TrueType fonts\"", ")", "mode", "=", "\"RGBA\"", "if", "embedded_color", "else", "self", ".", "fontmode", "bbox", "=", "font", ".", "getbbox", "(", "text", ",", "mode", ",", "direction", ",", "features", ",", "language", ",", "stroke_width", ",", "anchor", ")", "return", "bbox", "[", "0", "]", "+", "xy", "[", "0", "]", ",", "bbox", "[", "1", "]", "+", "xy", "[", "1", "]", ",", "bbox", "[", "2", "]", "+", "xy", "[", "0", "]", ",", "bbox", "[", "3", "]", "+", "xy", "[", "1", "]" ]
[ 614, 4 ]
[ 655, 81 ]
python
en
['en', 'en', 'en']
True
url_params_from_lookup_dict
(lookups)
Convert the type of lookups specified in a ForeignKey limit_choices_to attribute to a dictionary of query parameters
Convert the type of lookups specified in a ForeignKey limit_choices_to attribute to a dictionary of query parameters
def url_params_from_lookup_dict(lookups): """ Convert the type of lookups specified in a ForeignKey limit_choices_to attribute to a dictionary of query parameters """ params = {} if lookups and hasattr(lookups, 'items'): for k, v in lookups.items(): if callable(v): v = v() if isinstance(v, (tuple, list)): v = ','.join(str(x) for x in v) elif isinstance(v, bool): v = ('0', '1')[v] else: v = str(v) params[k] = v return params
[ "def", "url_params_from_lookup_dict", "(", "lookups", ")", ":", "params", "=", "{", "}", "if", "lookups", "and", "hasattr", "(", "lookups", ",", "'items'", ")", ":", "for", "k", ",", "v", "in", "lookups", ".", "items", "(", ")", ":", "if", "callable", "(", "v", ")", ":", "v", "=", "v", "(", ")", "if", "isinstance", "(", "v", ",", "(", "tuple", ",", "list", ")", ")", ":", "v", "=", "','", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "v", ")", "elif", "isinstance", "(", "v", ",", "bool", ")", ":", "v", "=", "(", "'0'", ",", "'1'", ")", "[", "v", "]", "else", ":", "v", "=", "str", "(", "v", ")", "params", "[", "k", "]", "=", "v", "return", "params" ]
[ 99, 0 ]
[ 116, 17 ]
python
en
['en', 'error', 'th']
False
AutocompleteMixin.build_attrs
(self, base_attrs, extra_attrs=None)
Set select2's AJAX attributes. Attributes can be set using the html5 data attribute. Nested attributes require a double dash as per https://select2.org/configuration/data-attributes#nested-subkey-options
Set select2's AJAX attributes.
def build_attrs(self, base_attrs, extra_attrs=None): """ Set select2's AJAX attributes. Attributes can be set using the html5 data attribute. Nested attributes require a double dash as per https://select2.org/configuration/data-attributes#nested-subkey-options """ attrs = super().build_attrs(base_attrs, extra_attrs=extra_attrs) attrs.setdefault('class', '') attrs.update({ 'data-ajax--cache': 'true', 'data-ajax--delay': 250, 'data-ajax--type': 'GET', 'data-ajax--url': self.get_url(), 'data-app-label': self.field.model._meta.app_label, 'data-model-name': self.field.model._meta.model_name, 'data-field-name': self.field.name, 'data-theme': 'admin-autocomplete', 'data-allow-clear': json.dumps(not self.is_required), 'data-placeholder': '', # Allows clearing of the input. 'class': attrs['class'] + (' ' if attrs['class'] else '') + 'admin-autocomplete', }) return attrs
[ "def", "build_attrs", "(", "self", ",", "base_attrs", ",", "extra_attrs", "=", "None", ")", ":", "attrs", "=", "super", "(", ")", ".", "build_attrs", "(", "base_attrs", ",", "extra_attrs", "=", "extra_attrs", ")", "attrs", ".", "setdefault", "(", "'class'", ",", "''", ")", "attrs", ".", "update", "(", "{", "'data-ajax--cache'", ":", "'true'", ",", "'data-ajax--delay'", ":", "250", ",", "'data-ajax--type'", ":", "'GET'", ",", "'data-ajax--url'", ":", "self", ".", "get_url", "(", ")", ",", "'data-app-label'", ":", "self", ".", "field", ".", "model", ".", "_meta", ".", "app_label", ",", "'data-model-name'", ":", "self", ".", "field", ".", "model", ".", "_meta", ".", "model_name", ",", "'data-field-name'", ":", "self", ".", "field", ".", "name", ",", "'data-theme'", ":", "'admin-autocomplete'", ",", "'data-allow-clear'", ":", "json", ".", "dumps", "(", "not", "self", ".", "is_required", ")", ",", "'data-placeholder'", ":", "''", ",", "# Allows clearing of the input.", "'class'", ":", "attrs", "[", "'class'", "]", "+", "(", "' '", "if", "attrs", "[", "'class'", "]", "else", "''", ")", "+", "'admin-autocomplete'", ",", "}", ")", "return", "attrs" ]
[ 394, 4 ]
[ 417, 20 ]
python
en
['en', 'error', 'th']
False
AutocompleteMixin.optgroups
(self, name, value, attr=None)
Return selected options based on the ModelChoiceIterator.
Return selected options based on the ModelChoiceIterator.
def optgroups(self, name, value, attr=None): """Return selected options based on the ModelChoiceIterator.""" default = (None, [], 0) groups = [default] has_selected = False selected_choices = { str(v) for v in value if str(v) not in self.choices.field.empty_values } if not self.is_required and not self.allow_multiple_selected: default[1].append(self.create_option(name, '', '', False, 0)) remote_model_opts = self.field.remote_field.model._meta to_field_name = getattr(self.field.remote_field, 'field_name', remote_model_opts.pk.attname) to_field_name = remote_model_opts.get_field(to_field_name).attname choices = ( (getattr(obj, to_field_name), self.choices.field.label_from_instance(obj)) for obj in self.choices.queryset.using(self.db).filter(**{'%s__in' % to_field_name: selected_choices}) ) for option_value, option_label in choices: selected = ( str(option_value) in value and (has_selected is False or self.allow_multiple_selected) ) has_selected |= selected index = len(default[1]) subgroup = default[1] subgroup.append(self.create_option(name, option_value, option_label, selected_choices, index)) return groups
[ "def", "optgroups", "(", "self", ",", "name", ",", "value", ",", "attr", "=", "None", ")", ":", "default", "=", "(", "None", ",", "[", "]", ",", "0", ")", "groups", "=", "[", "default", "]", "has_selected", "=", "False", "selected_choices", "=", "{", "str", "(", "v", ")", "for", "v", "in", "value", "if", "str", "(", "v", ")", "not", "in", "self", ".", "choices", ".", "field", ".", "empty_values", "}", "if", "not", "self", ".", "is_required", "and", "not", "self", ".", "allow_multiple_selected", ":", "default", "[", "1", "]", ".", "append", "(", "self", ".", "create_option", "(", "name", ",", "''", ",", "''", ",", "False", ",", "0", ")", ")", "remote_model_opts", "=", "self", ".", "field", ".", "remote_field", ".", "model", ".", "_meta", "to_field_name", "=", "getattr", "(", "self", ".", "field", ".", "remote_field", ",", "'field_name'", ",", "remote_model_opts", ".", "pk", ".", "attname", ")", "to_field_name", "=", "remote_model_opts", ".", "get_field", "(", "to_field_name", ")", ".", "attname", "choices", "=", "(", "(", "getattr", "(", "obj", ",", "to_field_name", ")", ",", "self", ".", "choices", ".", "field", ".", "label_from_instance", "(", "obj", ")", ")", "for", "obj", "in", "self", ".", "choices", ".", "queryset", ".", "using", "(", "self", ".", "db", ")", ".", "filter", "(", "*", "*", "{", "'%s__in'", "%", "to_field_name", ":", "selected_choices", "}", ")", ")", "for", "option_value", ",", "option_label", "in", "choices", ":", "selected", "=", "(", "str", "(", "option_value", ")", "in", "value", "and", "(", "has_selected", "is", "False", "or", "self", ".", "allow_multiple_selected", ")", ")", "has_selected", "|=", "selected", "index", "=", "len", "(", "default", "[", "1", "]", ")", "subgroup", "=", "default", "[", "1", "]", "subgroup", ".", "append", "(", "self", ".", "create_option", "(", "name", ",", "option_value", ",", "option_label", ",", "selected_choices", ",", "index", ")", ")", "return", "groups" ]
[ 419, 4 ]
[ 446, 21 ]
python
en
['en', 'en', 'en']
True
_should_retry_response
(resp_status, content)
Determines whether a response should be retried. Args: resp_status: The response status received. content: The response content body. Returns: True if the response should be retried, otherwise False.
Determines whether a response should be retried.
def _should_retry_response(resp_status, content): """Determines whether a response should be retried. Args: resp_status: The response status received. content: The response content body. Returns: True if the response should be retried, otherwise False. """ # Retry on 5xx errors. if resp_status >= 500: return True # Retry on 429 errors. if resp_status == _TOO_MANY_REQUESTS: return True # For 403 errors, we have to check for the `reason` in the response to # determine if we should retry. if resp_status == six.moves.http_client.FORBIDDEN: # If there's no details about the 403 type, don't retry. if not content: return False # Content is in JSON format. try: data = json.loads(content.decode('utf-8')) reason = data['error']['errors'][0]['reason'] except (UnicodeDecodeError, ValueError, KeyError): LOGGER.warning('Invalid JSON content from response: %s', content) return False LOGGER.warning('Encountered 403 Forbidden with reason "%s"', reason) # Only retry on rate limit related failures. if reason in ('userRateLimitExceeded', 'rateLimitExceeded', ): return True # Everything else is a success or non-retriable so break. return False
[ "def", "_should_retry_response", "(", "resp_status", ",", "content", ")", ":", "# Retry on 5xx errors.", "if", "resp_status", ">=", "500", ":", "return", "True", "# Retry on 429 errors.", "if", "resp_status", "==", "_TOO_MANY_REQUESTS", ":", "return", "True", "# For 403 errors, we have to check for the `reason` in the response to", "# determine if we should retry.", "if", "resp_status", "==", "six", ".", "moves", ".", "http_client", ".", "FORBIDDEN", ":", "# If there's no details about the 403 type, don't retry.", "if", "not", "content", ":", "return", "False", "# Content is in JSON format.", "try", ":", "data", "=", "json", ".", "loads", "(", "content", ".", "decode", "(", "'utf-8'", ")", ")", "reason", "=", "data", "[", "'error'", "]", "[", "'errors'", "]", "[", "0", "]", "[", "'reason'", "]", "except", "(", "UnicodeDecodeError", ",", "ValueError", ",", "KeyError", ")", ":", "LOGGER", ".", "warning", "(", "'Invalid JSON content from response: %s'", ",", "content", ")", "return", "False", "LOGGER", ".", "warning", "(", "'Encountered 403 Forbidden with reason \"%s\"'", ",", "reason", ")", "# Only retry on rate limit related failures.", "if", "reason", "in", "(", "'userRateLimitExceeded'", ",", "'rateLimitExceeded'", ",", ")", ":", "return", "True", "# Everything else is a success or non-retriable so break.", "return", "False" ]
[ 85, 0 ]
[ 125, 14 ]
python
en
['en', 'en', 'en']
True
_retry_request
(http, num_retries, req_type, sleep, rand, uri, method, *args, **kwargs)
Retries an HTTP request multiple times while handling errors. If after all retries the request still fails, last error is either returned as return value (for HTTP 5xx errors) or thrown (for ssl.SSLError). Args: http: Http object to be used to execute request. num_retries: Maximum number of retries. req_type: Type of the request (used for logging retries). sleep, rand: Functions to sleep for random time between retries. uri: URI to be requested. method: HTTP method to be used. args, kwargs: Additional arguments passed to http.request. Returns: resp, content - Response from the http request (may be HTTP 5xx).
Retries an HTTP request multiple times while handling errors.
def _retry_request(http, num_retries, req_type, sleep, rand, uri, method, *args, **kwargs): """Retries an HTTP request multiple times while handling errors. If after all retries the request still fails, last error is either returned as return value (for HTTP 5xx errors) or thrown (for ssl.SSLError). Args: http: Http object to be used to execute request. num_retries: Maximum number of retries. req_type: Type of the request (used for logging retries). sleep, rand: Functions to sleep for random time between retries. uri: URI to be requested. method: HTTP method to be used. args, kwargs: Additional arguments passed to http.request. Returns: resp, content - Response from the http request (may be HTTP 5xx). """ resp = None content = None for retry_num in range(num_retries + 1): if retry_num > 0: # Sleep before retrying. sleep_time = rand() * 2 ** retry_num LOGGER.warning( 'Sleeping %.2f seconds before retry %d of %d for %s: %s %s, after %s', sleep_time, retry_num, num_retries, req_type, method, uri, resp.status if resp else exception) sleep(sleep_time) try: exception = None resp, content = http.request(uri, method, *args, **kwargs) # Retry on SSL errors and socket timeout errors. except _ssl_SSLError as ssl_error: exception = ssl_error except socket.error as socket_error: # errno's contents differ by platform, so we have to match by name. if socket.errno.errorcode.get(socket_error.errno) not in ( 'WSAETIMEDOUT', 'ETIMEDOUT', 'EPIPE', 'ECONNABORTED', ): raise exception = socket_error if exception: if retry_num == num_retries: raise exception else: continue if not _should_retry_response(resp.status, content): break return resp, content
[ "def", "_retry_request", "(", "http", ",", "num_retries", ",", "req_type", ",", "sleep", ",", "rand", ",", "uri", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "resp", "=", "None", "content", "=", "None", "for", "retry_num", "in", "range", "(", "num_retries", "+", "1", ")", ":", "if", "retry_num", ">", "0", ":", "# Sleep before retrying.", "sleep_time", "=", "rand", "(", ")", "*", "2", "**", "retry_num", "LOGGER", ".", "warning", "(", "'Sleeping %.2f seconds before retry %d of %d for %s: %s %s, after %s'", ",", "sleep_time", ",", "retry_num", ",", "num_retries", ",", "req_type", ",", "method", ",", "uri", ",", "resp", ".", "status", "if", "resp", "else", "exception", ")", "sleep", "(", "sleep_time", ")", "try", ":", "exception", "=", "None", "resp", ",", "content", "=", "http", ".", "request", "(", "uri", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# Retry on SSL errors and socket timeout errors.", "except", "_ssl_SSLError", "as", "ssl_error", ":", "exception", "=", "ssl_error", "except", "socket", ".", "error", "as", "socket_error", ":", "# errno's contents differ by platform, so we have to match by name.", "if", "socket", ".", "errno", ".", "errorcode", ".", "get", "(", "socket_error", ".", "errno", ")", "not", "in", "(", "'WSAETIMEDOUT'", ",", "'ETIMEDOUT'", ",", "'EPIPE'", ",", "'ECONNABORTED'", ",", ")", ":", "raise", "exception", "=", "socket_error", "if", "exception", ":", "if", "retry_num", "==", "num_retries", ":", "raise", "exception", "else", ":", "continue", "if", "not", "_should_retry_response", "(", "resp", ".", "status", ",", "content", ")", ":", "break", "return", "resp", ",", "content" ]
[ 128, 0 ]
[ 181, 22 ]
python
en
['en', 'en', 'en']
True
set_user_agent
(http, user_agent)
Set the user-agent on every request. Args: http - An instance of httplib2.Http or something that acts like it. user_agent: string, the value for the user-agent header. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = set_user_agent(h, "my-app-name/6.0") Most of the time the user-agent will be set doing auth, this is for the rare cases where you are accessing an unauthenticated endpoint.
Set the user-agent on every request.
def set_user_agent(http, user_agent): """Set the user-agent on every request. Args: http - An instance of httplib2.Http or something that acts like it. user_agent: string, the value for the user-agent header. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = set_user_agent(h, "my-app-name/6.0") Most of the time the user-agent will be set doing auth, this is for the rare cases where you are accessing an unauthenticated endpoint. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the user-agent.""" if headers is None: headers = {} if 'user-agent' in headers: headers['user-agent'] = user_agent + ' ' + headers['user-agent'] else: headers['user-agent'] = user_agent resp, content = request_orig(uri, method, body, headers, redirections, connection_type) return resp, content http.request = new_request return http
[ "def", "set_user_agent", "(", "http", ",", "user_agent", ")", ":", "request_orig", "=", "http", ".", "request", "# The closure that will replace 'httplib2.Http.request'.", "def", "new_request", "(", "uri", ",", "method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "redirections", "=", "httplib2", ".", "DEFAULT_MAX_REDIRECTS", ",", "connection_type", "=", "None", ")", ":", "\"\"\"Modify the request headers to add the user-agent.\"\"\"", "if", "headers", "is", "None", ":", "headers", "=", "{", "}", "if", "'user-agent'", "in", "headers", ":", "headers", "[", "'user-agent'", "]", "=", "user_agent", "+", "' '", "+", "headers", "[", "'user-agent'", "]", "else", ":", "headers", "[", "'user-agent'", "]", "=", "user_agent", "resp", ",", "content", "=", "request_orig", "(", "uri", ",", "method", ",", "body", ",", "headers", ",", "redirections", ",", "connection_type", ")", "return", "resp", ",", "content", "http", ".", "request", "=", "new_request", "return", "http" ]
[ 1657, 0 ]
[ 1694, 13 ]
python
en
['en', 'en', 'en']
True
tunnel_patch
(http)
Tunnel PATCH requests over POST. Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = tunnel_patch(h, "my-app-name/6.0") Useful if you are running on a platform that doesn't support PATCH. Apply this last if you are using OAuth 1.0, as changing the method will result in a different signature.
Tunnel PATCH requests over POST. Args: http - An instance of httplib2.Http or something that acts like it.
def tunnel_patch(http): """Tunnel PATCH requests over POST. Args: http - An instance of httplib2.Http or something that acts like it. Returns: A modified instance of http that was passed in. Example: h = httplib2.Http() h = tunnel_patch(h, "my-app-name/6.0") Useful if you are running on a platform that doesn't support PATCH. Apply this last if you are using OAuth 1.0, as changing the method will result in a different signature. """ request_orig = http.request # The closure that will replace 'httplib2.Http.request'. def new_request(uri, method='GET', body=None, headers=None, redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): """Modify the request headers to add the user-agent.""" if headers is None: headers = {} if method == 'PATCH': if 'oauth_token' in headers.get('authorization', ''): LOGGER.warning( 'OAuth 1.0 request made with Credentials after tunnel_patch.') headers['x-http-method-override'] = "PATCH" method = 'POST' resp, content = request_orig(uri, method, body, headers, redirections, connection_type) return resp, content http.request = new_request return http
[ "def", "tunnel_patch", "(", "http", ")", ":", "request_orig", "=", "http", ".", "request", "# The closure that will replace 'httplib2.Http.request'.", "def", "new_request", "(", "uri", ",", "method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "redirections", "=", "httplib2", ".", "DEFAULT_MAX_REDIRECTS", ",", "connection_type", "=", "None", ")", ":", "\"\"\"Modify the request headers to add the user-agent.\"\"\"", "if", "headers", "is", "None", ":", "headers", "=", "{", "}", "if", "method", "==", "'PATCH'", ":", "if", "'oauth_token'", "in", "headers", ".", "get", "(", "'authorization'", ",", "''", ")", ":", "LOGGER", ".", "warning", "(", "'OAuth 1.0 request made with Credentials after tunnel_patch.'", ")", "headers", "[", "'x-http-method-override'", "]", "=", "\"PATCH\"", "method", "=", "'POST'", "resp", ",", "content", "=", "request_orig", "(", "uri", ",", "method", ",", "body", ",", "headers", ",", "redirections", ",", "connection_type", ")", "return", "resp", ",", "content", "http", ".", "request", "=", "new_request", "return", "http" ]
[ 1697, 0 ]
[ 1735, 13 ]
python
en
['en', 'en', 'en']
True
build_http
()
Builds httplib2.Http object Returns: A httplib2.Http object, which is used to make http requests, and which has timeout set by default. To override default timeout call socket.setdefaulttimeout(timeout_in_sec) before interacting with this method.
Builds httplib2.Http object
def build_http(): """Builds httplib2.Http object Returns: A httplib2.Http object, which is used to make http requests, and which has timeout set by default. To override default timeout call socket.setdefaulttimeout(timeout_in_sec) before interacting with this method. """ if socket.getdefaulttimeout() is not None: http_timeout = socket.getdefaulttimeout() else: http_timeout = DEFAULT_HTTP_TIMEOUT_SEC return httplib2.Http(timeout=http_timeout)
[ "def", "build_http", "(", ")", ":", "if", "socket", ".", "getdefaulttimeout", "(", ")", "is", "not", "None", ":", "http_timeout", "=", "socket", ".", "getdefaulttimeout", "(", ")", "else", ":", "http_timeout", "=", "DEFAULT_HTTP_TIMEOUT_SEC", "return", "httplib2", ".", "Http", "(", "timeout", "=", "http_timeout", ")" ]
[ 1738, 0 ]
[ 1753, 44 ]
python
en
['en', 'no', 'en']
True
MediaUploadProgress.__init__
(self, resumable_progress, total_size)
Constructor. Args: resumable_progress: int, bytes sent so far. total_size: int, total bytes in complete upload, or None if the total upload size isn't known ahead of time.
Constructor.
def __init__(self, resumable_progress, total_size): """Constructor. Args: resumable_progress: int, bytes sent so far. total_size: int, total bytes in complete upload, or None if the total upload size isn't known ahead of time. """ self.resumable_progress = resumable_progress self.total_size = total_size
[ "def", "__init__", "(", "self", ",", "resumable_progress", ",", "total_size", ")", ":", "self", ".", "resumable_progress", "=", "resumable_progress", "self", ".", "total_size", "=", "total_size" ]
[ 187, 2 ]
[ 196, 32 ]
python
en
['en', 'en', 'en']
False
MediaUploadProgress.progress
(self)
Percent of upload completed, as a float. Returns: the percentage complete as a float, returning 0.0 if the total size of the upload is unknown.
Percent of upload completed, as a float.
def progress(self): """Percent of upload completed, as a float. Returns: the percentage complete as a float, returning 0.0 if the total size of the upload is unknown. """ if self.total_size is not None: return float(self.resumable_progress) / float(self.total_size) else: return 0.0
[ "def", "progress", "(", "self", ")", ":", "if", "self", ".", "total_size", "is", "not", "None", ":", "return", "float", "(", "self", ".", "resumable_progress", ")", "/", "float", "(", "self", ".", "total_size", ")", "else", ":", "return", "0.0" ]
[ 198, 2 ]
[ 208, 16 ]
python
en
['en', 'en', 'en']
True
MediaDownloadProgress.__init__
(self, resumable_progress, total_size)
Constructor. Args: resumable_progress: int, bytes received so far. total_size: int, total bytes in complete download.
Constructor.
def __init__(self, resumable_progress, total_size): """Constructor. Args: resumable_progress: int, bytes received so far. total_size: int, total bytes in complete download. """ self.resumable_progress = resumable_progress self.total_size = total_size
[ "def", "__init__", "(", "self", ",", "resumable_progress", ",", "total_size", ")", ":", "self", ".", "resumable_progress", "=", "resumable_progress", "self", ".", "total_size", "=", "total_size" ]
[ 214, 2 ]
[ 222, 32 ]
python
en
['en', 'en', 'en']
False
MediaDownloadProgress.progress
(self)
Percent of download completed, as a float. Returns: the percentage complete as a float, returning 0.0 if the total size of the download is unknown.
Percent of download completed, as a float.
def progress(self): """Percent of download completed, as a float. Returns: the percentage complete as a float, returning 0.0 if the total size of the download is unknown. """ if self.total_size is not None: return float(self.resumable_progress) / float(self.total_size) else: return 0.0
[ "def", "progress", "(", "self", ")", ":", "if", "self", ".", "total_size", "is", "not", "None", ":", "return", "float", "(", "self", ".", "resumable_progress", ")", "/", "float", "(", "self", ".", "total_size", ")", "else", ":", "return", "0.0" ]
[ 224, 2 ]
[ 234, 16 ]
python
en
['en', 'en', 'en']
True
MediaUpload.chunksize
(self)
Chunk size for resumable uploads. Returns: Chunk size in bytes.
Chunk size for resumable uploads.
def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ raise NotImplementedError()
[ "def", "chunksize", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 264, 2 ]
[ 270, 31 ]
python
en
['en', 'zu', 'en']
True
MediaUpload.mimetype
(self)
Mime type of the body. Returns: Mime type.
Mime type of the body.
def mimetype(self): """Mime type of the body. Returns: Mime type. """ return 'application/octet-stream'
[ "def", "mimetype", "(", "self", ")", ":", "return", "'application/octet-stream'" ]
[ 272, 2 ]
[ 278, 37 ]
python
en
['en', 'en', 'en']
True
MediaUpload.size
(self)
Size of upload. Returns: Size of the body, or None of the size is unknown.
Size of upload.
def size(self): """Size of upload. Returns: Size of the body, or None of the size is unknown. """ return None
[ "def", "size", "(", "self", ")", ":", "return", "None" ]
[ 280, 2 ]
[ 286, 15 ]
python
en
['en', 'zu', 'en']
True
MediaUpload.resumable
(self)
Whether this upload is resumable. Returns: True if resumable upload or False.
Whether this upload is resumable.
def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return False
[ "def", "resumable", "(", "self", ")", ":", "return", "False" ]
[ 288, 2 ]
[ 294, 16 ]
python
en
['en', 'en', 'en']
True
MediaUpload.getbytes
(self, begin, end)
Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first.
Get bytes from the media.
def getbytes(self, begin, end): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorter than length if EOF was reached first. """ raise NotImplementedError()
[ "def", "getbytes", "(", "self", ",", "begin", ",", "end", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 296, 2 ]
[ 307, 31 ]
python
en
['en', 'en', 'en']
True
MediaUpload.has_stream
(self)
Does the underlying upload support a streaming interface. Streaming means it is an io.IOBase subclass that supports seek, i.e. seekable() returns True. Returns: True if the call to stream() will return an instance of a seekable io.Base subclass.
Does the underlying upload support a streaming interface.
def has_stream(self): """Does the underlying upload support a streaming interface. Streaming means it is an io.IOBase subclass that supports seek, i.e. seekable() returns True. Returns: True if the call to stream() will return an instance of a seekable io.Base subclass. """ return False
[ "def", "has_stream", "(", "self", ")", ":", "return", "False" ]
[ 309, 2 ]
[ 319, 16 ]
python
en
['en', 'en', 'en']
True
MediaUpload.stream
(self)
A stream interface to the data being uploaded. Returns: The returned value is an io.IOBase subclass that supports seek, i.e. seekable() returns True.
A stream interface to the data being uploaded.
def stream(self): """A stream interface to the data being uploaded. Returns: The returned value is an io.IOBase subclass that supports seek, i.e. seekable() returns True. """ raise NotImplementedError()
[ "def", "stream", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 321, 2 ]
[ 328, 31 ]
python
en
['en', 'en', 'en']
True
MediaUpload._to_json
(self, strip=None)
Utility function for creating a JSON representation of a MediaUpload. Args: strip: array, An array of names of members to not include in the JSON. Returns: string, a JSON representation of this instance, suitable to pass to from_json().
Utility function for creating a JSON representation of a MediaUpload.
def _to_json(self, strip=None): """Utility function for creating a JSON representation of a MediaUpload. Args: strip: array, An array of names of members to not include in the JSON. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ t = type(self) d = copy.copy(self.__dict__) if strip is not None: for member in strip: del d[member] d['_class'] = t.__name__ d['_module'] = t.__module__ return json.dumps(d)
[ "def", "_to_json", "(", "self", ",", "strip", "=", "None", ")", ":", "t", "=", "type", "(", "self", ")", "d", "=", "copy", ".", "copy", "(", "self", ".", "__dict__", ")", "if", "strip", "is", "not", "None", ":", "for", "member", "in", "strip", ":", "del", "d", "[", "member", "]", "d", "[", "'_class'", "]", "=", "t", ".", "__name__", "d", "[", "'_module'", "]", "=", "t", ".", "__module__", "return", "json", ".", "dumps", "(", "d", ")" ]
[ 331, 2 ]
[ 348, 24 ]
python
en
['en', 'en', 'en']
True
MediaUpload.to_json
(self)
Create a JSON representation of an instance of MediaUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json().
Create a JSON representation of an instance of MediaUpload.
def to_json(self): """Create a JSON representation of an instance of MediaUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json()
[ "def", "to_json", "(", "self", ")", ":", "return", "self", ".", "_to_json", "(", ")" ]
[ 350, 2 ]
[ 357, 26 ]
python
en
['en', 'en', 'en']
True
MediaUpload.new_from_json
(cls, s)
Utility class method to instantiate a MediaUpload subclass from a JSON representation produced by to_json(). Args: s: string, JSON from to_json(). Returns: An instance of the subclass of MediaUpload that was serialized with to_json().
Utility class method to instantiate a MediaUpload subclass from a JSON representation produced by to_json().
def new_from_json(cls, s): """Utility class method to instantiate a MediaUpload subclass from a JSON representation produced by to_json(). Args: s: string, JSON from to_json(). Returns: An instance of the subclass of MediaUpload that was serialized with to_json(). """ data = json.loads(s) # Find and call the right classmethod from_json() to restore the object. module = data['_module'] m = __import__(module, fromlist=module.split('.')[:-1]) kls = getattr(m, data['_class']) from_json = getattr(kls, 'from_json') return from_json(s)
[ "def", "new_from_json", "(", "cls", ",", "s", ")", ":", "data", "=", "json", ".", "loads", "(", "s", ")", "# Find and call the right classmethod from_json() to restore the object.", "module", "=", "data", "[", "'_module'", "]", "m", "=", "__import__", "(", "module", ",", "fromlist", "=", "module", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "kls", "=", "getattr", "(", "m", ",", "data", "[", "'_class'", "]", ")", "from_json", "=", "getattr", "(", "kls", ",", "'from_json'", ")", "return", "from_json", "(", "s", ")" ]
[ 360, 2 ]
[ 377, 23 ]
python
en
['en', 'en', 'en']
True
MediaIoBaseUpload.__init__
(self, fd, mimetype, chunksize=DEFAULT_CHUNK_SIZE, resumable=False)
Constructor. Args: fd: io.Base or file object, The source of the bytes to upload. MUST be opened in blocking mode, do not use streams opened in non-blocking mode. The given stream must be seekable, that is, it must be able to call seek() on fd. mimetype: string, Mime-type of the file. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. Pass in a value of -1 if the file is to be uploaded as a single chunk. Note that Google App Engine has a 5MB limit on request size, so you should never set your chunksize larger than 5MB, or to -1. resumable: bool, True if this is a resumable upload. False means upload in a single request.
Constructor.
def __init__(self, fd, mimetype, chunksize=DEFAULT_CHUNK_SIZE, resumable=False): """Constructor. Args: fd: io.Base or file object, The source of the bytes to upload. MUST be opened in blocking mode, do not use streams opened in non-blocking mode. The given stream must be seekable, that is, it must be able to call seek() on fd. mimetype: string, Mime-type of the file. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. Pass in a value of -1 if the file is to be uploaded as a single chunk. Note that Google App Engine has a 5MB limit on request size, so you should never set your chunksize larger than 5MB, or to -1. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ super(MediaIoBaseUpload, self).__init__() self._fd = fd self._mimetype = mimetype if not (chunksize == -1 or chunksize > 0): raise InvalidChunkSizeError() self._chunksize = chunksize self._resumable = resumable self._fd.seek(0, os.SEEK_END) self._size = self._fd.tell()
[ "def", "__init__", "(", "self", ",", "fd", ",", "mimetype", ",", "chunksize", "=", "DEFAULT_CHUNK_SIZE", ",", "resumable", "=", "False", ")", ":", "super", "(", "MediaIoBaseUpload", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "_fd", "=", "fd", "self", ".", "_mimetype", "=", "mimetype", "if", "not", "(", "chunksize", "==", "-", "1", "or", "chunksize", ">", "0", ")", ":", "raise", "InvalidChunkSizeError", "(", ")", "self", ".", "_chunksize", "=", "chunksize", "self", ".", "_resumable", "=", "resumable", "self", ".", "_fd", ".", "seek", "(", "0", ",", "os", ".", "SEEK_END", ")", "self", ".", "_size", "=", "self", ".", "_fd", ".", "tell", "(", ")" ]
[ 404, 2 ]
[ 431, 32 ]
python
en
['en', 'en', 'en']
False
MediaIoBaseUpload.chunksize
(self)
Chunk size for resumable uploads. Returns: Chunk size in bytes.
Chunk size for resumable uploads.
def chunksize(self): """Chunk size for resumable uploads. Returns: Chunk size in bytes. """ return self._chunksize
[ "def", "chunksize", "(", "self", ")", ":", "return", "self", ".", "_chunksize" ]
[ 433, 2 ]
[ 439, 26 ]
python
en
['en', 'zu', 'en']
True
MediaIoBaseUpload.mimetype
(self)
Mime type of the body. Returns: Mime type.
Mime type of the body.
def mimetype(self): """Mime type of the body. Returns: Mime type. """ return self._mimetype
[ "def", "mimetype", "(", "self", ")", ":", "return", "self", ".", "_mimetype" ]
[ 441, 2 ]
[ 447, 25 ]
python
en
['en', 'en', 'en']
True
MediaIoBaseUpload.size
(self)
Size of upload. Returns: Size of the body, or None of the size is unknown.
Size of upload.
def size(self): """Size of upload. Returns: Size of the body, or None of the size is unknown. """ return self._size
[ "def", "size", "(", "self", ")", ":", "return", "self", ".", "_size" ]
[ 449, 2 ]
[ 455, 21 ]
python
en
['en', 'zu', 'en']
True
MediaIoBaseUpload.resumable
(self)
Whether this upload is resumable. Returns: True if resumable upload or False.
Whether this upload is resumable.
def resumable(self): """Whether this upload is resumable. Returns: True if resumable upload or False. """ return self._resumable
[ "def", "resumable", "(", "self", ")", ":", "return", "self", ".", "_resumable" ]
[ 457, 2 ]
[ 463, 26 ]
python
en
['en', 'en', 'en']
True
MediaIoBaseUpload.getbytes
(self, begin, length)
Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorted than length if EOF was reached first.
Get bytes from the media.
def getbytes(self, begin, length): """Get bytes from the media. Args: begin: int, offset from beginning of file. length: int, number of bytes to read, starting at begin. Returns: A string of bytes read. May be shorted than length if EOF was reached first. """ self._fd.seek(begin) return self._fd.read(length)
[ "def", "getbytes", "(", "self", ",", "begin", ",", "length", ")", ":", "self", ".", "_fd", ".", "seek", "(", "begin", ")", "return", "self", ".", "_fd", ".", "read", "(", "length", ")" ]
[ 465, 2 ]
[ 477, 32 ]
python
en
['en', 'en', 'en']
True
MediaIoBaseUpload.has_stream
(self)
Does the underlying upload support a streaming interface. Streaming means it is an io.IOBase subclass that supports seek, i.e. seekable() returns True. Returns: True if the call to stream() will return an instance of a seekable io.Base subclass.
Does the underlying upload support a streaming interface.
def has_stream(self): """Does the underlying upload support a streaming interface. Streaming means it is an io.IOBase subclass that supports seek, i.e. seekable() returns True. Returns: True if the call to stream() will return an instance of a seekable io.Base subclass. """ return True
[ "def", "has_stream", "(", "self", ")", ":", "return", "True" ]
[ 479, 2 ]
[ 489, 15 ]
python
en
['en', 'en', 'en']
True
MediaIoBaseUpload.stream
(self)
A stream interface to the data being uploaded. Returns: The returned value is an io.IOBase subclass that supports seek, i.e. seekable() returns True.
A stream interface to the data being uploaded.
def stream(self): """A stream interface to the data being uploaded. Returns: The returned value is an io.IOBase subclass that supports seek, i.e. seekable() returns True. """ return self._fd
[ "def", "stream", "(", "self", ")", ":", "return", "self", ".", "_fd" ]
[ 491, 2 ]
[ 498, 19 ]
python
en
['en', 'en', 'en']
True
MediaIoBaseUpload.to_json
(self)
This upload type is not serializable.
This upload type is not serializable.
def to_json(self): """This upload type is not serializable.""" raise NotImplementedError('MediaIoBaseUpload is not serializable.')
[ "def", "to_json", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'MediaIoBaseUpload is not serializable.'", ")" ]
[ 500, 2 ]
[ 502, 71 ]
python
en
['en', 'en', 'en']
True
MediaFileUpload.__init__
(self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE, resumable=False)
Constructor. Args: filename: string, Name of the file. mimetype: string, Mime-type of the file. If None then a mime-type will be guessed from the file extension. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. Pass in a value of -1 if the file is to be uploaded in a single chunk. Note that Google App Engine has a 5MB limit on request size, so you should never set your chunksize larger than 5MB, or to -1. resumable: bool, True if this is a resumable upload. False means upload in a single request.
Constructor.
def __init__(self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE, resumable=False): """Constructor. Args: filename: string, Name of the file. mimetype: string, Mime-type of the file. If None then a mime-type will be guessed from the file extension. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. Pass in a value of -1 if the file is to be uploaded in a single chunk. Note that Google App Engine has a 5MB limit on request size, so you should never set your chunksize larger than 5MB, or to -1. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ self._filename = filename fd = open(self._filename, 'rb') if mimetype is None: # No mimetype provided, make a guess. mimetype, _ = mimetypes.guess_type(filename) if mimetype is None: # Guess failed, use octet-stream. mimetype = 'application/octet-stream' super(MediaFileUpload, self).__init__(fd, mimetype, chunksize=chunksize, resumable=resumable)
[ "def", "__init__", "(", "self", ",", "filename", ",", "mimetype", "=", "None", ",", "chunksize", "=", "DEFAULT_CHUNK_SIZE", ",", "resumable", "=", "False", ")", ":", "self", ".", "_filename", "=", "filename", "fd", "=", "open", "(", "self", ".", "_filename", ",", "'rb'", ")", "if", "mimetype", "is", "None", ":", "# No mimetype provided, make a guess.", "mimetype", ",", "_", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "if", "mimetype", "is", "None", ":", "# Guess failed, use octet-stream.", "mimetype", "=", "'application/octet-stream'", "super", "(", "MediaFileUpload", ",", "self", ")", ".", "__init__", "(", "fd", ",", "mimetype", ",", "chunksize", "=", "chunksize", ",", "resumable", "=", "resumable", ")" ]
[ 529, 2 ]
[ 554, 62 ]
python
en
['en', 'en', 'en']
False
MediaFileUpload.to_json
(self)
Creating a JSON representation of an instance of MediaFileUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json().
Creating a JSON representation of an instance of MediaFileUpload.
def to_json(self): """Creating a JSON representation of an instance of MediaFileUpload. Returns: string, a JSON representation of this instance, suitable to pass to from_json(). """ return self._to_json(strip=['_fd'])
[ "def", "to_json", "(", "self", ")", ":", "return", "self", ".", "_to_json", "(", "strip", "=", "[", "'_fd'", "]", ")" ]
[ 556, 2 ]
[ 563, 39 ]
python
en
['en', 'en', 'en']
True
MediaInMemoryUpload.__init__
(self, body, mimetype='application/octet-stream', chunksize=DEFAULT_CHUNK_SIZE, resumable=False)
Create a new MediaInMemoryUpload. DEPRECATED: Use MediaIoBaseUpload with either io.TextIOBase or StringIO for the stream. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request.
Create a new MediaInMemoryUpload.
def __init__(self, body, mimetype='application/octet-stream', chunksize=DEFAULT_CHUNK_SIZE, resumable=False): """Create a new MediaInMemoryUpload. DEPRECATED: Use MediaIoBaseUpload with either io.TextIOBase or StringIO for the stream. Args: body: string, Bytes of body content. mimetype: string, Mime-type of the file or default of 'application/octet-stream'. chunksize: int, File will be uploaded in chunks of this many bytes. Only used if resumable=True. resumable: bool, True if this is a resumable upload. False means upload in a single request. """ fd = BytesIO(body) super(MediaInMemoryUpload, self).__init__(fd, mimetype, chunksize=chunksize, resumable=resumable)
[ "def", "__init__", "(", "self", ",", "body", ",", "mimetype", "=", "'application/octet-stream'", ",", "chunksize", "=", "DEFAULT_CHUNK_SIZE", ",", "resumable", "=", "False", ")", ":", "fd", "=", "BytesIO", "(", "body", ")", "super", "(", "MediaInMemoryUpload", ",", "self", ")", ".", "__init__", "(", "fd", ",", "mimetype", ",", "chunksize", "=", "chunksize", ",", "resumable", "=", "resumable", ")" ]
[ 580, 2 ]
[ 598, 66 ]
python
en
['en', 'sn', 'en']
True
MediaIoBaseDownload.__init__
(self, fd, request, chunksize=DEFAULT_CHUNK_SIZE)
Constructor. Args: fd: io.Base or file object, The stream in which to write the downloaded bytes. request: googleapiclient.http.HttpRequest, the media request to perform in chunks. chunksize: int, File will be downloaded in chunks of this many bytes.
Constructor.
def __init__(self, fd, request, chunksize=DEFAULT_CHUNK_SIZE): """Constructor. Args: fd: io.Base or file object, The stream in which to write the downloaded bytes. request: googleapiclient.http.HttpRequest, the media request to perform in chunks. chunksize: int, File will be downloaded in chunks of this many bytes. """ self._fd = fd self._request = request self._uri = request.uri self._chunksize = chunksize self._progress = 0 self._total_size = None self._done = False # Stubs for testing. self._sleep = time.sleep self._rand = random.random
[ "def", "__init__", "(", "self", ",", "fd", ",", "request", ",", "chunksize", "=", "DEFAULT_CHUNK_SIZE", ")", ":", "self", ".", "_fd", "=", "fd", "self", ".", "_request", "=", "request", "self", ".", "_uri", "=", "request", ".", "uri", "self", ".", "_chunksize", "=", "chunksize", "self", ".", "_progress", "=", "0", "self", ".", "_total_size", "=", "None", "self", ".", "_done", "=", "False", "# Stubs for testing.", "self", ".", "_sleep", "=", "time", ".", "sleep", "self", ".", "_rand", "=", "random", ".", "random" ]
[ 622, 2 ]
[ 642, 30 ]
python
en
['en', 'en', 'en']
False
MediaIoBaseDownload.next_chunk
(self, num_retries=0)
Get the next chunk of the download. Args: num_retries: Integer, number of times to retry with randomized exponential backoff. If all retries fail, the raised HttpError represents the last request. If zero (default), we attempt the request only once. Returns: (status, done): (MediaDownloadStatus, boolean) The value of 'done' will be True when the media has been fully downloaded. Raises: googleapiclient.errors.HttpError if the response was not a 2xx. httplib2.HttpLib2Error if a transport error has occured.
Get the next chunk of the download.
def next_chunk(self, num_retries=0): """Get the next chunk of the download. Args: num_retries: Integer, number of times to retry with randomized exponential backoff. If all retries fail, the raised HttpError represents the last request. If zero (default), we attempt the request only once. Returns: (status, done): (MediaDownloadStatus, boolean) The value of 'done' will be True when the media has been fully downloaded. Raises: googleapiclient.errors.HttpError if the response was not a 2xx. httplib2.HttpLib2Error if a transport error has occured. """ headers = { 'range': 'bytes=%d-%d' % ( self._progress, self._progress + self._chunksize) } http = self._request.http resp, content = _retry_request( http, num_retries, 'media download', self._sleep, self._rand, self._uri, 'GET', headers=headers) if resp.status in [200, 206]: if 'content-location' in resp and resp['content-location'] != self._uri: self._uri = resp['content-location'] self._progress += len(content) self._fd.write(content) if 'content-range' in resp: content_range = resp['content-range'] length = content_range.rsplit('/', 1)[1] self._total_size = int(length) elif 'content-length' in resp: self._total_size = int(resp['content-length']) if self._progress == self._total_size: self._done = True return MediaDownloadProgress(self._progress, self._total_size), self._done else: raise HttpError(resp, content, uri=self._uri)
[ "def", "next_chunk", "(", "self", ",", "num_retries", "=", "0", ")", ":", "headers", "=", "{", "'range'", ":", "'bytes=%d-%d'", "%", "(", "self", ".", "_progress", ",", "self", ".", "_progress", "+", "self", ".", "_chunksize", ")", "}", "http", "=", "self", ".", "_request", ".", "http", "resp", ",", "content", "=", "_retry_request", "(", "http", ",", "num_retries", ",", "'media download'", ",", "self", ".", "_sleep", ",", "self", ".", "_rand", ",", "self", ".", "_uri", ",", "'GET'", ",", "headers", "=", "headers", ")", "if", "resp", ".", "status", "in", "[", "200", ",", "206", "]", ":", "if", "'content-location'", "in", "resp", "and", "resp", "[", "'content-location'", "]", "!=", "self", ".", "_uri", ":", "self", ".", "_uri", "=", "resp", "[", "'content-location'", "]", "self", ".", "_progress", "+=", "len", "(", "content", ")", "self", ".", "_fd", ".", "write", "(", "content", ")", "if", "'content-range'", "in", "resp", ":", "content_range", "=", "resp", "[", "'content-range'", "]", "length", "=", "content_range", ".", "rsplit", "(", "'/'", ",", "1", ")", "[", "1", "]", "self", ".", "_total_size", "=", "int", "(", "length", ")", "elif", "'content-length'", "in", "resp", ":", "self", ".", "_total_size", "=", "int", "(", "resp", "[", "'content-length'", "]", ")", "if", "self", ".", "_progress", "==", "self", ".", "_total_size", ":", "self", ".", "_done", "=", "True", "return", "MediaDownloadProgress", "(", "self", ".", "_progress", ",", "self", ".", "_total_size", ")", ",", "self", ".", "_done", "else", ":", "raise", "HttpError", "(", "resp", ",", "content", ",", "uri", "=", "self", ".", "_uri", ")" ]
[ 645, 2 ]
[ 690, 51 ]
python
en
['en', 'en', 'en']
True
_StreamSlice.__init__
(self, stream, begin, chunksize)
Constructor. Args: stream: (io.Base, file object), the stream to wrap. begin: int, the seek position the chunk begins at. chunksize: int, the size of the chunk.
Constructor.
def __init__(self, stream, begin, chunksize): """Constructor. Args: stream: (io.Base, file object), the stream to wrap. begin: int, the seek position the chunk begins at. chunksize: int, the size of the chunk. """ self._stream = stream self._begin = begin self._chunksize = chunksize self._stream.seek(begin)
[ "def", "__init__", "(", "self", ",", "stream", ",", "begin", ",", "chunksize", ")", ":", "self", ".", "_stream", "=", "stream", "self", ".", "_begin", "=", "begin", "self", ".", "_chunksize", "=", "chunksize", "self", ".", "_stream", ".", "seek", "(", "begin", ")" ]
[ 703, 2 ]
[ 714, 28 ]
python
en
['en', 'en', 'en']
False
_StreamSlice.read
(self, n=-1)
Read n bytes. Args: n, int, the number of bytes to read. Returns: A string of length 'n', or less if EOF is reached.
Read n bytes.
def read(self, n=-1): """Read n bytes. Args: n, int, the number of bytes to read. Returns: A string of length 'n', or less if EOF is reached. """ # The data left available to read sits in [cur, end) cur = self._stream.tell() end = self._begin + self._chunksize if n == -1 or cur + n > end: n = end - cur return self._stream.read(n)
[ "def", "read", "(", "self", ",", "n", "=", "-", "1", ")", ":", "# The data left available to read sits in [cur, end)", "cur", "=", "self", ".", "_stream", ".", "tell", "(", ")", "end", "=", "self", ".", "_begin", "+", "self", ".", "_chunksize", "if", "n", "==", "-", "1", "or", "cur", "+", "n", ">", "end", ":", "n", "=", "end", "-", "cur", "return", "self", ".", "_stream", ".", "read", "(", "n", ")" ]
[ 716, 2 ]
[ 730, 31 ]
python
en
['en', 'cy', 'en']
True
HttpRequest.__init__
(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None)
Constructor for an HttpRequest. Args: http: httplib2.Http, the transport object to use to make a request postproc: callable, called on the HTTP response and content to transform it into a data object before returning, or raising an exception on an error. uri: string, the absolute URI to send the request to method: string, the HTTP method to use body: string, the request body of the HTTP request, headers: dict, the HTTP request headers methodId: string, a unique identifier for the API method being called. resumable: MediaUpload, None if this is not a resumbale request.
Constructor for an HttpRequest.
def __init__(self, http, postproc, uri, method='GET', body=None, headers=None, methodId=None, resumable=None): """Constructor for an HttpRequest. Args: http: httplib2.Http, the transport object to use to make a request postproc: callable, called on the HTTP response and content to transform it into a data object before returning, or raising an exception on an error. uri: string, the absolute URI to send the request to method: string, the HTTP method to use body: string, the request body of the HTTP request, headers: dict, the HTTP request headers methodId: string, a unique identifier for the API method being called. resumable: MediaUpload, None if this is not a resumbale request. """ self.uri = uri self.method = method self.body = body self.headers = headers or {} self.methodId = methodId self.http = http self.postproc = postproc self.resumable = resumable self.response_callbacks = [] self._in_error_state = False # Pull the multipart boundary out of the content-type header. major, minor, params = mimeparse.parse_mime_type( self.headers.get('content-type', 'application/json')) # The size of the non-media part of the request. self.body_size = len(self.body or '') # The resumable URI to send chunks to. self.resumable_uri = None # The bytes that have been uploaded. self.resumable_progress = 0 # Stubs for testing. self._rand = random.random self._sleep = time.sleep
[ "def", "__init__", "(", "self", ",", "http", ",", "postproc", ",", "uri", ",", "method", "=", "'GET'", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "methodId", "=", "None", ",", "resumable", "=", "None", ")", ":", "self", ".", "uri", "=", "uri", "self", ".", "method", "=", "method", "self", ".", "body", "=", "body", "self", ".", "headers", "=", "headers", "or", "{", "}", "self", ".", "methodId", "=", "methodId", "self", ".", "http", "=", "http", "self", ".", "postproc", "=", "postproc", "self", ".", "resumable", "=", "resumable", "self", ".", "response_callbacks", "=", "[", "]", "self", ".", "_in_error_state", "=", "False", "# Pull the multipart boundary out of the content-type header.", "major", ",", "minor", ",", "params", "=", "mimeparse", ".", "parse_mime_type", "(", "self", ".", "headers", ".", "get", "(", "'content-type'", ",", "'application/json'", ")", ")", "# The size of the non-media part of the request.", "self", ".", "body_size", "=", "len", "(", "self", ".", "body", "or", "''", ")", "# The resumable URI to send chunks to.", "self", ".", "resumable_uri", "=", "None", "# The bytes that have been uploaded.", "self", ".", "resumable_progress", "=", "0", "# Stubs for testing.", "self", ".", "_rand", "=", "random", ".", "random", "self", ".", "_sleep", "=", "time", ".", "sleep" ]
[ 737, 2 ]
[ 783, 28 ]
python
en
['en', 'en', 'en']
True
HttpRequest.execute
(self, http=None, num_retries=0)
Execute the request. Args: http: httplib2.Http, an http object to be used in place of the one the HttpRequest request object was constructed with. num_retries: Integer, number of times to retry with randomized exponential backoff. If all retries fail, the raised HttpError represents the last request. If zero (default), we attempt the request only once. Returns: A deserialized object model of the response body as determined by the postproc. Raises: googleapiclient.errors.HttpError if the response was not a 2xx. httplib2.HttpLib2Error if a transport error has occured.
Execute the request.
def execute(self, http=None, num_retries=0): """Execute the request. Args: http: httplib2.Http, an http object to be used in place of the one the HttpRequest request object was constructed with. num_retries: Integer, number of times to retry with randomized exponential backoff. If all retries fail, the raised HttpError represents the last request. If zero (default), we attempt the request only once. Returns: A deserialized object model of the response body as determined by the postproc. Raises: googleapiclient.errors.HttpError if the response was not a 2xx. httplib2.HttpLib2Error if a transport error has occured. """ if http is None: http = self.http if self.resumable: body = None while body is None: _, body = self.next_chunk(http=http, num_retries=num_retries) return body # Non-resumable case. if 'content-length' not in self.headers: self.headers['content-length'] = str(self.body_size) # If the request URI is too long then turn it into a POST request. if len(self.uri) > MAX_URI_LENGTH and self.method == 'GET': self.method = 'POST' self.headers['x-http-method-override'] = 'GET' self.headers['content-type'] = 'application/x-www-form-urlencoded' parsed = urlparse(self.uri) self.uri = urlunparse( (parsed.scheme, parsed.netloc, parsed.path, parsed.params, None, None) ) self.body = parsed.query self.headers['content-length'] = str(len(self.body)) # Handle retries for server-side errors. resp, content = _retry_request( http, num_retries, 'request', self._sleep, self._rand, str(self.uri), method=str(self.method), body=self.body, headers=self.headers) for callback in self.response_callbacks: callback(resp) if resp.status >= 300: raise HttpError(resp, content, uri=self.uri) return self.postproc(resp, content)
[ "def", "execute", "(", "self", ",", "http", "=", "None", ",", "num_retries", "=", "0", ")", ":", "if", "http", "is", "None", ":", "http", "=", "self", ".", "http", "if", "self", ".", "resumable", ":", "body", "=", "None", "while", "body", "is", "None", ":", "_", ",", "body", "=", "self", ".", "next_chunk", "(", "http", "=", "http", ",", "num_retries", "=", "num_retries", ")", "return", "body", "# Non-resumable case.", "if", "'content-length'", "not", "in", "self", ".", "headers", ":", "self", ".", "headers", "[", "'content-length'", "]", "=", "str", "(", "self", ".", "body_size", ")", "# If the request URI is too long then turn it into a POST request.", "if", "len", "(", "self", ".", "uri", ")", ">", "MAX_URI_LENGTH", "and", "self", ".", "method", "==", "'GET'", ":", "self", ".", "method", "=", "'POST'", "self", ".", "headers", "[", "'x-http-method-override'", "]", "=", "'GET'", "self", ".", "headers", "[", "'content-type'", "]", "=", "'application/x-www-form-urlencoded'", "parsed", "=", "urlparse", "(", "self", ".", "uri", ")", "self", ".", "uri", "=", "urlunparse", "(", "(", "parsed", ".", "scheme", ",", "parsed", ".", "netloc", ",", "parsed", ".", "path", ",", "parsed", ".", "params", ",", "None", ",", "None", ")", ")", "self", ".", "body", "=", "parsed", ".", "query", "self", ".", "headers", "[", "'content-length'", "]", "=", "str", "(", "len", "(", "self", ".", "body", ")", ")", "# Handle retries for server-side errors.", "resp", ",", "content", "=", "_retry_request", "(", "http", ",", "num_retries", ",", "'request'", ",", "self", ".", "_sleep", ",", "self", ".", "_rand", ",", "str", "(", "self", ".", "uri", ")", ",", "method", "=", "str", "(", "self", ".", "method", ")", ",", "body", "=", "self", ".", "body", ",", "headers", "=", "self", ".", "headers", ")", "for", "callback", "in", "self", ".", "response_callbacks", ":", "callback", "(", "resp", ")", "if", "resp", ".", "status", ">=", "300", ":", "raise", "HttpError", "(", "resp", ",", "content", ",", "uri", "=", "self", ".", "uri", ")", "return", "self", ".", "postproc", "(", "resp", ",", "content", ")" ]
[ 786, 2 ]
[ 840, 39 ]
python
en
['en', 'en', 'en']
True
HttpRequest.add_response_callback
(self, cb)
add_response_headers_callback Args: cb: Callback to be called on receiving the response headers, of signature: def cb(resp): # Where resp is an instance of httplib2.Response
add_response_headers_callback
def add_response_callback(self, cb): """add_response_headers_callback Args: cb: Callback to be called on receiving the response headers, of signature: def cb(resp): # Where resp is an instance of httplib2.Response """ self.response_callbacks.append(cb)
[ "def", "add_response_callback", "(", "self", ",", "cb", ")", ":", "self", ".", "response_callbacks", ".", "append", "(", "cb", ")" ]
[ 843, 2 ]
[ 852, 38 ]
python
en
['en', 'ko', 'en']
False
HttpRequest.next_chunk
(self, http=None, num_retries=0)
Execute the next step of a resumable upload. Can only be used if the method being executed supports media uploads and the MediaUpload object passed in was flagged as using resumable upload. Example: media = MediaFileUpload('cow.png', mimetype='image/png', chunksize=1000, resumable=True) request = farm.animals().insert( id='cow', name='cow.png', media_body=media) response = None while response is None: status, response = request.next_chunk() if status: print "Upload %d%% complete." % int(status.progress() * 100) Args: http: httplib2.Http, an http object to be used in place of the one the HttpRequest request object was constructed with. num_retries: Integer, number of times to retry with randomized exponential backoff. If all retries fail, the raised HttpError represents the last request. If zero (default), we attempt the request only once. Returns: (status, body): (ResumableMediaStatus, object) The body will be None until the resumable media is fully uploaded. Raises: googleapiclient.errors.HttpError if the response was not a 2xx. httplib2.HttpLib2Error if a transport error has occured.
Execute the next step of a resumable upload.
def next_chunk(self, http=None, num_retries=0): """Execute the next step of a resumable upload. Can only be used if the method being executed supports media uploads and the MediaUpload object passed in was flagged as using resumable upload. Example: media = MediaFileUpload('cow.png', mimetype='image/png', chunksize=1000, resumable=True) request = farm.animals().insert( id='cow', name='cow.png', media_body=media) response = None while response is None: status, response = request.next_chunk() if status: print "Upload %d%% complete." % int(status.progress() * 100) Args: http: httplib2.Http, an http object to be used in place of the one the HttpRequest request object was constructed with. num_retries: Integer, number of times to retry with randomized exponential backoff. If all retries fail, the raised HttpError represents the last request. If zero (default), we attempt the request only once. Returns: (status, body): (ResumableMediaStatus, object) The body will be None until the resumable media is fully uploaded. Raises: googleapiclient.errors.HttpError if the response was not a 2xx. httplib2.HttpLib2Error if a transport error has occured. """ if http is None: http = self.http if self.resumable.size() is None: size = '*' else: size = str(self.resumable.size()) if self.resumable_uri is None: start_headers = copy.copy(self.headers) start_headers['X-Upload-Content-Type'] = self.resumable.mimetype() if size != '*': start_headers['X-Upload-Content-Length'] = size start_headers['content-length'] = str(self.body_size) resp, content = _retry_request( http, num_retries, 'resumable URI request', self._sleep, self._rand, self.uri, method=self.method, body=self.body, headers=start_headers) if resp.status == 200 and 'location' in resp: self.resumable_uri = resp['location'] else: raise ResumableUploadError(resp, content) elif self._in_error_state: # If we are in an error state then query the server for current state of # the upload by sending an empty PUT and reading the 'range' header in # the response. headers = { 'Content-Range': 'bytes */%s' % size, 'content-length': '0' } resp, content = http.request(self.resumable_uri, 'PUT', headers=headers) status, body = self._process_response(resp, content) if body: # The upload was complete. return (status, body) if self.resumable.has_stream(): data = self.resumable.stream() if self.resumable.chunksize() == -1: data.seek(self.resumable_progress) chunk_end = self.resumable.size() - self.resumable_progress - 1 else: # Doing chunking with a stream, so wrap a slice of the stream. data = _StreamSlice(data, self.resumable_progress, self.resumable.chunksize()) chunk_end = min( self.resumable_progress + self.resumable.chunksize() - 1, self.resumable.size() - 1) else: data = self.resumable.getbytes( self.resumable_progress, self.resumable.chunksize()) # A short read implies that we are at EOF, so finish the upload. if len(data) < self.resumable.chunksize(): size = str(self.resumable_progress + len(data)) chunk_end = self.resumable_progress + len(data) - 1 headers = { 'Content-Range': 'bytes %d-%d/%s' % ( self.resumable_progress, chunk_end, size), # Must set the content-length header here because httplib can't # calculate the size when working with _StreamSlice. 'Content-Length': str(chunk_end - self.resumable_progress + 1) } for retry_num in range(num_retries + 1): if retry_num > 0: self._sleep(self._rand() * 2**retry_num) LOGGER.warning( 'Retry #%d for media upload: %s %s, following status: %d' % (retry_num, self.method, self.uri, resp.status)) try: resp, content = http.request(self.resumable_uri, method='PUT', body=data, headers=headers) except: self._in_error_state = True raise if not _should_retry_response(resp.status, content): break return self._process_response(resp, content)
[ "def", "next_chunk", "(", "self", ",", "http", "=", "None", ",", "num_retries", "=", "0", ")", ":", "if", "http", "is", "None", ":", "http", "=", "self", ".", "http", "if", "self", ".", "resumable", ".", "size", "(", ")", "is", "None", ":", "size", "=", "'*'", "else", ":", "size", "=", "str", "(", "self", ".", "resumable", ".", "size", "(", ")", ")", "if", "self", ".", "resumable_uri", "is", "None", ":", "start_headers", "=", "copy", ".", "copy", "(", "self", ".", "headers", ")", "start_headers", "[", "'X-Upload-Content-Type'", "]", "=", "self", ".", "resumable", ".", "mimetype", "(", ")", "if", "size", "!=", "'*'", ":", "start_headers", "[", "'X-Upload-Content-Length'", "]", "=", "size", "start_headers", "[", "'content-length'", "]", "=", "str", "(", "self", ".", "body_size", ")", "resp", ",", "content", "=", "_retry_request", "(", "http", ",", "num_retries", ",", "'resumable URI request'", ",", "self", ".", "_sleep", ",", "self", ".", "_rand", ",", "self", ".", "uri", ",", "method", "=", "self", ".", "method", ",", "body", "=", "self", ".", "body", ",", "headers", "=", "start_headers", ")", "if", "resp", ".", "status", "==", "200", "and", "'location'", "in", "resp", ":", "self", ".", "resumable_uri", "=", "resp", "[", "'location'", "]", "else", ":", "raise", "ResumableUploadError", "(", "resp", ",", "content", ")", "elif", "self", ".", "_in_error_state", ":", "# If we are in an error state then query the server for current state of", "# the upload by sending an empty PUT and reading the 'range' header in", "# the response.", "headers", "=", "{", "'Content-Range'", ":", "'bytes */%s'", "%", "size", ",", "'content-length'", ":", "'0'", "}", "resp", ",", "content", "=", "http", ".", "request", "(", "self", ".", "resumable_uri", ",", "'PUT'", ",", "headers", "=", "headers", ")", "status", ",", "body", "=", "self", ".", "_process_response", "(", "resp", ",", "content", ")", "if", "body", ":", "# The upload was complete.", "return", "(", "status", ",", "body", ")", "if", "self", ".", "resumable", ".", "has_stream", "(", ")", ":", "data", "=", "self", ".", "resumable", ".", "stream", "(", ")", "if", "self", ".", "resumable", ".", "chunksize", "(", ")", "==", "-", "1", ":", "data", ".", "seek", "(", "self", ".", "resumable_progress", ")", "chunk_end", "=", "self", ".", "resumable", ".", "size", "(", ")", "-", "self", ".", "resumable_progress", "-", "1", "else", ":", "# Doing chunking with a stream, so wrap a slice of the stream.", "data", "=", "_StreamSlice", "(", "data", ",", "self", ".", "resumable_progress", ",", "self", ".", "resumable", ".", "chunksize", "(", ")", ")", "chunk_end", "=", "min", "(", "self", ".", "resumable_progress", "+", "self", ".", "resumable", ".", "chunksize", "(", ")", "-", "1", ",", "self", ".", "resumable", ".", "size", "(", ")", "-", "1", ")", "else", ":", "data", "=", "self", ".", "resumable", ".", "getbytes", "(", "self", ".", "resumable_progress", ",", "self", ".", "resumable", ".", "chunksize", "(", ")", ")", "# A short read implies that we are at EOF, so finish the upload.", "if", "len", "(", "data", ")", "<", "self", ".", "resumable", ".", "chunksize", "(", ")", ":", "size", "=", "str", "(", "self", ".", "resumable_progress", "+", "len", "(", "data", ")", ")", "chunk_end", "=", "self", ".", "resumable_progress", "+", "len", "(", "data", ")", "-", "1", "headers", "=", "{", "'Content-Range'", ":", "'bytes %d-%d/%s'", "%", "(", "self", ".", "resumable_progress", ",", "chunk_end", ",", "size", ")", ",", "# Must set the content-length header here because httplib can't", "# calculate the size when working with _StreamSlice.", "'Content-Length'", ":", "str", "(", "chunk_end", "-", "self", ".", "resumable_progress", "+", "1", ")", "}", "for", "retry_num", "in", "range", "(", "num_retries", "+", "1", ")", ":", "if", "retry_num", ">", "0", ":", "self", ".", "_sleep", "(", "self", ".", "_rand", "(", ")", "*", "2", "**", "retry_num", ")", "LOGGER", ".", "warning", "(", "'Retry #%d for media upload: %s %s, following status: %d'", "%", "(", "retry_num", ",", "self", ".", "method", ",", "self", ".", "uri", ",", "resp", ".", "status", ")", ")", "try", ":", "resp", ",", "content", "=", "http", ".", "request", "(", "self", ".", "resumable_uri", ",", "method", "=", "'PUT'", ",", "body", "=", "data", ",", "headers", "=", "headers", ")", "except", ":", "self", ".", "_in_error_state", "=", "True", "raise", "if", "not", "_should_retry_response", "(", "resp", ".", "status", ",", "content", ")", ":", "break", "return", "self", ".", "_process_response", "(", "resp", ",", "content", ")" ]
[ 855, 2 ]
[ 978, 48 ]
python
en
['en', 'en', 'en']
True