repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
henzk/ape | ape/container_mode/utils.py | get_features_from_equation | def get_features_from_equation(container_dir, product_name):
"""
Takes the container dir and the product name and returns the list of features.
:param container_dir: path of the container dir
:param product_name: name of the product
:return: list of strings, each representing one feature
"""
import featuremonkey
file_path = os.path.join(container_dir, 'products', product_name, 'product.equation')
return featuremonkey.get_features_from_equation_file(file_path) | python | def get_features_from_equation(container_dir, product_name):
"""
Takes the container dir and the product name and returns the list of features.
:param container_dir: path of the container dir
:param product_name: name of the product
:return: list of strings, each representing one feature
"""
import featuremonkey
file_path = os.path.join(container_dir, 'products', product_name, 'product.equation')
return featuremonkey.get_features_from_equation_file(file_path) | [
"def",
"get_features_from_equation",
"(",
"container_dir",
",",
"product_name",
")",
":",
"import",
"featuremonkey",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"container_dir",
",",
"'products'",
",",
"product_name",
",",
"'product.equation'",
")",
"re... | Takes the container dir and the product name and returns the list of features.
:param container_dir: path of the container dir
:param product_name: name of the product
:return: list of strings, each representing one feature | [
"Takes",
"the",
"container",
"dir",
"and",
"the",
"product",
"name",
"and",
"returns",
"the",
"list",
"of",
"features",
".",
":",
"param",
"container_dir",
":",
"path",
"of",
"the",
"container",
"dir",
":",
"param",
"product_name",
":",
"name",
"of",
"the"... | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/container_mode/utils.py#L53-L62 |
henzk/ape | ape/container_mode/utils.py | get_feature_ide_paths | def get_feature_ide_paths(container_dir, product_name):
"""
Takes the container_dir and the product name and returns all relevant paths from the
feature_order_json to the config_file_path.
:param container_dir: the full path of the container dir
:param product_name: the name of the product
:return: object with divert path attributes
"""
repo_name = get_repo_name(container_dir)
class Paths(object):
feature_order_json = os.path.join(container_dir, '_lib/featuremodel/productline/feature_order.json')
model_xml_path = os.path.join(container_dir, '_lib/featuremodel/productline/model.xml')
config_file_path = os.path.join(container_dir, '_lib/featuremodel/productline/products/', repo_name, product_name, 'product.equation.config')
equation_file_path = os.path.join(container_dir, 'products', product_name, 'product.equation')
product_spec_path = os.path.join(container_dir, '_lib/featuremodel/productline/products/', repo_name, 'product_spec.json')
return Paths | python | def get_feature_ide_paths(container_dir, product_name):
"""
Takes the container_dir and the product name and returns all relevant paths from the
feature_order_json to the config_file_path.
:param container_dir: the full path of the container dir
:param product_name: the name of the product
:return: object with divert path attributes
"""
repo_name = get_repo_name(container_dir)
class Paths(object):
feature_order_json = os.path.join(container_dir, '_lib/featuremodel/productline/feature_order.json')
model_xml_path = os.path.join(container_dir, '_lib/featuremodel/productline/model.xml')
config_file_path = os.path.join(container_dir, '_lib/featuremodel/productline/products/', repo_name, product_name, 'product.equation.config')
equation_file_path = os.path.join(container_dir, 'products', product_name, 'product.equation')
product_spec_path = os.path.join(container_dir, '_lib/featuremodel/productline/products/', repo_name, 'product_spec.json')
return Paths | [
"def",
"get_feature_ide_paths",
"(",
"container_dir",
",",
"product_name",
")",
":",
"repo_name",
"=",
"get_repo_name",
"(",
"container_dir",
")",
"class",
"Paths",
"(",
"object",
")",
":",
"feature_order_json",
"=",
"os",
".",
"path",
".",
"join",
"(",
"conta... | Takes the container_dir and the product name and returns all relevant paths from the
feature_order_json to the config_file_path.
:param container_dir: the full path of the container dir
:param product_name: the name of the product
:return: object with divert path attributes | [
"Takes",
"the",
"container_dir",
"and",
"the",
"product",
"name",
"and",
"returns",
"all",
"relevant",
"paths",
"from",
"the",
"feature_order_json",
"to",
"the",
"config_file_path",
".",
":",
"param",
"container_dir",
":",
"the",
"full",
"path",
"of",
"the",
"... | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/container_mode/utils.py#L65-L82 |
Datary/scrapbag | scrapbag/geo/google.py | index_get | def index_get(array, *argv):
"""
checks if a index is available in the array and returns it
:param array: the data array
:param argv: index integers
:return: None if not available or the return value
"""
try:
for index in argv:
array = array[index]
return array
# there is either no info available or no popular times
# TypeError: rating/rating_n/populartimes wrong of not available
except (IndexError, TypeError):
return None | python | def index_get(array, *argv):
"""
checks if a index is available in the array and returns it
:param array: the data array
:param argv: index integers
:return: None if not available or the return value
"""
try:
for index in argv:
array = array[index]
return array
# there is either no info available or no popular times
# TypeError: rating/rating_n/populartimes wrong of not available
except (IndexError, TypeError):
return None | [
"def",
"index_get",
"(",
"array",
",",
"*",
"argv",
")",
":",
"try",
":",
"for",
"index",
"in",
"argv",
":",
"array",
"=",
"array",
"[",
"index",
"]",
"return",
"array",
"# there is either no info available or no popular times",
"# TypeError: rating/rating_n/popular... | checks if a index is available in the array and returns it
:param array: the data array
:param argv: index integers
:return: None if not available or the return value | [
"checks",
"if",
"a",
"index",
"is",
"available",
"in",
"the",
"array",
"and",
"returns",
"it",
":",
"param",
"array",
":",
"the",
"data",
"array",
":",
"param",
"argv",
":",
"index",
"integers",
":",
"return",
":",
"None",
"if",
"not",
"available",
"or... | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/geo/google.py#L70-L88 |
Datary/scrapbag | scrapbag/geo/google.py | add_optional_parameters | def add_optional_parameters(detail_json, detail, rating, rating_n, popularity, current_popularity, time_spent):
"""
check for optional return parameters and add them to the result json
:param detail_json:
:param detail:
:param rating:
:param rating_n:
:param popularity:
:param current_popularity:
:param time_spent:
:return:
"""
if rating is not None:
detail_json["rating"] = rating
elif "rating" in detail:
detail_json["rating"] = detail["rating"]
if rating_n is not None:
detail_json["rating_n"] = rating_n
if "international_phone_number" in detail:
detail_json["international_phone_number"] = detail["international_phone_number"]
if current_popularity is not None:
detail_json["current_popularity"] = current_popularity
if popularity is not None:
popularity, wait_times = get_popularity_for_day(popularity)
detail_json["populartimes"] = popularity
detail_json["time_wait"] = wait_times
if time_spent is not None:
detail_json["time_spent"] = time_spent
return detail_json | python | def add_optional_parameters(detail_json, detail, rating, rating_n, popularity, current_popularity, time_spent):
"""
check for optional return parameters and add them to the result json
:param detail_json:
:param detail:
:param rating:
:param rating_n:
:param popularity:
:param current_popularity:
:param time_spent:
:return:
"""
if rating is not None:
detail_json["rating"] = rating
elif "rating" in detail:
detail_json["rating"] = detail["rating"]
if rating_n is not None:
detail_json["rating_n"] = rating_n
if "international_phone_number" in detail:
detail_json["international_phone_number"] = detail["international_phone_number"]
if current_popularity is not None:
detail_json["current_popularity"] = current_popularity
if popularity is not None:
popularity, wait_times = get_popularity_for_day(popularity)
detail_json["populartimes"] = popularity
detail_json["time_wait"] = wait_times
if time_spent is not None:
detail_json["time_spent"] = time_spent
return detail_json | [
"def",
"add_optional_parameters",
"(",
"detail_json",
",",
"detail",
",",
"rating",
",",
"rating_n",
",",
"popularity",
",",
"current_popularity",
",",
"time_spent",
")",
":",
"if",
"rating",
"is",
"not",
"None",
":",
"detail_json",
"[",
"\"rating\"",
"]",
"="... | check for optional return parameters and add them to the result json
:param detail_json:
:param detail:
:param rating:
:param rating_n:
:param popularity:
:param current_popularity:
:param time_spent:
:return: | [
"check",
"for",
"optional",
"return",
"parameters",
"and",
"add",
"them",
"to",
"the",
"result",
"json",
":",
"param",
"detail_json",
":",
":",
"param",
"detail",
":",
":",
"param",
"rating",
":",
":",
"param",
"rating_n",
":",
":",
"param",
"popularity",
... | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/geo/google.py#L91-L127 |
Datary/scrapbag | scrapbag/geo/google.py | get_populartimes_from_search | def get_populartimes_from_search(place_identifier, user_agent=default_user_agent, **kwargs):
"""
request information for a place and parse current popularity
:param place_identifier: name and address string
:return:
"""
params_url = {
"tbm": "map",
"tch": 1,
"q": urllib.parse.quote_plus(place_identifier),
"pb": "!4m12!1m3!1d4005.9771522653964!2d-122.42072974863942!3d37.8077459796541!2m3!1f0!2f0!3f0!3m2!1i1125!2i976"
"!4f13.1!7i20!10b1!12m6!2m3!5m1!6e2!20e3!10b1!16b1!19m3!2m2!1i392!2i106!20m61!2m2!1i203!2i100!3m2!2i4!5b1"
"!6m6!1m2!1i86!2i86!1m2!1i408!2i200!7m46!1m3!1e1!2b0!3e3!1m3!1e2!2b1!3e2!1m3!1e2!2b0!3e3!1m3!1e3!2b0!3e3!"
"1m3!1e4!2b0!3e3!1m3!1e8!2b0!3e3!1m3!1e3!2b1!3e2!1m3!1e9!2b1!3e2!1m3!1e10!2b0!3e3!1m3!1e10!2b1!3e2!1m3!1e"
"10!2b0!3e4!2b1!4b1!9b0!22m6!1sa9fVWea_MsX8adX8j8AE%3A1!2zMWk6Mix0OjExODg3LGU6MSxwOmE5ZlZXZWFfTXNYOGFkWDh"
"qOEFFOjE!7e81!12e3!17sa9fVWea_MsX8adX8j8AE%3A564!18e15!24m15!2b1!5m4!2b1!3b1!5b1!6b1!10m1!8e3!17b1!24b1!"
"25b1!26b1!30m1!2b1!36b1!26m3!2m2!1i80!2i92!30m28!1m6!1m2!1i0!2i0!2m2!1i458!2i976!1m6!1m2!1i1075!2i0!2m2!"
"1i1125!2i976!1m6!1m2!1i0!2i0!2m2!1i1125!2i20!1m6!1m2!1i0!2i956!2m2!1i1125!2i976!37m1!1e81!42b1!47m0!49m1"
"!3b1"
}
search_url = "https://www.google.es/search?" + "&".join(k + "=" + str(v) for k, v in params_url.items())
logging.info("searchterm: " + search_url)
# noinspection PyUnresolvedReferences
gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
resp = urllib.request.urlopen(
urllib.request.Request(
url=search_url,
data=None,
headers=user_agent),
context=gcontext)
data = resp.read().decode('utf-8').split('/*""*/')[0]
# find eof json
jend = data.rfind("}")
if jend >= 0:
data = data[:jend + 1]
jdata = json.loads(data)["d"]
jdata = json.loads(jdata[4:])
# get info from result array, has to be adapted if backend api changes
info = index_get(jdata, 0, 1, 0, 14)
rating = index_get(info, 4, 7)
rating_n = index_get(info, 4, 8)
popular_times = index_get(info, 84, 0)
# current_popularity is also not available if popular_times isn't
current_popularity = index_get(info, 84, 7, 1)
time_spent = index_get(info, 117, 0)
# extract numbers from time string
if time_spent is not None:
time_spent = time_spent.replace("\xa0", " ")
time_spent = [[
float(s) for s in time_spent.replace("-", " ").replace(",", ".").split(" ")
if s.replace('.', '', 1).isdigit()
], time_spent]
return rating, rating_n, popular_times, current_popularity, time_spent | python | def get_populartimes_from_search(place_identifier, user_agent=default_user_agent, **kwargs):
"""
request information for a place and parse current popularity
:param place_identifier: name and address string
:return:
"""
params_url = {
"tbm": "map",
"tch": 1,
"q": urllib.parse.quote_plus(place_identifier),
"pb": "!4m12!1m3!1d4005.9771522653964!2d-122.42072974863942!3d37.8077459796541!2m3!1f0!2f0!3f0!3m2!1i1125!2i976"
"!4f13.1!7i20!10b1!12m6!2m3!5m1!6e2!20e3!10b1!16b1!19m3!2m2!1i392!2i106!20m61!2m2!1i203!2i100!3m2!2i4!5b1"
"!6m6!1m2!1i86!2i86!1m2!1i408!2i200!7m46!1m3!1e1!2b0!3e3!1m3!1e2!2b1!3e2!1m3!1e2!2b0!3e3!1m3!1e3!2b0!3e3!"
"1m3!1e4!2b0!3e3!1m3!1e8!2b0!3e3!1m3!1e3!2b1!3e2!1m3!1e9!2b1!3e2!1m3!1e10!2b0!3e3!1m3!1e10!2b1!3e2!1m3!1e"
"10!2b0!3e4!2b1!4b1!9b0!22m6!1sa9fVWea_MsX8adX8j8AE%3A1!2zMWk6Mix0OjExODg3LGU6MSxwOmE5ZlZXZWFfTXNYOGFkWDh"
"qOEFFOjE!7e81!12e3!17sa9fVWea_MsX8adX8j8AE%3A564!18e15!24m15!2b1!5m4!2b1!3b1!5b1!6b1!10m1!8e3!17b1!24b1!"
"25b1!26b1!30m1!2b1!36b1!26m3!2m2!1i80!2i92!30m28!1m6!1m2!1i0!2i0!2m2!1i458!2i976!1m6!1m2!1i1075!2i0!2m2!"
"1i1125!2i976!1m6!1m2!1i0!2i0!2m2!1i1125!2i20!1m6!1m2!1i0!2i956!2m2!1i1125!2i976!37m1!1e81!42b1!47m0!49m1"
"!3b1"
}
search_url = "https://www.google.es/search?" + "&".join(k + "=" + str(v) for k, v in params_url.items())
logging.info("searchterm: " + search_url)
# noinspection PyUnresolvedReferences
gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
resp = urllib.request.urlopen(
urllib.request.Request(
url=search_url,
data=None,
headers=user_agent),
context=gcontext)
data = resp.read().decode('utf-8').split('/*""*/')[0]
# find eof json
jend = data.rfind("}")
if jend >= 0:
data = data[:jend + 1]
jdata = json.loads(data)["d"]
jdata = json.loads(jdata[4:])
# get info from result array, has to be adapted if backend api changes
info = index_get(jdata, 0, 1, 0, 14)
rating = index_get(info, 4, 7)
rating_n = index_get(info, 4, 8)
popular_times = index_get(info, 84, 0)
# current_popularity is also not available if popular_times isn't
current_popularity = index_get(info, 84, 7, 1)
time_spent = index_get(info, 117, 0)
# extract numbers from time string
if time_spent is not None:
time_spent = time_spent.replace("\xa0", " ")
time_spent = [[
float(s) for s in time_spent.replace("-", " ").replace(",", ".").split(" ")
if s.replace('.', '', 1).isdigit()
], time_spent]
return rating, rating_n, popular_times, current_popularity, time_spent | [
"def",
"get_populartimes_from_search",
"(",
"place_identifier",
",",
"user_agent",
"=",
"default_user_agent",
",",
"*",
"*",
"kwargs",
")",
":",
"params_url",
"=",
"{",
"\"tbm\"",
":",
"\"map\"",
",",
"\"tch\"",
":",
"1",
",",
"\"q\"",
":",
"urllib",
".",
"p... | request information for a place and parse current popularity
:param place_identifier: name and address string
:return: | [
"request",
"information",
"for",
"a",
"place",
"and",
"parse",
"current",
"popularity",
":",
"param",
"place_identifier",
":",
"name",
"and",
"address",
"string",
":",
"return",
":"
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/geo/google.py#L130-L196 |
Datary/scrapbag | scrapbag/geo/google.py | check_response_code | def check_response_code(resp):
"""
check if query quota has been surpassed or other errors occured
:param resp: json response
:return:
"""
if resp["status"] == "OK" or resp["status"] == "ZERO_RESULTS":
return
if resp["status"] == "REQUEST_DENIED":
raise Exception("Google Places " + resp["status"],
"Request was denied, the API key is invalid.")
if resp["status"] == "OVER_QUERY_LIMIT":
raise Exception("Google Places " + resp["status"],
"You exceeded your Query Limit for Google Places API Web Service, "
"check https://developers.google.com/places/web-service/usage "
"to upgrade your quota.")
if resp["status"] == "INVALID_REQUEST":
raise Exception("Google Places " + resp["status"],
"The query string is malformed, "
"check if your formatting for lat/lng and radius is correct.")
raise Exception("Google Places " + resp["status"],
"Unidentified error with the Places API, please check the response code") | python | def check_response_code(resp):
"""
check if query quota has been surpassed or other errors occured
:param resp: json response
:return:
"""
if resp["status"] == "OK" or resp["status"] == "ZERO_RESULTS":
return
if resp["status"] == "REQUEST_DENIED":
raise Exception("Google Places " + resp["status"],
"Request was denied, the API key is invalid.")
if resp["status"] == "OVER_QUERY_LIMIT":
raise Exception("Google Places " + resp["status"],
"You exceeded your Query Limit for Google Places API Web Service, "
"check https://developers.google.com/places/web-service/usage "
"to upgrade your quota.")
if resp["status"] == "INVALID_REQUEST":
raise Exception("Google Places " + resp["status"],
"The query string is malformed, "
"check if your formatting for lat/lng and radius is correct.")
raise Exception("Google Places " + resp["status"],
"Unidentified error with the Places API, please check the response code") | [
"def",
"check_response_code",
"(",
"resp",
")",
":",
"if",
"resp",
"[",
"\"status\"",
"]",
"==",
"\"OK\"",
"or",
"resp",
"[",
"\"status\"",
"]",
"==",
"\"ZERO_RESULTS\"",
":",
"return",
"if",
"resp",
"[",
"\"status\"",
"]",
"==",
"\"REQUEST_DENIED\"",
":",
... | check if query quota has been surpassed or other errors occured
:param resp: json response
:return: | [
"check",
"if",
"query",
"quota",
"has",
"been",
"surpassed",
"or",
"other",
"errors",
"occured",
":",
"param",
"resp",
":",
"json",
"response",
":",
"return",
":"
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/geo/google.py#L199-L224 |
Datary/scrapbag | scrapbag/geo/google.py | get_place_details | def get_place_details(api_key, place_id, **kwargs):
"""
sends request to detail to get a search string and uses standard proto buffer to get additional information
on the current status of popular times
:return: json details
"""
params = {
'placeid': place_id,
'key': api_key,
}
resp = requests.get(url=DETAIL_GOOGLEMAPS_API_URL, params=params)
if resp.status_code >= 300:
raise Exception('Bad status code rerieved from google api')
data = json.loads(resp.text)
# check api response status codess
check_response_code(data)
detail = data.get("result", {})
place_identifier = "{} {}".format(detail.get("name"), detail.get("formatted_address"))
detail_json = {
"id": detail.get("place_id"),
"name": detail.get("name"),
"address": detail.get("formatted_address"),
"types": detail.get("types"),
"coordinates": detail.get("geometry", {}).get("location")
}
detail_json = add_optional_parameters(
detail_json, detail,
*get_populartimes_from_search(place_identifier, **kwargs)
)
return detail_json | python | def get_place_details(api_key, place_id, **kwargs):
"""
sends request to detail to get a search string and uses standard proto buffer to get additional information
on the current status of popular times
:return: json details
"""
params = {
'placeid': place_id,
'key': api_key,
}
resp = requests.get(url=DETAIL_GOOGLEMAPS_API_URL, params=params)
if resp.status_code >= 300:
raise Exception('Bad status code rerieved from google api')
data = json.loads(resp.text)
# check api response status codess
check_response_code(data)
detail = data.get("result", {})
place_identifier = "{} {}".format(detail.get("name"), detail.get("formatted_address"))
detail_json = {
"id": detail.get("place_id"),
"name": detail.get("name"),
"address": detail.get("formatted_address"),
"types": detail.get("types"),
"coordinates": detail.get("geometry", {}).get("location")
}
detail_json = add_optional_parameters(
detail_json, detail,
*get_populartimes_from_search(place_identifier, **kwargs)
)
return detail_json | [
"def",
"get_place_details",
"(",
"api_key",
",",
"place_id",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'placeid'",
":",
"place_id",
",",
"'key'",
":",
"api_key",
",",
"}",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"DETAIL_GOOG... | sends request to detail to get a search string and uses standard proto buffer to get additional information
on the current status of popular times
:return: json details | [
"sends",
"request",
"to",
"detail",
"to",
"get",
"a",
"search",
"string",
"and",
"uses",
"standard",
"proto",
"buffer",
"to",
"get",
"additional",
"information",
"on",
"the",
"current",
"status",
"of",
"popular",
"times",
":",
"return",
":",
"json",
"details... | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/geo/google.py#L227-L266 |
hzdg/django-ecstatic | ecstatic/utils.py | get_hashed_filename | def get_hashed_filename(name, file, suffix=None):
"""
Gets a new filename for the provided file of the form
"oldfilename.hash.ext". If the old filename looks like it already contains a
hash, it will be replaced (so you don't end up with names like
"pic.hash.hash.ext")
"""
basename, hash, ext = split_filename(name)
file.seek(0)
new_hash = '.%s' % md5(file.read()).hexdigest()[:12]
if suffix is not None:
basename = '%s_%s' % (basename, suffix)
return '%s%s%s' % (basename, new_hash, ext) | python | def get_hashed_filename(name, file, suffix=None):
"""
Gets a new filename for the provided file of the form
"oldfilename.hash.ext". If the old filename looks like it already contains a
hash, it will be replaced (so you don't end up with names like
"pic.hash.hash.ext")
"""
basename, hash, ext = split_filename(name)
file.seek(0)
new_hash = '.%s' % md5(file.read()).hexdigest()[:12]
if suffix is not None:
basename = '%s_%s' % (basename, suffix)
return '%s%s%s' % (basename, new_hash, ext) | [
"def",
"get_hashed_filename",
"(",
"name",
",",
"file",
",",
"suffix",
"=",
"None",
")",
":",
"basename",
",",
"hash",
",",
"ext",
"=",
"split_filename",
"(",
"name",
")",
"file",
".",
"seek",
"(",
"0",
")",
"new_hash",
"=",
"'.%s'",
"%",
"md5",
"(",... | Gets a new filename for the provided file of the form
"oldfilename.hash.ext". If the old filename looks like it already contains a
hash, it will be replaced (so you don't end up with names like
"pic.hash.hash.ext") | [
"Gets",
"a",
"new",
"filename",
"for",
"the",
"provided",
"file",
"of",
"the",
"form",
"oldfilename",
".",
"hash",
".",
"ext",
".",
"If",
"the",
"old",
"filename",
"looks",
"like",
"it",
"already",
"contains",
"a",
"hash",
"it",
"will",
"be",
"replaced",... | train | https://github.com/hzdg/django-ecstatic/blob/e2b9bd57ae19938449315457b31130c8df831911/ecstatic/utils.py#L33-L46 |
hzdg/django-ecstatic | ecstatic/utils.py | split_filename | def split_filename(name):
"""
Splits the filename into three parts: the name part, the hash part, and the
extension. Like with the extension, the hash part starts with a dot.
"""
parts = hashed_filename_re.match(name).groupdict()
return (parts['name'] or '', parts['hash'] or '', parts['ext'] or '') | python | def split_filename(name):
"""
Splits the filename into three parts: the name part, the hash part, and the
extension. Like with the extension, the hash part starts with a dot.
"""
parts = hashed_filename_re.match(name).groupdict()
return (parts['name'] or '', parts['hash'] or '', parts['ext'] or '') | [
"def",
"split_filename",
"(",
"name",
")",
":",
"parts",
"=",
"hashed_filename_re",
".",
"match",
"(",
"name",
")",
".",
"groupdict",
"(",
")",
"return",
"(",
"parts",
"[",
"'name'",
"]",
"or",
"''",
",",
"parts",
"[",
"'hash'",
"]",
"or",
"''",
",",... | Splits the filename into three parts: the name part, the hash part, and the
extension. Like with the extension, the hash part starts with a dot. | [
"Splits",
"the",
"filename",
"into",
"three",
"parts",
":",
"the",
"name",
"part",
"the",
"hash",
"part",
"and",
"the",
"extension",
".",
"Like",
"with",
"the",
"extension",
"the",
"hash",
"part",
"starts",
"with",
"a",
"dot",
"."
] | train | https://github.com/hzdg/django-ecstatic/blob/e2b9bd57ae19938449315457b31130c8df831911/ecstatic/utils.py#L49-L56 |
stmcli/stmcli | stmcli/bus.py | next_departures | def next_departures(bus_number, stop_code, date, time, nb_departure, db_file):
"""
Getting the 10 next departures
How to check with tools database
sqlite3 stm.db
SELECT "t2"."departure_time"
FROM "trips" AS t1 INNER JOIN "stop_times" AS t2 ON ("t1"."trip_id" = "t2"."trip_id")
INNER JOIN "stops" AS t3 ON ("t2"."stop_id" = "t3"."stop_id")
WHERE ((("t1"."route_id" = '51')
AND ("t3"."stop_code" = '51176'))
AND ("t1"."service_id" IN (SELECT "t4"."service_id"
FROM "calendar" AS t4
WHERE ('20190102' BETWEEN "t4"."start_date" AND "t4"."end_date" )
AND "t4".wednesday == 1
AND "t4".service_id NOT IN (select c2.service_id from calendar_dates as c2 WHERE 20190102 == c2.date)
)
)
)
ORDER BY "t2"."departure_time" ;
Replace 20190102 with the expected date
Replace wednesday with corresponding day of week
make it also for bus number '51' and '51176'
Other guideline to get valid working schedule for the weekday
select * from calendar WHERE (20190102 BETWEEN start_date AND end_date) AND sunday == 1
select * from calendar_dates WHERE 20190102 == date
Select where cases of holiday for days that does not apply
SELECT t1.service_id
FROM calendar AS t1
WHERE (20190102 BETWEEN t1.start_date AND t1.end_date)
AND t1.wednesday == 1
AND (t1.service_id NOT IN (select c2.service_id from calendar_dates as c2 WHERE 20190102 == c2.date))
"""
# Use table Calendar as update from december 2018
day_of_week = datetime.datetime.strptime(
date, "%Y%m%d").strftime("%A").lower()
# Extract dates that the service is disabled
subquery_days_off = CalendarDate.select(CalendarDate.service_id)\
.where(
date == CalendarDate.date
)
# Use calendar to get all services minus days off
subquery = Calendar.select(Calendar.service_id)\
.where(
(date >= Calendar.start_date) &
(date <= Calendar.end_date) &
(getattr(Calendar, day_of_week) == 1) &
Calendar.service_id.not_in(subquery_days_off)
)
# Filter service_id as list of service_id available
query_result = Trip.select(StopTime.departure_time)\
.join(StopTime, on=(Trip.trip_id == StopTime.trip_id))\
.join(Stop, on=(StopTime.stop_id == Stop.stop_id))\
.where(
(Trip.route_id == bus_number) &
(Stop.stop_code == stop_code) &
(Trip.service_id .in_(subquery)))\
.order_by(StopTime.departure_time)
result = []
departures_listed = 0
for i in query_result.dicts():
dep_time = i['departure_time'].split(':')
if dep_time[0] == time[0] and dep_time[1] >= time[1]:
result.append("{0}:{1}".format(dep_time[0], dep_time[1]))
departures_listed += 1
elif dep_time[0] > time[0]:
result.append("{0}:{1}".format(dep_time[0], dep_time[1]))
departures_listed += 1
if departures_listed is nb_departure:
break
return result | python | def next_departures(bus_number, stop_code, date, time, nb_departure, db_file):
"""
Getting the 10 next departures
How to check with tools database
sqlite3 stm.db
SELECT "t2"."departure_time"
FROM "trips" AS t1 INNER JOIN "stop_times" AS t2 ON ("t1"."trip_id" = "t2"."trip_id")
INNER JOIN "stops" AS t3 ON ("t2"."stop_id" = "t3"."stop_id")
WHERE ((("t1"."route_id" = '51')
AND ("t3"."stop_code" = '51176'))
AND ("t1"."service_id" IN (SELECT "t4"."service_id"
FROM "calendar" AS t4
WHERE ('20190102' BETWEEN "t4"."start_date" AND "t4"."end_date" )
AND "t4".wednesday == 1
AND "t4".service_id NOT IN (select c2.service_id from calendar_dates as c2 WHERE 20190102 == c2.date)
)
)
)
ORDER BY "t2"."departure_time" ;
Replace 20190102 with the expected date
Replace wednesday with corresponding day of week
make it also for bus number '51' and '51176'
Other guideline to get valid working schedule for the weekday
select * from calendar WHERE (20190102 BETWEEN start_date AND end_date) AND sunday == 1
select * from calendar_dates WHERE 20190102 == date
Select where cases of holiday for days that does not apply
SELECT t1.service_id
FROM calendar AS t1
WHERE (20190102 BETWEEN t1.start_date AND t1.end_date)
AND t1.wednesday == 1
AND (t1.service_id NOT IN (select c2.service_id from calendar_dates as c2 WHERE 20190102 == c2.date))
"""
# Use table Calendar as update from december 2018
day_of_week = datetime.datetime.strptime(
date, "%Y%m%d").strftime("%A").lower()
# Extract dates that the service is disabled
subquery_days_off = CalendarDate.select(CalendarDate.service_id)\
.where(
date == CalendarDate.date
)
# Use calendar to get all services minus days off
subquery = Calendar.select(Calendar.service_id)\
.where(
(date >= Calendar.start_date) &
(date <= Calendar.end_date) &
(getattr(Calendar, day_of_week) == 1) &
Calendar.service_id.not_in(subquery_days_off)
)
# Filter service_id as list of service_id available
query_result = Trip.select(StopTime.departure_time)\
.join(StopTime, on=(Trip.trip_id == StopTime.trip_id))\
.join(Stop, on=(StopTime.stop_id == Stop.stop_id))\
.where(
(Trip.route_id == bus_number) &
(Stop.stop_code == stop_code) &
(Trip.service_id .in_(subquery)))\
.order_by(StopTime.departure_time)
result = []
departures_listed = 0
for i in query_result.dicts():
dep_time = i['departure_time'].split(':')
if dep_time[0] == time[0] and dep_time[1] >= time[1]:
result.append("{0}:{1}".format(dep_time[0], dep_time[1]))
departures_listed += 1
elif dep_time[0] > time[0]:
result.append("{0}:{1}".format(dep_time[0], dep_time[1]))
departures_listed += 1
if departures_listed is nb_departure:
break
return result | [
"def",
"next_departures",
"(",
"bus_number",
",",
"stop_code",
",",
"date",
",",
"time",
",",
"nb_departure",
",",
"db_file",
")",
":",
"# Use table Calendar as update from december 2018",
"day_of_week",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"date"... | Getting the 10 next departures
How to check with tools database
sqlite3 stm.db
SELECT "t2"."departure_time"
FROM "trips" AS t1 INNER JOIN "stop_times" AS t2 ON ("t1"."trip_id" = "t2"."trip_id")
INNER JOIN "stops" AS t3 ON ("t2"."stop_id" = "t3"."stop_id")
WHERE ((("t1"."route_id" = '51')
AND ("t3"."stop_code" = '51176'))
AND ("t1"."service_id" IN (SELECT "t4"."service_id"
FROM "calendar" AS t4
WHERE ('20190102' BETWEEN "t4"."start_date" AND "t4"."end_date" )
AND "t4".wednesday == 1
AND "t4".service_id NOT IN (select c2.service_id from calendar_dates as c2 WHERE 20190102 == c2.date)
)
)
)
ORDER BY "t2"."departure_time" ;
Replace 20190102 with the expected date
Replace wednesday with corresponding day of week
make it also for bus number '51' and '51176'
Other guideline to get valid working schedule for the weekday
select * from calendar WHERE (20190102 BETWEEN start_date AND end_date) AND sunday == 1
select * from calendar_dates WHERE 20190102 == date
Select where cases of holiday for days that does not apply
SELECT t1.service_id
FROM calendar AS t1
WHERE (20190102 BETWEEN t1.start_date AND t1.end_date)
AND t1.wednesday == 1
AND (t1.service_id NOT IN (select c2.service_id from calendar_dates as c2 WHERE 20190102 == c2.date)) | [
"Getting",
"the",
"10",
"next",
"departures"
] | train | https://github.com/stmcli/stmcli/blob/425b90cfa920c2c8d4da9d10f9e30fbbe71b811e/stmcli/bus.py#L10-L91 |
cloudboss/friend | friend/net.py | random_ipv4 | def random_ipv4(cidr='10.0.0.0/8'):
"""
Return a random IPv4 address from the given CIDR block.
:key str cidr: CIDR block
:returns: An IPv4 address from the given CIDR block
:rtype: ipaddress.IPv4Address
"""
try:
u_cidr = unicode(cidr)
except NameError:
u_cidr = cidr
network = ipaddress.ip_network(u_cidr)
start = int(network.network_address) + 1
end = int(network.broadcast_address)
randint = random.randrange(start, end)
return ipaddress.ip_address(randint) | python | def random_ipv4(cidr='10.0.0.0/8'):
"""
Return a random IPv4 address from the given CIDR block.
:key str cidr: CIDR block
:returns: An IPv4 address from the given CIDR block
:rtype: ipaddress.IPv4Address
"""
try:
u_cidr = unicode(cidr)
except NameError:
u_cidr = cidr
network = ipaddress.ip_network(u_cidr)
start = int(network.network_address) + 1
end = int(network.broadcast_address)
randint = random.randrange(start, end)
return ipaddress.ip_address(randint) | [
"def",
"random_ipv4",
"(",
"cidr",
"=",
"'10.0.0.0/8'",
")",
":",
"try",
":",
"u_cidr",
"=",
"unicode",
"(",
"cidr",
")",
"except",
"NameError",
":",
"u_cidr",
"=",
"cidr",
"network",
"=",
"ipaddress",
".",
"ip_network",
"(",
"u_cidr",
")",
"start",
"=",... | Return a random IPv4 address from the given CIDR block.
:key str cidr: CIDR block
:returns: An IPv4 address from the given CIDR block
:rtype: ipaddress.IPv4Address | [
"Return",
"a",
"random",
"IPv4",
"address",
"from",
"the",
"given",
"CIDR",
"block",
"."
] | train | https://github.com/cloudboss/friend/blob/3357e6ec849552e3ae9ed28017ff0926e4006e4e/friend/net.py#L25-L41 |
benley/butcher | butcher/targets/filegroup.py | FileGroup.output_files | def output_files(self):
"""Returns the list of output files from this rule.
Paths are relative to buildroot.
"""
for item in self.source_files:
yield os.path.join(self.address.repo, self.address.path, item) | python | def output_files(self):
"""Returns the list of output files from this rule.
Paths are relative to buildroot.
"""
for item in self.source_files:
yield os.path.join(self.address.repo, self.address.path, item) | [
"def",
"output_files",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"source_files",
":",
"yield",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"address",
".",
"repo",
",",
"self",
".",
"address",
".",
"path",
",",
"item",
")"
] | Returns the list of output files from this rule.
Paths are relative to buildroot. | [
"Returns",
"the",
"list",
"of",
"output",
"files",
"from",
"this",
"rule",
"."
] | train | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/targets/filegroup.py#L23-L29 |
etcher-be/epab | epab/cmd/_compile_qt.py | _compile_qt_resources | def _compile_qt_resources():
"""
Compiles PyQT resources file
"""
if config.QT_RES_SRC():
epab.utils.ensure_exe('pyrcc5')
LOGGER.info('compiling Qt resources')
elib_run.run(f'pyrcc5 {config.QT_RES_SRC()} -o {config.QT_RES_TGT()}') | python | def _compile_qt_resources():
"""
Compiles PyQT resources file
"""
if config.QT_RES_SRC():
epab.utils.ensure_exe('pyrcc5')
LOGGER.info('compiling Qt resources')
elib_run.run(f'pyrcc5 {config.QT_RES_SRC()} -o {config.QT_RES_TGT()}') | [
"def",
"_compile_qt_resources",
"(",
")",
":",
"if",
"config",
".",
"QT_RES_SRC",
"(",
")",
":",
"epab",
".",
"utils",
".",
"ensure_exe",
"(",
"'pyrcc5'",
")",
"LOGGER",
".",
"info",
"(",
"'compiling Qt resources'",
")",
"elib_run",
".",
"run",
"(",
"f'pyr... | Compiles PyQT resources file | [
"Compiles",
"PyQT",
"resources",
"file"
] | train | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/cmd/_compile_qt.py#L20-L27 |
cohorte/cohorte-herald | python/herald/utils.py | to_json | def to_json(msg):
"""
Returns a JSON string representation of this message
"""
result = {}
# herald specification version
#result[herald.MESSAGE_HERALD_VERSION] = herald.HERALD_SPECIFICATION_VERSION
# headers
result[herald.MESSAGE_HEADERS] = {}
if msg.headers is not None:
for key in msg.headers:
result[herald.MESSAGE_HEADERS][key] = msg.headers.get(key) or None
# subject
result[herald.MESSAGE_SUBJECT] = msg.subject
# content
if msg.content is not None:
if isinstance(msg.content, str):
# string content
result[herald.MESSAGE_CONTENT] = msg.content
else:
# jaborb content
result[herald.MESSAGE_CONTENT] = jabsorb.to_jabsorb(msg.content)
# metadata
result[herald.MESSAGE_METADATA] = {}
if msg.metadata is not None:
for key in msg.metadata:
result[herald.MESSAGE_METADATA][key] = msg.metadata.get(key) or None
return json.dumps(result, default=herald.utils.json_converter) | python | def to_json(msg):
"""
Returns a JSON string representation of this message
"""
result = {}
# herald specification version
#result[herald.MESSAGE_HERALD_VERSION] = herald.HERALD_SPECIFICATION_VERSION
# headers
result[herald.MESSAGE_HEADERS] = {}
if msg.headers is not None:
for key in msg.headers:
result[herald.MESSAGE_HEADERS][key] = msg.headers.get(key) or None
# subject
result[herald.MESSAGE_SUBJECT] = msg.subject
# content
if msg.content is not None:
if isinstance(msg.content, str):
# string content
result[herald.MESSAGE_CONTENT] = msg.content
else:
# jaborb content
result[herald.MESSAGE_CONTENT] = jabsorb.to_jabsorb(msg.content)
# metadata
result[herald.MESSAGE_METADATA] = {}
if msg.metadata is not None:
for key in msg.metadata:
result[herald.MESSAGE_METADATA][key] = msg.metadata.get(key) or None
return json.dumps(result, default=herald.utils.json_converter) | [
"def",
"to_json",
"(",
"msg",
")",
":",
"result",
"=",
"{",
"}",
"# herald specification version",
"#result[herald.MESSAGE_HERALD_VERSION] = herald.HERALD_SPECIFICATION_VERSION",
"# headers",
"result",
"[",
"herald",
".",
"MESSAGE_HEADERS",
"]",
"=",
"{",
"}",
"if",
"ms... | Returns a JSON string representation of this message | [
"Returns",
"a",
"JSON",
"string",
"representation",
"of",
"this",
"message"
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/utils.py#L60-L92 |
cohorte/cohorte-herald | python/herald/utils.py | from_json | def from_json(json_string):
"""
Returns a new MessageReceived from the provided json_string string
"""
# parse the provided json_message
try:
parsed_msg = json.loads(json_string)
except ValueError as ex:
# if the provided json_message is not a valid JSON
return None
except TypeError as ex:
# if json_message not string or buffer
return None
herald_version = None
# check if it is a valid Herald JSON message
if herald.MESSAGE_HEADERS in parsed_msg:
if herald.MESSAGE_HERALD_VERSION in parsed_msg[herald.MESSAGE_HEADERS]:
herald_version = parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HERALD_VERSION)
if herald_version is None or herald_version != herald.HERALD_SPECIFICATION_VERSION:
_logger.error("Herald specification of the received message is not supported!")
return None
# construct new Message object from the provided JSON object
msg = herald.beans.MessageReceived(uid=(parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HEADER_UID) or None),
subject=parsed_msg[herald.MESSAGE_SUBJECT],
content=None,
sender_uid=(parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HEADER_SENDER_UID) or None),
reply_to=(parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HEADER_REPLIES_TO) or None),
access=None,
timestamp=(parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HEADER_TIMESTAMP) or None)
)
# set content
try:
if herald.MESSAGE_CONTENT in parsed_msg:
parsed_content = parsed_msg[herald.MESSAGE_CONTENT]
if parsed_content is not None:
if isinstance(parsed_content, str):
msg.set_content(parsed_content)
else:
msg.set_content(jabsorb.from_jabsorb(parsed_content))
except KeyError as ex:
_logger.error("Error retrieving message content! " + str(ex))
# other headers
if herald.MESSAGE_HEADERS in parsed_msg:
for key in parsed_msg[herald.MESSAGE_HEADERS]:
if key not in msg._headers:
msg._headers[key] = parsed_msg[herald.MESSAGE_HEADERS][key]
# metadata
if herald.MESSAGE_METADATA in parsed_msg:
for key in parsed_msg[herald.MESSAGE_METADATA]:
if key not in msg._metadata:
msg._metadata[key] = parsed_msg[herald.MESSAGE_METADATA][key]
return msg | python | def from_json(json_string):
"""
Returns a new MessageReceived from the provided json_string string
"""
# parse the provided json_message
try:
parsed_msg = json.loads(json_string)
except ValueError as ex:
# if the provided json_message is not a valid JSON
return None
except TypeError as ex:
# if json_message not string or buffer
return None
herald_version = None
# check if it is a valid Herald JSON message
if herald.MESSAGE_HEADERS in parsed_msg:
if herald.MESSAGE_HERALD_VERSION in parsed_msg[herald.MESSAGE_HEADERS]:
herald_version = parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HERALD_VERSION)
if herald_version is None or herald_version != herald.HERALD_SPECIFICATION_VERSION:
_logger.error("Herald specification of the received message is not supported!")
return None
# construct new Message object from the provided JSON object
msg = herald.beans.MessageReceived(uid=(parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HEADER_UID) or None),
subject=parsed_msg[herald.MESSAGE_SUBJECT],
content=None,
sender_uid=(parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HEADER_SENDER_UID) or None),
reply_to=(parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HEADER_REPLIES_TO) or None),
access=None,
timestamp=(parsed_msg[herald.MESSAGE_HEADERS].get(herald.MESSAGE_HEADER_TIMESTAMP) or None)
)
# set content
try:
if herald.MESSAGE_CONTENT in parsed_msg:
parsed_content = parsed_msg[herald.MESSAGE_CONTENT]
if parsed_content is not None:
if isinstance(parsed_content, str):
msg.set_content(parsed_content)
else:
msg.set_content(jabsorb.from_jabsorb(parsed_content))
except KeyError as ex:
_logger.error("Error retrieving message content! " + str(ex))
# other headers
if herald.MESSAGE_HEADERS in parsed_msg:
for key in parsed_msg[herald.MESSAGE_HEADERS]:
if key not in msg._headers:
msg._headers[key] = parsed_msg[herald.MESSAGE_HEADERS][key]
# metadata
if herald.MESSAGE_METADATA in parsed_msg:
for key in parsed_msg[herald.MESSAGE_METADATA]:
if key not in msg._metadata:
msg._metadata[key] = parsed_msg[herald.MESSAGE_METADATA][key]
return msg | [
"def",
"from_json",
"(",
"json_string",
")",
":",
"# parse the provided json_message",
"try",
":",
"parsed_msg",
"=",
"json",
".",
"loads",
"(",
"json_string",
")",
"except",
"ValueError",
"as",
"ex",
":",
"# if the provided json_message is not a valid JSON",
"return",
... | Returns a new MessageReceived from the provided json_string string | [
"Returns",
"a",
"new",
"MessageReceived",
"from",
"the",
"provided",
"json_string",
"string"
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/utils.py#L95-L147 |
cohorte/cohorte-herald | python/herald/utils.py | LoopTimer.run | def run(self):
"""
Runs the given method until cancel() is called
"""
# The "or" part is for Python 2.6
while not (self.finished.wait(self.interval)
or self.finished.is_set()):
self.function(*self.args, **self.kwargs) | python | def run(self):
"""
Runs the given method until cancel() is called
"""
# The "or" part is for Python 2.6
while not (self.finished.wait(self.interval)
or self.finished.is_set()):
self.function(*self.args, **self.kwargs) | [
"def",
"run",
"(",
"self",
")",
":",
"# The \"or\" part is for Python 2.6",
"while",
"not",
"(",
"self",
".",
"finished",
".",
"wait",
"(",
"self",
".",
"interval",
")",
"or",
"self",
".",
"finished",
".",
"is_set",
"(",
")",
")",
":",
"self",
".",
"fu... | Runs the given method until cancel() is called | [
"Runs",
"the",
"given",
"method",
"until",
"cancel",
"()",
"is",
"called"
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/utils.py#L218-L225 |
eReuse/utils | ereuse_utils/naming.py | Naming.resource | def resource(string: str):
"""
:param string: String can be type, resource or python case
"""
try:
prefix, resulting_type = Naming.pop_prefix(string)
prefix += Naming.RESOURCE_PREFIX
except IndexError:
prefix = ''
resulting_type = string
resulting_type = dasherize(underscore(resulting_type))
return prefix + (pluralize(resulting_type) if Naming._pluralize(resulting_type) else resulting_type) | python | def resource(string: str):
"""
:param string: String can be type, resource or python case
"""
try:
prefix, resulting_type = Naming.pop_prefix(string)
prefix += Naming.RESOURCE_PREFIX
except IndexError:
prefix = ''
resulting_type = string
resulting_type = dasherize(underscore(resulting_type))
return prefix + (pluralize(resulting_type) if Naming._pluralize(resulting_type) else resulting_type) | [
"def",
"resource",
"(",
"string",
":",
"str",
")",
":",
"try",
":",
"prefix",
",",
"resulting_type",
"=",
"Naming",
".",
"pop_prefix",
"(",
"string",
")",
"prefix",
"+=",
"Naming",
".",
"RESOURCE_PREFIX",
"except",
"IndexError",
":",
"prefix",
"=",
"''",
... | :param string: String can be type, resource or python case | [
":",
"param",
"string",
":",
"String",
"can",
"be",
"type",
"resource",
"or",
"python",
"case"
] | train | https://github.com/eReuse/utils/blob/989062e85095ea4e1204523fe0e298cf1046a01c/ereuse_utils/naming.py#L21-L32 |
eReuse/utils | ereuse_utils/naming.py | Naming.python | def python(string: str):
"""
:param string: String can be type, resource or python case
"""
return underscore(singularize(string) if Naming._pluralize(string) else string) | python | def python(string: str):
"""
:param string: String can be type, resource or python case
"""
return underscore(singularize(string) if Naming._pluralize(string) else string) | [
"def",
"python",
"(",
"string",
":",
"str",
")",
":",
"return",
"underscore",
"(",
"singularize",
"(",
"string",
")",
"if",
"Naming",
".",
"_pluralize",
"(",
"string",
")",
"else",
"string",
")"
] | :param string: String can be type, resource or python case | [
":",
"param",
"string",
":",
"String",
"can",
"be",
"type",
"resource",
"or",
"python",
"case"
] | train | https://github.com/eReuse/utils/blob/989062e85095ea4e1204523fe0e298cf1046a01c/ereuse_utils/naming.py#L35-L39 |
eReuse/utils | ereuse_utils/naming.py | Naming.pop_prefix | def pop_prefix(string: str):
"""Erases the prefix and returns it.
:throws IndexError: There is no prefix.
:return A set with two elements: 1- the prefix, 2- the type without it.
"""
result = string.split(Naming.TYPE_PREFIX)
if len(result) == 1:
result = string.split(Naming.RESOURCE_PREFIX)
if len(result) == 1:
raise IndexError()
return result | python | def pop_prefix(string: str):
"""Erases the prefix and returns it.
:throws IndexError: There is no prefix.
:return A set with two elements: 1- the prefix, 2- the type without it.
"""
result = string.split(Naming.TYPE_PREFIX)
if len(result) == 1:
result = string.split(Naming.RESOURCE_PREFIX)
if len(result) == 1:
raise IndexError()
return result | [
"def",
"pop_prefix",
"(",
"string",
":",
"str",
")",
":",
"result",
"=",
"string",
".",
"split",
"(",
"Naming",
".",
"TYPE_PREFIX",
")",
"if",
"len",
"(",
"result",
")",
"==",
"1",
":",
"result",
"=",
"string",
".",
"split",
"(",
"Naming",
".",
"RE... | Erases the prefix and returns it.
:throws IndexError: There is no prefix.
:return A set with two elements: 1- the prefix, 2- the type without it. | [
"Erases",
"the",
"prefix",
"and",
"returns",
"it",
".",
":",
"throws",
"IndexError",
":",
"There",
"is",
"no",
"prefix",
".",
":",
"return",
"A",
"set",
"with",
"two",
"elements",
":",
"1",
"-",
"the",
"prefix",
"2",
"-",
"the",
"type",
"without",
"i... | train | https://github.com/eReuse/utils/blob/989062e85095ea4e1204523fe0e298cf1046a01c/ereuse_utils/naming.py#L67-L77 |
eReuse/utils | ereuse_utils/naming.py | Naming.new_type | def new_type(type_name: str, prefix: str or None = None) -> str:
"""
Creates a resource type with optionally a prefix.
Using the rules of JSON-LD, we use prefixes to disambiguate between different types with the same name:
one can Accept a device or a project. In eReuse.org there are different events with the same names, in
linked-data terms they have different URI. In eReuse.org, we solve this with the following:
"@type": "devices:Accept" // the URI for these events is 'devices/events/accept'
"@type": "projects:Accept" // the URI for these events is 'projects/events/accept
...
Type is only used in events, when there are ambiguities. The rest of
"@type": "devices:Accept"
"@type": "Accept"
But these not:
"@type": "projects:Accept" // it is an event from a project
"@type": "Accept" // it is an event from a device
"""
if Naming.TYPE_PREFIX in type_name:
raise TypeError('Cannot create new type: type {} is already prefixed.'.format(type_name))
prefix = (prefix + Naming.TYPE_PREFIX) if prefix is not None else ''
return prefix + type_name | python | def new_type(type_name: str, prefix: str or None = None) -> str:
"""
Creates a resource type with optionally a prefix.
Using the rules of JSON-LD, we use prefixes to disambiguate between different types with the same name:
one can Accept a device or a project. In eReuse.org there are different events with the same names, in
linked-data terms they have different URI. In eReuse.org, we solve this with the following:
"@type": "devices:Accept" // the URI for these events is 'devices/events/accept'
"@type": "projects:Accept" // the URI for these events is 'projects/events/accept
...
Type is only used in events, when there are ambiguities. The rest of
"@type": "devices:Accept"
"@type": "Accept"
But these not:
"@type": "projects:Accept" // it is an event from a project
"@type": "Accept" // it is an event from a device
"""
if Naming.TYPE_PREFIX in type_name:
raise TypeError('Cannot create new type: type {} is already prefixed.'.format(type_name))
prefix = (prefix + Naming.TYPE_PREFIX) if prefix is not None else ''
return prefix + type_name | [
"def",
"new_type",
"(",
"type_name",
":",
"str",
",",
"prefix",
":",
"str",
"or",
"None",
"=",
"None",
")",
"->",
"str",
":",
"if",
"Naming",
".",
"TYPE_PREFIX",
"in",
"type_name",
":",
"raise",
"TypeError",
"(",
"'Cannot create new type: type {} is already pr... | Creates a resource type with optionally a prefix.
Using the rules of JSON-LD, we use prefixes to disambiguate between different types with the same name:
one can Accept a device or a project. In eReuse.org there are different events with the same names, in
linked-data terms they have different URI. In eReuse.org, we solve this with the following:
"@type": "devices:Accept" // the URI for these events is 'devices/events/accept'
"@type": "projects:Accept" // the URI for these events is 'projects/events/accept
...
Type is only used in events, when there are ambiguities. The rest of
"@type": "devices:Accept"
"@type": "Accept"
But these not:
"@type": "projects:Accept" // it is an event from a project
"@type": "Accept" // it is an event from a device | [
"Creates",
"a",
"resource",
"type",
"with",
"optionally",
"a",
"prefix",
"."
] | train | https://github.com/eReuse/utils/blob/989062e85095ea4e1204523fe0e298cf1046a01c/ereuse_utils/naming.py#L80-L105 |
eReuse/utils | ereuse_utils/naming.py | Naming.hid | def hid(manufacturer: str, serial_number: str, model: str) -> str:
"""Computes the HID for the given properties of a device. The HID is suitable to use to an URI."""
return Naming.url_word(manufacturer) + '-' + Naming.url_word(serial_number) + '-' + Naming.url_word(model) | python | def hid(manufacturer: str, serial_number: str, model: str) -> str:
"""Computes the HID for the given properties of a device. The HID is suitable to use to an URI."""
return Naming.url_word(manufacturer) + '-' + Naming.url_word(serial_number) + '-' + Naming.url_word(model) | [
"def",
"hid",
"(",
"manufacturer",
":",
"str",
",",
"serial_number",
":",
"str",
",",
"model",
":",
"str",
")",
"->",
"str",
":",
"return",
"Naming",
".",
"url_word",
"(",
"manufacturer",
")",
"+",
"'-'",
"+",
"Naming",
".",
"url_word",
"(",
"serial_nu... | Computes the HID for the given properties of a device. The HID is suitable to use to an URI. | [
"Computes",
"the",
"HID",
"for",
"the",
"given",
"properties",
"of",
"a",
"device",
".",
"The",
"HID",
"is",
"suitable",
"to",
"use",
"to",
"an",
"URI",
"."
] | train | https://github.com/eReuse/utils/blob/989062e85095ea4e1204523fe0e298cf1046a01c/ereuse_utils/naming.py#L108-L110 |
duniter/duniter-python-api | examples/send_membership.py | get_membership_document | def get_membership_document(membership_type: str, current_block: dict, identity: Identity, salt: str,
password: str) -> Membership:
"""
Get a Membership document
:param membership_type: "IN" to ask for membership or "OUT" to cancel membership
:param current_block: Current block data
:param identity: Identity document
:param salt: Passphrase of the account
:param password: Password of the account
:rtype: Membership
"""
# get current block BlockStamp
timestamp = BlockUID(current_block['number'], current_block['hash'])
# create keys from credentials
key = SigningKey.from_credentials(salt, password)
# create identity document
membership = Membership(
version=10,
currency=current_block['currency'],
issuer=key.pubkey,
membership_ts=timestamp,
membership_type=membership_type,
uid=identity.uid,
identity_ts=identity.timestamp,
signature=None
)
# sign document
membership.sign([key])
return membership | python | def get_membership_document(membership_type: str, current_block: dict, identity: Identity, salt: str,
password: str) -> Membership:
"""
Get a Membership document
:param membership_type: "IN" to ask for membership or "OUT" to cancel membership
:param current_block: Current block data
:param identity: Identity document
:param salt: Passphrase of the account
:param password: Password of the account
:rtype: Membership
"""
# get current block BlockStamp
timestamp = BlockUID(current_block['number'], current_block['hash'])
# create keys from credentials
key = SigningKey.from_credentials(salt, password)
# create identity document
membership = Membership(
version=10,
currency=current_block['currency'],
issuer=key.pubkey,
membership_ts=timestamp,
membership_type=membership_type,
uid=identity.uid,
identity_ts=identity.timestamp,
signature=None
)
# sign document
membership.sign([key])
return membership | [
"def",
"get_membership_document",
"(",
"membership_type",
":",
"str",
",",
"current_block",
":",
"dict",
",",
"identity",
":",
"Identity",
",",
"salt",
":",
"str",
",",
"password",
":",
"str",
")",
"->",
"Membership",
":",
"# get current block BlockStamp",
"time... | Get a Membership document
:param membership_type: "IN" to ask for membership or "OUT" to cancel membership
:param current_block: Current block data
:param identity: Identity document
:param salt: Passphrase of the account
:param password: Password of the account
:rtype: Membership | [
"Get",
"a",
"Membership",
"document"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/examples/send_membership.py#L54-L89 |
benley/butcher | tools/python_getvar.py | getvar | def getvar(syntree, targetvar):
"""Scan an ast object for targetvar and return its value.
Only handles single direct assignment of python literal types. See docs on
ast.literal_eval for more info:
http://docs.python.org/2/library/ast.html#ast.literal_eval
Args:
syntree: ast.Module object
targetvar: name of global variable to return
Returns:
Value of targetvar if found in syntree, or None if not found.
"""
for node in syntree.body:
if isinstance(node, ast.Assign):
for var in node.targets:
if var.id == targetvar:
return ast.literal_eval(node.value) | python | def getvar(syntree, targetvar):
"""Scan an ast object for targetvar and return its value.
Only handles single direct assignment of python literal types. See docs on
ast.literal_eval for more info:
http://docs.python.org/2/library/ast.html#ast.literal_eval
Args:
syntree: ast.Module object
targetvar: name of global variable to return
Returns:
Value of targetvar if found in syntree, or None if not found.
"""
for node in syntree.body:
if isinstance(node, ast.Assign):
for var in node.targets:
if var.id == targetvar:
return ast.literal_eval(node.value) | [
"def",
"getvar",
"(",
"syntree",
",",
"targetvar",
")",
":",
"for",
"node",
"in",
"syntree",
".",
"body",
":",
"if",
"isinstance",
"(",
"node",
",",
"ast",
".",
"Assign",
")",
":",
"for",
"var",
"in",
"node",
".",
"targets",
":",
"if",
"var",
".",
... | Scan an ast object for targetvar and return its value.
Only handles single direct assignment of python literal types. See docs on
ast.literal_eval for more info:
http://docs.python.org/2/library/ast.html#ast.literal_eval
Args:
syntree: ast.Module object
targetvar: name of global variable to return
Returns:
Value of targetvar if found in syntree, or None if not found. | [
"Scan",
"an",
"ast",
"object",
"for",
"targetvar",
"and",
"return",
"its",
"value",
"."
] | train | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/tools/python_getvar.py#L9-L26 |
mixmastamyk/fr | fr/utils.py | run | def run(cmd, shell=False, debug=False):
'Run a command and return the output.'
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=shell)
(out, _) = proc.communicate() # no need for stderr
if debug:
print(cmd)
print(out)
return out | python | def run(cmd, shell=False, debug=False):
'Run a command and return the output.'
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=shell)
(out, _) = proc.communicate() # no need for stderr
if debug:
print(cmd)
print(out)
return out | [
"def",
"run",
"(",
"cmd",
",",
"shell",
"=",
"False",
",",
"debug",
"=",
"False",
")",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"shell",
"=",
"shell",
")",
"(",
"out",
",",
"_",... | Run a command and return the output. | [
"Run",
"a",
"command",
"and",
"return",
"the",
"output",
"."
] | train | https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/utils.py#L67-L74 |
unt-libraries/pypairtree | pypairtree/pairtree.py | findObjects | def findObjects(path):
"""Finds objects in pairtree.
Given a path that corresponds to a pairtree, walk it and look for
non-shorty (it's ya birthday) directories.
"""
objects = []
if not os.path.isdir(path):
return []
contents = os.listdir(path)
for item in contents:
fullPath = os.path.join(path, item)
if not os.path.isdir(fullPath):
# deal with a split end at this point
# we might want to consider a normalize option
return [path]
else:
if isShorty(item):
objects = objects + findObjects(fullPath)
else:
objects.append(fullPath)
return objects | python | def findObjects(path):
"""Finds objects in pairtree.
Given a path that corresponds to a pairtree, walk it and look for
non-shorty (it's ya birthday) directories.
"""
objects = []
if not os.path.isdir(path):
return []
contents = os.listdir(path)
for item in contents:
fullPath = os.path.join(path, item)
if not os.path.isdir(fullPath):
# deal with a split end at this point
# we might want to consider a normalize option
return [path]
else:
if isShorty(item):
objects = objects + findObjects(fullPath)
else:
objects.append(fullPath)
return objects | [
"def",
"findObjects",
"(",
"path",
")",
":",
"objects",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"[",
"]",
"contents",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"for",
"item",
"in",
"content... | Finds objects in pairtree.
Given a path that corresponds to a pairtree, walk it and look for
non-shorty (it's ya birthday) directories. | [
"Finds",
"objects",
"in",
"pairtree",
"."
] | train | https://github.com/unt-libraries/pypairtree/blob/2107b46718bbf9ef7ef3d5c63d557d1f772e5d69/pypairtree/pairtree.py#L14-L35 |
unt-libraries/pypairtree | pypairtree/pairtree.py | get_pair_path | def get_pair_path(meta_id):
"""Determines the pair path for the digital object meta-id."""
pair_tree = pair_tree_creator(meta_id)
pair_path = os.path.join(pair_tree, meta_id)
return pair_path | python | def get_pair_path(meta_id):
"""Determines the pair path for the digital object meta-id."""
pair_tree = pair_tree_creator(meta_id)
pair_path = os.path.join(pair_tree, meta_id)
return pair_path | [
"def",
"get_pair_path",
"(",
"meta_id",
")",
":",
"pair_tree",
"=",
"pair_tree_creator",
"(",
"meta_id",
")",
"pair_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pair_tree",
",",
"meta_id",
")",
"return",
"pair_path"
] | Determines the pair path for the digital object meta-id. | [
"Determines",
"the",
"pair",
"path",
"for",
"the",
"digital",
"object",
"meta",
"-",
"id",
"."
] | train | https://github.com/unt-libraries/pypairtree/blob/2107b46718bbf9ef7ef3d5c63d557d1f772e5d69/pypairtree/pairtree.py#L38-L42 |
unt-libraries/pypairtree | pypairtree/pairtree.py | pair_tree_creator | def pair_tree_creator(meta_id):
"""Splits string into a pairtree path."""
chunks = []
for x in range(0, len(meta_id)):
if x % 2:
continue
if (len(meta_id) - 1) == x:
chunk = meta_id[x]
else:
chunk = meta_id[x: x + 2]
chunks.append(chunk)
return os.sep + os.sep.join(chunks) + os.sep | python | def pair_tree_creator(meta_id):
"""Splits string into a pairtree path."""
chunks = []
for x in range(0, len(meta_id)):
if x % 2:
continue
if (len(meta_id) - 1) == x:
chunk = meta_id[x]
else:
chunk = meta_id[x: x + 2]
chunks.append(chunk)
return os.sep + os.sep.join(chunks) + os.sep | [
"def",
"pair_tree_creator",
"(",
"meta_id",
")",
":",
"chunks",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"meta_id",
")",
")",
":",
"if",
"x",
"%",
"2",
":",
"continue",
"if",
"(",
"len",
"(",
"meta_id",
")",
"-",
"1"... | Splits string into a pairtree path. | [
"Splits",
"string",
"into",
"a",
"pairtree",
"path",
"."
] | train | https://github.com/unt-libraries/pypairtree/blob/2107b46718bbf9ef7ef3d5c63d557d1f772e5d69/pypairtree/pairtree.py#L51-L62 |
unt-libraries/pypairtree | pypairtree/pairtree.py | deSanitizeString | def deSanitizeString(name):
"""Reverses sanitization process.
Reverses changes made to a string that has been sanitized for use
as a pairtree identifier.
"""
oldString = name
# first pass
replaceTable2 = [
("/", "="),
(":", "+"),
(".", ","),
]
for r in replaceTable2:
oldString = oldString.replace(r[1], r[0])
# reverse ascii 0-32 stuff
# must subtract number added at sanitization
for x in range(0, 33):
oldString = oldString.replace(
hex(x + sanitizerNum).replace('0x', '^'), chr(x))
# second pass
replaceTable = [
('"', '^22'),
('<', '^3c'),
('?', '^3f'),
('*', '^2a'),
('=', '^3d'),
('+', '^2b'),
('>', '^3e'),
('|', '^7c'),
(',', '^2c'),
('^', '^5e'),
]
for r in replaceTable:
oldString = oldString.replace(r[1], r[0])
return oldString | python | def deSanitizeString(name):
"""Reverses sanitization process.
Reverses changes made to a string that has been sanitized for use
as a pairtree identifier.
"""
oldString = name
# first pass
replaceTable2 = [
("/", "="),
(":", "+"),
(".", ","),
]
for r in replaceTable2:
oldString = oldString.replace(r[1], r[0])
# reverse ascii 0-32 stuff
# must subtract number added at sanitization
for x in range(0, 33):
oldString = oldString.replace(
hex(x + sanitizerNum).replace('0x', '^'), chr(x))
# second pass
replaceTable = [
('"', '^22'),
('<', '^3c'),
('?', '^3f'),
('*', '^2a'),
('=', '^3d'),
('+', '^2b'),
('>', '^3e'),
('|', '^7c'),
(',', '^2c'),
('^', '^5e'),
]
for r in replaceTable:
oldString = oldString.replace(r[1], r[0])
return oldString | [
"def",
"deSanitizeString",
"(",
"name",
")",
":",
"oldString",
"=",
"name",
"# first pass",
"replaceTable2",
"=",
"[",
"(",
"\"/\"",
",",
"\"=\"",
")",
",",
"(",
"\":\"",
",",
"\"+\"",
")",
",",
"(",
"\".\"",
",",
"\",\"",
")",
",",
"]",
"for",
"r",
... | Reverses sanitization process.
Reverses changes made to a string that has been sanitized for use
as a pairtree identifier. | [
"Reverses",
"sanitization",
"process",
"."
] | train | https://github.com/unt-libraries/pypairtree/blob/2107b46718bbf9ef7ef3d5c63d557d1f772e5d69/pypairtree/pairtree.py#L65-L101 |
unt-libraries/pypairtree | pypairtree/pairtree.py | sanitizeString | def sanitizeString(name):
"""Cleans string in preparation for splitting for use as a pairtree
identifier."""
newString = name
# string cleaning, pass 1
replaceTable = [
('^', '^5e'), # we need to do this one first
('"', '^22'),
('<', '^3c'),
('?', '^3f'),
('*', '^2a'),
('=', '^3d'),
('+', '^2b'),
('>', '^3e'),
('|', '^7c'),
(',', '^2c'),
]
# " hex 22 < hex 3c ? hex 3f
# * hex 2a = hex 3d ^ hex 5e
# + hex 2b > hex 3e | hex 7c
# , hex 2c
for r in replaceTable:
newString = newString.replace(r[0], r[1])
# replace ascii 0-32
for x in range(0, 33):
# must add somewhat arbitrary num to avoid conflict at deSanitization
# conflict example: is ^x1e supposed to be ^x1 (ascii 1) followed by
# letter 'e' or really ^x1e (ascii 30)
newString = newString.replace(
chr(x), hex(x + sanitizerNum).replace('0x', '^'))
replaceTable2 = [
("/", "="),
(":", "+"),
(".", ","),
]
# / -> =
# : -> +
# . -> ,
# string cleaning pass 2
for r in replaceTable2:
newString = newString.replace(r[0], r[1])
return newString | python | def sanitizeString(name):
"""Cleans string in preparation for splitting for use as a pairtree
identifier."""
newString = name
# string cleaning, pass 1
replaceTable = [
('^', '^5e'), # we need to do this one first
('"', '^22'),
('<', '^3c'),
('?', '^3f'),
('*', '^2a'),
('=', '^3d'),
('+', '^2b'),
('>', '^3e'),
('|', '^7c'),
(',', '^2c'),
]
# " hex 22 < hex 3c ? hex 3f
# * hex 2a = hex 3d ^ hex 5e
# + hex 2b > hex 3e | hex 7c
# , hex 2c
for r in replaceTable:
newString = newString.replace(r[0], r[1])
# replace ascii 0-32
for x in range(0, 33):
# must add somewhat arbitrary num to avoid conflict at deSanitization
# conflict example: is ^x1e supposed to be ^x1 (ascii 1) followed by
# letter 'e' or really ^x1e (ascii 30)
newString = newString.replace(
chr(x), hex(x + sanitizerNum).replace('0x', '^'))
replaceTable2 = [
("/", "="),
(":", "+"),
(".", ","),
]
# / -> =
# : -> +
# . -> ,
# string cleaning pass 2
for r in replaceTable2:
newString = newString.replace(r[0], r[1])
return newString | [
"def",
"sanitizeString",
"(",
"name",
")",
":",
"newString",
"=",
"name",
"# string cleaning, pass 1",
"replaceTable",
"=",
"[",
"(",
"'^'",
",",
"'^5e'",
")",
",",
"# we need to do this one first",
"(",
"'\"'",
",",
"'^22'",
")",
",",
"(",
"'<'",
",",
"'^3c... | Cleans string in preparation for splitting for use as a pairtree
identifier. | [
"Cleans",
"string",
"in",
"preparation",
"for",
"splitting",
"for",
"use",
"as",
"a",
"pairtree",
"identifier",
"."
] | train | https://github.com/unt-libraries/pypairtree/blob/2107b46718bbf9ef7ef3d5c63d557d1f772e5d69/pypairtree/pairtree.py#L104-L150 |
unt-libraries/pypairtree | pypairtree/pairtree.py | toPairTreePath | def toPairTreePath(name):
"""Cleans a string, and then splits it into a pairtree path."""
sName = sanitizeString(name)
chunks = []
for x in range(0, len(sName)):
if x % 2:
continue
if (len(sName) - 1) == x:
chunk = sName[x]
else:
chunk = sName[x: x + 2]
chunks.append(chunk)
return os.sep.join(chunks) + os.sep | python | def toPairTreePath(name):
"""Cleans a string, and then splits it into a pairtree path."""
sName = sanitizeString(name)
chunks = []
for x in range(0, len(sName)):
if x % 2:
continue
if (len(sName) - 1) == x:
chunk = sName[x]
else:
chunk = sName[x: x + 2]
chunks.append(chunk)
return os.sep.join(chunks) + os.sep | [
"def",
"toPairTreePath",
"(",
"name",
")",
":",
"sName",
"=",
"sanitizeString",
"(",
"name",
")",
"chunks",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"sName",
")",
")",
":",
"if",
"x",
"%",
"2",
":",
"continue",
"if",
... | Cleans a string, and then splits it into a pairtree path. | [
"Cleans",
"a",
"string",
"and",
"then",
"splits",
"it",
"into",
"a",
"pairtree",
"path",
"."
] | train | https://github.com/unt-libraries/pypairtree/blob/2107b46718bbf9ef7ef3d5c63d557d1f772e5d69/pypairtree/pairtree.py#L153-L165 |
unt-libraries/pypairtree | pypairtree/pairtree.py | create_paired_dir | def create_paired_dir(output_dir, meta_id, static=False, needwebdir=True):
"""Creates the meta or static dirs.
Adds an "even" or "odd" subdirectory to the static path
based on the meta-id.
"""
# get the absolute root path
root_path = os.path.abspath(output_dir)
# if it's a static directory, add even and odd
if static:
# determine whether meta-id is odd or even
if meta_id[-1].isdigit():
last_character = int(meta_id[-1])
else:
last_character = ord(meta_id[-1])
if last_character % 2 == 0:
num_dir = 'even'
else:
num_dir = 'odd'
# add odd or even to the path, based on the meta-id
output_path = os.path.join(root_path, num_dir)
# if it's a meta directory, output as normal
else:
output_path = root_path
# if it doesn't already exist, create the output path (includes even/odd)
if not os.path.exists(output_path):
os.mkdir(output_path)
# add the pairtree to the output path
path_name = add_to_pairtree(output_path, meta_id)
# add the meta-id directory to the end of the pairpath
meta_dir = os.path.join(path_name, meta_id)
os.mkdir(meta_dir)
# if we are creating static output
if static and needwebdir:
# add the web path to the output directory
os.mkdir(os.path.join(meta_dir, 'web'))
static_dir = os.path.join(meta_dir, 'web')
return static_dir
# else we are creating meta output or don't need web directory
else:
return meta_dir | python | def create_paired_dir(output_dir, meta_id, static=False, needwebdir=True):
"""Creates the meta or static dirs.
Adds an "even" or "odd" subdirectory to the static path
based on the meta-id.
"""
# get the absolute root path
root_path = os.path.abspath(output_dir)
# if it's a static directory, add even and odd
if static:
# determine whether meta-id is odd or even
if meta_id[-1].isdigit():
last_character = int(meta_id[-1])
else:
last_character = ord(meta_id[-1])
if last_character % 2 == 0:
num_dir = 'even'
else:
num_dir = 'odd'
# add odd or even to the path, based on the meta-id
output_path = os.path.join(root_path, num_dir)
# if it's a meta directory, output as normal
else:
output_path = root_path
# if it doesn't already exist, create the output path (includes even/odd)
if not os.path.exists(output_path):
os.mkdir(output_path)
# add the pairtree to the output path
path_name = add_to_pairtree(output_path, meta_id)
# add the meta-id directory to the end of the pairpath
meta_dir = os.path.join(path_name, meta_id)
os.mkdir(meta_dir)
# if we are creating static output
if static and needwebdir:
# add the web path to the output directory
os.mkdir(os.path.join(meta_dir, 'web'))
static_dir = os.path.join(meta_dir, 'web')
return static_dir
# else we are creating meta output or don't need web directory
else:
return meta_dir | [
"def",
"create_paired_dir",
"(",
"output_dir",
",",
"meta_id",
",",
"static",
"=",
"False",
",",
"needwebdir",
"=",
"True",
")",
":",
"# get the absolute root path",
"root_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"output_dir",
")",
"# if it's a static... | Creates the meta or static dirs.
Adds an "even" or "odd" subdirectory to the static path
based on the meta-id. | [
"Creates",
"the",
"meta",
"or",
"static",
"dirs",
"."
] | train | https://github.com/unt-libraries/pypairtree/blob/2107b46718bbf9ef7ef3d5c63d557d1f772e5d69/pypairtree/pairtree.py#L168-L208 |
unt-libraries/pypairtree | pypairtree/pairtree.py | add_to_pairtree | def add_to_pairtree(output_path, meta_id):
"""Creates pairtree dir structure within pairtree for new
element."""
# create the pair path
paired_path = pair_tree_creator(meta_id)
path_append = ''
# for each directory in the pair path
for pair_dir in paired_path.split(os.sep):
# append the pair path together, one directory at a time
path_append = os.path.join(path_append, pair_dir)
# append the pair path to the output path
combined_path = os.path.join(output_path, path_append)
# if the path doesn't already exist, create it
if not os.path.exists(combined_path):
os.mkdir(combined_path)
return combined_path | python | def add_to_pairtree(output_path, meta_id):
"""Creates pairtree dir structure within pairtree for new
element."""
# create the pair path
paired_path = pair_tree_creator(meta_id)
path_append = ''
# for each directory in the pair path
for pair_dir in paired_path.split(os.sep):
# append the pair path together, one directory at a time
path_append = os.path.join(path_append, pair_dir)
# append the pair path to the output path
combined_path = os.path.join(output_path, path_append)
# if the path doesn't already exist, create it
if not os.path.exists(combined_path):
os.mkdir(combined_path)
return combined_path | [
"def",
"add_to_pairtree",
"(",
"output_path",
",",
"meta_id",
")",
":",
"# create the pair path",
"paired_path",
"=",
"pair_tree_creator",
"(",
"meta_id",
")",
"path_append",
"=",
"''",
"# for each directory in the pair path",
"for",
"pair_dir",
"in",
"paired_path",
"."... | Creates pairtree dir structure within pairtree for new
element. | [
"Creates",
"pairtree",
"dir",
"structure",
"within",
"pairtree",
"for",
"new",
"element",
"."
] | train | https://github.com/unt-libraries/pypairtree/blob/2107b46718bbf9ef7ef3d5c63d557d1f772e5d69/pypairtree/pairtree.py#L211-L226 |
unt-libraries/pypairtree | pypairtree/pairtree.py | get_pairtree_prefix | def get_pairtree_prefix(pairtree_store):
"""Returns the prefix given in pairtree_prefix file."""
prefix_path = os.path.join(pairtree_store, 'pairtree_prefix')
with open(prefix_path, 'r') as prefixf:
prefix = prefixf.read().strip()
return prefix | python | def get_pairtree_prefix(pairtree_store):
"""Returns the prefix given in pairtree_prefix file."""
prefix_path = os.path.join(pairtree_store, 'pairtree_prefix')
with open(prefix_path, 'r') as prefixf:
prefix = prefixf.read().strip()
return prefix | [
"def",
"get_pairtree_prefix",
"(",
"pairtree_store",
")",
":",
"prefix_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pairtree_store",
",",
"'pairtree_prefix'",
")",
"with",
"open",
"(",
"prefix_path",
",",
"'r'",
")",
"as",
"prefixf",
":",
"prefix",
"=",... | Returns the prefix given in pairtree_prefix file. | [
"Returns",
"the",
"prefix",
"given",
"in",
"pairtree_prefix",
"file",
"."
] | train | https://github.com/unt-libraries/pypairtree/blob/2107b46718bbf9ef7ef3d5c63d557d1f772e5d69/pypairtree/pairtree.py#L229-L234 |
duniter/duniter-python-api | duniterpy/documents/document.py | Document.parse_field | def parse_field(cls: Type[DocumentType], field_name: str, line: str) -> Any:
"""
Parse a document field with regular expression and return the value
:param field_name: Name of the field
:param line: Line string to parse
:return:
"""
try:
match = cls.fields_parsers[field_name].match(line)
if match is None:
raise AttributeError
value = match.group(1)
except AttributeError:
raise MalformedDocumentError(field_name)
return value | python | def parse_field(cls: Type[DocumentType], field_name: str, line: str) -> Any:
"""
Parse a document field with regular expression and return the value
:param field_name: Name of the field
:param line: Line string to parse
:return:
"""
try:
match = cls.fields_parsers[field_name].match(line)
if match is None:
raise AttributeError
value = match.group(1)
except AttributeError:
raise MalformedDocumentError(field_name)
return value | [
"def",
"parse_field",
"(",
"cls",
":",
"Type",
"[",
"DocumentType",
"]",
",",
"field_name",
":",
"str",
",",
"line",
":",
"str",
")",
"->",
"Any",
":",
"try",
":",
"match",
"=",
"cls",
".",
"fields_parsers",
"[",
"field_name",
"]",
".",
"match",
"(",... | Parse a document field with regular expression and return the value
:param field_name: Name of the field
:param line: Line string to parse
:return: | [
"Parse",
"a",
"document",
"field",
"with",
"regular",
"expression",
"and",
"return",
"the",
"value"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/document.py#L57-L72 |
duniter/duniter-python-api | duniterpy/documents/document.py | Document.signed_raw | def signed_raw(self) -> str:
"""
If keys are None, returns the raw + current signatures
If keys are present, returns the raw signed by these keys
:return:
"""
raw = self.raw()
signed = "\n".join(self.signatures)
signed_raw = raw + signed + "\n"
return signed_raw | python | def signed_raw(self) -> str:
"""
If keys are None, returns the raw + current signatures
If keys are present, returns the raw signed by these keys
:return:
"""
raw = self.raw()
signed = "\n".join(self.signatures)
signed_raw = raw + signed + "\n"
return signed_raw | [
"def",
"signed_raw",
"(",
"self",
")",
"->",
"str",
":",
"raw",
"=",
"self",
".",
"raw",
"(",
")",
"signed",
"=",
"\"\\n\"",
".",
"join",
"(",
"self",
".",
"signatures",
")",
"signed_raw",
"=",
"raw",
"+",
"signed",
"+",
"\"\\n\"",
"return",
"signed_... | If keys are None, returns the raw + current signatures
If keys are present, returns the raw signed by these keys
:return: | [
"If",
"keys",
"are",
"None",
"returns",
"the",
"raw",
"+",
"current",
"signatures",
"If",
"keys",
"are",
"present",
"returns",
"the",
"raw",
"signed",
"by",
"these",
"keys",
":",
"return",
":"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/document.py#L94-L103 |
duniter/duniter-python-api | duniterpy/documents/document.py | Document.sha_hash | def sha_hash(self) -> str:
"""
Return uppercase hex sha256 hash from signed raw document
:return:
"""
return hashlib.sha256(self.signed_raw().encode("ascii")).hexdigest().upper() | python | def sha_hash(self) -> str:
"""
Return uppercase hex sha256 hash from signed raw document
:return:
"""
return hashlib.sha256(self.signed_raw().encode("ascii")).hexdigest().upper() | [
"def",
"sha_hash",
"(",
"self",
")",
"->",
"str",
":",
"return",
"hashlib",
".",
"sha256",
"(",
"self",
".",
"signed_raw",
"(",
")",
".",
"encode",
"(",
"\"ascii\"",
")",
")",
".",
"hexdigest",
"(",
")",
".",
"upper",
"(",
")"
] | Return uppercase hex sha256 hash from signed raw document
:return: | [
"Return",
"uppercase",
"hex",
"sha256",
"hash",
"from",
"signed",
"raw",
"document"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/documents/document.py#L106-L112 |
NerdWalletOSS/savage | src/savage/models/__init__.py | SavageLogMixin.build_row_dict | def build_row_dict(cls, row, dialect, deleted=False, user_id=None, use_dirty=True):
"""
Builds a dictionary of archive data from row which is suitable for insert.
NOTE: If `deleted` is False, version ID will be set to an AsIs SQL construct.
:param row: instance of :class:`~SavageModelMixin`
:param dialect: :py:class:`~sqlalchemy.engine.interfaces.Dialect`
:param deleted: whether or not the row is deleted (defaults to False)
:param user_id: ID of user that is performing the update on this row (defaults to None)
:param use_dirty: whether to use the dirty fields from row or not (defaults to True)
:return: a dictionary of archive table column names to values, suitable for insert
:rtype: dict
"""
data = {
'data': row.to_archivable_dict(dialect, use_dirty=use_dirty),
'deleted': deleted,
'updated_at': datetime.now(),
'version_id': current_version_sql(as_is=True) if deleted else row.version_id
}
for col_name in row.version_columns:
data[col_name] = utils.get_column_attribute(row, col_name, use_dirty=use_dirty)
if user_id is not None:
data['user_id'] = user_id
return data | python | def build_row_dict(cls, row, dialect, deleted=False, user_id=None, use_dirty=True):
"""
Builds a dictionary of archive data from row which is suitable for insert.
NOTE: If `deleted` is False, version ID will be set to an AsIs SQL construct.
:param row: instance of :class:`~SavageModelMixin`
:param dialect: :py:class:`~sqlalchemy.engine.interfaces.Dialect`
:param deleted: whether or not the row is deleted (defaults to False)
:param user_id: ID of user that is performing the update on this row (defaults to None)
:param use_dirty: whether to use the dirty fields from row or not (defaults to True)
:return: a dictionary of archive table column names to values, suitable for insert
:rtype: dict
"""
data = {
'data': row.to_archivable_dict(dialect, use_dirty=use_dirty),
'deleted': deleted,
'updated_at': datetime.now(),
'version_id': current_version_sql(as_is=True) if deleted else row.version_id
}
for col_name in row.version_columns:
data[col_name] = utils.get_column_attribute(row, col_name, use_dirty=use_dirty)
if user_id is not None:
data['user_id'] = user_id
return data | [
"def",
"build_row_dict",
"(",
"cls",
",",
"row",
",",
"dialect",
",",
"deleted",
"=",
"False",
",",
"user_id",
"=",
"None",
",",
"use_dirty",
"=",
"True",
")",
":",
"data",
"=",
"{",
"'data'",
":",
"row",
".",
"to_archivable_dict",
"(",
"dialect",
",",... | Builds a dictionary of archive data from row which is suitable for insert.
NOTE: If `deleted` is False, version ID will be set to an AsIs SQL construct.
:param row: instance of :class:`~SavageModelMixin`
:param dialect: :py:class:`~sqlalchemy.engine.interfaces.Dialect`
:param deleted: whether or not the row is deleted (defaults to False)
:param user_id: ID of user that is performing the update on this row (defaults to None)
:param use_dirty: whether to use the dirty fields from row or not (defaults to True)
:return: a dictionary of archive table column names to values, suitable for insert
:rtype: dict | [
"Builds",
"a",
"dictionary",
"of",
"archive",
"data",
"from",
"row",
"which",
"is",
"suitable",
"for",
"insert",
"."
] | train | https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/models/__init__.py#L59-L83 |
NerdWalletOSS/savage | src/savage/models/__init__.py | SavageLogMixin.bulk_archive_rows | def bulk_archive_rows(cls, rows, session, user_id=None, chunk_size=1000, commit=True):
"""
Bulk archives data previously written to DB.
:param rows: iterable of previously saved model instances to archive
:param session: DB session to use for inserts
:param user_id: ID of user responsible for row modifications
:return:
"""
dialect = utils.get_dialect(session)
to_insert_dicts = []
for row in rows:
row_dict = cls.build_row_dict(row, user_id=user_id, dialect=dialect)
to_insert_dicts.append(row_dict)
if len(to_insert_dicts) < chunk_size:
continue
# Insert a batch of rows
session.execute(insert(cls).values(to_insert_dicts))
to_insert_dicts = []
# Insert final batch of rows (if any)
if to_insert_dicts:
session.execute(insert(cls).values(to_insert_dicts))
if commit:
session.commit() | python | def bulk_archive_rows(cls, rows, session, user_id=None, chunk_size=1000, commit=True):
"""
Bulk archives data previously written to DB.
:param rows: iterable of previously saved model instances to archive
:param session: DB session to use for inserts
:param user_id: ID of user responsible for row modifications
:return:
"""
dialect = utils.get_dialect(session)
to_insert_dicts = []
for row in rows:
row_dict = cls.build_row_dict(row, user_id=user_id, dialect=dialect)
to_insert_dicts.append(row_dict)
if len(to_insert_dicts) < chunk_size:
continue
# Insert a batch of rows
session.execute(insert(cls).values(to_insert_dicts))
to_insert_dicts = []
# Insert final batch of rows (if any)
if to_insert_dicts:
session.execute(insert(cls).values(to_insert_dicts))
if commit:
session.commit() | [
"def",
"bulk_archive_rows",
"(",
"cls",
",",
"rows",
",",
"session",
",",
"user_id",
"=",
"None",
",",
"chunk_size",
"=",
"1000",
",",
"commit",
"=",
"True",
")",
":",
"dialect",
"=",
"utils",
".",
"get_dialect",
"(",
"session",
")",
"to_insert_dicts",
"... | Bulk archives data previously written to DB.
:param rows: iterable of previously saved model instances to archive
:param session: DB session to use for inserts
:param user_id: ID of user responsible for row modifications
:return: | [
"Bulk",
"archives",
"data",
"previously",
"written",
"to",
"DB",
"."
] | train | https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/models/__init__.py#L86-L111 |
NerdWalletOSS/savage | src/savage/models/__init__.py | SavageLogMixin._validate | def _validate(cls, engine, *version_cols):
"""
Validates the archive table.
Validates the following criteria:
- all version columns exist in the archive table
- the python types of the user table and archive table columns are the same
- a user_id column exists
- there is a unique constraint on version and the other versioned columns from the
user table
:param engine: instance of :class:`~sqlalchemy.engine.Engine`
:param *version_cols: instances of :class:`~InstrumentedAttribute` from
the user table corresponding to the columns that versioning pivots around
:raises: :class:`~LogTableCreationError`
"""
cls._version_col_names = set()
for version_column_ut in version_cols:
# Make sure all version columns exist on this table
version_col_name = version_column_ut.key
version_column_at = getattr(cls, version_col_name, None)
if not isinstance(version_column_at, InstrumentedAttribute):
raise LogTableCreationError("Log table needs {} column".format(version_col_name))
# Make sure the type of the user table and log table columns are the same
version_col_at_t = version_column_at.property.columns[0].type.__class__
version_col_ut_t = version_column_ut.property.columns[0].type.__class__
if version_col_at_t != version_col_ut_t:
raise LogTableCreationError(
"Type of column {} must match in log and user table".format(version_col_name)
)
cls._version_col_names.add(version_col_name)
# Ensure user added a user_id column
# TODO: should user_id column be optional?
user_id = getattr(cls, 'user_id', None)
if not isinstance(user_id, InstrumentedAttribute):
raise LogTableCreationError("Log table needs user_id column")
# Check the unique constraint on the versioned columns
version_col_names = list(cls._version_col_names) + ['version_id']
if not utils.has_constraint(cls, engine, *version_col_names):
raise LogTableCreationError("There is no unique constraint on the version columns") | python | def _validate(cls, engine, *version_cols):
"""
Validates the archive table.
Validates the following criteria:
- all version columns exist in the archive table
- the python types of the user table and archive table columns are the same
- a user_id column exists
- there is a unique constraint on version and the other versioned columns from the
user table
:param engine: instance of :class:`~sqlalchemy.engine.Engine`
:param *version_cols: instances of :class:`~InstrumentedAttribute` from
the user table corresponding to the columns that versioning pivots around
:raises: :class:`~LogTableCreationError`
"""
cls._version_col_names = set()
for version_column_ut in version_cols:
# Make sure all version columns exist on this table
version_col_name = version_column_ut.key
version_column_at = getattr(cls, version_col_name, None)
if not isinstance(version_column_at, InstrumentedAttribute):
raise LogTableCreationError("Log table needs {} column".format(version_col_name))
# Make sure the type of the user table and log table columns are the same
version_col_at_t = version_column_at.property.columns[0].type.__class__
version_col_ut_t = version_column_ut.property.columns[0].type.__class__
if version_col_at_t != version_col_ut_t:
raise LogTableCreationError(
"Type of column {} must match in log and user table".format(version_col_name)
)
cls._version_col_names.add(version_col_name)
# Ensure user added a user_id column
# TODO: should user_id column be optional?
user_id = getattr(cls, 'user_id', None)
if not isinstance(user_id, InstrumentedAttribute):
raise LogTableCreationError("Log table needs user_id column")
# Check the unique constraint on the versioned columns
version_col_names = list(cls._version_col_names) + ['version_id']
if not utils.has_constraint(cls, engine, *version_col_names):
raise LogTableCreationError("There is no unique constraint on the version columns") | [
"def",
"_validate",
"(",
"cls",
",",
"engine",
",",
"*",
"version_cols",
")",
":",
"cls",
".",
"_version_col_names",
"=",
"set",
"(",
")",
"for",
"version_column_ut",
"in",
"version_cols",
":",
"# Make sure all version columns exist on this table",
"version_col_name",... | Validates the archive table.
Validates the following criteria:
- all version columns exist in the archive table
- the python types of the user table and archive table columns are the same
- a user_id column exists
- there is a unique constraint on version and the other versioned columns from the
user table
:param engine: instance of :class:`~sqlalchemy.engine.Engine`
:param *version_cols: instances of :class:`~InstrumentedAttribute` from
the user table corresponding to the columns that versioning pivots around
:raises: :class:`~LogTableCreationError` | [
"Validates",
"the",
"archive",
"table",
"."
] | train | https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/models/__init__.py#L114-L156 |
NerdWalletOSS/savage | src/savage/models/__init__.py | SavageModelMixin.register | def register(cls, archive_table, engine):
"""
:param archive_table: the model for the users archive table
:param engine: the database engine
:param version_col_names: strings which correspond to columns that versioning will pivot \
around. These columns must have a unique constraint set on them.
"""
version_col_names = cls.version_columns
if not version_col_names:
raise LogTableCreationError('Need to specify version cols in cls.version_columns')
if cls.ignore_columns is None:
cls.ignore_columns = set()
cls.ignore_columns.add('version_id')
version_cols = [getattr(cls, col_name, None) for col_name in version_col_names]
cls._validate(engine, *version_cols)
archive_table._validate(engine, *version_cols)
cls.ArchiveTable = archive_table | python | def register(cls, archive_table, engine):
"""
:param archive_table: the model for the users archive table
:param engine: the database engine
:param version_col_names: strings which correspond to columns that versioning will pivot \
around. These columns must have a unique constraint set on them.
"""
version_col_names = cls.version_columns
if not version_col_names:
raise LogTableCreationError('Need to specify version cols in cls.version_columns')
if cls.ignore_columns is None:
cls.ignore_columns = set()
cls.ignore_columns.add('version_id')
version_cols = [getattr(cls, col_name, None) for col_name in version_col_names]
cls._validate(engine, *version_cols)
archive_table._validate(engine, *version_cols)
cls.ArchiveTable = archive_table | [
"def",
"register",
"(",
"cls",
",",
"archive_table",
",",
"engine",
")",
":",
"version_col_names",
"=",
"cls",
".",
"version_columns",
"if",
"not",
"version_col_names",
":",
"raise",
"LogTableCreationError",
"(",
"'Need to specify version cols in cls.version_columns'",
... | :param archive_table: the model for the users archive table
:param engine: the database engine
:param version_col_names: strings which correspond to columns that versioning will pivot \
around. These columns must have a unique constraint set on them. | [
":",
"param",
"archive_table",
":",
"the",
"model",
"for",
"the",
"users",
"archive",
"table",
":",
"param",
"engine",
":",
"the",
"database",
"engine",
":",
"param",
"version_col_names",
":",
"strings",
"which",
"correspond",
"to",
"columns",
"that",
"version... | train | https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/models/__init__.py#L176-L194 |
NerdWalletOSS/savage | src/savage/models/__init__.py | SavageModelMixin.to_archivable_dict | def to_archivable_dict(self, dialect, use_dirty=True):
"""
:param dialect: a :py:class:`~sqlalchemy.engine.interfaces.Dialect` corresponding to the \
SQL dialect being used.
:param use_dirty: whether to make a dict of the fields as they stand, or the fields \
before the row was updated
:return: a dictionary of key value pairs representing this row.
:rtype: dict
"""
return {
cn: utils.get_column_attribute(self, c, use_dirty=use_dirty, dialect=dialect)
for c, cn in utils.get_column_keys_and_names(self)
if c not in self.ignore_columns
} | python | def to_archivable_dict(self, dialect, use_dirty=True):
"""
:param dialect: a :py:class:`~sqlalchemy.engine.interfaces.Dialect` corresponding to the \
SQL dialect being used.
:param use_dirty: whether to make a dict of the fields as they stand, or the fields \
before the row was updated
:return: a dictionary of key value pairs representing this row.
:rtype: dict
"""
return {
cn: utils.get_column_attribute(self, c, use_dirty=use_dirty, dialect=dialect)
for c, cn in utils.get_column_keys_and_names(self)
if c not in self.ignore_columns
} | [
"def",
"to_archivable_dict",
"(",
"self",
",",
"dialect",
",",
"use_dirty",
"=",
"True",
")",
":",
"return",
"{",
"cn",
":",
"utils",
".",
"get_column_attribute",
"(",
"self",
",",
"c",
",",
"use_dirty",
"=",
"use_dirty",
",",
"dialect",
"=",
"dialect",
... | :param dialect: a :py:class:`~sqlalchemy.engine.interfaces.Dialect` corresponding to the \
SQL dialect being used.
:param use_dirty: whether to make a dict of the fields as they stand, or the fields \
before the row was updated
:return: a dictionary of key value pairs representing this row.
:rtype: dict | [
":",
"param",
"dialect",
":",
"a",
":",
"py",
":",
"class",
":",
"~sqlalchemy",
".",
"engine",
".",
"interfaces",
".",
"Dialect",
"corresponding",
"to",
"the",
"\\",
"SQL",
"dialect",
"being",
"used",
".",
":",
"param",
"use_dirty",
":",
"whether",
"to",... | train | https://github.com/NerdWalletOSS/savage/blob/54f64ac1c912528710365107952967d31d56e60d/src/savage/models/__init__.py#L202-L216 |
CodyKochmann/strict_functions | strict_functions/self_aware.py | self_aware | def self_aware(fn):
''' decorating a function with this allows it to
refer to itself as 'self' inside the function
body.
'''
if isgeneratorfunction(fn):
@wraps(fn)
def wrapper(*a,**k):
generator = fn(*a,**k)
if hasattr(
generator,
'gi_frame'
) and hasattr(
generator.gi_frame,
'f_builtins'
) and hasattr(
generator.gi_frame.f_builtins,
'__setitem__'
):
generator.gi_frame.f_builtins[
'self'
] = generator
return wrapper
else:
fn=strict_globals(**fn.__globals__)(fn)
fn.__globals__['self']=fn
return fn | python | def self_aware(fn):
''' decorating a function with this allows it to
refer to itself as 'self' inside the function
body.
'''
if isgeneratorfunction(fn):
@wraps(fn)
def wrapper(*a,**k):
generator = fn(*a,**k)
if hasattr(
generator,
'gi_frame'
) and hasattr(
generator.gi_frame,
'f_builtins'
) and hasattr(
generator.gi_frame.f_builtins,
'__setitem__'
):
generator.gi_frame.f_builtins[
'self'
] = generator
return wrapper
else:
fn=strict_globals(**fn.__globals__)(fn)
fn.__globals__['self']=fn
return fn | [
"def",
"self_aware",
"(",
"fn",
")",
":",
"if",
"isgeneratorfunction",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"a",
",",
"*",
"*",
"k",
")",
":",
"generator",
"=",
"fn",
"(",
"*",
"a",
",",
"*",
"*",
"k"... | decorating a function with this allows it to
refer to itself as 'self' inside the function
body. | [
"decorating",
"a",
"function",
"with",
"this",
"allows",
"it",
"to",
"refer",
"to",
"itself",
"as",
"self",
"inside",
"the",
"function",
"body",
"."
] | train | https://github.com/CodyKochmann/strict_functions/blob/adaf78084c66929552d80c95f980e7e0c4331478/strict_functions/self_aware.py#L5-L31 |
mozilla/socorrolib | socorrolib/app/fetch_transform_save_app.py | FetchTransformSaveApp._basic_iterator | def _basic_iterator(self):
"""this iterator yields individual crash_ids and/or Nones from the
iterator specified by the "_create_iter" method. Bare values yielded
by the "_create_iter" method get wrapped into an *args, **kwargs form.
That form is then used by the task manager as the arguments to the
worker function."""
for x in self._create_iter():
if x is None or isinstance(x, tuple):
yield x
else:
yield ((x,), {})
self._action_between_each_iteration()
else:
# when the iterator is exhausted, yield None as this is an
# indicator to some of the clients to take an action.
# This is a moribund action, but in this current refactoring
# we don't want to change old behavior
yield None
self._action_after_iteration_completes() | python | def _basic_iterator(self):
"""this iterator yields individual crash_ids and/or Nones from the
iterator specified by the "_create_iter" method. Bare values yielded
by the "_create_iter" method get wrapped into an *args, **kwargs form.
That form is then used by the task manager as the arguments to the
worker function."""
for x in self._create_iter():
if x is None or isinstance(x, tuple):
yield x
else:
yield ((x,), {})
self._action_between_each_iteration()
else:
# when the iterator is exhausted, yield None as this is an
# indicator to some of the clients to take an action.
# This is a moribund action, but in this current refactoring
# we don't want to change old behavior
yield None
self._action_after_iteration_completes() | [
"def",
"_basic_iterator",
"(",
"self",
")",
":",
"for",
"x",
"in",
"self",
".",
"_create_iter",
"(",
")",
":",
"if",
"x",
"is",
"None",
"or",
"isinstance",
"(",
"x",
",",
"tuple",
")",
":",
"yield",
"x",
"else",
":",
"yield",
"(",
"(",
"x",
",",
... | this iterator yields individual crash_ids and/or Nones from the
iterator specified by the "_create_iter" method. Bare values yielded
by the "_create_iter" method get wrapped into an *args, **kwargs form.
That form is then used by the task manager as the arguments to the
worker function. | [
"this",
"iterator",
"yields",
"individual",
"crash_ids",
"and",
"/",
"or",
"Nones",
"from",
"the",
"iterator",
"specified",
"by",
"the",
"_create_iter",
"method",
".",
"Bare",
"values",
"yielded",
"by",
"the",
"_create_iter",
"method",
"get",
"wrapped",
"into",
... | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/app/fetch_transform_save_app.py#L167-L185 |
mozilla/socorrolib | socorrolib/app/fetch_transform_save_app.py | FetchTransformSaveApp._infinite_iterator | def _infinite_iterator(self):
"""this iterator wraps the "_basic_iterator" when the configuration
specifies that the "number_of_submissions" is set to "forever".
Whenever the "_basic_iterator" is exhausted, it is called again to
restart the iteration. It is up to the implementation of the innermost
iterator to define what starting over means. Some iterators may
repeat exactly what they did before, while others may iterate over
new values"""
while True:
for crash_id in self._basic_iterator():
if self._filter_disallowed_values(crash_id):
continue
yield crash_id | python | def _infinite_iterator(self):
"""this iterator wraps the "_basic_iterator" when the configuration
specifies that the "number_of_submissions" is set to "forever".
Whenever the "_basic_iterator" is exhausted, it is called again to
restart the iteration. It is up to the implementation of the innermost
iterator to define what starting over means. Some iterators may
repeat exactly what they did before, while others may iterate over
new values"""
while True:
for crash_id in self._basic_iterator():
if self._filter_disallowed_values(crash_id):
continue
yield crash_id | [
"def",
"_infinite_iterator",
"(",
"self",
")",
":",
"while",
"True",
":",
"for",
"crash_id",
"in",
"self",
".",
"_basic_iterator",
"(",
")",
":",
"if",
"self",
".",
"_filter_disallowed_values",
"(",
"crash_id",
")",
":",
"continue",
"yield",
"crash_id"
] | this iterator wraps the "_basic_iterator" when the configuration
specifies that the "number_of_submissions" is set to "forever".
Whenever the "_basic_iterator" is exhausted, it is called again to
restart the iteration. It is up to the implementation of the innermost
iterator to define what starting over means. Some iterators may
repeat exactly what they did before, while others may iterate over
new values | [
"this",
"iterator",
"wraps",
"the",
"_basic_iterator",
"when",
"the",
"configuration",
"specifies",
"that",
"the",
"number_of_submissions",
"is",
"set",
"to",
"forever",
".",
"Whenever",
"the",
"_basic_iterator",
"is",
"exhausted",
"it",
"is",
"called",
"again",
"... | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/app/fetch_transform_save_app.py#L188-L200 |
mozilla/socorrolib | socorrolib/app/fetch_transform_save_app.py | FetchTransformSaveApp._limited_iterator | def _limited_iterator(self):
"""this is the iterator for the case when "number_of_submissions" is
set to an integer. It goes through the innermost iterator exactly the
number of times specified by "number_of_submissions" To do that, it
might run the innermost iterator to exhaustion. If that happens, that
innermost iterator is called again to start over. It is up to the
implementation of the innermost iteration to define what starting
over means. Some iterators may repeat exactly what they did before,
while others may iterate over new values"""
i = 0
while True:
for crash_id in self._basic_iterator():
if self._filter_disallowed_values(crash_id):
continue
if crash_id is None:
# it's ok to yield None, however, we don't want it to
# be counted as a yielded value
yield crash_id
continue
if i == int(self.config.number_of_submissions):
# break out of inner loop, abandoning the wrapped iter
break
i += 1
yield crash_id
# repeat the quit test, to break out of the outer loop and
# if necessary, prevent recycling the wrapped iter
if i == int(self.config.number_of_submissions):
break | python | def _limited_iterator(self):
"""this is the iterator for the case when "number_of_submissions" is
set to an integer. It goes through the innermost iterator exactly the
number of times specified by "number_of_submissions" To do that, it
might run the innermost iterator to exhaustion. If that happens, that
innermost iterator is called again to start over. It is up to the
implementation of the innermost iteration to define what starting
over means. Some iterators may repeat exactly what they did before,
while others may iterate over new values"""
i = 0
while True:
for crash_id in self._basic_iterator():
if self._filter_disallowed_values(crash_id):
continue
if crash_id is None:
# it's ok to yield None, however, we don't want it to
# be counted as a yielded value
yield crash_id
continue
if i == int(self.config.number_of_submissions):
# break out of inner loop, abandoning the wrapped iter
break
i += 1
yield crash_id
# repeat the quit test, to break out of the outer loop and
# if necessary, prevent recycling the wrapped iter
if i == int(self.config.number_of_submissions):
break | [
"def",
"_limited_iterator",
"(",
"self",
")",
":",
"i",
"=",
"0",
"while",
"True",
":",
"for",
"crash_id",
"in",
"self",
".",
"_basic_iterator",
"(",
")",
":",
"if",
"self",
".",
"_filter_disallowed_values",
"(",
"crash_id",
")",
":",
"continue",
"if",
"... | this is the iterator for the case when "number_of_submissions" is
set to an integer. It goes through the innermost iterator exactly the
number of times specified by "number_of_submissions" To do that, it
might run the innermost iterator to exhaustion. If that happens, that
innermost iterator is called again to start over. It is up to the
implementation of the innermost iteration to define what starting
over means. Some iterators may repeat exactly what they did before,
while others may iterate over new values | [
"this",
"is",
"the",
"iterator",
"for",
"the",
"case",
"when",
"number_of_submissions",
"is",
"set",
"to",
"an",
"integer",
".",
"It",
"goes",
"through",
"the",
"innermost",
"iterator",
"exactly",
"the",
"number",
"of",
"times",
"specified",
"by",
"number_of_s... | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/app/fetch_transform_save_app.py#L214-L241 |
mozilla/socorrolib | socorrolib/app/fetch_transform_save_app.py | FetchTransformSaveApp._transform | def _transform(self, crash_id):
"""this default transform function only transfers raw data from the
source to the destination without changing the data. While this may
be good enough for the raw crashmover, the processor would override
this method to create and save processed crashes"""
try:
raw_crash = self.source.get_raw_crash(crash_id)
except Exception as x:
self.config.logger.error(
"reading raw_crash: %s",
str(x),
exc_info=True
)
raw_crash = {}
try:
dumps = self.source.get_raw_dumps(crash_id)
except Exception as x:
self.config.logger.error(
"reading dump: %s",
str(x),
exc_info=True
)
dumps = {}
try:
self.destination.save_raw_crash(raw_crash, dumps, crash_id)
self.config.logger.info('saved - %s', crash_id)
except Exception as x:
self.config.logger.error(
"writing raw: %s",
str(x),
exc_info=True
)
else:
try:
self.source.remove(crash_id)
except Exception as x:
self.config.logger.error(
"removing raw: %s",
str(x),
exc_info=True
) | python | def _transform(self, crash_id):
"""this default transform function only transfers raw data from the
source to the destination without changing the data. While this may
be good enough for the raw crashmover, the processor would override
this method to create and save processed crashes"""
try:
raw_crash = self.source.get_raw_crash(crash_id)
except Exception as x:
self.config.logger.error(
"reading raw_crash: %s",
str(x),
exc_info=True
)
raw_crash = {}
try:
dumps = self.source.get_raw_dumps(crash_id)
except Exception as x:
self.config.logger.error(
"reading dump: %s",
str(x),
exc_info=True
)
dumps = {}
try:
self.destination.save_raw_crash(raw_crash, dumps, crash_id)
self.config.logger.info('saved - %s', crash_id)
except Exception as x:
self.config.logger.error(
"writing raw: %s",
str(x),
exc_info=True
)
else:
try:
self.source.remove(crash_id)
except Exception as x:
self.config.logger.error(
"removing raw: %s",
str(x),
exc_info=True
) | [
"def",
"_transform",
"(",
"self",
",",
"crash_id",
")",
":",
"try",
":",
"raw_crash",
"=",
"self",
".",
"source",
".",
"get_raw_crash",
"(",
"crash_id",
")",
"except",
"Exception",
"as",
"x",
":",
"self",
".",
"config",
".",
"logger",
".",
"error",
"("... | this default transform function only transfers raw data from the
source to the destination without changing the data. While this may
be good enough for the raw crashmover, the processor would override
this method to create and save processed crashes | [
"this",
"default",
"transform",
"function",
"only",
"transfers",
"raw",
"data",
"from",
"the",
"source",
"to",
"the",
"destination",
"without",
"changing",
"the",
"data",
".",
"While",
"this",
"may",
"be",
"good",
"enough",
"for",
"the",
"raw",
"crashmover",
... | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/app/fetch_transform_save_app.py#L277-L317 |
mozilla/socorrolib | socorrolib/app/fetch_transform_save_app.py | FetchTransformSaveApp._setup_source_and_destination | def _setup_source_and_destination(self):
"""instantiate the classes that implement the source and destination
crash storage systems."""
try:
self.source = self.config.source.crashstorage_class(
self.config.source,
quit_check_callback=self.quit_check
)
except Exception:
self.config.logger.critical(
'Error in creating crash source',
exc_info=True
)
raise
try:
self.destination = self.config.destination.crashstorage_class(
self.config.destination,
quit_check_callback=self.quit_check
)
except Exception:
self.config.logger.critical(
'Error in creating crash destination',
exc_info=True
)
raise | python | def _setup_source_and_destination(self):
"""instantiate the classes that implement the source and destination
crash storage systems."""
try:
self.source = self.config.source.crashstorage_class(
self.config.source,
quit_check_callback=self.quit_check
)
except Exception:
self.config.logger.critical(
'Error in creating crash source',
exc_info=True
)
raise
try:
self.destination = self.config.destination.crashstorage_class(
self.config.destination,
quit_check_callback=self.quit_check
)
except Exception:
self.config.logger.critical(
'Error in creating crash destination',
exc_info=True
)
raise | [
"def",
"_setup_source_and_destination",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"source",
"=",
"self",
".",
"config",
".",
"source",
".",
"crashstorage_class",
"(",
"self",
".",
"config",
".",
"source",
",",
"quit_check_callback",
"=",
"self",
".",
... | instantiate the classes that implement the source and destination
crash storage systems. | [
"instantiate",
"the",
"classes",
"that",
"implement",
"the",
"source",
"and",
"destination",
"crash",
"storage",
"systems",
"."
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/app/fetch_transform_save_app.py#L328-L352 |
mozilla/socorrolib | socorrolib/app/fetch_transform_save_app.py | FetchTransformSaveApp._setup_task_manager | def _setup_task_manager(self):
"""instantiate the threaded task manager to run the producer/consumer
queue that is the heart of the processor."""
self.config.logger.info('installing signal handers')
# set up the signal handler for dealing with SIGTERM. the target should
# be this app instance so the signal handler can reach in and set the
# quit flag to be True. See the 'respond_to_SIGTERM' method for the
# more information
respond_to_SIGTERM_with_logging = partial(
respond_to_SIGTERM,
target=self
)
signal.signal(signal.SIGTERM, respond_to_SIGTERM_with_logging)
self.task_manager = \
self.config.producer_consumer.producer_consumer_class(
self.config.producer_consumer,
job_source_iterator=self.source_iterator,
task_func=self.transform
)
self.config.executor_identity = self.task_manager.executor_identity | python | def _setup_task_manager(self):
"""instantiate the threaded task manager to run the producer/consumer
queue that is the heart of the processor."""
self.config.logger.info('installing signal handers')
# set up the signal handler for dealing with SIGTERM. the target should
# be this app instance so the signal handler can reach in and set the
# quit flag to be True. See the 'respond_to_SIGTERM' method for the
# more information
respond_to_SIGTERM_with_logging = partial(
respond_to_SIGTERM,
target=self
)
signal.signal(signal.SIGTERM, respond_to_SIGTERM_with_logging)
self.task_manager = \
self.config.producer_consumer.producer_consumer_class(
self.config.producer_consumer,
job_source_iterator=self.source_iterator,
task_func=self.transform
)
self.config.executor_identity = self.task_manager.executor_identity | [
"def",
"_setup_task_manager",
"(",
"self",
")",
":",
"self",
".",
"config",
".",
"logger",
".",
"info",
"(",
"'installing signal handers'",
")",
"# set up the signal handler for dealing with SIGTERM. the target should",
"# be this app instance so the signal handler can reach in and... | instantiate the threaded task manager to run the producer/consumer
queue that is the heart of the processor. | [
"instantiate",
"the",
"threaded",
"task",
"manager",
"to",
"run",
"the",
"producer",
"/",
"consumer",
"queue",
"that",
"is",
"the",
"heart",
"of",
"the",
"processor",
"."
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/app/fetch_transform_save_app.py#L355-L374 |
mozilla/socorrolib | socorrolib/app/fetch_transform_save_app.py | FetchTransformSaveApp.main | def main(self):
"""this main routine sets up the signal handlers, the source and
destination crashstorage systems at the theaded task manager. That
starts a flock of threads that are ready to shepherd crashes from
the source to the destination."""
self._setup_task_manager()
self._setup_source_and_destination()
self.task_manager.blocking_start(waiting_func=self.waiting_func)
self.close()
self.config.logger.info('done.') | python | def main(self):
"""this main routine sets up the signal handlers, the source and
destination crashstorage systems at the theaded task manager. That
starts a flock of threads that are ready to shepherd crashes from
the source to the destination."""
self._setup_task_manager()
self._setup_source_and_destination()
self.task_manager.blocking_start(waiting_func=self.waiting_func)
self.close()
self.config.logger.info('done.') | [
"def",
"main",
"(",
"self",
")",
":",
"self",
".",
"_setup_task_manager",
"(",
")",
"self",
".",
"_setup_source_and_destination",
"(",
")",
"self",
".",
"task_manager",
".",
"blocking_start",
"(",
"waiting_func",
"=",
"self",
".",
"waiting_func",
")",
"self",
... | this main routine sets up the signal handlers, the source and
destination crashstorage systems at the theaded task manager. That
starts a flock of threads that are ready to shepherd crashes from
the source to the destination. | [
"this",
"main",
"routine",
"sets",
"up",
"the",
"signal",
"handlers",
"the",
"source",
"and",
"destination",
"crashstorage",
"systems",
"at",
"the",
"theaded",
"task",
"manager",
".",
"That",
"starts",
"a",
"flock",
"of",
"threads",
"that",
"are",
"ready",
"... | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/app/fetch_transform_save_app.py#L390-L400 |
mozilla/socorrolib | socorrolib/app/fetch_transform_save_app.py | FetchTransformSaveWithSeparateNewCrashSourceApp._setup_source_and_destination | def _setup_source_and_destination(self):
"""use the base class to setup the source and destinations but add to
that setup the instantiation of the "new_crash_source" """
super(FetchTransformSaveWithSeparateNewCrashSourceApp, self) \
._setup_source_and_destination()
if self.config.new_crash_source.new_crash_source_class:
self.new_crash_source = \
self.config.new_crash_source.new_crash_source_class(
self.config.new_crash_source,
name=self.app_instance_name,
quit_check_callback=self.quit_check
)
else:
# the configuration failed to provide a "new_crash_source", fall
# back to tying the "new_crash_source" to the "source".
self.new_crash_source = self.source | python | def _setup_source_and_destination(self):
"""use the base class to setup the source and destinations but add to
that setup the instantiation of the "new_crash_source" """
super(FetchTransformSaveWithSeparateNewCrashSourceApp, self) \
._setup_source_and_destination()
if self.config.new_crash_source.new_crash_source_class:
self.new_crash_source = \
self.config.new_crash_source.new_crash_source_class(
self.config.new_crash_source,
name=self.app_instance_name,
quit_check_callback=self.quit_check
)
else:
# the configuration failed to provide a "new_crash_source", fall
# back to tying the "new_crash_source" to the "source".
self.new_crash_source = self.source | [
"def",
"_setup_source_and_destination",
"(",
"self",
")",
":",
"super",
"(",
"FetchTransformSaveWithSeparateNewCrashSourceApp",
",",
"self",
")",
".",
"_setup_source_and_destination",
"(",
")",
"if",
"self",
".",
"config",
".",
"new_crash_source",
".",
"new_crash_source... | use the base class to setup the source and destinations but add to
that setup the instantiation of the "new_crash_source" | [
"use",
"the",
"base",
"class",
"to",
"setup",
"the",
"source",
"and",
"destinations",
"but",
"add",
"to",
"that",
"setup",
"the",
"instantiation",
"of",
"the",
"new_crash_source"
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/app/fetch_transform_save_app.py#L426-L441 |
mixmastamyk/fr | fr/__init__.py | load_config | def load_config(options):
''' Load options, platform, colors, and icons. '''
global opts, pform
opts = options
pform = options.pform
global_ns = globals()
# get colors
if pform.hicolor:
global_ns['dim_templ'] = ansi.dim8t
global_ns['swap_clr_templ'] = ansi.csi8_blk % ansi.blu8
else:
global_ns['dim_templ'] = ansi.dim4t
global_ns['swap_clr_templ'] = ansi.fbblue
# load icons into module namespace
for varname in dir(pform):
if varname.startswith('_') and varname.endswith('ico'):
global_ns[varname] = getattr(pform, varname) | python | def load_config(options):
''' Load options, platform, colors, and icons. '''
global opts, pform
opts = options
pform = options.pform
global_ns = globals()
# get colors
if pform.hicolor:
global_ns['dim_templ'] = ansi.dim8t
global_ns['swap_clr_templ'] = ansi.csi8_blk % ansi.blu8
else:
global_ns['dim_templ'] = ansi.dim4t
global_ns['swap_clr_templ'] = ansi.fbblue
# load icons into module namespace
for varname in dir(pform):
if varname.startswith('_') and varname.endswith('ico'):
global_ns[varname] = getattr(pform, varname) | [
"def",
"load_config",
"(",
"options",
")",
":",
"global",
"opts",
",",
"pform",
"opts",
"=",
"options",
"pform",
"=",
"options",
".",
"pform",
"global_ns",
"=",
"globals",
"(",
")",
"# get colors",
"if",
"pform",
".",
"hicolor",
":",
"global_ns",
"[",
"'... | Load options, platform, colors, and icons. | [
"Load",
"options",
"platform",
"colors",
"and",
"icons",
"."
] | train | https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/__init__.py#L41-L59 |
mixmastamyk/fr | fr/__init__.py | fmtstr | def fmtstr(text='', colorstr=None, align='>', trunc=True, width=0, end=' '):
''' Formats, justifies, and returns a given string according to
specifications.
'''
colwidth = width or opts.colwidth
if trunc:
if len(text) > colwidth:
text = truncstr(text, colwidth, align=trunc) # truncate w/ellipsis
value = f'{text:{align}{colwidth}}'
if opts.incolor and colorstr:
return colorstr % value + end
else:
return value + end | python | def fmtstr(text='', colorstr=None, align='>', trunc=True, width=0, end=' '):
''' Formats, justifies, and returns a given string according to
specifications.
'''
colwidth = width or opts.colwidth
if trunc:
if len(text) > colwidth:
text = truncstr(text, colwidth, align=trunc) # truncate w/ellipsis
value = f'{text:{align}{colwidth}}'
if opts.incolor and colorstr:
return colorstr % value + end
else:
return value + end | [
"def",
"fmtstr",
"(",
"text",
"=",
"''",
",",
"colorstr",
"=",
"None",
",",
"align",
"=",
"'>'",
",",
"trunc",
"=",
"True",
",",
"width",
"=",
"0",
",",
"end",
"=",
"' '",
")",
":",
"colwidth",
"=",
"width",
"or",
"opts",
".",
"colwidth",
"if",
... | Formats, justifies, and returns a given string according to
specifications. | [
"Formats",
"justifies",
"and",
"returns",
"a",
"given",
"string",
"according",
"to",
"specifications",
"."
] | train | https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/__init__.py#L63-L77 |
mixmastamyk/fr | fr/__init__.py | fmtval | def fmtval(value, colorstr=None, precision=None, spacing=True, trunc=True,
end=' '):
''' Formats and returns a given number according to specifications. '''
colwidth = opts.colwidth
# get precision
if precision is None:
precision = opts.precision
fmt = '%%.%sf' % precision
# format with decimal mark, separators
result = locale.format(fmt, value, True)
if spacing:
result = '%%%ss' % colwidth % result
if trunc:
if len(result) > colwidth: # truncate w/ellipsis
result = truncstr(result, colwidth)
# Add color if needed
if opts.incolor and colorstr:
return colorstr % result + end
else:
return result + end | python | def fmtval(value, colorstr=None, precision=None, spacing=True, trunc=True,
end=' '):
''' Formats and returns a given number according to specifications. '''
colwidth = opts.colwidth
# get precision
if precision is None:
precision = opts.precision
fmt = '%%.%sf' % precision
# format with decimal mark, separators
result = locale.format(fmt, value, True)
if spacing:
result = '%%%ss' % colwidth % result
if trunc:
if len(result) > colwidth: # truncate w/ellipsis
result = truncstr(result, colwidth)
# Add color if needed
if opts.incolor and colorstr:
return colorstr % result + end
else:
return result + end | [
"def",
"fmtval",
"(",
"value",
",",
"colorstr",
"=",
"None",
",",
"precision",
"=",
"None",
",",
"spacing",
"=",
"True",
",",
"trunc",
"=",
"True",
",",
"end",
"=",
"' '",
")",
":",
"colwidth",
"=",
"opts",
".",
"colwidth",
"# get precision",
"if",
"... | Formats and returns a given number according to specifications. | [
"Formats",
"and",
"returns",
"a",
"given",
"number",
"according",
"to",
"specifications",
"."
] | train | https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/__init__.py#L80-L103 |
mixmastamyk/fr | fr/__init__.py | get_units | def get_units(unit, binary=False):
''' Sets the output unit and precision for future calculations and returns
an integer and the string representation of it.
'''
result = None
if unit == 'b':
result = 1, 'Byte'
elif binary: # 2^X
if unit == 'k':
result = 1024, 'Kibibyte'
elif unit == 'm':
result = 1048576, 'Mebibyte'
elif unit == 'g':
if opts.precision == -1:
opts.precision = 3
result = 1073741824, 'Gibibyte'
elif unit == 't':
if opts.precision == -1:
opts.precision = 3
result = 1099511627776, 'Tebibyte'
else: # 10^x
if unit == 'k':
result = 1000, 'Kilobyte'
elif unit == 'm':
result = 1000000, 'Megabyte'
elif unit == 'g':
if opts.precision == -1:
opts.precision = 3 # new defaults
result = 1000000000, 'Gigabyte'
elif unit == 't':
if opts.precision == -1:
opts.precision = 3
result = 1000000000000, 'Terabyte'
if not result:
print(f'Warning: incorrect parameter: {unit}.')
result = _outunit
if opts.precision == -1: # auto
opts.precision = 0
return result | python | def get_units(unit, binary=False):
''' Sets the output unit and precision for future calculations and returns
an integer and the string representation of it.
'''
result = None
if unit == 'b':
result = 1, 'Byte'
elif binary: # 2^X
if unit == 'k':
result = 1024, 'Kibibyte'
elif unit == 'm':
result = 1048576, 'Mebibyte'
elif unit == 'g':
if opts.precision == -1:
opts.precision = 3
result = 1073741824, 'Gibibyte'
elif unit == 't':
if opts.precision == -1:
opts.precision = 3
result = 1099511627776, 'Tebibyte'
else: # 10^x
if unit == 'k':
result = 1000, 'Kilobyte'
elif unit == 'm':
result = 1000000, 'Megabyte'
elif unit == 'g':
if opts.precision == -1:
opts.precision = 3 # new defaults
result = 1000000000, 'Gigabyte'
elif unit == 't':
if opts.precision == -1:
opts.precision = 3
result = 1000000000000, 'Terabyte'
if not result:
print(f'Warning: incorrect parameter: {unit}.')
result = _outunit
if opts.precision == -1: # auto
opts.precision = 0
return result | [
"def",
"get_units",
"(",
"unit",
",",
"binary",
"=",
"False",
")",
":",
"result",
"=",
"None",
"if",
"unit",
"==",
"'b'",
":",
"result",
"=",
"1",
",",
"'Byte'",
"elif",
"binary",
":",
"# 2^X",
"if",
"unit",
"==",
"'k'",
":",
"result",
"=",
"1024",... | Sets the output unit and precision for future calculations and returns
an integer and the string representation of it. | [
"Sets",
"the",
"output",
"unit",
"and",
"precision",
"for",
"future",
"calculations",
"and",
"returns",
"an",
"integer",
"and",
"the",
"string",
"representation",
"of",
"it",
"."
] | train | https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/__init__.py#L106-L149 |
mixmastamyk/fr | fr/__init__.py | print_diskinfo | def print_diskinfo(diskinfo, widelayout, incolor):
''' Disk information output function. '''
sep = ' '
if opts.relative:
import math
base = max([ disk.ocap for disk in diskinfo ])
for disk in diskinfo:
if disk.ismntd: ico = _diskico
else: ico = _unmnico
if disk.isrem: ico = _remvico
if disk.isopt: ico = _discico
if disk.isnet: ico = _netwico
if disk.isram: ico = _ramico
if disk.isimg: ico = _imgico
if disk.mntp == '/boot/efi':
ico = _gearico
if opts.relative and disk.ocap and disk.ocap != base:
# increase log size reduction by raising to 4th power:
gwidth = int((math.log(disk.ocap, base)**4) * opts.width)
else:
gwidth = opts.width
# check color settings, ffg: free foreground, ufg: used forground
if disk.rw:
ffg = ufg = None # auto colors
else:
# dim or dark grey
ffg = ufg = (ansi.dim8 if opts.hicolor else ansi.dim4)
cap = disk.cap
if cap and disk.rw:
lblcolor = ansi.get_label_tmpl(disk.pcnt, opts.width, opts.hicolor)
else:
lblcolor = None
# print stats
data = (
(_usedico, disk.pcnt, ufg, None, pform.boldbar), # Used
(_freeico, 100-disk.pcnt, ffg, None, False), # free
)
mntp = fmtstr(disk.mntp, align='<', trunc='left',
width=(opts.colwidth * 2) + 2)
mntp = mntp.rstrip() # prevent wrap
if disk.label is None:
label = fmtstr(_emptico, dim_templ, align='<')
else:
label = fmtstr(disk.label, align='<')
if widelayout:
out(
fmtstr(ico + sep + disk.dev, align='<') + label
)
if cap:
out(fmtval(cap))
if disk.rw:
out(
fmtval(disk.used, lblcolor) +
fmtval(disk.free, lblcolor)
)
else:
out(
fmtstr() +
fmtstr(_emptico, dim_templ)
)
else:
out(fmtstr(_emptico, dim_templ))
if cap:
if disk.rw: # factoring this caused colored brackets
ansi.rainbar(data, gwidth, incolor,
hicolor=opts.hicolor,
cbrackets=_brckico)
else:
ansi.bargraph(data, gwidth, incolor, cbrackets=_brckico)
if opts.relative and opts.width != gwidth:
out(sep * (opts.width - gwidth))
out(sep + mntp)
print()
else:
out(
fmtstr(ico + sep + disk.dev, align="<") + label
)
if cap:
out(
fmtval(cap) +
fmtval(disk.used, lblcolor) +
fmtval(disk.free, lblcolor)
)
else:
out(fmtstr(_emptico, dim_templ) + fmtstr() + fmtstr())
print(sep, mntp)
if cap:
out(fmtstr())
if disk.rw:
ansi.rainbar(data, gwidth, incolor, hicolor=opts.hicolor,
cbrackets=_brckico)
else:
ansi.bargraph(data, gwidth, incolor, cbrackets=_brckico)
print()
print()
print() | python | def print_diskinfo(diskinfo, widelayout, incolor):
''' Disk information output function. '''
sep = ' '
if opts.relative:
import math
base = max([ disk.ocap for disk in diskinfo ])
for disk in diskinfo:
if disk.ismntd: ico = _diskico
else: ico = _unmnico
if disk.isrem: ico = _remvico
if disk.isopt: ico = _discico
if disk.isnet: ico = _netwico
if disk.isram: ico = _ramico
if disk.isimg: ico = _imgico
if disk.mntp == '/boot/efi':
ico = _gearico
if opts.relative and disk.ocap and disk.ocap != base:
# increase log size reduction by raising to 4th power:
gwidth = int((math.log(disk.ocap, base)**4) * opts.width)
else:
gwidth = opts.width
# check color settings, ffg: free foreground, ufg: used forground
if disk.rw:
ffg = ufg = None # auto colors
else:
# dim or dark grey
ffg = ufg = (ansi.dim8 if opts.hicolor else ansi.dim4)
cap = disk.cap
if cap and disk.rw:
lblcolor = ansi.get_label_tmpl(disk.pcnt, opts.width, opts.hicolor)
else:
lblcolor = None
# print stats
data = (
(_usedico, disk.pcnt, ufg, None, pform.boldbar), # Used
(_freeico, 100-disk.pcnt, ffg, None, False), # free
)
mntp = fmtstr(disk.mntp, align='<', trunc='left',
width=(opts.colwidth * 2) + 2)
mntp = mntp.rstrip() # prevent wrap
if disk.label is None:
label = fmtstr(_emptico, dim_templ, align='<')
else:
label = fmtstr(disk.label, align='<')
if widelayout:
out(
fmtstr(ico + sep + disk.dev, align='<') + label
)
if cap:
out(fmtval(cap))
if disk.rw:
out(
fmtval(disk.used, lblcolor) +
fmtval(disk.free, lblcolor)
)
else:
out(
fmtstr() +
fmtstr(_emptico, dim_templ)
)
else:
out(fmtstr(_emptico, dim_templ))
if cap:
if disk.rw: # factoring this caused colored brackets
ansi.rainbar(data, gwidth, incolor,
hicolor=opts.hicolor,
cbrackets=_brckico)
else:
ansi.bargraph(data, gwidth, incolor, cbrackets=_brckico)
if opts.relative and opts.width != gwidth:
out(sep * (opts.width - gwidth))
out(sep + mntp)
print()
else:
out(
fmtstr(ico + sep + disk.dev, align="<") + label
)
if cap:
out(
fmtval(cap) +
fmtval(disk.used, lblcolor) +
fmtval(disk.free, lblcolor)
)
else:
out(fmtstr(_emptico, dim_templ) + fmtstr() + fmtstr())
print(sep, mntp)
if cap:
out(fmtstr())
if disk.rw:
ansi.rainbar(data, gwidth, incolor, hicolor=opts.hicolor,
cbrackets=_brckico)
else:
ansi.bargraph(data, gwidth, incolor, cbrackets=_brckico)
print()
print()
print() | [
"def",
"print_diskinfo",
"(",
"diskinfo",
",",
"widelayout",
",",
"incolor",
")",
":",
"sep",
"=",
"' '",
"if",
"opts",
".",
"relative",
":",
"import",
"math",
"base",
"=",
"max",
"(",
"[",
"disk",
".",
"ocap",
"for",
"disk",
"in",
"diskinfo",
"]",
"... | Disk information output function. | [
"Disk",
"information",
"output",
"function",
"."
] | train | https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/__init__.py#L152-L256 |
mixmastamyk/fr | fr/__init__.py | print_meminfo | def print_meminfo(meminfo, widelayout, incolor):
''' Memory information output function. '''
sep = ' '
# prep Mem numbers
totl = meminfo.memtotal
cach = meminfo.cached + meminfo.buffers
free = meminfo.memfree
used = meminfo.used
usep = float(used) / totl * 100 # % used of total ram
cacp = float(cach) / totl * 100 # % cache
frep = float(free) / totl * 100 # % free
rlblcolor = ansi.get_label_tmpl(usep, opts.width, opts.hicolor)
# Prepare Swap numbers
swpt = meminfo.swaptotal
if swpt:
swpf = meminfo.swapfree
swpc = meminfo.swapcached
swpu = meminfo.swapused
swfp = float(swpf) / swpt * 100 # % free of total sw
swcp = float(swpc) / swpt * 100 # % cache
swup = float(swpu) / swpt * 100 # % used
slblcolor = ansi.get_label_tmpl(swup, opts.width, opts.hicolor)
else:
swpf = swpc = swpu = swfp = swcp = swup = 0 # avoid /0 error
slblcolor = None
cacheico = _usedico if incolor else _cmonico
# print RAM info
data = (
(_usedico, usep, None, None, pform.boldbar), # used
(cacheico, cacp, ansi.blue, None, pform.boldbar), # cache
(_freeico, frep, None, None, False), # free
)
if widelayout:
out(
fmtstr(_ramico + ' RAM', align='<') +
fmtstr() + # volume col
fmtval(totl) +
fmtval(used, rlblcolor) +
fmtval(free, rlblcolor)
)
# print graph
ansi.rainbar(data, opts.width, incolor, hicolor=opts.hicolor,
cbrackets=_brckico)
print('', fmtval(cach, swap_clr_templ))
else:
out(
fmtstr(_ramico + ' RAM', align="<") +
fmtstr() + # volume col
fmtval(totl) +
fmtval(used, rlblcolor) +
fmtval(free, rlblcolor) +
sep + sep +
fmtval(cach, swap_clr_templ) + '\n' +
fmtstr() # blank space
)
# print graph
ansi.rainbar(data, opts.width, incolor, hicolor=opts.hicolor,
cbrackets=_brckico)
print() # extra line in narrow layout
# Swap time:
data = (
(_usedico, swup, None, None, pform.boldbar), # used
(_usedico, swcp, None, None, pform.boldbar), # cache
(_freeico, swfp, None, None, False), # free
)
if widelayout:
out(fmtstr(_diskico + ' SWAP', align='<') + fmtstr()) # label
if swpt:
out(
fmtval(swpt) +
fmtval(swpu, slblcolor) +
fmtval(swpf, slblcolor)
)
else:
print(fmtstr(_emptico, dim_templ))
# print graph
if swpt:
ansi.rainbar(data, opts.width, incolor, hicolor=opts.hicolor,
cbrackets=_brckico)
if swpc:
out(' ' + fmtval(swpc, swap_clr_templ))
print()
else:
out(fmtstr(_diskico + ' SWAP', align='<'))
if swpt:
out(
fmtstr() + # volume col
fmtval(swpt) +
fmtval(swpu, slblcolor) +
fmtval(swpf, slblcolor)
)
if swpc:
out(' ' + fmtval(swpc, swap_clr_templ))
print()
out(fmtstr()) # blank space
# print graph
ansi.rainbar(data, opts.width, incolor, hicolor=opts.hicolor,
cbrackets=_brckico)
print()
else:
print(' ' + fmtstr(_emptico, dim_templ, align='<'))
print()
print() | python | def print_meminfo(meminfo, widelayout, incolor):
''' Memory information output function. '''
sep = ' '
# prep Mem numbers
totl = meminfo.memtotal
cach = meminfo.cached + meminfo.buffers
free = meminfo.memfree
used = meminfo.used
usep = float(used) / totl * 100 # % used of total ram
cacp = float(cach) / totl * 100 # % cache
frep = float(free) / totl * 100 # % free
rlblcolor = ansi.get_label_tmpl(usep, opts.width, opts.hicolor)
# Prepare Swap numbers
swpt = meminfo.swaptotal
if swpt:
swpf = meminfo.swapfree
swpc = meminfo.swapcached
swpu = meminfo.swapused
swfp = float(swpf) / swpt * 100 # % free of total sw
swcp = float(swpc) / swpt * 100 # % cache
swup = float(swpu) / swpt * 100 # % used
slblcolor = ansi.get_label_tmpl(swup, opts.width, opts.hicolor)
else:
swpf = swpc = swpu = swfp = swcp = swup = 0 # avoid /0 error
slblcolor = None
cacheico = _usedico if incolor else _cmonico
# print RAM info
data = (
(_usedico, usep, None, None, pform.boldbar), # used
(cacheico, cacp, ansi.blue, None, pform.boldbar), # cache
(_freeico, frep, None, None, False), # free
)
if widelayout:
out(
fmtstr(_ramico + ' RAM', align='<') +
fmtstr() + # volume col
fmtval(totl) +
fmtval(used, rlblcolor) +
fmtval(free, rlblcolor)
)
# print graph
ansi.rainbar(data, opts.width, incolor, hicolor=opts.hicolor,
cbrackets=_brckico)
print('', fmtval(cach, swap_clr_templ))
else:
out(
fmtstr(_ramico + ' RAM', align="<") +
fmtstr() + # volume col
fmtval(totl) +
fmtval(used, rlblcolor) +
fmtval(free, rlblcolor) +
sep + sep +
fmtval(cach, swap_clr_templ) + '\n' +
fmtstr() # blank space
)
# print graph
ansi.rainbar(data, opts.width, incolor, hicolor=opts.hicolor,
cbrackets=_brckico)
print() # extra line in narrow layout
# Swap time:
data = (
(_usedico, swup, None, None, pform.boldbar), # used
(_usedico, swcp, None, None, pform.boldbar), # cache
(_freeico, swfp, None, None, False), # free
)
if widelayout:
out(fmtstr(_diskico + ' SWAP', align='<') + fmtstr()) # label
if swpt:
out(
fmtval(swpt) +
fmtval(swpu, slblcolor) +
fmtval(swpf, slblcolor)
)
else:
print(fmtstr(_emptico, dim_templ))
# print graph
if swpt:
ansi.rainbar(data, opts.width, incolor, hicolor=opts.hicolor,
cbrackets=_brckico)
if swpc:
out(' ' + fmtval(swpc, swap_clr_templ))
print()
else:
out(fmtstr(_diskico + ' SWAP', align='<'))
if swpt:
out(
fmtstr() + # volume col
fmtval(swpt) +
fmtval(swpu, slblcolor) +
fmtval(swpf, slblcolor)
)
if swpc:
out(' ' + fmtval(swpc, swap_clr_templ))
print()
out(fmtstr()) # blank space
# print graph
ansi.rainbar(data, opts.width, incolor, hicolor=opts.hicolor,
cbrackets=_brckico)
print()
else:
print(' ' + fmtstr(_emptico, dim_templ, align='<'))
print()
print() | [
"def",
"print_meminfo",
"(",
"meminfo",
",",
"widelayout",
",",
"incolor",
")",
":",
"sep",
"=",
"' '",
"# prep Mem numbers",
"totl",
"=",
"meminfo",
".",
"memtotal",
"cach",
"=",
"meminfo",
".",
"cached",
"+",
"meminfo",
".",
"buffers",
"free",
"=",
"memi... | Memory information output function. | [
"Memory",
"information",
"output",
"function",
"."
] | train | https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/__init__.py#L259-L368 |
mixmastamyk/fr | fr/__init__.py | truncstr | def truncstr(text, width, align='right'):
''' Truncate a string, with trailing ellipsis. '''
before = after = ''
if align == 'left':
truncated = text[-width+1:]
before = _ellpico
elif align:
truncated = text[:width-1]
after = _ellpico
return f'{before}{truncated}{after}' | python | def truncstr(text, width, align='right'):
''' Truncate a string, with trailing ellipsis. '''
before = after = ''
if align == 'left':
truncated = text[-width+1:]
before = _ellpico
elif align:
truncated = text[:width-1]
after = _ellpico
return f'{before}{truncated}{after}' | [
"def",
"truncstr",
"(",
"text",
",",
"width",
",",
"align",
"=",
"'right'",
")",
":",
"before",
"=",
"after",
"=",
"''",
"if",
"align",
"==",
"'left'",
":",
"truncated",
"=",
"text",
"[",
"-",
"width",
"+",
"1",
":",
"]",
"before",
"=",
"_ellpico",... | Truncate a string, with trailing ellipsis. | [
"Truncate",
"a",
"string",
"with",
"trailing",
"ellipsis",
"."
] | train | https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/__init__.py#L371-L381 |
COLORFULBOARD/revision | revision/archiver.py | Archiver.archive | def archive(self, target_path=None, zip_path=None):
"""
Writes the Zip-encoded file to a directory.
:param target_path: The directory path to add.
:type target_path: str
:param zip_path: The file path of the ZIP archive.
:type zip_path: str
"""
if target_path:
self.target_path = target_path
if zip_path:
self.zip_path = zip_path
if self.has_path is False or os.path.isdir(self.target_path) is False:
raise RuntimeError("")
zip = zipfile.ZipFile(
self.zip_path,
'w',
zipfile.ZIP_DEFLATED
)
for root, _, files in os.walk(self.target_path):
for file in files:
if file in ARCHIVE_IGNORE_FILES:
continue
current_dir = os.path.relpath(root, self.target_path)
if current_dir == ".":
file_path = file
else:
file_path = os.path.join(current_dir, file)
print("Archive {}".format(file))
zip.write(
os.path.join(root, file),
file_path
)
zip.close() | python | def archive(self, target_path=None, zip_path=None):
"""
Writes the Zip-encoded file to a directory.
:param target_path: The directory path to add.
:type target_path: str
:param zip_path: The file path of the ZIP archive.
:type zip_path: str
"""
if target_path:
self.target_path = target_path
if zip_path:
self.zip_path = zip_path
if self.has_path is False or os.path.isdir(self.target_path) is False:
raise RuntimeError("")
zip = zipfile.ZipFile(
self.zip_path,
'w',
zipfile.ZIP_DEFLATED
)
for root, _, files in os.walk(self.target_path):
for file in files:
if file in ARCHIVE_IGNORE_FILES:
continue
current_dir = os.path.relpath(root, self.target_path)
if current_dir == ".":
file_path = file
else:
file_path = os.path.join(current_dir, file)
print("Archive {}".format(file))
zip.write(
os.path.join(root, file),
file_path
)
zip.close() | [
"def",
"archive",
"(",
"self",
",",
"target_path",
"=",
"None",
",",
"zip_path",
"=",
"None",
")",
":",
"if",
"target_path",
":",
"self",
".",
"target_path",
"=",
"target_path",
"if",
"zip_path",
":",
"self",
".",
"zip_path",
"=",
"zip_path",
"if",
"self... | Writes the Zip-encoded file to a directory.
:param target_path: The directory path to add.
:type target_path: str
:param zip_path: The file path of the ZIP archive.
:type zip_path: str | [
"Writes",
"the",
"Zip",
"-",
"encoded",
"file",
"to",
"a",
"directory",
"."
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/archiver.py#L47-L90 |
COLORFULBOARD/revision | revision/archiver.py | Archiver.unarchive | def unarchive(self, target_path=None, zip_path=None):
"""
Extract the given files to the specified destination.
:param src_path: The destination path where to extract the files.
:type src_path: str
:param zip_path: The file path of the ZIP archive.
:type zip_path: str
"""
if target_path:
self.target_path = target_path
if zip_path:
self.zip_path = zip_path
if self.has_path is False:
raise RuntimeError("")
if os.path.isdir(self.target_path) is False:
os.mkdir(self.target_path)
with zipfile.ZipFile(self.zip_path, 'r') as zip:
zip.extractall(self.target_path) | python | def unarchive(self, target_path=None, zip_path=None):
"""
Extract the given files to the specified destination.
:param src_path: The destination path where to extract the files.
:type src_path: str
:param zip_path: The file path of the ZIP archive.
:type zip_path: str
"""
if target_path:
self.target_path = target_path
if zip_path:
self.zip_path = zip_path
if self.has_path is False:
raise RuntimeError("")
if os.path.isdir(self.target_path) is False:
os.mkdir(self.target_path)
with zipfile.ZipFile(self.zip_path, 'r') as zip:
zip.extractall(self.target_path) | [
"def",
"unarchive",
"(",
"self",
",",
"target_path",
"=",
"None",
",",
"zip_path",
"=",
"None",
")",
":",
"if",
"target_path",
":",
"self",
".",
"target_path",
"=",
"target_path",
"if",
"zip_path",
":",
"self",
".",
"zip_path",
"=",
"zip_path",
"if",
"se... | Extract the given files to the specified destination.
:param src_path: The destination path where to extract the files.
:type src_path: str
:param zip_path: The file path of the ZIP archive.
:type zip_path: str | [
"Extract",
"the",
"given",
"files",
"to",
"the",
"specified",
"destination",
"."
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/archiver.py#L92-L114 |
petebachant/PXL | pxl/styleplot.py | set_sns | def set_sns(style="white", context="paper", font_scale=1.5, color_codes=True,
rc={}):
"""Set default plot style using seaborn.
Font size is set to match the size of the tick labels, rather than the axes
labels.
"""
rcd = {"lines.markersize": 8, "lines.markeredgewidth": 1.25,
"legend.fontsize": "small", "font.size": 12/1.5*font_scale,
"legend.frameon": True, "axes.formatter.limits": (-5, 5),
"axes.grid": True}
rcd.update(rc)
import seaborn as sns
sns.set(style=style, context=context, font_scale=font_scale,
color_codes=color_codes, rc=rcd) | python | def set_sns(style="white", context="paper", font_scale=1.5, color_codes=True,
rc={}):
"""Set default plot style using seaborn.
Font size is set to match the size of the tick labels, rather than the axes
labels.
"""
rcd = {"lines.markersize": 8, "lines.markeredgewidth": 1.25,
"legend.fontsize": "small", "font.size": 12/1.5*font_scale,
"legend.frameon": True, "axes.formatter.limits": (-5, 5),
"axes.grid": True}
rcd.update(rc)
import seaborn as sns
sns.set(style=style, context=context, font_scale=font_scale,
color_codes=color_codes, rc=rcd) | [
"def",
"set_sns",
"(",
"style",
"=",
"\"white\"",
",",
"context",
"=",
"\"paper\"",
",",
"font_scale",
"=",
"1.5",
",",
"color_codes",
"=",
"True",
",",
"rc",
"=",
"{",
"}",
")",
":",
"rcd",
"=",
"{",
"\"lines.markersize\"",
":",
"8",
",",
"\"lines.mar... | Set default plot style using seaborn.
Font size is set to match the size of the tick labels, rather than the axes
labels. | [
"Set",
"default",
"plot",
"style",
"using",
"seaborn",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/styleplot.py#L40-L54 |
petebachant/PXL | pxl/styleplot.py | label_subplot | def label_subplot(ax=None, x=0.5, y=-0.25, text="(a)", **kwargs):
"""Create a subplot label."""
if ax is None:
ax = plt.gca()
ax.text(x=x, y=y, s=text, transform=ax.transAxes,
horizontalalignment="center", verticalalignment="top", **kwargs) | python | def label_subplot(ax=None, x=0.5, y=-0.25, text="(a)", **kwargs):
"""Create a subplot label."""
if ax is None:
ax = plt.gca()
ax.text(x=x, y=y, s=text, transform=ax.transAxes,
horizontalalignment="center", verticalalignment="top", **kwargs) | [
"def",
"label_subplot",
"(",
"ax",
"=",
"None",
",",
"x",
"=",
"0.5",
",",
"y",
"=",
"-",
"0.25",
",",
"text",
"=",
"\"(a)\"",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"ax",
"... | Create a subplot label. | [
"Create",
"a",
"subplot",
"label",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/styleplot.py#L57-L62 |
Kraymer/high | setup.py | coerce_file | def coerce_file(fn):
"""Coerce file content to something useful for setuptools.setup(), turn :
.py into mock object by extracting __special__ attributes values
.md into rst text. Remove images with "[nopypi" alt text and emojis
:url: https://github.com/Kraymer/setupgoon
"""
import ast, os, re, tempfile, time, subprocess # NOQA
text = open(os.path.join(os.path.dirname(__file__), fn)).read()
if fn.endswith('.py'): # extract version, docstring etc out of python file
mock = type('mock', (object,), {})()
for attr in ('version', 'author', 'author_email', 'license', 'url'):
regex = r'^__%s__\s*=\s*[\'"]([^\'"]*)[\'"]$' % attr
m = re.search(regex, text, re.MULTILINE)
setattr(mock, attr, m.group(1) if m else None)
mock.docstring = ast.get_docstring(ast.parse(text))
if mock.version.endswith('dev'):
mock.version += str(int(time.time()))
return mock
if 'upload' in sys.argv and fn.endswith('md'): # convert markdown to rest
text = '\n'.join([l for l in text.split('\n') if '[nopypi' not in l])
text = re.sub(r':\S+:', '', text) # no emojis
with tempfile.NamedTemporaryFile(mode='w+') as tmp:
tmp.write(text)
tmp.flush()
text, stderr = subprocess.Popen(['pandoc', '-t', 'rst', tmp.name],
stdout=subprocess.PIPE).communicate()
return text | python | def coerce_file(fn):
"""Coerce file content to something useful for setuptools.setup(), turn :
.py into mock object by extracting __special__ attributes values
.md into rst text. Remove images with "[nopypi" alt text and emojis
:url: https://github.com/Kraymer/setupgoon
"""
import ast, os, re, tempfile, time, subprocess # NOQA
text = open(os.path.join(os.path.dirname(__file__), fn)).read()
if fn.endswith('.py'): # extract version, docstring etc out of python file
mock = type('mock', (object,), {})()
for attr in ('version', 'author', 'author_email', 'license', 'url'):
regex = r'^__%s__\s*=\s*[\'"]([^\'"]*)[\'"]$' % attr
m = re.search(regex, text, re.MULTILINE)
setattr(mock, attr, m.group(1) if m else None)
mock.docstring = ast.get_docstring(ast.parse(text))
if mock.version.endswith('dev'):
mock.version += str(int(time.time()))
return mock
if 'upload' in sys.argv and fn.endswith('md'): # convert markdown to rest
text = '\n'.join([l for l in text.split('\n') if '[nopypi' not in l])
text = re.sub(r':\S+:', '', text) # no emojis
with tempfile.NamedTemporaryFile(mode='w+') as tmp:
tmp.write(text)
tmp.flush()
text, stderr = subprocess.Popen(['pandoc', '-t', 'rst', tmp.name],
stdout=subprocess.PIPE).communicate()
return text | [
"def",
"coerce_file",
"(",
"fn",
")",
":",
"import",
"ast",
",",
"os",
",",
"re",
",",
"tempfile",
",",
"time",
",",
"subprocess",
"# NOQA",
"text",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"_... | Coerce file content to something useful for setuptools.setup(), turn :
.py into mock object by extracting __special__ attributes values
.md into rst text. Remove images with "[nopypi" alt text and emojis
:url: https://github.com/Kraymer/setupgoon | [
"Coerce",
"file",
"content",
"to",
"something",
"useful",
"for",
"setuptools",
".",
"setup",
"()",
"turn",
":",
".",
"py",
"into",
"mock",
"object",
"by",
"extracting",
"__special__",
"attributes",
"values",
".",
"md",
"into",
"rst",
"text",
".",
"Remove",
... | train | https://github.com/Kraymer/high/blob/11bb86733875ec708264ffb92bf5ef09a9d2f08c/setup.py#L5-L31 |
benley/butcher | butcher/targets/gendeb.py | GenDebSetup.setup_function | def setup_function(self):
"""twitter.comon.app runs this before any global main() function."""
fpm_path = app.get_options().fpm_bin
if not os.path.exists(fpm_path):
log.warn('Could not find fpm; gendeb cannot function.')
else:
GenDebBuilder.fpm_bin = fpm_path | python | def setup_function(self):
"""twitter.comon.app runs this before any global main() function."""
fpm_path = app.get_options().fpm_bin
if not os.path.exists(fpm_path):
log.warn('Could not find fpm; gendeb cannot function.')
else:
GenDebBuilder.fpm_bin = fpm_path | [
"def",
"setup_function",
"(",
"self",
")",
":",
"fpm_path",
"=",
"app",
".",
"get_options",
"(",
")",
".",
"fpm_bin",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fpm_path",
")",
":",
"log",
".",
"warn",
"(",
"'Could not find fpm; gendeb cannot fun... | twitter.comon.app runs this before any global main() function. | [
"twitter",
".",
"comon",
".",
"app",
"runs",
"this",
"before",
"any",
"global",
"main",
"()",
"function",
"."
] | train | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/targets/gendeb.py#L31-L37 |
benley/butcher | butcher/targets/gendeb.py | GenDebBuilder.genchanges | def genchanges(self):
"""Generate a .changes file for this package."""
chparams = self.params.copy()
debpath = os.path.join(self.buildroot, self.rule.output_files[0])
chparams.update({
'fullversion': '{epoch}:{version}-{release}'.format(**chparams),
'metahash': self._metahash().hexdigest(),
'deb_sha1': util.hash_file(debpath, hashlib.sha1()).hexdigest(),
'deb_sha256': util.hash_file(debpath, hashlib.sha256()
).hexdigest(),
'deb_md5': util.hash_file(debpath, hashlib.md5()).hexdigest(),
'deb_bytes': os.stat(debpath).st_size,
# TODO: having to do this split('/')[-1] is absurd:
'deb_filename': debpath.split('/')[-1],
})
output = '\n'.join([
'Format: 1.8',
# Static date string for repeatable builds:
'Date: Tue, 01 Jan 2013 00:00:00 -0700',
'Source: {package_name}',
'Binary: {package_name}',
'Architecture: {arch}',
'Version: {fullversion}',
'Distribution: {distro}',
'Urgency: {urgency}',
'Maintainer: {packager}',
'Description: ',
' {package_name} - {short_description}',
'Changes: ',
' {package_name} ({fullversion}) {distro}; urgency={urgency}',
' .',
' * Built by Butcher - metahash for this build is {metahash}',
'Checksums-Sha1: ',
' {deb_sha1} {deb_bytes} {deb_filename}',
'Checksums-Sha256: ',
' {deb_sha256} {deb_bytes} {deb_filename}',
'Files: ',
' {deb_md5} {deb_bytes} {section} {priority} {deb_filename}',
'' # Newline at end of file.
]).format(**chparams)
return output | python | def genchanges(self):
"""Generate a .changes file for this package."""
chparams = self.params.copy()
debpath = os.path.join(self.buildroot, self.rule.output_files[0])
chparams.update({
'fullversion': '{epoch}:{version}-{release}'.format(**chparams),
'metahash': self._metahash().hexdigest(),
'deb_sha1': util.hash_file(debpath, hashlib.sha1()).hexdigest(),
'deb_sha256': util.hash_file(debpath, hashlib.sha256()
).hexdigest(),
'deb_md5': util.hash_file(debpath, hashlib.md5()).hexdigest(),
'deb_bytes': os.stat(debpath).st_size,
# TODO: having to do this split('/')[-1] is absurd:
'deb_filename': debpath.split('/')[-1],
})
output = '\n'.join([
'Format: 1.8',
# Static date string for repeatable builds:
'Date: Tue, 01 Jan 2013 00:00:00 -0700',
'Source: {package_name}',
'Binary: {package_name}',
'Architecture: {arch}',
'Version: {fullversion}',
'Distribution: {distro}',
'Urgency: {urgency}',
'Maintainer: {packager}',
'Description: ',
' {package_name} - {short_description}',
'Changes: ',
' {package_name} ({fullversion}) {distro}; urgency={urgency}',
' .',
' * Built by Butcher - metahash for this build is {metahash}',
'Checksums-Sha1: ',
' {deb_sha1} {deb_bytes} {deb_filename}',
'Checksums-Sha256: ',
' {deb_sha256} {deb_bytes} {deb_filename}',
'Files: ',
' {deb_md5} {deb_bytes} {section} {priority} {deb_filename}',
'' # Newline at end of file.
]).format(**chparams)
return output | [
"def",
"genchanges",
"(",
"self",
")",
":",
"chparams",
"=",
"self",
".",
"params",
".",
"copy",
"(",
")",
"debpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"buildroot",
",",
"self",
".",
"rule",
".",
"output_files",
"[",
"0",
"]",
... | Generate a .changes file for this package. | [
"Generate",
"a",
".",
"changes",
"file",
"for",
"this",
"package",
"."
] | train | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/targets/gendeb.py#L155-L197 |
benley/butcher | butcher/targets/gendeb.py | GenDeb.validate_args | def validate_args(self):
"""Input validators for this rule type."""
base.BaseTarget.validate_args(self)
params = self.params
if params['extra_control_fields'] is not None:
assert isinstance(params['extra_control_fields'], list), (
'extra_control_fields must be a list of tuples, not %s' % type(
params['extra_control_fields']))
for elem in params['extra_control_fields']:
assert (isinstance(elem, tuple) and len(elem) == 1), (
'extra_control_fields must be a list of 2-element tuples. '
'Invalid contents: %s' % elem)
pkgname_re = '^[a-z][a-z0-9+-.]+'
assert re.match(pkgname_re, params['package_name']), (
'Invalid package name: %s. Must match %s' % (
params['package_name'], pkgname_re)) | python | def validate_args(self):
"""Input validators for this rule type."""
base.BaseTarget.validate_args(self)
params = self.params
if params['extra_control_fields'] is not None:
assert isinstance(params['extra_control_fields'], list), (
'extra_control_fields must be a list of tuples, not %s' % type(
params['extra_control_fields']))
for elem in params['extra_control_fields']:
assert (isinstance(elem, tuple) and len(elem) == 1), (
'extra_control_fields must be a list of 2-element tuples. '
'Invalid contents: %s' % elem)
pkgname_re = '^[a-z][a-z0-9+-.]+'
assert re.match(pkgname_re, params['package_name']), (
'Invalid package name: %s. Must match %s' % (
params['package_name'], pkgname_re)) | [
"def",
"validate_args",
"(",
"self",
")",
":",
"base",
".",
"BaseTarget",
".",
"validate_args",
"(",
"self",
")",
"params",
"=",
"self",
".",
"params",
"if",
"params",
"[",
"'extra_control_fields'",
"]",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(... | Input validators for this rule type. | [
"Input",
"validators",
"for",
"this",
"rule",
"type",
"."
] | train | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/targets/gendeb.py#L270-L285 |
etcher-be/epab | epab/utils/_next_version.py | get_next_version | def get_next_version() -> str:
"""
Returns: next version for this Git repository
"""
LOGGER.info('computing next version')
should_be_alpha = bool(CTX.repo.get_current_branch() != 'master')
LOGGER.info('alpha: %s', should_be_alpha)
calver = _get_calver()
LOGGER.info('current calver: %s', calver)
calver_tags = _get_current_calver_tags(calver)
LOGGER.info('found %s matching tags for this calver', len(calver_tags))
next_stable_version = _next_stable_version(calver, calver_tags)
LOGGER.info('next stable version: %s', next_stable_version)
if should_be_alpha:
return _next_alpha_version(next_stable_version, calver_tags)
return next_stable_version | python | def get_next_version() -> str:
"""
Returns: next version for this Git repository
"""
LOGGER.info('computing next version')
should_be_alpha = bool(CTX.repo.get_current_branch() != 'master')
LOGGER.info('alpha: %s', should_be_alpha)
calver = _get_calver()
LOGGER.info('current calver: %s', calver)
calver_tags = _get_current_calver_tags(calver)
LOGGER.info('found %s matching tags for this calver', len(calver_tags))
next_stable_version = _next_stable_version(calver, calver_tags)
LOGGER.info('next stable version: %s', next_stable_version)
if should_be_alpha:
return _next_alpha_version(next_stable_version, calver_tags)
return next_stable_version | [
"def",
"get_next_version",
"(",
")",
"->",
"str",
":",
"LOGGER",
".",
"info",
"(",
"'computing next version'",
")",
"should_be_alpha",
"=",
"bool",
"(",
"CTX",
".",
"repo",
".",
"get_current_branch",
"(",
")",
"!=",
"'master'",
")",
"LOGGER",
".",
"info",
... | Returns: next version for this Git repository | [
"Returns",
":",
"next",
"version",
"for",
"this",
"Git",
"repository"
] | train | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_next_version.py#L130-L146 |
SYNHAK/spiff | spiff/payment/models.py | LineDiscountItem.value | def value(self):
"""Returns the positive value to subtract from the total."""
originalPrice = self.lineItem.totalPrice
if self.flatRate == 0:
return originalPrice * self.percent
return self.flatRate | python | def value(self):
"""Returns the positive value to subtract from the total."""
originalPrice = self.lineItem.totalPrice
if self.flatRate == 0:
return originalPrice * self.percent
return self.flatRate | [
"def",
"value",
"(",
"self",
")",
":",
"originalPrice",
"=",
"self",
".",
"lineItem",
".",
"totalPrice",
"if",
"self",
".",
"flatRate",
"==",
"0",
":",
"return",
"originalPrice",
"*",
"self",
".",
"percent",
"return",
"self",
".",
"flatRate"
] | Returns the positive value to subtract from the total. | [
"Returns",
"the",
"positive",
"value",
"to",
"subtract",
"from",
"the",
"total",
"."
] | train | https://github.com/SYNHAK/spiff/blob/5e5c731f67954ddc11d2fb75371cfcfd0fef49b7/spiff/payment/models.py#L142-L147 |
azraq27/neural | neural/stats.py | voxel_count | def voxel_count(dset,p=None,positive_only=False,mask=None,ROI=None):
''' returns the number of non-zero voxels
:p: threshold the dataset at the given *p*-value, then count
:positive_only: only count positive values
:mask: count within the given mask
:ROI: only use the ROI with the given value (or list of values) within the mask
if ROI is 'all' then return the voxel count of each ROI
as a dictionary
'''
if p:
dset = nl.thresh(dset,p,positive_only)
else:
if positive_only:
dset = nl.calc(dset,'step(a)')
count = 0
devnull = open(os.devnull,"w")
if mask:
cmd = ['3dROIstats','-1Dformat','-nomeanout','-nobriklab', '-nzvoxels']
cmd += ['-mask',str(mask),str(dset)]
out = subprocess.check_output(cmd,stderr=devnull).split('\n')
if len(out)<4:
return 0
rois = [int(x.replace('NZcount_','')) for x in out[1].strip()[1:].split()]
counts = [int(x.replace('NZcount_','')) for x in out[3].strip().split()]
count_dict = None
if ROI==None:
ROI = rois
if ROI=='all':
count_dict = {}
ROI = rois
else:
if not isinstance(ROI,list):
ROI = [ROI]
for r in ROI:
if r in rois:
roi_count = counts[rois.index(r)]
if count_dict!=None:
count_dict[r] = roi_count
else:
count += roi_count
else:
cmd = ['3dBrickStat', '-slow', '-count', '-non-zero', str(dset)]
count = int(subprocess.check_output(cmd,stderr=devnull).strip())
if count_dict:
return count_dict
return count | python | def voxel_count(dset,p=None,positive_only=False,mask=None,ROI=None):
''' returns the number of non-zero voxels
:p: threshold the dataset at the given *p*-value, then count
:positive_only: only count positive values
:mask: count within the given mask
:ROI: only use the ROI with the given value (or list of values) within the mask
if ROI is 'all' then return the voxel count of each ROI
as a dictionary
'''
if p:
dset = nl.thresh(dset,p,positive_only)
else:
if positive_only:
dset = nl.calc(dset,'step(a)')
count = 0
devnull = open(os.devnull,"w")
if mask:
cmd = ['3dROIstats','-1Dformat','-nomeanout','-nobriklab', '-nzvoxels']
cmd += ['-mask',str(mask),str(dset)]
out = subprocess.check_output(cmd,stderr=devnull).split('\n')
if len(out)<4:
return 0
rois = [int(x.replace('NZcount_','')) for x in out[1].strip()[1:].split()]
counts = [int(x.replace('NZcount_','')) for x in out[3].strip().split()]
count_dict = None
if ROI==None:
ROI = rois
if ROI=='all':
count_dict = {}
ROI = rois
else:
if not isinstance(ROI,list):
ROI = [ROI]
for r in ROI:
if r in rois:
roi_count = counts[rois.index(r)]
if count_dict!=None:
count_dict[r] = roi_count
else:
count += roi_count
else:
cmd = ['3dBrickStat', '-slow', '-count', '-non-zero', str(dset)]
count = int(subprocess.check_output(cmd,stderr=devnull).strip())
if count_dict:
return count_dict
return count | [
"def",
"voxel_count",
"(",
"dset",
",",
"p",
"=",
"None",
",",
"positive_only",
"=",
"False",
",",
"mask",
"=",
"None",
",",
"ROI",
"=",
"None",
")",
":",
"if",
"p",
":",
"dset",
"=",
"nl",
".",
"thresh",
"(",
"dset",
",",
"p",
",",
"positive_onl... | returns the number of non-zero voxels
:p: threshold the dataset at the given *p*-value, then count
:positive_only: only count positive values
:mask: count within the given mask
:ROI: only use the ROI with the given value (or list of values) within the mask
if ROI is 'all' then return the voxel count of each ROI
as a dictionary | [
"returns",
"the",
"number",
"of",
"non",
"-",
"zero",
"voxels"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/stats.py#L13-L60 |
azraq27/neural | neural/stats.py | mask_average | def mask_average(dset,mask):
'''Returns average of voxels in ``dset`` within non-zero voxels of ``mask``'''
o = nl.run(['3dmaskave','-q','-mask',mask,dset])
if o:
return float(o.output.split()[-1]) | python | def mask_average(dset,mask):
'''Returns average of voxels in ``dset`` within non-zero voxels of ``mask``'''
o = nl.run(['3dmaskave','-q','-mask',mask,dset])
if o:
return float(o.output.split()[-1]) | [
"def",
"mask_average",
"(",
"dset",
",",
"mask",
")",
":",
"o",
"=",
"nl",
".",
"run",
"(",
"[",
"'3dmaskave'",
",",
"'-q'",
",",
"'-mask'",
",",
"mask",
",",
"dset",
"]",
")",
"if",
"o",
":",
"return",
"float",
"(",
"o",
".",
"output",
".",
"s... | Returns average of voxels in ``dset`` within non-zero voxels of ``mask`` | [
"Returns",
"average",
"of",
"voxels",
"in",
"dset",
"within",
"non",
"-",
"zero",
"voxels",
"of",
"mask"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/stats.py#L62-L66 |
azraq27/neural | neural/stats.py | sphere_average | def sphere_average(dset,x,y,z,radius=1):
'''returns a list of average values (one for each subbrick/time point) within the coordinate ``(x,y,z)`` (in RAI order) using a sphere of radius ``radius`` in ``dset``'''
return_list = []
if isinstance(dset,basestring):
dset = [dset]
for d in dset:
return_list += [float(a) for a in subprocess.check_output(['3dmaskave','-q','-dball',str(x),str(y),str(z),str(radius),d],stderr=subprocess.PIPE).split()]
return return_list | python | def sphere_average(dset,x,y,z,radius=1):
'''returns a list of average values (one for each subbrick/time point) within the coordinate ``(x,y,z)`` (in RAI order) using a sphere of radius ``radius`` in ``dset``'''
return_list = []
if isinstance(dset,basestring):
dset = [dset]
for d in dset:
return_list += [float(a) for a in subprocess.check_output(['3dmaskave','-q','-dball',str(x),str(y),str(z),str(radius),d],stderr=subprocess.PIPE).split()]
return return_list | [
"def",
"sphere_average",
"(",
"dset",
",",
"x",
",",
"y",
",",
"z",
",",
"radius",
"=",
"1",
")",
":",
"return_list",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"dset",
",",
"basestring",
")",
":",
"dset",
"=",
"[",
"dset",
"]",
"for",
"d",
"in",
... | returns a list of average values (one for each subbrick/time point) within the coordinate ``(x,y,z)`` (in RAI order) using a sphere of radius ``radius`` in ``dset`` | [
"returns",
"a",
"list",
"of",
"average",
"values",
"(",
"one",
"for",
"each",
"subbrick",
"/",
"time",
"point",
")",
"within",
"the",
"coordinate",
"(",
"x",
"y",
"z",
")",
"(",
"in",
"RAI",
"order",
")",
"using",
"a",
"sphere",
"of",
"radius",
"radi... | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/stats.py#L68-L75 |
peterpakos/ppipa | ppipa/freeipauser.py | FreeIPAUser.is_member_of | def is_member_of(self, group_name):
"""Return True if member of LDAP group, otherwise return False"""
group_dn = 'cn=%s,cn=groups,cn=accounts,%s' % (group_name, self._base_dn)
if str(group_dn).lower() in [str(i).lower() for i in self.member_of]:
return True
else:
return False | python | def is_member_of(self, group_name):
"""Return True if member of LDAP group, otherwise return False"""
group_dn = 'cn=%s,cn=groups,cn=accounts,%s' % (group_name, self._base_dn)
if str(group_dn).lower() in [str(i).lower() for i in self.member_of]:
return True
else:
return False | [
"def",
"is_member_of",
"(",
"self",
",",
"group_name",
")",
":",
"group_dn",
"=",
"'cn=%s,cn=groups,cn=accounts,%s'",
"%",
"(",
"group_name",
",",
"self",
".",
"_base_dn",
")",
"if",
"str",
"(",
"group_dn",
")",
".",
"lower",
"(",
")",
"in",
"[",
"str",
... | Return True if member of LDAP group, otherwise return False | [
"Return",
"True",
"if",
"member",
"of",
"LDAP",
"group",
"otherwise",
"return",
"False"
] | train | https://github.com/peterpakos/ppipa/blob/cc7565fe9afa079437cccfaf8d6b8c3da3f080ee/ppipa/freeipauser.py#L111-L117 |
peterpakos/ppipa | ppipa/freeipauser.py | FreeIPAUser._get_attr_list | def _get_attr_list(self, attr):
"""Return user's attribute/attributes"""
a = self._attrs.get(attr)
if not a:
return []
if type(a) is list:
r = [i.decode('utf-8', 'ignore') for i in a]
else:
r = [a.decode('utf-8', 'ignore')]
return r | python | def _get_attr_list(self, attr):
"""Return user's attribute/attributes"""
a = self._attrs.get(attr)
if not a:
return []
if type(a) is list:
r = [i.decode('utf-8', 'ignore') for i in a]
else:
r = [a.decode('utf-8', 'ignore')]
return r | [
"def",
"_get_attr_list",
"(",
"self",
",",
"attr",
")",
":",
"a",
"=",
"self",
".",
"_attrs",
".",
"get",
"(",
"attr",
")",
"if",
"not",
"a",
":",
"return",
"[",
"]",
"if",
"type",
"(",
"a",
")",
"is",
"list",
":",
"r",
"=",
"[",
"i",
".",
... | Return user's attribute/attributes | [
"Return",
"user",
"s",
"attribute",
"/",
"attributes"
] | train | https://github.com/peterpakos/ppipa/blob/cc7565fe9afa079437cccfaf8d6b8c3da3f080ee/ppipa/freeipauser.py#L119-L128 |
oblalex/verboselib | verboselib/helpers.py | to_locale | def to_locale(language, to_lower=False):
"""
Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is
True, the last component is lower-cased (en_us).
Taken `from Django <http://bit.ly/1ssrxqE>`_.
"""
p = language.find('-')
if p >= 0:
if to_lower:
return language[:p].lower() + '_' + language[p + 1:].lower()
else:
# Get correct locale for sr-latn
if len(language[p + 1:]) > 2:
locale = language[:p].lower() + '_' + language[p + 1].upper()
return locale + language[p + 2:].lower()
return language[:p].lower() + '_' + language[p + 1:].upper()
else:
return language.lower() | python | def to_locale(language, to_lower=False):
"""
Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is
True, the last component is lower-cased (en_us).
Taken `from Django <http://bit.ly/1ssrxqE>`_.
"""
p = language.find('-')
if p >= 0:
if to_lower:
return language[:p].lower() + '_' + language[p + 1:].lower()
else:
# Get correct locale for sr-latn
if len(language[p + 1:]) > 2:
locale = language[:p].lower() + '_' + language[p + 1].upper()
return locale + language[p + 2:].lower()
return language[:p].lower() + '_' + language[p + 1:].upper()
else:
return language.lower() | [
"def",
"to_locale",
"(",
"language",
",",
"to_lower",
"=",
"False",
")",
":",
"p",
"=",
"language",
".",
"find",
"(",
"'-'",
")",
"if",
"p",
">=",
"0",
":",
"if",
"to_lower",
":",
"return",
"language",
"[",
":",
"p",
"]",
".",
"lower",
"(",
")",
... | Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is
True, the last component is lower-cased (en_us).
Taken `from Django <http://bit.ly/1ssrxqE>`_. | [
"Turns",
"a",
"language",
"name",
"(",
"en",
"-",
"us",
")",
"into",
"a",
"locale",
"name",
"(",
"en_US",
")",
".",
"If",
"to_lower",
"is",
"True",
"the",
"last",
"component",
"is",
"lower",
"-",
"cased",
"(",
"en_us",
")",
"."
] | train | https://github.com/oblalex/verboselib/blob/3c108bef060b091e1f7c08861ab07672c87ddcff/verboselib/helpers.py#L6-L24 |
oblalex/verboselib | verboselib/helpers.py | to_language | def to_language(locale):
"""
Turns a locale name (en_US) into a language name (en-us).
Taken `from Django <http://bit.ly/1vWACbE>`_.
"""
p = locale.find('_')
if p >= 0:
return locale[:p].lower() + '-' + locale[p + 1:].lower()
else:
return locale.lower() | python | def to_language(locale):
"""
Turns a locale name (en_US) into a language name (en-us).
Taken `from Django <http://bit.ly/1vWACbE>`_.
"""
p = locale.find('_')
if p >= 0:
return locale[:p].lower() + '-' + locale[p + 1:].lower()
else:
return locale.lower() | [
"def",
"to_language",
"(",
"locale",
")",
":",
"p",
"=",
"locale",
".",
"find",
"(",
"'_'",
")",
"if",
"p",
">=",
"0",
":",
"return",
"locale",
"[",
":",
"p",
"]",
".",
"lower",
"(",
")",
"+",
"'-'",
"+",
"locale",
"[",
"p",
"+",
"1",
":",
... | Turns a locale name (en_US) into a language name (en-us).
Taken `from Django <http://bit.ly/1vWACbE>`_. | [
"Turns",
"a",
"locale",
"name",
"(",
"en_US",
")",
"into",
"a",
"language",
"name",
"(",
"en",
"-",
"us",
")",
"."
] | train | https://github.com/oblalex/verboselib/blob/3c108bef060b091e1f7c08861ab07672c87ddcff/verboselib/helpers.py#L27-L37 |
Synerty/peek-plugin-base | peek_plugin_base/storage/DbConnection.py | _commonPrefetchDeclarativeIds | def _commonPrefetchDeclarativeIds(engine, mutex,
Declarative, count) -> Optional[Iterable[int]]:
""" Common Prefetch Declarative IDs
This function is used by the worker and server
"""
if not count:
logger.debug("Count was zero, no range returned")
return
conn = engine.connect()
transaction = conn.begin()
mutex.acquire()
try:
sequence = Sequence('%s_id_seq' % Declarative.__tablename__,
schema=Declarative.metadata.schema)
if isPostGreSQLDialect(engine):
sql = "SELECT setval('%(seq)s', (select nextval('%(seq)s') + %(add)s), true)"
sql %= {
'seq': '"%s"."%s"' % (sequence.schema, sequence.name),
'add': count
}
nextStartId = conn.execute(sql).fetchone()[0]
startId = nextStartId - count
elif isMssqlDialect(engine):
startId = conn.execute(
'SELECT NEXT VALUE FOR "%s"."%s"'
% (sequence.schema, sequence.name)
).fetchone()[0] + 1
nextStartId = startId + count
conn.execute('alter sequence "%s"."%s" restart with %s'
% (sequence.schema, sequence.name, nextStartId))
else:
raise NotImplementedError()
transaction.commit()
return iter(range(startId, nextStartId))
finally:
mutex.release()
conn.close() | python | def _commonPrefetchDeclarativeIds(engine, mutex,
Declarative, count) -> Optional[Iterable[int]]:
""" Common Prefetch Declarative IDs
This function is used by the worker and server
"""
if not count:
logger.debug("Count was zero, no range returned")
return
conn = engine.connect()
transaction = conn.begin()
mutex.acquire()
try:
sequence = Sequence('%s_id_seq' % Declarative.__tablename__,
schema=Declarative.metadata.schema)
if isPostGreSQLDialect(engine):
sql = "SELECT setval('%(seq)s', (select nextval('%(seq)s') + %(add)s), true)"
sql %= {
'seq': '"%s"."%s"' % (sequence.schema, sequence.name),
'add': count
}
nextStartId = conn.execute(sql).fetchone()[0]
startId = nextStartId - count
elif isMssqlDialect(engine):
startId = conn.execute(
'SELECT NEXT VALUE FOR "%s"."%s"'
% (sequence.schema, sequence.name)
).fetchone()[0] + 1
nextStartId = startId + count
conn.execute('alter sequence "%s"."%s" restart with %s'
% (sequence.schema, sequence.name, nextStartId))
else:
raise NotImplementedError()
transaction.commit()
return iter(range(startId, nextStartId))
finally:
mutex.release()
conn.close() | [
"def",
"_commonPrefetchDeclarativeIds",
"(",
"engine",
",",
"mutex",
",",
"Declarative",
",",
"count",
")",
"->",
"Optional",
"[",
"Iterable",
"[",
"int",
"]",
"]",
":",
"if",
"not",
"count",
":",
"logger",
".",
"debug",
"(",
"\"Count was zero, no range return... | Common Prefetch Declarative IDs
This function is used by the worker and server | [
"Common",
"Prefetch",
"Declarative",
"IDs"
] | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/DbConnection.py#L221-L267 |
Synerty/peek-plugin-base | peek_plugin_base/storage/DbConnection.py | DbConnection.ormSessionCreator | def ormSessionCreator(self) -> DbSessionCreator:
""" Get Orm Session
:return: A SQLAlchemy session scoped for the callers thread..
"""
assert self._dbConnectString
if self._ScopedSession:
return self._ScopedSession
self._dbEngine = create_engine(
self._dbConnectString,
**self._dbEngineArgs
)
self._ScopedSession = scoped_session(
sessionmaker(bind=self._dbEngine))
return self._ScopedSession | python | def ormSessionCreator(self) -> DbSessionCreator:
""" Get Orm Session
:return: A SQLAlchemy session scoped for the callers thread..
"""
assert self._dbConnectString
if self._ScopedSession:
return self._ScopedSession
self._dbEngine = create_engine(
self._dbConnectString,
**self._dbEngineArgs
)
self._ScopedSession = scoped_session(
sessionmaker(bind=self._dbEngine))
return self._ScopedSession | [
"def",
"ormSessionCreator",
"(",
"self",
")",
"->",
"DbSessionCreator",
":",
"assert",
"self",
".",
"_dbConnectString",
"if",
"self",
".",
"_ScopedSession",
":",
"return",
"self",
".",
"_ScopedSession",
"self",
".",
"_dbEngine",
"=",
"create_engine",
"(",
"self"... | Get Orm Session
:return: A SQLAlchemy session scoped for the callers thread.. | [
"Get",
"Orm",
"Session"
] | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/DbConnection.py#L82-L100 |
Synerty/peek-plugin-base | peek_plugin_base/storage/DbConnection.py | DbConnection.migrate | def migrate(self) -> None:
""" Migrate
Perform a database migration, upgrading to the latest schema level.
"""
assert self.ormSessionCreator, "ormSessionCreator is not defined"
connection = self._dbEngine.connect()
isDbInitialised = self._dbEngine.dialect.has_table(
connection, 'alembic_version',
schema=self._metadata.schema)
connection.close()
if isDbInitialised or not self._enableCreateAll:
self._doMigration(self._dbEngine)
else:
self._doCreateAll(self._dbEngine)
if self._enableForeignKeys:
self.checkForeignKeys(self._dbEngine) | python | def migrate(self) -> None:
""" Migrate
Perform a database migration, upgrading to the latest schema level.
"""
assert self.ormSessionCreator, "ormSessionCreator is not defined"
connection = self._dbEngine.connect()
isDbInitialised = self._dbEngine.dialect.has_table(
connection, 'alembic_version',
schema=self._metadata.schema)
connection.close()
if isDbInitialised or not self._enableCreateAll:
self._doMigration(self._dbEngine)
else:
self._doCreateAll(self._dbEngine)
if self._enableForeignKeys:
self.checkForeignKeys(self._dbEngine) | [
"def",
"migrate",
"(",
"self",
")",
"->",
"None",
":",
"assert",
"self",
".",
"ormSessionCreator",
",",
"\"ormSessionCreator is not defined\"",
"connection",
"=",
"self",
".",
"_dbEngine",
".",
"connect",
"(",
")",
"isDbInitialised",
"=",
"self",
".",
"_dbEngine... | Migrate
Perform a database migration, upgrading to the latest schema level. | [
"Migrate"
] | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/DbConnection.py#L114-L135 |
Synerty/peek-plugin-base | peek_plugin_base/storage/DbConnection.py | DbConnection.checkForeignKeys | def checkForeignKeys(self, engine: Engine) -> None:
""" Check Foreign Keys
Log any foreign keys that don't have indexes assigned to them.
This is a performance issue.
"""
missing = (sqlalchemy_utils.functions
.non_indexed_foreign_keys(self._metadata, engine=engine))
for table, keys in missing.items():
for key in keys:
logger.warning("Missing index on ForeignKey %s" % key.columns) | python | def checkForeignKeys(self, engine: Engine) -> None:
""" Check Foreign Keys
Log any foreign keys that don't have indexes assigned to them.
This is a performance issue.
"""
missing = (sqlalchemy_utils.functions
.non_indexed_foreign_keys(self._metadata, engine=engine))
for table, keys in missing.items():
for key in keys:
logger.warning("Missing index on ForeignKey %s" % key.columns) | [
"def",
"checkForeignKeys",
"(",
"self",
",",
"engine",
":",
"Engine",
")",
"->",
"None",
":",
"missing",
"=",
"(",
"sqlalchemy_utils",
".",
"functions",
".",
"non_indexed_foreign_keys",
"(",
"self",
".",
"_metadata",
",",
"engine",
"=",
"engine",
")",
")",
... | Check Foreign Keys
Log any foreign keys that don't have indexes assigned to them.
This is a performance issue. | [
"Check",
"Foreign",
"Keys"
] | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/DbConnection.py#L137-L149 |
Synerty/peek-plugin-base | peek_plugin_base/storage/DbConnection.py | DbConnection.prefetchDeclarativeIds | def prefetchDeclarativeIds(self, Declarative, count) -> DelcarativeIdGen:
""" Prefetch Declarative IDs
This function prefetches a chunk of IDs from a database sequence.
Doing this allows us to preallocate the IDs before an insert, which significantly
speeds up :
* Orm inserts, especially those using inheritance
* When we need the ID to assign it to a related object that we're also inserting.
:param Declarative: The SQLAlchemy declarative class.
(The class that inherits from DeclarativeBase)
:param count: The number of IDs to prefetch
:return: An iterable that dispenses the new IDs
"""
return _commonPrefetchDeclarativeIds(
self.dbEngine, self._sequenceMutex, Declarative, count
) | python | def prefetchDeclarativeIds(self, Declarative, count) -> DelcarativeIdGen:
""" Prefetch Declarative IDs
This function prefetches a chunk of IDs from a database sequence.
Doing this allows us to preallocate the IDs before an insert, which significantly
speeds up :
* Orm inserts, especially those using inheritance
* When we need the ID to assign it to a related object that we're also inserting.
:param Declarative: The SQLAlchemy declarative class.
(The class that inherits from DeclarativeBase)
:param count: The number of IDs to prefetch
:return: An iterable that dispenses the new IDs
"""
return _commonPrefetchDeclarativeIds(
self.dbEngine, self._sequenceMutex, Declarative, count
) | [
"def",
"prefetchDeclarativeIds",
"(",
"self",
",",
"Declarative",
",",
"count",
")",
"->",
"DelcarativeIdGen",
":",
"return",
"_commonPrefetchDeclarativeIds",
"(",
"self",
".",
"dbEngine",
",",
"self",
".",
"_sequenceMutex",
",",
"Declarative",
",",
"count",
")"
] | Prefetch Declarative IDs
This function prefetches a chunk of IDs from a database sequence.
Doing this allows us to preallocate the IDs before an insert, which significantly
speeds up :
* Orm inserts, especially those using inheritance
* When we need the ID to assign it to a related object that we're also inserting.
:param Declarative: The SQLAlchemy declarative class.
(The class that inherits from DeclarativeBase)
:param count: The number of IDs to prefetch
:return: An iterable that dispenses the new IDs | [
"Prefetch",
"Declarative",
"IDs"
] | train | https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/storage/DbConnection.py#L152-L171 |
etcher-be/epab | epab/cmd/_chglog.py | temporary_tag | def temporary_tag(tag):
"""
Temporarily tags the repo
"""
if tag:
CTX.repo.tag(tag)
try:
yield
finally:
if tag:
CTX.repo.remove_tag(tag) | python | def temporary_tag(tag):
"""
Temporarily tags the repo
"""
if tag:
CTX.repo.tag(tag)
try:
yield
finally:
if tag:
CTX.repo.remove_tag(tag) | [
"def",
"temporary_tag",
"(",
"tag",
")",
":",
"if",
"tag",
":",
"CTX",
".",
"repo",
".",
"tag",
"(",
"tag",
")",
"try",
":",
"yield",
"finally",
":",
"if",
"tag",
":",
"CTX",
".",
"repo",
".",
"remove_tag",
"(",
"tag",
")"
] | Temporarily tags the repo | [
"Temporarily",
"tags",
"the",
"repo"
] | train | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/cmd/_chglog.py#L53-L63 |
etcher-be/epab | epab/cmd/_chglog.py | _chglog | def _chglog(amend: bool = False, stage: bool = False, next_version: str = None, auto_next_version: bool = False):
"""
Writes the changelog
Args:
amend: amend last commit with changes
stage: stage changes
"""
if config.CHANGELOG_DISABLE():
LOGGER.info('skipping changelog update as per config')
else:
epab.utils.ensure_exe('git')
epab.utils.ensure_exe('gitchangelog')
LOGGER.info('writing changelog')
if auto_next_version:
next_version = epab.utils.get_next_version()
with gitchangelog_config():
with temporary_tag(next_version):
changelog, _ = elib_run.run('gitchangelog', mute=True)
# changelog = changelog.encode('utf8').replace(b'\r\n', b'\n').decode('utf8')
changelog = re.sub(BOGUS_LINE_PATTERN, '\\1\n', changelog)
Path(config.CHANGELOG_FILE_PATH()).write_text(changelog, encoding='utf8')
if amend:
CTX.repo.amend_commit(
append_to_msg='update changelog [auto]', files_to_add=str(config.CHANGELOG_FILE_PATH())
)
elif stage:
CTX.repo.stage_subset(str(config.CHANGELOG_FILE_PATH())) | python | def _chglog(amend: bool = False, stage: bool = False, next_version: str = None, auto_next_version: bool = False):
"""
Writes the changelog
Args:
amend: amend last commit with changes
stage: stage changes
"""
if config.CHANGELOG_DISABLE():
LOGGER.info('skipping changelog update as per config')
else:
epab.utils.ensure_exe('git')
epab.utils.ensure_exe('gitchangelog')
LOGGER.info('writing changelog')
if auto_next_version:
next_version = epab.utils.get_next_version()
with gitchangelog_config():
with temporary_tag(next_version):
changelog, _ = elib_run.run('gitchangelog', mute=True)
# changelog = changelog.encode('utf8').replace(b'\r\n', b'\n').decode('utf8')
changelog = re.sub(BOGUS_LINE_PATTERN, '\\1\n', changelog)
Path(config.CHANGELOG_FILE_PATH()).write_text(changelog, encoding='utf8')
if amend:
CTX.repo.amend_commit(
append_to_msg='update changelog [auto]', files_to_add=str(config.CHANGELOG_FILE_PATH())
)
elif stage:
CTX.repo.stage_subset(str(config.CHANGELOG_FILE_PATH())) | [
"def",
"_chglog",
"(",
"amend",
":",
"bool",
"=",
"False",
",",
"stage",
":",
"bool",
"=",
"False",
",",
"next_version",
":",
"str",
"=",
"None",
",",
"auto_next_version",
":",
"bool",
"=",
"False",
")",
":",
"if",
"config",
".",
"CHANGELOG_DISABLE",
"... | Writes the changelog
Args:
amend: amend last commit with changes
stage: stage changes | [
"Writes",
"the",
"changelog"
] | train | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/cmd/_chglog.py#L69-L96 |
etcher-be/epab | epab/cmd/_chglog.py | chglog | def chglog(amend: bool = False, stage: bool = False, next_version: str = None, auto_next_version: bool = False):
"""
Writes the changelog
Args:
amend: amend last commit with changes
stage: stage changes
next_version: indicates next version
auto_next_version: infer next version from VCS
"""
changed_files = CTX.repo.changed_files()
changelog_file_path: Path = config.CHANGELOG_FILE_PATH()
changelog_file_name = changelog_file_path.name
if changelog_file_name in changed_files:
LOGGER.error('changelog has changed; cannot update it')
exit(-1)
_chglog(amend, stage, next_version, auto_next_version) | python | def chglog(amend: bool = False, stage: bool = False, next_version: str = None, auto_next_version: bool = False):
"""
Writes the changelog
Args:
amend: amend last commit with changes
stage: stage changes
next_version: indicates next version
auto_next_version: infer next version from VCS
"""
changed_files = CTX.repo.changed_files()
changelog_file_path: Path = config.CHANGELOG_FILE_PATH()
changelog_file_name = changelog_file_path.name
if changelog_file_name in changed_files:
LOGGER.error('changelog has changed; cannot update it')
exit(-1)
_chglog(amend, stage, next_version, auto_next_version) | [
"def",
"chglog",
"(",
"amend",
":",
"bool",
"=",
"False",
",",
"stage",
":",
"bool",
"=",
"False",
",",
"next_version",
":",
"str",
"=",
"None",
",",
"auto_next_version",
":",
"bool",
"=",
"False",
")",
":",
"changed_files",
"=",
"CTX",
".",
"repo",
... | Writes the changelog
Args:
amend: amend last commit with changes
stage: stage changes
next_version: indicates next version
auto_next_version: infer next version from VCS | [
"Writes",
"the",
"changelog"
] | train | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/cmd/_chglog.py#L104-L120 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/git.py | Git.check_rev_options | def check_rev_options(self, rev, dest, rev_options):
"""Check the revision options before checkout to compensate that tags
and branches may need origin/ as a prefix.
Returns the SHA1 of the branch or tag if found.
"""
revisions = self.get_tag_revs(dest)
revisions.update(self.get_branch_revs(dest))
origin_rev = 'origin/%s' % rev
if origin_rev in revisions:
# remote branch
return [revisions[origin_rev]]
elif rev in revisions:
# a local tag or branch name
return [revisions[rev]]
else:
logger.warn("Could not find a tag or branch '%s', assuming commit." % rev)
return rev_options | python | def check_rev_options(self, rev, dest, rev_options):
"""Check the revision options before checkout to compensate that tags
and branches may need origin/ as a prefix.
Returns the SHA1 of the branch or tag if found.
"""
revisions = self.get_tag_revs(dest)
revisions.update(self.get_branch_revs(dest))
origin_rev = 'origin/%s' % rev
if origin_rev in revisions:
# remote branch
return [revisions[origin_rev]]
elif rev in revisions:
# a local tag or branch name
return [revisions[rev]]
else:
logger.warn("Could not find a tag or branch '%s', assuming commit." % rev)
return rev_options | [
"def",
"check_rev_options",
"(",
"self",
",",
"rev",
",",
"dest",
",",
"rev_options",
")",
":",
"revisions",
"=",
"self",
".",
"get_tag_revs",
"(",
"dest",
")",
"revisions",
".",
"update",
"(",
"self",
".",
"get_branch_revs",
"(",
"dest",
")",
")",
"orig... | Check the revision options before checkout to compensate that tags
and branches may need origin/ as a prefix.
Returns the SHA1 of the branch or tag if found. | [
"Check",
"the",
"revision",
"options",
"before",
"checkout",
"to",
"compensate",
"that",
"tags",
"and",
"branches",
"may",
"need",
"origin",
"/",
"as",
"a",
"prefix",
".",
"Returns",
"the",
"SHA1",
"of",
"the",
"branch",
"or",
"tag",
"if",
"found",
"."
] | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/vcs/git.py#L63-L80 |
petebachant/PXL | pxl/io.py | savejson | def savejson(filename, datadict):
"""Save data from a dictionary in JSON format. Note that this only
works to the second level of the dictionary with Numpy arrays.
"""
for key, value in datadict.items():
if type(value) == np.ndarray:
datadict[key] = value.tolist()
if type(value) == dict:
for key2, value2 in value.items():
if type(value2) == np.ndarray:
datadict[key][key2] = value2.tolist()
with open(filename, "w") as f:
f.write(json.dumps(datadict, indent=4)) | python | def savejson(filename, datadict):
"""Save data from a dictionary in JSON format. Note that this only
works to the second level of the dictionary with Numpy arrays.
"""
for key, value in datadict.items():
if type(value) == np.ndarray:
datadict[key] = value.tolist()
if type(value) == dict:
for key2, value2 in value.items():
if type(value2) == np.ndarray:
datadict[key][key2] = value2.tolist()
with open(filename, "w") as f:
f.write(json.dumps(datadict, indent=4)) | [
"def",
"savejson",
"(",
"filename",
",",
"datadict",
")",
":",
"for",
"key",
",",
"value",
"in",
"datadict",
".",
"items",
"(",
")",
":",
"if",
"type",
"(",
"value",
")",
"==",
"np",
".",
"ndarray",
":",
"datadict",
"[",
"key",
"]",
"=",
"value",
... | Save data from a dictionary in JSON format. Note that this only
works to the second level of the dictionary with Numpy arrays. | [
"Save",
"data",
"from",
"a",
"dictionary",
"in",
"JSON",
"format",
".",
"Note",
"that",
"this",
"only",
"works",
"to",
"the",
"second",
"level",
"of",
"the",
"dictionary",
"with",
"Numpy",
"arrays",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/io.py#L13-L25 |
petebachant/PXL | pxl/io.py | loadjson | def loadjson(filename, asnparrays=False):
"""Load data from text file in JSON format.
Numpy arrays are converted if specified with the `asnparrays` keyword
argument. Note that this only works to the second level of the dictionary.
Returns a single dict.
"""
with open(filename) as f:
data = json.load(f)
if asnparrays:
for key, value in data.items():
if type(value) is list:
data[key] = np.asarray(value)
if type(value) is dict:
for key2, value2 in value.items():
if type(value2) is list:
data[key][key2] = np.asarray(value2)
return data | python | def loadjson(filename, asnparrays=False):
"""Load data from text file in JSON format.
Numpy arrays are converted if specified with the `asnparrays` keyword
argument. Note that this only works to the second level of the dictionary.
Returns a single dict.
"""
with open(filename) as f:
data = json.load(f)
if asnparrays:
for key, value in data.items():
if type(value) is list:
data[key] = np.asarray(value)
if type(value) is dict:
for key2, value2 in value.items():
if type(value2) is list:
data[key][key2] = np.asarray(value2)
return data | [
"def",
"loadjson",
"(",
"filename",
",",
"asnparrays",
"=",
"False",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"data",
"=",
"json",
".",
"load",
"(",
"f",
")",
"if",
"asnparrays",
":",
"for",
"key",
",",
"value",
"in",
"data",... | Load data from text file in JSON format.
Numpy arrays are converted if specified with the `asnparrays` keyword
argument. Note that this only works to the second level of the dictionary.
Returns a single dict. | [
"Load",
"data",
"from",
"text",
"file",
"in",
"JSON",
"format",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/io.py#L28-L45 |
petebachant/PXL | pxl/io.py | savecsv | def savecsv(filename, datadict, mode="w"):
"""Save a dictionary of data to CSV."""
if mode == "a" :
header = False
else:
header = True
with open(filename, mode) as f:
_pd.DataFrame(datadict).to_csv(f, index=False, header=header) | python | def savecsv(filename, datadict, mode="w"):
"""Save a dictionary of data to CSV."""
if mode == "a" :
header = False
else:
header = True
with open(filename, mode) as f:
_pd.DataFrame(datadict).to_csv(f, index=False, header=header) | [
"def",
"savecsv",
"(",
"filename",
",",
"datadict",
",",
"mode",
"=",
"\"w\"",
")",
":",
"if",
"mode",
"==",
"\"a\"",
":",
"header",
"=",
"False",
"else",
":",
"header",
"=",
"True",
"with",
"open",
"(",
"filename",
",",
"mode",
")",
"as",
"f",
":"... | Save a dictionary of data to CSV. | [
"Save",
"a",
"dictionary",
"of",
"data",
"to",
"CSV",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/io.py#L48-L55 |
petebachant/PXL | pxl/io.py | loadcsv | def loadcsv(filename):
"""Load data from CSV file.
Returns a single dict with column names as keys.
"""
dataframe = _pd.read_csv(filename)
data = {}
for key, value in dataframe.items():
data[key] = value.values
return data | python | def loadcsv(filename):
"""Load data from CSV file.
Returns a single dict with column names as keys.
"""
dataframe = _pd.read_csv(filename)
data = {}
for key, value in dataframe.items():
data[key] = value.values
return data | [
"def",
"loadcsv",
"(",
"filename",
")",
":",
"dataframe",
"=",
"_pd",
".",
"read_csv",
"(",
"filename",
")",
"data",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"dataframe",
".",
"items",
"(",
")",
":",
"data",
"[",
"key",
"]",
"=",
"value",
... | Load data from CSV file.
Returns a single dict with column names as keys. | [
"Load",
"data",
"from",
"CSV",
"file",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/io.py#L58-L67 |
petebachant/PXL | pxl/io.py | savehdf | def savehdf(filename, datadict, groupname="data", mode="a", metadata=None,
as_dataframe=False, append=False):
"""Save a dictionary of arrays to file--similar to how `scipy.io.savemat`
works. If `datadict` is a DataFrame, it will be converted automatically.
"""
if as_dataframe:
df = _pd.DataFrame(datadict)
df.to_hdf(filename, groupname)
else:
if isinstance(datadict, _pd.DataFrame):
datadict = datadict.to_dict("list")
with _h5py.File(filename, mode) as f:
for key, value in datadict.items():
if append:
try:
f[groupname + "/" + key] = np.append(f[groupname + "/" + key], value)
except KeyError:
f[groupname + "/" + key] = value
else:
f[groupname + "/" + key] = value
if metadata:
for key, value in metadata.items():
f[groupname].attrs[key] = value | python | def savehdf(filename, datadict, groupname="data", mode="a", metadata=None,
as_dataframe=False, append=False):
"""Save a dictionary of arrays to file--similar to how `scipy.io.savemat`
works. If `datadict` is a DataFrame, it will be converted automatically.
"""
if as_dataframe:
df = _pd.DataFrame(datadict)
df.to_hdf(filename, groupname)
else:
if isinstance(datadict, _pd.DataFrame):
datadict = datadict.to_dict("list")
with _h5py.File(filename, mode) as f:
for key, value in datadict.items():
if append:
try:
f[groupname + "/" + key] = np.append(f[groupname + "/" + key], value)
except KeyError:
f[groupname + "/" + key] = value
else:
f[groupname + "/" + key] = value
if metadata:
for key, value in metadata.items():
f[groupname].attrs[key] = value | [
"def",
"savehdf",
"(",
"filename",
",",
"datadict",
",",
"groupname",
"=",
"\"data\"",
",",
"mode",
"=",
"\"a\"",
",",
"metadata",
"=",
"None",
",",
"as_dataframe",
"=",
"False",
",",
"append",
"=",
"False",
")",
":",
"if",
"as_dataframe",
":",
"df",
"... | Save a dictionary of arrays to file--similar to how `scipy.io.savemat`
works. If `datadict` is a DataFrame, it will be converted automatically. | [
"Save",
"a",
"dictionary",
"of",
"arrays",
"to",
"file",
"--",
"similar",
"to",
"how",
"scipy",
".",
"io",
".",
"savemat",
"works",
".",
"If",
"datadict",
"is",
"a",
"DataFrame",
"it",
"will",
"be",
"converted",
"automatically",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/io.py#L70-L92 |
petebachant/PXL | pxl/io.py | loadhdf | def loadhdf(filename, groupname="data", to_dataframe=False):
"""Load all data from top level of HDF5 file--similar to how
`scipy.io.loadmat` works.
"""
data = {}
with _h5py.File(filename, "r") as f:
for key, value in f[groupname].items():
data[key] = np.array(value)
if to_dataframe:
return _pd.DataFrame(data)
else:
return data | python | def loadhdf(filename, groupname="data", to_dataframe=False):
"""Load all data from top level of HDF5 file--similar to how
`scipy.io.loadmat` works.
"""
data = {}
with _h5py.File(filename, "r") as f:
for key, value in f[groupname].items():
data[key] = np.array(value)
if to_dataframe:
return _pd.DataFrame(data)
else:
return data | [
"def",
"loadhdf",
"(",
"filename",
",",
"groupname",
"=",
"\"data\"",
",",
"to_dataframe",
"=",
"False",
")",
":",
"data",
"=",
"{",
"}",
"with",
"_h5py",
".",
"File",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"key",
",",
"value",
... | Load all data from top level of HDF5 file--similar to how
`scipy.io.loadmat` works. | [
"Load",
"all",
"data",
"from",
"top",
"level",
"of",
"HDF5",
"file",
"--",
"similar",
"to",
"how",
"scipy",
".",
"io",
".",
"loadmat",
"works",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/io.py#L95-L106 |
petebachant/PXL | pxl/io.py | save_hdf_metadata | def save_hdf_metadata(filename, metadata, groupname="data", mode="a"):
""""Save a dictionary of metadata to a group's attrs."""
with _h5py.File(filename, mode) as f:
for key, val in metadata.items():
f[groupname].attrs[key] = val | python | def save_hdf_metadata(filename, metadata, groupname="data", mode="a"):
""""Save a dictionary of metadata to a group's attrs."""
with _h5py.File(filename, mode) as f:
for key, val in metadata.items():
f[groupname].attrs[key] = val | [
"def",
"save_hdf_metadata",
"(",
"filename",
",",
"metadata",
",",
"groupname",
"=",
"\"data\"",
",",
"mode",
"=",
"\"a\"",
")",
":",
"with",
"_h5py",
".",
"File",
"(",
"filename",
",",
"mode",
")",
"as",
"f",
":",
"for",
"key",
",",
"val",
"in",
"me... | Save a dictionary of metadata to a group's attrs. | [
"Save",
"a",
"dictionary",
"of",
"metadata",
"to",
"a",
"group",
"s",
"attrs",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/io.py#L109-L113 |
petebachant/PXL | pxl/io.py | load_hdf_metadata | def load_hdf_metadata(filename, groupname="data"):
""""Load attrs of the desired group into a dictionary."""
with _h5py.File(filename, "r") as f:
data = dict(f[groupname].attrs)
return data | python | def load_hdf_metadata(filename, groupname="data"):
""""Load attrs of the desired group into a dictionary."""
with _h5py.File(filename, "r") as f:
data = dict(f[groupname].attrs)
return data | [
"def",
"load_hdf_metadata",
"(",
"filename",
",",
"groupname",
"=",
"\"data\"",
")",
":",
"with",
"_h5py",
".",
"File",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"f",
":",
"data",
"=",
"dict",
"(",
"f",
"[",
"groupname",
"]",
".",
"attrs",
")",
"retu... | Load attrs of the desired group into a dictionary. | [
"Load",
"attrs",
"of",
"the",
"desired",
"group",
"into",
"a",
"dictionary",
"."
] | train | https://github.com/petebachant/PXL/blob/d7d06cb74422e1ac0154741351fbecea080cfcc0/pxl/io.py#L116-L120 |
ShawnClake/Apitax | apitax/ah/api/controllers/migrations/any_controller.py | authenticate | def authenticate(user=None): # noqa: E501
"""Authenticate
Authenticate with the API # noqa: E501
:param user: The user authentication object.
:type user: dict | bytes
:rtype: AuthResponse
"""
if connexion.request.is_json:
user = UserAuth.from_dict(connexion.request.get_json()) # noqa: E501
return 'do some magic!' | python | def authenticate(user=None): # noqa: E501
"""Authenticate
Authenticate with the API # noqa: E501
:param user: The user authentication object.
:type user: dict | bytes
:rtype: AuthResponse
"""
if connexion.request.is_json:
user = UserAuth.from_dict(connexion.request.get_json()) # noqa: E501
return 'do some magic!' | [
"def",
"authenticate",
"(",
"user",
"=",
"None",
")",
":",
"# noqa: E501",
"if",
"connexion",
".",
"request",
".",
"is_json",
":",
"user",
"=",
"UserAuth",
".",
"from_dict",
"(",
"connexion",
".",
"request",
".",
"get_json",
"(",
")",
")",
"# noqa: E501",
... | Authenticate
Authenticate with the API # noqa: E501
:param user: The user authentication object.
:type user: dict | bytes
:rtype: AuthResponse | [
"Authenticate"
] | train | https://github.com/ShawnClake/Apitax/blob/2eb9c6990d4088b2503c7f13c2a76f8e59606e6d/apitax/ah/api/controllers/migrations/any_controller.py#L10-L22 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.get_param_doc | def get_param_doc(doc, param):
"""Get the documentation and datatype for a parameter
This function returns the documentation and the argument for a
napoleon like structured docstring `doc`
Parameters
----------
doc: str
The base docstring to use
param: str
The argument to use
Returns
-------
str
The documentation of the given `param`
str
The datatype of the given `param`"""
arg_doc = docstrings.keep_params_s(doc, [param]) or \
docstrings.keep_types_s(doc, [param])
dtype = None
if arg_doc:
lines = arg_doc.splitlines()
arg_doc = dedents('\n' + '\n'.join(lines[1:]))
param_desc = lines[0].split(':', 1)
if len(param_desc) > 1:
dtype = param_desc[1].strip()
return arg_doc, dtype | python | def get_param_doc(doc, param):
"""Get the documentation and datatype for a parameter
This function returns the documentation and the argument for a
napoleon like structured docstring `doc`
Parameters
----------
doc: str
The base docstring to use
param: str
The argument to use
Returns
-------
str
The documentation of the given `param`
str
The datatype of the given `param`"""
arg_doc = docstrings.keep_params_s(doc, [param]) or \
docstrings.keep_types_s(doc, [param])
dtype = None
if arg_doc:
lines = arg_doc.splitlines()
arg_doc = dedents('\n' + '\n'.join(lines[1:]))
param_desc = lines[0].split(':', 1)
if len(param_desc) > 1:
dtype = param_desc[1].strip()
return arg_doc, dtype | [
"def",
"get_param_doc",
"(",
"doc",
",",
"param",
")",
":",
"arg_doc",
"=",
"docstrings",
".",
"keep_params_s",
"(",
"doc",
",",
"[",
"param",
"]",
")",
"or",
"docstrings",
".",
"keep_types_s",
"(",
"doc",
",",
"[",
"param",
"]",
")",
"dtype",
"=",
"... | Get the documentation and datatype for a parameter
This function returns the documentation and the argument for a
napoleon like structured docstring `doc`
Parameters
----------
doc: str
The base docstring to use
param: str
The argument to use
Returns
-------
str
The documentation of the given `param`
str
The datatype of the given `param` | [
"Get",
"the",
"documentation",
"and",
"datatype",
"for",
"a",
"parameter"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L129-L157 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.setup_args | def setup_args(self, func=None, setup_as=None, insert_at=None,
interprete=True, epilog_sections=None,
overwrite=False, append_epilog=True):
"""
Add the parameters from the given `func` to the parameter settings
Parameters
----------
func: function
The function to use. If None, a function will be returned that can
be used as a decorator
setup_as: str
The attribute that shall be assigned to the function in the
resulting namespace. If specified, this function will be used when
calling the :meth:`parse2func` method
insert_at: int
The position where the given `func` should be inserted. If None,
it will be appended at the end and used when calling the
:meth:`parse2func` method
interprete: bool
If True (default), the docstrings are interpreted and switches and
lists are automatically inserted (see the
[interpretation-docs]_
epilog_sections: list of str
The headers of the sections to extract. If None, the
:attr:`epilog_sections` attribute is used
overwrite: bool
If True, overwrite the existing epilog and the existing description
of the parser
append_epilog: bool
If True, append to the existing epilog
Returns
-------
function
Either the function that can be used as a decorator (if `func` is
``None``), or the given `func` itself.
Examples
--------
Use this method as a decorator::
>>> @parser.setup_args
... def do_something(a=1):
'''
Just an example
Parameters
----------
a: int
A number to increment by one
'''
return a + 1
>>> args = parser.parse_args('-a 2'.split())
Or by specifying the setup_as function::
>>> @parser.setup_args(setup_as='func')
... def do_something(a=1):
'''
Just an example
Parameters
----------
a: int
A number to increment by one
'''
return a + 1
>>> args = parser.parse_args('-a 2'.split())
>>> args.func is do_something
>>> parser.parse2func('-a 2'.split())
3
References
----------
.. [interpretation-docs]
http://funcargparse.readthedocs.io/en/latest/docstring_interpretation.html)
"""
def setup(func):
# insert the function
if insert_at is None:
self._used_functions.append(func)
else:
self._used_functions.insert(insert_at, func)
args_dict = self.unfinished_arguments
# save the function to use in parse2funcs
if setup_as:
args_dict[setup_as] = dict(
long=setup_as, default=func, help=argparse.SUPPRESS)
self._setup_as = setup_as
# create arguments
args, varargs, varkw, defaults = inspect.getargspec(func)
full_doc = docstrings.dedents(inspect.getdoc(func))
summary = docstrings.get_full_description(full_doc)
if summary:
if not self.description or overwrite:
self.description = summary
full_doc = docstrings._remove_summary(full_doc)
self.extract_as_epilog(full_doc, epilog_sections, overwrite,
append_epilog)
doc = docstrings._get_section(full_doc, 'Parameters') + '\n'
doc += docstrings._get_section(full_doc, 'Other Parameters')
doc = doc.rstrip()
default_min = len(args or []) - len(defaults or [])
for i, arg in enumerate(args):
if arg == 'self' or arg in args_dict:
continue
arg_doc, dtype = self.get_param_doc(doc, arg)
args_dict[arg] = d = {'dest': arg, 'short': arg.replace('_',
'-'),
'long': arg.replace('_', '-')}
if arg_doc:
d['help'] = arg_doc
if i >= default_min:
d['default'] = defaults[i - default_min]
else:
d['positional'] = True
if interprete and dtype == 'bool' and 'default' in d:
d['action'] = 'store_false' if d['default'] else \
'store_true'
elif interprete and dtype:
if dtype.startswith('list of'):
d['nargs'] = '+'
dtype = dtype[7:].strip()
if dtype in ['str', 'string', 'strings']:
d['type'] = six.text_type
if dtype == 'strings':
dtype = 'string'
else:
try:
d['type'] = getattr(builtins, dtype)
except AttributeError:
try: # maybe the dtype has a final 's'
d['type'] = getattr(builtins, dtype[:-1])
dtype = dtype[:-1]
except AttributeError:
pass
d['metavar'] = dtype
return func
if func is None:
return setup
else:
return setup(func) | python | def setup_args(self, func=None, setup_as=None, insert_at=None,
interprete=True, epilog_sections=None,
overwrite=False, append_epilog=True):
"""
Add the parameters from the given `func` to the parameter settings
Parameters
----------
func: function
The function to use. If None, a function will be returned that can
be used as a decorator
setup_as: str
The attribute that shall be assigned to the function in the
resulting namespace. If specified, this function will be used when
calling the :meth:`parse2func` method
insert_at: int
The position where the given `func` should be inserted. If None,
it will be appended at the end and used when calling the
:meth:`parse2func` method
interprete: bool
If True (default), the docstrings are interpreted and switches and
lists are automatically inserted (see the
[interpretation-docs]_
epilog_sections: list of str
The headers of the sections to extract. If None, the
:attr:`epilog_sections` attribute is used
overwrite: bool
If True, overwrite the existing epilog and the existing description
of the parser
append_epilog: bool
If True, append to the existing epilog
Returns
-------
function
Either the function that can be used as a decorator (if `func` is
``None``), or the given `func` itself.
Examples
--------
Use this method as a decorator::
>>> @parser.setup_args
... def do_something(a=1):
'''
Just an example
Parameters
----------
a: int
A number to increment by one
'''
return a + 1
>>> args = parser.parse_args('-a 2'.split())
Or by specifying the setup_as function::
>>> @parser.setup_args(setup_as='func')
... def do_something(a=1):
'''
Just an example
Parameters
----------
a: int
A number to increment by one
'''
return a + 1
>>> args = parser.parse_args('-a 2'.split())
>>> args.func is do_something
>>> parser.parse2func('-a 2'.split())
3
References
----------
.. [interpretation-docs]
http://funcargparse.readthedocs.io/en/latest/docstring_interpretation.html)
"""
def setup(func):
# insert the function
if insert_at is None:
self._used_functions.append(func)
else:
self._used_functions.insert(insert_at, func)
args_dict = self.unfinished_arguments
# save the function to use in parse2funcs
if setup_as:
args_dict[setup_as] = dict(
long=setup_as, default=func, help=argparse.SUPPRESS)
self._setup_as = setup_as
# create arguments
args, varargs, varkw, defaults = inspect.getargspec(func)
full_doc = docstrings.dedents(inspect.getdoc(func))
summary = docstrings.get_full_description(full_doc)
if summary:
if not self.description or overwrite:
self.description = summary
full_doc = docstrings._remove_summary(full_doc)
self.extract_as_epilog(full_doc, epilog_sections, overwrite,
append_epilog)
doc = docstrings._get_section(full_doc, 'Parameters') + '\n'
doc += docstrings._get_section(full_doc, 'Other Parameters')
doc = doc.rstrip()
default_min = len(args or []) - len(defaults or [])
for i, arg in enumerate(args):
if arg == 'self' or arg in args_dict:
continue
arg_doc, dtype = self.get_param_doc(doc, arg)
args_dict[arg] = d = {'dest': arg, 'short': arg.replace('_',
'-'),
'long': arg.replace('_', '-')}
if arg_doc:
d['help'] = arg_doc
if i >= default_min:
d['default'] = defaults[i - default_min]
else:
d['positional'] = True
if interprete and dtype == 'bool' and 'default' in d:
d['action'] = 'store_false' if d['default'] else \
'store_true'
elif interprete and dtype:
if dtype.startswith('list of'):
d['nargs'] = '+'
dtype = dtype[7:].strip()
if dtype in ['str', 'string', 'strings']:
d['type'] = six.text_type
if dtype == 'strings':
dtype = 'string'
else:
try:
d['type'] = getattr(builtins, dtype)
except AttributeError:
try: # maybe the dtype has a final 's'
d['type'] = getattr(builtins, dtype[:-1])
dtype = dtype[:-1]
except AttributeError:
pass
d['metavar'] = dtype
return func
if func is None:
return setup
else:
return setup(func) | [
"def",
"setup_args",
"(",
"self",
",",
"func",
"=",
"None",
",",
"setup_as",
"=",
"None",
",",
"insert_at",
"=",
"None",
",",
"interprete",
"=",
"True",
",",
"epilog_sections",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"append_epilog",
"=",
"True... | Add the parameters from the given `func` to the parameter settings
Parameters
----------
func: function
The function to use. If None, a function will be returned that can
be used as a decorator
setup_as: str
The attribute that shall be assigned to the function in the
resulting namespace. If specified, this function will be used when
calling the :meth:`parse2func` method
insert_at: int
The position where the given `func` should be inserted. If None,
it will be appended at the end and used when calling the
:meth:`parse2func` method
interprete: bool
If True (default), the docstrings are interpreted and switches and
lists are automatically inserted (see the
[interpretation-docs]_
epilog_sections: list of str
The headers of the sections to extract. If None, the
:attr:`epilog_sections` attribute is used
overwrite: bool
If True, overwrite the existing epilog and the existing description
of the parser
append_epilog: bool
If True, append to the existing epilog
Returns
-------
function
Either the function that can be used as a decorator (if `func` is
``None``), or the given `func` itself.
Examples
--------
Use this method as a decorator::
>>> @parser.setup_args
... def do_something(a=1):
'''
Just an example
Parameters
----------
a: int
A number to increment by one
'''
return a + 1
>>> args = parser.parse_args('-a 2'.split())
Or by specifying the setup_as function::
>>> @parser.setup_args(setup_as='func')
... def do_something(a=1):
'''
Just an example
Parameters
----------
a: int
A number to increment by one
'''
return a + 1
>>> args = parser.parse_args('-a 2'.split())
>>> args.func is do_something
>>> parser.parse2func('-a 2'.split())
3
References
----------
.. [interpretation-docs]
http://funcargparse.readthedocs.io/en/latest/docstring_interpretation.html) | [
"Add",
"the",
"parameters",
"from",
"the",
"given",
"func",
"to",
"the",
"parameter",
"settings"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L162-L310 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.add_subparsers | def add_subparsers(self, *args, **kwargs):
"""
Add subparsers to this parser
Parameters
----------
``*args, **kwargs``
As specified by the original
:meth:`argparse.ArgumentParser.add_subparsers` method
chain: bool
Default: False. If True, It is enabled to chain subparsers"""
chain = kwargs.pop('chain', None)
ret = super(FuncArgParser, self).add_subparsers(*args, **kwargs)
if chain:
self._chain_subparsers = True
self._subparsers_action = ret
return ret | python | def add_subparsers(self, *args, **kwargs):
"""
Add subparsers to this parser
Parameters
----------
``*args, **kwargs``
As specified by the original
:meth:`argparse.ArgumentParser.add_subparsers` method
chain: bool
Default: False. If True, It is enabled to chain subparsers"""
chain = kwargs.pop('chain', None)
ret = super(FuncArgParser, self).add_subparsers(*args, **kwargs)
if chain:
self._chain_subparsers = True
self._subparsers_action = ret
return ret | [
"def",
"add_subparsers",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"chain",
"=",
"kwargs",
".",
"pop",
"(",
"'chain'",
",",
"None",
")",
"ret",
"=",
"super",
"(",
"FuncArgParser",
",",
"self",
")",
".",
"add_subparsers",
"(",
... | Add subparsers to this parser
Parameters
----------
``*args, **kwargs``
As specified by the original
:meth:`argparse.ArgumentParser.add_subparsers` method
chain: bool
Default: False. If True, It is enabled to chain subparsers | [
"Add",
"subparsers",
"to",
"this",
"parser"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L314-L330 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.setup_subparser | def setup_subparser(
self, func=None, setup_as=None, insert_at=None, interprete=True,
epilog_sections=None, overwrite=False, append_epilog=True,
return_parser=False, name=None, **kwargs):
"""
Create a subparser with the name of the given function
Parameters are the same as for the :meth:`setup_args` function, other
parameters are parsed to the :meth:`add_subparsers` method if (and only
if) this method has not already been called.
Parameters
----------
%(FuncArgParser.setup_args.parameters)s
return_parser: bool
If True, the create parser is returned instead of the function
name: str
The name of the created parser. If None, the function name is used
and underscores (``'_'``) are replaced by minus (``'-'``)
``**kwargs``
Any other parameter that is passed to the add_parser method that
creates the parser
Other Parameters
----------------
Returns
-------
FuncArgParser or %(FuncArgParser.setup_args.returns)s
If return_parser is True, the created subparser is returned
Examples
--------
Use this method as a decorator::
>>> from funcargparser import FuncArgParser
>>> parser = FuncArgParser()
>>> @parser.setup_subparser
... def my_func(my_argument=None):
... pass
>>> args = parser.parse_args('my-func -my-argument 1'.split())
"""
def setup(func):
if self._subparsers_action is None:
raise RuntimeError(
"No subparsers have yet been created! Run the "
"add_subparsers method first!")
# replace underscore by '-'
name2use = name
if name2use is None:
name2use = func.__name__.replace('_', '-')
kwargs.setdefault('help', docstrings.get_summary(
docstrings.dedents(inspect.getdoc(func))))
parser = self._subparsers_action.add_parser(name2use, **kwargs)
parser.setup_args(
func, setup_as=setup_as, insert_at=insert_at,
interprete=interprete, epilog_sections=epilog_sections,
overwrite=overwrite, append_epilog=append_epilog)
return func, parser
if func is None:
return lambda f: setup(f)[0]
else:
return setup(func)[int(return_parser)] | python | def setup_subparser(
self, func=None, setup_as=None, insert_at=None, interprete=True,
epilog_sections=None, overwrite=False, append_epilog=True,
return_parser=False, name=None, **kwargs):
"""
Create a subparser with the name of the given function
Parameters are the same as for the :meth:`setup_args` function, other
parameters are parsed to the :meth:`add_subparsers` method if (and only
if) this method has not already been called.
Parameters
----------
%(FuncArgParser.setup_args.parameters)s
return_parser: bool
If True, the create parser is returned instead of the function
name: str
The name of the created parser. If None, the function name is used
and underscores (``'_'``) are replaced by minus (``'-'``)
``**kwargs``
Any other parameter that is passed to the add_parser method that
creates the parser
Other Parameters
----------------
Returns
-------
FuncArgParser or %(FuncArgParser.setup_args.returns)s
If return_parser is True, the created subparser is returned
Examples
--------
Use this method as a decorator::
>>> from funcargparser import FuncArgParser
>>> parser = FuncArgParser()
>>> @parser.setup_subparser
... def my_func(my_argument=None):
... pass
>>> args = parser.parse_args('my-func -my-argument 1'.split())
"""
def setup(func):
if self._subparsers_action is None:
raise RuntimeError(
"No subparsers have yet been created! Run the "
"add_subparsers method first!")
# replace underscore by '-'
name2use = name
if name2use is None:
name2use = func.__name__.replace('_', '-')
kwargs.setdefault('help', docstrings.get_summary(
docstrings.dedents(inspect.getdoc(func))))
parser = self._subparsers_action.add_parser(name2use, **kwargs)
parser.setup_args(
func, setup_as=setup_as, insert_at=insert_at,
interprete=interprete, epilog_sections=epilog_sections,
overwrite=overwrite, append_epilog=append_epilog)
return func, parser
if func is None:
return lambda f: setup(f)[0]
else:
return setup(func)[int(return_parser)] | [
"def",
"setup_subparser",
"(",
"self",
",",
"func",
"=",
"None",
",",
"setup_as",
"=",
"None",
",",
"insert_at",
"=",
"None",
",",
"interprete",
"=",
"True",
",",
"epilog_sections",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"append_epilog",
"=",
... | Create a subparser with the name of the given function
Parameters are the same as for the :meth:`setup_args` function, other
parameters are parsed to the :meth:`add_subparsers` method if (and only
if) this method has not already been called.
Parameters
----------
%(FuncArgParser.setup_args.parameters)s
return_parser: bool
If True, the create parser is returned instead of the function
name: str
The name of the created parser. If None, the function name is used
and underscores (``'_'``) are replaced by minus (``'-'``)
``**kwargs``
Any other parameter that is passed to the add_parser method that
creates the parser
Other Parameters
----------------
Returns
-------
FuncArgParser or %(FuncArgParser.setup_args.returns)s
If return_parser is True, the created subparser is returned
Examples
--------
Use this method as a decorator::
>>> from funcargparser import FuncArgParser
>>> parser = FuncArgParser()
>>> @parser.setup_subparser
... def my_func(my_argument=None):
... pass
>>> args = parser.parse_args('my-func -my-argument 1'.split()) | [
"Create",
"a",
"subparser",
"with",
"the",
"name",
"of",
"the",
"given",
"function"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L333-L398 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.update_arg | def update_arg(self, arg, if_existent=None, **kwargs):
"""
Update the `add_argument` data for the given parameter
Parameters
----------
arg: str
The name of the function argument
if_existent: bool or None
If True, the argument is updated. If None (default), the argument
is only updated, if it exists. Otherwise, if False, the given
``**kwargs`` are only used if the argument is not yet existing
``**kwargs``
The keyword arguments any parameter for the
:meth:`argparse.ArgumentParser.add_argument` method
"""
if if_existent or (if_existent is None and
arg in self.unfinished_arguments):
self.unfinished_arguments[arg].update(kwargs)
elif not if_existent and if_existent is not None:
self.unfinished_arguments.setdefault(arg, kwargs) | python | def update_arg(self, arg, if_existent=None, **kwargs):
"""
Update the `add_argument` data for the given parameter
Parameters
----------
arg: str
The name of the function argument
if_existent: bool or None
If True, the argument is updated. If None (default), the argument
is only updated, if it exists. Otherwise, if False, the given
``**kwargs`` are only used if the argument is not yet existing
``**kwargs``
The keyword arguments any parameter for the
:meth:`argparse.ArgumentParser.add_argument` method
"""
if if_existent or (if_existent is None and
arg in self.unfinished_arguments):
self.unfinished_arguments[arg].update(kwargs)
elif not if_existent and if_existent is not None:
self.unfinished_arguments.setdefault(arg, kwargs) | [
"def",
"update_arg",
"(",
"self",
",",
"arg",
",",
"if_existent",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"if_existent",
"or",
"(",
"if_existent",
"is",
"None",
"and",
"arg",
"in",
"self",
".",
"unfinished_arguments",
")",
":",
"self",
".... | Update the `add_argument` data for the given parameter
Parameters
----------
arg: str
The name of the function argument
if_existent: bool or None
If True, the argument is updated. If None (default), the argument
is only updated, if it exists. Otherwise, if False, the given
``**kwargs`` are only used if the argument is not yet existing
``**kwargs``
The keyword arguments any parameter for the
:meth:`argparse.ArgumentParser.add_argument` method | [
"Update",
"the",
"add_argument",
"data",
"for",
"the",
"given",
"parameter"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L402-L422 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser._get_corresponding_parsers | def _get_corresponding_parsers(self, func):
"""Get the parser that has been set up by the given `function`"""
if func in self._used_functions:
yield self
if self._subparsers_action is not None:
for parser in self._subparsers_action.choices.values():
for sp in parser._get_corresponding_parsers(func):
yield sp | python | def _get_corresponding_parsers(self, func):
"""Get the parser that has been set up by the given `function`"""
if func in self._used_functions:
yield self
if self._subparsers_action is not None:
for parser in self._subparsers_action.choices.values():
for sp in parser._get_corresponding_parsers(func):
yield sp | [
"def",
"_get_corresponding_parsers",
"(",
"self",
",",
"func",
")",
":",
"if",
"func",
"in",
"self",
".",
"_used_functions",
":",
"yield",
"self",
"if",
"self",
".",
"_subparsers_action",
"is",
"not",
"None",
":",
"for",
"parser",
"in",
"self",
".",
"_subp... | Get the parser that has been set up by the given `function` | [
"Get",
"the",
"parser",
"that",
"has",
"been",
"set",
"up",
"by",
"the",
"given",
"function"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L467-L474 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.pop_key | def pop_key(self, arg, key, *args, **kwargs):
"""Delete a previously defined key for the `add_argument`
"""
return self.unfinished_arguments[arg].pop(key, *args, **kwargs) | python | def pop_key(self, arg, key, *args, **kwargs):
"""Delete a previously defined key for the `add_argument`
"""
return self.unfinished_arguments[arg].pop(key, *args, **kwargs) | [
"def",
"pop_key",
"(",
"self",
",",
"arg",
",",
"key",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"unfinished_arguments",
"[",
"arg",
"]",
".",
"pop",
"(",
"key",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Delete a previously defined key for the `add_argument` | [
"Delete",
"a",
"previously",
"defined",
"key",
"for",
"the",
"add_argument"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L487-L490 |
Chilipp/funcargparse | funcargparse/__init__.py | FuncArgParser.create_arguments | def create_arguments(self, subparsers=False):
"""Create and add the arguments
Parameters
----------
subparsers: bool
If True, the arguments of the subparsers are also created"""
ret = []
if not self._finalized:
for arg, d in self.unfinished_arguments.items():
try:
not_positional = int(not d.pop('positional', False))
short = d.pop('short', None)
long_name = d.pop('long', None)
if short is None and long_name is None:
raise ValueError(
"Either a short (-) or a long (--) argument must "
"be provided!")
if not not_positional:
short = arg
long_name = None
d.pop('dest', None)
if short == long_name:
long_name = None
args = []
if short:
args.append('-' * not_positional + short)
if long_name:
args.append('--' * not_positional + long_name)
group = d.pop('group', self)
if d.get('action') in ['store_true', 'store_false']:
d.pop('metavar', None)
ret.append(group.add_argument(*args, **d))
except Exception:
print('Error while creating argument %s' % arg)
raise
else:
raise ValueError('Parser has already been finalized!')
self._finalized = True
if subparsers and self._subparsers_action is not None:
for parser in self._subparsers_action.choices.values():
parser.create_arguments(True)
return ret | python | def create_arguments(self, subparsers=False):
"""Create and add the arguments
Parameters
----------
subparsers: bool
If True, the arguments of the subparsers are also created"""
ret = []
if not self._finalized:
for arg, d in self.unfinished_arguments.items():
try:
not_positional = int(not d.pop('positional', False))
short = d.pop('short', None)
long_name = d.pop('long', None)
if short is None and long_name is None:
raise ValueError(
"Either a short (-) or a long (--) argument must "
"be provided!")
if not not_positional:
short = arg
long_name = None
d.pop('dest', None)
if short == long_name:
long_name = None
args = []
if short:
args.append('-' * not_positional + short)
if long_name:
args.append('--' * not_positional + long_name)
group = d.pop('group', self)
if d.get('action') in ['store_true', 'store_false']:
d.pop('metavar', None)
ret.append(group.add_argument(*args, **d))
except Exception:
print('Error while creating argument %s' % arg)
raise
else:
raise ValueError('Parser has already been finalized!')
self._finalized = True
if subparsers and self._subparsers_action is not None:
for parser in self._subparsers_action.choices.values():
parser.create_arguments(True)
return ret | [
"def",
"create_arguments",
"(",
"self",
",",
"subparsers",
"=",
"False",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"_finalized",
":",
"for",
"arg",
",",
"d",
"in",
"self",
".",
"unfinished_arguments",
".",
"items",
"(",
")",
":",
"try... | Create and add the arguments
Parameters
----------
subparsers: bool
If True, the arguments of the subparsers are also created | [
"Create",
"and",
"add",
"the",
"arguments"
] | train | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L498-L540 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.