hexsha
stringlengths
40
40
repo
stringlengths
7
114
path
stringlengths
4
124
license
listlengths
1
9
language
stringclasses
1 value
identifier
stringlengths
1
71
return_type
stringlengths
1
749
⌀
original_string
stringlengths
76
22.7k
original_docstring
stringlengths
16
7.61k
docstring
stringlengths
16
2.47k
docstring_tokens
listlengths
6
477
code
stringlengths
14
10.2k
code_tokens
listlengths
6
996
short_docstring
stringlengths
2
644
short_docstring_tokens
listlengths
1
116
comment
listlengths
1
89
parameters
listlengths
0
64
docstring_params
dict
2806057742efcb94eca5ba27ef4dd2d6ec387989
resuly/embedding
model/train.py
[ "Apache-2.0" ]
Python
train_and_evaluate
null
def train_and_evaluate(model, optimizer, scheduler, loss_fn, metrics, params, model_dir, restore_file=None): """Train the model and evaluate every epoch. Args: model: (torch.nn.Module) the neural network train_dataloader: (DataLoader) a torch.utils.data.DataLoader object that fetches train...
Train the model and evaluate every epoch. Args: model: (torch.nn.Module) the neural network train_dataloader: (DataLoader) a torch.utils.data.DataLoader object that fetches training data val_dataloader: (DataLoader) a torch.utils.data.DataLoader object that fetches validation data o...
Train the model and evaluate every epoch.
[ "Train", "the", "model", "and", "evaluate", "every", "epoch", "." ]
def train_and_evaluate(model, optimizer, scheduler, loss_fn, metrics, params, model_dir, restore_file=None): if restore_file is not None: restore_path = os.path.join(args.model_dir, args.restore_file + '.pth.tar') logging.info("Restoring parameters from {}".format(restore_path)) utils.l...
[ "def", "train_and_evaluate", "(", "model", ",", "optimizer", ",", "scheduler", ",", "loss_fn", ",", "metrics", ",", "params", ",", "model_dir", ",", "restore_file", "=", "None", ")", ":", "if", "restore_file", "is", "not", "None", ":", "restore_path", "=", ...
Train the model and evaluate every epoch.
[ "Train", "the", "model", "and", "evaluate", "every", "epoch", "." ]
[ "\"\"\"Train the model and evaluate every epoch.\n\n Args:\n model: (torch.nn.Module) the neural network\n train_dataloader: (DataLoader) a torch.utils.data.DataLoader object that fetches training data\n val_dataloader: (DataLoader) a torch.utils.data.DataLoader object that fetches validatio...
[ { "param": "model", "type": null }, { "param": "optimizer", "type": null }, { "param": "scheduler", "type": null }, { "param": "loss_fn", "type": null }, { "param": "metrics", "type": null }, { "param": "params", "type": null }, { "param": ...
{ "returns": [], "raises": [], "params": [ { "identifier": "model", "type": null, "docstring": "(torch.nn.Module) the neural network", "docstring_tokens": [ "(", "torch", ".", "nn", ".", "Module", ")", "the", "neur...
0a7412710d58a30d9908471e978f6e27f741290a
dakrauth/picker
picker/models/picks.py
[ "MIT" ]
Python
update_picks
null
def update_picks(self, games=None, points=None): ''' games can be dict of {game.id: winner_id} for all picked games to update ''' if games: game_dict = {g.id: g for g in self.gameset.games.filter(id__in=games)} game_picks = {pick.game.id: pick for pick in self.gam...
games can be dict of {game.id: winner_id} for all picked games to update
games can be dict of {game.id: winner_id} for all picked games to update
[ "games", "can", "be", "dict", "of", "{", "game", ".", "id", ":", "winner_id", "}", "for", "all", "picked", "games", "to", "update" ]
def update_picks(self, games=None, points=None): if games: game_dict = {g.id: g for g in self.gameset.games.filter(id__in=games)} game_picks = {pick.game.id: pick for pick in self.gamepicks.filter(game__id__in=games)} for key, winner in games.items(): game = g...
[ "def", "update_picks", "(", "self", ",", "games", "=", "None", ",", "points", "=", "None", ")", ":", "if", "games", ":", "game_dict", "=", "{", "g", ".", "id", ":", "g", "for", "g", "in", "self", ".", "gameset", ".", "games", ".", "filter", "(", ...
games can be dict of {game.id: winner_id} for all picked games to update
[ "games", "can", "be", "dict", "of", "{", "game", ".", "id", ":", "winner_id", "}", "for", "all", "picked", "games", "to", "update" ]
[ "'''\n games can be dict of {game.id: winner_id} for all picked games to update\n '''" ]
[ { "param": "self", "type": null }, { "param": "games", "type": null }, { "param": "points", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "games", "type": null, "docstring": null, "docstring_tokens": ...
cbc8b0de47f77e3f6b8853e45477fbff45287fcc
TheHolyWay/ficus-tracker-backend
ficus-tracker/app/api_v1/users.py
[ "MIT" ]
Python
create_user_or_return_token
<not_specific>
def create_user_or_return_token(): """ Create user and return it's token if user doesn't exists otherwise return user token """ resp_data = {} # response data headers = request.headers or {} # Check request if 'Authorization' not in headers: return bad_request("Missing 'Authorization' head...
Create user and return it's token if user doesn't exists otherwise return user token
Create user and return it's token if user doesn't exists otherwise return user token
[ "Create", "user", "and", "return", "it", "'", "s", "token", "if", "user", "doesn", "'", "t", "exists", "otherwise", "return", "user", "token" ]
def create_user_or_return_token(): resp_data = {} headers = request.headers or {} if 'Authorization' not in headers: return bad_request("Missing 'Authorization' header in request") try: login, password = parse_authorization_header(headers.get('Authorization')) except Exception as e...
[ "def", "create_user_or_return_token", "(", ")", ":", "resp_data", "=", "{", "}", "headers", "=", "request", ".", "headers", "or", "{", "}", "if", "'Authorization'", "not", "in", "headers", ":", "return", "bad_request", "(", "\"Missing 'Authorization' header in req...
Create user and return it's token if user doesn't exists otherwise return user token
[ "Create", "user", "and", "return", "it", "'", "s", "token", "if", "user", "doesn", "'", "t", "exists", "otherwise", "return", "user", "token" ]
[ "\"\"\" Create user and return it's token if user doesn't exists otherwise return user token \"\"\"", "# response data", "# Check request", "# Parse auth", "# Return token if user already exists", "# Check credentials", "# Create user", "# Commit changes to db" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
375cd8f5cf0c7eedbbf98f144f1569ac88a97f2c
TheHolyWay/ficus-tracker-backend
ficus-tracker/app/api_v1/flowers.py
[ "MIT" ]
Python
create_flower
<not_specific>
def create_flower(): """ Create flower if it doesn't exists """ logging.info("Called creating flower endpoint ...") headers = request.headers or {} # Check request if 'Authorization' not in headers: return bad_request("Missing 'Authorization' header in request") # Parse auth try: ...
Create flower if it doesn't exists
Create flower if it doesn't exists
[ "Create", "flower", "if", "it", "doesn", "'", "t", "exists" ]
def create_flower(): logging.info("Called creating flower endpoint ...") headers = request.headers or {} if 'Authorization' not in headers: return bad_request("Missing 'Authorization' header in request") try: login, password = parse_authorization_header(headers.get('Authorization')) ...
[ "def", "create_flower", "(", ")", ":", "logging", ".", "info", "(", "\"Called creating flower endpoint ...\"", ")", "headers", "=", "request", ".", "headers", "or", "{", "}", "if", "'Authorization'", "not", "in", "headers", ":", "return", "bad_request", "(", "...
Create flower if it doesn't exists
[ "Create", "flower", "if", "it", "doesn", "'", "t", "exists" ]
[ "\"\"\" Create flower if it doesn't exists \"\"\"", "# Check request", "# Parse auth", "# Commit changes to db" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7c076f083d68ddd0fbd96c9b0317545d2d30de08
TheHolyWay/ficus-tracker-backend
ficus-tracker/app/utils.py
[ "MIT" ]
Python
create_response_from_data_with_code
<not_specific>
def create_response_from_data_with_code(data, code: int=200): """ Apply method jsonify to specified data and add status_code to result""" resp = jsonify(data) resp.status_code = code return resp
Apply method jsonify to specified data and add status_code to result
Apply method jsonify to specified data and add status_code to result
[ "Apply", "method", "jsonify", "to", "specified", "data", "and", "add", "status_code", "to", "result" ]
def create_response_from_data_with_code(data, code: int=200): resp = jsonify(data) resp.status_code = code return resp
[ "def", "create_response_from_data_with_code", "(", "data", ",", "code", ":", "int", "=", "200", ")", ":", "resp", "=", "jsonify", "(", "data", ")", "resp", ".", "status_code", "=", "code", "return", "resp" ]
Apply method jsonify to specified data and add status_code to result
[ "Apply", "method", "jsonify", "to", "specified", "data", "and", "add", "status_code", "to", "result" ]
[ "\"\"\" Apply method jsonify to specified data and add status_code to result\"\"\"" ]
[ { "param": "data", "type": null }, { "param": "code", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "data", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "code", "type": "int", "docstring": null, "docstring_tokens": ...
7c076f083d68ddd0fbd96c9b0317545d2d30de08
TheHolyWay/ficus-tracker-backend
ficus-tracker/app/utils.py
[ "MIT" ]
Python
authorize
<not_specific>
def authorize(login, password, user=None): """ Return true if user credentials correct """ if not user: user = User.query.filter_by(login=login).first() if user: return user.check_password(password) else: return False
Return true if user credentials correct
Return true if user credentials correct
[ "Return", "true", "if", "user", "credentials", "correct" ]
def authorize(login, password, user=None): if not user: user = User.query.filter_by(login=login).first() if user: return user.check_password(password) else: return False
[ "def", "authorize", "(", "login", ",", "password", ",", "user", "=", "None", ")", ":", "if", "not", "user", ":", "user", "=", "User", ".", "query", ".", "filter_by", "(", "login", "=", "login", ")", ".", "first", "(", ")", "if", "user", ":", "ret...
Return true if user credentials correct
[ "Return", "true", "if", "user", "credentials", "correct" ]
[ "\"\"\" Return true if user credentials correct \"\"\"" ]
[ { "param": "login", "type": null }, { "param": "password", "type": null }, { "param": "user", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "login", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "password", "type": null, "docstring": null, "docstring_token...
7c076f083d68ddd0fbd96c9b0317545d2d30de08
TheHolyWay/ficus-tracker-backend
ficus-tracker/app/utils.py
[ "MIT" ]
Python
parse_authorization_header
<not_specific>
def parse_authorization_header(auth_header): """ Parse auth header and return (login, password) """ auth_str = auth_header.split(' ')[1] # Remove 'Basic ' part auth_str = base64.b64decode(auth_str).decode() # Decode from base64 auth_str = auth_str.split(':') return auth_str[0], auth_str[1]
Parse auth header and return (login, password)
Parse auth header and return (login, password)
[ "Parse", "auth", "header", "and", "return", "(", "login", "password", ")" ]
def parse_authorization_header(auth_header): auth_str = auth_header.split(' ')[1] auth_str = base64.b64decode(auth_str).decode() auth_str = auth_str.split(':') return auth_str[0], auth_str[1]
[ "def", "parse_authorization_header", "(", "auth_header", ")", ":", "auth_str", "=", "auth_header", ".", "split", "(", "' '", ")", "[", "1", "]", "auth_str", "=", "base64", ".", "b64decode", "(", "auth_str", ")", ".", "decode", "(", ")", "auth_str", "=", ...
Parse auth header and return (login, password)
[ "Parse", "auth", "header", "and", "return", "(", "login", "password", ")" ]
[ "\"\"\" Parse auth header and return (login, password) \"\"\"", "# Remove 'Basic ' part", "# Decode from base64" ]
[ { "param": "auth_header", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "auth_header", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
193cafd3f514c2e0ea372734a5b5def5dc70619a
coleslaw481/nbgwas_rest
nbgwas_rest/__init__.py
[ "BSD-3-Clause" ]
Python
create_task
<not_specific>
def create_task(params): """ Creates a task by consuming data from request_obj passed in and persisting that information to the filesystem under JOB_PATH/SUBMIT_DIR/<IP ADDRESS>/UUID with various parameters stored in TASK_JSON file and if the 'network' file is set that data is dumped to NETWORK_...
Creates a task by consuming data from request_obj passed in and persisting that information to the filesystem under JOB_PATH/SUBMIT_DIR/<IP ADDRESS>/UUID with various parameters stored in TASK_JSON file and if the 'network' file is set that data is dumped to NETWORK_DATA file within the directory ...
Creates a task by consuming data from request_obj passed in and persisting that information to the filesystem under JOB_PATH/SUBMIT_DIR//UUID with various parameters stored in TASK_JSON file and if the 'network' file is set that data is dumped to NETWORK_DATA file within the directory
[ "Creates", "a", "task", "by", "consuming", "data", "from", "request_obj", "passed", "in", "and", "persisting", "that", "information", "to", "the", "filesystem", "under", "JOB_PATH", "/", "SUBMIT_DIR", "//", "UUID", "with", "various", "parameters", "stored", "in"...
def create_task(params): params['uuid'] = get_uuid() params['tasktype'] = SNP_ANALYZER_TASK taskpath = os.path.join(get_submit_dir(), str(params['remoteip']), str(params['uuid'])) try: original_umask = os.umask(0) os.makedirs(taskpath, mode=0o775) finally:...
[ "def", "create_task", "(", "params", ")", ":", "params", "[", "'uuid'", "]", "=", "get_uuid", "(", ")", "params", "[", "'tasktype'", "]", "=", "SNP_ANALYZER_TASK", "taskpath", "=", "os", ".", "path", ".", "join", "(", "get_submit_dir", "(", ")", ",", "...
Creates a task by consuming data from request_obj passed in and persisting that information to the filesystem under JOB_PATH/SUBMIT_DIR/<IP ADDRESS>/UUID with various parameters stored in TASK_JSON file and if the 'network' file is set that data is dumped to NETWORK_DATA file within the directory
[ "Creates", "a", "task", "by", "consuming", "data", "from", "request_obj", "passed", "in", "and", "persisting", "that", "information", "to", "the", "filesystem", "under", "JOB_PATH", "/", "SUBMIT_DIR", "/", "<IP", "ADDRESS", ">", "/", "UUID", "with", "various",...
[ "\"\"\"\n Creates a task by consuming data from request_obj passed in\n and persisting that information to the filesystem under\n JOB_PATH/SUBMIT_DIR/<IP ADDRESS>/UUID with various parameters\n stored in TASK_JSON file and if the 'network' file is set\n that data is dumped to NETWORK_DATA file within...
[ { "param": "params", "type": null } ]
{ "returns": [ { "docstring": "string that is a uuid which denotes directory name", "docstring_tokens": [ "string", "that", "is", "a", "uuid", "which", "denotes", "directory", "name" ], "type": null } ], "raise...
193cafd3f514c2e0ea372734a5b5def5dc70619a
coleslaw481/nbgwas_rest
nbgwas_rest/__init__.py
[ "BSD-3-Clause" ]
Python
log_task_json_file
<not_specific>
def log_task_json_file(taskpath): """ Writes information about task to logger :param taskpath: path to task :return: None """ if taskpath is None: return None tmp_task_json = TASK_JSON taskfilename = os.path.join(taskpath, tmp_task_json) if not os.path.isfile(taskfilename):...
Writes information about task to logger :param taskpath: path to task :return: None
Writes information about task to logger
[ "Writes", "information", "about", "task", "to", "logger" ]
def log_task_json_file(taskpath): if taskpath is None: return None tmp_task_json = TASK_JSON taskfilename = os.path.join(taskpath, tmp_task_json) if not os.path.isfile(taskfilename): return None with open(taskfilename, 'r') as f: data = json.load(f) app.logger.info('J...
[ "def", "log_task_json_file", "(", "taskpath", ")", ":", "if", "taskpath", "is", "None", ":", "return", "None", "tmp_task_json", "=", "TASK_JSON", "taskfilename", "=", "os", ".", "path", ".", "join", "(", "taskpath", ",", "tmp_task_json", ")", "if", "not", ...
Writes information about task to logger
[ "Writes", "information", "about", "task", "to", "logger" ]
[ "\"\"\"\n Writes information about task to logger\n :param taskpath: path to task\n :return: None\n \"\"\"" ]
[ { "param": "taskpath", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "taskpath", "type": null, "docstring": "path to task", "docstring_tokens": [ "path", "to", "...
193cafd3f514c2e0ea372734a5b5def5dc70619a
coleslaw481/nbgwas_rest
nbgwas_rest/__init__.py
[ "BSD-3-Clause" ]
Python
wait_for_task
<not_specific>
def wait_for_task(uuidstr, hintlist=None): """ Waits for task to appear in done directory :param uuidstr: uuid of task :param hintlist: list of ip addresses to search under :return: string containing full path to task or None if not found """ if uuidstr is None: app.logger.error('uui...
Waits for task to appear in done directory :param uuidstr: uuid of task :param hintlist: list of ip addresses to search under :return: string containing full path to task or None if not found
Waits for task to appear in done directory
[ "Waits", "for", "task", "to", "appear", "in", "done", "directory" ]
def wait_for_task(uuidstr, hintlist=None): if uuidstr is None: app.logger.error('uuid is None') return None counter = 0 taskpath = None done_dir = get_done_dir() while counter < app.config[WAIT_COUNT_KEY]: taskpath = get_task(uuidstr, iphintlist=hintlist, ...
[ "def", "wait_for_task", "(", "uuidstr", ",", "hintlist", "=", "None", ")", ":", "if", "uuidstr", "is", "None", ":", "app", ".", "logger", ".", "error", "(", "'uuid is None'", ")", "return", "None", "counter", "=", "0", "taskpath", "=", "None", "done_dir"...
Waits for task to appear in done directory
[ "Waits", "for", "task", "to", "appear", "in", "done", "directory" ]
[ "\"\"\"\n Waits for task to appear in done directory\n :param uuidstr: uuid of task\n :param hintlist: list of ip addresses to search under\n :return: string containing full path to task or None if not found\n \"\"\"" ]
[ { "param": "uuidstr", "type": null }, { "param": "hintlist", "type": null } ]
{ "returns": [ { "docstring": "string containing full path to task or None if not found", "docstring_tokens": [ "string", "containing", "full", "path", "to", "task", "or", "None", "if", "not", "found" ], ...
193cafd3f514c2e0ea372734a5b5def5dc70619a
coleslaw481/nbgwas_rest
nbgwas_rest/__init__.py
[ "BSD-3-Clause" ]
Python
_get_task_parameters
<not_specific>
def _get_task_parameters(self, taskpath): """ Gets task parameters from TASK_JSON file as a dictionary :param taskpath: :return: task parameters :rtype dict: """ taskparams = None try: taskjsonfile = os.path.join(taskpath, TASK_JSON) ...
Gets task parameters from TASK_JSON file as a dictionary :param taskpath: :return: task parameters :rtype dict:
Gets task parameters from TASK_JSON file as a dictionary
[ "Gets", "task", "parameters", "from", "TASK_JSON", "file", "as", "a", "dictionary" ]
def _get_task_parameters(self, taskpath): taskparams = None try: taskjsonfile = os.path.join(taskpath, TASK_JSON) if os.path.isfile(taskjsonfile): with open(taskjsonfile, 'r') as f: taskparams = json.load(f) if REMOTEIP_PARAM in...
[ "def", "_get_task_parameters", "(", "self", ",", "taskpath", ")", ":", "taskparams", "=", "None", "try", ":", "taskjsonfile", "=", "os", ".", "path", ".", "join", "(", "taskpath", ",", "TASK_JSON", ")", "if", "os", ".", "path", ".", "isfile", "(", "tas...
Gets task parameters from TASK_JSON file as a dictionary
[ "Gets", "task", "parameters", "from", "TASK_JSON", "file", "as", "a", "dictionary" ]
[ "\"\"\"\n Gets task parameters from TASK_JSON file as\n a dictionary\n :param taskpath:\n :return: task parameters\n :rtype dict:\n \"\"\"", "# delete the remote ip" ]
[ { "param": "self", "type": null }, { "param": "taskpath", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
193cafd3f514c2e0ea372734a5b5def5dc70619a
coleslaw481/nbgwas_rest
nbgwas_rest/__init__.py
[ "BSD-3-Clause" ]
Python
delete
<not_specific>
def delete(self, id): """ Deletes task associated with {id} passed in """ resp = flask.make_response() try: req_dir = get_delete_request_dir() if not os.path.isdir(req_dir): app.logger.debug('Creating directory: ' + req_dir) ...
Deletes task associated with {id} passed in
Deletes task associated with {id} passed in
[ "Deletes", "task", "associated", "with", "{", "id", "}", "passed", "in" ]
def delete(self, id): resp = flask.make_response() try: req_dir = get_delete_request_dir() if not os.path.isdir(req_dir): app.logger.debug('Creating directory: ' + req_dir) os.makedirs(req_dir, mode=0o755) cleanid = id.strip() ...
[ "def", "delete", "(", "self", ",", "id", ")", ":", "resp", "=", "flask", ".", "make_response", "(", ")", "try", ":", "req_dir", "=", "get_delete_request_dir", "(", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "req_dir", ")", ":", "app", ...
Deletes task associated with {id} passed in
[ "Deletes", "task", "associated", "with", "{", "id", "}", "passed", "in" ]
[ "\"\"\"\n Deletes task associated with {id} passed in\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "id", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "id", "type": null, "docstring": null, "docstring_tokens": [],...
c7998f37466c1493ec4adba9215ea2dbc0025625
AaronYang2333/CSCI_570
records/08-17/conbine1.py
[ "Apache-2.0" ]
Python
merge
None
def merge(self, nums1, m: int, nums2, n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ if n != 0: nums1[m:m + n] = nums2 def insertation_sort(arr): for i in range(len(arr)): pre_idx = i - 1 ...
Do not return anything, modify nums1 in-place instead.
Do not return anything, modify nums1 in-place instead.
[ "Do", "not", "return", "anything", "modify", "nums1", "in", "-", "place", "instead", "." ]
def merge(self, nums1, m: int, nums2, n: int) -> None: if n != 0: nums1[m:m + n] = nums2 def insertation_sort(arr): for i in range(len(arr)): pre_idx = i - 1 current = arr[i] while pre_idx >= 0 and arr[pre_idx] >...
[ "def", "merge", "(", "self", ",", "nums1", ",", "m", ":", "int", ",", "nums2", ",", "n", ":", "int", ")", "->", "None", ":", "if", "n", "!=", "0", ":", "nums1", "[", "m", ":", "m", "+", "n", "]", "=", "nums2", "def", "insertation_sort", "(", ...
Do not return anything, modify nums1 in-place instead.
[ "Do", "not", "return", "anything", "modify", "nums1", "in", "-", "place", "instead", "." ]
[ "\"\"\"\n Do not return anything, modify nums1 in-place instead.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "nums1", "type": null }, { "param": "m", "type": "int" }, { "param": "nums2", "type": null }, { "param": "n", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "nums1", "type": null, "docstring": null, "docstring_tokens": ...
da6b5af74b411229849470e27379afee57a2f280
AaronYang2333/CSCI_570
records/08-13/asda111.py
[ "Apache-2.0" ]
Python
rotate
None
def rotate(self, nums, k: int) -> None: """ Do not return anything, modify nums in-place instead. """ k %= len(nums) if k <= len(nums): res = [] while k: val = nums.pop() res.append(val) k -= 1 f...
Do not return anything, modify nums in-place instead.
Do not return anything, modify nums in-place instead.
[ "Do", "not", "return", "anything", "modify", "nums", "in", "-", "place", "instead", "." ]
def rotate(self, nums, k: int) -> None: k %= len(nums) if k <= len(nums): res = [] while k: val = nums.pop() res.append(val) k -= 1 for val in res: nums.insert(0, val) else: nums.rever...
[ "def", "rotate", "(", "self", ",", "nums", ",", "k", ":", "int", ")", "->", "None", ":", "k", "%=", "len", "(", "nums", ")", "if", "k", "<=", "len", "(", "nums", ")", ":", "res", "=", "[", "]", "while", "k", ":", "val", "=", "nums", ".", ...
Do not return anything, modify nums in-place instead.
[ "Do", "not", "return", "anything", "modify", "nums", "in", "-", "place", "instead", "." ]
[ "\"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "nums", "type": null }, { "param": "k", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "nums", "type": null, "docstring": null, "docstring_tokens": [...
da6b5af74b411229849470e27379afee57a2f280
AaronYang2333/CSCI_570
records/08-13/asda111.py
[ "Apache-2.0" ]
Python
rotate2
None
def rotate2(self, nums, k: int) -> None: """ Do not return anything, modify nums in-place instead. """ from collections import deque ss = deque(nums) k %= len(nums) while k: val = ss.pop() ss.appendleft(val) k -= 1 nums[...
Do not return anything, modify nums in-place instead.
Do not return anything, modify nums in-place instead.
[ "Do", "not", "return", "anything", "modify", "nums", "in", "-", "place", "instead", "." ]
def rotate2(self, nums, k: int) -> None: from collections import deque ss = deque(nums) k %= len(nums) while k: val = ss.pop() ss.appendleft(val) k -= 1 nums[:] = ss
[ "def", "rotate2", "(", "self", ",", "nums", ",", "k", ":", "int", ")", "->", "None", ":", "from", "collections", "import", "deque", "ss", "=", "deque", "(", "nums", ")", "k", "%=", "len", "(", "nums", ")", "while", "k", ":", "val", "=", "ss", "...
Do not return anything, modify nums in-place instead.
[ "Do", "not", "return", "anything", "modify", "nums", "in", "-", "place", "instead", "." ]
[ "\"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "nums", "type": null }, { "param": "k", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "nums", "type": null, "docstring": null, "docstring_tokens": [...
1f338ad33bae27d7c29d7eb88cb737e85a636db9
AaronYang2333/CSCI_570
records/07-30/test_and.py
[ "Apache-2.0" ]
Python
solveSudoku
None
def solveSudoku(self, board) -> None: """ Do not return anything, modify board in-place instead. """ row = [set(range(1, 10)) for _ in range(9)] col = [set(range(1, 10)) for _ in range(9)] box = [set(range(1, 10)) for _ in range(9)] empty = [] for i in ra...
Do not return anything, modify board in-place instead.
Do not return anything, modify board in-place instead.
[ "Do", "not", "return", "anything", "modify", "board", "in", "-", "place", "instead", "." ]
def solveSudoku(self, board) -> None: row = [set(range(1, 10)) for _ in range(9)] col = [set(range(1, 10)) for _ in range(9)] box = [set(range(1, 10)) for _ in range(9)] empty = [] for i in range(9): for j in range(9): if board[i][j] != '.': ...
[ "def", "solveSudoku", "(", "self", ",", "board", ")", "->", "None", ":", "row", "=", "[", "set", "(", "range", "(", "1", ",", "10", ")", ")", "for", "_", "in", "range", "(", "9", ")", "]", "col", "=", "[", "set", "(", "range", "(", "1", ","...
Do not return anything, modify board in-place instead.
[ "Do", "not", "return", "anything", "modify", "board", "in", "-", "place", "instead", "." ]
[ "\"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"", "# search fewest candidates first", "# sort the list IN PLACE", "# terminator", "# for ll in cands:" ]
[ { "param": "self", "type": null }, { "param": "board", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "board", "type": null, "docstring": null, "docstring_tokens": ...
881c1300bb29afc39e4e4edb4f3c88ca48777826
AaronYang2333/CSCI_570
records/07-25/adada.py
[ "Apache-2.0" ]
Python
rotate
null
def rotate(self, nums, k): """ Do not return anything, modify nums in-place instead. """ if nums and k > 0: while k > 0: nums, val = nums[:-1], nums[-1] nums.insert(0, val) k -= 1 print(nums)
Do not return anything, modify nums in-place instead.
Do not return anything, modify nums in-place instead.
[ "Do", "not", "return", "anything", "modify", "nums", "in", "-", "place", "instead", "." ]
def rotate(self, nums, k): if nums and k > 0: while k > 0: nums, val = nums[:-1], nums[-1] nums.insert(0, val) k -= 1 print(nums)
[ "def", "rotate", "(", "self", ",", "nums", ",", "k", ")", ":", "if", "nums", "and", "k", ">", "0", ":", "while", "k", ">", "0", ":", "nums", ",", "val", "=", "nums", "[", ":", "-", "1", "]", ",", "nums", "[", "-", "1", "]", "nums", ".", ...
Do not return anything, modify nums in-place instead.
[ "Do", "not", "return", "anything", "modify", "nums", "in", "-", "place", "instead", "." ]
[ "\"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "nums", "type": null }, { "param": "k", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "nums", "type": null, "docstring": null, "docstring_tokens": [...
105ea3e3a3cd4e5b1ed40b5e6df1c43a240c42e0
AaronYang2333/CSCI_570
records/01-05/sss.py
[ "Apache-2.0" ]
Python
rotate
None
def rotate(self, nums, k: int) -> None: """ Do not return anything, modify nums in-place instead. """ size = len(nums) nums[:] = nums[size - k:] + nums[:size - k] print(nums)
Do not return anything, modify nums in-place instead.
Do not return anything, modify nums in-place instead.
[ "Do", "not", "return", "anything", "modify", "nums", "in", "-", "place", "instead", "." ]
def rotate(self, nums, k: int) -> None: size = len(nums) nums[:] = nums[size - k:] + nums[:size - k] print(nums)
[ "def", "rotate", "(", "self", ",", "nums", ",", "k", ":", "int", ")", "->", "None", ":", "size", "=", "len", "(", "nums", ")", "nums", "[", ":", "]", "=", "nums", "[", "size", "-", "k", ":", "]", "+", "nums", "[", ":", "size", "-", "k", "...
Do not return anything, modify nums in-place instead.
[ "Do", "not", "return", "anything", "modify", "nums", "in", "-", "place", "instead", "." ]
[ "\"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "nums", "type": null }, { "param": "k", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "nums", "type": null, "docstring": null, "docstring_tokens": [...
97f71c267369876093780ede24e209df0693489e
harukou/SpectralNet
src/core/data.py
[ "MIT" ]
Python
load_data
<not_specific>
def load_data(params): ''' Convenience function: reads from disk, downloads, or generates the data specified in params ''' if params['dset'] == 'reuters': with h5py.File('../../data/reuters/reutersidf_total.h5', 'r') as f: x = np.asarray(f.get('data'), dtype='float32') y ...
Convenience function: reads from disk, downloads, or generates the data specified in params
Convenience function: reads from disk, downloads, or generates the data specified in params
[ "Convenience", "function", ":", "reads", "from", "disk", "downloads", "or", "generates", "the", "data", "specified", "in", "params" ]
def load_data(params): if params['dset'] == 'reuters': with h5py.File('../../data/reuters/reutersidf_total.h5', 'r') as f: x = np.asarray(f.get('data'), dtype='float32') y = np.asarray(f.get('labels'), dtype='float32') n_train = int(0.9 * len(x)) x_train, x_te...
[ "def", "load_data", "(", "params", ")", ":", "if", "params", "[", "'dset'", "]", "==", "'reuters'", ":", "with", "h5py", ".", "File", "(", "'../../data/reuters/reutersidf_total.h5'", ",", "'r'", ")", "as", "f", ":", "x", "=", "np", ".", "asarray", "(", ...
Convenience function: reads from disk, downloads, or generates the data specified in params
[ "Convenience", "function", ":", "reads", "from", "disk", "downloads", "or", "generates", "the", "data", "specified", "in", "params" ]
[ "'''\n Convenience function: reads from disk, downloads, or generates the data specified in params\n '''" ]
[ { "param": "params", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "params", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
97f71c267369876093780ede24e209df0693489e
harukou/SpectralNet
src/core/data.py
[ "MIT" ]
Python
embed_data
<not_specific>
def embed_data(x, dset): ''' Convenience function: embeds x into the code space using the corresponding autoencoder (specified by dset). ''' if not len(x): return np.zeros(shape=(0, 10)) if dset == 'reuters': dset = 'reuters10k' json_path = '../pretrain_weights/ae_{}.json'.f...
Convenience function: embeds x into the code space using the corresponding autoencoder (specified by dset).
Convenience function: embeds x into the code space using the corresponding autoencoder (specified by dset).
[ "Convenience", "function", ":", "embeds", "x", "into", "the", "code", "space", "using", "the", "corresponding", "autoencoder", "(", "specified", "by", "dset", ")", "." ]
def embed_data(x, dset): if not len(x): return np.zeros(shape=(0, 10)) if dset == 'reuters': dset = 'reuters10k' json_path = '../pretrain_weights/ae_{}.json'.format(dset) weights_path = '../pretrain_weights/ae_{}_weights.h5'.format(dset) with open(json_path) as f: pt_ae = mod...
[ "def", "embed_data", "(", "x", ",", "dset", ")", ":", "if", "not", "len", "(", "x", ")", ":", "return", "np", ".", "zeros", "(", "shape", "=", "(", "0", ",", "10", ")", ")", "if", "dset", "==", "'reuters'", ":", "dset", "=", "'reuters10k'", "js...
Convenience function: embeds x into the code space using the corresponding autoencoder (specified by dset).
[ "Convenience", "function", ":", "embeds", "x", "into", "the", "code", "space", "using", "the", "corresponding", "autoencoder", "(", "specified", "by", "dset", ")", "." ]
[ "'''\n Convenience function: embeds x into the code space using the corresponding\n autoencoder (specified by dset).\n '''" ]
[ { "param": "x", "type": null }, { "param": "dset", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "x", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "dset", "type": null, "docstring": null, "docstring_tokens": [], ...
9b7929954f7c125ea5d48def79c05388e6d05213
harukou/SpectralNet
src/core/util.py
[ "MIT" ]
Python
on_epoch_end
<not_specific>
def on_epoch_end(self, epoch, logs=None): ''' Per epoch logic for managing learning rate and early stopping ''' stop_training = False # check if we need to stop or increase scheduler stage if isinstance(logs, dict): loss = logs['val_loss'] else: ...
Per epoch logic for managing learning rate and early stopping
Per epoch logic for managing learning rate and early stopping
[ "Per", "epoch", "logic", "for", "managing", "learning", "rate", "and", "early", "stopping" ]
def on_epoch_end(self, epoch, logs=None): stop_training = False if isinstance(logs, dict): loss = logs['val_loss'] else: loss = logs if loss <= self.best_loss: self.best_loss = loss self.wait = 0 else: self.wait += 1 ...
[ "def", "on_epoch_end", "(", "self", ",", "epoch", ",", "logs", "=", "None", ")", ":", "stop_training", "=", "False", "if", "isinstance", "(", "logs", ",", "dict", ")", ":", "loss", "=", "logs", "[", "'val_loss'", "]", "else", ":", "loss", "=", "logs"...
Per epoch logic for managing learning rate and early stopping
[ "Per", "epoch", "logic", "for", "managing", "learning", "rate", "and", "early", "stopping" ]
[ "'''\n Per epoch logic for managing learning rate and early stopping\n '''", "# check if we need to stop or increase scheduler stage", "# calculate and set learning rate", "# built in stopping if lr is way too small", "# for keras" ]
[ { "param": "self", "type": null }, { "param": "epoch", "type": null }, { "param": "logs", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "epoch", "type": null, "docstring": null, "docstring_tokens": ...
9b7929954f7c125ea5d48def79c05388e6d05213
harukou/SpectralNet
src/core/util.py
[ "MIT" ]
Python
print_accuracy
null
def print_accuracy(cluster_assignments, y_true, n_clusters, extra_identifier=''): ''' Convenience function: prints the accuracy ''' # get accuracy accuracy, confusion_matrix = get_accuracy(cluster_assignments, y_true, n_clusters) # get the confusion matrix print('confusion matrix{}: '.format...
Convenience function: prints the accuracy
Convenience function: prints the accuracy
[ "Convenience", "function", ":", "prints", "the", "accuracy" ]
def print_accuracy(cluster_assignments, y_true, n_clusters, extra_identifier=''): accuracy, confusion_matrix = get_accuracy(cluster_assignments, y_true, n_clusters) print('confusion matrix{}: '.format(extra_identifier)) print(confusion_matrix) print('spectralNet{} accuracy: '.format(extra_identifier) + ...
[ "def", "print_accuracy", "(", "cluster_assignments", ",", "y_true", ",", "n_clusters", ",", "extra_identifier", "=", "''", ")", ":", "accuracy", ",", "confusion_matrix", "=", "get_accuracy", "(", "cluster_assignments", ",", "y_true", ",", "n_clusters", ")", "print...
Convenience function: prints the accuracy
[ "Convenience", "function", ":", "prints", "the", "accuracy" ]
[ "'''\n Convenience function: prints the accuracy\n '''", "# get accuracy", "# get the confusion matrix" ]
[ { "param": "cluster_assignments", "type": null }, { "param": "y_true", "type": null }, { "param": "n_clusters", "type": null }, { "param": "extra_identifier", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cluster_assignments", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "y_true", "type": null, "docstring": null, "doc...
9b7929954f7c125ea5d48def79c05388e6d05213
harukou/SpectralNet
src/core/util.py
[ "MIT" ]
Python
grassmann
<not_specific>
def grassmann(A, B): ''' Computes the Grassmann distance between matrices A and B A, B: input matrices returns: the grassmann distance between A and B ''' M = np.dot(np.transpose(A), B) _, s, _ = np.linalg.svd(M, full_matrices=False) s = 1 - np.square(s) grassmann = np.sum...
Computes the Grassmann distance between matrices A and B A, B: input matrices returns: the grassmann distance between A and B
Computes the Grassmann distance between matrices A and B A, B: input matrices the grassmann distance between A and B
[ "Computes", "the", "Grassmann", "distance", "between", "matrices", "A", "and", "B", "A", "B", ":", "input", "matrices", "the", "grassmann", "distance", "between", "A", "and", "B" ]
def grassmann(A, B): M = np.dot(np.transpose(A), B) _, s, _ = np.linalg.svd(M, full_matrices=False) s = 1 - np.square(s) grassmann = np.sum(s) return grassmann
[ "def", "grassmann", "(", "A", ",", "B", ")", ":", "M", "=", "np", ".", "dot", "(", "np", ".", "transpose", "(", "A", ")", ",", "B", ")", "_", ",", "s", ",", "_", "=", "np", ".", "linalg", ".", "svd", "(", "M", ",", "full_matrices", "=", "...
Computes the Grassmann distance between matrices A and B A, B: input matrices
[ "Computes", "the", "Grassmann", "distance", "between", "matrices", "A", "and", "B", "A", "B", ":", "input", "matrices" ]
[ "'''\n Computes the Grassmann distance between matrices A and B\n\n A, B: input matrices\n\n returns: the grassmann distance between A and B\n '''" ]
[ { "param": "A", "type": null }, { "param": "B", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "A", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "B", "type": null, "docstring": null, "docstring_tokens": [], ...
9b7929954f7c125ea5d48def79c05388e6d05213
harukou/SpectralNet
src/core/util.py
[ "MIT" ]
Python
spectral_clustering
<not_specific>
def spectral_clustering(x, scale, n_nbrs=None, affinity='full', W=None): ''' Computes the eigenvectors of the graph Laplacian of x, using the full Gaussian affinity matrix (full), the symmetrized Gaussian affinity matrix with k nonzero affinities for each point (knn), or the Siamese affinity mat...
Computes the eigenvectors of the graph Laplacian of x, using the full Gaussian affinity matrix (full), the symmetrized Gaussian affinity matrix with k nonzero affinities for each point (knn), or the Siamese affinity matrix (siamese) x: input data n_nbrs: number of neighbors us...
Computes the eigenvectors of the graph Laplacian of x, using the full Gaussian affinity matrix (full), the symmetrized Gaussian affinity matrix with k nonzero affinities for each point (knn), or the Siamese affinity matrix (siamese) input data n_nbrs: number of neighbors used affinity: the aforementeiond affinit...
[ "Computes", "the", "eigenvectors", "of", "the", "graph", "Laplacian", "of", "x", "using", "the", "full", "Gaussian", "affinity", "matrix", "(", "full", ")", "the", "symmetrized", "Gaussian", "affinity", "matrix", "with", "k", "nonzero", "affinities", "for", "e...
def spectral_clustering(x, scale, n_nbrs=None, affinity='full', W=None): if affinity == 'full': W = K.eval(cf.full_affinity(K.variable(x), scale)) elif affinity == 'knn': if n_nbrs is None: raise ValueError('n_nbrs must be provided if affinity = knn!') W = K.eval(cf.knn_aff...
[ "def", "spectral_clustering", "(", "x", ",", "scale", ",", "n_nbrs", "=", "None", ",", "affinity", "=", "'full'", ",", "W", "=", "None", ")", ":", "if", "affinity", "==", "'full'", ":", "W", "=", "K", ".", "eval", "(", "cf", ".", "full_affinity", "...
Computes the eigenvectors of the graph Laplacian of x, using the full Gaussian affinity matrix (full), the symmetrized Gaussian affinity matrix with k nonzero affinities for each point (knn), or the Siamese affinity matrix (siamese)
[ "Computes", "the", "eigenvectors", "of", "the", "graph", "Laplacian", "of", "x", "using", "the", "full", "Gaussian", "affinity", "matrix", "(", "full", ")", "the", "symmetrized", "Gaussian", "affinity", "matrix", "with", "k", "nonzero", "affinities", "for", "e...
[ "'''\n Computes the eigenvectors of the graph Laplacian of x,\n using the full Gaussian affinity matrix (full), the\n symmetrized Gaussian affinity matrix with k nonzero\n affinities for each point (knn), or the Siamese affinity\n matrix (siamese)\n\n x: input data\n n_nbrs: number...
[ { "param": "x", "type": null }, { "param": "scale", "type": null }, { "param": "n_nbrs", "type": null }, { "param": "affinity", "type": null }, { "param": "W", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "x", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "scale", "type": null, "docstring": null, "docstring_tokens": [],...
0014d4504bbf9fb615f6759803f509fecb327724
harukou/SpectralNet
asmk.py
[ "MIT" ]
Python
L2
<not_specific>
def L2(x,y): ''' x,y: 2 matrices, each row is a data return L2 distance matrix of x and y ''' xx = np.sum(x*x,axis=1,keepdims=1) # row*1 yy = np.sum(y*y,axis=1,keepdims=1) # row*1 xy = x.dot(y.T) # row*row x2 = repmat(xx.T,len(yy),1) # row*row y2 = repm...
x,y: 2 matrices, each row is a data return L2 distance matrix of x and y
x,y: 2 matrices, each row is a data return L2 distance matrix of x and y
[ "x", "y", ":", "2", "matrices", "each", "row", "is", "a", "data", "return", "L2", "distance", "matrix", "of", "x", "and", "y" ]
def L2(x,y): xx = np.sum(x*x,axis=1,keepdims=1) yy = np.sum(y*y,axis=1,keepdims=1) xy = x.dot(y.T) x2 = repmat(xx.T,len(yy),1) y2 = repmat(yy,1,len(xx)) d = x2 + y2 - 2*xy return d
[ "def", "L2", "(", "x", ",", "y", ")", ":", "xx", "=", "np", ".", "sum", "(", "x", "*", "x", ",", "axis", "=", "1", ",", "keepdims", "=", "1", ")", "yy", "=", "np", ".", "sum", "(", "y", "*", "y", ",", "axis", "=", "1", ",", "keepdims", ...
x,y: 2 matrices, each row is a data return L2 distance matrix of x and y
[ "x", "y", ":", "2", "matrices", "each", "row", "is", "a", "data", "return", "L2", "distance", "matrix", "of", "x", "and", "y" ]
[ "'''\n x,y: 2 matrices, each row is a data\n return L2 distance matrix of x and y\n '''", "# row*1", "# row*1", "# row*row", "# row*row", "# row*row" ]
[ { "param": "x", "type": null }, { "param": "y", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "x", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "y", "type": null, "docstring": null, "docstring_tokens": [], ...
8028b19f73dc27f43e28fa521bbe4e9007dbc3c7
harukou/SpectralNet
src/core/layer.py
[ "MIT" ]
Python
orthonorm_op
<not_specific>
def orthonorm_op(x, epsilon=1e-7): ''' Computes a matrix that orthogonalizes the input matrix x x: an n x d input matrix eps: epsilon to prevent nonzero values in the diagonal entries of x returns: a d x d matrix, ortho_weights, which orthogonalizes x by right multiplica...
Computes a matrix that orthogonalizes the input matrix x x: an n x d input matrix eps: epsilon to prevent nonzero values in the diagonal entries of x returns: a d x d matrix, ortho_weights, which orthogonalizes x by right multiplication
Computes a matrix that orthogonalizes the input matrix x x: an n x d input matrix eps: epsilon to prevent nonzero values in the diagonal entries of x a d x d matrix, ortho_weights, which orthogonalizes x by right multiplication
[ "Computes", "a", "matrix", "that", "orthogonalizes", "the", "input", "matrix", "x", "x", ":", "an", "n", "x", "d", "input", "matrix", "eps", ":", "epsilon", "to", "prevent", "nonzero", "values", "in", "the", "diagonal", "entries", "of", "x", "a", "d", ...
def orthonorm_op(x, epsilon=1e-7): x_2 = K.dot(K.transpose(x), x) x_2 += K.eye(K.int_shape(x)[1])*epsilon L = tf.cholesky(x_2) ortho_weights = tf.transpose(tf.matrix_inverse(L)) * tf.sqrt(tf.cast(tf.shape(x)[0], dtype=K.floatx())) return ortho_weights
[ "def", "orthonorm_op", "(", "x", ",", "epsilon", "=", "1e-7", ")", ":", "x_2", "=", "K", ".", "dot", "(", "K", ".", "transpose", "(", "x", ")", ",", "x", ")", "x_2", "+=", "K", ".", "eye", "(", "K", ".", "int_shape", "(", "x", ")", "[", "1"...
Computes a matrix that orthogonalizes the input matrix x x: an n x d input matrix eps: epsilon to prevent nonzero values in the diagonal entries of x
[ "Computes", "a", "matrix", "that", "orthogonalizes", "the", "input", "matrix", "x", "x", ":", "an", "n", "x", "d", "input", "matrix", "eps", ":", "epsilon", "to", "prevent", "nonzero", "values", "in", "the", "diagonal", "entries", "of", "x" ]
[ "'''\n Computes a matrix that orthogonalizes the input matrix x\n\n x: an n x d input matrix\n eps: epsilon to prevent nonzero values in the diagonal entries of x\n\n returns: a d x d matrix, ortho_weights, which orthogonalizes x by\n right multiplication\n '''" ]
[ { "param": "x", "type": null }, { "param": "epsilon", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "x", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "epsilon", "type": null, "docstring": null, "docstring_tokens": [...
8028b19f73dc27f43e28fa521bbe4e9007dbc3c7
harukou/SpectralNet
src/core/layer.py
[ "MIT" ]
Python
Orthonorm
<not_specific>
def Orthonorm(x, name=None): ''' Builds keras layer that handles orthogonalization of x x: an n x d input matrix name: name of the keras layer returns: a keras layer instance. during evaluation, the instance returns an n x d orthogonal matrix if x is full rank and not sin...
Builds keras layer that handles orthogonalization of x x: an n x d input matrix name: name of the keras layer returns: a keras layer instance. during evaluation, the instance returns an n x d orthogonal matrix if x is full rank and not singular
Builds keras layer that handles orthogonalization of x x: an n x d input matrix name: name of the keras layer a keras layer instance. during evaluation, the instance returns an n x d orthogonal matrix if x is full rank and not singular
[ "Builds", "keras", "layer", "that", "handles", "orthogonalization", "of", "x", "x", ":", "an", "n", "x", "d", "input", "matrix", "name", ":", "name", "of", "the", "keras", "layer", "a", "keras", "layer", "instance", ".", "during", "evaluation", "the", "i...
def Orthonorm(x, name=None): d = x.get_shape().as_list()[-1] ortho_weights = orthonorm_op(x) ortho_weights_store = K.variable(np.zeros((d,d))) ortho_weights_update = tf.assign(ortho_weights_store, ortho_weights, name='ortho_weights_update') l = Lambda(lambda x: K.in_train_phase(K.dot(x, ortho_weight...
[ "def", "Orthonorm", "(", "x", ",", "name", "=", "None", ")", ":", "d", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "-", "1", "]", "ortho_weights", "=", "orthonorm_op", "(", "x", ")", "ortho_weights_store", "=", "K", ".", ...
Builds keras layer that handles orthogonalization of x x: an n x d input matrix name: name of the keras layer
[ "Builds", "keras", "layer", "that", "handles", "orthogonalization", "of", "x", "x", ":", "an", "n", "x", "d", "input", "matrix", "name", ":", "name", "of", "the", "keras", "layer" ]
[ "'''\n Builds keras layer that handles orthogonalization of x\n\n x: an n x d input matrix\n name: name of the keras layer\n\n returns: a keras layer instance. during evaluation, the instance returns an n x d orthogonal matrix\n if x is full rank and not singular\n '''", "#...
[ { "param": "x", "type": null }, { "param": "name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "x", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "name", "type": null, "docstring": null, "docstring_tokens": [], ...
8028b19f73dc27f43e28fa521bbe4e9007dbc3c7
harukou/SpectralNet
src/core/layer.py
[ "MIT" ]
Python
stack_layers
<not_specific>
def stack_layers(inputs, layers, kernel_initializer='glorot_uniform'): ''' Builds the architecture of the network by applying each layer specified in layers to inputs. inputs: a dict containing input_types and input_placeholders for each key and value pair, respecively. for spectralnet,...
Builds the architecture of the network by applying each layer specified in layers to inputs. inputs: a dict containing input_types and input_placeholders for each key and value pair, respecively. for spectralnet, this means the input_types 'Unlabeled' and 'Orthonorm'* layers: a lis...
Builds the architecture of the network by applying each layer specified in layers to inputs. inputs: a dict containing input_types and input_placeholders for each key and value pair, respecively. for spectralnet, this means the input_types 'Unlabeled' and 'Orthonorm' layers: a list of dicts containing all layer...
[ "Builds", "the", "architecture", "of", "the", "network", "by", "applying", "each", "layer", "specified", "in", "layers", "to", "inputs", ".", "inputs", ":", "a", "dict", "containing", "input_types", "and", "input_placeholders", "for", "each", "key", "and", "va...
def stack_layers(inputs, layers, kernel_initializer='glorot_uniform'): outputs = dict() for key in inputs: outputs[key]=inputs[key] for layer in layers: l2_reg = layer.get('l2_reg') if l2_reg: l2_reg = l2(layer['l2_reg']) if layer['type'] == 'softplus_reg': ...
[ "def", "stack_layers", "(", "inputs", ",", "layers", ",", "kernel_initializer", "=", "'glorot_uniform'", ")", ":", "outputs", "=", "dict", "(", ")", "for", "key", "in", "inputs", ":", "outputs", "[", "key", "]", "=", "inputs", "[", "key", "]", "for", "...
Builds the architecture of the network by applying each layer specified in layers to inputs.
[ "Builds", "the", "architecture", "of", "the", "network", "by", "applying", "each", "layer", "specified", "in", "layers", "to", "inputs", "." ]
[ "'''\n Builds the architecture of the network by applying each layer specified in layers to inputs.\n\n inputs: a dict containing input_types and input_placeholders for each key and value pair, respecively.\n for spectralnet, this means the input_types 'Unlabeled' and 'Orthonorm'*\n laye...
[ { "param": "inputs", "type": null }, { "param": "layers", "type": null }, { "param": "kernel_initializer", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "inputs", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "layers", "type": null, "docstring": null, "docstring_tokens...
c9ee285b98a5459fcd66f92ec8690e31e5b35b83
harukou/SpectralNet
src/core/train.py
[ "MIT" ]
Python
check_inputs
<not_specific>
def check_inputs(x_unlabeled, x_labeled, y_labeled, y_true): ''' Checks the data inputs to both train_step and predict and creates empty arrays if necessary ''' if x_unlabeled is None: if x_labeled is None: raise Exception("No data, labeled or unlabeled, passed to check_inputs!")...
Checks the data inputs to both train_step and predict and creates empty arrays if necessary
Checks the data inputs to both train_step and predict and creates empty arrays if necessary
[ "Checks", "the", "data", "inputs", "to", "both", "train_step", "and", "predict", "and", "creates", "empty", "arrays", "if", "necessary" ]
def check_inputs(x_unlabeled, x_labeled, y_labeled, y_true): if x_unlabeled is None: if x_labeled is None: raise Exception("No data, labeled or unlabeled, passed to check_inputs!") x_unlabeled = x_labeled[0:0] if x_labeled is not None and y_labeled is not None: pass elif ...
[ "def", "check_inputs", "(", "x_unlabeled", ",", "x_labeled", ",", "y_labeled", ",", "y_true", ")", ":", "if", "x_unlabeled", "is", "None", ":", "if", "x_labeled", "is", "None", ":", "raise", "Exception", "(", "\"No data, labeled or unlabeled, passed to check_inputs!...
Checks the data inputs to both train_step and predict and creates empty arrays if necessary
[ "Checks", "the", "data", "inputs", "to", "both", "train_step", "and", "predict", "and", "creates", "empty", "arrays", "if", "necessary" ]
[ "'''\n Checks the data inputs to both train_step and predict and creates\n empty arrays if necessary\n '''" ]
[ { "param": "x_unlabeled", "type": null }, { "param": "x_labeled", "type": null }, { "param": "y_labeled", "type": null }, { "param": "y_true", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "x_unlabeled", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "x_labeled", "type": null, "docstring": null, "docstrin...
c9ee285b98a5459fcd66f92ec8690e31e5b35b83
harukou/SpectralNet
src/core/train.py
[ "MIT" ]
Python
train_step
<not_specific>
def train_step(return_var, updates, x_unlabeled, inputs, y_true, batch_sizes, x_labeled=None, y_labeled=None, batches_per_epoch=100): ''' Performs one training step. Evaluates the tensors in return_var and updates, then returns the values of the tensors in return_var. return_var: ...
Performs one training step. Evaluates the tensors in return_var and updates, then returns the values of the tensors in return_var. return_var: list of tensors to evaluate and return updates: list of tensors to evaluate only x_unlabeled: unlabeled input data inputs: ...
Performs one training step. Evaluates the tensors in return_var and updates, then returns the values of the tensors in return_var. the evaluated result of all tensors in return_var, summed across all epochs the term epoch is used loosely here, it does not necessarily refer to one iteration over the entire dataset. ...
[ "Performs", "one", "training", "step", ".", "Evaluates", "the", "tensors", "in", "return_var", "and", "updates", "then", "returns", "the", "values", "of", "the", "tensors", "in", "return_var", ".", "the", "evaluated", "result", "of", "all", "tensors", "in", ...
def train_step(return_var, updates, x_unlabeled, inputs, y_true, batch_sizes, x_labeled=None, y_labeled=None, batches_per_epoch=100): x_unlabeled, x_labeled, y_labeled = check_inputs(x_unlabeled, x_labeled, y_labeled, y_true) x = np.concatenate((x_unlabeled, x_labeled), 0) y_shape = y_true.g...
[ "def", "train_step", "(", "return_var", ",", "updates", ",", "x_unlabeled", ",", "inputs", ",", "y_true", ",", "batch_sizes", ",", "x_labeled", "=", "None", ",", "y_labeled", "=", "None", ",", "batches_per_epoch", "=", "100", ")", ":", "x_unlabeled", ",", ...
Performs one training step.
[ "Performs", "one", "training", "step", "." ]
[ "'''\n Performs one training step. Evaluates the tensors in return_var and\n updates, then returns the values of the tensors in return_var.\n\n return_var: list of tensors to evaluate and return\n updates: list of tensors to evaluate only\n x_unlabeled: unlabeled input data\...
[ { "param": "return_var", "type": null }, { "param": "updates", "type": null }, { "param": "x_unlabeled", "type": null }, { "param": "inputs", "type": null }, { "param": "y_true", "type": null }, { "param": "batch_sizes", "type": null }, { "...
{ "returns": [], "raises": [], "params": [ { "identifier": "return_var", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "updates", "type": null, "docstring": null, "docstring_t...
c9ee285b98a5459fcd66f92ec8690e31e5b35b83
harukou/SpectralNet
src/core/train.py
[ "MIT" ]
Python
predict_sum
<not_specific>
def predict_sum(predict_var, x_unlabeled, inputs, y_true, batch_sizes, x_labeled=None, y_labeled=None): ''' Convenience function: sums over all the points to return a single value per tensor in predict_var ''' y = predict(predict_var, x_unlabeled, inputs, y_true, batch_sizes, x_labeled=x...
Convenience function: sums over all the points to return a single value per tensor in predict_var
Convenience function: sums over all the points to return a single value per tensor in predict_var
[ "Convenience", "function", ":", "sums", "over", "all", "the", "points", "to", "return", "a", "single", "value", "per", "tensor", "in", "predict_var" ]
def predict_sum(predict_var, x_unlabeled, inputs, y_true, batch_sizes, x_labeled=None, y_labeled=None): y = predict(predict_var, x_unlabeled, inputs, y_true, batch_sizes, x_labeled=x_labeled, y_labeled=y_labeled) return np.sum(y)
[ "def", "predict_sum", "(", "predict_var", ",", "x_unlabeled", ",", "inputs", ",", "y_true", ",", "batch_sizes", ",", "x_labeled", "=", "None", ",", "y_labeled", "=", "None", ")", ":", "y", "=", "predict", "(", "predict_var", ",", "x_unlabeled", ",", "input...
Convenience function: sums over all the points to return a single value per tensor in predict_var
[ "Convenience", "function", ":", "sums", "over", "all", "the", "points", "to", "return", "a", "single", "value", "per", "tensor", "in", "predict_var" ]
[ "'''\n Convenience function: sums over all the points to return a single value\n per tensor in predict_var\n '''" ]
[ { "param": "predict_var", "type": null }, { "param": "x_unlabeled", "type": null }, { "param": "inputs", "type": null }, { "param": "y_true", "type": null }, { "param": "batch_sizes", "type": null }, { "param": "x_labeled", "type": null }, { ...
{ "returns": [], "raises": [], "params": [ { "identifier": "predict_var", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "x_unlabeled", "type": null, "docstring": null, "docstr...
8e734c6ac47efe8c2ac82193d5c2ae0f606e91b7
harukou/SpectralNet
src/new_dset/concentric2.py
[ "MIT" ]
Python
generate_circle2
<not_specific>
def generate_circle2(n=1200, noise_sigma=0.1, train_set_fraction=0.5): ''' Generates and returns 2 concentric example dataset ''' pts_per_cluster = int(n / 2) r = 1 # generate clusters theta1 = (np.random.uniform(0, 1, pts_per_cluster) * 2 * np.pi).reshape(pts_per_cluster, 1) theta2 = ...
Generates and returns 2 concentric example dataset
Generates and returns 2 concentric example dataset
[ "Generates", "and", "returns", "2", "concentric", "example", "dataset" ]
def generate_circle2(n=1200, noise_sigma=0.1, train_set_fraction=0.5): pts_per_cluster = int(n / 2) r = 1 theta1 = (np.random.uniform(0, 1, pts_per_cluster) * 2 * np.pi).reshape(pts_per_cluster, 1) theta2 = (np.random.uniform(0, 1, pts_per_cluster) * 2 * np.pi).reshape(pts_per_cluster, 1) cluster1 =...
[ "def", "generate_circle2", "(", "n", "=", "1200", ",", "noise_sigma", "=", "0.1", ",", "train_set_fraction", "=", "0.5", ")", ":", "pts_per_cluster", "=", "int", "(", "n", "/", "2", ")", "r", "=", "1", "theta1", "=", "(", "np", ".", "random", ".", ...
Generates and returns 2 concentric example dataset
[ "Generates", "and", "returns", "2", "concentric", "example", "dataset" ]
[ "'''\n Generates and returns 2 concentric example dataset \n '''", "# generate clusters", "# shift and reverse cluster 2, radius = 2", "# combine clusters", "# add noise to x", "# generate labels", "# shuffle", "# make train and test splits" ]
[ { "param": "n", "type": null }, { "param": "noise_sigma", "type": null }, { "param": "train_set_fraction", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "n", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "noise_sigma", "type": null, "docstring": null, "docstring_tokens...
016b29bff36c8970237cca26e9a95439478b2aa6
08haganh/crystal_interactions_finder_hh
PYTHON/utils.py
[ "MIT" ]
Python
calc_intermolecular_atom_distances
<not_specific>
def calc_intermolecular_atom_distances(crystal): ''' Calculates all interatomic atom atom distances in a crystal structure calculates distances on batch between central molecules and a neighbour molecule, rather than a simple nested for loop calculates distances in batches between atom i in central ...
Calculates all interatomic atom atom distances in a crystal structure calculates distances on batch between central molecules and a neighbour molecule, rather than a simple nested for loop calculates distances in batches between atom i in central molecule and atom (i - x) in neighbour returns a dat...
Calculates all interatomic atom atom distances in a crystal structure calculates distances on batch between central molecules and a neighbour molecule, rather than a simple nested for loop calculates distances in batches between atom i in central molecule and atom (i - x) in neighbour returns a dataframe with all atom ...
[ "Calculates", "all", "interatomic", "atom", "atom", "distances", "in", "a", "crystal", "structure", "calculates", "distances", "on", "batch", "between", "central", "molecules", "and", "a", "neighbour", "molecule", "rather", "than", "a", "simple", "nested", "for", ...
def calc_intermolecular_atom_distances(crystal): central_molecule, central_idx = crystal.get_central_molecule(return_idx=True) central_atom_coords = np.array([atom.coordinates for atom in central_molecule.atoms]) all_atom_coords = [] for mol in crystal.molecules: all_atom_coords.append(np.array...
[ "def", "calc_intermolecular_atom_distances", "(", "crystal", ")", ":", "central_molecule", ",", "central_idx", "=", "crystal", ".", "get_central_molecule", "(", "return_idx", "=", "True", ")", "central_atom_coords", "=", "np", ".", "array", "(", "[", "atom", ".", ...
Calculates all interatomic atom atom distances in a crystal structure calculates distances on batch between central molecules and a neighbour molecule, rather than a simple nested for loop calculates distances in batches between atom i in central molecule and atom (i - x) in neighbour returns a dataframe with all atom ...
[ "Calculates", "all", "interatomic", "atom", "atom", "distances", "in", "a", "crystal", "structure", "calculates", "distances", "on", "batch", "between", "central", "molecules", "and", "a", "neighbour", "molecule", "rather", "than", "a", "simple", "nested", "for", ...
[ "'''\n Calculates all interatomic atom atom distances in a crystal structure\n calculates distances on batch between central molecules and a neighbour molecule, rather than a simple\n nested for loop\n calculates distances in batches between atom i in central molecule and atom (i - x) in neighbour\n ...
[ { "param": "crystal", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "crystal", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
016b29bff36c8970237cca26e9a95439478b2aa6
08haganh/crystal_interactions_finder_hh
PYTHON/utils.py
[ "MIT" ]
Python
add_interactions
<not_specific>
def add_interactions(atom_dist_df,crystal): ''' Add intermolecular interaction types to bond distances ''' atom_dicts = [] for idx in atom_dist_df.index: m1_idx = atom_dist_df.at[idx,'mol1s'] m2_idx = atom_dist_df.at[idx,'mol2s'] a1_idx = atom_dist_df.at[idx,'atom1s'] ...
Add intermolecular interaction types to bond distances
Add intermolecular interaction types to bond distances
[ "Add", "intermolecular", "interaction", "types", "to", "bond", "distances" ]
def add_interactions(atom_dist_df,crystal): atom_dicts = [] for idx in atom_dist_df.index: m1_idx = atom_dist_df.at[idx,'mol1s'] m2_idx = atom_dist_df.at[idx,'mol2s'] a1_idx = atom_dist_df.at[idx,'atom1s'] a2_idx = atom_dist_df.at[idx,'atom2s'] atom1 = crystal.molecules[m...
[ "def", "add_interactions", "(", "atom_dist_df", ",", "crystal", ")", ":", "atom_dicts", "=", "[", "]", "for", "idx", "in", "atom_dist_df", ".", "index", ":", "m1_idx", "=", "atom_dist_df", ".", "at", "[", "idx", ",", "'mol1s'", "]", "m2_idx", "=", "atom_...
Add intermolecular interaction types to bond distances
[ "Add", "intermolecular", "interaction", "types", "to", "bond", "distances" ]
[ "'''\n Add intermolecular interaction types to bond distances\n '''" ]
[ { "param": "atom_dist_df", "type": null }, { "param": "crystal", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "atom_dist_df", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "crystal", "type": null, "docstring": null, "docstring...
1d1cefb48944ca484b26931b6e0b09b08275bdba
08haganh/crystal_interactions_finder_hh
PYTHON/Geometry.py
[ "MIT" ]
Python
mvee
<not_specific>
def mvee(atoms, tol = 0.00001): """ Find the minimum volume ellipse around a set of atom objects. Return A, c where the equation for the ellipse given in "center form" is (x-c).T * A * (x-c) = 1 [U Q V] = svd(A); where r = 1/sqrt(Q) V is rotation matrix U is ??? """ points_asar...
Find the minimum volume ellipse around a set of atom objects. Return A, c where the equation for the ellipse given in "center form" is (x-c).T * A * (x-c) = 1 [U Q V] = svd(A); where r = 1/sqrt(Q) V is rotation matrix U is ???
Find the minimum volume ellipse around a set of atom objects.
[ "Find", "the", "minimum", "volume", "ellipse", "around", "a", "set", "of", "atom", "objects", "." ]
def mvee(atoms, tol = 0.00001): points_asarray = np.array([atom.coordinates for atom in atoms]) points = np.asmatrix(points_asarray) N, d = points.shape Q = np.column_stack((points, np.ones(N))).T err = tol+1.0 u = np.ones(N)/N try: while err > tol: X = Q * np.diag(u) * Q...
[ "def", "mvee", "(", "atoms", ",", "tol", "=", "0.00001", ")", ":", "points_asarray", "=", "np", ".", "array", "(", "[", "atom", ".", "coordinates", "for", "atom", "in", "atoms", "]", ")", "points", "=", "np", ".", "asmatrix", "(", "points_asarray", "...
Find the minimum volume ellipse around a set of atom objects.
[ "Find", "the", "minimum", "volume", "ellipse", "around", "a", "set", "of", "atom", "objects", "." ]
[ "\"\"\"\n Find the minimum volume ellipse around a set of atom objects.\n Return A, c where the equation for the ellipse given in \"center form\" is\n (x-c).T * A * (x-c) = 1\n [U Q V] = svd(A); \n where r = 1/sqrt(Q)\n V is rotation matrix\n U is ??? \n \"\"\"", "# assert u.sum() == 1 # i...
[ { "param": "atoms", "type": null }, { "param": "tol", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "atoms", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "tol", "type": null, "docstring": null, "docstring_tokens": [...
fcf01f11d891e6953213569c87dab5383a216142
agormp/treetool
treetool.py
[ "MIT" ]
Python
read_treefile
<not_specific>
def read_treefile(options, filename): """Takes filename as input, returns Tree object""" if options.informat.lower() == "nexus": treefile = phylotreelib.Nexustreefile(filename) else: treefile = phylotreelib.Newicktreefile(filename) tree = next(treefile) return tree
Takes filename as input, returns Tree object
Takes filename as input, returns Tree object
[ "Takes", "filename", "as", "input", "returns", "Tree", "object" ]
def read_treefile(options, filename): if options.informat.lower() == "nexus": treefile = phylotreelib.Nexustreefile(filename) else: treefile = phylotreelib.Newicktreefile(filename) tree = next(treefile) return tree
[ "def", "read_treefile", "(", "options", ",", "filename", ")", ":", "if", "options", ".", "informat", ".", "lower", "(", ")", "==", "\"nexus\"", ":", "treefile", "=", "phylotreelib", ".", "Nexustreefile", "(", "filename", ")", "else", ":", "treefile", "=", ...
Takes filename as input, returns Tree object
[ "Takes", "filename", "as", "input", "returns", "Tree", "object" ]
[ "\"\"\"Takes filename as input, returns Tree object\"\"\"" ]
[ { "param": "options", "type": null }, { "param": "filename", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "options", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "filename", "type": null, "docstring": null, "docstring_tok...
fcf01f11d891e6953213569c87dab5383a216142
agormp/treetool
treetool.py
[ "MIT" ]
Python
read_names
<not_specific>
def read_names(filename): """File with name "filename" assumed to contain one leafname per line. Read and return set of names""" names = set() with open(filename, "r") as infile: for line in infile: leaf = line.strip() if leaf: names.add(leaf) return name...
File with name "filename" assumed to contain one leafname per line. Read and return set of names
File with name "filename" assumed to contain one leafname per line. Read and return set of names
[ "File", "with", "name", "\"", "filename", "\"", "assumed", "to", "contain", "one", "leafname", "per", "line", ".", "Read", "and", "return", "set", "of", "names" ]
def read_names(filename): names = set() with open(filename, "r") as infile: for line in infile: leaf = line.strip() if leaf: names.add(leaf) return names
[ "def", "read_names", "(", "filename", ")", ":", "names", "=", "set", "(", ")", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "infile", ":", "for", "line", "in", "infile", ":", "leaf", "=", "line", ".", "strip", "(", ")", "if", "leaf", ...
File with name "filename" assumed to contain one leafname per line.
[ "File", "with", "name", "\"", "filename", "\"", "assumed", "to", "contain", "one", "leafname", "per", "line", "." ]
[ "\"\"\"File with name \"filename\" assumed to contain one leafname per line. Read and return set of names\"\"\"" ]
[ { "param": "filename", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "filename", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fcf01f11d891e6953213569c87dab5383a216142
agormp/treetool
treetool.py
[ "MIT" ]
Python
print_tree
null
def print_tree(options, tree): """Accepts either Tree or Tree_set as input. Prints all trees on stdout""" # Print tree on standard out if options.outformat.lower() == "nexus": print(tree.nexus()) else: print(tree.newick())
Accepts either Tree or Tree_set as input. Prints all trees on stdout
Accepts either Tree or Tree_set as input. Prints all trees on stdout
[ "Accepts", "either", "Tree", "or", "Tree_set", "as", "input", ".", "Prints", "all", "trees", "on", "stdout" ]
def print_tree(options, tree): if options.outformat.lower() == "nexus": print(tree.nexus()) else: print(tree.newick())
[ "def", "print_tree", "(", "options", ",", "tree", ")", ":", "if", "options", ".", "outformat", ".", "lower", "(", ")", "==", "\"nexus\"", ":", "print", "(", "tree", ".", "nexus", "(", ")", ")", "else", ":", "print", "(", "tree", ".", "newick", "(",...
Accepts either Tree or Tree_set as input.
[ "Accepts", "either", "Tree", "or", "Tree_set", "as", "input", "." ]
[ "\"\"\"Accepts either Tree or Tree_set as input. Prints all trees on stdout\"\"\"", "# Print tree on standard out" ]
[ { "param": "options", "type": null }, { "param": "tree", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "options", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "tree", "type": null, "docstring": null, "docstring_tokens"...
8ea64db6acf7c355638fd72aed854e540ff20f64
AravindRam/Artificial-Intelligence
CNF Converter/DPLL.py
[ "Apache-2.0" ]
Python
is_negative_symbol
<not_specific>
def is_negative_symbol(s): """ Function to find if s is a negative symbol by checking if its a list, length of the list s is equal to 2, first element in the list is not and the length of second element in the list is equal to 1""" return isinstance(s, list) and len(s) == 2 and s[0] == NOT and len(s[1]) == 1
Function to find if s is a negative symbol by checking if its a list, length of the list s is equal to 2, first element in the list is not and the length of second element in the list is equal to 1
Function to find if s is a negative symbol by checking if its a list, length of the list s is equal to 2, first element in the list is not and the length of second element in the list is equal to 1
[ "Function", "to", "find", "if", "s", "is", "a", "negative", "symbol", "by", "checking", "if", "its", "a", "list", "length", "of", "the", "list", "s", "is", "equal", "to", "2", "first", "element", "in", "the", "list", "is", "not", "and", "the", "lengt...
def is_negative_symbol(s): return isinstance(s, list) and len(s) == 2 and s[0] == NOT and len(s[1]) == 1
[ "def", "is_negative_symbol", "(", "s", ")", ":", "return", "isinstance", "(", "s", ",", "list", ")", "and", "len", "(", "s", ")", "==", "2", "and", "s", "[", "0", "]", "==", "NOT", "and", "len", "(", "s", "[", "1", "]", ")", "==", "1" ]
Function to find if s is a negative symbol by checking if its a list, length of the list s is equal to 2, first element in the list is not and the length of second element in the list is equal to 1
[ "Function", "to", "find", "if", "s", "is", "a", "negative", "symbol", "by", "checking", "if", "its", "a", "list", "length", "of", "the", "list", "s", "is", "equal", "to", "2", "first", "element", "in", "the", "list", "is", "not", "and", "the", "lengt...
[ "\"\"\" Function to find if s is a negative symbol by checking if its a list,\r\n\t\tlength of the list s is equal to 2, first element in the list is not and \r\n\t\tthe length of second element in the list is equal to 1\"\"\"" ]
[ { "param": "s", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "s", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8ea64db6acf7c355638fd72aed854e540ff20f64
AravindRam/Artificial-Intelligence
CNF Converter/DPLL.py
[ "Apache-2.0" ]
Python
make_clauses
<not_specific>
def make_clauses(sentence): """ Function to form clauses from the given input and return a list of all clauses""" clauses=[] for i in range(1,len(sentence)): if(sentence[0] == NOT): # for negative clauses or symbols clauses.append([NOT,sentence[i]]) else: # for positive clauses or symbols clause...
Function to form clauses from the given input and return a list of all clauses
Function to form clauses from the given input and return a list of all clauses
[ "Function", "to", "form", "clauses", "from", "the", "given", "input", "and", "return", "a", "list", "of", "all", "clauses" ]
def make_clauses(sentence): clauses=[] for i in range(1,len(sentence)): if(sentence[0] == NOT): clauses.append([NOT,sentence[i]]) else: clauses.append(sentence[i]) return clauses
[ "def", "make_clauses", "(", "sentence", ")", ":", "clauses", "=", "[", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "sentence", ")", ")", ":", "if", "(", "sentence", "[", "0", "]", "==", "NOT", ")", ":", "clauses", ".", "append", ...
Function to form clauses from the given input and return a list of all clauses
[ "Function", "to", "form", "clauses", "from", "the", "given", "input", "and", "return", "a", "list", "of", "all", "clauses" ]
[ "\"\"\" Function to form clauses from the given input and return a list of all clauses\"\"\"", "# for negative clauses or symbols\r", "# for positive clauses or symbols\r" ]
[ { "param": "sentence", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sentence", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8ea64db6acf7c355638fd72aed854e540ff20f64
AravindRam/Artificial-Intelligence
CNF Converter/DPLL.py
[ "Apache-2.0" ]
Python
extract_symbols
<not_specific>
def extract_symbols(clauses): """Function to extract only the symbols from each clause in a given input and return a list of symbols for each input""" symbols=[] symbols_without_not=[] symbols_with_not=[] for i in range(len(clauses)): if is_positive_symbol(clauses[i]) and clauses[i] not in symbols: # ...
Function to extract only the symbols from each clause in a given input and return a list of symbols for each input
Function to extract only the symbols from each clause in a given input and return a list of symbols for each input
[ "Function", "to", "extract", "only", "the", "symbols", "from", "each", "clause", "in", "a", "given", "input", "and", "return", "a", "list", "of", "symbols", "for", "each", "input" ]
def extract_symbols(clauses): symbols=[] symbols_without_not=[] symbols_with_not=[] for i in range(len(clauses)): if is_positive_symbol(clauses[i]) and clauses[i] not in symbols: symbols.extend(clauses[i]) symbols_without_not.extend(clauses[i]) elif is_negative_symbol(clauses[i]) and clauses[i][1] not in...
[ "def", "extract_symbols", "(", "clauses", ")", ":", "symbols", "=", "[", "]", "symbols_without_not", "=", "[", "]", "symbols_with_not", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "clauses", ")", ")", ":", "if", "is_positive_symbol", "(", ...
Function to extract only the symbols from each clause in a given input and return a list of symbols for each input
[ "Function", "to", "extract", "only", "the", "symbols", "from", "each", "clause", "in", "a", "given", "input", "and", "return", "a", "list", "of", "symbols", "for", "each", "input" ]
[ "\"\"\"Function to extract only the symbols from each clause in a given input and\r\n\t return a list of symbols for each input\"\"\"", "# add symbol to list if symbol is positive and not already in list\r", "# add symbol to list if symbol is negative and not already in list\r", "# if clause is a list, iter...
[ { "param": "clauses", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "clauses", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8ea64db6acf7c355638fd72aed854e540ff20f64
AravindRam/Artificial-Intelligence
CNF Converter/DPLL.py
[ "Apache-2.0" ]
Python
find_pure_symbol
<not_specific>
def find_pure_symbol(symbols, clauses, model): """Function to find if a symbol is a pure symbol and its value if it is present only a positive symbol or only as a negative symbol in all the clauses in a given input.""" print symbols,clauses for i in range(len(symbols)): found_pos, found_neg = False, False...
Function to find if a symbol is a pure symbol and its value if it is present only a positive symbol or only as a negative symbol in all the clauses in a given input.
Function to find if a symbol is a pure symbol and its value if it is present only a positive symbol or only as a negative symbol in all the clauses in a given input.
[ "Function", "to", "find", "if", "a", "symbol", "is", "a", "pure", "symbol", "and", "its", "value", "if", "it", "is", "present", "only", "a", "positive", "symbol", "or", "only", "as", "a", "negative", "symbol", "in", "all", "the", "clauses", "in", "a", ...
def find_pure_symbol(symbols, clauses, model): print symbols,clauses for i in range(len(symbols)): found_pos, found_neg = False, False for j in range(len(clauses)): if not found_pos and symbols[i] in clauses[j]: found_pos = True if not found_neg and str([NOT , symbols[i]]) in clauses[j]: found_neg =...
[ "def", "find_pure_symbol", "(", "symbols", ",", "clauses", ",", "model", ")", ":", "print", "symbols", ",", "clauses", "for", "i", "in", "range", "(", "len", "(", "symbols", ")", ")", ":", "found_pos", ",", "found_neg", "=", "False", ",", "False", "for...
Function to find if a symbol is a pure symbol and its value if it is present only a positive symbol or only as a negative symbol in all the clauses in a given input.
[ "Function", "to", "find", "if", "a", "symbol", "is", "a", "pure", "symbol", "and", "its", "value", "if", "it", "is", "present", "only", "a", "positive", "symbol", "or", "only", "as", "a", "negative", "symbol", "in", "all", "the", "clauses", "in", "a", ...
[ "\"\"\"Function to find if a symbol is a pure symbol and its value if it is present only a positive symbol\r\n or only as a negative symbol in all the clauses in a given input.\"\"\"" ]
[ { "param": "symbols", "type": null }, { "param": "clauses", "type": null }, { "param": "model", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "symbols", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "clauses", "type": null, "docstring": null, "docstring_toke...
8ea64db6acf7c355638fd72aed854e540ff20f64
AravindRam/Artificial-Intelligence
CNF Converter/DPLL.py
[ "Apache-2.0" ]
Python
find_unit_clause
<not_specific>
def find_unit_clause(clauses, model): """ Function to find a unit clause and its value if it is present only as a symbol and not in a list""" print clauses for i in range(len(clauses)): count = 0 literals,literal_list = extract_symbols(clauses[i]) for j in range(len(literal_list[0])): if literal_list...
Function to find a unit clause and its value if it is present only as a symbol and not in a list
Function to find a unit clause and its value if it is present only as a symbol and not in a list
[ "Function", "to", "find", "a", "unit", "clause", "and", "its", "value", "if", "it", "is", "present", "only", "as", "a", "symbol", "and", "not", "in", "a", "list" ]
def find_unit_clause(clauses, model): print clauses for i in range(len(clauses)): count = 0 literals,literal_list = extract_symbols(clauses[i]) for j in range(len(literal_list[0])): if literal_list[0][j] not in model: count += 1 P, value = literal_list[0][j], "'true'" for j in range(len(literal_lis...
[ "def", "find_unit_clause", "(", "clauses", ",", "model", ")", ":", "print", "clauses", "for", "i", "in", "range", "(", "len", "(", "clauses", ")", ")", ":", "count", "=", "0", "literals", ",", "literal_list", "=", "extract_symbols", "(", "clauses", "[", ...
Function to find a unit clause and its value if it is present only as a symbol and not in a list
[ "Function", "to", "find", "a", "unit", "clause", "and", "its", "value", "if", "it", "is", "present", "only", "as", "a", "symbol", "and", "not", "in", "a", "list" ]
[ "\"\"\" Function to find a unit clause and its value if it is present only as a symbol and not in a list\"\"\"" ]
[ { "param": "clauses", "type": null }, { "param": "model", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "clauses", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "model", "type": null, "docstring": null, "docstring_tokens...
8ea64db6acf7c355638fd72aed854e540ff20f64
AravindRam/Artificial-Intelligence
CNF Converter/DPLL.py
[ "Apache-2.0" ]
Python
pl_true
<not_specific>
def pl_true(clause, model={}): """ Function to find if every clause in a given input is True or False """ if clause == "TRUE": return True elif clause == "FALSE": return False elif clause[0] == NOT: value = pl_true(clause[1], model) if value is None: return None else: return not value e...
Function to find if every clause in a given input is True or False
Function to find if every clause in a given input is True or False
[ "Function", "to", "find", "if", "every", "clause", "in", "a", "given", "input", "is", "True", "or", "False" ]
def pl_true(clause, model={}): if clause == "TRUE": return True elif clause == "FALSE": return False elif clause[0] == NOT: value = pl_true(clause[1], model) if value is None: return None else: return not value elif clause[0] == OR: result = False for i in range(1,len(clause)): value = pl_tru...
[ "def", "pl_true", "(", "clause", ",", "model", "=", "{", "}", ")", ":", "if", "clause", "==", "\"TRUE\"", ":", "return", "True", "elif", "clause", "==", "\"FALSE\"", ":", "return", "False", "elif", "clause", "[", "0", "]", "==", "NOT", ":", "value", ...
Function to find if every clause in a given input is True or False
[ "Function", "to", "find", "if", "every", "clause", "in", "a", "given", "input", "is", "True", "or", "False" ]
[ "\"\"\" Function to find if every clause in a given input is True or False \"\"\"" ]
[ { "param": "clause", "type": null }, { "param": "model", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "clause", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "model", "type": null, "docstring": null, "docstring_tokens"...
395c8ee44dbfe1db5c9ed1a9ac0aede878aa6879
AravindRam/Artificial-Intelligence
CNF Converter/CNFConverter.py
[ "Apache-2.0" ]
Python
recursive_call
<not_specific>
def recursive_call(input,flag): """ Helper function to simplify recursion calls which adds the outputing clauses or symbols to the output list """ output = [] ; output.append(input[0]); for i in range(1,len(input)): if flag == 1: output.append(eliminate_biconditional(input[i])) elif flag == 2: out...
Helper function to simplify recursion calls which adds the outputing clauses or symbols to the output list
Helper function to simplify recursion calls which adds the outputing clauses or symbols to the output list
[ "Helper", "function", "to", "simplify", "recursion", "calls", "which", "adds", "the", "outputing", "clauses", "or", "symbols", "to", "the", "output", "list" ]
def recursive_call(input,flag): output = [] ; output.append(input[0]); for i in range(1,len(input)): if flag == 1: output.append(eliminate_biconditional(input[i])) elif flag == 2: output.append(eliminate_implication(input[i])) elif flag == 3: output.append(inner_demorgan(input[i])) elif flag == 4: ...
[ "def", "recursive_call", "(", "input", ",", "flag", ")", ":", "output", "=", "[", "]", ";", "output", ".", "append", "(", "input", "[", "0", "]", ")", ";", "for", "i", "in", "range", "(", "1", ",", "len", "(", "input", ")", ")", ":", "if", "f...
Helper function to simplify recursion calls which adds the outputing clauses or symbols to the output list
[ "Helper", "function", "to", "simplify", "recursion", "calls", "which", "adds", "the", "outputing", "clauses", "or", "symbols", "to", "the", "output", "list" ]
[ "\"\"\" Helper function to simplify recursion calls which adds the outputing clauses or symbols to the output list \"\"\"" ]
[ { "param": "input", "type": null }, { "param": "flag", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "flag", "type": null, "docstring": null, "docstring_tokens": ...
395c8ee44dbfe1db5c9ed1a9ac0aede878aa6879
AravindRam/Artificial-Intelligence
CNF Converter/CNFConverter.py
[ "Apache-2.0" ]
Python
eliminate_biconditional
<not_specific>
def eliminate_biconditional(input): """ Function to eliminate biconditionals and to replace them with their implication equivalents """ if is_symbol(input): # check if its a symbol then return as it is return input if input[0] in [AND, OR, NOT, IMPLIES]: # append the clauses to the output if the connective is...
Function to eliminate biconditionals and to replace them with their implication equivalents
Function to eliminate biconditionals and to replace them with their implication equivalents
[ "Function", "to", "eliminate", "biconditionals", "and", "to", "replace", "them", "with", "their", "implication", "equivalents" ]
def eliminate_biconditional(input): if is_symbol(input): return input if input[0] in [AND, OR, NOT, IMPLIES]: return recursive_call(input,1) if input[0]==IFF: input[0] = AND input[1] = [IMPLIES, eliminate_biconditional(input[1]), eliminate_biconditional(input[2])] input[2] = [IMPLIES, eliminate_bicond...
[ "def", "eliminate_biconditional", "(", "input", ")", ":", "if", "is_symbol", "(", "input", ")", ":", "return", "input", "if", "input", "[", "0", "]", "in", "[", "AND", ",", "OR", ",", "NOT", ",", "IMPLIES", "]", ":", "return", "recursive_call", "(", ...
Function to eliminate biconditionals and to replace them with their implication equivalents
[ "Function", "to", "eliminate", "biconditionals", "and", "to", "replace", "them", "with", "their", "implication", "equivalents" ]
[ "\"\"\" Function to eliminate biconditionals and to replace them with their implication equivalents \"\"\"", "# check if its a symbol then return as it is\r", "# append the clauses to the output if the connective is not a biconditional\r", "# input - [\"iff\",\"A\",\"B\"] then convert it to [\"and\", [\"impli...
[ { "param": "input", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
395c8ee44dbfe1db5c9ed1a9ac0aede878aa6879
AravindRam/Artificial-Intelligence
CNF Converter/CNFConverter.py
[ "Apache-2.0" ]
Python
eliminate_implication
<not_specific>
def eliminate_implication(input): """ Function to eliminate implications and to replace them with their not and or equivalents """ if is_symbol(input): # check if its a symbol then return as it is return input if input[0] in [AND, OR, NOT, IFF]: # append the clauses to the output if the connective is not an i...
Function to eliminate implications and to replace them with their not and or equivalents
Function to eliminate implications and to replace them with their not and or equivalents
[ "Function", "to", "eliminate", "implications", "and", "to", "replace", "them", "with", "their", "not", "and", "or", "equivalents" ]
def eliminate_implication(input): if is_symbol(input): return input if input[0] in [AND, OR, NOT, IFF]: return recursive_call(input,2) if input[0] == IMPLIES: input[0] = OR input[1] = eliminate_implication([NOT,input[1]]) input[2] = eliminate_implication(input[2]) return input
[ "def", "eliminate_implication", "(", "input", ")", ":", "if", "is_symbol", "(", "input", ")", ":", "return", "input", "if", "input", "[", "0", "]", "in", "[", "AND", ",", "OR", ",", "NOT", ",", "IFF", "]", ":", "return", "recursive_call", "(", "input...
Function to eliminate implications and to replace them with their not and or equivalents
[ "Function", "to", "eliminate", "implications", "and", "to", "replace", "them", "with", "their", "not", "and", "or", "equivalents" ]
[ "\"\"\" Function to eliminate implications and to replace them with their not and or equivalents \"\"\"", "# check if its a symbol then return as it is\r", "# append the clauses to the output if the connective is not an implication\r", "# input - [\"implies\",\"A\",\"B\"] then convert it to [\"or\", [\"not\",...
[ { "param": "input", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
395c8ee44dbfe1db5c9ed1a9ac0aede878aa6879
AravindRam/Artificial-Intelligence
CNF Converter/CNFConverter.py
[ "Apache-2.0" ]
Python
inner_demorgan
<not_specific>
def inner_demorgan(input): """ Function to move not inwards in the inner clauses """ for i in range(len(input)): if is_symbol(input): # check if its a symbol then return as it is return input elif input[i][0] in [AND,OR]: # append the clauses to the output if the connective is AND or OR return rec...
Function to move not inwards in the inner clauses
Function to move not inwards in the inner clauses
[ "Function", "to", "move", "not", "inwards", "in", "the", "inner", "clauses" ]
def inner_demorgan(input): for i in range(len(input)): if is_symbol(input): return input elif input[i][0] in [AND,OR]: return recursive_call(input,3) elif input[i][0] == NOT and input[i][1][0] in [AND,OR]: output = [] if(input[i][1][0] == AND): output.append(OR) elif(input[i...
[ "def", "inner_demorgan", "(", "input", ")", ":", "for", "i", "in", "range", "(", "len", "(", "input", ")", ")", ":", "if", "is_symbol", "(", "input", ")", ":", "return", "input", "elif", "input", "[", "i", "]", "[", "0", "]", "in", "[", "AND", ...
Function to move not inwards in the inner clauses
[ "Function", "to", "move", "not", "inwards", "in", "the", "inner", "clauses" ]
[ "\"\"\" Function to move not inwards in the inner clauses \"\"\"", "# check if its a symbol then return as it is\r", "# append the clauses to the output if the connective is AND or OR\r", "# input - [\"and\" ,[\"not\",[\"or\",\"A\",\"B\"]],\"A\" ] then convert it to [\"and\", [\"and\",[\"not\",\"A\"],[\"not\"...
[ { "param": "input", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
395c8ee44dbfe1db5c9ed1a9ac0aede878aa6879
AravindRam/Artificial-Intelligence
CNF Converter/CNFConverter.py
[ "Apache-2.0" ]
Python
outer_demorgan
<not_specific>
def outer_demorgan(input): """ Function to move not inwards in the outermost clause """ if is_symbol(input): # check if its a symbol then return as it is return input elif input[0] in [AND,OR]: # append the clauses to the output if the connective is AND or OR return recursive_call(input,4) elif input[0] ...
Function to move not inwards in the outermost clause
Function to move not inwards in the outermost clause
[ "Function", "to", "move", "not", "inwards", "in", "the", "outermost", "clause" ]
def outer_demorgan(input): if is_symbol(input): return input elif input[0] in [AND,OR]: return recursive_call(input,4) elif input[0] == NOT and input[1][0] in [AND,OR]: output = [] if(input[1][0] == AND): output.append(OR) elif(input[1][0] == OR): output.append(AND) for i in range(1,l...
[ "def", "outer_demorgan", "(", "input", ")", ":", "if", "is_symbol", "(", "input", ")", ":", "return", "input", "elif", "input", "[", "0", "]", "in", "[", "AND", ",", "OR", "]", ":", "return", "recursive_call", "(", "input", ",", "4", ")", "elif", "...
Function to move not inwards in the outermost clause
[ "Function", "to", "move", "not", "inwards", "in", "the", "outermost", "clause" ]
[ "\"\"\" Function to move not inwards in the outermost clause \"\"\"", "# check if its a symbol then return as it is\r", "# append the clauses to the output if the connective is AND or OR\r", "# input - [\"not\",[\"or\",\"A\",\"B\"]] then convert it to [\"and\", [\"not\",\"A\"],[\"not\",\"B\"]] \r" ]
[ { "param": "input", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
395c8ee44dbfe1db5c9ed1a9ac0aede878aa6879
AravindRam/Artificial-Intelligence
CNF Converter/CNFConverter.py
[ "Apache-2.0" ]
Python
distributivity
<not_specific>
def distributivity(clause1,clause2): """ Function to distribute OR over AND """ if isinstance(clause1, list) and clause1[0] == AND: output = [AND, distributivity(clause1[1],clause2), distributivity(clause1[2],clause2)] elif isinstance(clause2, list) and clause2[0] == AND: output = [AND, distributivity(cla...
Function to distribute OR over AND
Function to distribute OR over AND
[ "Function", "to", "distribute", "OR", "over", "AND" ]
def distributivity(clause1,clause2): if isinstance(clause1, list) and clause1[0] == AND: output = [AND, distributivity(clause1[1],clause2), distributivity(clause1[2],clause2)] elif isinstance(clause2, list) and clause2[0] == AND: output = [AND, distributivity(clause1,clause2[1]), distributivity(clause1,clause2[...
[ "def", "distributivity", "(", "clause1", ",", "clause2", ")", ":", "if", "isinstance", "(", "clause1", ",", "list", ")", "and", "clause1", "[", "0", "]", "==", "AND", ":", "output", "=", "[", "AND", ",", "distributivity", "(", "clause1", "[", "1", "]...
Function to distribute OR over AND
[ "Function", "to", "distribute", "OR", "over", "AND" ]
[ "\"\"\" Function to distribute OR over AND \"\"\"" ]
[ { "param": "clause1", "type": null }, { "param": "clause2", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "clause1", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "clause2", "type": null, "docstring": null, "docstring_toke...
395c8ee44dbfe1db5c9ed1a9ac0aede878aa6879
AravindRam/Artificial-Intelligence
CNF Converter/CNFConverter.py
[ "Apache-2.0" ]
Python
associativity
<not_specific>
def associativity(input): """ Function to associate OR and OR, AND and AND """ if is_symbol(input): # check if its a symbol then return as it is return input elif input[0] in [AND,OR]: temp1=[] temp2=[] for index in range(1,len(input)): if input[0] == input[index][0]: temp1.extend(input[ind...
Function to associate OR and OR, AND and AND
Function to associate OR and OR, AND and AND
[ "Function", "to", "associate", "OR", "and", "OR", "AND", "and", "AND" ]
def associativity(input): if is_symbol(input): return input elif input[0] in [AND,OR]: temp1=[] temp2=[] for index in range(1,len(input)): if input[0] == input[index][0]: temp1.extend(input[index][1:]) temp2.append(input[index]) for element in temp2: input.remove(element) input.extend(tem...
[ "def", "associativity", "(", "input", ")", ":", "if", "is_symbol", "(", "input", ")", ":", "return", "input", "elif", "input", "[", "0", "]", "in", "[", "AND", ",", "OR", "]", ":", "temp1", "=", "[", "]", "temp2", "=", "[", "]", "for", "index", ...
Function to associate OR and OR, AND and AND
[ "Function", "to", "associate", "OR", "and", "OR", "AND", "and", "AND" ]
[ "\"\"\" Function to associate OR and OR, AND and AND \"\"\"", "# check if its a symbol then return as it is\r" ]
[ { "param": "input", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a862dbb10ac6d731c4ed75c60c82dc7565d56338
LincLabUCCS/Jack_RNN_Chatbot
chatbot.py
[ "MIT" ]
Python
NET_Probability
<not_specific>
def NET_Probability(sess, net, states, input_sample, args): ''' pass it forward and get network probabilities ''' prob, states = net.forward_model(sess, states, input_sample) print (np.shape(states)) exit() return (prob,states)
pass it forward and get network probabilities
pass it forward and get network probabilities
[ "pass", "it", "forward", "and", "get", "network", "probabilities" ]
def NET_Probability(sess, net, states, input_sample, args): prob, states = net.forward_model(sess, states, input_sample) print (np.shape(states)) exit() return (prob,states)
[ "def", "NET_Probability", "(", "sess", ",", "net", ",", "states", ",", "input_sample", ",", "args", ")", ":", "prob", ",", "states", "=", "net", ".", "forward_model", "(", "sess", ",", "states", ",", "input_sample", ")", "print", "(", "np", ".", "shape...
pass it forward and get network probabilities
[ "pass", "it", "forward", "and", "get", "network", "probabilities" ]
[ "''' pass it forward and get network probabilities '''" ]
[ { "param": "sess", "type": null }, { "param": "net", "type": null }, { "param": "states", "type": null }, { "param": "input_sample", "type": null }, { "param": "args", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sess", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "net", "type": null, "docstring": null, "docstring_tokens": []...
a862dbb10ac6d731c4ed75c60c82dc7565d56338
LincLabUCCS/Jack_RNN_Chatbot
chatbot.py
[ "MIT" ]
Python
ENT_Probability
<not_specific>
def ENT_Probability(sess, net, states, input_sample, args): ''' pass it forward and get network probabilities ''' prob, states = net.forward_model(sess, states, input_sample) prob *= args.freqs prob = prob/sum(prob) return (prob,states)
pass it forward and get network probabilities
pass it forward and get network probabilities
[ "pass", "it", "forward", "and", "get", "network", "probabilities" ]
def ENT_Probability(sess, net, states, input_sample, args): prob, states = net.forward_model(sess, states, input_sample) prob *= args.freqs prob = prob/sum(prob) return (prob,states)
[ "def", "ENT_Probability", "(", "sess", ",", "net", ",", "states", ",", "input_sample", ",", "args", ")", ":", "prob", ",", "states", "=", "net", ".", "forward_model", "(", "sess", ",", "states", ",", "input_sample", ")", "prob", "*=", "args", ".", "fre...
pass it forward and get network probabilities
[ "pass", "it", "forward", "and", "get", "network", "probabilities" ]
[ "''' pass it forward and get network probabilities '''" ]
[ { "param": "sess", "type": null }, { "param": "net", "type": null }, { "param": "states", "type": null }, { "param": "input_sample", "type": null }, { "param": "args", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sess", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "net", "type": null, "docstring": null, "docstring_tokens": []...
a862dbb10ac6d731c4ed75c60c82dc7565d56338
LincLabUCCS/Jack_RNN_Chatbot
chatbot.py
[ "MIT" ]
Python
beam_search_generator
<not_specific>
def beam_search_generator(sess, net, initial_state, initial_sample, early_term_token, beam_width, args): # global args '''Run beam search! Yield consensus tokens sequentially, as a generator; return when reaching early_term_token (newline). Args: sess: tensorflow session reference net:...
Run beam search! Yield consensus tokens sequentially, as a generator; return when reaching early_term_token (newline). Args: sess: tensorflow session reference net: tensorflow net graph (must be compatible with the forward_net function) initial_state: initial hidden state of the net ...
Run beam search. Yield consensus tokens sequentially, as a generator; return when reaching early_term_token (newline).
[ "Run", "beam", "search", ".", "Yield", "consensus", "tokens", "sequentially", "as", "a", "generator", ";", "return", "when", "reaching", "early_term_token", "(", "newline", ")", "." ]
def beam_search_generator(sess, net, initial_state, initial_sample, early_term_token, beam_width, args): beam_states = [initial_state] beam_outputs = [[initial_sample]] beam_probs = [1.] beam_entps = [1.] count = 0 while True: new_beam_indices = [] new_beam_probs = [] ...
[ "def", "beam_search_generator", "(", "sess", ",", "net", ",", "initial_state", ",", "initial_sample", ",", "early_term_token", ",", "beam_width", ",", "args", ")", ":", "beam_states", "=", "[", "initial_state", "]", "beam_outputs", "=", "[", "[", "initial_sample...
Run beam search!
[ "Run", "beam", "search!" ]
[ "# global args", "'''Run beam search! Yield consensus tokens sequentially, as a generator;\n return when reaching early_term_token (newline).\n\n Args:\n sess: tensorflow session reference\n net: tensorflow net graph (must be compatible with the forward_net function)\n initial_state: in...
[ { "param": "sess", "type": null }, { "param": "net", "type": null }, { "param": "initial_state", "type": null }, { "param": "initial_sample", "type": null }, { "param": "early_term_token", "type": null }, { "param": "beam_width", "type": null }, ...
{ "returns": [], "raises": [], "params": [ { "identifier": "sess", "type": null, "docstring": "tensorflow session reference", "docstring_tokens": [ "tensorflow", "session", "reference" ], "default": null, "is_optional": null }, { ...
bc5119e36adcfe1c5eedeca52b169f04567d0563
dentearl/n50PlottingTools
src/lengthsToN50Plot.py
[ "MIT" ]
Python
initImage
<not_specific>
def initImage(width, height, options): """ initImage takes a width and height and returns both a fig and pdf object. options must contain outFormat, and dpi """ pdf = None if options.outFormat == 'pdf' or options.outFormat == 'all': pdf = pltBack.PdfPages(options.out + '.pdf') fi...
initImage takes a width and height and returns both a fig and pdf object. options must contain outFormat, and dpi
initImage takes a width and height and returns both a fig and pdf object. options must contain outFormat, and dpi
[ "initImage", "takes", "a", "width", "and", "height", "and", "returns", "both", "a", "fig", "and", "pdf", "object", ".", "options", "must", "contain", "outFormat", "and", "dpi" ]
def initImage(width, height, options): pdf = None if options.outFormat == 'pdf' or options.outFormat == 'all': pdf = pltBack.PdfPages(options.out + '.pdf') fig = plt.figure(figsize=(width, height), dpi=options.dpi, facecolor='w') return (fig, pdf)
[ "def", "initImage", "(", "width", ",", "height", ",", "options", ")", ":", "pdf", "=", "None", "if", "options", ".", "outFormat", "==", "'pdf'", "or", "options", ".", "outFormat", "==", "'all'", ":", "pdf", "=", "pltBack", ".", "PdfPages", "(", "option...
initImage takes a width and height and returns both a fig and pdf object.
[ "initImage", "takes", "a", "width", "and", "height", "and", "returns", "both", "a", "fig", "and", "pdf", "object", "." ]
[ "\"\"\"\n initImage takes a width and height and returns\n both a fig and pdf object. options must contain outFormat,\n and dpi\n \"\"\"" ]
[ { "param": "width", "type": null }, { "param": "height", "type": null }, { "param": "options", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "width", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "height", "type": null, "docstring": null, "docstring_tokens"...
bc5119e36adcfe1c5eedeca52b169f04567d0563
dentearl/n50PlottingTools
src/lengthsToN50Plot.py
[ "MIT" ]
Python
writeImage
null
def writeImage(fig, pdf, options): """ writeImage assumes options contains outFormat and dpi. """ if options.outFormat == 'pdf': fig.savefig(pdf, format = 'pdf') pdf.close() elif options.outFormat == 'png': fig.savefig(options.out + '.png', format='png', dpi=options.dpi) ...
writeImage assumes options contains outFormat and dpi.
writeImage assumes options contains outFormat and dpi.
[ "writeImage", "assumes", "options", "contains", "outFormat", "and", "dpi", "." ]
def writeImage(fig, pdf, options): if options.outFormat == 'pdf': fig.savefig(pdf, format = 'pdf') pdf.close() elif options.outFormat == 'png': fig.savefig(options.out + '.png', format='png', dpi=options.dpi) elif options.outFormat == 'all': fig.savefig(pdf, format='pdf') ...
[ "def", "writeImage", "(", "fig", ",", "pdf", ",", "options", ")", ":", "if", "options", ".", "outFormat", "==", "'pdf'", ":", "fig", ".", "savefig", "(", "pdf", ",", "format", "=", "'pdf'", ")", "pdf", ".", "close", "(", ")", "elif", "options", "."...
writeImage assumes options contains outFormat and dpi.
[ "writeImage", "assumes", "options", "contains", "outFormat", "and", "dpi", "." ]
[ "\"\"\"\n writeImage assumes options contains outFormat and dpi.\n \"\"\"" ]
[ { "param": "fig", "type": null }, { "param": "pdf", "type": null }, { "param": "options", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "fig", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pdf", "type": null, "docstring": null, "docstring_tokens": [],...
bc5119e36adcfe1c5eedeca52b169f04567d0563
dentearl/n50PlottingTools
src/lengthsToN50Plot.py
[ "MIT" ]
Python
nValue
<not_specific>
def nValue(a, x): """ given a dict populated as the processData returned dicts, `a' and a a float x in the range (0, 1.0) nValue returns the Nx value """ if not isinstance(a, LengthObj): raise RuntimeError('Type of `a\' must be LengthObj, not %s' % x.__class__) if ...
given a dict populated as the processData returned dicts, `a' and a a float x in the range (0, 1.0) nValue returns the Nx value
given a dict populated as the processData returned dicts, `a' and a a float x in the range (0, 1.0) nValue returns the Nx value
[ "given", "a", "dict", "populated", "as", "the", "processData", "returned", "dicts", "`", "a", "'", "and", "a", "a", "float", "x", "in", "the", "range", "(", "0", "1", ".", "0", ")", "nValue", "returns", "the", "Nx", "value" ]
def nValue(a, x): if not isinstance(a, LengthObj): raise RuntimeError('Type of `a\' must be LengthObj, not %s' % x.__class__) if not isinstance(x, float): raise RuntimeError('Type of `x\' must be float, not %s' % x.__class__) if not (0.0 < x < 1.0): raise R...
[ "def", "nValue", "(", "a", ",", "x", ")", ":", "if", "not", "isinstance", "(", "a", ",", "LengthObj", ")", ":", "raise", "RuntimeError", "(", "'Type of `a\\' must be LengthObj, not %s'", "%", "x", ".", "__class__", ")", "if", "not", "isinstance", "(", "x",...
given a dict populated as the processData returned dicts, `a' and a a float x in the range (0, 1.0) nValue returns the Nx value
[ "given", "a", "dict", "populated", "as", "the", "processData", "returned", "dicts", "`", "a", "'", "and", "a", "a", "float", "x", "in", "the", "range", "(", "0", "1", ".", "0", ")", "nValue", "returns", "the", "Nx", "value" ]
[ "\"\"\" given a dict populated as the processData returned dicts, `a'\n and a a float x in the range (0, 1.0) nValue returns the Nx value\n \"\"\"" ]
[ { "param": "a", "type": null }, { "param": "x", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "a", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "x", "type": null, "docstring": null, "docstring_tokens": [], ...
bc5119e36adcfe1c5eedeca52b169f04567d0563
dentearl/n50PlottingTools
src/lengthsToN50Plot.py
[ "MIT" ]
Python
processData
null
def processData(lengthObjList, options): """ processData() takes the list of LengthObjs and sorts their lengths, if necessary, """ if options.genomeLength is None: options.genomeLength = max(map(lambda x: x.xData[-1], lengthObjList)) for l in lengthObjList: l.xData = numpy.divide(l.x...
processData() takes the list of LengthObjs and sorts their lengths, if necessary,
processData() takes the list of LengthObjs and sorts their lengths, if necessary.
[ "processData", "()", "takes", "the", "list", "of", "LengthObjs", "and", "sorts", "their", "lengths", "if", "necessary", "." ]
def processData(lengthObjList, options): if options.genomeLength is None: options.genomeLength = max(map(lambda x: x.xData[-1], lengthObjList)) for l in lengthObjList: l.xData = numpy.divide(l.xData, float(options.genomeLength))
[ "def", "processData", "(", "lengthObjList", ",", "options", ")", ":", "if", "options", ".", "genomeLength", "is", "None", ":", "options", ".", "genomeLength", "=", "max", "(", "map", "(", "lambda", "x", ":", "x", ".", "xData", "[", "-", "1", "]", ","...
processData() takes the list of LengthObjs and sorts their lengths, if necessary,
[ "processData", "()", "takes", "the", "list", "of", "LengthObjs", "and", "sorts", "their", "lengths", "if", "necessary" ]
[ "\"\"\" processData() takes the list of LengthObjs and sorts\n their lengths, if necessary,\n \"\"\"" ]
[ { "param": "lengthObjList", "type": null }, { "param": "options", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lengthObjList", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "options", "type": null, "docstring": null, "docstrin...
16f8c905324c3030afa921fb9b6dfbf9325c898f
cjwinchester/co-early-vote-count-parser
co-early-votes.py
[ "Unlicense" ]
Python
table_parser
<not_specific>
def table_parser(table): ''' given a table from a PDFplumber page -- a list of lists with every data point for a county and gender total in a single row -- melt into a tidy list of dictionaries with keys that match `OUTCOLS` above ''' # list to dump data into outlist = [] # placeholder...
given a table from a PDFplumber page -- a list of lists with every data point for a county and gender total in a single row -- melt into a tidy list of dictionaries with keys that match `OUTCOLS` above
given a table from a PDFplumber page -- a list of lists with every data point for a county and gender total in a single row -- melt into a tidy list of dictionaries with keys that match `OUTCOLS` above
[ "given", "a", "table", "from", "a", "PDFplumber", "page", "--", "a", "list", "of", "lists", "with", "every", "data", "point", "for", "a", "county", "and", "gender", "total", "in", "a", "single", "row", "--", "melt", "into", "a", "tidy", "list", "of", ...
def table_parser(table): outlist = [] county = None for row in table: if 'COUNTY' in row[0]: continue if row[0]: county = row[0] gender = row[1] for i, col in enumerate(INCOLS): if col.upper() in ['COUNTY', 'GENDER']: contin...
[ "def", "table_parser", "(", "table", ")", ":", "outlist", "=", "[", "]", "county", "=", "None", "for", "row", "in", "table", ":", "if", "'COUNTY'", "in", "row", "[", "0", "]", ":", "continue", "if", "row", "[", "0", "]", ":", "county", "=", "row"...
given a table from a PDFplumber page -- a list of lists with every data point for a county and gender total in a single row -- melt into a tidy list of dictionaries with keys that match `OUTCOLS` above
[ "given", "a", "table", "from", "a", "PDFplumber", "page", "--", "a", "list", "of", "lists", "with", "every", "data", "point", "for", "a", "county", "and", "gender", "total", "in", "a", "single", "row", "--", "melt", "into", "a", "tidy", "list", "of", ...
[ "'''\n given a table from a PDFplumber page -- a list of lists with every\n data point for a county and gender total in a single row -- melt\n into a tidy list of dictionaries with keys that match `OUTCOLS` above\n '''", "# list to dump data into", "# placeholder value for county, which will be upda...
[ { "param": "table", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "table", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
72387354b865e2a21ac7fadbfb20d60cd09b149e
VolkerH/Optimal-cuFFT-dimensions-in-Python
factorization_cufft_pad.py
[ "BSD-3-Clause" ]
Python
closest_optimal
<not_specific>
def closest_optimal(n, search_next_largest: bool=True, allowed_factors=(2,3,5,7)): """ Finds closest optimal array dimensions for cuFFT Parameters ---------- n : iterable of integers Input dimensions search_next_largest : bool if True (default) search closest optimal dim...
Finds closest optimal array dimensions for cuFFT Parameters ---------- n : iterable of integers Input dimensions search_next_largest : bool if True (default) search closest optimal dimensions that are larger or equal to original otherwise look for smaller ones. ...
Finds closest optimal array dimensions for cuFFT
[ "Finds", "closest", "optimal", "array", "dimensions", "for", "cuFFT" ]
def closest_optimal(n, search_next_largest: bool=True, allowed_factors=(2,3,5,7)): n = np.asarray(n) scalar_input = False if n.ndim == 0: n = n[None] scalar_input = True ret = np.array([_closest_optimal(ni, search_next_largest, allowed_factors) for ni in n]) if scalar_input: ...
[ "def", "closest_optimal", "(", "n", ",", "search_next_largest", ":", "bool", "=", "True", ",", "allowed_factors", "=", "(", "2", ",", "3", ",", "5", ",", "7", ")", ")", ":", "n", "=", "np", ".", "asarray", "(", "n", ")", "scalar_input", "=", "False...
Finds closest optimal array dimensions for cuFFT
[ "Finds", "closest", "optimal", "array", "dimensions", "for", "cuFFT" ]
[ "\"\"\" Finds closest optimal array dimensions for cuFFT\r\n \r\n Parameters\r\n ----------\r\n n : iterable of integers\r\n Input dimensions\r\n search_next_largest : bool\r\n if True (default) search closest optimal dimensions that are larger or equal to original\r\n otherwise ...
[ { "param": "n", "type": null }, { "param": "search_next_largest", "type": "bool" }, { "param": "allowed_factors", "type": null } ]
{ "returns": [ { "docstring": "optimal dimensions for cuFFT", "docstring_tokens": [ "optimal", "dimensions", "for", "cuFFT" ], "type": "np.array of ints\r" }, { "docstring": null, "docstring_tokens": [ "None" ], "type"...
e5cead119cda73c6f12be4d5ef46c2114dbb181c
tonybaloney/pywinexe
build/lib/pywinexe/api.py
[ "Apache-2.0" ]
Python
cmd
<not_specific>
def cmd(cmd, **kwargs): """Run statements with the windows cmd interpreter :param cmd: Statements to run :param \*\*kwargs: Optional arguments that ``Request`` takes """ return Request('cmd', cmd=cmd, **kwargs).send()
Run statements with the windows cmd interpreter :param cmd: Statements to run :param \*\*kwargs: Optional arguments that ``Request`` takes
Run statements with the windows cmd interpreter
[ "Run", "statements", "with", "the", "windows", "cmd", "interpreter" ]
def cmd(cmd, **kwargs): return Request('cmd', cmd=cmd, **kwargs).send()
[ "def", "cmd", "(", "cmd", ",", "**", "kwargs", ")", ":", "return", "Request", "(", "'cmd'", ",", "cmd", "=", "cmd", ",", "**", "kwargs", ")", ".", "send", "(", ")" ]
Run statements with the windows cmd interpreter
[ "Run", "statements", "with", "the", "windows", "cmd", "interpreter" ]
[ "\"\"\"Run statements with the windows cmd interpreter\n\n :param cmd: Statements to run\n :param \\*\\*kwargs: Optional arguments that ``Request`` takes\n \"\"\"" ]
[ { "param": "cmd", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cmd", "type": null, "docstring": "Statements to run", "docstring_tokens": [ "Statements", "to", "run" ], "default": null, "is_optional": null } ], "outlier_params": [ { ...
e5cead119cda73c6f12be4d5ef46c2114dbb181c
tonybaloney/pywinexe
build/lib/pywinexe/api.py
[ "Apache-2.0" ]
Python
ps
<not_specific>
def ps(cmd, **kwargs): """Run statements with the windows powershell interpreter :param cmd: Statements to run :param \*\*kwargs: Optional arguments that ``Request`` takes """ return Request('ps', cmd=cmd, **kwargs).send()
Run statements with the windows powershell interpreter :param cmd: Statements to run :param \*\*kwargs: Optional arguments that ``Request`` takes
Run statements with the windows powershell interpreter
[ "Run", "statements", "with", "the", "windows", "powershell", "interpreter" ]
def ps(cmd, **kwargs): return Request('ps', cmd=cmd, **kwargs).send()
[ "def", "ps", "(", "cmd", ",", "**", "kwargs", ")", ":", "return", "Request", "(", "'ps'", ",", "cmd", "=", "cmd", ",", "**", "kwargs", ")", ".", "send", "(", ")" ]
Run statements with the windows powershell interpreter
[ "Run", "statements", "with", "the", "windows", "powershell", "interpreter" ]
[ "\"\"\"Run statements with the windows powershell interpreter\n\n :param cmd: Statements to run\n :param \\*\\*kwargs: Optional arguments that ``Request`` takes\n \"\"\"" ]
[ { "param": "cmd", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cmd", "type": null, "docstring": "Statements to run", "docstring_tokens": [ "Statements", "to", "run" ], "default": null, "is_optional": null } ], "outlier_params": [ { ...
e5cead119cda73c6f12be4d5ef46c2114dbb181c
tonybaloney/pywinexe
build/lib/pywinexe/api.py
[ "Apache-2.0" ]
Python
script
<not_specific>
def script(script, *args, **kwargs): """Run the statements in the script :param script: script to execute :param \*args: Arguments to the script :param \*\*kwargs: Optional arguments that ``Request`` takes """ kwargs['script'] = script kwargs['args'] = args return Request('script', **kw...
Run the statements in the script :param script: script to execute :param \*args: Arguments to the script :param \*\*kwargs: Optional arguments that ``Request`` takes
Run the statements in the script
[ "Run", "the", "statements", "in", "the", "script" ]
def script(script, *args, **kwargs): kwargs['script'] = script kwargs['args'] = args return Request('script', **kwargs).send()
[ "def", "script", "(", "script", ",", "*", "args", ",", "**", "kwargs", ")", ":", "kwargs", "[", "'script'", "]", "=", "script", "kwargs", "[", "'args'", "]", "=", "args", "return", "Request", "(", "'script'", ",", "**", "kwargs", ")", ".", "send", ...
Run the statements in the script
[ "Run", "the", "statements", "in", "the", "script" ]
[ "\"\"\"Run the statements in the script\n\n :param script: script to execute\n :param \\*args: Arguments to the script\n :param \\*\\*kwargs: Optional arguments that ``Request`` takes\n \"\"\"" ]
[ { "param": "script", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "script", "type": null, "docstring": "script to execute", "docstring_tokens": [ "script", "to", "execute" ], "default": null, "is_optional": null } ], "outlier_params": [ { ...
4642ae784fb674daf23693da895ce35a7be3bc5a
tonybaloney/pywinexe
build/lib/pywinexe/parser.py
[ "Apache-2.0" ]
Python
parse_ps
<not_specific>
def parse_ps(ps, *args): """Returns a one line version of a powershell script """ # insert args if args: ps = _insert_ps_args(ps, *args) # Oneliner ps = ';'.join(ps.split('\n')) # Prepare for execution in shell, escapes ps = ps.replace('\\', '\\\\').replace('"', '\\"') return...
Returns a one line version of a powershell script
Returns a one line version of a powershell script
[ "Returns", "a", "one", "line", "version", "of", "a", "powershell", "script" ]
def parse_ps(ps, *args): if args: ps = _insert_ps_args(ps, *args) ps = ';'.join(ps.split('\n')) ps = ps.replace('\\', '\\\\').replace('"', '\\"') return 'powershell "%s"' % ps
[ "def", "parse_ps", "(", "ps", ",", "*", "args", ")", ":", "if", "args", ":", "ps", "=", "_insert_ps_args", "(", "ps", ",", "*", "args", ")", "ps", "=", "';'", ".", "join", "(", "ps", ".", "split", "(", "'\\n'", ")", ")", "ps", "=", "ps", ".",...
Returns a one line version of a powershell script
[ "Returns", "a", "one", "line", "version", "of", "a", "powershell", "script" ]
[ "\"\"\"Returns a one line version of a powershell script\n \"\"\"", "# insert args", "# Oneliner", "# Prepare for execution in shell, escapes" ]
[ { "param": "ps", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ps", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4642ae784fb674daf23693da895ce35a7be3bc5a
tonybaloney/pywinexe
build/lib/pywinexe/parser.py
[ "Apache-2.0" ]
Python
parse_cmd
<not_specific>
def parse_cmd(script, *args): """Returns a one line version of a bat script """ if args: raise Exception('Args for cmd not implemented') # http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true oneline_cmd = '&&'.join(script.split('\n')) oneline_...
Returns a one line version of a bat script
Returns a one line version of a bat script
[ "Returns", "a", "one", "line", "version", "of", "a", "bat", "script" ]
def parse_cmd(script, *args): if args: raise Exception('Args for cmd not implemented') oneline_cmd = '&&'.join(script.split('\n')) oneline_cmd = 'cmd.exe /c "%s"' % oneline_cmd return oneline_cmd
[ "def", "parse_cmd", "(", "script", ",", "*", "args", ")", ":", "if", "args", ":", "raise", "Exception", "(", "'Args for cmd not implemented'", ")", "oneline_cmd", "=", "'&&'", ".", "join", "(", "script", ".", "split", "(", "'\\n'", ")", ")", "oneline_cmd",...
Returns a one line version of a bat script
[ "Returns", "a", "one", "line", "version", "of", "a", "bat", "script" ]
[ "\"\"\"Returns a one line version of a bat script\n \"\"\"", "# http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true" ]
[ { "param": "script", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "script", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
15293f255b8e2ed6f7209ef7e3bd60e77c4d0133
tonybaloney/pywinexe
build/lib/pywinexe/models.py
[ "Apache-2.0" ]
Python
parse
null
def parse(self): """Parse commands and convert to winexe supported commands """ if self.method == 'script': self.cmd = parser.parse(self.script, *self.args) elif self.method == 'cmd': self.cmd = parser.parse_cmd(self.cmd, *self.args) elif self.method == ...
Parse commands and convert to winexe supported commands
Parse commands and convert to winexe supported commands
[ "Parse", "commands", "and", "convert", "to", "winexe", "supported", "commands" ]
def parse(self): if self.method == 'script': self.cmd = parser.parse(self.script, *self.args) elif self.method == 'cmd': self.cmd = parser.parse_cmd(self.cmd, *self.args) elif self.method == 'ps': self.cmd = parser.parse_ps(self.cmd, *self.args) else: ...
[ "def", "parse", "(", "self", ")", ":", "if", "self", ".", "method", "==", "'script'", ":", "self", ".", "cmd", "=", "parser", ".", "parse", "(", "self", ".", "script", ",", "*", "self", ".", "args", ")", "elif", "self", ".", "method", "==", "'cmd...
Parse commands and convert to winexe supported commands
[ "Parse", "commands", "and", "convert", "to", "winexe", "supported", "commands" ]
[ "\"\"\"Parse commands and convert to winexe supported commands\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
15293f255b8e2ed6f7209ef7e3bd60e77c4d0133
tonybaloney/pywinexe
build/lib/pywinexe/models.py
[ "Apache-2.0" ]
Python
command
<not_specific>
def command(self): """Constructs a complete winexe command. Returns command in a list. """ args = ['winexe'] if self.user and self.password: args.extend(['-U', '%s%%%s' % (self.user, self.password)]) args.append('//%s' % self.host) args.append(self.cmd) ...
Constructs a complete winexe command. Returns command in a list.
Constructs a complete winexe command. Returns command in a list.
[ "Constructs", "a", "complete", "winexe", "command", ".", "Returns", "command", "in", "a", "list", "." ]
def command(self): args = ['winexe'] if self.user and self.password: args.extend(['-U', '%s%%%s' % (self.user, self.password)]) args.append('//%s' % self.host) args.append(self.cmd) return args
[ "def", "command", "(", "self", ")", ":", "args", "=", "[", "'winexe'", "]", "if", "self", ".", "user", "and", "self", ".", "password", ":", "args", ".", "extend", "(", "[", "'-U'", ",", "'%s%%%s'", "%", "(", "self", ".", "user", ",", "self", ".",...
Constructs a complete winexe command.
[ "Constructs", "a", "complete", "winexe", "command", "." ]
[ "\"\"\"Constructs a complete winexe command. Returns command in a list.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
15293f255b8e2ed6f7209ef7e3bd60e77c4d0133
tonybaloney/pywinexe
build/lib/pywinexe/models.py
[ "Apache-2.0" ]
Python
command_str
<not_specific>
def command_str(self): """Return the winexe command. Can by pasted directly to the terminal. """ args = self.command() args[-1] = "'%s'" % self.cmd return ' '.join(args)
Return the winexe command. Can by pasted directly to the terminal.
Return the winexe command. Can by pasted directly to the terminal.
[ "Return", "the", "winexe", "command", ".", "Can", "by", "pasted", "directly", "to", "the", "terminal", "." ]
def command_str(self): args = self.command() args[-1] = "'%s'" % self.cmd return ' '.join(args)
[ "def", "command_str", "(", "self", ")", ":", "args", "=", "self", ".", "command", "(", ")", "args", "[", "-", "1", "]", "=", "\"'%s'\"", "%", "self", ".", "cmd", "return", "' '", ".", "join", "(", "args", ")" ]
Return the winexe command.
[ "Return", "the", "winexe", "command", "." ]
[ "\"\"\"Return the winexe command. Can by pasted directly to the terminal.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
15293f255b8e2ed6f7209ef7e3bd60e77c4d0133
tonybaloney/pywinexe
build/lib/pywinexe/models.py
[ "Apache-2.0" ]
Python
send
<not_specific>
def send(self): """Sends the request. Returns output, success """ winexe_cmd = self.command() log.debug("Executing command: %s" % self.command_str()) try: output = subprocess.check_output(winexe_cmd, stderr=subprocess.STDOU...
Sends the request. Returns output, success
Sends the request. Returns output, success
[ "Sends", "the", "request", ".", "Returns", "output", "success" ]
def send(self): winexe_cmd = self.command() log.debug("Executing command: %s" % self.command_str()) try: output = subprocess.check_output(winexe_cmd, stderr=subprocess.STDOUT) output = output.rstrip('\r\n') return o...
[ "def", "send", "(", "self", ")", ":", "winexe_cmd", "=", "self", ".", "command", "(", ")", "log", ".", "debug", "(", "\"Executing command: %s\"", "%", "self", ".", "command_str", "(", ")", ")", "try", ":", "output", "=", "subprocess", ".", "check_output"...
Sends the request.
[ "Sends", "the", "request", "." ]
[ "\"\"\"Sends the request. Returns output, success\n \"\"\"", "# always strip ending windows newlines" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
16c2fd1e4b194b567c16b6454e8a7c9f7966228a
Acrobot/incubator-mxnet
python/mxnet/ndarray/numpy/random.py
[ "Apache-2.0" ]
Python
uniform
<not_specific>
def uniform(low=0.0, high=1.0, size=None, dtype=None, ctx=None, out=None): r"""Draw samples from a uniform distribution. Samples are uniformly distributed over the half-open interval ``[low, high)`` (includes low, but excludes high). In other words, any value within the given interval is equally likel...
r"""Draw samples from a uniform distribution. Samples are uniformly distributed over the half-open interval ``[low, high)`` (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by `uniform`. Parameters ---------- low : float,...
r"""Draw samples from a uniform distribution. Samples are uniformly distributed over the half-open interval ``[low, high)`` (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by `uniform`. Parameters low : float, ndarray, optional Lower boundary of th...
[ "r", "\"", "\"", "\"", "Draw", "samples", "from", "a", "uniform", "distribution", ".", "Samples", "are", "uniformly", "distributed", "over", "the", "half", "-", "open", "interval", "`", "`", "[", "low", "high", ")", "`", "`", "(", "includes", "low", "b...
def uniform(low=0.0, high=1.0, size=None, dtype=None, ctx=None, out=None): from ...numpy import ndarray as np_ndarray input_type = (isinstance(low, np_ndarray), isinstance(high, np_ndarray)) if dtype is None: dtype = 'float32' if ctx is None: ctx = current_context() if size == (): ...
[ "def", "uniform", "(", "low", "=", "0.0", ",", "high", "=", "1.0", ",", "size", "=", "None", ",", "dtype", "=", "None", ",", "ctx", "=", "None", ",", "out", "=", "None", ")", ":", "from", ".", ".", ".", "numpy", "import", "ndarray", "as", "np_n...
r"""Draw samples from a uniform distribution.
[ "r", "\"", "\"", "\"", "Draw", "samples", "from", "a", "uniform", "distribution", "." ]
[ "r\"\"\"Draw samples from a uniform distribution.\n\n Samples are uniformly distributed over the half-open interval\n ``[low, high)`` (includes low, but excludes high). In other words,\n any value within the given interval is equally likely to be drawn\n by `uniform`.\n\n Parameters\n ----------\...
[ { "param": "low", "type": null }, { "param": "high", "type": null }, { "param": "size", "type": null }, { "param": "dtype", "type": null }, { "param": "ctx", "type": null }, { "param": "out", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "low", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "high", "type": null, "docstring": null, "docstring_tokens": []...
16c2fd1e4b194b567c16b6454e8a7c9f7966228a
Acrobot/incubator-mxnet
python/mxnet/ndarray/numpy/random.py
[ "Apache-2.0" ]
Python
lognormal
<not_specific>
def lognormal(mean=0.0, sigma=1.0, size=None, dtype=None, ctx=None, out=None): r"""Draw samples from a log-normal distribution. Draw samples from a log-normal distribution with specified mean, standard deviation, and array shape. Note that the mean and standard deviation are not the values for the dist...
r"""Draw samples from a log-normal distribution. Draw samples from a log-normal distribution with specified mean, standard deviation, and array shape. Note that the mean and standard deviation are not the values for the distribution itself, but of the underlying normal distribution it is derived from. ...
r"""Draw samples from a log-normal distribution. Draw samples from a log-normal distribution with specified mean, standard deviation, and array shape. Note that the mean and standard deviation are not the values for the distribution itself, but of the underlying normal distribution it is derived from. Parameters mean...
[ "r", "\"", "\"", "\"", "Draw", "samples", "from", "a", "log", "-", "normal", "distribution", ".", "Draw", "samples", "from", "a", "log", "-", "normal", "distribution", "with", "specified", "mean", "standard", "deviation", "and", "array", "shape", ".", "Not...
def lognormal(mean=0.0, sigma=1.0, size=None, dtype=None, ctx=None, out=None): from . import _op as _mx_np_op return _mx_np_op.exp(normal(loc=mean, scale=sigma, size=size, dtype=dtype, ctx=ctx, out=out))
[ "def", "lognormal", "(", "mean", "=", "0.0", ",", "sigma", "=", "1.0", ",", "size", "=", "None", ",", "dtype", "=", "None", ",", "ctx", "=", "None", ",", "out", "=", "None", ")", ":", "from", ".", "import", "_op", "as", "_mx_np_op", "return", "_m...
r"""Draw samples from a log-normal distribution.
[ "r", "\"", "\"", "\"", "Draw", "samples", "from", "a", "log", "-", "normal", "distribution", "." ]
[ "r\"\"\"Draw samples from a log-normal distribution.\n Draw samples from a log-normal distribution with specified mean,\n standard deviation, and array shape. Note that the mean and standard\n deviation are not the values for the distribution itself, but of the\n underlying normal distribution it is de...
[ { "param": "mean", "type": null }, { "param": "sigma", "type": null }, { "param": "size", "type": null }, { "param": "dtype", "type": null }, { "param": "ctx", "type": null }, { "param": "out", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "mean", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sigma", "type": null, "docstring": null, "docstring_tokens": ...
16c2fd1e4b194b567c16b6454e8a7c9f7966228a
Acrobot/incubator-mxnet
python/mxnet/ndarray/numpy/random.py
[ "Apache-2.0" ]
Python
multivariate_normal
<not_specific>
def multivariate_normal(mean, cov, size=None, check_valid=None, tol=None): """ multivariate_normal(mean, cov, size=None, check_valid=None, tol=None) Draw random samples from a multivariate normal distribution. The multivariate normal, multinormal or Gaussian distribution is a generalization of the...
multivariate_normal(mean, cov, size=None, check_valid=None, tol=None) Draw random samples from a multivariate normal distribution. The multivariate normal, multinormal or Gaussian distribution is a generalization of the one-dimensional normal distribution to higher dimensions. Such a distributio...
multivariate_normal(mean, cov, size=None, check_valid=None, tol=None) Draw random samples from a multivariate normal distribution. The multivariate normal, multinormal or Gaussian distribution is a generalization of the one-dimensional normal distribution to higher dimensions. Such a distribution is specified by its ...
[ "multivariate_normal", "(", "mean", "cov", "size", "=", "None", "check_valid", "=", "None", "tol", "=", "None", ")", "Draw", "random", "samples", "from", "a", "multivariate", "normal", "distribution", ".", "The", "multivariate", "normal", "multinormal", "or", ...
def multivariate_normal(mean, cov, size=None, check_valid=None, tol=None): if check_valid is not None: raise NotImplementedError('Parameter `check_valid` is not supported') if tol is not None: raise NotImplementedError('Parameter `tol` is not supported') return _npi.mvn_fallback(mean, cov, s...
[ "def", "multivariate_normal", "(", "mean", ",", "cov", ",", "size", "=", "None", ",", "check_valid", "=", "None", ",", "tol", "=", "None", ")", ":", "if", "check_valid", "is", "not", "None", ":", "raise", "NotImplementedError", "(", "'Parameter `check_valid`...
multivariate_normal(mean, cov, size=None, check_valid=None, tol=None) Draw random samples from a multivariate normal distribution.
[ "multivariate_normal", "(", "mean", "cov", "size", "=", "None", "check_valid", "=", "None", "tol", "=", "None", ")", "Draw", "random", "samples", "from", "a", "multivariate", "normal", "distribution", "." ]
[ "\"\"\"\n multivariate_normal(mean, cov, size=None, check_valid=None, tol=None)\n\n Draw random samples from a multivariate normal distribution.\n\n The multivariate normal, multinormal or Gaussian distribution is a\n generalization of the one-dimensional normal distribution to higher\n dimensions. ...
[ { "param": "mean", "type": null }, { "param": "cov", "type": null }, { "param": "size", "type": null }, { "param": "check_valid", "type": null }, { "param": "tol", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "mean", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "cov", "type": null, "docstring": null, "docstring_tokens": []...
16c2fd1e4b194b567c16b6454e8a7c9f7966228a
Acrobot/incubator-mxnet
python/mxnet/ndarray/numpy/random.py
[ "Apache-2.0" ]
Python
gamma
<not_specific>
def gamma(shape, scale=1.0, size=None, dtype=None, ctx=None, out=None): """Draw samples from a Gamma distribution. Samples are drawn from a Gamma distribution with specified parameters, `shape` (sometimes designated "k") and `scale` (sometimes designated "theta"), where both parameters are > 0. Pa...
Draw samples from a Gamma distribution. Samples are drawn from a Gamma distribution with specified parameters, `shape` (sometimes designated "k") and `scale` (sometimes designated "theta"), where both parameters are > 0. Parameters ---------- shape : float or array_like of floats The s...
Draw samples from a Gamma distribution. Samples are drawn from a Gamma distribution with specified parameters, `shape` (sometimes designated "k") and `scale` (sometimes designated "theta"), where both parameters are > 0. Parameters shape : float or array_like of floats The shape of the gamma distribution. Should be g...
[ "Draw", "samples", "from", "a", "Gamma", "distribution", ".", "Samples", "are", "drawn", "from", "a", "Gamma", "distribution", "with", "specified", "parameters", "`", "shape", "`", "(", "sometimes", "designated", "\"", "k", "\"", ")", "and", "`", "scale", ...
def gamma(shape, scale=1.0, size=None, dtype=None, ctx=None, out=None): from ...numpy import ndarray as np_ndarray input_type = (isinstance(shape, np_ndarray), isinstance(scale, np_ndarray)) if dtype is None: dtype = 'float32' if ctx is None: ctx = current_context() if out is not Non...
[ "def", "gamma", "(", "shape", ",", "scale", "=", "1.0", ",", "size", "=", "None", ",", "dtype", "=", "None", ",", "ctx", "=", "None", ",", "out", "=", "None", ")", ":", "from", ".", ".", ".", "numpy", "import", "ndarray", "as", "np_ndarray", "inp...
Draw samples from a Gamma distribution.
[ "Draw", "samples", "from", "a", "Gamma", "distribution", "." ]
[ "\"\"\"Draw samples from a Gamma distribution.\n\n Samples are drawn from a Gamma distribution with specified parameters,\n `shape` (sometimes designated \"k\") and `scale` (sometimes designated\n \"theta\"), where both parameters are > 0.\n\n Parameters\n ----------\n shape : float or array_like ...
[ { "param": "shape", "type": null }, { "param": "scale", "type": null }, { "param": "size", "type": null }, { "param": "dtype", "type": null }, { "param": "ctx", "type": null }, { "param": "out", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "shape", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "scale", "type": null, "docstring": null, "docstring_tokens":...
16c2fd1e4b194b567c16b6454e8a7c9f7966228a
Acrobot/incubator-mxnet
python/mxnet/ndarray/numpy/random.py
[ "Apache-2.0" ]
Python
shuffle
null
def shuffle(x): """ Modify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remain the same. Parameters ---------- x: ndarray The array o...
Modify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remain the same. Parameters ---------- x: ndarray The array or list to be shuffled. ...
Modify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remain the same. Parameters ndarray The array or list to be shuffled. Returns None Examples Multi-dimensional array...
[ "Modify", "a", "sequence", "in", "-", "place", "by", "shuffling", "its", "contents", ".", "This", "function", "only", "shuffles", "the", "array", "along", "the", "first", "axis", "of", "a", "multi", "-", "dimensional", "array", ".", "The", "order", "of", ...
def shuffle(x): _npi.shuffle(x, out=x)
[ "def", "shuffle", "(", "x", ")", ":", "_npi", ".", "shuffle", "(", "x", ",", "out", "=", "x", ")" ]
Modify a sequence in-place by shuffling its contents.
[ "Modify", "a", "sequence", "in", "-", "place", "by", "shuffling", "its", "contents", "." ]
[ "\"\"\"\n Modify a sequence in-place by shuffling its contents.\n\n This function only shuffles the array along the first axis of a\n multi-dimensional array. The order of sub-arrays is changed but\n their contents remain the same.\n\n Parameters\n ----------\n x: ndarray\n The array or ...
[ { "param": "x", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "x", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
f35c7c6ec7f333708830e5450fcdbb730c8af96f
maxjnorman/genetic-algorithm-feature-selection
genetic-algorithm-feature-selection/modules/clade.py
[ "MIT" ]
Python
collapse
null
def collapse(self): """ want to remove clades with single descendants """ if self._len_descs() == 1: if list(self.descs)[0]._len_descs() > 0: # it is not an Individual desc = list(self.descs)[0] # the descendant object self._descs = list(desc...
want to remove clades with single descendants
want to remove clades with single descendants
[ "want", "to", "remove", "clades", "with", "single", "descendants" ]
def collapse(self): if self._len_descs() == 1: if list(self.descs)[0]._len_descs() > 0: desc = list(self.descs)[0] self._descs = list(desc.descs) for desc in self.descs: desc.collapse() if desc._len_descs() == 1: sel...
[ "def", "collapse", "(", "self", ")", ":", "if", "self", ".", "_len_descs", "(", ")", "==", "1", ":", "if", "list", "(", "self", ".", "descs", ")", "[", "0", "]", ".", "_len_descs", "(", ")", ">", "0", ":", "desc", "=", "list", "(", "self", "....
want to remove clades with single descendants
[ "want", "to", "remove", "clades", "with", "single", "descendants" ]
[ "\"\"\"\n want to remove clades with single descendants\n \"\"\"", "# it is not an Individual", "# the descendant object" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4eda36ef50beb6ccb58484c15752b92a2134a13d
Livit/Labster.OAuth2Client
oauth2_client/management/commands/oauth2client_app.py
[ "MIT" ]
Python
app_model
<not_specific>
def app_model(self): """ Application model type to be used """ return Application
Application model type to be used
Application model type to be used
[ "Application", "model", "type", "to", "be", "used" ]
def app_model(self): return Application
[ "def", "app_model", "(", "self", ")", ":", "return", "Application" ]
Application model type to be used
[ "Application", "model", "type", "to", "be", "used" ]
[ "\"\"\"\n Application model type to be used\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4eda36ef50beb6ccb58484c15752b92a2134a13d
Livit/Labster.OAuth2Client
oauth2_client/management/commands/oauth2client_app.py
[ "MIT" ]
Python
add_arguments
null
def add_arguments(self, parser): """ Arguments for fields we need populated in the resulting Application instance. Follow a convention that `argument name == model property name` Use help messages defined on the model. """ super(Command, self).add_arguments(parser) ...
Arguments for fields we need populated in the resulting Application instance. Follow a convention that `argument name == model property name` Use help messages defined on the model.
Arguments for fields we need populated in the resulting Application instance. Follow a convention that `argument name == model property name` Use help messages defined on the model.
[ "Arguments", "for", "fields", "we", "need", "populated", "in", "the", "resulting", "Application", "instance", ".", "Follow", "a", "convention", "that", "`", "argument", "name", "==", "model", "property", "name", "`", "Use", "help", "messages", "defined", "on",...
def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--client-id', type=str, help=help_text('client_id', Application) ) parser.add_argument( '--client-secret', type=str, h...
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "super", "(", "Command", ",", "self", ")", ".", "add_arguments", "(", "parser", ")", "parser", ".", "add_argument", "(", "'--client-id'", ",", "type", "=", "str", ",", "help", "=", "help_text"...
Arguments for fields we need populated in the resulting Application instance.
[ "Arguments", "for", "fields", "we", "need", "populated", "in", "the", "resulting", "Application", "instance", "." ]
[ "\"\"\"\n Arguments for fields we need populated in the resulting Application instance.\n Follow a convention that `argument name == model property name`\n Use help messages defined on the model.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "parser", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "parser", "type": null, "docstring": null, "docstring_tokens":...
41859b4499d974ee9d6267fefb3911eebee68be3
Livit/Labster.OAuth2Client
oauth2_client/utils/django/model.py
[ "MIT" ]
Python
help_text
<not_specific>
def help_text(field_name, model_type): """ Get help text from the model field. Args: field_name (str): model_type (type): Returns: str: help_text defined on the model """ # noinspection PyUnresolvedReferences,PyProtectedMember return model_type._meta.get_field(field...
Get help text from the model field. Args: field_name (str): model_type (type): Returns: str: help_text defined on the model
Get help text from the model field.
[ "Get", "help", "text", "from", "the", "model", "field", "." ]
def help_text(field_name, model_type): return model_type._meta.get_field(field_name).help_text
[ "def", "help_text", "(", "field_name", ",", "model_type", ")", ":", "return", "model_type", ".", "_meta", ".", "get_field", "(", "field_name", ")", ".", "help_text" ]
Get help text from the model field.
[ "Get", "help", "text", "from", "the", "model", "field", "." ]
[ "\"\"\"\n Get help text from the model field.\n\n Args:\n field_name (str):\n model_type (type):\n\n Returns:\n str: help_text defined on the model\n \"\"\"", "# noinspection PyUnresolvedReferences,PyProtectedMember" ]
[ { "param": "field_name", "type": null }, { "param": "model_type", "type": null } ]
{ "returns": [ { "docstring": "help_text defined on the model", "docstring_tokens": [ "help_text", "defined", "on", "the", "model" ], "type": "str" } ], "raises": [], "params": [ { "identifier": "field_name", "type": null, ...
de238f2f52238168fcaeb05aeba8fe365f2de319
Livit/Labster.OAuth2Client
oauth2_client/utils/django/base_cmd.py
[ "MIT" ]
Python
create_parser
<not_specific>
def create_parser(self, *args, **kwargs): """ Enable multiline command help text. https://stackoverflow.com/questions/35470680/django-command-how-to-insert-newline-in-the-help-text """ parser = BaseCommand.create_parser(self, *args, **kwargs) parser.formatter_class = Help...
Enable multiline command help text. https://stackoverflow.com/questions/35470680/django-command-how-to-insert-newline-in-the-help-text
Enable multiline command help text.
[ "Enable", "multiline", "command", "help", "text", "." ]
def create_parser(self, *args, **kwargs): parser = BaseCommand.create_parser(self, *args, **kwargs) parser.formatter_class = HelpTextFormatter return parser
[ "def", "create_parser", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "parser", "=", "BaseCommand", ".", "create_parser", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "parser", ".", "formatter_class", "=", "HelpTextFormatter", ...
Enable multiline command help text.
[ "Enable", "multiline", "command", "help", "text", "." ]
[ "\"\"\"\n Enable multiline command help text.\n https://stackoverflow.com/questions/35470680/django-command-how-to-insert-newline-in-the-help-text\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
938f0af36d72e9ec19fa5d83851c68f0fffcb94b
Livit/Labster.OAuth2Client
oauth2_client/utils/date_time.py
[ "MIT" ]
Python
datetime_to_float
<not_specific>
def datetime_to_float(dt): """ Convert a datetime object to a floating point timestamp. Return a number of seconds elapsed from the UTC epoch. If the input object is timezone-aware, the result includes timezone difference between UTC and the timezone. If the input object is timezone-naive, it'...
Convert a datetime object to a floating point timestamp. Return a number of seconds elapsed from the UTC epoch. If the input object is timezone-aware, the result includes timezone difference between UTC and the timezone. If the input object is timezone-naive, it's treated as UTC. NOTE: This b...
Convert a datetime object to a floating point timestamp. Return a number of seconds elapsed from the UTC epoch. If the input object is timezone-aware, the result includes timezone difference between UTC and the timezone. If the input object is timezone-naive, it's treated as UTC. NOTE: This behaviour is different fro...
[ "Convert", "a", "datetime", "object", "to", "a", "floating", "point", "timestamp", ".", "Return", "a", "number", "of", "seconds", "elapsed", "from", "the", "UTC", "epoch", ".", "If", "the", "input", "object", "is", "timezone", "-", "aware", "the", "result"...
def datetime_to_float(dt): epoch = datetime.fromtimestamp(0, tz=pytz.UTC) if not dt.tzinfo: epoch = epoch.replace(tzinfo=None) total_seconds = (dt - epoch).total_seconds() return total_seconds
[ "def", "datetime_to_float", "(", "dt", ")", ":", "epoch", "=", "datetime", ".", "fromtimestamp", "(", "0", ",", "tz", "=", "pytz", ".", "UTC", ")", "if", "not", "dt", ".", "tzinfo", ":", "epoch", "=", "epoch", ".", "replace", "(", "tzinfo", "=", "N...
Convert a datetime object to a floating point timestamp.
[ "Convert", "a", "datetime", "object", "to", "a", "floating", "point", "timestamp", "." ]
[ "\"\"\"\n Convert a datetime object to a floating point timestamp.\n Return a number of seconds elapsed from the UTC epoch.\n\n If the input object is timezone-aware, the result includes timezone\n difference between UTC and the timezone.\n\n If the input object is timezone-naive, it's treated as UTC...
[ { "param": "dt", "type": null } ]
{ "returns": [ { "docstring": "e.g. 123456.123, always counting from UTC", "docstring_tokens": [ "e", ".", "g", ".", "123456", ".", "123", "always", "counting", "from", "UTC" ], "type": "float" } ...
938f0af36d72e9ec19fa5d83851c68f0fffcb94b
Livit/Labster.OAuth2Client
oauth2_client/utils/date_time.py
[ "MIT" ]
Python
float_to_datetime
<not_specific>
def float_to_datetime(timestamp, tzinfo=None): """ Convert a timestamp to a datetime instance. If tzinfo is passed, interpret the timestamp in the given timezone. If tzinfo isn't passed, interpret the timestamp as UTC. NOTE: this behaviour is different from the standard's library `datetime.fro...
Convert a timestamp to a datetime instance. If tzinfo is passed, interpret the timestamp in the given timezone. If tzinfo isn't passed, interpret the timestamp as UTC. NOTE: this behaviour is different from the standard's library `datetime.fromtimestamp()`, that assumes local timezone. For e...
Convert a timestamp to a datetime instance. If tzinfo is passed, interpret the timestamp in the given timezone. If tzinfo isn't passed, interpret the timestamp as UTC. NOTE: this behaviour is different from the standard's library `datetime.fromtimestamp()`, that assumes local timezone. For example, epoch starts at 1a...
[ "Convert", "a", "timestamp", "to", "a", "datetime", "instance", ".", "If", "tzinfo", "is", "passed", "interpret", "the", "timestamp", "in", "the", "given", "timezone", ".", "If", "tzinfo", "isn", "'", "t", "passed", "interpret", "the", "timestamp", "as", "...
def float_to_datetime(timestamp, tzinfo=None): _tz = tzinfo if tzinfo else pytz.UTC dt = datetime.fromtimestamp(timestamp, tz=_tz) if not tzinfo: dt = dt.replace(tzinfo=None) return dt
[ "def", "float_to_datetime", "(", "timestamp", ",", "tzinfo", "=", "None", ")", ":", "_tz", "=", "tzinfo", "if", "tzinfo", "else", "pytz", ".", "UTC", "dt", "=", "datetime", ".", "fromtimestamp", "(", "timestamp", ",", "tz", "=", "_tz", ")", "if", "not"...
Convert a timestamp to a datetime instance.
[ "Convert", "a", "timestamp", "to", "a", "datetime", "instance", "." ]
[ "\"\"\"\n Convert a timestamp to a datetime instance.\n\n If tzinfo is passed, interpret the timestamp in the given timezone.\n\n If tzinfo isn't passed, interpret the timestamp as UTC.\n NOTE: this behaviour is different from the standard's library\n `datetime.fromtimestamp()`, that assumes local ti...
[ { "param": "timestamp", "type": null }, { "param": "tzinfo", "type": null } ]
{ "returns": [ { "docstring": "if no timezone given - a timezone-naive datetime.\nOtherwise - a datetime object in the given timezone.", "docstring_tokens": [ "if", "no", "timezone", "given", "-", "a", "timezone", "-", "naive", ...
cab1b33b3627d2193b1f83a7c422eae2e7a5ee3b
Livit/Labster.OAuth2Client
oauth2_client/models.py
[ "MIT" ]
Python
validate_jwt_grant_data
null
def validate_jwt_grant_data(self): """ If JWT token bearer grant is used, subject has to be specified. Details: https://tools.ietf.org/html/rfc7523#section-3 Returns: None: Raises: ValidationError: 1) when subject not specified """ subjec...
If JWT token bearer grant is used, subject has to be specified. Details: https://tools.ietf.org/html/rfc7523#section-3 Returns: None: Raises: ValidationError: 1) when subject not specified
If JWT token bearer grant is used, subject has to be specified.
[ "If", "JWT", "token", "bearer", "grant", "is", "used", "subject", "has", "to", "be", "specified", "." ]
def validate_jwt_grant_data(self): subject = self.extra_settings.get('subject') if self.authorization_grant_type == Application.GRANT_JWT_BEARER and not subject: msg = ( "grant_type={} requires `subject` to be specified in app.extra_settings['subject']. " "See...
[ "def", "validate_jwt_grant_data", "(", "self", ")", ":", "subject", "=", "self", ".", "extra_settings", ".", "get", "(", "'subject'", ")", "if", "self", ".", "authorization_grant_type", "==", "Application", ".", "GRANT_JWT_BEARER", "and", "not", "subject", ":", ...
If JWT token bearer grant is used, subject has to be specified.
[ "If", "JWT", "token", "bearer", "grant", "is", "used", "subject", "has", "to", "be", "specified", "." ]
[ "\"\"\"\n If JWT token bearer grant is used, subject has to be specified.\n Details: https://tools.ietf.org/html/rfc7523#section-3\n\n Returns:\n None:\n\n Raises:\n ValidationError: 1) when subject not specified\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "None" } ], "raises": [ { "docstring": "1) when subject not specified", "docstring_tokens": [ "1", ")", "when", "subject", "not", "spe...
cab1b33b3627d2193b1f83a7c422eae2e7a5ee3b
Livit/Labster.OAuth2Client
oauth2_client/models.py
[ "MIT" ]
Python
is_expired
<not_specific>
def is_expired(self): """ The token is expired when 1) expiration info available AND 2) expiration datetime is in the past. TIMEOUT_SECONDS margin is used to prevent token expiration issues during long-running requests. Apart from `expired`, the token could be `valid` or `unknown...
The token is expired when 1) expiration info available AND 2) expiration datetime is in the past. TIMEOUT_SECONDS margin is used to prevent token expiration issues during long-running requests. Apart from `expired`, the token could be `valid` or `unknown` (no expiration info available) ...
The token is expired when 1) expiration info available AND 2) expiration datetime is in the past. TIMEOUT_SECONDS margin is used to prevent token expiration issues during long-running requests.
[ "The", "token", "is", "expired", "when", "1", ")", "expiration", "info", "available", "AND", "2", ")", "expiration", "datetime", "is", "in", "the", "past", ".", "TIMEOUT_SECONDS", "margin", "is", "used", "to", "prevent", "token", "expiration", "issues", "dur...
def is_expired(self): if self.expires and timezone.now() >= self.expires - timedelta(seconds=self.TIMEOUT_SECONDS): return True return False
[ "def", "is_expired", "(", "self", ")", ":", "if", "self", ".", "expires", "and", "timezone", ".", "now", "(", ")", ">=", "self", ".", "expires", "-", "timedelta", "(", "seconds", "=", "self", ".", "TIMEOUT_SECONDS", ")", ":", "return", "True", "return"...
The token is expired when 1) expiration info available AND 2) expiration datetime is in the past.
[ "The", "token", "is", "expired", "when", "1", ")", "expiration", "info", "available", "AND", "2", ")", "expiration", "datetime", "is", "in", "the", "past", "." ]
[ "\"\"\"\n The token is expired when 1) expiration info available AND 2) expiration datetime is in the past.\n TIMEOUT_SECONDS margin is used to prevent token expiration issues during long-running\n requests.\n Apart from `expired`, the token could be `valid` or `unknown` (no expiration i...
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "bool" } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
cab1b33b3627d2193b1f83a7c422eae2e7a5ee3b
Livit/Labster.OAuth2Client
oauth2_client/models.py
[ "MIT" ]
Python
to_client_dict
<not_specific>
def to_client_dict(self): """ Transform this AccessToken to a dict as expected by `OAuth2Session` class :return: dict """ as_dict = model_to_dict(self, fields=["token", "token_type", "expires", "scope"]) as_dict["access_token"] = as_dict.pop('token') if 'expires'...
Transform this AccessToken to a dict as expected by `OAuth2Session` class :return: dict
Transform this AccessToken to a dict as expected by `OAuth2Session` class
[ "Transform", "this", "AccessToken", "to", "a", "dict", "as", "expected", "by", "`", "OAuth2Session", "`", "class" ]
def to_client_dict(self): as_dict = model_to_dict(self, fields=["token", "token_type", "expires", "scope"]) as_dict["access_token"] = as_dict.pop('token') if 'expires' in as_dict and as_dict['expires']: expires_dt = as_dict.pop('expires') as_dict["expires_in"] = (expires_...
[ "def", "to_client_dict", "(", "self", ")", ":", "as_dict", "=", "model_to_dict", "(", "self", ",", "fields", "=", "[", "\"token\"", ",", "\"token_type\"", ",", "\"expires\"", ",", "\"scope\"", "]", ")", "as_dict", "[", "\"access_token\"", "]", "=", "as_dict"...
Transform this AccessToken to a dict as expected by `OAuth2Session` class
[ "Transform", "this", "AccessToken", "to", "a", "dict", "as", "expected", "by", "`", "OAuth2Session", "`", "class" ]
[ "\"\"\"\n Transform this AccessToken to a dict as expected by `OAuth2Session` class\n\n :return: dict\n \"\"\"", "# expiry info can be used by oauth2_session (client's 3rd party parent class)" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
33cdde54835d80c25340aad79782cff49dc69ded
Livit/Labster.OAuth2Client
oauth2_client/management/commands/oauth2_app_maker.py
[ "MIT" ]
Python
app_model
null
def app_model(self): """ Specify model class to use. Returns: type: Application model type to be used """ raise NotImplementedError( 'subclasses of OAuth2AppMaker must provide an app_model() method' )
Specify model class to use. Returns: type: Application model type to be used
Specify model class to use.
[ "Specify", "model", "class", "to", "use", "." ]
def app_model(self): raise NotImplementedError( 'subclasses of OAuth2AppMaker must provide an app_model() method' )
[ "def", "app_model", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of OAuth2AppMaker must provide an app_model() method'", ")" ]
Specify model class to use.
[ "Specify", "model", "class", "to", "use", "." ]
[ "\"\"\"\n Specify model class to use.\n\n Returns:\n type: Application model type to be used\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": "Application model type to be used", "docstring_tokens": [ "Application", "model", "type", "to", "be", "used" ], "type": "type" } ], "raises": [], "params": [ { "identifier": "self", "ty...
33cdde54835d80c25340aad79782cff49dc69ded
Livit/Labster.OAuth2Client
oauth2_client/management/commands/oauth2_app_maker.py
[ "MIT" ]
Python
add_arguments
null
def add_arguments(self, parser): """ Add common arguments required for all extending commands. """ parser.add_argument( '--update', action='store_true', help='A flag to update an existing application. Defaults to `False`' ) parser.add_a...
Add common arguments required for all extending commands.
Add common arguments required for all extending commands.
[ "Add", "common", "arguments", "required", "for", "all", "extending", "commands", "." ]
def add_arguments(self, parser): parser.add_argument( '--update', action='store_true', help='A flag to update an existing application. Defaults to `False`' ) parser.add_argument( '--name', type=str, required=True, ...
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "parser", ".", "add_argument", "(", "'--update'", ",", "action", "=", "'store_true'", ",", "help", "=", "'A flag to update an existing application. Defaults to `False`'", ")", "parser", ".", "add_argument",...
Add common arguments required for all extending commands.
[ "Add", "common", "arguments", "required", "for", "all", "extending", "commands", "." ]
[ "\"\"\"\n Add common arguments required for all extending commands.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "parser", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "parser", "type": null, "docstring": null, "docstring_tokens":...
33cdde54835d80c25340aad79782cff49dc69ded
Livit/Labster.OAuth2Client
oauth2_client/management/commands/oauth2_app_maker.py
[ "MIT" ]
Python
_filter_cmd_argument
<not_specific>
def _filter_cmd_argument(argument_name, argument_value, model_fields, update_mode): """ Command arguments always include a lot of ones added by Django, that we don't want to use to determine properties of our model object, e.g. `verbosity`, `settings`, `pythonpath` etc. This utility dete...
Command arguments always include a lot of ones added by Django, that we don't want to use to determine properties of our model object, e.g. `verbosity`, `settings`, `pythonpath` etc. This utility determines if we should use a command's input argument and pass its value to the App model ...
Command arguments always include a lot of ones added by Django, that we don't want to use to determine properties of our model object, e.g. Some extra logic applies to argument's value, depending on `update` parameter value. Create mode (update==False): Use only arguments that have specified values. Don't pass any in...
[ "Command", "arguments", "always", "include", "a", "lot", "of", "ones", "added", "by", "Django", "that", "we", "don", "'", "t", "want", "to", "use", "to", "determine", "properties", "of", "our", "model", "object", "e", ".", "g", ".", "Some", "extra", "l...
def _filter_cmd_argument(argument_name, argument_value, model_fields, update_mode): if update_mode: return bool(argument_name in model_fields and argument_value is not None) else: return bool(argument_name in model_fields and argument_value)
[ "def", "_filter_cmd_argument", "(", "argument_name", ",", "argument_value", ",", "model_fields", ",", "update_mode", ")", ":", "if", "update_mode", ":", "return", "bool", "(", "argument_name", "in", "model_fields", "and", "argument_value", "is", "not", "None", ")"...
Command arguments always include a lot of ones added by Django, that we don't want to use to determine properties of our model object, e.g.
[ "Command", "arguments", "always", "include", "a", "lot", "of", "ones", "added", "by", "Django", "that", "we", "don", "'", "t", "want", "to", "use", "to", "determine", "properties", "of", "our", "model", "object", "e", ".", "g", "." ]
[ "\"\"\"\n Command arguments always include a lot of ones added by Django, that we don't want to use to\n determine properties of our model object, e.g. `verbosity`, `settings`, `pythonpath` etc.\n This utility determines if we should use a command's input argument and pass its value to\n ...
[ { "param": "argument_name", "type": null }, { "param": "argument_value", "type": null }, { "param": "model_fields", "type": null }, { "param": "update_mode", "type": null } ]
{ "returns": [ { "docstring": "shall the argument and it's value be used", "docstring_tokens": [ "shall", "the", "argument", "and", "it", "'", "s", "value", "be", "used" ], "type": "bool" } ], "raises":...
33cdde54835d80c25340aad79782cff49dc69ded
Livit/Labster.OAuth2Client
oauth2_client/management/commands/oauth2_app_maker.py
[ "MIT" ]
Python
_validate
null
def _validate(model_type): """ Validate provided application model type. Args: model_type (type): e.g. oauth2_client.models.Application Returns: None: Raises: ValidationError: 1) when model type is wrong; 2) when not all required fields avai...
Validate provided application model type. Args: model_type (type): e.g. oauth2_client.models.Application Returns: None: Raises: ValidationError: 1) when model type is wrong; 2) when not all required fields available on the model type ...
Validate provided application model type. 1) when model type is wrong; 2) when not all required fields available on the model type
[ "Validate", "provided", "application", "model", "type", ".", "1", ")", "when", "model", "type", "is", "wrong", ";", "2", ")", "when", "not", "all", "required", "fields", "available", "on", "the", "model", "type" ]
def _validate(model_type): if not issubclass(model_type, models.Model): raise ValidationError('The model class must extend django.db.models.Model') app_fields = [field.name for field in model_type._meta.fields] required_fields = {'name', 'updated'} if any([required_field no...
[ "def", "_validate", "(", "model_type", ")", ":", "if", "not", "issubclass", "(", "model_type", ",", "models", ".", "Model", ")", ":", "raise", "ValidationError", "(", "'The model class must extend django.db.models.Model'", ")", "app_fields", "=", "[", "field", "."...
Validate provided application model type.
[ "Validate", "provided", "application", "model", "type", "." ]
[ "\"\"\"\n Validate provided application model type.\n\n Args:\n model_type (type): e.g. oauth2_client.models.Application\n\n Returns:\n None:\n\n Raises:\n ValidationError: 1) when model type is wrong; 2) when not all required fields available\n ...
[ { "param": "model_type", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "model_type", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33cdde54835d80c25340aad79782cff49dc69ded
Livit/Labster.OAuth2Client
oauth2_client/management/commands/oauth2_app_maker.py
[ "MIT" ]
Python
handle
null
def handle(self, *args, **options): """ Django hook to run the command. Dynamically extract all command's parameters related to the application, based on the model's type metadata. This works now and in the future, with any Application models. Run the logic, report errors if any,...
Django hook to run the command. Dynamically extract all command's parameters related to the application, based on the model's type metadata. This works now and in the future, with any Application models. Run the logic, report errors if any, re-raise so user gets a non-zero exit code if ...
Django hook to run the command. Dynamically extract all command's parameters related to the application, based on the model's type metadata. This works now and in the future, with any Application models. Run the logic, report errors if any, re-raise so user gets a non-zero exit code if execution fails.
[ "Django", "hook", "to", "run", "the", "command", ".", "Dynamically", "extract", "all", "command", "'", "s", "parameters", "related", "to", "the", "application", "based", "on", "the", "model", "'", "s", "type", "metadata", ".", "This", "works", "now", "and"...
def handle(self, *args, **options): app_model = self.app_model() self._validate(app_model) application_fields = [field.name for field in app_model._meta.fields] application_data = {} is_update = options.pop('update') for arg_name, arg_value in options.items(): ...
[ "def", "handle", "(", "self", ",", "*", "args", ",", "**", "options", ")", ":", "app_model", "=", "self", ".", "app_model", "(", ")", "self", ".", "_validate", "(", "app_model", ")", "application_fields", "=", "[", "field", ".", "name", "for", "field",...
Django hook to run the command.
[ "Django", "hook", "to", "run", "the", "command", "." ]
[ "\"\"\"\n Django hook to run the command.\n Dynamically extract all command's parameters related to the application, based on the model's\n type metadata. This works now and in the future, with any Application models. Run the logic,\n report errors if any, re-raise so user gets a non-zer...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
33cdde54835d80c25340aad79782cff49dc69ded
Livit/Labster.OAuth2Client
oauth2_client/management/commands/oauth2_app_maker.py
[ "MIT" ]
Python
_update
null
def _update(self, application_data): """ Updates an existing application, if model validation successful. Args: application_data (dict): key-values to update the App with Returns: None: Raises: ValidationError: 1) when app does not exist; 2...
Updates an existing application, if model validation successful. Args: application_data (dict): key-values to update the App with Returns: None: Raises: ValidationError: 1) when app does not exist; 2) when multiple apps exist with same name; ...
Updates an existing application, if model validation successful. Args: application_data (dict): key-values to update the App with 1) when app does not exist; 2) when multiple apps exist with same name; 3) when data constraints defined on the model violated
[ "Updates", "an", "existing", "application", "if", "model", "validation", "successful", ".", "Args", ":", "application_data", "(", "dict", ")", ":", "key", "-", "values", "to", "update", "the", "App", "with", "1", ")", "when", "app", "does", "not", "exist",...
def _update(self, application_data): app_name = application_data.pop('name') app_model = self.app_model() application_data['updated'] = timezone.now() try: app = app_model.objects.get(name=app_name) changed = False for key, target_val in application_da...
[ "def", "_update", "(", "self", ",", "application_data", ")", ":", "app_name", "=", "application_data", ".", "pop", "(", "'name'", ")", "app_model", "=", "self", ".", "app_model", "(", ")", "application_data", "[", "'updated'", "]", "=", "timezone", ".", "n...
Updates an existing application, if model validation successful.
[ "Updates", "an", "existing", "application", "if", "model", "validation", "successful", "." ]
[ "\"\"\"\n Updates an existing application, if model validation successful.\n\n Args:\n application_data (dict): key-values to update the App with\n\n Returns:\n None:\n\n Raises:\n ValidationError: 1) when app does not exist; 2) when multiple apps exist ...
[ { "param": "self", "type": null }, { "param": "application_data", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "application_data", "type": null, "docstring": null, "docstrin...
33cdde54835d80c25340aad79782cff49dc69ded
Livit/Labster.OAuth2Client
oauth2_client/management/commands/oauth2_app_maker.py
[ "MIT" ]
Python
_create
null
def _create(self, application_data): """ Create an application, if model validation successful. Enforce unique name, even when uniqueness not defined in the model. Args: application_data (dict): key-values for the new Application record Returns: None: ...
Create an application, if model validation successful. Enforce unique name, even when uniqueness not defined in the model. Args: application_data (dict): key-values for the new Application record Returns: None: Raises: ValidationError: 1) w...
Create an application, if model validation successful. Enforce unique name, even when uniqueness not defined in the model. application_data (dict): key-values for the new Application record 1) when app with this name already exist; 2) when data constraints defined on the model violated
[ "Create", "an", "application", "if", "model", "validation", "successful", ".", "Enforce", "unique", "name", "even", "when", "uniqueness", "not", "defined", "in", "the", "model", ".", "application_data", "(", "dict", ")", ":", "key", "-", "values", "for", "th...
def _create(self, application_data): app_model = self.app_model() target_application = app_model(**application_data) name_field = target_application._meta.get_field('name') if not name_field.unique: name_field.validators.append(self.validate_unique) if name_field.bl...
[ "def", "_create", "(", "self", ",", "application_data", ")", ":", "app_model", "=", "self", ".", "app_model", "(", ")", "target_application", "=", "app_model", "(", "**", "application_data", ")", "name_field", "=", "target_application", ".", "_meta", ".", "get...
Create an application, if model validation successful.
[ "Create", "an", "application", "if", "model", "validation", "successful", "." ]
[ "\"\"\"\n Create an application, if model validation successful. Enforce unique name, even when\n uniqueness not defined in the model.\n\n Args:\n application_data (dict): key-values for the new Application record\n\n Returns:\n None:\n\n Raises:\n ...
[ { "param": "self", "type": null }, { "param": "application_data", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "application_data", "type": null, "docstring": null, "docstrin...
33cdde54835d80c25340aad79782cff49dc69ded
Livit/Labster.OAuth2Client
oauth2_client/management/commands/oauth2_app_maker.py
[ "MIT" ]
Python
validate_unique
null
def validate_unique(self, name): """ Validate Application.name uniqueness, before creating. Used for models, that don't enforce that themselves. Raises: ValidationError: """ count = self.app_model().objects.filter(name=name).count() if count > 0: ...
Validate Application.name uniqueness, before creating. Used for models, that don't enforce that themselves. Raises: ValidationError:
Validate Application.name uniqueness, before creating. Used for models, that don't enforce that themselves.
[ "Validate", "Application", ".", "name", "uniqueness", "before", "creating", ".", "Used", "for", "models", "that", "don", "'", "t", "enforce", "that", "themselves", "." ]
def validate_unique(self, name): count = self.app_model().objects.filter(name=name).count() if count > 0: raise ValidationError( "Application already exists. Number of existing instances where name={}: {}. " "`name` field has to be unique and present.".format(...
[ "def", "validate_unique", "(", "self", ",", "name", ")", ":", "count", "=", "self", ".", "app_model", "(", ")", ".", "objects", ".", "filter", "(", "name", "=", "name", ")", ".", "count", "(", ")", "if", "count", ">", "0", ":", "raise", "Validation...
Validate Application.name uniqueness, before creating.
[ "Validate", "Application", ".", "name", "uniqueness", "before", "creating", "." ]
[ "\"\"\"\n Validate Application.name uniqueness, before creating. Used for models,\n that don't enforce that themselves.\n\n Raises:\n ValidationError:\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "name", "type": null } ]
{ "returns": [], "raises": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "ValidationError" } ], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optio...
66dca13bfba4815f397a1bd634b932a34ffadc8e
Livit/Labster.OAuth2Client
oauth2_client/fetcher.py
[ "MIT" ]
Python
fetch_token
<not_specific>
def fetch_token(app): """ Obtain a token from auth provider, using a fetcher specific to application's grant type. Args: app (oauth2_client.models.Application): app instance you need a token for Returns: oauth2_client.models.AccessToken: obtained token """ fetcher_grant_dispatc...
Obtain a token from auth provider, using a fetcher specific to application's grant type. Args: app (oauth2_client.models.Application): app instance you need a token for Returns: oauth2_client.models.AccessToken: obtained token
Obtain a token from auth provider, using a fetcher specific to application's grant type.
[ "Obtain", "a", "token", "from", "auth", "provider", "using", "a", "fetcher", "specific", "to", "application", "'", "s", "grant", "type", "." ]
def fetch_token(app): fetcher_grant_dispatcher = { Application.GRANT_CLIENT_CREDENTIALS: ClientCredentialsFetcher, Application.GRANT_JWT_BEARER: JWTFetcher, } fetcher = fetcher_grant_dispatcher[app.authorization_grant_type](app) return fetcher.fetch_token()
[ "def", "fetch_token", "(", "app", ")", ":", "fetcher_grant_dispatcher", "=", "{", "Application", ".", "GRANT_CLIENT_CREDENTIALS", ":", "ClientCredentialsFetcher", ",", "Application", ".", "GRANT_JWT_BEARER", ":", "JWTFetcher", ",", "}", "fetcher", "=", "fetcher_grant_...
Obtain a token from auth provider, using a fetcher specific to application's grant type.
[ "Obtain", "a", "token", "from", "auth", "provider", "using", "a", "fetcher", "specific", "to", "application", "'", "s", "grant", "type", "." ]
[ "\"\"\"\n Obtain a token from auth provider, using a fetcher specific to application's grant type.\n\n Args:\n app (oauth2_client.models.Application): app instance you need a token for\n\n Returns:\n oauth2_client.models.AccessToken: obtained token\n \"\"\"" ]
[ { "param": "app", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "oauth2_client.models.AccessToken" } ], "raises": [], "params": [ { "identifier": "app", "type": null, "docstring": "app instance you need a token for", "docstring_toke...
66dca13bfba4815f397a1bd634b932a34ffadc8e
Livit/Labster.OAuth2Client
oauth2_client/fetcher.py
[ "MIT" ]
Python
fetch_token
<not_specific>
def fetch_token(self): """ Top-level method, that runs the auth flow and returns the token. This is most likely what you are looking for. Returns: oauth2_client.models.AccessToken: """ raw_token = self.fetch_raw_token() return self.access_token_from_r...
Top-level method, that runs the auth flow and returns the token. This is most likely what you are looking for. Returns: oauth2_client.models.AccessToken:
Top-level method, that runs the auth flow and returns the token. This is most likely what you are looking for.
[ "Top", "-", "level", "method", "that", "runs", "the", "auth", "flow", "and", "returns", "the", "token", ".", "This", "is", "most", "likely", "what", "you", "are", "looking", "for", "." ]
def fetch_token(self): raw_token = self.fetch_raw_token() return self.access_token_from_raw_token(raw_token)
[ "def", "fetch_token", "(", "self", ")", ":", "raw_token", "=", "self", ".", "fetch_raw_token", "(", ")", "return", "self", ".", "access_token_from_raw_token", "(", "raw_token", ")" ]
Top-level method, that runs the auth flow and returns the token.
[ "Top", "-", "level", "method", "that", "runs", "the", "auth", "flow", "and", "returns", "the", "token", "." ]
[ "\"\"\"\n Top-level method, that runs the auth flow and returns the token. This is most likely\n what you are looking for.\n\n Returns:\n oauth2_client.models.AccessToken:\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "oauth2_client.models.AccessToken" } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null...
66dca13bfba4815f397a1bd634b932a34ffadc8e
Livit/Labster.OAuth2Client
oauth2_client/fetcher.py
[ "MIT" ]
Python
fetch_raw_token
null
def fetch_raw_token(self): """ Fetch a token from auth provider. Exact object type and available properties are provider specific. """ raise NotImplementedError('Subclasses of Fetcher must implement fetch_raw_token() method.')
Fetch a token from auth provider. Exact object type and available properties are provider specific.
Fetch a token from auth provider. Exact object type and available properties are provider specific.
[ "Fetch", "a", "token", "from", "auth", "provider", ".", "Exact", "object", "type", "and", "available", "properties", "are", "provider", "specific", "." ]
def fetch_raw_token(self): raise NotImplementedError('Subclasses of Fetcher must implement fetch_raw_token() method.')
[ "def", "fetch_raw_token", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'Subclasses of Fetcher must implement fetch_raw_token() method.'", ")" ]
Fetch a token from auth provider.
[ "Fetch", "a", "token", "from", "auth", "provider", "." ]
[ "\"\"\"\n Fetch a token from auth provider. Exact object type and available properties are\n provider specific.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
66dca13bfba4815f397a1bd634b932a34ffadc8e
Livit/Labster.OAuth2Client
oauth2_client/fetcher.py
[ "MIT" ]
Python
requested_scope
<not_specific>
def requested_scope(self): """ Get the scope to be requested from the provider in the auth flow. """ scope = self.app.scope return scope.split() if scope else []
Get the scope to be requested from the provider in the auth flow.
Get the scope to be requested from the provider in the auth flow.
[ "Get", "the", "scope", "to", "be", "requested", "from", "the", "provider", "in", "the", "auth", "flow", "." ]
def requested_scope(self): scope = self.app.scope return scope.split() if scope else []
[ "def", "requested_scope", "(", "self", ")", ":", "scope", "=", "self", ".", "app", ".", "scope", "return", "scope", ".", "split", "(", ")", "if", "scope", "else", "[", "]" ]
Get the scope to be requested from the provider in the auth flow.
[ "Get", "the", "scope", "to", "be", "requested", "from", "the", "provider", "in", "the", "auth", "flow", "." ]
[ "\"\"\"\n Get the scope to be requested from the provider in the auth flow.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
66dca13bfba4815f397a1bd634b932a34ffadc8e
Livit/Labster.OAuth2Client
oauth2_client/fetcher.py
[ "MIT" ]
Python
received_scope
<not_specific>
def received_scope(self, token, default=""): """ Extract scope granted by the provider from the token. The RFC isn't strict about the scope, so aren't we. Reference: > The authorization server MAY fully or partially ignore the scope > requested by the client, bas...
Extract scope granted by the provider from the token. The RFC isn't strict about the scope, so aren't we. Reference: > The authorization server MAY fully or partially ignore the scope > requested by the client, based on the authorization server policy or > t...
Extract scope granted by the provider from the token. The RFC isn't strict about the scope, so aren't we. > The authorization server MAY fully or partially ignore the scope > requested by the client, based on the authorization server policy or > the resource owner's instructions. If the issued access token scope > is...
[ "Extract", "scope", "granted", "by", "the", "provider", "from", "the", "token", ".", "The", "RFC", "isn", "'", "t", "strict", "about", "the", "scope", "so", "aren", "'", "t", "we", ".", ">", "The", "authorization", "server", "MAY", "fully", "or", "part...
def received_scope(self, token, default=""): received = getattr(token, "scope", None) if received is None: received = token.get('scope', default) requested_list = self.requested_scope() requested_set = set(requested_list) received_set = set(received.split()) i...
[ "def", "received_scope", "(", "self", ",", "token", ",", "default", "=", "\"\"", ")", ":", "received", "=", "getattr", "(", "token", ",", "\"scope\"", ",", "None", ")", "if", "received", "is", "None", ":", "received", "=", "token", ".", "get", "(", "...
Extract scope granted by the provider from the token.
[ "Extract", "scope", "granted", "by", "the", "provider", "from", "the", "token", "." ]
[ "\"\"\"\n Extract scope granted by the provider from the token. The RFC isn't\n strict about the scope, so aren't we.\n\n Reference:\n > The authorization server MAY fully or partially ignore the scope\n > requested by the client, based on the authorization server policy o...
[ { "param": "self", "type": null }, { "param": "token", "type": null }, { "param": "default", "type": null } ]
{ "returns": [ { "docstring": "scope as one string or default", "docstring_tokens": [ "scope", "as", "one", "string", "or", "default" ], "type": "str" } ], "raises": [], "params": [ { "identifier": "self", "type": nu...
66dca13bfba4815f397a1bd634b932a34ffadc8e
Livit/Labster.OAuth2Client
oauth2_client/fetcher.py
[ "MIT" ]
Python
fetch_raw_token
<not_specific>
def fetch_raw_token(self): """ Fetch token using JWT Bearer flow. Returns: dict: raw token from provider Raises: ValidationError: if the Application object we are fetching token for doesn't provide all required input data RequestExcep...
Fetch token using JWT Bearer flow. Returns: dict: raw token from provider Raises: ValidationError: if the Application object we are fetching token for doesn't provide all required input data RequestException: from `requests` library ...
Fetch token using JWT Bearer flow.
[ "Fetch", "token", "using", "JWT", "Bearer", "flow", "." ]
def fetch_raw_token(self): self.app.validate_jwt_grant_data() payload = self.auth_payload() response = requests.post(self.app.token_uri, data=payload) data = json.loads(response.text) return data
[ "def", "fetch_raw_token", "(", "self", ")", ":", "self", ".", "app", ".", "validate_jwt_grant_data", "(", ")", "payload", "=", "self", ".", "auth_payload", "(", ")", "response", "=", "requests", ".", "post", "(", "self", ".", "app", ".", "token_uri", ","...
Fetch token using JWT Bearer flow.
[ "Fetch", "token", "using", "JWT", "Bearer", "flow", "." ]
[ "\"\"\"\n Fetch token using JWT Bearer flow.\n\n Returns:\n dict: raw token from provider\n\n Raises:\n ValidationError: if the Application object we are fetching token\n for doesn't provide all required input data\n RequestException: from `reques...
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": "raw token from provider", "docstring_tokens": [ "raw", "token", "from", "provider" ], "type": "dict" } ], "raises": [ { "docstring": "if the Application object we are fetching token\nfor doesn't provide all re...
66dca13bfba4815f397a1bd634b932a34ffadc8e
Livit/Labster.OAuth2Client
oauth2_client/fetcher.py
[ "MIT" ]
Python
auth_payload
<not_specific>
def auth_payload(self): """ Prepare authorization request payload according to RFC 7523. Generated claim has to be signed using RSA with SHA256. Application's X509 certificate's key is used as the signing key. Key's location is specified in `Application.client_secret` and has ...
Prepare authorization request payload according to RFC 7523. Generated claim has to be signed using RSA with SHA256. Application's X509 certificate's key is used as the signing key. Key's location is specified in `Application.client_secret` and has to be available for reading on...
Prepare authorization request payload according to RFC 7523. Generated claim has to be signed using RSA with SHA256. Application's X509 certificate's key is used as the signing key. Key's location is specified in `Application.client_secret` and has to be available for reading on the server machine.
[ "Prepare", "authorization", "request", "payload", "according", "to", "RFC", "7523", ".", "Generated", "claim", "has", "to", "be", "signed", "using", "RSA", "with", "SHA256", ".", "Application", "'", "s", "X509", "certificate", "'", "s", "key", "is", "used", ...
def auth_payload(self): claim = self.jwt_claim() claim_signature = sign_rs256(claim.encode(), self.app.client_secret) claim_signature = urlsafe_b64encode(claim_signature).decode() auth_payload = { "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "asser...
[ "def", "auth_payload", "(", "self", ")", ":", "claim", "=", "self", ".", "jwt_claim", "(", ")", "claim_signature", "=", "sign_rs256", "(", "claim", ".", "encode", "(", ")", ",", "self", ".", "app", ".", "client_secret", ")", "claim_signature", "=", "urls...
Prepare authorization request payload according to RFC 7523.
[ "Prepare", "authorization", "request", "payload", "according", "to", "RFC", "7523", "." ]
[ "\"\"\"\n Prepare authorization request payload according to RFC 7523.\n Generated claim has to be signed using RSA with SHA256.\n Application's X509 certificate's key is used as the signing key.\n Key's location is specified in `Application.client_secret` and has\n to be availabl...
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": "payload as a dict", "docstring_tokens": [ "payload", "as", "a", "dict" ], "type": "dict" } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_t...
66dca13bfba4815f397a1bd634b932a34ffadc8e
Livit/Labster.OAuth2Client
oauth2_client/fetcher.py
[ "MIT" ]
Python
jwt_claim
<not_specific>
def jwt_claim(self, expiration_s=150): """ Build a JWT claim used to obtain token from auth provider. Logic and naming explained here: https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.html https://tools.ietf.org/html/rfc7523 Args: expira...
Build a JWT claim used to obtain token from auth provider. Logic and naming explained here: https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.html https://tools.ietf.org/html/rfc7523 Args: expiration_s (int): value for `exp` claim field. Per RFC...
Build a JWT claim used to obtain token from auth provider.
[ "Build", "a", "JWT", "claim", "used", "to", "obtain", "token", "from", "auth", "provider", "." ]
def jwt_claim(self, expiration_s=150): claim = urlsafe_b64encode('{"alg":"RS256"}'.encode()).decode() claim += "." expiration_ts = int(datetime_to_float(timezone.now() + timedelta(seconds=expiration_s))) claim_template = '{{"iss": "{iss}", "sub": "{sub}", "aud": "{aud}", "exp": {exp}}}' ...
[ "def", "jwt_claim", "(", "self", ",", "expiration_s", "=", "150", ")", ":", "claim", "=", "urlsafe_b64encode", "(", "'{\"alg\":\"RS256\"}'", ".", "encode", "(", ")", ")", ".", "decode", "(", ")", "claim", "+=", "\".\"", "expiration_ts", "=", "int", "(", ...
Build a JWT claim used to obtain token from auth provider.
[ "Build", "a", "JWT", "claim", "used", "to", "obtain", "token", "from", "auth", "provider", "." ]
[ "\"\"\"\n Build a JWT claim used to obtain token from auth provider.\n Logic and naming explained here:\n https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.html\n https://tools.ietf.org/html/rfc7523\n\n Args:\n expiration_s (int): value for `exp` cl...
[ { "param": "self", "type": null }, { "param": "expiration_s", "type": null } ]
{ "returns": [ { "docstring": "claim as base64 string", "docstring_tokens": [ "claim", "as", "base64", "string" ], "type": "str" } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "do...