id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
10,100
|
diging/tethne
|
tethne/serialize/paper.py
|
Serialize.serializeInstitution
|
def serializeInstitution(self):
"""
This method creates a fixture for the "django-tethne_citation_institution" model.
Returns
-------
institution details which can be written to a file
"""
institution_data = []
institution_instance_data = []
affiliation_data = []
affiliation_id = tethnedao.getMaxAffiliationID()
institution_id = tethnedao.getMaxInstitutionID()
institution_instance_id = tethnedao.getMaxInstitutionInstanceID()
for paper in self.corpus:
if hasattr(paper, 'authorAddress'):
paper_key = getattr(paper, Serialize.paper_source_map[self.source])
if type(paper.authorAddress) is unicode:
institution_id += 1
institution_instance_id += 1
institute_literal, authors = SerializeUtility.get_auth_inst(paper.authorAddress)
institute_row, institute_instance_row = self.get_details_from_inst_literal(institute_literal,
institution_id,
institution_instance_id,
paper_key)
if institute_row:
institution_data.append(institute_row)
institution_instance_data.append(institute_instance_row)
if authors:
for author in authors:
affiliation_id += 1
affiliation_row = self.get_affiliation_details(author, affiliation_id, institute_literal)
affiliation_data.append(affiliation_row)
elif type(paper.authorAddress) is list:
for address in paper.authorAddress:
institution_id += 1
institution_instance_id += 1
institute_literal, authors = SerializeUtility.get_auth_inst(address)
institute_row, institute_instance_row = self.get_details_from_inst_literal(institute_literal,
institution_id,
institution_instance_id,
paper_key)
if institute_row:
institution_data.append(institute_row)
institution_instance_data.append(institute_instance_row)
if authors is None:
authors = prevAuthors
for author in authors:
affiliation_id += 1
affiliation_row = self.get_affiliation_details(author, affiliation_id, institute_literal)
affiliation_data.append(affiliation_row)
prevAuthors = authors
return institution_data, institution_instance_data, affiliation_data
|
python
|
def serializeInstitution(self):
"""
This method creates a fixture for the "django-tethne_citation_institution" model.
Returns
-------
institution details which can be written to a file
"""
institution_data = []
institution_instance_data = []
affiliation_data = []
affiliation_id = tethnedao.getMaxAffiliationID()
institution_id = tethnedao.getMaxInstitutionID()
institution_instance_id = tethnedao.getMaxInstitutionInstanceID()
for paper in self.corpus:
if hasattr(paper, 'authorAddress'):
paper_key = getattr(paper, Serialize.paper_source_map[self.source])
if type(paper.authorAddress) is unicode:
institution_id += 1
institution_instance_id += 1
institute_literal, authors = SerializeUtility.get_auth_inst(paper.authorAddress)
institute_row, institute_instance_row = self.get_details_from_inst_literal(institute_literal,
institution_id,
institution_instance_id,
paper_key)
if institute_row:
institution_data.append(institute_row)
institution_instance_data.append(institute_instance_row)
if authors:
for author in authors:
affiliation_id += 1
affiliation_row = self.get_affiliation_details(author, affiliation_id, institute_literal)
affiliation_data.append(affiliation_row)
elif type(paper.authorAddress) is list:
for address in paper.authorAddress:
institution_id += 1
institution_instance_id += 1
institute_literal, authors = SerializeUtility.get_auth_inst(address)
institute_row, institute_instance_row = self.get_details_from_inst_literal(institute_literal,
institution_id,
institution_instance_id,
paper_key)
if institute_row:
institution_data.append(institute_row)
institution_instance_data.append(institute_instance_row)
if authors is None:
authors = prevAuthors
for author in authors:
affiliation_id += 1
affiliation_row = self.get_affiliation_details(author, affiliation_id, institute_literal)
affiliation_data.append(affiliation_row)
prevAuthors = authors
return institution_data, institution_instance_data, affiliation_data
|
[
"def",
"serializeInstitution",
"(",
"self",
")",
":",
"institution_data",
"=",
"[",
"]",
"institution_instance_data",
"=",
"[",
"]",
"affiliation_data",
"=",
"[",
"]",
"affiliation_id",
"=",
"tethnedao",
".",
"getMaxAffiliationID",
"(",
")",
"institution_id",
"=",
"tethnedao",
".",
"getMaxInstitutionID",
"(",
")",
"institution_instance_id",
"=",
"tethnedao",
".",
"getMaxInstitutionInstanceID",
"(",
")",
"for",
"paper",
"in",
"self",
".",
"corpus",
":",
"if",
"hasattr",
"(",
"paper",
",",
"'authorAddress'",
")",
":",
"paper_key",
"=",
"getattr",
"(",
"paper",
",",
"Serialize",
".",
"paper_source_map",
"[",
"self",
".",
"source",
"]",
")",
"if",
"type",
"(",
"paper",
".",
"authorAddress",
")",
"is",
"unicode",
":",
"institution_id",
"+=",
"1",
"institution_instance_id",
"+=",
"1",
"institute_literal",
",",
"authors",
"=",
"SerializeUtility",
".",
"get_auth_inst",
"(",
"paper",
".",
"authorAddress",
")",
"institute_row",
",",
"institute_instance_row",
"=",
"self",
".",
"get_details_from_inst_literal",
"(",
"institute_literal",
",",
"institution_id",
",",
"institution_instance_id",
",",
"paper_key",
")",
"if",
"institute_row",
":",
"institution_data",
".",
"append",
"(",
"institute_row",
")",
"institution_instance_data",
".",
"append",
"(",
"institute_instance_row",
")",
"if",
"authors",
":",
"for",
"author",
"in",
"authors",
":",
"affiliation_id",
"+=",
"1",
"affiliation_row",
"=",
"self",
".",
"get_affiliation_details",
"(",
"author",
",",
"affiliation_id",
",",
"institute_literal",
")",
"affiliation_data",
".",
"append",
"(",
"affiliation_row",
")",
"elif",
"type",
"(",
"paper",
".",
"authorAddress",
")",
"is",
"list",
":",
"for",
"address",
"in",
"paper",
".",
"authorAddress",
":",
"institution_id",
"+=",
"1",
"institution_instance_id",
"+=",
"1",
"institute_literal",
",",
"authors",
"=",
"SerializeUtility",
".",
"get_auth_inst",
"(",
"address",
")",
"institute_row",
",",
"institute_instance_row",
"=",
"self",
".",
"get_details_from_inst_literal",
"(",
"institute_literal",
",",
"institution_id",
",",
"institution_instance_id",
",",
"paper_key",
")",
"if",
"institute_row",
":",
"institution_data",
".",
"append",
"(",
"institute_row",
")",
"institution_instance_data",
".",
"append",
"(",
"institute_instance_row",
")",
"if",
"authors",
"is",
"None",
":",
"authors",
"=",
"prevAuthors",
"for",
"author",
"in",
"authors",
":",
"affiliation_id",
"+=",
"1",
"affiliation_row",
"=",
"self",
".",
"get_affiliation_details",
"(",
"author",
",",
"affiliation_id",
",",
"institute_literal",
")",
"affiliation_data",
".",
"append",
"(",
"affiliation_row",
")",
"prevAuthors",
"=",
"authors",
"return",
"institution_data",
",",
"institution_instance_data",
",",
"affiliation_data"
] |
This method creates a fixture for the "django-tethne_citation_institution" model.
Returns
-------
institution details which can be written to a file
|
[
"This",
"method",
"creates",
"a",
"fixture",
"for",
"the",
"django",
"-",
"tethne_citation_institution",
"model",
"."
] |
ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f
|
https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/serialize/paper.py#L289-L344
|
10,101
|
diging/tethne
|
tethne/serialize/paper.py
|
Serialize.get_details_from_inst_literal
|
def get_details_from_inst_literal(self, institute_literal, institution_id, institution_instance_id, paper_key):
"""
This method parses the institute literal to get the following
1. Department naame
2. Country
3. University name
4. ZIP, STATE AND CITY (Only if the country is USA. For other countries the standard may vary. So parsing these
values becomes very difficult. However, the complete address can be found in the column "AddressLine1"
Parameters
----------
institute_literal -> The literal value of the institute
institution_id -> the Primary key value which is to be added in the fixture
institution_instance_id -> Primary key value which is to be added in the fixture
paper_key -> The Paper key which is used for the Institution Instance
Returns
-------
"""
institute_details = institute_literal.split(',')
institute_name = institute_details[0]
country = institute_details[len(institute_details)-1].lstrip().replace('.', '')
institute_row = None
zipcode = ""
state = ""
city = ""
if 'USA' in country:
temp = country
if(len(temp.split())) == 3:
country = temp.split()[2]
zipcode = temp.split()[1]
state = temp.split()[0]
elif(len(temp.split())) == 2:
country = temp.split()[1]
state = temp.split()[0]
city = institute_details[len(institute_details)-2].lstrip()
addressline1 = ""
for i in range(1, len(institute_details)-1, 1):
if i != len(institute_details)-2:
addressline1 = addressline1 + institute_details[i]+','
else:
addressline1 = addressline1 + institute_details[i]
if institute_literal not in self.instituteIdMap:
self.instituteIdMap[institute_literal] = institution_id
institute_row = {
"model": "django-tethne.institution",
"pk": institution_id,
"fields": {
"institute_name": institute_name,
"addressLine1": addressline1,
"country": country,
"zip": zipcode,
"state": state,
"city": city
}
}
department = ""
if re.search('Dept([^,]*),', institute_literal) is not None:
department = re.search('Dept([^,]*),', institute_literal).group().replace(',', '')
institute_instance_row = {
"model": "django-tethne.institution_instance",
"pk": institution_instance_id,
"fields": {
"institution": self.instituteIdMap[institute_literal],
"literal": institute_literal,
"institute_name": institute_name,
"addressLine1": addressline1,
"country": country,
"paper": self.paperIdMap[paper_key],
"department": department,
"zip": zipcode,
"state": state,
"city": city
}
}
return institute_row, institute_instance_row
|
python
|
def get_details_from_inst_literal(self, institute_literal, institution_id, institution_instance_id, paper_key):
"""
This method parses the institute literal to get the following
1. Department naame
2. Country
3. University name
4. ZIP, STATE AND CITY (Only if the country is USA. For other countries the standard may vary. So parsing these
values becomes very difficult. However, the complete address can be found in the column "AddressLine1"
Parameters
----------
institute_literal -> The literal value of the institute
institution_id -> the Primary key value which is to be added in the fixture
institution_instance_id -> Primary key value which is to be added in the fixture
paper_key -> The Paper key which is used for the Institution Instance
Returns
-------
"""
institute_details = institute_literal.split(',')
institute_name = institute_details[0]
country = institute_details[len(institute_details)-1].lstrip().replace('.', '')
institute_row = None
zipcode = ""
state = ""
city = ""
if 'USA' in country:
temp = country
if(len(temp.split())) == 3:
country = temp.split()[2]
zipcode = temp.split()[1]
state = temp.split()[0]
elif(len(temp.split())) == 2:
country = temp.split()[1]
state = temp.split()[0]
city = institute_details[len(institute_details)-2].lstrip()
addressline1 = ""
for i in range(1, len(institute_details)-1, 1):
if i != len(institute_details)-2:
addressline1 = addressline1 + institute_details[i]+','
else:
addressline1 = addressline1 + institute_details[i]
if institute_literal not in self.instituteIdMap:
self.instituteIdMap[institute_literal] = institution_id
institute_row = {
"model": "django-tethne.institution",
"pk": institution_id,
"fields": {
"institute_name": institute_name,
"addressLine1": addressline1,
"country": country,
"zip": zipcode,
"state": state,
"city": city
}
}
department = ""
if re.search('Dept([^,]*),', institute_literal) is not None:
department = re.search('Dept([^,]*),', institute_literal).group().replace(',', '')
institute_instance_row = {
"model": "django-tethne.institution_instance",
"pk": institution_instance_id,
"fields": {
"institution": self.instituteIdMap[institute_literal],
"literal": institute_literal,
"institute_name": institute_name,
"addressLine1": addressline1,
"country": country,
"paper": self.paperIdMap[paper_key],
"department": department,
"zip": zipcode,
"state": state,
"city": city
}
}
return institute_row, institute_instance_row
|
[
"def",
"get_details_from_inst_literal",
"(",
"self",
",",
"institute_literal",
",",
"institution_id",
",",
"institution_instance_id",
",",
"paper_key",
")",
":",
"institute_details",
"=",
"institute_literal",
".",
"split",
"(",
"','",
")",
"institute_name",
"=",
"institute_details",
"[",
"0",
"]",
"country",
"=",
"institute_details",
"[",
"len",
"(",
"institute_details",
")",
"-",
"1",
"]",
".",
"lstrip",
"(",
")",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
"institute_row",
"=",
"None",
"zipcode",
"=",
"\"\"",
"state",
"=",
"\"\"",
"city",
"=",
"\"\"",
"if",
"'USA'",
"in",
"country",
":",
"temp",
"=",
"country",
"if",
"(",
"len",
"(",
"temp",
".",
"split",
"(",
")",
")",
")",
"==",
"3",
":",
"country",
"=",
"temp",
".",
"split",
"(",
")",
"[",
"2",
"]",
"zipcode",
"=",
"temp",
".",
"split",
"(",
")",
"[",
"1",
"]",
"state",
"=",
"temp",
".",
"split",
"(",
")",
"[",
"0",
"]",
"elif",
"(",
"len",
"(",
"temp",
".",
"split",
"(",
")",
")",
")",
"==",
"2",
":",
"country",
"=",
"temp",
".",
"split",
"(",
")",
"[",
"1",
"]",
"state",
"=",
"temp",
".",
"split",
"(",
")",
"[",
"0",
"]",
"city",
"=",
"institute_details",
"[",
"len",
"(",
"institute_details",
")",
"-",
"2",
"]",
".",
"lstrip",
"(",
")",
"addressline1",
"=",
"\"\"",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"institute_details",
")",
"-",
"1",
",",
"1",
")",
":",
"if",
"i",
"!=",
"len",
"(",
"institute_details",
")",
"-",
"2",
":",
"addressline1",
"=",
"addressline1",
"+",
"institute_details",
"[",
"i",
"]",
"+",
"','",
"else",
":",
"addressline1",
"=",
"addressline1",
"+",
"institute_details",
"[",
"i",
"]",
"if",
"institute_literal",
"not",
"in",
"self",
".",
"instituteIdMap",
":",
"self",
".",
"instituteIdMap",
"[",
"institute_literal",
"]",
"=",
"institution_id",
"institute_row",
"=",
"{",
"\"model\"",
":",
"\"django-tethne.institution\"",
",",
"\"pk\"",
":",
"institution_id",
",",
"\"fields\"",
":",
"{",
"\"institute_name\"",
":",
"institute_name",
",",
"\"addressLine1\"",
":",
"addressline1",
",",
"\"country\"",
":",
"country",
",",
"\"zip\"",
":",
"zipcode",
",",
"\"state\"",
":",
"state",
",",
"\"city\"",
":",
"city",
"}",
"}",
"department",
"=",
"\"\"",
"if",
"re",
".",
"search",
"(",
"'Dept([^,]*),'",
",",
"institute_literal",
")",
"is",
"not",
"None",
":",
"department",
"=",
"re",
".",
"search",
"(",
"'Dept([^,]*),'",
",",
"institute_literal",
")",
".",
"group",
"(",
")",
".",
"replace",
"(",
"','",
",",
"''",
")",
"institute_instance_row",
"=",
"{",
"\"model\"",
":",
"\"django-tethne.institution_instance\"",
",",
"\"pk\"",
":",
"institution_instance_id",
",",
"\"fields\"",
":",
"{",
"\"institution\"",
":",
"self",
".",
"instituteIdMap",
"[",
"institute_literal",
"]",
",",
"\"literal\"",
":",
"institute_literal",
",",
"\"institute_name\"",
":",
"institute_name",
",",
"\"addressLine1\"",
":",
"addressline1",
",",
"\"country\"",
":",
"country",
",",
"\"paper\"",
":",
"self",
".",
"paperIdMap",
"[",
"paper_key",
"]",
",",
"\"department\"",
":",
"department",
",",
"\"zip\"",
":",
"zipcode",
",",
"\"state\"",
":",
"state",
",",
"\"city\"",
":",
"city",
"}",
"}",
"return",
"institute_row",
",",
"institute_instance_row"
] |
This method parses the institute literal to get the following
1. Department naame
2. Country
3. University name
4. ZIP, STATE AND CITY (Only if the country is USA. For other countries the standard may vary. So parsing these
values becomes very difficult. However, the complete address can be found in the column "AddressLine1"
Parameters
----------
institute_literal -> The literal value of the institute
institution_id -> the Primary key value which is to be added in the fixture
institution_instance_id -> Primary key value which is to be added in the fixture
paper_key -> The Paper key which is used for the Institution Instance
Returns
-------
|
[
"This",
"method",
"parses",
"the",
"institute",
"literal",
"to",
"get",
"the",
"following",
"1",
".",
"Department",
"naame",
"2",
".",
"Country",
"3",
".",
"University",
"name",
"4",
".",
"ZIP",
"STATE",
"AND",
"CITY",
"(",
"Only",
"if",
"the",
"country",
"is",
"USA",
".",
"For",
"other",
"countries",
"the",
"standard",
"may",
"vary",
".",
"So",
"parsing",
"these",
"values",
"becomes",
"very",
"difficult",
".",
"However",
"the",
"complete",
"address",
"can",
"be",
"found",
"in",
"the",
"column",
"AddressLine1"
] |
ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f
|
https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/serialize/paper.py#L346-L424
|
10,102
|
diging/tethne
|
tethne/serialize/paper.py
|
Serialize.get_affiliation_details
|
def get_affiliation_details(self, value, affiliation_id, institute_literal):
"""
This method is used to map the Affiliation between an author and Institution.
Parameters
----------
value - The author name
affiliation_id - Primary key of the affiliation table
institute_literal
Returns
-------
Affiliation details(JSON fixture) which can be written to a file
"""
tokens = tuple([t.upper().strip() for t in value.split(',')])
if len(tokens) == 1:
tokens = value.split()
if len(tokens) > 0:
if len(tokens) > 1:
aulast, auinit = tokens[0:2]
else:
aulast = tokens[0]
auinit = ''
else:
aulast, auinit = tokens[0], ''
aulast = _strip_punctuation(aulast).upper()
auinit = _strip_punctuation(auinit).upper()
author_key = auinit+aulast
affiliation_row = {
"model": "django-tethne.affiliation",
"pk": affiliation_id,
"fields": {
"author": self.authorIdMap[author_key],
"institution": self.instituteIdMap[institute_literal]
}
}
return affiliation_row
|
python
|
def get_affiliation_details(self, value, affiliation_id, institute_literal):
"""
This method is used to map the Affiliation between an author and Institution.
Parameters
----------
value - The author name
affiliation_id - Primary key of the affiliation table
institute_literal
Returns
-------
Affiliation details(JSON fixture) which can be written to a file
"""
tokens = tuple([t.upper().strip() for t in value.split(',')])
if len(tokens) == 1:
tokens = value.split()
if len(tokens) > 0:
if len(tokens) > 1:
aulast, auinit = tokens[0:2]
else:
aulast = tokens[0]
auinit = ''
else:
aulast, auinit = tokens[0], ''
aulast = _strip_punctuation(aulast).upper()
auinit = _strip_punctuation(auinit).upper()
author_key = auinit+aulast
affiliation_row = {
"model": "django-tethne.affiliation",
"pk": affiliation_id,
"fields": {
"author": self.authorIdMap[author_key],
"institution": self.instituteIdMap[institute_literal]
}
}
return affiliation_row
|
[
"def",
"get_affiliation_details",
"(",
"self",
",",
"value",
",",
"affiliation_id",
",",
"institute_literal",
")",
":",
"tokens",
"=",
"tuple",
"(",
"[",
"t",
".",
"upper",
"(",
")",
".",
"strip",
"(",
")",
"for",
"t",
"in",
"value",
".",
"split",
"(",
"','",
")",
"]",
")",
"if",
"len",
"(",
"tokens",
")",
"==",
"1",
":",
"tokens",
"=",
"value",
".",
"split",
"(",
")",
"if",
"len",
"(",
"tokens",
")",
">",
"0",
":",
"if",
"len",
"(",
"tokens",
")",
">",
"1",
":",
"aulast",
",",
"auinit",
"=",
"tokens",
"[",
"0",
":",
"2",
"]",
"else",
":",
"aulast",
"=",
"tokens",
"[",
"0",
"]",
"auinit",
"=",
"''",
"else",
":",
"aulast",
",",
"auinit",
"=",
"tokens",
"[",
"0",
"]",
",",
"''",
"aulast",
"=",
"_strip_punctuation",
"(",
"aulast",
")",
".",
"upper",
"(",
")",
"auinit",
"=",
"_strip_punctuation",
"(",
"auinit",
")",
".",
"upper",
"(",
")",
"author_key",
"=",
"auinit",
"+",
"aulast",
"affiliation_row",
"=",
"{",
"\"model\"",
":",
"\"django-tethne.affiliation\"",
",",
"\"pk\"",
":",
"affiliation_id",
",",
"\"fields\"",
":",
"{",
"\"author\"",
":",
"self",
".",
"authorIdMap",
"[",
"author_key",
"]",
",",
"\"institution\"",
":",
"self",
".",
"instituteIdMap",
"[",
"institute_literal",
"]",
"}",
"}",
"return",
"affiliation_row"
] |
This method is used to map the Affiliation between an author and Institution.
Parameters
----------
value - The author name
affiliation_id - Primary key of the affiliation table
institute_literal
Returns
-------
Affiliation details(JSON fixture) which can be written to a file
|
[
"This",
"method",
"is",
"used",
"to",
"map",
"the",
"Affiliation",
"between",
"an",
"author",
"and",
"Institution",
"."
] |
ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f
|
https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/serialize/paper.py#L426-L464
|
10,103
|
diging/tethne
|
tethne/readers/base.py
|
IterParser.start
|
def start(self):
"""
Find the first data entry and prepare to parse.
"""
while not self.is_start(self.current_tag):
self.next()
self.new_entry()
|
python
|
def start(self):
"""
Find the first data entry and prepare to parse.
"""
while not self.is_start(self.current_tag):
self.next()
self.new_entry()
|
[
"def",
"start",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"is_start",
"(",
"self",
".",
"current_tag",
")",
":",
"self",
".",
"next",
"(",
")",
"self",
".",
"new_entry",
"(",
")"
] |
Find the first data entry and prepare to parse.
|
[
"Find",
"the",
"first",
"data",
"entry",
"and",
"prepare",
"to",
"parse",
"."
] |
ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f
|
https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/readers/base.py#L129-L136
|
10,104
|
diging/tethne
|
tethne/readers/base.py
|
IterParser.handle
|
def handle(self, tag, data):
"""
Process a single line of data, and store the result.
Parameters
----------
tag : str
data :
"""
if self.is_end(tag):
self.postprocess_entry()
if self.is_start(tag):
self.new_entry()
if not data or not tag:
return
if getattr(self, 'parse_only', None) and tag not in self.parse_only:
return
# TODO: revisit encoding here.
if isinstance(data, unicode):
data = unicodedata.normalize('NFKD', data)#.encode('utf-8','ignore')
handler = self._get_handler(tag)
if handler is not None:
data = handler(data)
if tag in self.tags: # Rename the field.
tag = self.tags[tag]
# Multiline fields are represented as lists of values.
if hasattr(self.data[-1], tag):
value = getattr(self.data[-1], tag)
if tag in self.concat_fields:
value = ' '.join([value, unicode(data)])
elif type(value) is list:
value.append(data)
elif value not in [None, '']:
value = [value, data]
else:
value = data
setattr(self.data[-1], tag, value)
self.fields.add(tag)
|
python
|
def handle(self, tag, data):
"""
Process a single line of data, and store the result.
Parameters
----------
tag : str
data :
"""
if self.is_end(tag):
self.postprocess_entry()
if self.is_start(tag):
self.new_entry()
if not data or not tag:
return
if getattr(self, 'parse_only', None) and tag not in self.parse_only:
return
# TODO: revisit encoding here.
if isinstance(data, unicode):
data = unicodedata.normalize('NFKD', data)#.encode('utf-8','ignore')
handler = self._get_handler(tag)
if handler is not None:
data = handler(data)
if tag in self.tags: # Rename the field.
tag = self.tags[tag]
# Multiline fields are represented as lists of values.
if hasattr(self.data[-1], tag):
value = getattr(self.data[-1], tag)
if tag in self.concat_fields:
value = ' '.join([value, unicode(data)])
elif type(value) is list:
value.append(data)
elif value not in [None, '']:
value = [value, data]
else:
value = data
setattr(self.data[-1], tag, value)
self.fields.add(tag)
|
[
"def",
"handle",
"(",
"self",
",",
"tag",
",",
"data",
")",
":",
"if",
"self",
".",
"is_end",
"(",
"tag",
")",
":",
"self",
".",
"postprocess_entry",
"(",
")",
"if",
"self",
".",
"is_start",
"(",
"tag",
")",
":",
"self",
".",
"new_entry",
"(",
")",
"if",
"not",
"data",
"or",
"not",
"tag",
":",
"return",
"if",
"getattr",
"(",
"self",
",",
"'parse_only'",
",",
"None",
")",
"and",
"tag",
"not",
"in",
"self",
".",
"parse_only",
":",
"return",
"# TODO: revisit encoding here.",
"if",
"isinstance",
"(",
"data",
",",
"unicode",
")",
":",
"data",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKD'",
",",
"data",
")",
"#.encode('utf-8','ignore')",
"handler",
"=",
"self",
".",
"_get_handler",
"(",
"tag",
")",
"if",
"handler",
"is",
"not",
"None",
":",
"data",
"=",
"handler",
"(",
"data",
")",
"if",
"tag",
"in",
"self",
".",
"tags",
":",
"# Rename the field.",
"tag",
"=",
"self",
".",
"tags",
"[",
"tag",
"]",
"# Multiline fields are represented as lists of values.",
"if",
"hasattr",
"(",
"self",
".",
"data",
"[",
"-",
"1",
"]",
",",
"tag",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
".",
"data",
"[",
"-",
"1",
"]",
",",
"tag",
")",
"if",
"tag",
"in",
"self",
".",
"concat_fields",
":",
"value",
"=",
"' '",
".",
"join",
"(",
"[",
"value",
",",
"unicode",
"(",
"data",
")",
"]",
")",
"elif",
"type",
"(",
"value",
")",
"is",
"list",
":",
"value",
".",
"append",
"(",
"data",
")",
"elif",
"value",
"not",
"in",
"[",
"None",
",",
"''",
"]",
":",
"value",
"=",
"[",
"value",
",",
"data",
"]",
"else",
":",
"value",
"=",
"data",
"setattr",
"(",
"self",
".",
"data",
"[",
"-",
"1",
"]",
",",
"tag",
",",
"value",
")",
"self",
".",
"fields",
".",
"add",
"(",
"tag",
")"
] |
Process a single line of data, and store the result.
Parameters
----------
tag : str
data :
|
[
"Process",
"a",
"single",
"line",
"of",
"data",
"and",
"store",
"the",
"result",
"."
] |
ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f
|
https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/readers/base.py#L138-L183
|
10,105
|
diging/tethne
|
tethne/readers/base.py
|
FTParser.open
|
def open(self):
"""
Open the data file.
"""
if not os.path.exists(self.path):
raise IOError("No such path: {0}".format(self.path))
with open(self.path, "rb") as f:
msg = f.read()
result = chardet.detect(msg)
self.buffer = codecs.open(self.path, "rb", encoding=result['encoding'])
self.at_eof = False
|
python
|
def open(self):
"""
Open the data file.
"""
if not os.path.exists(self.path):
raise IOError("No such path: {0}".format(self.path))
with open(self.path, "rb") as f:
msg = f.read()
result = chardet.detect(msg)
self.buffer = codecs.open(self.path, "rb", encoding=result['encoding'])
self.at_eof = False
|
[
"def",
"open",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"raise",
"IOError",
"(",
"\"No such path: {0}\"",
".",
"format",
"(",
"self",
".",
"path",
")",
")",
"with",
"open",
"(",
"self",
".",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"msg",
"=",
"f",
".",
"read",
"(",
")",
"result",
"=",
"chardet",
".",
"detect",
"(",
"msg",
")",
"self",
".",
"buffer",
"=",
"codecs",
".",
"open",
"(",
"self",
".",
"path",
",",
"\"rb\"",
",",
"encoding",
"=",
"result",
"[",
"'encoding'",
"]",
")",
"self",
".",
"at_eof",
"=",
"False"
] |
Open the data file.
|
[
"Open",
"the",
"data",
"file",
"."
] |
ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f
|
https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/readers/base.py#L206-L221
|
10,106
|
diging/tethne
|
tethne/readers/base.py
|
FTParser.next
|
def next(self):
"""
Get the next line of data.
Returns
-------
tag : str
data :
"""
line = self.buffer.readline()
while line == '\n': # Skip forward to the next line with content.
line = self.buffer.readline()
if line == '': # End of file.
self.at_eof = True
return None, None
match = re.match('([A-Z]{2}|[C][1])\W(.*)', line)
if match is not None:
self.current_tag, data = match.groups()
else:
self.current_tag = self.last_tag
data = line.strip()
return self.current_tag, _cast(data)
|
python
|
def next(self):
"""
Get the next line of data.
Returns
-------
tag : str
data :
"""
line = self.buffer.readline()
while line == '\n': # Skip forward to the next line with content.
line = self.buffer.readline()
if line == '': # End of file.
self.at_eof = True
return None, None
match = re.match('([A-Z]{2}|[C][1])\W(.*)', line)
if match is not None:
self.current_tag, data = match.groups()
else:
self.current_tag = self.last_tag
data = line.strip()
return self.current_tag, _cast(data)
|
[
"def",
"next",
"(",
"self",
")",
":",
"line",
"=",
"self",
".",
"buffer",
".",
"readline",
"(",
")",
"while",
"line",
"==",
"'\\n'",
":",
"# Skip forward to the next line with content.",
"line",
"=",
"self",
".",
"buffer",
".",
"readline",
"(",
")",
"if",
"line",
"==",
"''",
":",
"# End of file.",
"self",
".",
"at_eof",
"=",
"True",
"return",
"None",
",",
"None",
"match",
"=",
"re",
".",
"match",
"(",
"'([A-Z]{2}|[C][1])\\W(.*)'",
",",
"line",
")",
"if",
"match",
"is",
"not",
"None",
":",
"self",
".",
"current_tag",
",",
"data",
"=",
"match",
".",
"groups",
"(",
")",
"else",
":",
"self",
".",
"current_tag",
"=",
"self",
".",
"last_tag",
"data",
"=",
"line",
".",
"strip",
"(",
")",
"return",
"self",
".",
"current_tag",
",",
"_cast",
"(",
"data",
")"
] |
Get the next line of data.
Returns
-------
tag : str
data :
|
[
"Get",
"the",
"next",
"line",
"of",
"data",
"."
] |
ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f
|
https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/readers/base.py#L223-L247
|
10,107
|
diging/tethne
|
tethne/networks/authors.py
|
coauthors
|
def coauthors(corpus, min_weight=1, edge_attrs=['ayjid', 'date'], **kwargs):
"""
A graph describing joint authorship in ``corpus``.
"""
return cooccurrence(corpus, 'authors', min_weight=min_weight,
edge_attrs=edge_attrs, **kwargs)
|
python
|
def coauthors(corpus, min_weight=1, edge_attrs=['ayjid', 'date'], **kwargs):
"""
A graph describing joint authorship in ``corpus``.
"""
return cooccurrence(corpus, 'authors', min_weight=min_weight,
edge_attrs=edge_attrs, **kwargs)
|
[
"def",
"coauthors",
"(",
"corpus",
",",
"min_weight",
"=",
"1",
",",
"edge_attrs",
"=",
"[",
"'ayjid'",
",",
"'date'",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cooccurrence",
"(",
"corpus",
",",
"'authors'",
",",
"min_weight",
"=",
"min_weight",
",",
"edge_attrs",
"=",
"edge_attrs",
",",
"*",
"*",
"kwargs",
")"
] |
A graph describing joint authorship in ``corpus``.
|
[
"A",
"graph",
"describing",
"joint",
"authorship",
"in",
"corpus",
"."
] |
ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f
|
https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/networks/authors.py#L22-L27
|
10,108
|
diging/tethne
|
tethne/readers/zotero.py
|
extract_text
|
def extract_text(fpath):
"""
Extracts structured text content from a plain-text file at ``fpath``.
Parameters
----------
fpath : str
Path to the text file..
Returns
-------
:class:`.StructuredFeature`
A :class:`.StructuredFeature` that contains sentence context.
"""
with codecs.open(fpath, 'r') as f: # Determine the encoding of the file.
document = f.read()
encoding = chardet.detect(document)['encoding']
document = document.decode(encoding)
tokens = []
sentences = []
i = 0
for sentence in nltk.tokenize.sent_tokenize(document):
sentences.append(i)
for word in nltk.tokenize.word_tokenize(sentence):
tokens.append(word)
i += 1
contexts = [('sentence', sentences)]
return StructuredFeature(tokens, contexts)
|
python
|
def extract_text(fpath):
"""
Extracts structured text content from a plain-text file at ``fpath``.
Parameters
----------
fpath : str
Path to the text file..
Returns
-------
:class:`.StructuredFeature`
A :class:`.StructuredFeature` that contains sentence context.
"""
with codecs.open(fpath, 'r') as f: # Determine the encoding of the file.
document = f.read()
encoding = chardet.detect(document)['encoding']
document = document.decode(encoding)
tokens = []
sentences = []
i = 0
for sentence in nltk.tokenize.sent_tokenize(document):
sentences.append(i)
for word in nltk.tokenize.word_tokenize(sentence):
tokens.append(word)
i += 1
contexts = [('sentence', sentences)]
return StructuredFeature(tokens, contexts)
|
[
"def",
"extract_text",
"(",
"fpath",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"fpath",
",",
"'r'",
")",
"as",
"f",
":",
"# Determine the encoding of the file.",
"document",
"=",
"f",
".",
"read",
"(",
")",
"encoding",
"=",
"chardet",
".",
"detect",
"(",
"document",
")",
"[",
"'encoding'",
"]",
"document",
"=",
"document",
".",
"decode",
"(",
"encoding",
")",
"tokens",
"=",
"[",
"]",
"sentences",
"=",
"[",
"]",
"i",
"=",
"0",
"for",
"sentence",
"in",
"nltk",
".",
"tokenize",
".",
"sent_tokenize",
"(",
"document",
")",
":",
"sentences",
".",
"append",
"(",
"i",
")",
"for",
"word",
"in",
"nltk",
".",
"tokenize",
".",
"word_tokenize",
"(",
"sentence",
")",
":",
"tokens",
".",
"append",
"(",
"word",
")",
"i",
"+=",
"1",
"contexts",
"=",
"[",
"(",
"'sentence'",
",",
"sentences",
")",
"]",
"return",
"StructuredFeature",
"(",
"tokens",
",",
"contexts",
")"
] |
Extracts structured text content from a plain-text file at ``fpath``.
Parameters
----------
fpath : str
Path to the text file..
Returns
-------
:class:`.StructuredFeature`
A :class:`.StructuredFeature` that contains sentence context.
|
[
"Extracts",
"structured",
"text",
"content",
"from",
"a",
"plain",
"-",
"text",
"file",
"at",
"fpath",
"."
] |
ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f
|
https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/readers/zotero.py#L86-L117
|
10,109
|
diging/tethne
|
tethne/readers/zotero.py
|
extract_pdf
|
def extract_pdf(fpath):
"""
Extracts structured text content from a PDF at ``fpath``.
Parameters
----------
fpath : str
Path to the PDF.
Returns
-------
:class:`.StructuredFeature`
A :class:`.StructuredFeature` that contains page and sentence contexts.
"""
with codecs.open(fpath, 'r') as f: # Determine the encoding of the file.
document = slate.PDF(f)
encoding = chardet.detect(document[0])
tokens = []
pages = []
sentences = []
tokenizer = nltk.tokenize.TextTilingTokenizer()
i = 0
for page in document:
pages.append(i)
# Decode using the correct encoding.
page = page.decode(encoding['encoding'])
for sentence in nltk.tokenize.sent_tokenize(page):
sentences.append(i)
for word in nltk.tokenize.word_tokenize(sentence):
if len(word) > 15:
words = nltk.tokenize.word_tokenize(_infer_spaces(word))
if mean([len(w) for w in words]) > 2:
for w in words:
tokens.append(w)
i += 1
continue
tokens.append(word)
i += 1
contexts = [('page', pages), ('sentence', sentences)]
return StructuredFeature(tokens, contexts)
|
python
|
def extract_pdf(fpath):
"""
Extracts structured text content from a PDF at ``fpath``.
Parameters
----------
fpath : str
Path to the PDF.
Returns
-------
:class:`.StructuredFeature`
A :class:`.StructuredFeature` that contains page and sentence contexts.
"""
with codecs.open(fpath, 'r') as f: # Determine the encoding of the file.
document = slate.PDF(f)
encoding = chardet.detect(document[0])
tokens = []
pages = []
sentences = []
tokenizer = nltk.tokenize.TextTilingTokenizer()
i = 0
for page in document:
pages.append(i)
# Decode using the correct encoding.
page = page.decode(encoding['encoding'])
for sentence in nltk.tokenize.sent_tokenize(page):
sentences.append(i)
for word in nltk.tokenize.word_tokenize(sentence):
if len(word) > 15:
words = nltk.tokenize.word_tokenize(_infer_spaces(word))
if mean([len(w) for w in words]) > 2:
for w in words:
tokens.append(w)
i += 1
continue
tokens.append(word)
i += 1
contexts = [('page', pages), ('sentence', sentences)]
return StructuredFeature(tokens, contexts)
|
[
"def",
"extract_pdf",
"(",
"fpath",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"fpath",
",",
"'r'",
")",
"as",
"f",
":",
"# Determine the encoding of the file.",
"document",
"=",
"slate",
".",
"PDF",
"(",
"f",
")",
"encoding",
"=",
"chardet",
".",
"detect",
"(",
"document",
"[",
"0",
"]",
")",
"tokens",
"=",
"[",
"]",
"pages",
"=",
"[",
"]",
"sentences",
"=",
"[",
"]",
"tokenizer",
"=",
"nltk",
".",
"tokenize",
".",
"TextTilingTokenizer",
"(",
")",
"i",
"=",
"0",
"for",
"page",
"in",
"document",
":",
"pages",
".",
"append",
"(",
"i",
")",
"# Decode using the correct encoding.",
"page",
"=",
"page",
".",
"decode",
"(",
"encoding",
"[",
"'encoding'",
"]",
")",
"for",
"sentence",
"in",
"nltk",
".",
"tokenize",
".",
"sent_tokenize",
"(",
"page",
")",
":",
"sentences",
".",
"append",
"(",
"i",
")",
"for",
"word",
"in",
"nltk",
".",
"tokenize",
".",
"word_tokenize",
"(",
"sentence",
")",
":",
"if",
"len",
"(",
"word",
")",
">",
"15",
":",
"words",
"=",
"nltk",
".",
"tokenize",
".",
"word_tokenize",
"(",
"_infer_spaces",
"(",
"word",
")",
")",
"if",
"mean",
"(",
"[",
"len",
"(",
"w",
")",
"for",
"w",
"in",
"words",
"]",
")",
">",
"2",
":",
"for",
"w",
"in",
"words",
":",
"tokens",
".",
"append",
"(",
"w",
")",
"i",
"+=",
"1",
"continue",
"tokens",
".",
"append",
"(",
"word",
")",
"i",
"+=",
"1",
"contexts",
"=",
"[",
"(",
"'page'",
",",
"pages",
")",
",",
"(",
"'sentence'",
",",
"sentences",
")",
"]",
"return",
"StructuredFeature",
"(",
"tokens",
",",
"contexts",
")"
] |
Extracts structured text content from a PDF at ``fpath``.
Parameters
----------
fpath : str
Path to the PDF.
Returns
-------
:class:`.StructuredFeature`
A :class:`.StructuredFeature` that contains page and sentence contexts.
|
[
"Extracts",
"structured",
"text",
"content",
"from",
"a",
"PDF",
"at",
"fpath",
"."
] |
ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f
|
https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/readers/zotero.py#L120-L167
|
10,110
|
diging/tethne
|
tethne/readers/zotero.py
|
read
|
def read(path, corpus=True, index_by='uri', follow_links=False, **kwargs):
"""
Read bibliographic data from Zotero RDF.
Examples
--------
Assuming that the Zotero collection was exported to the directory
``/my/working/dir`` with the name ``myCollection``, a subdirectory should
have been created at ``/my/working/dir/myCollection``, and an RDF file
should exist at ``/my/working/dir/myCollection/myCollection.rdf``.
.. code-block:: python
>>> from tethne.readers.zotero import read
>>> myCorpus = read('/my/working/dir/myCollection')
>>> myCorpus
<tethne.classes.corpus.Corpus object at 0x10047e350>
Parameters
----------
path : str
Path to the output directory created by Zotero. Expected to contain a
file called ``[directory_name].rdf``.
corpus : bool
(default: True) If True, returns a :class:`.Corpus`\. Otherwise,
returns a list of :class:`.Paper`\s.
index_by : str
(default: ``'identifier'``) :class:`.Paper` attribute name to use as
the primary indexing field. If the field is missing on a
:class:`.Paper`\, a unique identifier will be generated based on the
title and author names.
follow_links : bool
If ``True``, attempts to load full-text content from attached files
(e.g. PDFs with embedded text). Default: False.
kwargs : kwargs
Passed to the :class:`.Corpus` constructor.
Returns
-------
corpus : :class:`.Corpus`
"""
# TODO: is there a case where `from_dir` would make sense?
parser = ZoteroParser(path, index_by=index_by, follow_links=follow_links)
papers = parser.parse()
if corpus:
c = Corpus(papers, index_by=index_by, **kwargs)
if c.duplicate_papers:
warnings.warn("Duplicate papers detected. Use the 'duplicate_papers' attribute of the corpus to get the list", UserWarning)
for fset_name, fset_values in parser.full_text.iteritems():
c.features[fset_name] = StructuredFeatureSet(fset_values)
return c
return papers
|
python
|
def read(path, corpus=True, index_by='uri', follow_links=False, **kwargs):
"""
Read bibliographic data from Zotero RDF.
Examples
--------
Assuming that the Zotero collection was exported to the directory
``/my/working/dir`` with the name ``myCollection``, a subdirectory should
have been created at ``/my/working/dir/myCollection``, and an RDF file
should exist at ``/my/working/dir/myCollection/myCollection.rdf``.
.. code-block:: python
>>> from tethne.readers.zotero import read
>>> myCorpus = read('/my/working/dir/myCollection')
>>> myCorpus
<tethne.classes.corpus.Corpus object at 0x10047e350>
Parameters
----------
path : str
Path to the output directory created by Zotero. Expected to contain a
file called ``[directory_name].rdf``.
corpus : bool
(default: True) If True, returns a :class:`.Corpus`\. Otherwise,
returns a list of :class:`.Paper`\s.
index_by : str
(default: ``'identifier'``) :class:`.Paper` attribute name to use as
the primary indexing field. If the field is missing on a
:class:`.Paper`\, a unique identifier will be generated based on the
title and author names.
follow_links : bool
If ``True``, attempts to load full-text content from attached files
(e.g. PDFs with embedded text). Default: False.
kwargs : kwargs
Passed to the :class:`.Corpus` constructor.
Returns
-------
corpus : :class:`.Corpus`
"""
# TODO: is there a case where `from_dir` would make sense?
parser = ZoteroParser(path, index_by=index_by, follow_links=follow_links)
papers = parser.parse()
if corpus:
c = Corpus(papers, index_by=index_by, **kwargs)
if c.duplicate_papers:
warnings.warn("Duplicate papers detected. Use the 'duplicate_papers' attribute of the corpus to get the list", UserWarning)
for fset_name, fset_values in parser.full_text.iteritems():
c.features[fset_name] = StructuredFeatureSet(fset_values)
return c
return papers
|
[
"def",
"read",
"(",
"path",
",",
"corpus",
"=",
"True",
",",
"index_by",
"=",
"'uri'",
",",
"follow_links",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: is there a case where `from_dir` would make sense?",
"parser",
"=",
"ZoteroParser",
"(",
"path",
",",
"index_by",
"=",
"index_by",
",",
"follow_links",
"=",
"follow_links",
")",
"papers",
"=",
"parser",
".",
"parse",
"(",
")",
"if",
"corpus",
":",
"c",
"=",
"Corpus",
"(",
"papers",
",",
"index_by",
"=",
"index_by",
",",
"*",
"*",
"kwargs",
")",
"if",
"c",
".",
"duplicate_papers",
":",
"warnings",
".",
"warn",
"(",
"\"Duplicate papers detected. Use the 'duplicate_papers' attribute of the corpus to get the list\"",
",",
"UserWarning",
")",
"for",
"fset_name",
",",
"fset_values",
"in",
"parser",
".",
"full_text",
".",
"iteritems",
"(",
")",
":",
"c",
".",
"features",
"[",
"fset_name",
"]",
"=",
"StructuredFeatureSet",
"(",
"fset_values",
")",
"return",
"c",
"return",
"papers"
] |
Read bibliographic data from Zotero RDF.
Examples
--------
Assuming that the Zotero collection was exported to the directory
``/my/working/dir`` with the name ``myCollection``, a subdirectory should
have been created at ``/my/working/dir/myCollection``, and an RDF file
should exist at ``/my/working/dir/myCollection/myCollection.rdf``.
.. code-block:: python
>>> from tethne.readers.zotero import read
>>> myCorpus = read('/my/working/dir/myCollection')
>>> myCorpus
<tethne.classes.corpus.Corpus object at 0x10047e350>
Parameters
----------
path : str
Path to the output directory created by Zotero. Expected to contain a
file called ``[directory_name].rdf``.
corpus : bool
(default: True) If True, returns a :class:`.Corpus`\. Otherwise,
returns a list of :class:`.Paper`\s.
index_by : str
(default: ``'identifier'``) :class:`.Paper` attribute name to use as
the primary indexing field. If the field is missing on a
:class:`.Paper`\, a unique identifier will be generated based on the
title and author names.
follow_links : bool
If ``True``, attempts to load full-text content from attached files
(e.g. PDFs with embedded text). Default: False.
kwargs : kwargs
Passed to the :class:`.Corpus` constructor.
Returns
-------
corpus : :class:`.Corpus`
|
[
"Read",
"bibliographic",
"data",
"from",
"Zotero",
"RDF",
"."
] |
ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f
|
https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/readers/zotero.py#L391-L446
|
10,111
|
diging/tethne
|
tethne/readers/zotero.py
|
ZoteroParser.handle_date
|
def handle_date(self, value):
"""
Attempt to coerced date to ISO8601.
"""
try:
return iso8601.parse_date(unicode(value)).year
except iso8601.ParseError:
for datefmt in ("%B %d, %Y", "%Y-%m", "%Y-%m-%d", "%m/%d/%Y"):
try:
# TODO: remove str coercion.
return datetime.strptime(unicode(value), datefmt).date().year
except ValueError:
pass
|
python
|
def handle_date(self, value):
"""
Attempt to coerced date to ISO8601.
"""
try:
return iso8601.parse_date(unicode(value)).year
except iso8601.ParseError:
for datefmt in ("%B %d, %Y", "%Y-%m", "%Y-%m-%d", "%m/%d/%Y"):
try:
# TODO: remove str coercion.
return datetime.strptime(unicode(value), datefmt).date().year
except ValueError:
pass
|
[
"def",
"handle_date",
"(",
"self",
",",
"value",
")",
":",
"try",
":",
"return",
"iso8601",
".",
"parse_date",
"(",
"unicode",
"(",
"value",
")",
")",
".",
"year",
"except",
"iso8601",
".",
"ParseError",
":",
"for",
"datefmt",
"in",
"(",
"\"%B %d, %Y\"",
",",
"\"%Y-%m\"",
",",
"\"%Y-%m-%d\"",
",",
"\"%m/%d/%Y\"",
")",
":",
"try",
":",
"# TODO: remove str coercion.",
"return",
"datetime",
".",
"strptime",
"(",
"unicode",
"(",
"value",
")",
",",
"datefmt",
")",
".",
"date",
"(",
")",
".",
"year",
"except",
"ValueError",
":",
"pass"
] |
Attempt to coerced date to ISO8601.
|
[
"Attempt",
"to",
"coerced",
"date",
"to",
"ISO8601",
"."
] |
ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f
|
https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/readers/zotero.py#L242-L254
|
10,112
|
diging/tethne
|
tethne/readers/zotero.py
|
ZoteroParser.postprocess_link
|
def postprocess_link(self, entry):
"""
Attempt to load full-text content from resource.
"""
if not self.follow_links:
return
if type(entry.link) is not list:
entry.link = [entry.link]
for link in list(entry.link):
if not os.path.exists(link):
continue
mime_type = magic.from_file(link, mime=True)
if mime_type == 'application/pdf':
structuredfeature = extract_pdf(link)
elif mime_type == 'text/plain':
structuredfeature = extract_text(link)
else:
structuredfeature = None
if not structuredfeature:
continue
fset_name = mime_type.split('/')[-1] + '_text'
if not fset_name in self.full_text:
self.full_text[fset_name] = {}
if hasattr(self, 'index_by'):
ident = getattr(entry, self.index_by)
if type(ident) is list:
ident = ident[0]
else: # If `index_by` is not set, use `uri` by default.
ident = entry.uri
self.full_text[fset_name][ident] = structuredfeature
|
python
|
def postprocess_link(self, entry):
"""
Attempt to load full-text content from resource.
"""
if not self.follow_links:
return
if type(entry.link) is not list:
entry.link = [entry.link]
for link in list(entry.link):
if not os.path.exists(link):
continue
mime_type = magic.from_file(link, mime=True)
if mime_type == 'application/pdf':
structuredfeature = extract_pdf(link)
elif mime_type == 'text/plain':
structuredfeature = extract_text(link)
else:
structuredfeature = None
if not structuredfeature:
continue
fset_name = mime_type.split('/')[-1] + '_text'
if not fset_name in self.full_text:
self.full_text[fset_name] = {}
if hasattr(self, 'index_by'):
ident = getattr(entry, self.index_by)
if type(ident) is list:
ident = ident[0]
else: # If `index_by` is not set, use `uri` by default.
ident = entry.uri
self.full_text[fset_name][ident] = structuredfeature
|
[
"def",
"postprocess_link",
"(",
"self",
",",
"entry",
")",
":",
"if",
"not",
"self",
".",
"follow_links",
":",
"return",
"if",
"type",
"(",
"entry",
".",
"link",
")",
"is",
"not",
"list",
":",
"entry",
".",
"link",
"=",
"[",
"entry",
".",
"link",
"]",
"for",
"link",
"in",
"list",
"(",
"entry",
".",
"link",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"link",
")",
":",
"continue",
"mime_type",
"=",
"magic",
".",
"from_file",
"(",
"link",
",",
"mime",
"=",
"True",
")",
"if",
"mime_type",
"==",
"'application/pdf'",
":",
"structuredfeature",
"=",
"extract_pdf",
"(",
"link",
")",
"elif",
"mime_type",
"==",
"'text/plain'",
":",
"structuredfeature",
"=",
"extract_text",
"(",
"link",
")",
"else",
":",
"structuredfeature",
"=",
"None",
"if",
"not",
"structuredfeature",
":",
"continue",
"fset_name",
"=",
"mime_type",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"+",
"'_text'",
"if",
"not",
"fset_name",
"in",
"self",
".",
"full_text",
":",
"self",
".",
"full_text",
"[",
"fset_name",
"]",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'index_by'",
")",
":",
"ident",
"=",
"getattr",
"(",
"entry",
",",
"self",
".",
"index_by",
")",
"if",
"type",
"(",
"ident",
")",
"is",
"list",
":",
"ident",
"=",
"ident",
"[",
"0",
"]",
"else",
":",
"# If `index_by` is not set, use `uri` by default.",
"ident",
"=",
"entry",
".",
"uri",
"self",
".",
"full_text",
"[",
"fset_name",
"]",
"[",
"ident",
"]",
"=",
"structuredfeature"
] |
Attempt to load full-text content from resource.
|
[
"Attempt",
"to",
"load",
"full",
"-",
"text",
"content",
"from",
"resource",
"."
] |
ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f
|
https://github.com/diging/tethne/blob/ba10eeb264b7a3f2dbcce71cfd5cb2d6bbf7055f/tethne/readers/zotero.py#L351-L388
|
10,113
|
web-push-libs/pywebpush
|
pywebpush/__init__.py
|
webpush
|
def webpush(subscription_info,
data=None,
vapid_private_key=None,
vapid_claims=None,
content_encoding="aes128gcm",
curl=False,
timeout=None,
ttl=0):
"""
One call solution to endcode and send `data` to the endpoint
contained in `subscription_info` using optional VAPID auth headers.
in example:
.. code-block:: python
from pywebpush import python
webpush(
subscription_info={
"endpoint": "https://push.example.com/v1/abcd",
"keys": {"p256dh": "0123abcd...",
"auth": "001122..."}
},
data="Mary had a little lamb, with a nice mint jelly",
vapid_private_key="path/to/key.pem",
vapid_claims={"sub": "YourNameHere@example.com"}
)
No additional method call is required. Any non-success will throw a
`WebPushException`.
:param subscription_info: Provided by the client call
:type subscription_info: dict
:param data: Serialized data to send
:type data: str
:param vapid_private_key: Vapid instance or path to vapid private key PEM \
or encoded str
:type vapid_private_key: Union[Vapid, str]
:param vapid_claims: Dictionary of claims ('sub' required)
:type vapid_claims: dict
:param content_encoding: Optional content type string
:type content_encoding: str
:param curl: Return as "curl" string instead of sending
:type curl: bool
:param timeout: POST requests timeout
:type timeout: float or tuple
:param ttl: Time To Live
:type ttl: int
:return requests.Response or string
"""
vapid_headers = None
if vapid_claims:
if not vapid_claims.get('aud'):
url = urlparse(subscription_info.get('endpoint'))
aud = "{}://{}".format(url.scheme, url.netloc)
vapid_claims['aud'] = aud
if not vapid_claims.get('exp'):
# encryption lives for 12 hours
vapid_claims['exp'] = int(time.time()) + (12 * 60 * 60)
if not vapid_private_key:
raise WebPushException("VAPID dict missing 'private_key'")
if isinstance(vapid_private_key, Vapid):
vv = vapid_private_key
elif os.path.isfile(vapid_private_key):
# Presume that key from file is handled correctly by
# py_vapid.
vv = Vapid.from_file(
private_key_file=vapid_private_key) # pragma no cover
else:
vv = Vapid.from_string(private_key=vapid_private_key)
vapid_headers = vv.sign(vapid_claims)
response = WebPusher(subscription_info).send(
data,
vapid_headers,
ttl=ttl,
content_encoding=content_encoding,
curl=curl,
timeout=timeout,
)
if not curl and response.status_code > 202:
raise WebPushException("Push failed: {} {}".format(
response.status_code, response.reason),
response=response)
return response
|
python
|
def webpush(subscription_info,
data=None,
vapid_private_key=None,
vapid_claims=None,
content_encoding="aes128gcm",
curl=False,
timeout=None,
ttl=0):
"""
One call solution to endcode and send `data` to the endpoint
contained in `subscription_info` using optional VAPID auth headers.
in example:
.. code-block:: python
from pywebpush import python
webpush(
subscription_info={
"endpoint": "https://push.example.com/v1/abcd",
"keys": {"p256dh": "0123abcd...",
"auth": "001122..."}
},
data="Mary had a little lamb, with a nice mint jelly",
vapid_private_key="path/to/key.pem",
vapid_claims={"sub": "YourNameHere@example.com"}
)
No additional method call is required. Any non-success will throw a
`WebPushException`.
:param subscription_info: Provided by the client call
:type subscription_info: dict
:param data: Serialized data to send
:type data: str
:param vapid_private_key: Vapid instance or path to vapid private key PEM \
or encoded str
:type vapid_private_key: Union[Vapid, str]
:param vapid_claims: Dictionary of claims ('sub' required)
:type vapid_claims: dict
:param content_encoding: Optional content type string
:type content_encoding: str
:param curl: Return as "curl" string instead of sending
:type curl: bool
:param timeout: POST requests timeout
:type timeout: float or tuple
:param ttl: Time To Live
:type ttl: int
:return requests.Response or string
"""
vapid_headers = None
if vapid_claims:
if not vapid_claims.get('aud'):
url = urlparse(subscription_info.get('endpoint'))
aud = "{}://{}".format(url.scheme, url.netloc)
vapid_claims['aud'] = aud
if not vapid_claims.get('exp'):
# encryption lives for 12 hours
vapid_claims['exp'] = int(time.time()) + (12 * 60 * 60)
if not vapid_private_key:
raise WebPushException("VAPID dict missing 'private_key'")
if isinstance(vapid_private_key, Vapid):
vv = vapid_private_key
elif os.path.isfile(vapid_private_key):
# Presume that key from file is handled correctly by
# py_vapid.
vv = Vapid.from_file(
private_key_file=vapid_private_key) # pragma no cover
else:
vv = Vapid.from_string(private_key=vapid_private_key)
vapid_headers = vv.sign(vapid_claims)
response = WebPusher(subscription_info).send(
data,
vapid_headers,
ttl=ttl,
content_encoding=content_encoding,
curl=curl,
timeout=timeout,
)
if not curl and response.status_code > 202:
raise WebPushException("Push failed: {} {}".format(
response.status_code, response.reason),
response=response)
return response
|
[
"def",
"webpush",
"(",
"subscription_info",
",",
"data",
"=",
"None",
",",
"vapid_private_key",
"=",
"None",
",",
"vapid_claims",
"=",
"None",
",",
"content_encoding",
"=",
"\"aes128gcm\"",
",",
"curl",
"=",
"False",
",",
"timeout",
"=",
"None",
",",
"ttl",
"=",
"0",
")",
":",
"vapid_headers",
"=",
"None",
"if",
"vapid_claims",
":",
"if",
"not",
"vapid_claims",
".",
"get",
"(",
"'aud'",
")",
":",
"url",
"=",
"urlparse",
"(",
"subscription_info",
".",
"get",
"(",
"'endpoint'",
")",
")",
"aud",
"=",
"\"{}://{}\"",
".",
"format",
"(",
"url",
".",
"scheme",
",",
"url",
".",
"netloc",
")",
"vapid_claims",
"[",
"'aud'",
"]",
"=",
"aud",
"if",
"not",
"vapid_claims",
".",
"get",
"(",
"'exp'",
")",
":",
"# encryption lives for 12 hours",
"vapid_claims",
"[",
"'exp'",
"]",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"+",
"(",
"12",
"*",
"60",
"*",
"60",
")",
"if",
"not",
"vapid_private_key",
":",
"raise",
"WebPushException",
"(",
"\"VAPID dict missing 'private_key'\"",
")",
"if",
"isinstance",
"(",
"vapid_private_key",
",",
"Vapid",
")",
":",
"vv",
"=",
"vapid_private_key",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"vapid_private_key",
")",
":",
"# Presume that key from file is handled correctly by",
"# py_vapid.",
"vv",
"=",
"Vapid",
".",
"from_file",
"(",
"private_key_file",
"=",
"vapid_private_key",
")",
"# pragma no cover",
"else",
":",
"vv",
"=",
"Vapid",
".",
"from_string",
"(",
"private_key",
"=",
"vapid_private_key",
")",
"vapid_headers",
"=",
"vv",
".",
"sign",
"(",
"vapid_claims",
")",
"response",
"=",
"WebPusher",
"(",
"subscription_info",
")",
".",
"send",
"(",
"data",
",",
"vapid_headers",
",",
"ttl",
"=",
"ttl",
",",
"content_encoding",
"=",
"content_encoding",
",",
"curl",
"=",
"curl",
",",
"timeout",
"=",
"timeout",
",",
")",
"if",
"not",
"curl",
"and",
"response",
".",
"status_code",
">",
"202",
":",
"raise",
"WebPushException",
"(",
"\"Push failed: {} {}\"",
".",
"format",
"(",
"response",
".",
"status_code",
",",
"response",
".",
"reason",
")",
",",
"response",
"=",
"response",
")",
"return",
"response"
] |
One call solution to endcode and send `data` to the endpoint
contained in `subscription_info` using optional VAPID auth headers.
in example:
.. code-block:: python
from pywebpush import python
webpush(
subscription_info={
"endpoint": "https://push.example.com/v1/abcd",
"keys": {"p256dh": "0123abcd...",
"auth": "001122..."}
},
data="Mary had a little lamb, with a nice mint jelly",
vapid_private_key="path/to/key.pem",
vapid_claims={"sub": "YourNameHere@example.com"}
)
No additional method call is required. Any non-success will throw a
`WebPushException`.
:param subscription_info: Provided by the client call
:type subscription_info: dict
:param data: Serialized data to send
:type data: str
:param vapid_private_key: Vapid instance or path to vapid private key PEM \
or encoded str
:type vapid_private_key: Union[Vapid, str]
:param vapid_claims: Dictionary of claims ('sub' required)
:type vapid_claims: dict
:param content_encoding: Optional content type string
:type content_encoding: str
:param curl: Return as "curl" string instead of sending
:type curl: bool
:param timeout: POST requests timeout
:type timeout: float or tuple
:param ttl: Time To Live
:type ttl: int
:return requests.Response or string
|
[
"One",
"call",
"solution",
"to",
"endcode",
"and",
"send",
"data",
"to",
"the",
"endpoint",
"contained",
"in",
"subscription_info",
"using",
"optional",
"VAPID",
"auth",
"headers",
"."
] |
2a23f45b7819e31bd030de9fe1357a1cf7dcfdc4
|
https://github.com/web-push-libs/pywebpush/blob/2a23f45b7819e31bd030de9fe1357a1cf7dcfdc4/pywebpush/__init__.py#L350-L435
|
10,114
|
web-push-libs/pywebpush
|
pywebpush/__init__.py
|
WebPusher.encode
|
def encode(self, data, content_encoding="aes128gcm"):
"""Encrypt the data.
:param data: A serialized block of byte data (String, JSON, bit array,
etc.) Make sure that whatever you send, your client knows how
to understand it.
:type data: str
:param content_encoding: The content_encoding type to use to encrypt
the data. Defaults to RFC8188 "aes128gcm". The previous draft-01 is
"aesgcm", however this format is now deprecated.
:type content_encoding: enum("aesgcm", "aes128gcm")
"""
# Salt is a random 16 byte array.
if not data:
return
if not self.auth_key or not self.receiver_key:
raise WebPushException("No keys specified in subscription info")
salt = None
if content_encoding not in self.valid_encodings:
raise WebPushException("Invalid content encoding specified. "
"Select from " +
json.dumps(self.valid_encodings))
if content_encoding == "aesgcm":
salt = os.urandom(16)
# The server key is an ephemeral ECDH key used only for this
# transaction
server_key = ec.generate_private_key(ec.SECP256R1, default_backend())
crypto_key = server_key.public_key().public_bytes(
encoding=serialization.Encoding.X962,
format=serialization.PublicFormat.UncompressedPoint
)
if isinstance(data, six.string_types):
data = bytes(data.encode('utf8'))
if content_encoding == "aes128gcm":
encrypted = http_ece.encrypt(
data,
salt=salt,
private_key=server_key,
dh=self.receiver_key,
auth_secret=self.auth_key,
version=content_encoding)
reply = CaseInsensitiveDict({
'body': encrypted
})
else:
crypto_key = base64.urlsafe_b64encode(crypto_key).strip(b'=')
encrypted = http_ece.encrypt(
data,
salt=salt,
private_key=server_key,
keyid=crypto_key.decode(),
dh=self.receiver_key,
auth_secret=self.auth_key,
version=content_encoding)
reply = CaseInsensitiveDict({
'crypto_key': crypto_key,
'body': encrypted,
})
if salt:
reply['salt'] = base64.urlsafe_b64encode(salt).strip(b'=')
return reply
|
python
|
def encode(self, data, content_encoding="aes128gcm"):
"""Encrypt the data.
:param data: A serialized block of byte data (String, JSON, bit array,
etc.) Make sure that whatever you send, your client knows how
to understand it.
:type data: str
:param content_encoding: The content_encoding type to use to encrypt
the data. Defaults to RFC8188 "aes128gcm". The previous draft-01 is
"aesgcm", however this format is now deprecated.
:type content_encoding: enum("aesgcm", "aes128gcm")
"""
# Salt is a random 16 byte array.
if not data:
return
if not self.auth_key or not self.receiver_key:
raise WebPushException("No keys specified in subscription info")
salt = None
if content_encoding not in self.valid_encodings:
raise WebPushException("Invalid content encoding specified. "
"Select from " +
json.dumps(self.valid_encodings))
if content_encoding == "aesgcm":
salt = os.urandom(16)
# The server key is an ephemeral ECDH key used only for this
# transaction
server_key = ec.generate_private_key(ec.SECP256R1, default_backend())
crypto_key = server_key.public_key().public_bytes(
encoding=serialization.Encoding.X962,
format=serialization.PublicFormat.UncompressedPoint
)
if isinstance(data, six.string_types):
data = bytes(data.encode('utf8'))
if content_encoding == "aes128gcm":
encrypted = http_ece.encrypt(
data,
salt=salt,
private_key=server_key,
dh=self.receiver_key,
auth_secret=self.auth_key,
version=content_encoding)
reply = CaseInsensitiveDict({
'body': encrypted
})
else:
crypto_key = base64.urlsafe_b64encode(crypto_key).strip(b'=')
encrypted = http_ece.encrypt(
data,
salt=salt,
private_key=server_key,
keyid=crypto_key.decode(),
dh=self.receiver_key,
auth_secret=self.auth_key,
version=content_encoding)
reply = CaseInsensitiveDict({
'crypto_key': crypto_key,
'body': encrypted,
})
if salt:
reply['salt'] = base64.urlsafe_b64encode(salt).strip(b'=')
return reply
|
[
"def",
"encode",
"(",
"self",
",",
"data",
",",
"content_encoding",
"=",
"\"aes128gcm\"",
")",
":",
"# Salt is a random 16 byte array.",
"if",
"not",
"data",
":",
"return",
"if",
"not",
"self",
".",
"auth_key",
"or",
"not",
"self",
".",
"receiver_key",
":",
"raise",
"WebPushException",
"(",
"\"No keys specified in subscription info\"",
")",
"salt",
"=",
"None",
"if",
"content_encoding",
"not",
"in",
"self",
".",
"valid_encodings",
":",
"raise",
"WebPushException",
"(",
"\"Invalid content encoding specified. \"",
"\"Select from \"",
"+",
"json",
".",
"dumps",
"(",
"self",
".",
"valid_encodings",
")",
")",
"if",
"content_encoding",
"==",
"\"aesgcm\"",
":",
"salt",
"=",
"os",
".",
"urandom",
"(",
"16",
")",
"# The server key is an ephemeral ECDH key used only for this",
"# transaction",
"server_key",
"=",
"ec",
".",
"generate_private_key",
"(",
"ec",
".",
"SECP256R1",
",",
"default_backend",
"(",
")",
")",
"crypto_key",
"=",
"server_key",
".",
"public_key",
"(",
")",
".",
"public_bytes",
"(",
"encoding",
"=",
"serialization",
".",
"Encoding",
".",
"X962",
",",
"format",
"=",
"serialization",
".",
"PublicFormat",
".",
"UncompressedPoint",
")",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"string_types",
")",
":",
"data",
"=",
"bytes",
"(",
"data",
".",
"encode",
"(",
"'utf8'",
")",
")",
"if",
"content_encoding",
"==",
"\"aes128gcm\"",
":",
"encrypted",
"=",
"http_ece",
".",
"encrypt",
"(",
"data",
",",
"salt",
"=",
"salt",
",",
"private_key",
"=",
"server_key",
",",
"dh",
"=",
"self",
".",
"receiver_key",
",",
"auth_secret",
"=",
"self",
".",
"auth_key",
",",
"version",
"=",
"content_encoding",
")",
"reply",
"=",
"CaseInsensitiveDict",
"(",
"{",
"'body'",
":",
"encrypted",
"}",
")",
"else",
":",
"crypto_key",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"crypto_key",
")",
".",
"strip",
"(",
"b'='",
")",
"encrypted",
"=",
"http_ece",
".",
"encrypt",
"(",
"data",
",",
"salt",
"=",
"salt",
",",
"private_key",
"=",
"server_key",
",",
"keyid",
"=",
"crypto_key",
".",
"decode",
"(",
")",
",",
"dh",
"=",
"self",
".",
"receiver_key",
",",
"auth_secret",
"=",
"self",
".",
"auth_key",
",",
"version",
"=",
"content_encoding",
")",
"reply",
"=",
"CaseInsensitiveDict",
"(",
"{",
"'crypto_key'",
":",
"crypto_key",
",",
"'body'",
":",
"encrypted",
",",
"}",
")",
"if",
"salt",
":",
"reply",
"[",
"'salt'",
"]",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"salt",
")",
".",
"strip",
"(",
"b'='",
")",
"return",
"reply"
] |
Encrypt the data.
:param data: A serialized block of byte data (String, JSON, bit array,
etc.) Make sure that whatever you send, your client knows how
to understand it.
:type data: str
:param content_encoding: The content_encoding type to use to encrypt
the data. Defaults to RFC8188 "aes128gcm". The previous draft-01 is
"aesgcm", however this format is now deprecated.
:type content_encoding: enum("aesgcm", "aes128gcm")
|
[
"Encrypt",
"the",
"data",
"."
] |
2a23f45b7819e31bd030de9fe1357a1cf7dcfdc4
|
https://github.com/web-push-libs/pywebpush/blob/2a23f45b7819e31bd030de9fe1357a1cf7dcfdc4/pywebpush/__init__.py#L162-L224
|
10,115
|
web-push-libs/pywebpush
|
pywebpush/__init__.py
|
WebPusher.send
|
def send(self, data=None, headers=None, ttl=0, gcm_key=None, reg_id=None,
content_encoding="aes128gcm", curl=False, timeout=None):
"""Encode and send the data to the Push Service.
:param data: A serialized block of data (see encode() ).
:type data: str
:param headers: A dictionary containing any additional HTTP headers.
:type headers: dict
:param ttl: The Time To Live in seconds for this message if the
recipient is not online. (Defaults to "0", which discards the
message immediately if the recipient is unavailable.)
:type ttl: int
:param gcm_key: API key obtained from the Google Developer Console.
Needed if endpoint is https://android.googleapis.com/gcm/send
:type gcm_key: string
:param reg_id: registration id of the recipient. If not provided,
it will be extracted from the endpoint.
:type reg_id: str
:param content_encoding: ECE content encoding (defaults to "aes128gcm")
:type content_encoding: str
:param curl: Display output as `curl` command instead of sending
:type curl: bool
:param timeout: POST requests timeout
:type timeout: float or tuple
"""
# Encode the data.
if headers is None:
headers = dict()
encoded = {}
headers = CaseInsensitiveDict(headers)
if data:
encoded = self.encode(data, content_encoding)
if "crypto_key" in encoded:
# Append the p256dh to the end of any existing crypto-key
crypto_key = headers.get("crypto-key", "")
if crypto_key:
# due to some confusion by a push service provider, we
# should use ';' instead of ',' to append the headers.
# see
# https://github.com/webpush-wg/webpush-encryption/issues/6
crypto_key += ';'
crypto_key += (
"dh=" + encoded["crypto_key"].decode('utf8'))
headers.update({
'crypto-key': crypto_key
})
if "salt" in encoded:
headers.update({
'encryption': "salt=" + encoded['salt'].decode('utf8')
})
headers.update({
'content-encoding': content_encoding,
})
if gcm_key:
# guess if it is a legacy GCM project key or actual FCM key
# gcm keys are all about 40 chars (use 100 for confidence),
# fcm keys are 153-175 chars
if len(gcm_key) < 100:
endpoint = 'https://android.googleapis.com/gcm/send'
else:
endpoint = 'https://fcm.googleapis.com/fcm/send'
reg_ids = []
if not reg_id:
reg_id = self.subscription_info['endpoint'].rsplit('/', 1)[-1]
reg_ids.append(reg_id)
gcm_data = dict()
gcm_data['registration_ids'] = reg_ids
if data:
gcm_data['raw_data'] = base64.b64encode(
encoded.get('body')).decode('utf8')
gcm_data['time_to_live'] = int(
headers['ttl'] if 'ttl' in headers else ttl)
encoded_data = json.dumps(gcm_data)
headers.update({
'Authorization': 'key='+gcm_key,
'Content-Type': 'application/json',
})
else:
encoded_data = encoded.get('body')
endpoint = self.subscription_info['endpoint']
if 'ttl' not in headers or ttl:
headers['ttl'] = str(ttl or 0)
# Additionally useful headers:
# Authorization / Crypto-Key (VAPID headers)
if curl:
return self.as_curl(endpoint, encoded_data, headers)
return self.requests_method.post(endpoint,
data=encoded_data,
headers=headers,
timeout=timeout)
|
python
|
def send(self, data=None, headers=None, ttl=0, gcm_key=None, reg_id=None,
content_encoding="aes128gcm", curl=False, timeout=None):
"""Encode and send the data to the Push Service.
:param data: A serialized block of data (see encode() ).
:type data: str
:param headers: A dictionary containing any additional HTTP headers.
:type headers: dict
:param ttl: The Time To Live in seconds for this message if the
recipient is not online. (Defaults to "0", which discards the
message immediately if the recipient is unavailable.)
:type ttl: int
:param gcm_key: API key obtained from the Google Developer Console.
Needed if endpoint is https://android.googleapis.com/gcm/send
:type gcm_key: string
:param reg_id: registration id of the recipient. If not provided,
it will be extracted from the endpoint.
:type reg_id: str
:param content_encoding: ECE content encoding (defaults to "aes128gcm")
:type content_encoding: str
:param curl: Display output as `curl` command instead of sending
:type curl: bool
:param timeout: POST requests timeout
:type timeout: float or tuple
"""
# Encode the data.
if headers is None:
headers = dict()
encoded = {}
headers = CaseInsensitiveDict(headers)
if data:
encoded = self.encode(data, content_encoding)
if "crypto_key" in encoded:
# Append the p256dh to the end of any existing crypto-key
crypto_key = headers.get("crypto-key", "")
if crypto_key:
# due to some confusion by a push service provider, we
# should use ';' instead of ',' to append the headers.
# see
# https://github.com/webpush-wg/webpush-encryption/issues/6
crypto_key += ';'
crypto_key += (
"dh=" + encoded["crypto_key"].decode('utf8'))
headers.update({
'crypto-key': crypto_key
})
if "salt" in encoded:
headers.update({
'encryption': "salt=" + encoded['salt'].decode('utf8')
})
headers.update({
'content-encoding': content_encoding,
})
if gcm_key:
# guess if it is a legacy GCM project key or actual FCM key
# gcm keys are all about 40 chars (use 100 for confidence),
# fcm keys are 153-175 chars
if len(gcm_key) < 100:
endpoint = 'https://android.googleapis.com/gcm/send'
else:
endpoint = 'https://fcm.googleapis.com/fcm/send'
reg_ids = []
if not reg_id:
reg_id = self.subscription_info['endpoint'].rsplit('/', 1)[-1]
reg_ids.append(reg_id)
gcm_data = dict()
gcm_data['registration_ids'] = reg_ids
if data:
gcm_data['raw_data'] = base64.b64encode(
encoded.get('body')).decode('utf8')
gcm_data['time_to_live'] = int(
headers['ttl'] if 'ttl' in headers else ttl)
encoded_data = json.dumps(gcm_data)
headers.update({
'Authorization': 'key='+gcm_key,
'Content-Type': 'application/json',
})
else:
encoded_data = encoded.get('body')
endpoint = self.subscription_info['endpoint']
if 'ttl' not in headers or ttl:
headers['ttl'] = str(ttl or 0)
# Additionally useful headers:
# Authorization / Crypto-Key (VAPID headers)
if curl:
return self.as_curl(endpoint, encoded_data, headers)
return self.requests_method.post(endpoint,
data=encoded_data,
headers=headers,
timeout=timeout)
|
[
"def",
"send",
"(",
"self",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"ttl",
"=",
"0",
",",
"gcm_key",
"=",
"None",
",",
"reg_id",
"=",
"None",
",",
"content_encoding",
"=",
"\"aes128gcm\"",
",",
"curl",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"# Encode the data.",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"dict",
"(",
")",
"encoded",
"=",
"{",
"}",
"headers",
"=",
"CaseInsensitiveDict",
"(",
"headers",
")",
"if",
"data",
":",
"encoded",
"=",
"self",
".",
"encode",
"(",
"data",
",",
"content_encoding",
")",
"if",
"\"crypto_key\"",
"in",
"encoded",
":",
"# Append the p256dh to the end of any existing crypto-key",
"crypto_key",
"=",
"headers",
".",
"get",
"(",
"\"crypto-key\"",
",",
"\"\"",
")",
"if",
"crypto_key",
":",
"# due to some confusion by a push service provider, we",
"# should use ';' instead of ',' to append the headers.",
"# see",
"# https://github.com/webpush-wg/webpush-encryption/issues/6",
"crypto_key",
"+=",
"';'",
"crypto_key",
"+=",
"(",
"\"dh=\"",
"+",
"encoded",
"[",
"\"crypto_key\"",
"]",
".",
"decode",
"(",
"'utf8'",
")",
")",
"headers",
".",
"update",
"(",
"{",
"'crypto-key'",
":",
"crypto_key",
"}",
")",
"if",
"\"salt\"",
"in",
"encoded",
":",
"headers",
".",
"update",
"(",
"{",
"'encryption'",
":",
"\"salt=\"",
"+",
"encoded",
"[",
"'salt'",
"]",
".",
"decode",
"(",
"'utf8'",
")",
"}",
")",
"headers",
".",
"update",
"(",
"{",
"'content-encoding'",
":",
"content_encoding",
",",
"}",
")",
"if",
"gcm_key",
":",
"# guess if it is a legacy GCM project key or actual FCM key",
"# gcm keys are all about 40 chars (use 100 for confidence),",
"# fcm keys are 153-175 chars",
"if",
"len",
"(",
"gcm_key",
")",
"<",
"100",
":",
"endpoint",
"=",
"'https://android.googleapis.com/gcm/send'",
"else",
":",
"endpoint",
"=",
"'https://fcm.googleapis.com/fcm/send'",
"reg_ids",
"=",
"[",
"]",
"if",
"not",
"reg_id",
":",
"reg_id",
"=",
"self",
".",
"subscription_info",
"[",
"'endpoint'",
"]",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"[",
"-",
"1",
"]",
"reg_ids",
".",
"append",
"(",
"reg_id",
")",
"gcm_data",
"=",
"dict",
"(",
")",
"gcm_data",
"[",
"'registration_ids'",
"]",
"=",
"reg_ids",
"if",
"data",
":",
"gcm_data",
"[",
"'raw_data'",
"]",
"=",
"base64",
".",
"b64encode",
"(",
"encoded",
".",
"get",
"(",
"'body'",
")",
")",
".",
"decode",
"(",
"'utf8'",
")",
"gcm_data",
"[",
"'time_to_live'",
"]",
"=",
"int",
"(",
"headers",
"[",
"'ttl'",
"]",
"if",
"'ttl'",
"in",
"headers",
"else",
"ttl",
")",
"encoded_data",
"=",
"json",
".",
"dumps",
"(",
"gcm_data",
")",
"headers",
".",
"update",
"(",
"{",
"'Authorization'",
":",
"'key='",
"+",
"gcm_key",
",",
"'Content-Type'",
":",
"'application/json'",
",",
"}",
")",
"else",
":",
"encoded_data",
"=",
"encoded",
".",
"get",
"(",
"'body'",
")",
"endpoint",
"=",
"self",
".",
"subscription_info",
"[",
"'endpoint'",
"]",
"if",
"'ttl'",
"not",
"in",
"headers",
"or",
"ttl",
":",
"headers",
"[",
"'ttl'",
"]",
"=",
"str",
"(",
"ttl",
"or",
"0",
")",
"# Additionally useful headers:",
"# Authorization / Crypto-Key (VAPID headers)",
"if",
"curl",
":",
"return",
"self",
".",
"as_curl",
"(",
"endpoint",
",",
"encoded_data",
",",
"headers",
")",
"return",
"self",
".",
"requests_method",
".",
"post",
"(",
"endpoint",
",",
"data",
"=",
"encoded_data",
",",
"headers",
"=",
"headers",
",",
"timeout",
"=",
"timeout",
")"
] |
Encode and send the data to the Push Service.
:param data: A serialized block of data (see encode() ).
:type data: str
:param headers: A dictionary containing any additional HTTP headers.
:type headers: dict
:param ttl: The Time To Live in seconds for this message if the
recipient is not online. (Defaults to "0", which discards the
message immediately if the recipient is unavailable.)
:type ttl: int
:param gcm_key: API key obtained from the Google Developer Console.
Needed if endpoint is https://android.googleapis.com/gcm/send
:type gcm_key: string
:param reg_id: registration id of the recipient. If not provided,
it will be extracted from the endpoint.
:type reg_id: str
:param content_encoding: ECE content encoding (defaults to "aes128gcm")
:type content_encoding: str
:param curl: Display output as `curl` command instead of sending
:type curl: bool
:param timeout: POST requests timeout
:type timeout: float or tuple
|
[
"Encode",
"and",
"send",
"the",
"data",
"to",
"the",
"Push",
"Service",
"."
] |
2a23f45b7819e31bd030de9fe1357a1cf7dcfdc4
|
https://github.com/web-push-libs/pywebpush/blob/2a23f45b7819e31bd030de9fe1357a1cf7dcfdc4/pywebpush/__init__.py#L256-L347
|
10,116
|
martijnvermaat/calmap
|
calmap/__init__.py
|
calendarplot
|
def calendarplot(data, how='sum', yearlabels=True, yearascending=True, yearlabel_kws=None,
subplot_kws=None, gridspec_kws=None, fig_kws=None, **kwargs):
"""
Plot a timeseries as a calendar heatmap.
Parameters
----------
data : Series
Data for the plot. Must be indexed by a DatetimeIndex.
how : string
Method for resampling data by day. If `None`, assume data is already
sampled by day and don't resample. Otherwise, this is passed to Pandas
`Series.resample`.
yearlabels : bool
Whether or not to draw the year for each subplot.
yearascending : bool
Sort the calendar in ascending or descending order.
yearlabel_kws : dict
Keyword arguments passed to the matplotlib `set_ylabel` call which is
used to draw the year for each subplot.
subplot_kws : dict
Keyword arguments passed to the matplotlib `add_subplot` call used to
create each subplot.
gridspec_kws : dict
Keyword arguments passed to the matplotlib `GridSpec` constructor used
to create the grid the subplots are placed on.
fig_kws : dict
Keyword arguments passed to the matplotlib `figure` call.
kwargs : other keyword arguments
All other keyword arguments are passed to `yearplot`.
Returns
-------
fig, axes : matplotlib Figure and Axes
Tuple where `fig` is the matplotlib Figure object `axes` is an array
of matplotlib Axes objects with the calendar heatmaps, one per year.
Examples
--------
With `calendarplot` we can plot several years in one figure:
.. plot::
:context: close-figs
calmap.calendarplot(events)
"""
yearlabel_kws = yearlabel_kws or {}
subplot_kws = subplot_kws or {}
gridspec_kws = gridspec_kws or {}
fig_kws = fig_kws or {}
years = np.unique(data.index.year)
if not yearascending:
years = years[::-1]
fig, axes = plt.subplots(nrows=len(years), ncols=1, squeeze=False,
subplot_kw=subplot_kws,
gridspec_kw=gridspec_kws, **fig_kws)
axes = axes.T[0]
# We explicitely resample by day only once. This is an optimization.
if how is None:
by_day = data
else:
if _pandas_18:
by_day = data.resample('D').agg(how)
else:
by_day = data.resample('D', how=how)
ylabel_kws = dict(
fontsize=32,
color=kwargs.get('fillcolor', 'whitesmoke'),
fontweight='bold',
fontname='Arial',
ha='center')
ylabel_kws.update(yearlabel_kws)
max_weeks = 0
for year, ax in zip(years, axes):
yearplot(by_day, year=year, how=None, ax=ax, **kwargs)
max_weeks = max(max_weeks, ax.get_xlim()[1])
if yearlabels:
ax.set_ylabel(str(year), **ylabel_kws)
# In a leap year it might happen that we have 54 weeks (e.g., 2012).
# Here we make sure the width is consistent over all years.
for ax in axes:
ax.set_xlim(0, max_weeks)
# Make the axes look good.
plt.tight_layout()
return fig, axes
|
python
|
def calendarplot(data, how='sum', yearlabels=True, yearascending=True, yearlabel_kws=None,
subplot_kws=None, gridspec_kws=None, fig_kws=None, **kwargs):
"""
Plot a timeseries as a calendar heatmap.
Parameters
----------
data : Series
Data for the plot. Must be indexed by a DatetimeIndex.
how : string
Method for resampling data by day. If `None`, assume data is already
sampled by day and don't resample. Otherwise, this is passed to Pandas
`Series.resample`.
yearlabels : bool
Whether or not to draw the year for each subplot.
yearascending : bool
Sort the calendar in ascending or descending order.
yearlabel_kws : dict
Keyword arguments passed to the matplotlib `set_ylabel` call which is
used to draw the year for each subplot.
subplot_kws : dict
Keyword arguments passed to the matplotlib `add_subplot` call used to
create each subplot.
gridspec_kws : dict
Keyword arguments passed to the matplotlib `GridSpec` constructor used
to create the grid the subplots are placed on.
fig_kws : dict
Keyword arguments passed to the matplotlib `figure` call.
kwargs : other keyword arguments
All other keyword arguments are passed to `yearplot`.
Returns
-------
fig, axes : matplotlib Figure and Axes
Tuple where `fig` is the matplotlib Figure object `axes` is an array
of matplotlib Axes objects with the calendar heatmaps, one per year.
Examples
--------
With `calendarplot` we can plot several years in one figure:
.. plot::
:context: close-figs
calmap.calendarplot(events)
"""
yearlabel_kws = yearlabel_kws or {}
subplot_kws = subplot_kws or {}
gridspec_kws = gridspec_kws or {}
fig_kws = fig_kws or {}
years = np.unique(data.index.year)
if not yearascending:
years = years[::-1]
fig, axes = plt.subplots(nrows=len(years), ncols=1, squeeze=False,
subplot_kw=subplot_kws,
gridspec_kw=gridspec_kws, **fig_kws)
axes = axes.T[0]
# We explicitely resample by day only once. This is an optimization.
if how is None:
by_day = data
else:
if _pandas_18:
by_day = data.resample('D').agg(how)
else:
by_day = data.resample('D', how=how)
ylabel_kws = dict(
fontsize=32,
color=kwargs.get('fillcolor', 'whitesmoke'),
fontweight='bold',
fontname='Arial',
ha='center')
ylabel_kws.update(yearlabel_kws)
max_weeks = 0
for year, ax in zip(years, axes):
yearplot(by_day, year=year, how=None, ax=ax, **kwargs)
max_weeks = max(max_weeks, ax.get_xlim()[1])
if yearlabels:
ax.set_ylabel(str(year), **ylabel_kws)
# In a leap year it might happen that we have 54 weeks (e.g., 2012).
# Here we make sure the width is consistent over all years.
for ax in axes:
ax.set_xlim(0, max_weeks)
# Make the axes look good.
plt.tight_layout()
return fig, axes
|
[
"def",
"calendarplot",
"(",
"data",
",",
"how",
"=",
"'sum'",
",",
"yearlabels",
"=",
"True",
",",
"yearascending",
"=",
"True",
",",
"yearlabel_kws",
"=",
"None",
",",
"subplot_kws",
"=",
"None",
",",
"gridspec_kws",
"=",
"None",
",",
"fig_kws",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"yearlabel_kws",
"=",
"yearlabel_kws",
"or",
"{",
"}",
"subplot_kws",
"=",
"subplot_kws",
"or",
"{",
"}",
"gridspec_kws",
"=",
"gridspec_kws",
"or",
"{",
"}",
"fig_kws",
"=",
"fig_kws",
"or",
"{",
"}",
"years",
"=",
"np",
".",
"unique",
"(",
"data",
".",
"index",
".",
"year",
")",
"if",
"not",
"yearascending",
":",
"years",
"=",
"years",
"[",
":",
":",
"-",
"1",
"]",
"fig",
",",
"axes",
"=",
"plt",
".",
"subplots",
"(",
"nrows",
"=",
"len",
"(",
"years",
")",
",",
"ncols",
"=",
"1",
",",
"squeeze",
"=",
"False",
",",
"subplot_kw",
"=",
"subplot_kws",
",",
"gridspec_kw",
"=",
"gridspec_kws",
",",
"*",
"*",
"fig_kws",
")",
"axes",
"=",
"axes",
".",
"T",
"[",
"0",
"]",
"# We explicitely resample by day only once. This is an optimization.",
"if",
"how",
"is",
"None",
":",
"by_day",
"=",
"data",
"else",
":",
"if",
"_pandas_18",
":",
"by_day",
"=",
"data",
".",
"resample",
"(",
"'D'",
")",
".",
"agg",
"(",
"how",
")",
"else",
":",
"by_day",
"=",
"data",
".",
"resample",
"(",
"'D'",
",",
"how",
"=",
"how",
")",
"ylabel_kws",
"=",
"dict",
"(",
"fontsize",
"=",
"32",
",",
"color",
"=",
"kwargs",
".",
"get",
"(",
"'fillcolor'",
",",
"'whitesmoke'",
")",
",",
"fontweight",
"=",
"'bold'",
",",
"fontname",
"=",
"'Arial'",
",",
"ha",
"=",
"'center'",
")",
"ylabel_kws",
".",
"update",
"(",
"yearlabel_kws",
")",
"max_weeks",
"=",
"0",
"for",
"year",
",",
"ax",
"in",
"zip",
"(",
"years",
",",
"axes",
")",
":",
"yearplot",
"(",
"by_day",
",",
"year",
"=",
"year",
",",
"how",
"=",
"None",
",",
"ax",
"=",
"ax",
",",
"*",
"*",
"kwargs",
")",
"max_weeks",
"=",
"max",
"(",
"max_weeks",
",",
"ax",
".",
"get_xlim",
"(",
")",
"[",
"1",
"]",
")",
"if",
"yearlabels",
":",
"ax",
".",
"set_ylabel",
"(",
"str",
"(",
"year",
")",
",",
"*",
"*",
"ylabel_kws",
")",
"# In a leap year it might happen that we have 54 weeks (e.g., 2012).",
"# Here we make sure the width is consistent over all years.",
"for",
"ax",
"in",
"axes",
":",
"ax",
".",
"set_xlim",
"(",
"0",
",",
"max_weeks",
")",
"# Make the axes look good.",
"plt",
".",
"tight_layout",
"(",
")",
"return",
"fig",
",",
"axes"
] |
Plot a timeseries as a calendar heatmap.
Parameters
----------
data : Series
Data for the plot. Must be indexed by a DatetimeIndex.
how : string
Method for resampling data by day. If `None`, assume data is already
sampled by day and don't resample. Otherwise, this is passed to Pandas
`Series.resample`.
yearlabels : bool
Whether or not to draw the year for each subplot.
yearascending : bool
Sort the calendar in ascending or descending order.
yearlabel_kws : dict
Keyword arguments passed to the matplotlib `set_ylabel` call which is
used to draw the year for each subplot.
subplot_kws : dict
Keyword arguments passed to the matplotlib `add_subplot` call used to
create each subplot.
gridspec_kws : dict
Keyword arguments passed to the matplotlib `GridSpec` constructor used
to create the grid the subplots are placed on.
fig_kws : dict
Keyword arguments passed to the matplotlib `figure` call.
kwargs : other keyword arguments
All other keyword arguments are passed to `yearplot`.
Returns
-------
fig, axes : matplotlib Figure and Axes
Tuple where `fig` is the matplotlib Figure object `axes` is an array
of matplotlib Axes objects with the calendar heatmaps, one per year.
Examples
--------
With `calendarplot` we can plot several years in one figure:
.. plot::
:context: close-figs
calmap.calendarplot(events)
|
[
"Plot",
"a",
"timeseries",
"as",
"a",
"calendar",
"heatmap",
"."
] |
83e2a9a0bdc773c9e48e05772fb412ac8deb8bae
|
https://github.com/martijnvermaat/calmap/blob/83e2a9a0bdc773c9e48e05772fb412ac8deb8bae/calmap/__init__.py#L233-L329
|
10,117
|
Frojd/wagtail-geo-widget
|
wagtailgeowidget/helpers.py
|
geosgeometry_str_to_struct
|
def geosgeometry_str_to_struct(value):
'''
Parses a geosgeometry string into struct.
Example:
SRID=5432;POINT(12.0 13.0)
Returns:
>> [5432, 12.0, 13.0]
'''
result = geos_ptrn.match(value)
if not result:
return None
return {
'srid': result.group(1),
'x': result.group(2),
'y': result.group(3),
}
|
python
|
def geosgeometry_str_to_struct(value):
'''
Parses a geosgeometry string into struct.
Example:
SRID=5432;POINT(12.0 13.0)
Returns:
>> [5432, 12.0, 13.0]
'''
result = geos_ptrn.match(value)
if not result:
return None
return {
'srid': result.group(1),
'x': result.group(2),
'y': result.group(3),
}
|
[
"def",
"geosgeometry_str_to_struct",
"(",
"value",
")",
":",
"result",
"=",
"geos_ptrn",
".",
"match",
"(",
"value",
")",
"if",
"not",
"result",
":",
"return",
"None",
"return",
"{",
"'srid'",
":",
"result",
".",
"group",
"(",
"1",
")",
",",
"'x'",
":",
"result",
".",
"group",
"(",
"2",
")",
",",
"'y'",
":",
"result",
".",
"group",
"(",
"3",
")",
",",
"}"
] |
Parses a geosgeometry string into struct.
Example:
SRID=5432;POINT(12.0 13.0)
Returns:
>> [5432, 12.0, 13.0]
|
[
"Parses",
"a",
"geosgeometry",
"string",
"into",
"struct",
"."
] |
3482891be8903293812738d9128b9bda03b9a2ba
|
https://github.com/Frojd/wagtail-geo-widget/blob/3482891be8903293812738d9128b9bda03b9a2ba/wagtailgeowidget/helpers.py#L8-L27
|
10,118
|
Frojd/wagtail-geo-widget
|
example/examplesite/settings/__init__.py
|
get_env
|
def get_env(name, default=None):
"""Get the environment variable or return exception"""
if name in os.environ:
return os.environ[name]
if default is not None:
return default
error_msg = "Set the {} env variable".format(name)
raise ImproperlyConfigured(error_msg)
|
python
|
def get_env(name, default=None):
"""Get the environment variable or return exception"""
if name in os.environ:
return os.environ[name]
if default is not None:
return default
error_msg = "Set the {} env variable".format(name)
raise ImproperlyConfigured(error_msg)
|
[
"def",
"get_env",
"(",
"name",
",",
"default",
"=",
"None",
")",
":",
"if",
"name",
"in",
"os",
".",
"environ",
":",
"return",
"os",
".",
"environ",
"[",
"name",
"]",
"if",
"default",
"is",
"not",
"None",
":",
"return",
"default",
"error_msg",
"=",
"\"Set the {} env variable\"",
".",
"format",
"(",
"name",
")",
"raise",
"ImproperlyConfigured",
"(",
"error_msg",
")"
] |
Get the environment variable or return exception
|
[
"Get",
"the",
"environment",
"variable",
"or",
"return",
"exception"
] |
3482891be8903293812738d9128b9bda03b9a2ba
|
https://github.com/Frojd/wagtail-geo-widget/blob/3482891be8903293812738d9128b9bda03b9a2ba/example/examplesite/settings/__init__.py#L6-L15
|
10,119
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.user_defined_symbols
|
def user_defined_symbols(self):
"""Return a set of symbols that have been added to symtable after
construction.
I.e., the symbols from self.symtable that are not in
self.no_deepcopy.
Returns
-------
unique_symbols : set
symbols in symtable that are not in self.no_deepcopy
"""
sym_in_current = set(self.symtable.keys())
sym_from_construction = set(self.no_deepcopy)
unique_symbols = sym_in_current.difference(sym_from_construction)
return unique_symbols
|
python
|
def user_defined_symbols(self):
"""Return a set of symbols that have been added to symtable after
construction.
I.e., the symbols from self.symtable that are not in
self.no_deepcopy.
Returns
-------
unique_symbols : set
symbols in symtable that are not in self.no_deepcopy
"""
sym_in_current = set(self.symtable.keys())
sym_from_construction = set(self.no_deepcopy)
unique_symbols = sym_in_current.difference(sym_from_construction)
return unique_symbols
|
[
"def",
"user_defined_symbols",
"(",
"self",
")",
":",
"sym_in_current",
"=",
"set",
"(",
"self",
".",
"symtable",
".",
"keys",
"(",
")",
")",
"sym_from_construction",
"=",
"set",
"(",
"self",
".",
"no_deepcopy",
")",
"unique_symbols",
"=",
"sym_in_current",
".",
"difference",
"(",
"sym_from_construction",
")",
"return",
"unique_symbols"
] |
Return a set of symbols that have been added to symtable after
construction.
I.e., the symbols from self.symtable that are not in
self.no_deepcopy.
Returns
-------
unique_symbols : set
symbols in symtable that are not in self.no_deepcopy
|
[
"Return",
"a",
"set",
"of",
"symbols",
"that",
"have",
"been",
"added",
"to",
"symtable",
"after",
"construction",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L216-L232
|
10,120
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.unimplemented
|
def unimplemented(self, node):
"""Unimplemented nodes."""
self.raise_exception(node, exc=NotImplementedError,
msg="'%s' not supported" %
(node.__class__.__name__))
|
python
|
def unimplemented(self, node):
"""Unimplemented nodes."""
self.raise_exception(node, exc=NotImplementedError,
msg="'%s' not supported" %
(node.__class__.__name__))
|
[
"def",
"unimplemented",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"raise_exception",
"(",
"node",
",",
"exc",
"=",
"NotImplementedError",
",",
"msg",
"=",
"\"'%s' not supported\"",
"%",
"(",
"node",
".",
"__class__",
".",
"__name__",
")",
")"
] |
Unimplemented nodes.
|
[
"Unimplemented",
"nodes",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L234-L238
|
10,121
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.raise_exception
|
def raise_exception(self, node, exc=None, msg='', expr=None,
lineno=None):
"""Add an exception."""
if self.error is None:
self.error = []
if expr is None:
expr = self.expr
if len(self.error) > 0 and not isinstance(node, ast.Module):
msg = '%s' % msg
err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno)
self._interrupt = ast.Break()
self.error.append(err)
if self.error_msg is None:
self.error_msg = "at expr='%s'" % (self.expr)
elif len(msg) > 0:
self.error_msg = msg
if exc is None:
try:
exc = self.error[0].exc
except:
exc = RuntimeError
raise exc(self.error_msg)
|
python
|
def raise_exception(self, node, exc=None, msg='', expr=None,
lineno=None):
"""Add an exception."""
if self.error is None:
self.error = []
if expr is None:
expr = self.expr
if len(self.error) > 0 and not isinstance(node, ast.Module):
msg = '%s' % msg
err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno)
self._interrupt = ast.Break()
self.error.append(err)
if self.error_msg is None:
self.error_msg = "at expr='%s'" % (self.expr)
elif len(msg) > 0:
self.error_msg = msg
if exc is None:
try:
exc = self.error[0].exc
except:
exc = RuntimeError
raise exc(self.error_msg)
|
[
"def",
"raise_exception",
"(",
"self",
",",
"node",
",",
"exc",
"=",
"None",
",",
"msg",
"=",
"''",
",",
"expr",
"=",
"None",
",",
"lineno",
"=",
"None",
")",
":",
"if",
"self",
".",
"error",
"is",
"None",
":",
"self",
".",
"error",
"=",
"[",
"]",
"if",
"expr",
"is",
"None",
":",
"expr",
"=",
"self",
".",
"expr",
"if",
"len",
"(",
"self",
".",
"error",
")",
">",
"0",
"and",
"not",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Module",
")",
":",
"msg",
"=",
"'%s'",
"%",
"msg",
"err",
"=",
"ExceptionHolder",
"(",
"node",
",",
"exc",
"=",
"exc",
",",
"msg",
"=",
"msg",
",",
"expr",
"=",
"expr",
",",
"lineno",
"=",
"lineno",
")",
"self",
".",
"_interrupt",
"=",
"ast",
".",
"Break",
"(",
")",
"self",
".",
"error",
".",
"append",
"(",
"err",
")",
"if",
"self",
".",
"error_msg",
"is",
"None",
":",
"self",
".",
"error_msg",
"=",
"\"at expr='%s'\"",
"%",
"(",
"self",
".",
"expr",
")",
"elif",
"len",
"(",
"msg",
")",
">",
"0",
":",
"self",
".",
"error_msg",
"=",
"msg",
"if",
"exc",
"is",
"None",
":",
"try",
":",
"exc",
"=",
"self",
".",
"error",
"[",
"0",
"]",
".",
"exc",
"except",
":",
"exc",
"=",
"RuntimeError",
"raise",
"exc",
"(",
"self",
".",
"error_msg",
")"
] |
Add an exception.
|
[
"Add",
"an",
"exception",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L240-L261
|
10,122
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.run
|
def run(self, node, expr=None, lineno=None, with_raise=True):
"""Execute parsed Ast representation for an expression."""
# Note: keep the 'node is None' test: internal code here may run
# run(None) and expect a None in return.
if time.time() - self.start_time > self.max_time:
raise RuntimeError(ERR_MAX_TIME.format(self.max_time))
out = None
if len(self.error) > 0:
return out
if node is None:
return out
if isinstance(node, str):
node = self.parse(node)
if lineno is not None:
self.lineno = lineno
if expr is not None:
self.expr = expr
# get handler for this node:
# on_xxx with handle nodes of type 'xxx', etc
try:
handler = self.node_handlers[node.__class__.__name__.lower()]
except KeyError:
return self.unimplemented(node)
# run the handler: this will likely generate
# recursive calls into this run method.
try:
ret = handler(node)
if isinstance(ret, enumerate):
ret = list(ret)
return ret
except:
if with_raise:
self.raise_exception(node, expr=expr)
|
python
|
def run(self, node, expr=None, lineno=None, with_raise=True):
"""Execute parsed Ast representation for an expression."""
# Note: keep the 'node is None' test: internal code here may run
# run(None) and expect a None in return.
if time.time() - self.start_time > self.max_time:
raise RuntimeError(ERR_MAX_TIME.format(self.max_time))
out = None
if len(self.error) > 0:
return out
if node is None:
return out
if isinstance(node, str):
node = self.parse(node)
if lineno is not None:
self.lineno = lineno
if expr is not None:
self.expr = expr
# get handler for this node:
# on_xxx with handle nodes of type 'xxx', etc
try:
handler = self.node_handlers[node.__class__.__name__.lower()]
except KeyError:
return self.unimplemented(node)
# run the handler: this will likely generate
# recursive calls into this run method.
try:
ret = handler(node)
if isinstance(ret, enumerate):
ret = list(ret)
return ret
except:
if with_raise:
self.raise_exception(node, expr=expr)
|
[
"def",
"run",
"(",
"self",
",",
"node",
",",
"expr",
"=",
"None",
",",
"lineno",
"=",
"None",
",",
"with_raise",
"=",
"True",
")",
":",
"# Note: keep the 'node is None' test: internal code here may run",
"# run(None) and expect a None in return.",
"if",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"start_time",
">",
"self",
".",
"max_time",
":",
"raise",
"RuntimeError",
"(",
"ERR_MAX_TIME",
".",
"format",
"(",
"self",
".",
"max_time",
")",
")",
"out",
"=",
"None",
"if",
"len",
"(",
"self",
".",
"error",
")",
">",
"0",
":",
"return",
"out",
"if",
"node",
"is",
"None",
":",
"return",
"out",
"if",
"isinstance",
"(",
"node",
",",
"str",
")",
":",
"node",
"=",
"self",
".",
"parse",
"(",
"node",
")",
"if",
"lineno",
"is",
"not",
"None",
":",
"self",
".",
"lineno",
"=",
"lineno",
"if",
"expr",
"is",
"not",
"None",
":",
"self",
".",
"expr",
"=",
"expr",
"# get handler for this node:",
"# on_xxx with handle nodes of type 'xxx', etc",
"try",
":",
"handler",
"=",
"self",
".",
"node_handlers",
"[",
"node",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
"]",
"except",
"KeyError",
":",
"return",
"self",
".",
"unimplemented",
"(",
"node",
")",
"# run the handler: this will likely generate",
"# recursive calls into this run method.",
"try",
":",
"ret",
"=",
"handler",
"(",
"node",
")",
"if",
"isinstance",
"(",
"ret",
",",
"enumerate",
")",
":",
"ret",
"=",
"list",
"(",
"ret",
")",
"return",
"ret",
"except",
":",
"if",
"with_raise",
":",
"self",
".",
"raise_exception",
"(",
"node",
",",
"expr",
"=",
"expr",
")"
] |
Execute parsed Ast representation for an expression.
|
[
"Execute",
"parsed",
"Ast",
"representation",
"for",
"an",
"expression",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L279-L313
|
10,123
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.eval
|
def eval(self, expr, lineno=0, show_errors=True):
"""Evaluate a single statement."""
self.lineno = lineno
self.error = []
self.start_time = time.time()
try:
node = self.parse(expr)
except:
errmsg = exc_info()[1]
if len(self.error) > 0:
errmsg = "\n".join(self.error[0].get_error())
if not show_errors:
try:
exc = self.error[0].exc
except:
exc = RuntimeError
raise exc(errmsg)
print(errmsg, file=self.err_writer)
return
try:
return self.run(node, expr=expr, lineno=lineno)
except:
errmsg = exc_info()[1]
if len(self.error) > 0:
errmsg = "\n".join(self.error[0].get_error())
if not show_errors:
try:
exc = self.error[0].exc
except:
exc = RuntimeError
raise exc(errmsg)
print(errmsg, file=self.err_writer)
return
|
python
|
def eval(self, expr, lineno=0, show_errors=True):
"""Evaluate a single statement."""
self.lineno = lineno
self.error = []
self.start_time = time.time()
try:
node = self.parse(expr)
except:
errmsg = exc_info()[1]
if len(self.error) > 0:
errmsg = "\n".join(self.error[0].get_error())
if not show_errors:
try:
exc = self.error[0].exc
except:
exc = RuntimeError
raise exc(errmsg)
print(errmsg, file=self.err_writer)
return
try:
return self.run(node, expr=expr, lineno=lineno)
except:
errmsg = exc_info()[1]
if len(self.error) > 0:
errmsg = "\n".join(self.error[0].get_error())
if not show_errors:
try:
exc = self.error[0].exc
except:
exc = RuntimeError
raise exc(errmsg)
print(errmsg, file=self.err_writer)
return
|
[
"def",
"eval",
"(",
"self",
",",
"expr",
",",
"lineno",
"=",
"0",
",",
"show_errors",
"=",
"True",
")",
":",
"self",
".",
"lineno",
"=",
"lineno",
"self",
".",
"error",
"=",
"[",
"]",
"self",
".",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"try",
":",
"node",
"=",
"self",
".",
"parse",
"(",
"expr",
")",
"except",
":",
"errmsg",
"=",
"exc_info",
"(",
")",
"[",
"1",
"]",
"if",
"len",
"(",
"self",
".",
"error",
")",
">",
"0",
":",
"errmsg",
"=",
"\"\\n\"",
".",
"join",
"(",
"self",
".",
"error",
"[",
"0",
"]",
".",
"get_error",
"(",
")",
")",
"if",
"not",
"show_errors",
":",
"try",
":",
"exc",
"=",
"self",
".",
"error",
"[",
"0",
"]",
".",
"exc",
"except",
":",
"exc",
"=",
"RuntimeError",
"raise",
"exc",
"(",
"errmsg",
")",
"print",
"(",
"errmsg",
",",
"file",
"=",
"self",
".",
"err_writer",
")",
"return",
"try",
":",
"return",
"self",
".",
"run",
"(",
"node",
",",
"expr",
"=",
"expr",
",",
"lineno",
"=",
"lineno",
")",
"except",
":",
"errmsg",
"=",
"exc_info",
"(",
")",
"[",
"1",
"]",
"if",
"len",
"(",
"self",
".",
"error",
")",
">",
"0",
":",
"errmsg",
"=",
"\"\\n\"",
".",
"join",
"(",
"self",
".",
"error",
"[",
"0",
"]",
".",
"get_error",
"(",
")",
")",
"if",
"not",
"show_errors",
":",
"try",
":",
"exc",
"=",
"self",
".",
"error",
"[",
"0",
"]",
".",
"exc",
"except",
":",
"exc",
"=",
"RuntimeError",
"raise",
"exc",
"(",
"errmsg",
")",
"print",
"(",
"errmsg",
",",
"file",
"=",
"self",
".",
"err_writer",
")",
"return"
] |
Evaluate a single statement.
|
[
"Evaluate",
"a",
"single",
"statement",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L319-L351
|
10,124
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_module
|
def on_module(self, node): # ():('body',)
"""Module def."""
out = None
for tnode in node.body:
out = self.run(tnode)
return out
|
python
|
def on_module(self, node): # ():('body',)
"""Module def."""
out = None
for tnode in node.body:
out = self.run(tnode)
return out
|
[
"def",
"on_module",
"(",
"self",
",",
"node",
")",
":",
"# ():('body',)",
"out",
"=",
"None",
"for",
"tnode",
"in",
"node",
".",
"body",
":",
"out",
"=",
"self",
".",
"run",
"(",
"tnode",
")",
"return",
"out"
] |
Module def.
|
[
"Module",
"def",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L378-L383
|
10,125
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_assert
|
def on_assert(self, node): # ('test', 'msg')
"""Assert statement."""
if not self.run(node.test):
self.raise_exception(node, exc=AssertionError, msg=node.msg)
return True
|
python
|
def on_assert(self, node): # ('test', 'msg')
"""Assert statement."""
if not self.run(node.test):
self.raise_exception(node, exc=AssertionError, msg=node.msg)
return True
|
[
"def",
"on_assert",
"(",
"self",
",",
"node",
")",
":",
"# ('test', 'msg')",
"if",
"not",
"self",
".",
"run",
"(",
"node",
".",
"test",
")",
":",
"self",
".",
"raise_exception",
"(",
"node",
",",
"exc",
"=",
"AssertionError",
",",
"msg",
"=",
"node",
".",
"msg",
")",
"return",
"True"
] |
Assert statement.
|
[
"Assert",
"statement",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L411-L415
|
10,126
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_name
|
def on_name(self, node): # ('id', 'ctx')
"""Name node."""
ctx = node.ctx.__class__
if ctx in (ast.Param, ast.Del):
return str(node.id)
else:
if node.id in self.symtable:
return self.symtable[node.id]
else:
msg = "name '%s' is not defined" % node.id
self.raise_exception(node, exc=NameError, msg=msg)
|
python
|
def on_name(self, node): # ('id', 'ctx')
"""Name node."""
ctx = node.ctx.__class__
if ctx in (ast.Param, ast.Del):
return str(node.id)
else:
if node.id in self.symtable:
return self.symtable[node.id]
else:
msg = "name '%s' is not defined" % node.id
self.raise_exception(node, exc=NameError, msg=msg)
|
[
"def",
"on_name",
"(",
"self",
",",
"node",
")",
":",
"# ('id', 'ctx')",
"ctx",
"=",
"node",
".",
"ctx",
".",
"__class__",
"if",
"ctx",
"in",
"(",
"ast",
".",
"Param",
",",
"ast",
".",
"Del",
")",
":",
"return",
"str",
"(",
"node",
".",
"id",
")",
"else",
":",
"if",
"node",
".",
"id",
"in",
"self",
".",
"symtable",
":",
"return",
"self",
".",
"symtable",
"[",
"node",
".",
"id",
"]",
"else",
":",
"msg",
"=",
"\"name '%s' is not defined\"",
"%",
"node",
".",
"id",
"self",
".",
"raise_exception",
"(",
"node",
",",
"exc",
"=",
"NameError",
",",
"msg",
"=",
"msg",
")"
] |
Name node.
|
[
"Name",
"node",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L442-L452
|
10,127
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_attribute
|
def on_attribute(self, node): # ('value', 'attr', 'ctx')
"""Extract attribute."""
ctx = node.ctx.__class__
if ctx == ast.Store:
msg = "attribute for storage: shouldn't be here!"
self.raise_exception(node, exc=RuntimeError, msg=msg)
sym = self.run(node.value)
if ctx == ast.Del:
return delattr(sym, node.attr)
# ctx is ast.Load
fmt = "cannnot access attribute '%s' for %s"
if node.attr not in UNSAFE_ATTRS:
fmt = "no attribute '%s' for %s"
try:
return getattr(sym, node.attr)
except AttributeError:
pass
# AttributeError or accessed unsafe attribute
obj = self.run(node.value)
msg = fmt % (node.attr, obj)
self.raise_exception(node, exc=AttributeError, msg=msg)
|
python
|
def on_attribute(self, node): # ('value', 'attr', 'ctx')
"""Extract attribute."""
ctx = node.ctx.__class__
if ctx == ast.Store:
msg = "attribute for storage: shouldn't be here!"
self.raise_exception(node, exc=RuntimeError, msg=msg)
sym = self.run(node.value)
if ctx == ast.Del:
return delattr(sym, node.attr)
# ctx is ast.Load
fmt = "cannnot access attribute '%s' for %s"
if node.attr not in UNSAFE_ATTRS:
fmt = "no attribute '%s' for %s"
try:
return getattr(sym, node.attr)
except AttributeError:
pass
# AttributeError or accessed unsafe attribute
obj = self.run(node.value)
msg = fmt % (node.attr, obj)
self.raise_exception(node, exc=AttributeError, msg=msg)
|
[
"def",
"on_attribute",
"(",
"self",
",",
"node",
")",
":",
"# ('value', 'attr', 'ctx')",
"ctx",
"=",
"node",
".",
"ctx",
".",
"__class__",
"if",
"ctx",
"==",
"ast",
".",
"Store",
":",
"msg",
"=",
"\"attribute for storage: shouldn't be here!\"",
"self",
".",
"raise_exception",
"(",
"node",
",",
"exc",
"=",
"RuntimeError",
",",
"msg",
"=",
"msg",
")",
"sym",
"=",
"self",
".",
"run",
"(",
"node",
".",
"value",
")",
"if",
"ctx",
"==",
"ast",
".",
"Del",
":",
"return",
"delattr",
"(",
"sym",
",",
"node",
".",
"attr",
")",
"# ctx is ast.Load",
"fmt",
"=",
"\"cannnot access attribute '%s' for %s\"",
"if",
"node",
".",
"attr",
"not",
"in",
"UNSAFE_ATTRS",
":",
"fmt",
"=",
"\"no attribute '%s' for %s\"",
"try",
":",
"return",
"getattr",
"(",
"sym",
",",
"node",
".",
"attr",
")",
"except",
"AttributeError",
":",
"pass",
"# AttributeError or accessed unsafe attribute",
"obj",
"=",
"self",
".",
"run",
"(",
"node",
".",
"value",
")",
"msg",
"=",
"fmt",
"%",
"(",
"node",
".",
"attr",
",",
"obj",
")",
"self",
".",
"raise_exception",
"(",
"node",
",",
"exc",
"=",
"AttributeError",
",",
"msg",
"=",
"msg",
")"
] |
Extract attribute.
|
[
"Extract",
"attribute",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L496-L519
|
10,128
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_assign
|
def on_assign(self, node): # ('targets', 'value')
"""Simple assignment."""
val = self.run(node.value)
for tnode in node.targets:
self.node_assign(tnode, val)
return
|
python
|
def on_assign(self, node): # ('targets', 'value')
"""Simple assignment."""
val = self.run(node.value)
for tnode in node.targets:
self.node_assign(tnode, val)
return
|
[
"def",
"on_assign",
"(",
"self",
",",
"node",
")",
":",
"# ('targets', 'value')",
"val",
"=",
"self",
".",
"run",
"(",
"node",
".",
"value",
")",
"for",
"tnode",
"in",
"node",
".",
"targets",
":",
"self",
".",
"node_assign",
"(",
"tnode",
",",
"val",
")",
"return"
] |
Simple assignment.
|
[
"Simple",
"assignment",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L521-L526
|
10,129
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_augassign
|
def on_augassign(self, node): # ('target', 'op', 'value')
"""Augmented assign."""
return self.on_assign(ast.Assign(targets=[node.target],
value=ast.BinOp(left=node.target,
op=node.op,
right=node.value)))
|
python
|
def on_augassign(self, node): # ('target', 'op', 'value')
"""Augmented assign."""
return self.on_assign(ast.Assign(targets=[node.target],
value=ast.BinOp(left=node.target,
op=node.op,
right=node.value)))
|
[
"def",
"on_augassign",
"(",
"self",
",",
"node",
")",
":",
"# ('target', 'op', 'value')",
"return",
"self",
".",
"on_assign",
"(",
"ast",
".",
"Assign",
"(",
"targets",
"=",
"[",
"node",
".",
"target",
"]",
",",
"value",
"=",
"ast",
".",
"BinOp",
"(",
"left",
"=",
"node",
".",
"target",
",",
"op",
"=",
"node",
".",
"op",
",",
"right",
"=",
"node",
".",
"value",
")",
")",
")"
] |
Augmented assign.
|
[
"Augmented",
"assign",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L528-L533
|
10,130
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_slice
|
def on_slice(self, node): # ():('lower', 'upper', 'step')
"""Simple slice."""
return slice(self.run(node.lower),
self.run(node.upper),
self.run(node.step))
|
python
|
def on_slice(self, node): # ():('lower', 'upper', 'step')
"""Simple slice."""
return slice(self.run(node.lower),
self.run(node.upper),
self.run(node.step))
|
[
"def",
"on_slice",
"(",
"self",
",",
"node",
")",
":",
"# ():('lower', 'upper', 'step')",
"return",
"slice",
"(",
"self",
".",
"run",
"(",
"node",
".",
"lower",
")",
",",
"self",
".",
"run",
"(",
"node",
".",
"upper",
")",
",",
"self",
".",
"run",
"(",
"node",
".",
"step",
")",
")"
] |
Simple slice.
|
[
"Simple",
"slice",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L535-L539
|
10,131
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_extslice
|
def on_extslice(self, node): # ():('dims',)
"""Extended slice."""
return tuple([self.run(tnode) for tnode in node.dims])
|
python
|
def on_extslice(self, node): # ():('dims',)
"""Extended slice."""
return tuple([self.run(tnode) for tnode in node.dims])
|
[
"def",
"on_extslice",
"(",
"self",
",",
"node",
")",
":",
"# ():('dims',)",
"return",
"tuple",
"(",
"[",
"self",
".",
"run",
"(",
"tnode",
")",
"for",
"tnode",
"in",
"node",
".",
"dims",
"]",
")"
] |
Extended slice.
|
[
"Extended",
"slice",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L541-L543
|
10,132
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_delete
|
def on_delete(self, node): # ('targets',)
"""Delete statement."""
for tnode in node.targets:
if tnode.ctx.__class__ != ast.Del:
break
children = []
while tnode.__class__ == ast.Attribute:
children.append(tnode.attr)
tnode = tnode.value
if tnode.__class__ == ast.Name and tnode.id not in self.readonly_symbols:
children.append(tnode.id)
children.reverse()
self.symtable.pop('.'.join(children))
else:
msg = "could not delete symbol"
self.raise_exception(node, msg=msg)
|
python
|
def on_delete(self, node): # ('targets',)
"""Delete statement."""
for tnode in node.targets:
if tnode.ctx.__class__ != ast.Del:
break
children = []
while tnode.__class__ == ast.Attribute:
children.append(tnode.attr)
tnode = tnode.value
if tnode.__class__ == ast.Name and tnode.id not in self.readonly_symbols:
children.append(tnode.id)
children.reverse()
self.symtable.pop('.'.join(children))
else:
msg = "could not delete symbol"
self.raise_exception(node, msg=msg)
|
[
"def",
"on_delete",
"(",
"self",
",",
"node",
")",
":",
"# ('targets',)",
"for",
"tnode",
"in",
"node",
".",
"targets",
":",
"if",
"tnode",
".",
"ctx",
".",
"__class__",
"!=",
"ast",
".",
"Del",
":",
"break",
"children",
"=",
"[",
"]",
"while",
"tnode",
".",
"__class__",
"==",
"ast",
".",
"Attribute",
":",
"children",
".",
"append",
"(",
"tnode",
".",
"attr",
")",
"tnode",
"=",
"tnode",
".",
"value",
"if",
"tnode",
".",
"__class__",
"==",
"ast",
".",
"Name",
"and",
"tnode",
".",
"id",
"not",
"in",
"self",
".",
"readonly_symbols",
":",
"children",
".",
"append",
"(",
"tnode",
".",
"id",
")",
"children",
".",
"reverse",
"(",
")",
"self",
".",
"symtable",
".",
"pop",
"(",
"'.'",
".",
"join",
"(",
"children",
")",
")",
"else",
":",
"msg",
"=",
"\"could not delete symbol\"",
"self",
".",
"raise_exception",
"(",
"node",
",",
"msg",
"=",
"msg",
")"
] |
Delete statement.
|
[
"Delete",
"statement",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L559-L575
|
10,133
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_unaryop
|
def on_unaryop(self, node): # ('op', 'operand')
"""Unary operator."""
return op2func(node.op)(self.run(node.operand))
|
python
|
def on_unaryop(self, node): # ('op', 'operand')
"""Unary operator."""
return op2func(node.op)(self.run(node.operand))
|
[
"def",
"on_unaryop",
"(",
"self",
",",
"node",
")",
":",
"# ('op', 'operand')",
"return",
"op2func",
"(",
"node",
".",
"op",
")",
"(",
"self",
".",
"run",
"(",
"node",
".",
"operand",
")",
")"
] |
Unary operator.
|
[
"Unary",
"operator",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L577-L579
|
10,134
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_binop
|
def on_binop(self, node): # ('left', 'op', 'right')
"""Binary operator."""
return op2func(node.op)(self.run(node.left),
self.run(node.right))
|
python
|
def on_binop(self, node): # ('left', 'op', 'right')
"""Binary operator."""
return op2func(node.op)(self.run(node.left),
self.run(node.right))
|
[
"def",
"on_binop",
"(",
"self",
",",
"node",
")",
":",
"# ('left', 'op', 'right')",
"return",
"op2func",
"(",
"node",
".",
"op",
")",
"(",
"self",
".",
"run",
"(",
"node",
".",
"left",
")",
",",
"self",
".",
"run",
"(",
"node",
".",
"right",
")",
")"
] |
Binary operator.
|
[
"Binary",
"operator",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L581-L584
|
10,135
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_boolop
|
def on_boolop(self, node): # ('op', 'values')
"""Boolean operator."""
val = self.run(node.values[0])
is_and = ast.And == node.op.__class__
if (is_and and val) or (not is_and and not val):
for n in node.values[1:]:
val = op2func(node.op)(val, self.run(n))
if (is_and and not val) or (not is_and and val):
break
return val
|
python
|
def on_boolop(self, node): # ('op', 'values')
"""Boolean operator."""
val = self.run(node.values[0])
is_and = ast.And == node.op.__class__
if (is_and and val) or (not is_and and not val):
for n in node.values[1:]:
val = op2func(node.op)(val, self.run(n))
if (is_and and not val) or (not is_and and val):
break
return val
|
[
"def",
"on_boolop",
"(",
"self",
",",
"node",
")",
":",
"# ('op', 'values')",
"val",
"=",
"self",
".",
"run",
"(",
"node",
".",
"values",
"[",
"0",
"]",
")",
"is_and",
"=",
"ast",
".",
"And",
"==",
"node",
".",
"op",
".",
"__class__",
"if",
"(",
"is_and",
"and",
"val",
")",
"or",
"(",
"not",
"is_and",
"and",
"not",
"val",
")",
":",
"for",
"n",
"in",
"node",
".",
"values",
"[",
"1",
":",
"]",
":",
"val",
"=",
"op2func",
"(",
"node",
".",
"op",
")",
"(",
"val",
",",
"self",
".",
"run",
"(",
"n",
")",
")",
"if",
"(",
"is_and",
"and",
"not",
"val",
")",
"or",
"(",
"not",
"is_and",
"and",
"val",
")",
":",
"break",
"return",
"val"
] |
Boolean operator.
|
[
"Boolean",
"operator",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L586-L595
|
10,136
|
newville/asteval
|
asteval/asteval.py
|
Interpreter._printer
|
def _printer(self, *out, **kws):
"""Generic print function."""
flush = kws.pop('flush', True)
fileh = kws.pop('file', self.writer)
sep = kws.pop('sep', ' ')
end = kws.pop('sep', '\n')
print(*out, file=fileh, sep=sep, end=end)
if flush:
fileh.flush()
|
python
|
def _printer(self, *out, **kws):
"""Generic print function."""
flush = kws.pop('flush', True)
fileh = kws.pop('file', self.writer)
sep = kws.pop('sep', ' ')
end = kws.pop('sep', '\n')
print(*out, file=fileh, sep=sep, end=end)
if flush:
fileh.flush()
|
[
"def",
"_printer",
"(",
"self",
",",
"*",
"out",
",",
"*",
"*",
"kws",
")",
":",
"flush",
"=",
"kws",
".",
"pop",
"(",
"'flush'",
",",
"True",
")",
"fileh",
"=",
"kws",
".",
"pop",
"(",
"'file'",
",",
"self",
".",
"writer",
")",
"sep",
"=",
"kws",
".",
"pop",
"(",
"'sep'",
",",
"' '",
")",
"end",
"=",
"kws",
".",
"pop",
"(",
"'sep'",
",",
"'\\n'",
")",
"print",
"(",
"*",
"out",
",",
"file",
"=",
"fileh",
",",
"sep",
"=",
"sep",
",",
"end",
"=",
"end",
")",
"if",
"flush",
":",
"fileh",
".",
"flush",
"(",
")"
] |
Generic print function.
|
[
"Generic",
"print",
"function",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L626-L635
|
10,137
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_if
|
def on_if(self, node): # ('test', 'body', 'orelse')
"""Regular if-then-else statement."""
block = node.body
if not self.run(node.test):
block = node.orelse
for tnode in block:
self.run(tnode)
|
python
|
def on_if(self, node): # ('test', 'body', 'orelse')
"""Regular if-then-else statement."""
block = node.body
if not self.run(node.test):
block = node.orelse
for tnode in block:
self.run(tnode)
|
[
"def",
"on_if",
"(",
"self",
",",
"node",
")",
":",
"# ('test', 'body', 'orelse')",
"block",
"=",
"node",
".",
"body",
"if",
"not",
"self",
".",
"run",
"(",
"node",
".",
"test",
")",
":",
"block",
"=",
"node",
".",
"orelse",
"for",
"tnode",
"in",
"block",
":",
"self",
".",
"run",
"(",
"tnode",
")"
] |
Regular if-then-else statement.
|
[
"Regular",
"if",
"-",
"then",
"-",
"else",
"statement",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L637-L643
|
10,138
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_ifexp
|
def on_ifexp(self, node): # ('test', 'body', 'orelse')
"""If expressions."""
expr = node.orelse
if self.run(node.test):
expr = node.body
return self.run(expr)
|
python
|
def on_ifexp(self, node): # ('test', 'body', 'orelse')
"""If expressions."""
expr = node.orelse
if self.run(node.test):
expr = node.body
return self.run(expr)
|
[
"def",
"on_ifexp",
"(",
"self",
",",
"node",
")",
":",
"# ('test', 'body', 'orelse')",
"expr",
"=",
"node",
".",
"orelse",
"if",
"self",
".",
"run",
"(",
"node",
".",
"test",
")",
":",
"expr",
"=",
"node",
".",
"body",
"return",
"self",
".",
"run",
"(",
"expr",
")"
] |
If expressions.
|
[
"If",
"expressions",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L645-L650
|
10,139
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_while
|
def on_while(self, node): # ('test', 'body', 'orelse')
"""While blocks."""
while self.run(node.test):
self._interrupt = None
for tnode in node.body:
self.run(tnode)
if self._interrupt is not None:
break
if isinstance(self._interrupt, ast.Break):
break
else:
for tnode in node.orelse:
self.run(tnode)
self._interrupt = None
|
python
|
def on_while(self, node): # ('test', 'body', 'orelse')
"""While blocks."""
while self.run(node.test):
self._interrupt = None
for tnode in node.body:
self.run(tnode)
if self._interrupt is not None:
break
if isinstance(self._interrupt, ast.Break):
break
else:
for tnode in node.orelse:
self.run(tnode)
self._interrupt = None
|
[
"def",
"on_while",
"(",
"self",
",",
"node",
")",
":",
"# ('test', 'body', 'orelse')",
"while",
"self",
".",
"run",
"(",
"node",
".",
"test",
")",
":",
"self",
".",
"_interrupt",
"=",
"None",
"for",
"tnode",
"in",
"node",
".",
"body",
":",
"self",
".",
"run",
"(",
"tnode",
")",
"if",
"self",
".",
"_interrupt",
"is",
"not",
"None",
":",
"break",
"if",
"isinstance",
"(",
"self",
".",
"_interrupt",
",",
"ast",
".",
"Break",
")",
":",
"break",
"else",
":",
"for",
"tnode",
"in",
"node",
".",
"orelse",
":",
"self",
".",
"run",
"(",
"tnode",
")",
"self",
".",
"_interrupt",
"=",
"None"
] |
While blocks.
|
[
"While",
"blocks",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L652-L665
|
10,140
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_for
|
def on_for(self, node): # ('target', 'iter', 'body', 'orelse')
"""For blocks."""
for val in self.run(node.iter):
self.node_assign(node.target, val)
self._interrupt = None
for tnode in node.body:
self.run(tnode)
if self._interrupt is not None:
break
if isinstance(self._interrupt, ast.Break):
break
else:
for tnode in node.orelse:
self.run(tnode)
self._interrupt = None
|
python
|
def on_for(self, node): # ('target', 'iter', 'body', 'orelse')
"""For blocks."""
for val in self.run(node.iter):
self.node_assign(node.target, val)
self._interrupt = None
for tnode in node.body:
self.run(tnode)
if self._interrupt is not None:
break
if isinstance(self._interrupt, ast.Break):
break
else:
for tnode in node.orelse:
self.run(tnode)
self._interrupt = None
|
[
"def",
"on_for",
"(",
"self",
",",
"node",
")",
":",
"# ('target', 'iter', 'body', 'orelse')",
"for",
"val",
"in",
"self",
".",
"run",
"(",
"node",
".",
"iter",
")",
":",
"self",
".",
"node_assign",
"(",
"node",
".",
"target",
",",
"val",
")",
"self",
".",
"_interrupt",
"=",
"None",
"for",
"tnode",
"in",
"node",
".",
"body",
":",
"self",
".",
"run",
"(",
"tnode",
")",
"if",
"self",
".",
"_interrupt",
"is",
"not",
"None",
":",
"break",
"if",
"isinstance",
"(",
"self",
".",
"_interrupt",
",",
"ast",
".",
"Break",
")",
":",
"break",
"else",
":",
"for",
"tnode",
"in",
"node",
".",
"orelse",
":",
"self",
".",
"run",
"(",
"tnode",
")",
"self",
".",
"_interrupt",
"=",
"None"
] |
For blocks.
|
[
"For",
"blocks",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L667-L681
|
10,141
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_listcomp
|
def on_listcomp(self, node): # ('elt', 'generators')
"""List comprehension."""
out = []
for tnode in node.generators:
if tnode.__class__ == ast.comprehension:
for val in self.run(tnode.iter):
self.node_assign(tnode.target, val)
add = True
for cond in tnode.ifs:
add = add and self.run(cond)
if add:
out.append(self.run(node.elt))
return out
|
python
|
def on_listcomp(self, node): # ('elt', 'generators')
"""List comprehension."""
out = []
for tnode in node.generators:
if tnode.__class__ == ast.comprehension:
for val in self.run(tnode.iter):
self.node_assign(tnode.target, val)
add = True
for cond in tnode.ifs:
add = add and self.run(cond)
if add:
out.append(self.run(node.elt))
return out
|
[
"def",
"on_listcomp",
"(",
"self",
",",
"node",
")",
":",
"# ('elt', 'generators')",
"out",
"=",
"[",
"]",
"for",
"tnode",
"in",
"node",
".",
"generators",
":",
"if",
"tnode",
".",
"__class__",
"==",
"ast",
".",
"comprehension",
":",
"for",
"val",
"in",
"self",
".",
"run",
"(",
"tnode",
".",
"iter",
")",
":",
"self",
".",
"node_assign",
"(",
"tnode",
".",
"target",
",",
"val",
")",
"add",
"=",
"True",
"for",
"cond",
"in",
"tnode",
".",
"ifs",
":",
"add",
"=",
"add",
"and",
"self",
".",
"run",
"(",
"cond",
")",
"if",
"add",
":",
"out",
".",
"append",
"(",
"self",
".",
"run",
"(",
"node",
".",
"elt",
")",
")",
"return",
"out"
] |
List comprehension.
|
[
"List",
"comprehension",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L683-L695
|
10,142
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_excepthandler
|
def on_excepthandler(self, node): # ('type', 'name', 'body')
"""Exception handler..."""
return (self.run(node.type), node.name, node.body)
|
python
|
def on_excepthandler(self, node): # ('type', 'name', 'body')
"""Exception handler..."""
return (self.run(node.type), node.name, node.body)
|
[
"def",
"on_excepthandler",
"(",
"self",
",",
"node",
")",
":",
"# ('type', 'name', 'body')",
"return",
"(",
"self",
".",
"run",
"(",
"node",
".",
"type",
")",
",",
"node",
".",
"name",
",",
"node",
".",
"body",
")"
] |
Exception handler...
|
[
"Exception",
"handler",
"..."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L697-L699
|
10,143
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_call
|
def on_call(self, node):
"""Function execution."""
# ('func', 'args', 'keywords'. Py<3.5 has 'starargs' and 'kwargs' too)
func = self.run(node.func)
if not hasattr(func, '__call__') and not isinstance(func, type):
msg = "'%s' is not callable!!" % (func)
self.raise_exception(node, exc=TypeError, msg=msg)
args = [self.run(targ) for targ in node.args]
starargs = getattr(node, 'starargs', None)
if starargs is not None:
args = args + self.run(starargs)
keywords = {}
if six.PY3 and func == print:
keywords['file'] = self.writer
for key in node.keywords:
if not isinstance(key, ast.keyword):
msg = "keyword error in function call '%s'" % (func)
self.raise_exception(node, msg=msg)
keywords[key.arg] = self.run(key.value)
kwargs = getattr(node, 'kwargs', None)
if kwargs is not None:
keywords.update(self.run(kwargs))
try:
return func(*args, **keywords)
except Exception as ex:
self.raise_exception(
node, msg="Error running function call '%s' with args %s and "
"kwargs %s: %s" % (func.__name__, args, keywords, ex))
|
python
|
def on_call(self, node):
"""Function execution."""
# ('func', 'args', 'keywords'. Py<3.5 has 'starargs' and 'kwargs' too)
func = self.run(node.func)
if not hasattr(func, '__call__') and not isinstance(func, type):
msg = "'%s' is not callable!!" % (func)
self.raise_exception(node, exc=TypeError, msg=msg)
args = [self.run(targ) for targ in node.args]
starargs = getattr(node, 'starargs', None)
if starargs is not None:
args = args + self.run(starargs)
keywords = {}
if six.PY3 and func == print:
keywords['file'] = self.writer
for key in node.keywords:
if not isinstance(key, ast.keyword):
msg = "keyword error in function call '%s'" % (func)
self.raise_exception(node, msg=msg)
keywords[key.arg] = self.run(key.value)
kwargs = getattr(node, 'kwargs', None)
if kwargs is not None:
keywords.update(self.run(kwargs))
try:
return func(*args, **keywords)
except Exception as ex:
self.raise_exception(
node, msg="Error running function call '%s' with args %s and "
"kwargs %s: %s" % (func.__name__, args, keywords, ex))
|
[
"def",
"on_call",
"(",
"self",
",",
"node",
")",
":",
"# ('func', 'args', 'keywords'. Py<3.5 has 'starargs' and 'kwargs' too)",
"func",
"=",
"self",
".",
"run",
"(",
"node",
".",
"func",
")",
"if",
"not",
"hasattr",
"(",
"func",
",",
"'__call__'",
")",
"and",
"not",
"isinstance",
"(",
"func",
",",
"type",
")",
":",
"msg",
"=",
"\"'%s' is not callable!!\"",
"%",
"(",
"func",
")",
"self",
".",
"raise_exception",
"(",
"node",
",",
"exc",
"=",
"TypeError",
",",
"msg",
"=",
"msg",
")",
"args",
"=",
"[",
"self",
".",
"run",
"(",
"targ",
")",
"for",
"targ",
"in",
"node",
".",
"args",
"]",
"starargs",
"=",
"getattr",
"(",
"node",
",",
"'starargs'",
",",
"None",
")",
"if",
"starargs",
"is",
"not",
"None",
":",
"args",
"=",
"args",
"+",
"self",
".",
"run",
"(",
"starargs",
")",
"keywords",
"=",
"{",
"}",
"if",
"six",
".",
"PY3",
"and",
"func",
"==",
"print",
":",
"keywords",
"[",
"'file'",
"]",
"=",
"self",
".",
"writer",
"for",
"key",
"in",
"node",
".",
"keywords",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"ast",
".",
"keyword",
")",
":",
"msg",
"=",
"\"keyword error in function call '%s'\"",
"%",
"(",
"func",
")",
"self",
".",
"raise_exception",
"(",
"node",
",",
"msg",
"=",
"msg",
")",
"keywords",
"[",
"key",
".",
"arg",
"]",
"=",
"self",
".",
"run",
"(",
"key",
".",
"value",
")",
"kwargs",
"=",
"getattr",
"(",
"node",
",",
"'kwargs'",
",",
"None",
")",
"if",
"kwargs",
"is",
"not",
"None",
":",
"keywords",
".",
"update",
"(",
"self",
".",
"run",
"(",
"kwargs",
")",
")",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"keywords",
")",
"except",
"Exception",
"as",
"ex",
":",
"self",
".",
"raise_exception",
"(",
"node",
",",
"msg",
"=",
"\"Error running function call '%s' with args %s and \"",
"\"kwargs %s: %s\"",
"%",
"(",
"func",
".",
"__name__",
",",
"args",
",",
"keywords",
",",
"ex",
")",
")"
] |
Function execution.
|
[
"Function",
"execution",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L744-L776
|
10,144
|
newville/asteval
|
asteval/asteval.py
|
Interpreter.on_functiondef
|
def on_functiondef(self, node):
"""Define procedures."""
# ('name', 'args', 'body', 'decorator_list')
if node.decorator_list:
raise Warning("decorated procedures not supported!")
kwargs = []
if not valid_symbol_name(node.name) or node.name in self.readonly_symbols:
errmsg = "invalid function name (reserved word?) %s" % node.name
self.raise_exception(node, exc=NameError, msg=errmsg)
offset = len(node.args.args) - len(node.args.defaults)
for idef, defnode in enumerate(node.args.defaults):
defval = self.run(defnode)
keyval = self.run(node.args.args[idef+offset])
kwargs.append((keyval, defval))
if version_info[0] == 3:
args = [tnode.arg for tnode in node.args.args[:offset]]
else:
args = [tnode.id for tnode in node.args.args[:offset]]
doc = None
nb0 = node.body[0]
if isinstance(nb0, ast.Expr) and isinstance(nb0.value, ast.Str):
doc = nb0.value.s
varkws = node.args.kwarg
vararg = node.args.vararg
if version_info[0] == 3:
if isinstance(vararg, ast.arg):
vararg = vararg.arg
if isinstance(varkws, ast.arg):
varkws = varkws.arg
self.symtable[node.name] = Procedure(node.name, self, doc=doc,
lineno=self.lineno,
body=node.body,
args=args, kwargs=kwargs,
vararg=vararg, varkws=varkws)
if node.name in self.no_deepcopy:
self.no_deepcopy.remove(node.name)
|
python
|
def on_functiondef(self, node):
"""Define procedures."""
# ('name', 'args', 'body', 'decorator_list')
if node.decorator_list:
raise Warning("decorated procedures not supported!")
kwargs = []
if not valid_symbol_name(node.name) or node.name in self.readonly_symbols:
errmsg = "invalid function name (reserved word?) %s" % node.name
self.raise_exception(node, exc=NameError, msg=errmsg)
offset = len(node.args.args) - len(node.args.defaults)
for idef, defnode in enumerate(node.args.defaults):
defval = self.run(defnode)
keyval = self.run(node.args.args[idef+offset])
kwargs.append((keyval, defval))
if version_info[0] == 3:
args = [tnode.arg for tnode in node.args.args[:offset]]
else:
args = [tnode.id for tnode in node.args.args[:offset]]
doc = None
nb0 = node.body[0]
if isinstance(nb0, ast.Expr) and isinstance(nb0.value, ast.Str):
doc = nb0.value.s
varkws = node.args.kwarg
vararg = node.args.vararg
if version_info[0] == 3:
if isinstance(vararg, ast.arg):
vararg = vararg.arg
if isinstance(varkws, ast.arg):
varkws = varkws.arg
self.symtable[node.name] = Procedure(node.name, self, doc=doc,
lineno=self.lineno,
body=node.body,
args=args, kwargs=kwargs,
vararg=vararg, varkws=varkws)
if node.name in self.no_deepcopy:
self.no_deepcopy.remove(node.name)
|
[
"def",
"on_functiondef",
"(",
"self",
",",
"node",
")",
":",
"# ('name', 'args', 'body', 'decorator_list')",
"if",
"node",
".",
"decorator_list",
":",
"raise",
"Warning",
"(",
"\"decorated procedures not supported!\"",
")",
"kwargs",
"=",
"[",
"]",
"if",
"not",
"valid_symbol_name",
"(",
"node",
".",
"name",
")",
"or",
"node",
".",
"name",
"in",
"self",
".",
"readonly_symbols",
":",
"errmsg",
"=",
"\"invalid function name (reserved word?) %s\"",
"%",
"node",
".",
"name",
"self",
".",
"raise_exception",
"(",
"node",
",",
"exc",
"=",
"NameError",
",",
"msg",
"=",
"errmsg",
")",
"offset",
"=",
"len",
"(",
"node",
".",
"args",
".",
"args",
")",
"-",
"len",
"(",
"node",
".",
"args",
".",
"defaults",
")",
"for",
"idef",
",",
"defnode",
"in",
"enumerate",
"(",
"node",
".",
"args",
".",
"defaults",
")",
":",
"defval",
"=",
"self",
".",
"run",
"(",
"defnode",
")",
"keyval",
"=",
"self",
".",
"run",
"(",
"node",
".",
"args",
".",
"args",
"[",
"idef",
"+",
"offset",
"]",
")",
"kwargs",
".",
"append",
"(",
"(",
"keyval",
",",
"defval",
")",
")",
"if",
"version_info",
"[",
"0",
"]",
"==",
"3",
":",
"args",
"=",
"[",
"tnode",
".",
"arg",
"for",
"tnode",
"in",
"node",
".",
"args",
".",
"args",
"[",
":",
"offset",
"]",
"]",
"else",
":",
"args",
"=",
"[",
"tnode",
".",
"id",
"for",
"tnode",
"in",
"node",
".",
"args",
".",
"args",
"[",
":",
"offset",
"]",
"]",
"doc",
"=",
"None",
"nb0",
"=",
"node",
".",
"body",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"nb0",
",",
"ast",
".",
"Expr",
")",
"and",
"isinstance",
"(",
"nb0",
".",
"value",
",",
"ast",
".",
"Str",
")",
":",
"doc",
"=",
"nb0",
".",
"value",
".",
"s",
"varkws",
"=",
"node",
".",
"args",
".",
"kwarg",
"vararg",
"=",
"node",
".",
"args",
".",
"vararg",
"if",
"version_info",
"[",
"0",
"]",
"==",
"3",
":",
"if",
"isinstance",
"(",
"vararg",
",",
"ast",
".",
"arg",
")",
":",
"vararg",
"=",
"vararg",
".",
"arg",
"if",
"isinstance",
"(",
"varkws",
",",
"ast",
".",
"arg",
")",
":",
"varkws",
"=",
"varkws",
".",
"arg",
"self",
".",
"symtable",
"[",
"node",
".",
"name",
"]",
"=",
"Procedure",
"(",
"node",
".",
"name",
",",
"self",
",",
"doc",
"=",
"doc",
",",
"lineno",
"=",
"self",
".",
"lineno",
",",
"body",
"=",
"node",
".",
"body",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
",",
"vararg",
"=",
"vararg",
",",
"varkws",
"=",
"varkws",
")",
"if",
"node",
".",
"name",
"in",
"self",
".",
"no_deepcopy",
":",
"self",
".",
"no_deepcopy",
".",
"remove",
"(",
"node",
".",
"name",
")"
] |
Define procedures.
|
[
"Define",
"procedures",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/asteval.py#L782-L823
|
10,145
|
newville/asteval
|
asteval/astutils.py
|
safe_pow
|
def safe_pow(base, exp):
"""safe version of pow"""
if exp > MAX_EXPONENT:
raise RuntimeError("Invalid exponent, max exponent is {}".format(MAX_EXPONENT))
return base ** exp
|
python
|
def safe_pow(base, exp):
"""safe version of pow"""
if exp > MAX_EXPONENT:
raise RuntimeError("Invalid exponent, max exponent is {}".format(MAX_EXPONENT))
return base ** exp
|
[
"def",
"safe_pow",
"(",
"base",
",",
"exp",
")",
":",
"if",
"exp",
">",
"MAX_EXPONENT",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid exponent, max exponent is {}\"",
".",
"format",
"(",
"MAX_EXPONENT",
")",
")",
"return",
"base",
"**",
"exp"
] |
safe version of pow
|
[
"safe",
"version",
"of",
"pow"
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L183-L187
|
10,146
|
newville/asteval
|
asteval/astutils.py
|
safe_mult
|
def safe_mult(a, b):
"""safe version of multiply"""
if isinstance(a, str) and isinstance(b, int) and len(a) * b > MAX_STR_LEN:
raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN))
return a * b
|
python
|
def safe_mult(a, b):
"""safe version of multiply"""
if isinstance(a, str) and isinstance(b, int) and len(a) * b > MAX_STR_LEN:
raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN))
return a * b
|
[
"def",
"safe_mult",
"(",
"a",
",",
"b",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"str",
")",
"and",
"isinstance",
"(",
"b",
",",
"int",
")",
"and",
"len",
"(",
"a",
")",
"*",
"b",
">",
"MAX_STR_LEN",
":",
"raise",
"RuntimeError",
"(",
"\"String length exceeded, max string length is {}\"",
".",
"format",
"(",
"MAX_STR_LEN",
")",
")",
"return",
"a",
"*",
"b"
] |
safe version of multiply
|
[
"safe",
"version",
"of",
"multiply"
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L190-L194
|
10,147
|
newville/asteval
|
asteval/astutils.py
|
safe_add
|
def safe_add(a, b):
"""safe version of add"""
if isinstance(a, str) and isinstance(b, str) and len(a) + len(b) > MAX_STR_LEN:
raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN))
return a + b
|
python
|
def safe_add(a, b):
"""safe version of add"""
if isinstance(a, str) and isinstance(b, str) and len(a) + len(b) > MAX_STR_LEN:
raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN))
return a + b
|
[
"def",
"safe_add",
"(",
"a",
",",
"b",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"str",
")",
"and",
"isinstance",
"(",
"b",
",",
"str",
")",
"and",
"len",
"(",
"a",
")",
"+",
"len",
"(",
"b",
")",
">",
"MAX_STR_LEN",
":",
"raise",
"RuntimeError",
"(",
"\"String length exceeded, max string length is {}\"",
".",
"format",
"(",
"MAX_STR_LEN",
")",
")",
"return",
"a",
"+",
"b"
] |
safe version of add
|
[
"safe",
"version",
"of",
"add"
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L197-L201
|
10,148
|
newville/asteval
|
asteval/astutils.py
|
safe_lshift
|
def safe_lshift(a, b):
"""safe version of lshift"""
if b > MAX_SHIFT:
raise RuntimeError("Invalid left shift, max left shift is {}".format(MAX_SHIFT))
return a << b
|
python
|
def safe_lshift(a, b):
"""safe version of lshift"""
if b > MAX_SHIFT:
raise RuntimeError("Invalid left shift, max left shift is {}".format(MAX_SHIFT))
return a << b
|
[
"def",
"safe_lshift",
"(",
"a",
",",
"b",
")",
":",
"if",
"b",
">",
"MAX_SHIFT",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid left shift, max left shift is {}\"",
".",
"format",
"(",
"MAX_SHIFT",
")",
")",
"return",
"a",
"<<",
"b"
] |
safe version of lshift
|
[
"safe",
"version",
"of",
"lshift"
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L204-L208
|
10,149
|
newville/asteval
|
asteval/astutils.py
|
valid_symbol_name
|
def valid_symbol_name(name):
"""Determine whether the input symbol name is a valid name.
Arguments
---------
name : str
name to check for validity.
Returns
--------
valid : bool
whether name is a a valid symbol name
This checks for Python reserved words and that the name matches
the regular expression ``[a-zA-Z_][a-zA-Z0-9_]``
"""
if name in RESERVED_WORDS:
return False
gen = generate_tokens(io.BytesIO(name.encode('utf-8')).readline)
typ, _, start, end, _ = next(gen)
if typ == tk_ENCODING:
typ, _, start, end, _ = next(gen)
return typ == tk_NAME and start == (1, 0) and end == (1, len(name))
|
python
|
def valid_symbol_name(name):
"""Determine whether the input symbol name is a valid name.
Arguments
---------
name : str
name to check for validity.
Returns
--------
valid : bool
whether name is a a valid symbol name
This checks for Python reserved words and that the name matches
the regular expression ``[a-zA-Z_][a-zA-Z0-9_]``
"""
if name in RESERVED_WORDS:
return False
gen = generate_tokens(io.BytesIO(name.encode('utf-8')).readline)
typ, _, start, end, _ = next(gen)
if typ == tk_ENCODING:
typ, _, start, end, _ = next(gen)
return typ == tk_NAME and start == (1, 0) and end == (1, len(name))
|
[
"def",
"valid_symbol_name",
"(",
"name",
")",
":",
"if",
"name",
"in",
"RESERVED_WORDS",
":",
"return",
"False",
"gen",
"=",
"generate_tokens",
"(",
"io",
".",
"BytesIO",
"(",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"readline",
")",
"typ",
",",
"_",
",",
"start",
",",
"end",
",",
"_",
"=",
"next",
"(",
"gen",
")",
"if",
"typ",
"==",
"tk_ENCODING",
":",
"typ",
",",
"_",
",",
"start",
",",
"end",
",",
"_",
"=",
"next",
"(",
"gen",
")",
"return",
"typ",
"==",
"tk_NAME",
"and",
"start",
"==",
"(",
"1",
",",
"0",
")",
"and",
"end",
"==",
"(",
"1",
",",
"len",
"(",
"name",
")",
")"
] |
Determine whether the input symbol name is a valid name.
Arguments
---------
name : str
name to check for validity.
Returns
--------
valid : bool
whether name is a a valid symbol name
This checks for Python reserved words and that the name matches
the regular expression ``[a-zA-Z_][a-zA-Z0-9_]``
|
[
"Determine",
"whether",
"the",
"input",
"symbol",
"name",
"is",
"a",
"valid",
"name",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L241-L264
|
10,150
|
newville/asteval
|
asteval/astutils.py
|
make_symbol_table
|
def make_symbol_table(use_numpy=True, **kws):
"""Create a default symboltable, taking dict of user-defined symbols.
Arguments
---------
numpy : bool, optional
whether to include symbols from numpy
kws : optional
additional symbol name, value pairs to include in symbol table
Returns
--------
symbol_table : dict
a symbol table that can be used in `asteval.Interpereter`
"""
symtable = {}
for sym in FROM_PY:
if sym in builtins:
symtable[sym] = builtins[sym]
for sym in FROM_MATH:
if hasattr(math, sym):
symtable[sym] = getattr(math, sym)
if HAS_NUMPY and use_numpy:
for sym in FROM_NUMPY:
if hasattr(numpy, sym):
symtable[sym] = getattr(numpy, sym)
for name, sym in NUMPY_RENAMES.items():
if hasattr(numpy, sym):
symtable[name] = getattr(numpy, sym)
symtable.update(LOCALFUNCS)
symtable.update(kws)
return symtable
|
python
|
def make_symbol_table(use_numpy=True, **kws):
"""Create a default symboltable, taking dict of user-defined symbols.
Arguments
---------
numpy : bool, optional
whether to include symbols from numpy
kws : optional
additional symbol name, value pairs to include in symbol table
Returns
--------
symbol_table : dict
a symbol table that can be used in `asteval.Interpereter`
"""
symtable = {}
for sym in FROM_PY:
if sym in builtins:
symtable[sym] = builtins[sym]
for sym in FROM_MATH:
if hasattr(math, sym):
symtable[sym] = getattr(math, sym)
if HAS_NUMPY and use_numpy:
for sym in FROM_NUMPY:
if hasattr(numpy, sym):
symtable[sym] = getattr(numpy, sym)
for name, sym in NUMPY_RENAMES.items():
if hasattr(numpy, sym):
symtable[name] = getattr(numpy, sym)
symtable.update(LOCALFUNCS)
symtable.update(kws)
return symtable
|
[
"def",
"make_symbol_table",
"(",
"use_numpy",
"=",
"True",
",",
"*",
"*",
"kws",
")",
":",
"symtable",
"=",
"{",
"}",
"for",
"sym",
"in",
"FROM_PY",
":",
"if",
"sym",
"in",
"builtins",
":",
"symtable",
"[",
"sym",
"]",
"=",
"builtins",
"[",
"sym",
"]",
"for",
"sym",
"in",
"FROM_MATH",
":",
"if",
"hasattr",
"(",
"math",
",",
"sym",
")",
":",
"symtable",
"[",
"sym",
"]",
"=",
"getattr",
"(",
"math",
",",
"sym",
")",
"if",
"HAS_NUMPY",
"and",
"use_numpy",
":",
"for",
"sym",
"in",
"FROM_NUMPY",
":",
"if",
"hasattr",
"(",
"numpy",
",",
"sym",
")",
":",
"symtable",
"[",
"sym",
"]",
"=",
"getattr",
"(",
"numpy",
",",
"sym",
")",
"for",
"name",
",",
"sym",
"in",
"NUMPY_RENAMES",
".",
"items",
"(",
")",
":",
"if",
"hasattr",
"(",
"numpy",
",",
"sym",
")",
":",
"symtable",
"[",
"name",
"]",
"=",
"getattr",
"(",
"numpy",
",",
"sym",
")",
"symtable",
".",
"update",
"(",
"LOCALFUNCS",
")",
"symtable",
".",
"update",
"(",
"kws",
")",
"return",
"symtable"
] |
Create a default symboltable, taking dict of user-defined symbols.
Arguments
---------
numpy : bool, optional
whether to include symbols from numpy
kws : optional
additional symbol name, value pairs to include in symbol table
Returns
--------
symbol_table : dict
a symbol table that can be used in `asteval.Interpereter`
|
[
"Create",
"a",
"default",
"symboltable",
"taking",
"dict",
"of",
"user",
"-",
"defined",
"symbols",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L351-L389
|
10,151
|
newville/asteval
|
asteval/astutils.py
|
ExceptionHolder.get_error
|
def get_error(self):
"""Retrieve error data."""
col_offset = -1
if self.node is not None:
try:
col_offset = self.node.col_offset
except AttributeError:
pass
try:
exc_name = self.exc.__name__
except AttributeError:
exc_name = str(self.exc)
if exc_name in (None, 'None'):
exc_name = 'UnknownError'
out = [" %s" % self.expr]
if col_offset > 0:
out.append(" %s^^^" % ((col_offset)*' '))
out.append(str(self.msg))
return (exc_name, '\n'.join(out))
|
python
|
def get_error(self):
"""Retrieve error data."""
col_offset = -1
if self.node is not None:
try:
col_offset = self.node.col_offset
except AttributeError:
pass
try:
exc_name = self.exc.__name__
except AttributeError:
exc_name = str(self.exc)
if exc_name in (None, 'None'):
exc_name = 'UnknownError'
out = [" %s" % self.expr]
if col_offset > 0:
out.append(" %s^^^" % ((col_offset)*' '))
out.append(str(self.msg))
return (exc_name, '\n'.join(out))
|
[
"def",
"get_error",
"(",
"self",
")",
":",
"col_offset",
"=",
"-",
"1",
"if",
"self",
".",
"node",
"is",
"not",
"None",
":",
"try",
":",
"col_offset",
"=",
"self",
".",
"node",
".",
"col_offset",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"exc_name",
"=",
"self",
".",
"exc",
".",
"__name__",
"except",
"AttributeError",
":",
"exc_name",
"=",
"str",
"(",
"self",
".",
"exc",
")",
"if",
"exc_name",
"in",
"(",
"None",
",",
"'None'",
")",
":",
"exc_name",
"=",
"'UnknownError'",
"out",
"=",
"[",
"\" %s\"",
"%",
"self",
".",
"expr",
"]",
"if",
"col_offset",
">",
"0",
":",
"out",
".",
"append",
"(",
"\" %s^^^\"",
"%",
"(",
"(",
"col_offset",
")",
"*",
"' '",
")",
")",
"out",
".",
"append",
"(",
"str",
"(",
"self",
".",
"msg",
")",
")",
"return",
"(",
"exc_name",
",",
"'\\n'",
".",
"join",
"(",
"out",
")",
")"
] |
Retrieve error data.
|
[
"Retrieve",
"error",
"data",
"."
] |
bb7d3a95079f96ead75ea55662014bbcc82f9b28
|
https://github.com/newville/asteval/blob/bb7d3a95079f96ead75ea55662014bbcc82f9b28/asteval/astutils.py#L303-L322
|
10,152
|
admiralobvious/vyper
|
vyper/vyper.py
|
Vyper.add_config_path
|
def add_config_path(self, path):
"""Add a path for Vyper to search for the config file in.
Can be called multiple times to define multiple search paths.
"""
abspath = util.abs_pathify(path)
if abspath not in self._config_paths:
log.info("Adding {0} to paths to search".format(abspath))
self._config_paths.append(abspath)
|
python
|
def add_config_path(self, path):
"""Add a path for Vyper to search for the config file in.
Can be called multiple times to define multiple search paths.
"""
abspath = util.abs_pathify(path)
if abspath not in self._config_paths:
log.info("Adding {0} to paths to search".format(abspath))
self._config_paths.append(abspath)
|
[
"def",
"add_config_path",
"(",
"self",
",",
"path",
")",
":",
"abspath",
"=",
"util",
".",
"abs_pathify",
"(",
"path",
")",
"if",
"abspath",
"not",
"in",
"self",
".",
"_config_paths",
":",
"log",
".",
"info",
"(",
"\"Adding {0} to paths to search\"",
".",
"format",
"(",
"abspath",
")",
")",
"self",
".",
"_config_paths",
".",
"append",
"(",
"abspath",
")"
] |
Add a path for Vyper to search for the config file in.
Can be called multiple times to define multiple search paths.
|
[
"Add",
"a",
"path",
"for",
"Vyper",
"to",
"search",
"for",
"the",
"config",
"file",
"in",
".",
"Can",
"be",
"called",
"multiple",
"times",
"to",
"define",
"multiple",
"search",
"paths",
"."
] |
58ec7b90661502b7b2fea7a30849b90b907fcdec
|
https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L122-L129
|
10,153
|
admiralobvious/vyper
|
vyper/vyper.py
|
Vyper.sub
|
def sub(self, key):
"""Returns new Vyper instance representing a sub tree of this instance.
"""
subv = Vyper()
data = self.get(key)
if isinstance(data, dict):
subv._config = data
return subv
else:
return None
|
python
|
def sub(self, key):
"""Returns new Vyper instance representing a sub tree of this instance.
"""
subv = Vyper()
data = self.get(key)
if isinstance(data, dict):
subv._config = data
return subv
else:
return None
|
[
"def",
"sub",
"(",
"self",
",",
"key",
")",
":",
"subv",
"=",
"Vyper",
"(",
")",
"data",
"=",
"self",
".",
"get",
"(",
"key",
")",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"subv",
".",
"_config",
"=",
"data",
"return",
"subv",
"else",
":",
"return",
"None"
] |
Returns new Vyper instance representing a sub tree of this instance.
|
[
"Returns",
"new",
"Vyper",
"instance",
"representing",
"a",
"sub",
"tree",
"of",
"this",
"instance",
"."
] |
58ec7b90661502b7b2fea7a30849b90b907fcdec
|
https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L224-L233
|
10,154
|
admiralobvious/vyper
|
vyper/vyper.py
|
Vyper.unmarshall_key
|
def unmarshall_key(self, key, cls):
"""Takes a single key and unmarshalls it into a class."""
return setattr(cls, key, self.get(key))
|
python
|
def unmarshall_key(self, key, cls):
"""Takes a single key and unmarshalls it into a class."""
return setattr(cls, key, self.get(key))
|
[
"def",
"unmarshall_key",
"(",
"self",
",",
"key",
",",
"cls",
")",
":",
"return",
"setattr",
"(",
"cls",
",",
"key",
",",
"self",
".",
"get",
"(",
"key",
")",
")"
] |
Takes a single key and unmarshalls it into a class.
|
[
"Takes",
"a",
"single",
"key",
"and",
"unmarshalls",
"it",
"into",
"a",
"class",
"."
] |
58ec7b90661502b7b2fea7a30849b90b907fcdec
|
https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L235-L237
|
10,155
|
admiralobvious/vyper
|
vyper/vyper.py
|
Vyper.unmarshall
|
def unmarshall(self, cls):
"""Unmarshalls the config into a class. Make sure that the tags on
the attributes of the class are properly set.
"""
for k, v in self.all_settings().items():
setattr(cls, k, v)
return cls
|
python
|
def unmarshall(self, cls):
"""Unmarshalls the config into a class. Make sure that the tags on
the attributes of the class are properly set.
"""
for k, v in self.all_settings().items():
setattr(cls, k, v)
return cls
|
[
"def",
"unmarshall",
"(",
"self",
",",
"cls",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"all_settings",
"(",
")",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"cls",
",",
"k",
",",
"v",
")",
"return",
"cls"
] |
Unmarshalls the config into a class. Make sure that the tags on
the attributes of the class are properly set.
|
[
"Unmarshalls",
"the",
"config",
"into",
"a",
"class",
".",
"Make",
"sure",
"that",
"the",
"tags",
"on",
"the",
"attributes",
"of",
"the",
"class",
"are",
"properly",
"set",
"."
] |
58ec7b90661502b7b2fea7a30849b90b907fcdec
|
https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L239-L246
|
10,156
|
admiralobvious/vyper
|
vyper/vyper.py
|
Vyper.bind_env
|
def bind_env(self, *input_):
"""Binds a Vyper key to a ENV variable.
ENV variables are case sensitive.
If only a key is provided, it will use the env key matching the key,
uppercased.
`env_prefix` will be used when set when env name is not provided.
"""
if len(input_) == 0:
return "bind_env missing key to bind to"
key = input_[0].lower()
if len(input_) == 1:
env_key = self._merge_with_env_prefix(key)
else:
env_key = input_[1]
self._env[key] = env_key
if self._key_delimiter in key:
parts = input_[0].split(self._key_delimiter)
env_info = {
"path": parts[1:-1],
"final_key": parts[-1],
"env_key": env_key
}
if self._env.get(parts[0]) is None:
self._env[parts[0]] = [env_info]
else:
self._env[parts[0]].append(env_info)
return None
|
python
|
def bind_env(self, *input_):
"""Binds a Vyper key to a ENV variable.
ENV variables are case sensitive.
If only a key is provided, it will use the env key matching the key,
uppercased.
`env_prefix` will be used when set when env name is not provided.
"""
if len(input_) == 0:
return "bind_env missing key to bind to"
key = input_[0].lower()
if len(input_) == 1:
env_key = self._merge_with_env_prefix(key)
else:
env_key = input_[1]
self._env[key] = env_key
if self._key_delimiter in key:
parts = input_[0].split(self._key_delimiter)
env_info = {
"path": parts[1:-1],
"final_key": parts[-1],
"env_key": env_key
}
if self._env.get(parts[0]) is None:
self._env[parts[0]] = [env_info]
else:
self._env[parts[0]].append(env_info)
return None
|
[
"def",
"bind_env",
"(",
"self",
",",
"*",
"input_",
")",
":",
"if",
"len",
"(",
"input_",
")",
"==",
"0",
":",
"return",
"\"bind_env missing key to bind to\"",
"key",
"=",
"input_",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"if",
"len",
"(",
"input_",
")",
"==",
"1",
":",
"env_key",
"=",
"self",
".",
"_merge_with_env_prefix",
"(",
"key",
")",
"else",
":",
"env_key",
"=",
"input_",
"[",
"1",
"]",
"self",
".",
"_env",
"[",
"key",
"]",
"=",
"env_key",
"if",
"self",
".",
"_key_delimiter",
"in",
"key",
":",
"parts",
"=",
"input_",
"[",
"0",
"]",
".",
"split",
"(",
"self",
".",
"_key_delimiter",
")",
"env_info",
"=",
"{",
"\"path\"",
":",
"parts",
"[",
"1",
":",
"-",
"1",
"]",
",",
"\"final_key\"",
":",
"parts",
"[",
"-",
"1",
"]",
",",
"\"env_key\"",
":",
"env_key",
"}",
"if",
"self",
".",
"_env",
".",
"get",
"(",
"parts",
"[",
"0",
"]",
")",
"is",
"None",
":",
"self",
".",
"_env",
"[",
"parts",
"[",
"0",
"]",
"]",
"=",
"[",
"env_info",
"]",
"else",
":",
"self",
".",
"_env",
"[",
"parts",
"[",
"0",
"]",
"]",
".",
"append",
"(",
"env_info",
")",
"return",
"None"
] |
Binds a Vyper key to a ENV variable.
ENV variables are case sensitive.
If only a key is provided, it will use the env key matching the key,
uppercased.
`env_prefix` will be used when set when env name is not provided.
|
[
"Binds",
"a",
"Vyper",
"key",
"to",
"a",
"ENV",
"variable",
".",
"ENV",
"variables",
"are",
"case",
"sensitive",
".",
"If",
"only",
"a",
"key",
"is",
"provided",
"it",
"will",
"use",
"the",
"env",
"key",
"matching",
"the",
"key",
"uppercased",
".",
"env_prefix",
"will",
"be",
"used",
"when",
"set",
"when",
"env",
"name",
"is",
"not",
"provided",
"."
] |
58ec7b90661502b7b2fea7a30849b90b907fcdec
|
https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L289-L321
|
10,157
|
admiralobvious/vyper
|
vyper/vyper.py
|
Vyper.is_set
|
def is_set(self, key):
"""Check to see if the key has been set in any of the data locations.
"""
path = key.split(self._key_delimiter)
lower_case_key = key.lower()
val = self._find(lower_case_key)
if val is None:
source = self._find(path[0].lower())
if source is not None and isinstance(source, dict):
val = self._search_dict(source, path[1::])
return val is not None
|
python
|
def is_set(self, key):
"""Check to see if the key has been set in any of the data locations.
"""
path = key.split(self._key_delimiter)
lower_case_key = key.lower()
val = self._find(lower_case_key)
if val is None:
source = self._find(path[0].lower())
if source is not None and isinstance(source, dict):
val = self._search_dict(source, path[1::])
return val is not None
|
[
"def",
"is_set",
"(",
"self",
",",
"key",
")",
":",
"path",
"=",
"key",
".",
"split",
"(",
"self",
".",
"_key_delimiter",
")",
"lower_case_key",
"=",
"key",
".",
"lower",
"(",
")",
"val",
"=",
"self",
".",
"_find",
"(",
"lower_case_key",
")",
"if",
"val",
"is",
"None",
":",
"source",
"=",
"self",
".",
"_find",
"(",
"path",
"[",
"0",
"]",
".",
"lower",
"(",
")",
")",
"if",
"source",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"source",
",",
"dict",
")",
":",
"val",
"=",
"self",
".",
"_search_dict",
"(",
"source",
",",
"path",
"[",
"1",
":",
":",
"]",
")",
"return",
"val",
"is",
"not",
"None"
] |
Check to see if the key has been set in any of the data locations.
|
[
"Check",
"to",
"see",
"if",
"the",
"key",
"has",
"been",
"set",
"in",
"any",
"of",
"the",
"data",
"locations",
"."
] |
58ec7b90661502b7b2fea7a30849b90b907fcdec
|
https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L438-L451
|
10,158
|
admiralobvious/vyper
|
vyper/vyper.py
|
Vyper.register_alias
|
def register_alias(self, alias, key):
"""Aliases provide another accessor for the same key.
This enables one to change a name without breaking the application.
"""
alias = alias.lower()
key = key.lower()
if alias != key and alias != self._real_key(key):
exists = self._aliases.get(alias)
if exists is None:
# if we alias something that exists in one of the dicts to
# another name, we'll never be able to get that value using the
# original name, so move the config value to the new _real_key.
val = self._config.get(alias)
if val:
self._config.pop(alias)
self._config[key] = val
val = self._kvstore.get(alias)
if val:
self._kvstore.pop(alias)
self._kvstore[key] = val
val = self._defaults.get(alias)
if val:
self._defaults.pop(alias)
self._defaults[key] = val
val = self._override.get(alias)
if val:
self._override.pop(alias)
self._override[key] = val
self._aliases[alias] = key
else:
log.warning("Creating circular reference alias {0} {1} {2}".format(
alias, key, self._real_key(key)))
|
python
|
def register_alias(self, alias, key):
"""Aliases provide another accessor for the same key.
This enables one to change a name without breaking the application.
"""
alias = alias.lower()
key = key.lower()
if alias != key and alias != self._real_key(key):
exists = self._aliases.get(alias)
if exists is None:
# if we alias something that exists in one of the dicts to
# another name, we'll never be able to get that value using the
# original name, so move the config value to the new _real_key.
val = self._config.get(alias)
if val:
self._config.pop(alias)
self._config[key] = val
val = self._kvstore.get(alias)
if val:
self._kvstore.pop(alias)
self._kvstore[key] = val
val = self._defaults.get(alias)
if val:
self._defaults.pop(alias)
self._defaults[key] = val
val = self._override.get(alias)
if val:
self._override.pop(alias)
self._override[key] = val
self._aliases[alias] = key
else:
log.warning("Creating circular reference alias {0} {1} {2}".format(
alias, key, self._real_key(key)))
|
[
"def",
"register_alias",
"(",
"self",
",",
"alias",
",",
"key",
")",
":",
"alias",
"=",
"alias",
".",
"lower",
"(",
")",
"key",
"=",
"key",
".",
"lower",
"(",
")",
"if",
"alias",
"!=",
"key",
"and",
"alias",
"!=",
"self",
".",
"_real_key",
"(",
"key",
")",
":",
"exists",
"=",
"self",
".",
"_aliases",
".",
"get",
"(",
"alias",
")",
"if",
"exists",
"is",
"None",
":",
"# if we alias something that exists in one of the dicts to",
"# another name, we'll never be able to get that value using the",
"# original name, so move the config value to the new _real_key.",
"val",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"alias",
")",
"if",
"val",
":",
"self",
".",
"_config",
".",
"pop",
"(",
"alias",
")",
"self",
".",
"_config",
"[",
"key",
"]",
"=",
"val",
"val",
"=",
"self",
".",
"_kvstore",
".",
"get",
"(",
"alias",
")",
"if",
"val",
":",
"self",
".",
"_kvstore",
".",
"pop",
"(",
"alias",
")",
"self",
".",
"_kvstore",
"[",
"key",
"]",
"=",
"val",
"val",
"=",
"self",
".",
"_defaults",
".",
"get",
"(",
"alias",
")",
"if",
"val",
":",
"self",
".",
"_defaults",
".",
"pop",
"(",
"alias",
")",
"self",
".",
"_defaults",
"[",
"key",
"]",
"=",
"val",
"val",
"=",
"self",
".",
"_override",
".",
"get",
"(",
"alias",
")",
"if",
"val",
":",
"self",
".",
"_override",
".",
"pop",
"(",
"alias",
")",
"self",
".",
"_override",
"[",
"key",
"]",
"=",
"val",
"self",
".",
"_aliases",
"[",
"alias",
"]",
"=",
"key",
"else",
":",
"log",
".",
"warning",
"(",
"\"Creating circular reference alias {0} {1} {2}\"",
".",
"format",
"(",
"alias",
",",
"key",
",",
"self",
".",
"_real_key",
"(",
"key",
")",
")",
")"
] |
Aliases provide another accessor for the same key.
This enables one to change a name without breaking the application.
|
[
"Aliases",
"provide",
"another",
"accessor",
"for",
"the",
"same",
"key",
".",
"This",
"enables",
"one",
"to",
"change",
"a",
"name",
"without",
"breaking",
"the",
"application",
"."
] |
58ec7b90661502b7b2fea7a30849b90b907fcdec
|
https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L466-L499
|
10,159
|
admiralobvious/vyper
|
vyper/vyper.py
|
Vyper.set_default
|
def set_default(self, key, value):
"""Set the default value for this key.
Default only used when no value is provided by the user via
arg, config or env.
"""
k = self._real_key(key.lower())
self._defaults[k] = value
|
python
|
def set_default(self, key, value):
"""Set the default value for this key.
Default only used when no value is provided by the user via
arg, config or env.
"""
k = self._real_key(key.lower())
self._defaults[k] = value
|
[
"def",
"set_default",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"k",
"=",
"self",
".",
"_real_key",
"(",
"key",
".",
"lower",
"(",
")",
")",
"self",
".",
"_defaults",
"[",
"k",
"]",
"=",
"value"
] |
Set the default value for this key.
Default only used when no value is provided by the user via
arg, config or env.
|
[
"Set",
"the",
"default",
"value",
"for",
"this",
"key",
".",
"Default",
"only",
"used",
"when",
"no",
"value",
"is",
"provided",
"by",
"the",
"user",
"via",
"arg",
"config",
"or",
"env",
"."
] |
58ec7b90661502b7b2fea7a30849b90b907fcdec
|
https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L517-L523
|
10,160
|
admiralobvious/vyper
|
vyper/vyper.py
|
Vyper._unmarshall_reader
|
def _unmarshall_reader(self, file_, d):
"""Unmarshall a file into a `dict`."""
return util.unmarshall_config_reader(file_, d, self._get_config_type())
|
python
|
def _unmarshall_reader(self, file_, d):
"""Unmarshall a file into a `dict`."""
return util.unmarshall_config_reader(file_, d, self._get_config_type())
|
[
"def",
"_unmarshall_reader",
"(",
"self",
",",
"file_",
",",
"d",
")",
":",
"return",
"util",
".",
"unmarshall_config_reader",
"(",
"file_",
",",
"d",
",",
"self",
".",
"_get_config_type",
"(",
")",
")"
] |
Unmarshall a file into a `dict`.
|
[
"Unmarshall",
"a",
"file",
"into",
"a",
"dict",
"."
] |
58ec7b90661502b7b2fea7a30849b90b907fcdec
|
https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L586-L588
|
10,161
|
admiralobvious/vyper
|
vyper/vyper.py
|
Vyper._get_key_value_config
|
def _get_key_value_config(self):
"""Retrieves the first found remote configuration."""
for rp in self._remote_providers:
val = self._get_remote_config(rp)
self._kvstore = val
return None
raise errors.RemoteConfigError("No Files Found")
|
python
|
def _get_key_value_config(self):
"""Retrieves the first found remote configuration."""
for rp in self._remote_providers:
val = self._get_remote_config(rp)
self._kvstore = val
return None
raise errors.RemoteConfigError("No Files Found")
|
[
"def",
"_get_key_value_config",
"(",
"self",
")",
":",
"for",
"rp",
"in",
"self",
".",
"_remote_providers",
":",
"val",
"=",
"self",
".",
"_get_remote_config",
"(",
"rp",
")",
"self",
".",
"_kvstore",
"=",
"val",
"return",
"None",
"raise",
"errors",
".",
"RemoteConfigError",
"(",
"\"No Files Found\"",
")"
] |
Retrieves the first found remote configuration.
|
[
"Retrieves",
"the",
"first",
"found",
"remote",
"configuration",
"."
] |
58ec7b90661502b7b2fea7a30849b90b907fcdec
|
https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L590-L597
|
10,162
|
admiralobvious/vyper
|
vyper/vyper.py
|
Vyper.all_keys
|
def all_keys(self, uppercase_keys=False):
"""Return all keys regardless where they are set."""
d = {}
for k in self._override.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._args.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._env.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._config.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._kvstore.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._defaults.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._aliases.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
return d.keys()
|
python
|
def all_keys(self, uppercase_keys=False):
"""Return all keys regardless where they are set."""
d = {}
for k in self._override.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._args.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._env.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._config.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._kvstore.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._defaults.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._aliases.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
return d.keys()
|
[
"def",
"all_keys",
"(",
"self",
",",
"uppercase_keys",
"=",
"False",
")",
":",
"d",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_override",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_args",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_env",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_config",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_kvstore",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_defaults",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"_aliases",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
".",
"upper",
"(",
")",
"if",
"uppercase_keys",
"else",
"k",
".",
"lower",
"(",
")",
"]",
"=",
"{",
"}",
"return",
"d",
".",
"keys",
"(",
")"
] |
Return all keys regardless where they are set.
|
[
"Return",
"all",
"keys",
"regardless",
"where",
"they",
"are",
"set",
"."
] |
58ec7b90661502b7b2fea7a30849b90b907fcdec
|
https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L617-L642
|
10,163
|
admiralobvious/vyper
|
vyper/vyper.py
|
Vyper.all_settings
|
def all_settings(self, uppercase_keys=False):
"""Return all settings as a `dict`."""
d = {}
for k in self.all_keys(uppercase_keys):
d[k] = self.get(k)
return d
|
python
|
def all_settings(self, uppercase_keys=False):
"""Return all settings as a `dict`."""
d = {}
for k in self.all_keys(uppercase_keys):
d[k] = self.get(k)
return d
|
[
"def",
"all_settings",
"(",
"self",
",",
"uppercase_keys",
"=",
"False",
")",
":",
"d",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"all_keys",
"(",
"uppercase_keys",
")",
":",
"d",
"[",
"k",
"]",
"=",
"self",
".",
"get",
"(",
"k",
")",
"return",
"d"
] |
Return all settings as a `dict`.
|
[
"Return",
"all",
"settings",
"as",
"a",
"dict",
"."
] |
58ec7b90661502b7b2fea7a30849b90b907fcdec
|
https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L644-L651
|
10,164
|
admiralobvious/vyper
|
vyper/vyper.py
|
Vyper.debug
|
def debug(self): # pragma: no cover
"""Prints all configuration registries for debugging purposes."""
print("Aliases:")
pprint.pprint(self._aliases)
print("Override:")
pprint.pprint(self._override)
print("Args:")
pprint.pprint(self._args)
print("Env:")
pprint.pprint(self._env)
print("Config:")
pprint.pprint(self._config)
print("Key/Value Store:")
pprint.pprint(self._kvstore)
print("Defaults:")
pprint.pprint(self._defaults)
|
python
|
def debug(self): # pragma: no cover
"""Prints all configuration registries for debugging purposes."""
print("Aliases:")
pprint.pprint(self._aliases)
print("Override:")
pprint.pprint(self._override)
print("Args:")
pprint.pprint(self._args)
print("Env:")
pprint.pprint(self._env)
print("Config:")
pprint.pprint(self._config)
print("Key/Value Store:")
pprint.pprint(self._kvstore)
print("Defaults:")
pprint.pprint(self._defaults)
|
[
"def",
"debug",
"(",
"self",
")",
":",
"# pragma: no cover",
"print",
"(",
"\"Aliases:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_aliases",
")",
"print",
"(",
"\"Override:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_override",
")",
"print",
"(",
"\"Args:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_args",
")",
"print",
"(",
"\"Env:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_env",
")",
"print",
"(",
"\"Config:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_config",
")",
"print",
"(",
"\"Key/Value Store:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_kvstore",
")",
"print",
"(",
"\"Defaults:\"",
")",
"pprint",
".",
"pprint",
"(",
"self",
".",
"_defaults",
")"
] |
Prints all configuration registries for debugging purposes.
|
[
"Prints",
"all",
"configuration",
"registries",
"for",
"debugging",
"purposes",
"."
] |
58ec7b90661502b7b2fea7a30849b90b907fcdec
|
https://github.com/admiralobvious/vyper/blob/58ec7b90661502b7b2fea7a30849b90b907fcdec/vyper/vyper.py#L713-L729
|
10,165
|
rsalmei/clearly
|
clearly/command_line.py
|
server
|
def server(**kwargs):
"""
Starts the Clearly Server.
BROKER: The broker being used by celery, like "amqp://localhost".
"""
start_server(**{k: v for k, v in kwargs.items() if v},
blocking=True)
|
python
|
def server(**kwargs):
"""
Starts the Clearly Server.
BROKER: The broker being used by celery, like "amqp://localhost".
"""
start_server(**{k: v for k, v in kwargs.items() if v},
blocking=True)
|
[
"def",
"server",
"(",
"*",
"*",
"kwargs",
")",
":",
"start_server",
"(",
"*",
"*",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"v",
"}",
",",
"blocking",
"=",
"True",
")"
] |
Starts the Clearly Server.
BROKER: The broker being used by celery, like "amqp://localhost".
|
[
"Starts",
"the",
"Clearly",
"Server",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/command_line.py#L25-L32
|
10,166
|
rsalmei/clearly
|
clearly/server.py
|
start_server
|
def start_server(broker, backend=None, port=12223,
max_tasks=10000, max_workers=100,
blocking=False, debug=False): # pragma: no cover
"""Starts a Clearly Server programmatically."""
_setup_logging(debug)
queue_listener_dispatcher = Queue()
listener = EventListener(broker, queue_listener_dispatcher, backend=backend,
max_tasks_in_memory=max_tasks,
max_workers_in_memory=max_workers)
dispatcher = StreamingDispatcher(queue_listener_dispatcher)
clearlysrv = ClearlyServer(listener, dispatcher)
return _serve(clearlysrv, port, blocking)
|
python
|
def start_server(broker, backend=None, port=12223,
max_tasks=10000, max_workers=100,
blocking=False, debug=False): # pragma: no cover
"""Starts a Clearly Server programmatically."""
_setup_logging(debug)
queue_listener_dispatcher = Queue()
listener = EventListener(broker, queue_listener_dispatcher, backend=backend,
max_tasks_in_memory=max_tasks,
max_workers_in_memory=max_workers)
dispatcher = StreamingDispatcher(queue_listener_dispatcher)
clearlysrv = ClearlyServer(listener, dispatcher)
return _serve(clearlysrv, port, blocking)
|
[
"def",
"start_server",
"(",
"broker",
",",
"backend",
"=",
"None",
",",
"port",
"=",
"12223",
",",
"max_tasks",
"=",
"10000",
",",
"max_workers",
"=",
"100",
",",
"blocking",
"=",
"False",
",",
"debug",
"=",
"False",
")",
":",
"# pragma: no cover",
"_setup_logging",
"(",
"debug",
")",
"queue_listener_dispatcher",
"=",
"Queue",
"(",
")",
"listener",
"=",
"EventListener",
"(",
"broker",
",",
"queue_listener_dispatcher",
",",
"backend",
"=",
"backend",
",",
"max_tasks_in_memory",
"=",
"max_tasks",
",",
"max_workers_in_memory",
"=",
"max_workers",
")",
"dispatcher",
"=",
"StreamingDispatcher",
"(",
"queue_listener_dispatcher",
")",
"clearlysrv",
"=",
"ClearlyServer",
"(",
"listener",
",",
"dispatcher",
")",
"return",
"_serve",
"(",
"clearlysrv",
",",
"port",
",",
"blocking",
")"
] |
Starts a Clearly Server programmatically.
|
[
"Starts",
"a",
"Clearly",
"Server",
"programmatically",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L193-L205
|
10,167
|
rsalmei/clearly
|
clearly/server.py
|
ClearlyServer._event_to_pb
|
def _event_to_pb(event):
"""Supports converting internal TaskData and WorkerData, as well as
celery Task and Worker to proto buffers messages.
Args:
event (Union[TaskData|Task|WorkerData|Worker]):
Returns:
ProtoBuf object
"""
if isinstance(event, (TaskData, Task)):
key, klass = 'task', clearly_pb2.TaskMessage
elif isinstance(event, (WorkerData, Worker)):
key, klass = 'worker', clearly_pb2.WorkerMessage
else:
raise ValueError('unknown event')
keys = klass.DESCRIPTOR.fields_by_name.keys()
# noinspection PyProtectedMember
data = {k: v for k, v in
getattr(event, '_asdict', # internal TaskData and WorkerData
lambda: {f: getattr(event, f) for f in event._fields}) # celery Task and Worker
().items() if k in keys}
return key, klass(**data)
|
python
|
def _event_to_pb(event):
"""Supports converting internal TaskData and WorkerData, as well as
celery Task and Worker to proto buffers messages.
Args:
event (Union[TaskData|Task|WorkerData|Worker]):
Returns:
ProtoBuf object
"""
if isinstance(event, (TaskData, Task)):
key, klass = 'task', clearly_pb2.TaskMessage
elif isinstance(event, (WorkerData, Worker)):
key, klass = 'worker', clearly_pb2.WorkerMessage
else:
raise ValueError('unknown event')
keys = klass.DESCRIPTOR.fields_by_name.keys()
# noinspection PyProtectedMember
data = {k: v for k, v in
getattr(event, '_asdict', # internal TaskData and WorkerData
lambda: {f: getattr(event, f) for f in event._fields}) # celery Task and Worker
().items() if k in keys}
return key, klass(**data)
|
[
"def",
"_event_to_pb",
"(",
"event",
")",
":",
"if",
"isinstance",
"(",
"event",
",",
"(",
"TaskData",
",",
"Task",
")",
")",
":",
"key",
",",
"klass",
"=",
"'task'",
",",
"clearly_pb2",
".",
"TaskMessage",
"elif",
"isinstance",
"(",
"event",
",",
"(",
"WorkerData",
",",
"Worker",
")",
")",
":",
"key",
",",
"klass",
"=",
"'worker'",
",",
"clearly_pb2",
".",
"WorkerMessage",
"else",
":",
"raise",
"ValueError",
"(",
"'unknown event'",
")",
"keys",
"=",
"klass",
".",
"DESCRIPTOR",
".",
"fields_by_name",
".",
"keys",
"(",
")",
"# noinspection PyProtectedMember",
"data",
"=",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"getattr",
"(",
"event",
",",
"'_asdict'",
",",
"# internal TaskData and WorkerData",
"lambda",
":",
"{",
"f",
":",
"getattr",
"(",
"event",
",",
"f",
")",
"for",
"f",
"in",
"event",
".",
"_fields",
"}",
")",
"# celery Task and Worker",
"(",
")",
".",
"items",
"(",
")",
"if",
"k",
"in",
"keys",
"}",
"return",
"key",
",",
"klass",
"(",
"*",
"*",
"data",
")"
] |
Supports converting internal TaskData and WorkerData, as well as
celery Task and Worker to proto buffers messages.
Args:
event (Union[TaskData|Task|WorkerData|Worker]):
Returns:
ProtoBuf object
|
[
"Supports",
"converting",
"internal",
"TaskData",
"and",
"WorkerData",
"as",
"well",
"as",
"celery",
"Task",
"and",
"Worker",
"to",
"proto",
"buffers",
"messages",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L73-L96
|
10,168
|
rsalmei/clearly
|
clearly/server.py
|
ClearlyServer.filter_tasks
|
def filter_tasks(self, request, context):
"""Filter tasks by matching patterns to name, routing key and state."""
_log_request(request, context)
tasks_pattern, tasks_negate = PATTERN_PARAMS_OP(request.tasks_filter)
state_pattern = request.state_pattern
limit, reverse = request.limit, request.reverse
pregex = re.compile(tasks_pattern) # pattern filter condition
sregex = re.compile(state_pattern) # state filter condition
def pcondition(task):
return accepts(pregex, tasks_negate, task.name, task.routing_key)
def scondition(task):
return accepts(sregex, tasks_negate, task.state)
found_tasks = (task for _, task in
self.listener.memory.tasks_by_time(limit=limit or None,
reverse=reverse)
if pcondition(task) and scondition(task))
def callback(t):
logger.debug('%s iterated %d tasks in %s (%s)', self.filter_tasks.__name__,
t.count, t.duration_human, t.throughput_human)
for task in about_time(callback, found_tasks):
yield ClearlyServer._event_to_pb(task)[1]
|
python
|
def filter_tasks(self, request, context):
"""Filter tasks by matching patterns to name, routing key and state."""
_log_request(request, context)
tasks_pattern, tasks_negate = PATTERN_PARAMS_OP(request.tasks_filter)
state_pattern = request.state_pattern
limit, reverse = request.limit, request.reverse
pregex = re.compile(tasks_pattern) # pattern filter condition
sregex = re.compile(state_pattern) # state filter condition
def pcondition(task):
return accepts(pregex, tasks_negate, task.name, task.routing_key)
def scondition(task):
return accepts(sregex, tasks_negate, task.state)
found_tasks = (task for _, task in
self.listener.memory.tasks_by_time(limit=limit or None,
reverse=reverse)
if pcondition(task) and scondition(task))
def callback(t):
logger.debug('%s iterated %d tasks in %s (%s)', self.filter_tasks.__name__,
t.count, t.duration_human, t.throughput_human)
for task in about_time(callback, found_tasks):
yield ClearlyServer._event_to_pb(task)[1]
|
[
"def",
"filter_tasks",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"_log_request",
"(",
"request",
",",
"context",
")",
"tasks_pattern",
",",
"tasks_negate",
"=",
"PATTERN_PARAMS_OP",
"(",
"request",
".",
"tasks_filter",
")",
"state_pattern",
"=",
"request",
".",
"state_pattern",
"limit",
",",
"reverse",
"=",
"request",
".",
"limit",
",",
"request",
".",
"reverse",
"pregex",
"=",
"re",
".",
"compile",
"(",
"tasks_pattern",
")",
"# pattern filter condition",
"sregex",
"=",
"re",
".",
"compile",
"(",
"state_pattern",
")",
"# state filter condition",
"def",
"pcondition",
"(",
"task",
")",
":",
"return",
"accepts",
"(",
"pregex",
",",
"tasks_negate",
",",
"task",
".",
"name",
",",
"task",
".",
"routing_key",
")",
"def",
"scondition",
"(",
"task",
")",
":",
"return",
"accepts",
"(",
"sregex",
",",
"tasks_negate",
",",
"task",
".",
"state",
")",
"found_tasks",
"=",
"(",
"task",
"for",
"_",
",",
"task",
"in",
"self",
".",
"listener",
".",
"memory",
".",
"tasks_by_time",
"(",
"limit",
"=",
"limit",
"or",
"None",
",",
"reverse",
"=",
"reverse",
")",
"if",
"pcondition",
"(",
"task",
")",
"and",
"scondition",
"(",
"task",
")",
")",
"def",
"callback",
"(",
"t",
")",
":",
"logger",
".",
"debug",
"(",
"'%s iterated %d tasks in %s (%s)'",
",",
"self",
".",
"filter_tasks",
".",
"__name__",
",",
"t",
".",
"count",
",",
"t",
".",
"duration_human",
",",
"t",
".",
"throughput_human",
")",
"for",
"task",
"in",
"about_time",
"(",
"callback",
",",
"found_tasks",
")",
":",
"yield",
"ClearlyServer",
".",
"_event_to_pb",
"(",
"task",
")",
"[",
"1",
"]"
] |
Filter tasks by matching patterns to name, routing key and state.
|
[
"Filter",
"tasks",
"by",
"matching",
"patterns",
"to",
"name",
"routing",
"key",
"and",
"state",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L98-L124
|
10,169
|
rsalmei/clearly
|
clearly/server.py
|
ClearlyServer.filter_workers
|
def filter_workers(self, request, context):
"""Filter workers by matching a pattern to hostname."""
_log_request(request, context)
workers_pattern, workers_negate = PATTERN_PARAMS_OP(request.workers_filter)
hregex = re.compile(workers_pattern) # hostname filter condition
def hcondition(worker):
return accepts(hregex, workers_negate, worker.hostname) # pragma: no branch
found_workers = (worker for worker in
sorted(self.listener.memory.workers.values(),
key=WORKER_HOSTNAME_OP)
if hcondition(worker))
def callback(t):
logger.debug('%s iterated %d workers in %s (%s)', self.filter_workers.__name__,
t.count, t.duration_human, t.throughput_human)
for worker in about_time(callback, found_workers):
yield ClearlyServer._event_to_pb(worker)[1]
|
python
|
def filter_workers(self, request, context):
"""Filter workers by matching a pattern to hostname."""
_log_request(request, context)
workers_pattern, workers_negate = PATTERN_PARAMS_OP(request.workers_filter)
hregex = re.compile(workers_pattern) # hostname filter condition
def hcondition(worker):
return accepts(hregex, workers_negate, worker.hostname) # pragma: no branch
found_workers = (worker for worker in
sorted(self.listener.memory.workers.values(),
key=WORKER_HOSTNAME_OP)
if hcondition(worker))
def callback(t):
logger.debug('%s iterated %d workers in %s (%s)', self.filter_workers.__name__,
t.count, t.duration_human, t.throughput_human)
for worker in about_time(callback, found_workers):
yield ClearlyServer._event_to_pb(worker)[1]
|
[
"def",
"filter_workers",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"_log_request",
"(",
"request",
",",
"context",
")",
"workers_pattern",
",",
"workers_negate",
"=",
"PATTERN_PARAMS_OP",
"(",
"request",
".",
"workers_filter",
")",
"hregex",
"=",
"re",
".",
"compile",
"(",
"workers_pattern",
")",
"# hostname filter condition",
"def",
"hcondition",
"(",
"worker",
")",
":",
"return",
"accepts",
"(",
"hregex",
",",
"workers_negate",
",",
"worker",
".",
"hostname",
")",
"# pragma: no branch",
"found_workers",
"=",
"(",
"worker",
"for",
"worker",
"in",
"sorted",
"(",
"self",
".",
"listener",
".",
"memory",
".",
"workers",
".",
"values",
"(",
")",
",",
"key",
"=",
"WORKER_HOSTNAME_OP",
")",
"if",
"hcondition",
"(",
"worker",
")",
")",
"def",
"callback",
"(",
"t",
")",
":",
"logger",
".",
"debug",
"(",
"'%s iterated %d workers in %s (%s)'",
",",
"self",
".",
"filter_workers",
".",
"__name__",
",",
"t",
".",
"count",
",",
"t",
".",
"duration_human",
",",
"t",
".",
"throughput_human",
")",
"for",
"worker",
"in",
"about_time",
"(",
"callback",
",",
"found_workers",
")",
":",
"yield",
"ClearlyServer",
".",
"_event_to_pb",
"(",
"worker",
")",
"[",
"1",
"]"
] |
Filter workers by matching a pattern to hostname.
|
[
"Filter",
"workers",
"by",
"matching",
"a",
"pattern",
"to",
"hostname",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L126-L146
|
10,170
|
rsalmei/clearly
|
clearly/server.py
|
ClearlyServer.seen_tasks
|
def seen_tasks(self, request, context):
"""Returns all seen task types."""
_log_request(request, context)
result = clearly_pb2.SeenTasksMessage()
result.task_types.extend(self.listener.memory.task_types())
return result
|
python
|
def seen_tasks(self, request, context):
"""Returns all seen task types."""
_log_request(request, context)
result = clearly_pb2.SeenTasksMessage()
result.task_types.extend(self.listener.memory.task_types())
return result
|
[
"def",
"seen_tasks",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"_log_request",
"(",
"request",
",",
"context",
")",
"result",
"=",
"clearly_pb2",
".",
"SeenTasksMessage",
"(",
")",
"result",
".",
"task_types",
".",
"extend",
"(",
"self",
".",
"listener",
".",
"memory",
".",
"task_types",
"(",
")",
")",
"return",
"result"
] |
Returns all seen task types.
|
[
"Returns",
"all",
"seen",
"task",
"types",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L156-L161
|
10,171
|
rsalmei/clearly
|
clearly/server.py
|
ClearlyServer.reset_tasks
|
def reset_tasks(self, request, context):
"""Resets all captured tasks."""
_log_request(request, context)
self.listener.memory.clear_tasks()
return clearly_pb2.Empty()
|
python
|
def reset_tasks(self, request, context):
"""Resets all captured tasks."""
_log_request(request, context)
self.listener.memory.clear_tasks()
return clearly_pb2.Empty()
|
[
"def",
"reset_tasks",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"_log_request",
"(",
"request",
",",
"context",
")",
"self",
".",
"listener",
".",
"memory",
".",
"clear_tasks",
"(",
")",
"return",
"clearly_pb2",
".",
"Empty",
"(",
")"
] |
Resets all captured tasks.
|
[
"Resets",
"all",
"captured",
"tasks",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L163-L167
|
10,172
|
rsalmei/clearly
|
clearly/server.py
|
ClearlyServer.get_stats
|
def get_stats(self, request, context):
"""Returns the server statistics."""
_log_request(request, context)
m = self.listener.memory
return clearly_pb2.StatsMessage(
task_count=m.task_count,
event_count=m.event_count,
len_tasks=len(m.tasks),
len_workers=len(m.workers)
)
|
python
|
def get_stats(self, request, context):
"""Returns the server statistics."""
_log_request(request, context)
m = self.listener.memory
return clearly_pb2.StatsMessage(
task_count=m.task_count,
event_count=m.event_count,
len_tasks=len(m.tasks),
len_workers=len(m.workers)
)
|
[
"def",
"get_stats",
"(",
"self",
",",
"request",
",",
"context",
")",
":",
"_log_request",
"(",
"request",
",",
"context",
")",
"m",
"=",
"self",
".",
"listener",
".",
"memory",
"return",
"clearly_pb2",
".",
"StatsMessage",
"(",
"task_count",
"=",
"m",
".",
"task_count",
",",
"event_count",
"=",
"m",
".",
"event_count",
",",
"len_tasks",
"=",
"len",
"(",
"m",
".",
"tasks",
")",
",",
"len_workers",
"=",
"len",
"(",
"m",
".",
"workers",
")",
")"
] |
Returns the server statistics.
|
[
"Returns",
"the",
"server",
"statistics",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L169-L178
|
10,173
|
rsalmei/clearly
|
clearly/utils/data.py
|
accepts
|
def accepts(regex, negate, *values):
"""Given a compiled regex and a negate, find if any of the values match.
Args:
regex (Pattern):
negate (bool):
*values (str):
Returns:
"""
return any(v and regex.search(v) for v in values) != negate
|
python
|
def accepts(regex, negate, *values):
"""Given a compiled regex and a negate, find if any of the values match.
Args:
regex (Pattern):
negate (bool):
*values (str):
Returns:
"""
return any(v and regex.search(v) for v in values) != negate
|
[
"def",
"accepts",
"(",
"regex",
",",
"negate",
",",
"*",
"values",
")",
":",
"return",
"any",
"(",
"v",
"and",
"regex",
".",
"search",
"(",
"v",
")",
"for",
"v",
"in",
"values",
")",
"!=",
"negate"
] |
Given a compiled regex and a negate, find if any of the values match.
Args:
regex (Pattern):
negate (bool):
*values (str):
Returns:
|
[
"Given",
"a",
"compiled",
"regex",
"and",
"a",
"negate",
"find",
"if",
"any",
"of",
"the",
"values",
"match",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/utils/data.py#L1-L12
|
10,174
|
rsalmei/clearly
|
clearly/utils/data.py
|
copy_update
|
def copy_update(pb_message, **kwds):
"""Returns a copy of the PB object, with some fields updated.
Args:
pb_message:
**kwds:
Returns:
"""
result = pb_message.__class__()
result.CopyFrom(pb_message)
for k, v in kwds.items():
setattr(result, k, v)
return result
|
python
|
def copy_update(pb_message, **kwds):
"""Returns a copy of the PB object, with some fields updated.
Args:
pb_message:
**kwds:
Returns:
"""
result = pb_message.__class__()
result.CopyFrom(pb_message)
for k, v in kwds.items():
setattr(result, k, v)
return result
|
[
"def",
"copy_update",
"(",
"pb_message",
",",
"*",
"*",
"kwds",
")",
":",
"result",
"=",
"pb_message",
".",
"__class__",
"(",
")",
"result",
".",
"CopyFrom",
"(",
"pb_message",
")",
"for",
"k",
",",
"v",
"in",
"kwds",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"result",
",",
"k",
",",
"v",
")",
"return",
"result"
] |
Returns a copy of the PB object, with some fields updated.
Args:
pb_message:
**kwds:
Returns:
|
[
"Returns",
"a",
"copy",
"of",
"the",
"PB",
"object",
"with",
"some",
"fields",
"updated",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/utils/data.py#L15-L29
|
10,175
|
rsalmei/clearly
|
clearly/event_core/streaming_dispatcher.py
|
StreamingDispatcher.__start
|
def __start(self): # pragma: no cover
"""Starts the real-time engine that captures tasks."""
assert not self.dispatcher_thread
self.dispatcher_thread = threading.Thread(target=self.__run_dispatcher,
name='clearly-dispatcher')
self.dispatcher_thread.daemon = True
self.running = True # graceful shutdown
self.dispatcher_thread.start()
|
python
|
def __start(self): # pragma: no cover
"""Starts the real-time engine that captures tasks."""
assert not self.dispatcher_thread
self.dispatcher_thread = threading.Thread(target=self.__run_dispatcher,
name='clearly-dispatcher')
self.dispatcher_thread.daemon = True
self.running = True # graceful shutdown
self.dispatcher_thread.start()
|
[
"def",
"__start",
"(",
"self",
")",
":",
"# pragma: no cover",
"assert",
"not",
"self",
".",
"dispatcher_thread",
"self",
".",
"dispatcher_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"__run_dispatcher",
",",
"name",
"=",
"'clearly-dispatcher'",
")",
"self",
".",
"dispatcher_thread",
".",
"daemon",
"=",
"True",
"self",
".",
"running",
"=",
"True",
"# graceful shutdown",
"self",
".",
"dispatcher_thread",
".",
"start",
"(",
")"
] |
Starts the real-time engine that captures tasks.
|
[
"Starts",
"the",
"real",
"-",
"time",
"engine",
"that",
"captures",
"tasks",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/event_core/streaming_dispatcher.py#L56-L65
|
10,176
|
rsalmei/clearly
|
clearly/event_core/streaming_dispatcher.py
|
StreamingDispatcher.streaming_client
|
def streaming_client(self, tasks_regex, tasks_negate, workers_regex, workers_negate):
"""Connects a client to the streaming capture, filtering the events that are sent
to it.
Args:
tasks_regex (str): a pattern to filter tasks to capture.
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
tasks_negate (bool): if True, finds tasks that do not match criteria
workers_regex (str): a pattern to filter workers to capture.
ex.: 'service|priority' to filter names containing that
workers_negate (bool): if True, finds workers that do not match criteria
"""
cc = CapturingClient(Queue(),
re.compile(tasks_regex), tasks_negate,
re.compile(workers_regex), workers_negate)
self.observers.append(cc)
yield cc.queue
self.observers.remove(cc)
|
python
|
def streaming_client(self, tasks_regex, tasks_negate, workers_regex, workers_negate):
"""Connects a client to the streaming capture, filtering the events that are sent
to it.
Args:
tasks_regex (str): a pattern to filter tasks to capture.
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
tasks_negate (bool): if True, finds tasks that do not match criteria
workers_regex (str): a pattern to filter workers to capture.
ex.: 'service|priority' to filter names containing that
workers_negate (bool): if True, finds workers that do not match criteria
"""
cc = CapturingClient(Queue(),
re.compile(tasks_regex), tasks_negate,
re.compile(workers_regex), workers_negate)
self.observers.append(cc)
yield cc.queue
self.observers.remove(cc)
|
[
"def",
"streaming_client",
"(",
"self",
",",
"tasks_regex",
",",
"tasks_negate",
",",
"workers_regex",
",",
"workers_negate",
")",
":",
"cc",
"=",
"CapturingClient",
"(",
"Queue",
"(",
")",
",",
"re",
".",
"compile",
"(",
"tasks_regex",
")",
",",
"tasks_negate",
",",
"re",
".",
"compile",
"(",
"workers_regex",
")",
",",
"workers_negate",
")",
"self",
".",
"observers",
".",
"append",
"(",
"cc",
")",
"yield",
"cc",
".",
"queue",
"self",
".",
"observers",
".",
"remove",
"(",
"cc",
")"
] |
Connects a client to the streaming capture, filtering the events that are sent
to it.
Args:
tasks_regex (str): a pattern to filter tasks to capture.
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
tasks_negate (bool): if True, finds tasks that do not match criteria
workers_regex (str): a pattern to filter workers to capture.
ex.: 'service|priority' to filter names containing that
workers_negate (bool): if True, finds workers that do not match criteria
|
[
"Connects",
"a",
"client",
"to",
"the",
"streaming",
"capture",
"filtering",
"the",
"events",
"that",
"are",
"sent",
"to",
"it",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/event_core/streaming_dispatcher.py#L79-L100
|
10,177
|
rsalmei/clearly
|
clearly/event_core/event_listener.py
|
EventListener.__start
|
def __start(self): # pragma: no cover
"""Starts the real-time engine that captures events."""
assert not self._listener_thread
self._listener_thread = threading.Thread(target=self.__run_listener,
name='clearly-listener')
self._listener_thread.daemon = True
self._listener_thread.start()
self._wait_event.wait()
self._wait_event.clear()
|
python
|
def __start(self): # pragma: no cover
"""Starts the real-time engine that captures events."""
assert not self._listener_thread
self._listener_thread = threading.Thread(target=self.__run_listener,
name='clearly-listener')
self._listener_thread.daemon = True
self._listener_thread.start()
self._wait_event.wait()
self._wait_event.clear()
|
[
"def",
"__start",
"(",
"self",
")",
":",
"# pragma: no cover",
"assert",
"not",
"self",
".",
"_listener_thread",
"self",
".",
"_listener_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"__run_listener",
",",
"name",
"=",
"'clearly-listener'",
")",
"self",
".",
"_listener_thread",
".",
"daemon",
"=",
"True",
"self",
".",
"_listener_thread",
".",
"start",
"(",
")",
"self",
".",
"_wait_event",
".",
"wait",
"(",
")",
"self",
".",
"_wait_event",
".",
"clear",
"(",
")"
] |
Starts the real-time engine that captures events.
|
[
"Starts",
"the",
"real",
"-",
"time",
"engine",
"that",
"captures",
"events",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/event_core/event_listener.py#L71-L81
|
10,178
|
rsalmei/clearly
|
clearly/client.py
|
ClearlyClient.capture
|
def capture(self, pattern=None, negate=False, workers=None, negate_workers=False,
params=None, success=False, error=True, stats=False):
"""Starts capturing selected events in real-time. You can filter exactly what
you want to see, as the Clearly Server handles all tasks and workers updates
being sent to celery. Several clients can see different sets of events at the
same time.
This runs in the foreground, so you can see in real-time exactly what your
clients and celery workers are doing.
Press CTRL+C at any time to stop it.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter tasks to capture.
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
negate (bool): if True, finds tasks that do not match criteria.
workers (Optional[str]): a pattern to filter workers to capture.
ex.: 'service|priority' to filter names containing that
negate_workers (bool): if True, finds workers that do not match criteria.
Display args:
params (Optional[bool]): if True shows args and kwargs in the first and
last seen states, if False never shows, and if None follows the
success and error arguments.
default is None
success (bool): if True shows successful tasks' results.
default is False
error (bool): if True shows failed and retried tasks' tracebacks.
default is True, as you're monitoring to find errors, right?
stats (bool): if True shows complete workers' stats.
default is False
"""
request = clearly_pb2.CaptureRequest(
tasks_capture=clearly_pb2.PatternFilter(pattern=pattern or '.',
negate=negate),
workers_capture=clearly_pb2.PatternFilter(pattern=workers or '.',
negate=negate_workers),
)
try:
for realtime in self._stub.capture_realtime(request):
if realtime.HasField('task'):
ClearlyClient._display_task(realtime.task, params, success, error)
elif realtime.HasField('worker'):
ClearlyClient._display_worker(realtime.worker, stats)
else:
print('unknown event:', realtime)
break
except KeyboardInterrupt:
pass
|
python
|
def capture(self, pattern=None, negate=False, workers=None, negate_workers=False,
params=None, success=False, error=True, stats=False):
"""Starts capturing selected events in real-time. You can filter exactly what
you want to see, as the Clearly Server handles all tasks and workers updates
being sent to celery. Several clients can see different sets of events at the
same time.
This runs in the foreground, so you can see in real-time exactly what your
clients and celery workers are doing.
Press CTRL+C at any time to stop it.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter tasks to capture.
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
negate (bool): if True, finds tasks that do not match criteria.
workers (Optional[str]): a pattern to filter workers to capture.
ex.: 'service|priority' to filter names containing that
negate_workers (bool): if True, finds workers that do not match criteria.
Display args:
params (Optional[bool]): if True shows args and kwargs in the first and
last seen states, if False never shows, and if None follows the
success and error arguments.
default is None
success (bool): if True shows successful tasks' results.
default is False
error (bool): if True shows failed and retried tasks' tracebacks.
default is True, as you're monitoring to find errors, right?
stats (bool): if True shows complete workers' stats.
default is False
"""
request = clearly_pb2.CaptureRequest(
tasks_capture=clearly_pb2.PatternFilter(pattern=pattern or '.',
negate=negate),
workers_capture=clearly_pb2.PatternFilter(pattern=workers or '.',
negate=negate_workers),
)
try:
for realtime in self._stub.capture_realtime(request):
if realtime.HasField('task'):
ClearlyClient._display_task(realtime.task, params, success, error)
elif realtime.HasField('worker'):
ClearlyClient._display_worker(realtime.worker, stats)
else:
print('unknown event:', realtime)
break
except KeyboardInterrupt:
pass
|
[
"def",
"capture",
"(",
"self",
",",
"pattern",
"=",
"None",
",",
"negate",
"=",
"False",
",",
"workers",
"=",
"None",
",",
"negate_workers",
"=",
"False",
",",
"params",
"=",
"None",
",",
"success",
"=",
"False",
",",
"error",
"=",
"True",
",",
"stats",
"=",
"False",
")",
":",
"request",
"=",
"clearly_pb2",
".",
"CaptureRequest",
"(",
"tasks_capture",
"=",
"clearly_pb2",
".",
"PatternFilter",
"(",
"pattern",
"=",
"pattern",
"or",
"'.'",
",",
"negate",
"=",
"negate",
")",
",",
"workers_capture",
"=",
"clearly_pb2",
".",
"PatternFilter",
"(",
"pattern",
"=",
"workers",
"or",
"'.'",
",",
"negate",
"=",
"negate_workers",
")",
",",
")",
"try",
":",
"for",
"realtime",
"in",
"self",
".",
"_stub",
".",
"capture_realtime",
"(",
"request",
")",
":",
"if",
"realtime",
".",
"HasField",
"(",
"'task'",
")",
":",
"ClearlyClient",
".",
"_display_task",
"(",
"realtime",
".",
"task",
",",
"params",
",",
"success",
",",
"error",
")",
"elif",
"realtime",
".",
"HasField",
"(",
"'worker'",
")",
":",
"ClearlyClient",
".",
"_display_worker",
"(",
"realtime",
".",
"worker",
",",
"stats",
")",
"else",
":",
"print",
"(",
"'unknown event:'",
",",
"realtime",
")",
"break",
"except",
"KeyboardInterrupt",
":",
"pass"
] |
Starts capturing selected events in real-time. You can filter exactly what
you want to see, as the Clearly Server handles all tasks and workers updates
being sent to celery. Several clients can see different sets of events at the
same time.
This runs in the foreground, so you can see in real-time exactly what your
clients and celery workers are doing.
Press CTRL+C at any time to stop it.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter tasks to capture.
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
negate (bool): if True, finds tasks that do not match criteria.
workers (Optional[str]): a pattern to filter workers to capture.
ex.: 'service|priority' to filter names containing that
negate_workers (bool): if True, finds workers that do not match criteria.
Display args:
params (Optional[bool]): if True shows args and kwargs in the first and
last seen states, if False never shows, and if None follows the
success and error arguments.
default is None
success (bool): if True shows successful tasks' results.
default is False
error (bool): if True shows failed and retried tasks' tracebacks.
default is True, as you're monitoring to find errors, right?
stats (bool): if True shows complete workers' stats.
default is False
|
[
"Starts",
"capturing",
"selected",
"events",
"in",
"real",
"-",
"time",
".",
"You",
"can",
"filter",
"exactly",
"what",
"you",
"want",
"to",
"see",
"as",
"the",
"Clearly",
"Server",
"handles",
"all",
"tasks",
"and",
"workers",
"updates",
"being",
"sent",
"to",
"celery",
".",
"Several",
"clients",
"can",
"see",
"different",
"sets",
"of",
"events",
"at",
"the",
"same",
"time",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/client.py#L40-L92
|
10,179
|
rsalmei/clearly
|
clearly/client.py
|
ClearlyClient.tasks
|
def tasks(self, pattern=None, negate=False, state=None, limit=None, reverse=True,
params=None, success=False, error=True):
"""Filters stored tasks and displays their current statuses.
Note that, to be able to list the tasks sorted chronologically, celery retrieves
tasks from the LRU event heap instead of the dict storage, so the total number
of tasks fetched may be different than the server `max_tasks` setting. For
instance, the `limit` field refers to max events searched, not max tasks.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter tasks
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
negate (bool): if True, finds tasks that do not match criteria
state (Optional[str]): a celery task state to filter
limit (int): the maximum number of events to fetch
if None or 0, fetches all.
reverse (bool): if True (default), shows the most recent first
Display args:
params (Optional[bool]): if True shows args and kwargs in the first and
last seen states, if False never shows, and if None follows the
success and error arguments.
default is None
success (bool): if True shows successful tasks' results
default is False
error (bool): if True shows failed and retried tasks' tracebacks.
default is True, as you're monitoring to find errors, right?
"""
request = clearly_pb2.FilterTasksRequest(
tasks_filter=clearly_pb2.PatternFilter(pattern=pattern or '.',
negate=negate),
state_pattern=state or '.', limit=limit, reverse=reverse
)
for task in about_time(ClearlyClient._fetched_callback, self._stub.filter_tasks(request)):
ClearlyClient._display_task(task, params, success, error)
|
python
|
def tasks(self, pattern=None, negate=False, state=None, limit=None, reverse=True,
params=None, success=False, error=True):
"""Filters stored tasks and displays their current statuses.
Note that, to be able to list the tasks sorted chronologically, celery retrieves
tasks from the LRU event heap instead of the dict storage, so the total number
of tasks fetched may be different than the server `max_tasks` setting. For
instance, the `limit` field refers to max events searched, not max tasks.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter tasks
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
negate (bool): if True, finds tasks that do not match criteria
state (Optional[str]): a celery task state to filter
limit (int): the maximum number of events to fetch
if None or 0, fetches all.
reverse (bool): if True (default), shows the most recent first
Display args:
params (Optional[bool]): if True shows args and kwargs in the first and
last seen states, if False never shows, and if None follows the
success and error arguments.
default is None
success (bool): if True shows successful tasks' results
default is False
error (bool): if True shows failed and retried tasks' tracebacks.
default is True, as you're monitoring to find errors, right?
"""
request = clearly_pb2.FilterTasksRequest(
tasks_filter=clearly_pb2.PatternFilter(pattern=pattern or '.',
negate=negate),
state_pattern=state or '.', limit=limit, reverse=reverse
)
for task in about_time(ClearlyClient._fetched_callback, self._stub.filter_tasks(request)):
ClearlyClient._display_task(task, params, success, error)
|
[
"def",
"tasks",
"(",
"self",
",",
"pattern",
"=",
"None",
",",
"negate",
"=",
"False",
",",
"state",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"reverse",
"=",
"True",
",",
"params",
"=",
"None",
",",
"success",
"=",
"False",
",",
"error",
"=",
"True",
")",
":",
"request",
"=",
"clearly_pb2",
".",
"FilterTasksRequest",
"(",
"tasks_filter",
"=",
"clearly_pb2",
".",
"PatternFilter",
"(",
"pattern",
"=",
"pattern",
"or",
"'.'",
",",
"negate",
"=",
"negate",
")",
",",
"state_pattern",
"=",
"state",
"or",
"'.'",
",",
"limit",
"=",
"limit",
",",
"reverse",
"=",
"reverse",
")",
"for",
"task",
"in",
"about_time",
"(",
"ClearlyClient",
".",
"_fetched_callback",
",",
"self",
".",
"_stub",
".",
"filter_tasks",
"(",
"request",
")",
")",
":",
"ClearlyClient",
".",
"_display_task",
"(",
"task",
",",
"params",
",",
"success",
",",
"error",
")"
] |
Filters stored tasks and displays their current statuses.
Note that, to be able to list the tasks sorted chronologically, celery retrieves
tasks from the LRU event heap instead of the dict storage, so the total number
of tasks fetched may be different than the server `max_tasks` setting. For
instance, the `limit` field refers to max events searched, not max tasks.
Args:
Filter args:
pattern (Optional[str]): a pattern to filter tasks
ex.: '^dispatch|^email' to filter names starting with that
or 'dispatch.*123456' to filter that exact name and number
or even '123456' to filter that exact number anywhere.
negate (bool): if True, finds tasks that do not match criteria
state (Optional[str]): a celery task state to filter
limit (int): the maximum number of events to fetch
if None or 0, fetches all.
reverse (bool): if True (default), shows the most recent first
Display args:
params (Optional[bool]): if True shows args and kwargs in the first and
last seen states, if False never shows, and if None follows the
success and error arguments.
default is None
success (bool): if True shows successful tasks' results
default is False
error (bool): if True shows failed and retried tasks' tracebacks.
default is True, as you're monitoring to find errors, right?
|
[
"Filters",
"stored",
"tasks",
"and",
"displays",
"their",
"current",
"statuses",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/client.py#L118-L158
|
10,180
|
rsalmei/clearly
|
clearly/client.py
|
ClearlyClient.seen_tasks
|
def seen_tasks(self):
"""Shows a list of seen task types."""
print('\n'.join(self._stub.seen_tasks(clearly_pb2.Empty()).task_types))
|
python
|
def seen_tasks(self):
"""Shows a list of seen task types."""
print('\n'.join(self._stub.seen_tasks(clearly_pb2.Empty()).task_types))
|
[
"def",
"seen_tasks",
"(",
"self",
")",
":",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"self",
".",
"_stub",
".",
"seen_tasks",
"(",
"clearly_pb2",
".",
"Empty",
"(",
")",
")",
".",
"task_types",
")",
")"
] |
Shows a list of seen task types.
|
[
"Shows",
"a",
"list",
"of",
"seen",
"task",
"types",
"."
] |
fd784843d13f0fed28fc192565bec3668f1363f4
|
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/client.py#L197-L199
|
10,181
|
linuxlewis/channels-api
|
channels_api/decorators.py
|
detail_action
|
def detail_action(**kwargs):
"""
Used to mark a method on a ResourceBinding that should be routed for detail actions.
"""
def decorator(func):
func.action = True
func.detail = True
func.kwargs = kwargs
return func
return decorator
|
python
|
def detail_action(**kwargs):
"""
Used to mark a method on a ResourceBinding that should be routed for detail actions.
"""
def decorator(func):
func.action = True
func.detail = True
func.kwargs = kwargs
return func
return decorator
|
[
"def",
"detail_action",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"func",
".",
"action",
"=",
"True",
"func",
".",
"detail",
"=",
"True",
"func",
".",
"kwargs",
"=",
"kwargs",
"return",
"func",
"return",
"decorator"
] |
Used to mark a method on a ResourceBinding that should be routed for detail actions.
|
[
"Used",
"to",
"mark",
"a",
"method",
"on",
"a",
"ResourceBinding",
"that",
"should",
"be",
"routed",
"for",
"detail",
"actions",
"."
] |
ec2a81a1ae83606980ad5bb709bca517fdde077d
|
https://github.com/linuxlewis/channels-api/blob/ec2a81a1ae83606980ad5bb709bca517fdde077d/channels_api/decorators.py#L1-L10
|
10,182
|
linuxlewis/channels-api
|
channels_api/decorators.py
|
list_action
|
def list_action(**kwargs):
"""
Used to mark a method on a ResourceBinding that should be routed for list actions.
"""
def decorator(func):
func.action = True
func.detail = False
func.kwargs = kwargs
return func
return decorator
|
python
|
def list_action(**kwargs):
"""
Used to mark a method on a ResourceBinding that should be routed for list actions.
"""
def decorator(func):
func.action = True
func.detail = False
func.kwargs = kwargs
return func
return decorator
|
[
"def",
"list_action",
"(",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"func",
".",
"action",
"=",
"True",
"func",
".",
"detail",
"=",
"False",
"func",
".",
"kwargs",
"=",
"kwargs",
"return",
"func",
"return",
"decorator"
] |
Used to mark a method on a ResourceBinding that should be routed for list actions.
|
[
"Used",
"to",
"mark",
"a",
"method",
"on",
"a",
"ResourceBinding",
"that",
"should",
"be",
"routed",
"for",
"list",
"actions",
"."
] |
ec2a81a1ae83606980ad5bb709bca517fdde077d
|
https://github.com/linuxlewis/channels-api/blob/ec2a81a1ae83606980ad5bb709bca517fdde077d/channels_api/decorators.py#L13-L22
|
10,183
|
mattja/sdeint
|
sdeint/_broadcast.py
|
broadcast_to
|
def broadcast_to(array, shape, subok=False):
"""Broadcast an array to a new shape.
Parameters
----------
array : array_like
The array to broadcast.
shape : tuple
The shape of the desired array.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
Returns
-------
broadcast : array
A readonly view on the original array with the given shape. It is
typically not contiguous. Furthermore, more than one element of a
broadcasted array may refer to a single memory location.
Raises
------
ValueError
If the array is not compatible with the new shape according to NumPy's
broadcasting rules.
Notes
-----
.. versionadded:: 1.10.0
Examples
--------
>>> x = np.array([1, 2, 3])
>>> np.broadcast_to(x, (3, 3))
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
"""
return _broadcast_to(array, shape, subok=subok, readonly=True)
|
python
|
def broadcast_to(array, shape, subok=False):
"""Broadcast an array to a new shape.
Parameters
----------
array : array_like
The array to broadcast.
shape : tuple
The shape of the desired array.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
Returns
-------
broadcast : array
A readonly view on the original array with the given shape. It is
typically not contiguous. Furthermore, more than one element of a
broadcasted array may refer to a single memory location.
Raises
------
ValueError
If the array is not compatible with the new shape according to NumPy's
broadcasting rules.
Notes
-----
.. versionadded:: 1.10.0
Examples
--------
>>> x = np.array([1, 2, 3])
>>> np.broadcast_to(x, (3, 3))
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
"""
return _broadcast_to(array, shape, subok=subok, readonly=True)
|
[
"def",
"broadcast_to",
"(",
"array",
",",
"shape",
",",
"subok",
"=",
"False",
")",
":",
"return",
"_broadcast_to",
"(",
"array",
",",
"shape",
",",
"subok",
"=",
"subok",
",",
"readonly",
"=",
"True",
")"
] |
Broadcast an array to a new shape.
Parameters
----------
array : array_like
The array to broadcast.
shape : tuple
The shape of the desired array.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
Returns
-------
broadcast : array
A readonly view on the original array with the given shape. It is
typically not contiguous. Furthermore, more than one element of a
broadcasted array may refer to a single memory location.
Raises
------
ValueError
If the array is not compatible with the new shape according to NumPy's
broadcasting rules.
Notes
-----
.. versionadded:: 1.10.0
Examples
--------
>>> x = np.array([1, 2, 3])
>>> np.broadcast_to(x, (3, 3))
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
|
[
"Broadcast",
"an",
"array",
"to",
"a",
"new",
"shape",
"."
] |
7cf807cdf97b3bb39d29e1c2dc834b519499b601
|
https://github.com/mattja/sdeint/blob/7cf807cdf97b3bb39d29e1c2dc834b519499b601/sdeint/_broadcast.py#L70-L108
|
10,184
|
mattja/sdeint
|
sdeint/wiener.py
|
_K
|
def _K(m):
""" matrix K_m from Wiktorsson2001 """
M = m*(m - 1)//2
K = np.zeros((M, m**2), dtype=np.int64)
row = 0
for j in range(1, m):
col = (j - 1)*m + j
s = m - j
K[row:(row+s), col:(col+s)] = np.eye(s)
row += s
return K
|
python
|
def _K(m):
""" matrix K_m from Wiktorsson2001 """
M = m*(m - 1)//2
K = np.zeros((M, m**2), dtype=np.int64)
row = 0
for j in range(1, m):
col = (j - 1)*m + j
s = m - j
K[row:(row+s), col:(col+s)] = np.eye(s)
row += s
return K
|
[
"def",
"_K",
"(",
"m",
")",
":",
"M",
"=",
"m",
"*",
"(",
"m",
"-",
"1",
")",
"//",
"2",
"K",
"=",
"np",
".",
"zeros",
"(",
"(",
"M",
",",
"m",
"**",
"2",
")",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"row",
"=",
"0",
"for",
"j",
"in",
"range",
"(",
"1",
",",
"m",
")",
":",
"col",
"=",
"(",
"j",
"-",
"1",
")",
"*",
"m",
"+",
"j",
"s",
"=",
"m",
"-",
"j",
"K",
"[",
"row",
":",
"(",
"row",
"+",
"s",
")",
",",
"col",
":",
"(",
"col",
"+",
"s",
")",
"]",
"=",
"np",
".",
"eye",
"(",
"s",
")",
"row",
"+=",
"s",
"return",
"K"
] |
matrix K_m from Wiktorsson2001
|
[
"matrix",
"K_m",
"from",
"Wiktorsson2001"
] |
7cf807cdf97b3bb39d29e1c2dc834b519499b601
|
https://github.com/mattja/sdeint/blob/7cf807cdf97b3bb39d29e1c2dc834b519499b601/sdeint/wiener.py#L187-L197
|
10,185
|
riptano/ccm
|
ccmlib/cluster.py
|
Cluster.wait_for_compactions
|
def wait_for_compactions(self, timeout=600):
"""
Wait for all compactions to finish on all nodes.
"""
for node in list(self.nodes.values()):
if node.is_running():
node.wait_for_compactions(timeout)
return self
|
python
|
def wait_for_compactions(self, timeout=600):
"""
Wait for all compactions to finish on all nodes.
"""
for node in list(self.nodes.values()):
if node.is_running():
node.wait_for_compactions(timeout)
return self
|
[
"def",
"wait_for_compactions",
"(",
"self",
",",
"timeout",
"=",
"600",
")",
":",
"for",
"node",
"in",
"list",
"(",
"self",
".",
"nodes",
".",
"values",
"(",
")",
")",
":",
"if",
"node",
".",
"is_running",
"(",
")",
":",
"node",
".",
"wait_for_compactions",
"(",
"timeout",
")",
"return",
"self"
] |
Wait for all compactions to finish on all nodes.
|
[
"Wait",
"for",
"all",
"compactions",
"to",
"finish",
"on",
"all",
"nodes",
"."
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/cluster.py#L472-L479
|
10,186
|
riptano/ccm
|
ccmlib/dse_node.py
|
DseNode.watch_log_for_alive
|
def watch_log_for_alive(self, nodes, from_mark=None, timeout=720, filename='system.log'):
"""
Watch the log of this node until it detects that the provided other
nodes are marked UP. This method works similarly to watch_log_for_death.
We want to provide a higher default timeout when this is called on DSE.
"""
super(DseNode, self).watch_log_for_alive(nodes, from_mark=from_mark, timeout=timeout, filename=filename)
|
python
|
def watch_log_for_alive(self, nodes, from_mark=None, timeout=720, filename='system.log'):
"""
Watch the log of this node until it detects that the provided other
nodes are marked UP. This method works similarly to watch_log_for_death.
We want to provide a higher default timeout when this is called on DSE.
"""
super(DseNode, self).watch_log_for_alive(nodes, from_mark=from_mark, timeout=timeout, filename=filename)
|
[
"def",
"watch_log_for_alive",
"(",
"self",
",",
"nodes",
",",
"from_mark",
"=",
"None",
",",
"timeout",
"=",
"720",
",",
"filename",
"=",
"'system.log'",
")",
":",
"super",
"(",
"DseNode",
",",
"self",
")",
".",
"watch_log_for_alive",
"(",
"nodes",
",",
"from_mark",
"=",
"from_mark",
",",
"timeout",
"=",
"timeout",
",",
"filename",
"=",
"filename",
")"
] |
Watch the log of this node until it detects that the provided other
nodes are marked UP. This method works similarly to watch_log_for_death.
We want to provide a higher default timeout when this is called on DSE.
|
[
"Watch",
"the",
"log",
"of",
"this",
"node",
"until",
"it",
"detects",
"that",
"the",
"provided",
"other",
"nodes",
"are",
"marked",
"UP",
".",
"This",
"method",
"works",
"similarly",
"to",
"watch_log_for_death",
"."
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/dse_node.py#L102-L109
|
10,187
|
riptano/ccm
|
ccmlib/node.py
|
Node.load
|
def load(path, name, cluster):
"""
Load a node from from the path on disk to the config files, the node name and the
cluster the node is part of.
"""
node_path = os.path.join(path, name)
filename = os.path.join(node_path, 'node.conf')
with open(filename, 'r') as f:
data = yaml.safe_load(f)
try:
itf = data['interfaces']
initial_token = None
if 'initial_token' in data:
initial_token = data['initial_token']
cassandra_version = None
if 'cassandra_version' in data:
cassandra_version = LooseVersion(data['cassandra_version'])
remote_debug_port = 2000
if 'remote_debug_port' in data:
remote_debug_port = data['remote_debug_port']
binary_interface = None
if 'binary' in itf and itf['binary'] is not None:
binary_interface = tuple(itf['binary'])
thrift_interface = None
if 'thrift' in itf and itf['thrift'] is not None:
thrift_interface = tuple(itf['thrift'])
node = cluster.create_node(data['name'], data['auto_bootstrap'], thrift_interface, tuple(itf['storage']), data['jmx_port'], remote_debug_port, initial_token, save=False, binary_interface=binary_interface, byteman_port=data['byteman_port'], derived_cassandra_version=cassandra_version)
node.status = data['status']
if 'pid' in data:
node.pid = int(data['pid'])
if 'install_dir' in data:
node.__install_dir = data['install_dir']
if 'config_options' in data:
node.__config_options = data['config_options']
if 'dse_config_options' in data:
node._dse_config_options = data['dse_config_options']
if 'environment_variables' in data:
node.__environment_variables = data['environment_variables']
if 'data_center' in data:
node.data_center = data['data_center']
if 'workloads' in data:
node.workloads = data['workloads']
return node
except KeyError as k:
raise common.LoadError("Error Loading " + filename + ", missing property: " + str(k))
|
python
|
def load(path, name, cluster):
"""
Load a node from from the path on disk to the config files, the node name and the
cluster the node is part of.
"""
node_path = os.path.join(path, name)
filename = os.path.join(node_path, 'node.conf')
with open(filename, 'r') as f:
data = yaml.safe_load(f)
try:
itf = data['interfaces']
initial_token = None
if 'initial_token' in data:
initial_token = data['initial_token']
cassandra_version = None
if 'cassandra_version' in data:
cassandra_version = LooseVersion(data['cassandra_version'])
remote_debug_port = 2000
if 'remote_debug_port' in data:
remote_debug_port = data['remote_debug_port']
binary_interface = None
if 'binary' in itf and itf['binary'] is not None:
binary_interface = tuple(itf['binary'])
thrift_interface = None
if 'thrift' in itf and itf['thrift'] is not None:
thrift_interface = tuple(itf['thrift'])
node = cluster.create_node(data['name'], data['auto_bootstrap'], thrift_interface, tuple(itf['storage']), data['jmx_port'], remote_debug_port, initial_token, save=False, binary_interface=binary_interface, byteman_port=data['byteman_port'], derived_cassandra_version=cassandra_version)
node.status = data['status']
if 'pid' in data:
node.pid = int(data['pid'])
if 'install_dir' in data:
node.__install_dir = data['install_dir']
if 'config_options' in data:
node.__config_options = data['config_options']
if 'dse_config_options' in data:
node._dse_config_options = data['dse_config_options']
if 'environment_variables' in data:
node.__environment_variables = data['environment_variables']
if 'data_center' in data:
node.data_center = data['data_center']
if 'workloads' in data:
node.workloads = data['workloads']
return node
except KeyError as k:
raise common.LoadError("Error Loading " + filename + ", missing property: " + str(k))
|
[
"def",
"load",
"(",
"path",
",",
"name",
",",
"cluster",
")",
":",
"node_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"node_path",
",",
"'node.conf'",
")",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"data",
"=",
"yaml",
".",
"safe_load",
"(",
"f",
")",
"try",
":",
"itf",
"=",
"data",
"[",
"'interfaces'",
"]",
"initial_token",
"=",
"None",
"if",
"'initial_token'",
"in",
"data",
":",
"initial_token",
"=",
"data",
"[",
"'initial_token'",
"]",
"cassandra_version",
"=",
"None",
"if",
"'cassandra_version'",
"in",
"data",
":",
"cassandra_version",
"=",
"LooseVersion",
"(",
"data",
"[",
"'cassandra_version'",
"]",
")",
"remote_debug_port",
"=",
"2000",
"if",
"'remote_debug_port'",
"in",
"data",
":",
"remote_debug_port",
"=",
"data",
"[",
"'remote_debug_port'",
"]",
"binary_interface",
"=",
"None",
"if",
"'binary'",
"in",
"itf",
"and",
"itf",
"[",
"'binary'",
"]",
"is",
"not",
"None",
":",
"binary_interface",
"=",
"tuple",
"(",
"itf",
"[",
"'binary'",
"]",
")",
"thrift_interface",
"=",
"None",
"if",
"'thrift'",
"in",
"itf",
"and",
"itf",
"[",
"'thrift'",
"]",
"is",
"not",
"None",
":",
"thrift_interface",
"=",
"tuple",
"(",
"itf",
"[",
"'thrift'",
"]",
")",
"node",
"=",
"cluster",
".",
"create_node",
"(",
"data",
"[",
"'name'",
"]",
",",
"data",
"[",
"'auto_bootstrap'",
"]",
",",
"thrift_interface",
",",
"tuple",
"(",
"itf",
"[",
"'storage'",
"]",
")",
",",
"data",
"[",
"'jmx_port'",
"]",
",",
"remote_debug_port",
",",
"initial_token",
",",
"save",
"=",
"False",
",",
"binary_interface",
"=",
"binary_interface",
",",
"byteman_port",
"=",
"data",
"[",
"'byteman_port'",
"]",
",",
"derived_cassandra_version",
"=",
"cassandra_version",
")",
"node",
".",
"status",
"=",
"data",
"[",
"'status'",
"]",
"if",
"'pid'",
"in",
"data",
":",
"node",
".",
"pid",
"=",
"int",
"(",
"data",
"[",
"'pid'",
"]",
")",
"if",
"'install_dir'",
"in",
"data",
":",
"node",
".",
"__install_dir",
"=",
"data",
"[",
"'install_dir'",
"]",
"if",
"'config_options'",
"in",
"data",
":",
"node",
".",
"__config_options",
"=",
"data",
"[",
"'config_options'",
"]",
"if",
"'dse_config_options'",
"in",
"data",
":",
"node",
".",
"_dse_config_options",
"=",
"data",
"[",
"'dse_config_options'",
"]",
"if",
"'environment_variables'",
"in",
"data",
":",
"node",
".",
"__environment_variables",
"=",
"data",
"[",
"'environment_variables'",
"]",
"if",
"'data_center'",
"in",
"data",
":",
"node",
".",
"data_center",
"=",
"data",
"[",
"'data_center'",
"]",
"if",
"'workloads'",
"in",
"data",
":",
"node",
".",
"workloads",
"=",
"data",
"[",
"'workloads'",
"]",
"return",
"node",
"except",
"KeyError",
"as",
"k",
":",
"raise",
"common",
".",
"LoadError",
"(",
"\"Error Loading \"",
"+",
"filename",
"+",
"\", missing property: \"",
"+",
"str",
"(",
"k",
")",
")"
] |
Load a node from from the path on disk to the config files, the node name and the
cluster the node is part of.
|
[
"Load",
"a",
"node",
"from",
"from",
"the",
"path",
"on",
"disk",
"to",
"the",
"config",
"files",
"the",
"node",
"name",
"and",
"the",
"cluster",
"the",
"node",
"is",
"part",
"of",
"."
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L150-L194
|
10,188
|
riptano/ccm
|
ccmlib/node.py
|
Node.get_install_dir
|
def get_install_dir(self):
"""
Returns the path to the cassandra source directory used by this node.
"""
if self.__install_dir is None:
return self.cluster.get_install_dir()
else:
common.validate_install_dir(self.__install_dir)
return self.__install_dir
|
python
|
def get_install_dir(self):
"""
Returns the path to the cassandra source directory used by this node.
"""
if self.__install_dir is None:
return self.cluster.get_install_dir()
else:
common.validate_install_dir(self.__install_dir)
return self.__install_dir
|
[
"def",
"get_install_dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"__install_dir",
"is",
"None",
":",
"return",
"self",
".",
"cluster",
".",
"get_install_dir",
"(",
")",
"else",
":",
"common",
".",
"validate_install_dir",
"(",
"self",
".",
"__install_dir",
")",
"return",
"self",
".",
"__install_dir"
] |
Returns the path to the cassandra source directory used by this node.
|
[
"Returns",
"the",
"path",
"to",
"the",
"cassandra",
"source",
"directory",
"used",
"by",
"this",
"node",
"."
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L241-L249
|
10,189
|
riptano/ccm
|
ccmlib/node.py
|
Node.set_install_dir
|
def set_install_dir(self, install_dir=None, version=None, verbose=False):
"""
Sets the path to the cassandra source directory for use by this node.
"""
if version is None:
self.__install_dir = install_dir
if install_dir is not None:
common.validate_install_dir(install_dir)
else:
self.__install_dir = self.node_setup(version, verbose=verbose)
self._cassandra_version = common.get_version_from_build(self.__install_dir, cassandra=True)
if self.get_base_cassandra_version() >= 4.0:
self.network_interfaces['thrift'] = None
self.import_config_files()
self.import_bin_files()
self.__conf_updated = False
return self
|
python
|
def set_install_dir(self, install_dir=None, version=None, verbose=False):
"""
Sets the path to the cassandra source directory for use by this node.
"""
if version is None:
self.__install_dir = install_dir
if install_dir is not None:
common.validate_install_dir(install_dir)
else:
self.__install_dir = self.node_setup(version, verbose=verbose)
self._cassandra_version = common.get_version_from_build(self.__install_dir, cassandra=True)
if self.get_base_cassandra_version() >= 4.0:
self.network_interfaces['thrift'] = None
self.import_config_files()
self.import_bin_files()
self.__conf_updated = False
return self
|
[
"def",
"set_install_dir",
"(",
"self",
",",
"install_dir",
"=",
"None",
",",
"version",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"version",
"is",
"None",
":",
"self",
".",
"__install_dir",
"=",
"install_dir",
"if",
"install_dir",
"is",
"not",
"None",
":",
"common",
".",
"validate_install_dir",
"(",
"install_dir",
")",
"else",
":",
"self",
".",
"__install_dir",
"=",
"self",
".",
"node_setup",
"(",
"version",
",",
"verbose",
"=",
"verbose",
")",
"self",
".",
"_cassandra_version",
"=",
"common",
".",
"get_version_from_build",
"(",
"self",
".",
"__install_dir",
",",
"cassandra",
"=",
"True",
")",
"if",
"self",
".",
"get_base_cassandra_version",
"(",
")",
">=",
"4.0",
":",
"self",
".",
"network_interfaces",
"[",
"'thrift'",
"]",
"=",
"None",
"self",
".",
"import_config_files",
"(",
")",
"self",
".",
"import_bin_files",
"(",
")",
"self",
".",
"__conf_updated",
"=",
"False",
"return",
"self"
] |
Sets the path to the cassandra source directory for use by this node.
|
[
"Sets",
"the",
"path",
"to",
"the",
"cassandra",
"source",
"directory",
"for",
"use",
"by",
"this",
"node",
"."
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L255-L274
|
10,190
|
riptano/ccm
|
ccmlib/node.py
|
Node.show
|
def show(self, only_status=False, show_cluster=True):
"""
Print infos on this node configuration.
"""
self.__update_status()
indent = ''.join([" " for i in xrange(0, len(self.name) + 2)])
print_("{}: {}".format(self.name, self.__get_status_string()))
if not only_status:
if show_cluster:
print_("{}{}={}".format(indent, 'cluster', self.cluster.name))
print_("{}{}={}".format(indent, 'auto_bootstrap', self.auto_bootstrap))
if self.network_interfaces['thrift'] is not None:
print_("{}{}={}".format(indent, 'thrift', self.network_interfaces['thrift']))
if self.network_interfaces['binary'] is not None:
print_("{}{}={}".format(indent, 'binary', self.network_interfaces['binary']))
print_("{}{}={}".format(indent, 'storage', self.network_interfaces['storage']))
print_("{}{}={}".format(indent, 'jmx_port', self.jmx_port))
print_("{}{}={}".format(indent, 'remote_debug_port', self.remote_debug_port))
print_("{}{}={}".format(indent, 'byteman_port', self.byteman_port))
print_("{}{}={}".format(indent, 'initial_token', self.initial_token))
if self.pid:
print_("{}{}={}".format(indent, 'pid', self.pid))
|
python
|
def show(self, only_status=False, show_cluster=True):
"""
Print infos on this node configuration.
"""
self.__update_status()
indent = ''.join([" " for i in xrange(0, len(self.name) + 2)])
print_("{}: {}".format(self.name, self.__get_status_string()))
if not only_status:
if show_cluster:
print_("{}{}={}".format(indent, 'cluster', self.cluster.name))
print_("{}{}={}".format(indent, 'auto_bootstrap', self.auto_bootstrap))
if self.network_interfaces['thrift'] is not None:
print_("{}{}={}".format(indent, 'thrift', self.network_interfaces['thrift']))
if self.network_interfaces['binary'] is not None:
print_("{}{}={}".format(indent, 'binary', self.network_interfaces['binary']))
print_("{}{}={}".format(indent, 'storage', self.network_interfaces['storage']))
print_("{}{}={}".format(indent, 'jmx_port', self.jmx_port))
print_("{}{}={}".format(indent, 'remote_debug_port', self.remote_debug_port))
print_("{}{}={}".format(indent, 'byteman_port', self.byteman_port))
print_("{}{}={}".format(indent, 'initial_token', self.initial_token))
if self.pid:
print_("{}{}={}".format(indent, 'pid', self.pid))
|
[
"def",
"show",
"(",
"self",
",",
"only_status",
"=",
"False",
",",
"show_cluster",
"=",
"True",
")",
":",
"self",
".",
"__update_status",
"(",
")",
"indent",
"=",
"''",
".",
"join",
"(",
"[",
"\" \"",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"self",
".",
"name",
")",
"+",
"2",
")",
"]",
")",
"print_",
"(",
"\"{}: {}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"__get_status_string",
"(",
")",
")",
")",
"if",
"not",
"only_status",
":",
"if",
"show_cluster",
":",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'cluster'",
",",
"self",
".",
"cluster",
".",
"name",
")",
")",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'auto_bootstrap'",
",",
"self",
".",
"auto_bootstrap",
")",
")",
"if",
"self",
".",
"network_interfaces",
"[",
"'thrift'",
"]",
"is",
"not",
"None",
":",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'thrift'",
",",
"self",
".",
"network_interfaces",
"[",
"'thrift'",
"]",
")",
")",
"if",
"self",
".",
"network_interfaces",
"[",
"'binary'",
"]",
"is",
"not",
"None",
":",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'binary'",
",",
"self",
".",
"network_interfaces",
"[",
"'binary'",
"]",
")",
")",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'storage'",
",",
"self",
".",
"network_interfaces",
"[",
"'storage'",
"]",
")",
")",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'jmx_port'",
",",
"self",
".",
"jmx_port",
")",
")",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'remote_debug_port'",
",",
"self",
".",
"remote_debug_port",
")",
")",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'byteman_port'",
",",
"self",
".",
"byteman_port",
")",
")",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'initial_token'",
",",
"self",
".",
"initial_token",
")",
")",
"if",
"self",
".",
"pid",
":",
"print_",
"(",
"\"{}{}={}\"",
".",
"format",
"(",
"indent",
",",
"'pid'",
",",
"self",
".",
"pid",
")",
")"
] |
Print infos on this node configuration.
|
[
"Print",
"infos",
"on",
"this",
"node",
"configuration",
"."
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L329-L350
|
10,191
|
riptano/ccm
|
ccmlib/node.py
|
Node.is_running
|
def is_running(self):
"""
Return true if the node is running
"""
self.__update_status()
return self.status == Status.UP or self.status == Status.DECOMMISSIONED
|
python
|
def is_running(self):
"""
Return true if the node is running
"""
self.__update_status()
return self.status == Status.UP or self.status == Status.DECOMMISSIONED
|
[
"def",
"is_running",
"(",
"self",
")",
":",
"self",
".",
"__update_status",
"(",
")",
"return",
"self",
".",
"status",
"==",
"Status",
".",
"UP",
"or",
"self",
".",
"status",
"==",
"Status",
".",
"DECOMMISSIONED"
] |
Return true if the node is running
|
[
"Return",
"true",
"if",
"the",
"node",
"is",
"running"
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L352-L357
|
10,192
|
riptano/ccm
|
ccmlib/node.py
|
Node.grep_log
|
def grep_log(self, expr, filename='system.log', from_mark=None):
"""
Returns a list of lines matching the regular expression in parameter
in the Cassandra log of this node
"""
matchings = []
pattern = re.compile(expr)
with open(os.path.join(self.get_path(), 'logs', filename)) as f:
if from_mark:
f.seek(from_mark)
for line in f:
m = pattern.search(line)
if m:
matchings.append((line, m))
return matchings
|
python
|
def grep_log(self, expr, filename='system.log', from_mark=None):
"""
Returns a list of lines matching the regular expression in parameter
in the Cassandra log of this node
"""
matchings = []
pattern = re.compile(expr)
with open(os.path.join(self.get_path(), 'logs', filename)) as f:
if from_mark:
f.seek(from_mark)
for line in f:
m = pattern.search(line)
if m:
matchings.append((line, m))
return matchings
|
[
"def",
"grep_log",
"(",
"self",
",",
"expr",
",",
"filename",
"=",
"'system.log'",
",",
"from_mark",
"=",
"None",
")",
":",
"matchings",
"=",
"[",
"]",
"pattern",
"=",
"re",
".",
"compile",
"(",
"expr",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"get_path",
"(",
")",
",",
"'logs'",
",",
"filename",
")",
")",
"as",
"f",
":",
"if",
"from_mark",
":",
"f",
".",
"seek",
"(",
"from_mark",
")",
"for",
"line",
"in",
"f",
":",
"m",
"=",
"pattern",
".",
"search",
"(",
"line",
")",
"if",
"m",
":",
"matchings",
".",
"append",
"(",
"(",
"line",
",",
"m",
")",
")",
"return",
"matchings"
] |
Returns a list of lines matching the regular expression in parameter
in the Cassandra log of this node
|
[
"Returns",
"a",
"list",
"of",
"lines",
"matching",
"the",
"regular",
"expression",
"in",
"parameter",
"in",
"the",
"Cassandra",
"log",
"of",
"this",
"node"
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L387-L401
|
10,193
|
riptano/ccm
|
ccmlib/node.py
|
Node.wait_for_binary_interface
|
def wait_for_binary_interface(self, **kwargs):
"""
Waits for the Binary CQL interface to be listening. If > 1.2 will check
log for 'Starting listening for CQL clients' before checking for the
interface to be listening.
Emits a warning if not listening after 30 seconds.
"""
if self.cluster.version() >= '1.2':
self.watch_log_for("Starting listening for CQL clients", **kwargs)
binary_itf = self.network_interfaces['binary']
if not common.check_socket_listening(binary_itf, timeout=30):
warnings.warn("Binary interface %s:%s is not listening after 30 seconds, node may have failed to start."
% (binary_itf[0], binary_itf[1]))
|
python
|
def wait_for_binary_interface(self, **kwargs):
"""
Waits for the Binary CQL interface to be listening. If > 1.2 will check
log for 'Starting listening for CQL clients' before checking for the
interface to be listening.
Emits a warning if not listening after 30 seconds.
"""
if self.cluster.version() >= '1.2':
self.watch_log_for("Starting listening for CQL clients", **kwargs)
binary_itf = self.network_interfaces['binary']
if not common.check_socket_listening(binary_itf, timeout=30):
warnings.warn("Binary interface %s:%s is not listening after 30 seconds, node may have failed to start."
% (binary_itf[0], binary_itf[1]))
|
[
"def",
"wait_for_binary_interface",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"cluster",
".",
"version",
"(",
")",
">=",
"'1.2'",
":",
"self",
".",
"watch_log_for",
"(",
"\"Starting listening for CQL clients\"",
",",
"*",
"*",
"kwargs",
")",
"binary_itf",
"=",
"self",
".",
"network_interfaces",
"[",
"'binary'",
"]",
"if",
"not",
"common",
".",
"check_socket_listening",
"(",
"binary_itf",
",",
"timeout",
"=",
"30",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Binary interface %s:%s is not listening after 30 seconds, node may have failed to start.\"",
"%",
"(",
"binary_itf",
"[",
"0",
"]",
",",
"binary_itf",
"[",
"1",
"]",
")",
")"
] |
Waits for the Binary CQL interface to be listening. If > 1.2 will check
log for 'Starting listening for CQL clients' before checking for the
interface to be listening.
Emits a warning if not listening after 30 seconds.
|
[
"Waits",
"for",
"the",
"Binary",
"CQL",
"interface",
"to",
"be",
"listening",
".",
"If",
">",
"1",
".",
"2",
"will",
"check",
"log",
"for",
"Starting",
"listening",
"for",
"CQL",
"clients",
"before",
"checking",
"for",
"the",
"interface",
"to",
"be",
"listening",
"."
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L544-L558
|
10,194
|
riptano/ccm
|
ccmlib/node.py
|
Node.wait_for_thrift_interface
|
def wait_for_thrift_interface(self, **kwargs):
"""
Waits for the Thrift interface to be listening.
Emits a warning if not listening after 30 seconds.
"""
if self.cluster.version() >= '4':
return;
self.watch_log_for("Listening for thrift clients...", **kwargs)
thrift_itf = self.network_interfaces['thrift']
if not common.check_socket_listening(thrift_itf, timeout=30):
warnings.warn("Thrift interface {}:{} is not listening after 30 seconds, node may have failed to start.".format(thrift_itf[0], thrift_itf[1]))
|
python
|
def wait_for_thrift_interface(self, **kwargs):
"""
Waits for the Thrift interface to be listening.
Emits a warning if not listening after 30 seconds.
"""
if self.cluster.version() >= '4':
return;
self.watch_log_for("Listening for thrift clients...", **kwargs)
thrift_itf = self.network_interfaces['thrift']
if not common.check_socket_listening(thrift_itf, timeout=30):
warnings.warn("Thrift interface {}:{} is not listening after 30 seconds, node may have failed to start.".format(thrift_itf[0], thrift_itf[1]))
|
[
"def",
"wait_for_thrift_interface",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"cluster",
".",
"version",
"(",
")",
">=",
"'4'",
":",
"return",
"self",
".",
"watch_log_for",
"(",
"\"Listening for thrift clients...\"",
",",
"*",
"*",
"kwargs",
")",
"thrift_itf",
"=",
"self",
".",
"network_interfaces",
"[",
"'thrift'",
"]",
"if",
"not",
"common",
".",
"check_socket_listening",
"(",
"thrift_itf",
",",
"timeout",
"=",
"30",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Thrift interface {}:{} is not listening after 30 seconds, node may have failed to start.\"",
".",
"format",
"(",
"thrift_itf",
"[",
"0",
"]",
",",
"thrift_itf",
"[",
"1",
"]",
")",
")"
] |
Waits for the Thrift interface to be listening.
Emits a warning if not listening after 30 seconds.
|
[
"Waits",
"for",
"the",
"Thrift",
"interface",
"to",
"be",
"listening",
"."
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L560-L573
|
10,195
|
riptano/ccm
|
ccmlib/node.py
|
Node.wait_for_compactions
|
def wait_for_compactions(self, timeout=120):
"""
Wait for all compactions to finish on this node.
"""
pattern = re.compile("pending tasks: 0")
start = time.time()
while time.time() - start < timeout:
output, err, rc = self.nodetool("compactionstats")
if pattern.search(output):
return
time.sleep(1)
raise TimeoutError("{} [{}] Compactions did not finish in {} seconds".format(time.strftime("%d %b %Y %H:%M:%S", time.gmtime()), self.name, timeout))
|
python
|
def wait_for_compactions(self, timeout=120):
"""
Wait for all compactions to finish on this node.
"""
pattern = re.compile("pending tasks: 0")
start = time.time()
while time.time() - start < timeout:
output, err, rc = self.nodetool("compactionstats")
if pattern.search(output):
return
time.sleep(1)
raise TimeoutError("{} [{}] Compactions did not finish in {} seconds".format(time.strftime("%d %b %Y %H:%M:%S", time.gmtime()), self.name, timeout))
|
[
"def",
"wait_for_compactions",
"(",
"self",
",",
"timeout",
"=",
"120",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"\"pending tasks: 0\"",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"while",
"time",
".",
"time",
"(",
")",
"-",
"start",
"<",
"timeout",
":",
"output",
",",
"err",
",",
"rc",
"=",
"self",
".",
"nodetool",
"(",
"\"compactionstats\"",
")",
"if",
"pattern",
".",
"search",
"(",
"output",
")",
":",
"return",
"time",
".",
"sleep",
"(",
"1",
")",
"raise",
"TimeoutError",
"(",
"\"{} [{}] Compactions did not finish in {} seconds\"",
".",
"format",
"(",
"time",
".",
"strftime",
"(",
"\"%d %b %Y %H:%M:%S\"",
",",
"time",
".",
"gmtime",
"(",
")",
")",
",",
"self",
".",
"name",
",",
"timeout",
")",
")"
] |
Wait for all compactions to finish on this node.
|
[
"Wait",
"for",
"all",
"compactions",
"to",
"finish",
"on",
"this",
"node",
"."
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L804-L815
|
10,196
|
riptano/ccm
|
ccmlib/node.py
|
Node.update_startup_byteman_script
|
def update_startup_byteman_script(self, byteman_startup_script):
"""
Update the byteman startup script, i.e., rule injected before the node starts.
:param byteman_startup_script: the relative path to the script
:raise common.LoadError: if the node does not have byteman installed
"""
if self.byteman_port == '0':
raise common.LoadError('Byteman is not installed')
self.byteman_startup_script = byteman_startup_script
self.import_config_files()
|
python
|
def update_startup_byteman_script(self, byteman_startup_script):
"""
Update the byteman startup script, i.e., rule injected before the node starts.
:param byteman_startup_script: the relative path to the script
:raise common.LoadError: if the node does not have byteman installed
"""
if self.byteman_port == '0':
raise common.LoadError('Byteman is not installed')
self.byteman_startup_script = byteman_startup_script
self.import_config_files()
|
[
"def",
"update_startup_byteman_script",
"(",
"self",
",",
"byteman_startup_script",
")",
":",
"if",
"self",
".",
"byteman_port",
"==",
"'0'",
":",
"raise",
"common",
".",
"LoadError",
"(",
"'Byteman is not installed'",
")",
"self",
".",
"byteman_startup_script",
"=",
"byteman_startup_script",
"self",
".",
"import_config_files",
"(",
")"
] |
Update the byteman startup script, i.e., rule injected before the node starts.
:param byteman_startup_script: the relative path to the script
:raise common.LoadError: if the node does not have byteman installed
|
[
"Update",
"the",
"byteman",
"startup",
"script",
"i",
".",
"e",
".",
"rule",
"injected",
"before",
"the",
"node",
"starts",
"."
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L953-L963
|
10,197
|
riptano/ccm
|
ccmlib/node.py
|
Node._find_cmd
|
def _find_cmd(self, cmd):
"""
Locates command under cassandra root and fixes permissions if needed
"""
cdir = self.get_install_cassandra_root()
if self.get_base_cassandra_version() >= 2.1:
fcmd = common.join_bin(cdir, os.path.join('tools', 'bin'), cmd)
else:
fcmd = common.join_bin(cdir, 'bin', cmd)
try:
if os.path.exists(fcmd):
os.chmod(fcmd, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
except:
common.warning("Couldn't change permissions to use {0}.".format(cmd))
common.warning("If it didn't work, you will have to do so manually.")
return fcmd
|
python
|
def _find_cmd(self, cmd):
"""
Locates command under cassandra root and fixes permissions if needed
"""
cdir = self.get_install_cassandra_root()
if self.get_base_cassandra_version() >= 2.1:
fcmd = common.join_bin(cdir, os.path.join('tools', 'bin'), cmd)
else:
fcmd = common.join_bin(cdir, 'bin', cmd)
try:
if os.path.exists(fcmd):
os.chmod(fcmd, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
except:
common.warning("Couldn't change permissions to use {0}.".format(cmd))
common.warning("If it didn't work, you will have to do so manually.")
return fcmd
|
[
"def",
"_find_cmd",
"(",
"self",
",",
"cmd",
")",
":",
"cdir",
"=",
"self",
".",
"get_install_cassandra_root",
"(",
")",
"if",
"self",
".",
"get_base_cassandra_version",
"(",
")",
">=",
"2.1",
":",
"fcmd",
"=",
"common",
".",
"join_bin",
"(",
"cdir",
",",
"os",
".",
"path",
".",
"join",
"(",
"'tools'",
",",
"'bin'",
")",
",",
"cmd",
")",
"else",
":",
"fcmd",
"=",
"common",
".",
"join_bin",
"(",
"cdir",
",",
"'bin'",
",",
"cmd",
")",
"try",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fcmd",
")",
":",
"os",
".",
"chmod",
"(",
"fcmd",
",",
"stat",
".",
"S_IRUSR",
"|",
"stat",
".",
"S_IWUSR",
"|",
"stat",
".",
"S_IXUSR",
"|",
"stat",
".",
"S_IRGRP",
"|",
"stat",
".",
"S_IXGRP",
"|",
"stat",
".",
"S_IROTH",
"|",
"stat",
".",
"S_IXOTH",
")",
"except",
":",
"common",
".",
"warning",
"(",
"\"Couldn't change permissions to use {0}.\"",
".",
"format",
"(",
"cmd",
")",
")",
"common",
".",
"warning",
"(",
"\"If it didn't work, you will have to do so manually.\"",
")",
"return",
"fcmd"
] |
Locates command under cassandra root and fixes permissions if needed
|
[
"Locates",
"command",
"under",
"cassandra",
"root",
"and",
"fixes",
"permissions",
"if",
"needed"
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L1209-L1224
|
10,198
|
riptano/ccm
|
ccmlib/node.py
|
Node.data_size
|
def data_size(self, live_data=None):
"""Uses `nodetool info` to get the size of a node's data in KB."""
if live_data is not None:
warnings.warn("The 'live_data' keyword argument is deprecated.",
DeprecationWarning)
output = self.nodetool('info')[0]
return _get_load_from_info_output(output)
|
python
|
def data_size(self, live_data=None):
"""Uses `nodetool info` to get the size of a node's data in KB."""
if live_data is not None:
warnings.warn("The 'live_data' keyword argument is deprecated.",
DeprecationWarning)
output = self.nodetool('info')[0]
return _get_load_from_info_output(output)
|
[
"def",
"data_size",
"(",
"self",
",",
"live_data",
"=",
"None",
")",
":",
"if",
"live_data",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"The 'live_data' keyword argument is deprecated.\"",
",",
"DeprecationWarning",
")",
"output",
"=",
"self",
".",
"nodetool",
"(",
"'info'",
")",
"[",
"0",
"]",
"return",
"_get_load_from_info_output",
"(",
"output",
")"
] |
Uses `nodetool info` to get the size of a node's data in KB.
|
[
"Uses",
"nodetool",
"info",
"to",
"get",
"the",
"size",
"of",
"a",
"node",
"s",
"data",
"in",
"KB",
"."
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L1338-L1344
|
10,199
|
riptano/ccm
|
ccmlib/node.py
|
Node.get_sstable_data_files
|
def get_sstable_data_files(self, ks, table):
"""
Read sstable data files by using sstableutil, so we ignore temporary files
"""
p = self.get_sstable_data_files_process(ks=ks, table=table)
out, _, _ = handle_external_tool_process(p, ["sstableutil", '--type', 'final', ks, table])
return sorted(filter(lambda s: s.endswith('-Data.db'), out.splitlines()))
|
python
|
def get_sstable_data_files(self, ks, table):
"""
Read sstable data files by using sstableutil, so we ignore temporary files
"""
p = self.get_sstable_data_files_process(ks=ks, table=table)
out, _, _ = handle_external_tool_process(p, ["sstableutil", '--type', 'final', ks, table])
return sorted(filter(lambda s: s.endswith('-Data.db'), out.splitlines()))
|
[
"def",
"get_sstable_data_files",
"(",
"self",
",",
"ks",
",",
"table",
")",
":",
"p",
"=",
"self",
".",
"get_sstable_data_files_process",
"(",
"ks",
"=",
"ks",
",",
"table",
"=",
"table",
")",
"out",
",",
"_",
",",
"_",
"=",
"handle_external_tool_process",
"(",
"p",
",",
"[",
"\"sstableutil\"",
",",
"'--type'",
",",
"'final'",
",",
"ks",
",",
"table",
"]",
")",
"return",
"sorted",
"(",
"filter",
"(",
"lambda",
"s",
":",
"s",
".",
"endswith",
"(",
"'-Data.db'",
")",
",",
"out",
".",
"splitlines",
"(",
")",
")",
")"
] |
Read sstable data files by using sstableutil, so we ignore temporary files
|
[
"Read",
"sstable",
"data",
"files",
"by",
"using",
"sstableutil",
"so",
"we",
"ignore",
"temporary",
"files"
] |
275699f79d102b5039b79cc17fa6305dccf18412
|
https://github.com/riptano/ccm/blob/275699f79d102b5039b79cc17fa6305dccf18412/ccmlib/node.py#L2005-L2013
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.