hexsha
stringlengths
40
40
repo
stringlengths
5
121
path
stringlengths
4
227
license
sequence
language
stringclasses
1 value
identifier
stringlengths
1
107
return_type
stringlengths
2
237
original_string
stringlengths
75
13.4k
original_docstring
stringlengths
13
12.9k
docstring
stringlengths
13
2.57k
docstring_tokens
sequence
code
stringlengths
23
1.88k
code_tokens
sequence
short_docstring
stringlengths
1
1.32k
short_docstring_tokens
sequence
comment
sequence
parameters
list
docstring_params
dict
code_with_imports
stringlengths
23
1.88k
idxs
int64
0
611k
cluster
int64
0
1.02k
ce17ce335b1bc87e29cb03054c19176ad1b6803a
wedataintelligence/vivaldi-source
chromium/third_party/WebKit/Source/bindings/scripts/v8_utilities.py
[ "BSD-3-Clause" ]
Python
on_interface
<not_specific>
def on_interface(interface, member): """Returns True if the interface's member needs to be defined on the interface object. The following members must be defiend on an interface object. - static members """ if member.is_static: return True return False
Returns True if the interface's member needs to be defined on the interface object. The following members must be defiend on an interface object. - static members
Returns True if the interface's member needs to be defined on the interface object. The following members must be defiend on an interface object. static members
[ "Returns", "True", "if", "the", "interface", "'", "s", "member", "needs", "to", "be", "defined", "on", "the", "interface", "object", ".", "The", "following", "members", "must", "be", "defiend", "on", "an", "interface", "object", ".", "static", "members" ]
def on_interface(interface, member): if member.is_static: return True return False
[ "def", "on_interface", "(", "interface", ",", "member", ")", ":", "if", "member", ".", "is_static", ":", "return", "True", "return", "False" ]
Returns True if the interface's member needs to be defined on the interface object.
[ "Returns", "True", "if", "the", "interface", "'", "s", "member", "needs", "to", "be", "defined", "on", "the", "interface", "object", "." ]
[ "\"\"\"Returns True if the interface's member needs to be defined on the\n interface object.\n\n The following members must be defiend on an interface object.\n - static members\n \"\"\"" ]
[ { "param": "interface", "type": null }, { "param": "member", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "interface", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "member", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def on_interface(interface, member): if member.is_static: return True return False
609,851
71
f7ca4218c4f7dd1e1763cabdb41ba272024dce54
OGalOz/poolcount
lib/poct/MultiCodes.py
[ "MIT" ]
Python
IndexFileOrInameToPrefixInfo
<not_specific>
def IndexFileOrInameToPrefixInfo(inp_d): """ There are two options: Either an index file path to get index information, or an index name, in which case prefix is a list with length 1 Args: inp_d: (dict) [indexfile_fp] (str) OR index_name: (str) """ # Report String doesn't exist yet if "index_name" in inp_d: logging.info("Recognized index type as index name") # nLeading (int), Some sequence (str), index_name (str) prefix = [[0, "", inp_d['index_name']]] prefixNames = [inp_d['index_name']] else: raise Exception("Program only works with index_names now," " index file deprecated.") #updating inp_d inp_d['prefix'] = prefix inp_d['prefixNames'] = prefixNames return inp_d
There are two options: Either an index file path to get index information, or an index name, in which case prefix is a list with length 1 Args: inp_d: (dict) [indexfile_fp] (str) OR index_name: (str)
There are two options: Either an index file path to get index information, or an index name, in which case prefix is a list with length 1
[ "There", "are", "two", "options", ":", "Either", "an", "index", "file", "path", "to", "get", "index", "information", "or", "an", "index", "name", "in", "which", "case", "prefix", "is", "a", "list", "with", "length", "1" ]
def IndexFileOrInameToPrefixInfo(inp_d): if "index_name" in inp_d: logging.info("Recognized index type as index name") prefix = [[0, "", inp_d['index_name']]] prefixNames = [inp_d['index_name']] else: raise Exception("Program only works with index_names now," " index file deprecated.") inp_d['prefix'] = prefix inp_d['prefixNames'] = prefixNames return inp_d
[ "def", "IndexFileOrInameToPrefixInfo", "(", "inp_d", ")", ":", "if", "\"index_name\"", "in", "inp_d", ":", "logging", ".", "info", "(", "\"Recognized index type as index name\"", ")", "prefix", "=", "[", "[", "0", ",", "\"\"", ",", "inp_d", "[", "'index_name'", "]", "]", "]", "prefixNames", "=", "[", "inp_d", "[", "'index_name'", "]", "]", "else", ":", "raise", "Exception", "(", "\"Program only works with index_names now,\"", "\" index file deprecated.\"", ")", "inp_d", "[", "'prefix'", "]", "=", "prefix", "inp_d", "[", "'prefixNames'", "]", "=", "prefixNames", "return", "inp_d" ]
There are two options: Either an index file path to get index information, or an index name, in which case prefix is a list with length 1
[ "There", "are", "two", "options", ":", "Either", "an", "index", "file", "path", "to", "get", "index", "information", "or", "an", "index", "name", "in", "which", "case", "prefix", "is", "a", "list", "with", "length", "1" ]
[ "\"\"\"\n There are two options: Either an index file path to get index information,\n or an index name, in which case prefix is a list with length 1 \n Args:\n inp_d: (dict)\n [indexfile_fp] (str)\n\n OR\n\n index_name: (str)\n\n \"\"\"", "# Report String doesn't exist yet", "# nLeading (int), Some sequence (str), index_name (str)", "#updating inp_d" ]
[ { "param": "inp_d", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "inp_d", "type": null, "docstring": "(dict)\n[indexfile_fp] (str)\n\nOR\n\n(str)", "docstring_tokens": [ "(", "dict", ")", "[", "indexfile_fp", "]", "(", "str", ")", "OR", "(", "str", ")" ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import logging def IndexFileOrInameToPrefixInfo(inp_d): if "index_name" in inp_d: logging.info("Recognized index type as index name") prefix = [[0, "", inp_d['index_name']]] prefixNames = [inp_d['index_name']] else: raise Exception("Program only works with index_names now," " index file deprecated.") inp_d['prefix'] = prefix inp_d['prefixNames'] = prefixNames return inp_d
609,852
142
4021402f32354c3b42c14b1e813d6fc5aad596d8
TrueMyst/stripend
stripend/stripend.py
[ "MIT" ]
Python
string_is_empty
<not_specific>
def string_is_empty(string: str): """Checks to see whether the string is empty. Parameters ---------- string : str The string that needs to be checked. Returns ------- is_empty : str Checks the length of the string and Returns `True` if the string is empty, else `False`. """ is_empty = bool(len(string) <= 0) return is_empty
Checks to see whether the string is empty. Parameters ---------- string : str The string that needs to be checked. Returns ------- is_empty : str Checks the length of the string and Returns `True` if the string is empty, else `False`.
Checks to see whether the string is empty.
[ "Checks", "to", "see", "whether", "the", "string", "is", "empty", "." ]
def string_is_empty(string: str): is_empty = bool(len(string) <= 0) return is_empty
[ "def", "string_is_empty", "(", "string", ":", "str", ")", ":", "is_empty", "=", "bool", "(", "len", "(", "string", ")", "<=", "0", ")", "return", "is_empty" ]
Checks to see whether the string is empty.
[ "Checks", "to", "see", "whether", "the", "string", "is", "empty", "." ]
[ "\"\"\"Checks to see whether the string is empty.\r\n\r\n Parameters\r\n ----------\r\n string : str\r\n The string that needs to be checked.\r\n\r\n Returns\r\n -------\r\n is_empty : str\r\n Checks the length of the string and\r\n Returns `True` if the string is empty, else `False`.\r\n \"\"\"" ]
[ { "param": "string", "type": "str" } ]
{ "returns": [ { "docstring": "Checks the length of the string and\nReturns `True` if the string is empty, else `False`.", "docstring_tokens": [ "Checks", "the", "length", "of", "the", "string", "and", "Returns", "`", "True", "`", "if", "the", "string", "is", "empty", "else", "`", "False", "`", "." ], "type": "str\r" } ], "raises": [], "params": [ { "identifier": "string", "type": "str", "docstring": "The string that needs to be checked.", "docstring_tokens": [ "The", "string", "that", "needs", "to", "be", "checked", "." ], "default": null, "is_optional": false } ], "outlier_params": [], "others": [] }
def string_is_empty(string: str): is_empty = bool(len(string) <= 0) return is_empty
609,853
384
2c4afca7480bfa553ee11c46f53e315b02fb400d
remiomosowon/or-tools
ortools/constraint_solver/samples/cvrp.py
[ "Apache-2.0" ]
Python
create_demand_evaluator
<not_specific>
def create_demand_evaluator(data): """Creates callback to get demands at each location.""" _demands = data['demands'] def demand_evaluator(manager, node): """Returns the demand of the current node""" return _demands[manager.IndexToNode(node)] return demand_evaluator
Creates callback to get demands at each location.
Creates callback to get demands at each location.
[ "Creates", "callback", "to", "get", "demands", "at", "each", "location", "." ]
def create_demand_evaluator(data): _demands = data['demands'] def demand_evaluator(manager, node): return _demands[manager.IndexToNode(node)] return demand_evaluator
[ "def", "create_demand_evaluator", "(", "data", ")", ":", "_demands", "=", "data", "[", "'demands'", "]", "def", "demand_evaluator", "(", "manager", ",", "node", ")", ":", "\"\"\"Returns the demand of the current node\"\"\"", "return", "_demands", "[", "manager", ".", "IndexToNode", "(", "node", ")", "]", "return", "demand_evaluator" ]
Creates callback to get demands at each location.
[ "Creates", "callback", "to", "get", "demands", "at", "each", "location", "." ]
[ "\"\"\"Creates callback to get demands at each location.\"\"\"", "\"\"\"Returns the demand of the current node\"\"\"" ]
[ { "param": "data", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "data", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def create_demand_evaluator(data): _demands = data['demands'] def demand_evaluator(manager, node): return _demands[manager.IndexToNode(node)] return demand_evaluator
609,854
729
363a1c43aa87b5be77bf0f3561547c05f71c1cfe
jpolton/anyTide
NOCtidepred.py
[ "MIT" ]
Python
date2mjd
<not_specific>
def date2mjd(dates): """ Convert datetime into Modified Julian Date (float) This is a float data reference to 2000-01-01T00:00:00 which has a mjd of 51544 INPUT: datetime array OUTPUT: mjd array """ mjd = [ (d - datetime.datetime(2000,1,1)).days \ + (d - datetime.datetime(2000,1,1)).seconds/86400. + 51544 for d in dates] return mjd
Convert datetime into Modified Julian Date (float) This is a float data reference to 2000-01-01T00:00:00 which has a mjd of 51544 INPUT: datetime array OUTPUT: mjd array
Convert datetime into Modified Julian Date (float) This is a float data reference to 2000-01-01T00:00:00 which has a mjd of 51544 INPUT: datetime array OUTPUT: mjd array
[ "Convert", "datetime", "into", "Modified", "Julian", "Date", "(", "float", ")", "This", "is", "a", "float", "data", "reference", "to", "2000", "-", "01", "-", "01T00", ":", "00", ":", "00", "which", "has", "a", "mjd", "of", "51544", "INPUT", ":", "datetime", "array", "OUTPUT", ":", "mjd", "array" ]
def date2mjd(dates): mjd = [ (d - datetime.datetime(2000,1,1)).days \ + (d - datetime.datetime(2000,1,1)).seconds/86400. + 51544 for d in dates] return mjd
[ "def", "date2mjd", "(", "dates", ")", ":", "mjd", "=", "[", "(", "d", "-", "datetime", ".", "datetime", "(", "2000", ",", "1", ",", "1", ")", ")", ".", "days", "+", "(", "d", "-", "datetime", ".", "datetime", "(", "2000", ",", "1", ",", "1", ")", ")", ".", "seconds", "/", "86400.", "+", "51544", "for", "d", "in", "dates", "]", "return", "mjd" ]
Convert datetime into Modified Julian Date (float) This is a float data reference to 2000-01-01T00:00:00 which has a mjd of 51544 INPUT: datetime array OUTPUT: mjd array
[ "Convert", "datetime", "into", "Modified", "Julian", "Date", "(", "float", ")", "This", "is", "a", "float", "data", "reference", "to", "2000", "-", "01", "-", "01T00", ":", "00", ":", "00", "which", "has", "a", "mjd", "of", "51544", "INPUT", ":", "datetime", "array", "OUTPUT", ":", "mjd", "array" ]
[ "\"\"\"\n Convert datetime into Modified Julian Date (float)\n\n This is a float data reference to 2000-01-01T00:00:00 which has a mjd of 51544\n INPUT: datetime array\n OUTPUT: mjd array\n \"\"\"" ]
[ { "param": "dates", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "dates", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import datetime def date2mjd(dates): mjd = [ (d - datetime.datetime(2000,1,1)).days \ + (d - datetime.datetime(2000,1,1)).seconds/86400. + 51544 for d in dates] return mjd
609,855
488
dbfb7ae4dd117d13fda7ca809c657122754c571f
crimsonreaper/Project_PSIT61
MostPassenger.py
[ "MIT" ]
Python
fetch_data_2013
<not_specific>
def fetch_data_2013(): """For import data year 2013 from excel""" static = open("airtraffic.csv", newline="") data = csv.reader(static) static = [run for run in data] static_2013 = [] for run in static: if run[3] == "2013": static_2013.append(run) return static_2013
For import data year 2013 from excel
For import data year 2013 from excel
[ "For", "import", "data", "year", "2013", "from", "excel" ]
def fetch_data_2013(): static = open("airtraffic.csv", newline="") data = csv.reader(static) static = [run for run in data] static_2013 = [] for run in static: if run[3] == "2013": static_2013.append(run) return static_2013
[ "def", "fetch_data_2013", "(", ")", ":", "static", "=", "open", "(", "\"airtraffic.csv\"", ",", "newline", "=", "\"\"", ")", "data", "=", "csv", ".", "reader", "(", "static", ")", "static", "=", "[", "run", "for", "run", "in", "data", "]", "static_2013", "=", "[", "]", "for", "run", "in", "static", ":", "if", "run", "[", "3", "]", "==", "\"2013\"", ":", "static_2013", ".", "append", "(", "run", ")", "return", "static_2013" ]
For import data year 2013 from excel
[ "For", "import", "data", "year", "2013", "from", "excel" ]
[ "\"\"\"For import data year 2013 from excel\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
import csv def fetch_data_2013(): static = open("airtraffic.csv", newline="") data = csv.reader(static) static = [run for run in data] static_2013 = [] for run in static: if run[3] == "2013": static_2013.append(run) return static_2013
609,856
367
a5ffa1c2977ab32fb1eae1c4fe1784d0534da8d0
adriannaRodencal/Journey
toolbox.py
[ "MIT" ]
Python
is_number
<not_specific>
def is_number(testValue): """Returns True if testValue is an number and False otherwise.""" isNumber = True charactersDone = 0 currentCharacter = 0 positiveNegative = 0 decimal = 0 testValueString = str(testValue) testValueString = testValueString.strip() totalCharacters = len(testValueString) if totalCharacters == 0: isInteger = False while charactersDone < totalCharacters: if testValueString[currentCharacter] not in '-+0123456789. ': isNumber = False if testValueString[currentCharacter] in [' ', '-', '+', '.'] and totalCharacters == 1: isNumber = False if testValueString[currentCharacter] in ['-', '+'] and currentCharacter != 0: isNumber = False if testValueString[currentCharacter] in ['-', '+']: positiveNegative = positiveNegative + 1 if testValueString[currentCharacter] in ['.']: decimal = decimal + 1 if positiveNegative > 1 or decimal > 1: isNumber = False currentCharacter = currentCharacter + 1 charactersDone = charactersDone + 1 return isNumber
Returns True if testValue is an number and False otherwise.
Returns True if testValue is an number and False otherwise.
[ "Returns", "True", "if", "testValue", "is", "an", "number", "and", "False", "otherwise", "." ]
def is_number(testValue): isNumber = True charactersDone = 0 currentCharacter = 0 positiveNegative = 0 decimal = 0 testValueString = str(testValue) testValueString = testValueString.strip() totalCharacters = len(testValueString) if totalCharacters == 0: isInteger = False while charactersDone < totalCharacters: if testValueString[currentCharacter] not in '-+0123456789. ': isNumber = False if testValueString[currentCharacter] in [' ', '-', '+', '.'] and totalCharacters == 1: isNumber = False if testValueString[currentCharacter] in ['-', '+'] and currentCharacter != 0: isNumber = False if testValueString[currentCharacter] in ['-', '+']: positiveNegative = positiveNegative + 1 if testValueString[currentCharacter] in ['.']: decimal = decimal + 1 if positiveNegative > 1 or decimal > 1: isNumber = False currentCharacter = currentCharacter + 1 charactersDone = charactersDone + 1 return isNumber
[ "def", "is_number", "(", "testValue", ")", ":", "isNumber", "=", "True", "charactersDone", "=", "0", "currentCharacter", "=", "0", "positiveNegative", "=", "0", "decimal", "=", "0", "testValueString", "=", "str", "(", "testValue", ")", "testValueString", "=", "testValueString", ".", "strip", "(", ")", "totalCharacters", "=", "len", "(", "testValueString", ")", "if", "totalCharacters", "==", "0", ":", "isInteger", "=", "False", "while", "charactersDone", "<", "totalCharacters", ":", "if", "testValueString", "[", "currentCharacter", "]", "not", "in", "'-+0123456789. '", ":", "isNumber", "=", "False", "if", "testValueString", "[", "currentCharacter", "]", "in", "[", "' '", ",", "'-'", ",", "'+'", ",", "'.'", "]", "and", "totalCharacters", "==", "1", ":", "isNumber", "=", "False", "if", "testValueString", "[", "currentCharacter", "]", "in", "[", "'-'", ",", "'+'", "]", "and", "currentCharacter", "!=", "0", ":", "isNumber", "=", "False", "if", "testValueString", "[", "currentCharacter", "]", "in", "[", "'-'", ",", "'+'", "]", ":", "positiveNegative", "=", "positiveNegative", "+", "1", "if", "testValueString", "[", "currentCharacter", "]", "in", "[", "'.'", "]", ":", "decimal", "=", "decimal", "+", "1", "if", "positiveNegative", ">", "1", "or", "decimal", ">", "1", ":", "isNumber", "=", "False", "currentCharacter", "=", "currentCharacter", "+", "1", "charactersDone", "=", "charactersDone", "+", "1", "return", "isNumber" ]
Returns True if testValue is an number and False otherwise.
[ "Returns", "True", "if", "testValue", "is", "an", "number", "and", "False", "otherwise", "." ]
[ "\"\"\"Returns True if testValue is an number and False otherwise.\"\"\"" ]
[ { "param": "testValue", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "testValue", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def is_number(testValue): isNumber = True charactersDone = 0 currentCharacter = 0 positiveNegative = 0 decimal = 0 testValueString = str(testValue) testValueString = testValueString.strip() totalCharacters = len(testValueString) if totalCharacters == 0: isInteger = False while charactersDone < totalCharacters: if testValueString[currentCharacter] not in '-+0123456789. ': isNumber = False if testValueString[currentCharacter] in [' ', '-', '+', '.'] and totalCharacters == 1: isNumber = False if testValueString[currentCharacter] in ['-', '+'] and currentCharacter != 0: isNumber = False if testValueString[currentCharacter] in ['-', '+']: positiveNegative = positiveNegative + 1 if testValueString[currentCharacter] in ['.']: decimal = decimal + 1 if positiveNegative > 1 or decimal > 1: isNumber = False currentCharacter = currentCharacter + 1 charactersDone = charactersDone + 1 return isNumber
609,857
997
1ee220df4b8e1b4fc6e56633f04ba5884a4dd0e5
DonalChilde/Pfm-Util
src/pfmsoft/util/string/str_util.py
[ "MIT" ]
Python
strip_end
str
def strip_end(text: str, suffix: str, case_insensitive: bool = False) -> str: """Strips the suffix from a string if present. https://stackoverflow.com/a/1038999 :param text: String to check for suffix :param suffix: Suffix to look for. :param case_insensitive: Do a case insensitive match. Defaults to False. :returns: The resulting string. """ if case_insensitive: if not text.lower().endswith(suffix.lower()): return text else: if not text.endswith(suffix): return text return text[: len(text) - len(suffix)]
Strips the suffix from a string if present. https://stackoverflow.com/a/1038999 :param text: String to check for suffix :param suffix: Suffix to look for. :param case_insensitive: Do a case insensitive match. Defaults to False. :returns: The resulting string.
Strips the suffix from a string if present.
[ "Strips", "the", "suffix", "from", "a", "string", "if", "present", "." ]
def strip_end(text: str, suffix: str, case_insensitive: bool = False) -> str: if case_insensitive: if not text.lower().endswith(suffix.lower()): return text else: if not text.endswith(suffix): return text return text[: len(text) - len(suffix)]
[ "def", "strip_end", "(", "text", ":", "str", ",", "suffix", ":", "str", ",", "case_insensitive", ":", "bool", "=", "False", ")", "->", "str", ":", "if", "case_insensitive", ":", "if", "not", "text", ".", "lower", "(", ")", ".", "endswith", "(", "suffix", ".", "lower", "(", ")", ")", ":", "return", "text", "else", ":", "if", "not", "text", ".", "endswith", "(", "suffix", ")", ":", "return", "text", "return", "text", "[", ":", "len", "(", "text", ")", "-", "len", "(", "suffix", ")", "]" ]
Strips the suffix from a string if present.
[ "Strips", "the", "suffix", "from", "a", "string", "if", "present", "." ]
[ "\"\"\"Strips the suffix from a string if present.\n\n https://stackoverflow.com/a/1038999\n\n :param text: String to check for suffix\n :param suffix: Suffix to look for.\n :param case_insensitive: Do a case insensitive match. Defaults to False.\n :returns: The resulting string.\n \"\"\"" ]
[ { "param": "text", "type": "str" }, { "param": "suffix", "type": "str" }, { "param": "case_insensitive", "type": "bool" } ]
{ "returns": [ { "docstring": "The resulting string.", "docstring_tokens": [ "The", "resulting", "string", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "text", "type": "str", "docstring": "String to check for suffix", "docstring_tokens": [ "String", "to", "check", "for", "suffix" ], "default": null, "is_optional": null }, { "identifier": "suffix", "type": "str", "docstring": "Suffix to look for.", "docstring_tokens": [ "Suffix", "to", "look", "for", "." ], "default": null, "is_optional": null }, { "identifier": "case_insensitive", "type": "bool", "docstring": "Do a case insensitive match. Defaults to False.", "docstring_tokens": [ "Do", "a", "case", "insensitive", "match", ".", "Defaults", "to", "False", "." ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def strip_end(text: str, suffix: str, case_insensitive: bool = False) -> str: if case_insensitive: if not text.lower().endswith(suffix.lower()): return text else: if not text.endswith(suffix): return text return text[: len(text) - len(suffix)]
609,858
978
abfe6556d89f64f790fce13e93dbfc09d170fd72
sloria/scrapi
scrapi/base/helpers.py
[ "Apache-2.0" ]
Python
extract_and_replace_one
<not_specific>
def extract_and_replace_one(text, pattern): ''' Works with regexes with two matches, where the text of the first match is replaced and the text of the second is returned In the case where there is a match: >>> text = 'I feelvery happy' >>> pattern = re.compile(r'.*(very\s*(\S*)).*') >>> modified_text, match = extract_and_replace_one(text, pattern) >>> print(modified_text) I feel >>> print(match) happy In the case where there is not a match: >>> text = 'I feel happy' >>> modified_text, match = extract_and_replace_one(text, pattern) >>> modified_text == text True >>> match is None True ''' matches = pattern.findall(text) if matches and len(matches) == 1: return text.replace(matches[0][0], ''), matches[0][1] return text, None
Works with regexes with two matches, where the text of the first match is replaced and the text of the second is returned In the case where there is a match: >>> text = 'I feelvery happy' >>> pattern = re.compile(r'.*(very\s*(\S*)).*') >>> modified_text, match = extract_and_replace_one(text, pattern) >>> print(modified_text) I feel >>> print(match) happy In the case where there is not a match: >>> text = 'I feel happy' >>> modified_text, match = extract_and_replace_one(text, pattern) >>> modified_text == text True >>> match is None True
Works with regexes with two matches, where the text of the first match is replaced and the text of the second is returned
[ "Works", "with", "regexes", "with", "two", "matches", "where", "the", "text", "of", "the", "first", "match", "is", "replaced", "and", "the", "text", "of", "the", "second", "is", "returned" ]
def extract_and_replace_one(text, pattern): matches = pattern.findall(text) if matches and len(matches) == 1: return text.replace(matches[0][0], ''), matches[0][1] return text, None
[ "def", "extract_and_replace_one", "(", "text", ",", "pattern", ")", ":", "matches", "=", "pattern", ".", "findall", "(", "text", ")", "if", "matches", "and", "len", "(", "matches", ")", "==", "1", ":", "return", "text", ".", "replace", "(", "matches", "[", "0", "]", "[", "0", "]", ",", "''", ")", ",", "matches", "[", "0", "]", "[", "1", "]", "return", "text", ",", "None" ]
Works with regexes with two matches, where the text of the first match is replaced and the text of the second is returned
[ "Works", "with", "regexes", "with", "two", "matches", "where", "the", "text", "of", "the", "first", "match", "is", "replaced", "and", "the", "text", "of", "the", "second", "is", "returned" ]
[ "''' Works with regexes with two matches, where the text of the first match\n is replaced and the text of the second is returned\n\n In the case where there is a match:\n >>> text = 'I feelvery happy'\n >>> pattern = re.compile(r'.*(very\\s*(\\S*)).*')\n >>> modified_text, match = extract_and_replace_one(text, pattern)\n >>> print(modified_text)\n I feel\n >>> print(match)\n happy\n\n In the case where there is not a match:\n >>> text = 'I feel happy'\n >>> modified_text, match = extract_and_replace_one(text, pattern)\n >>> modified_text == text\n True\n >>> match is None\n True\n '''" ]
[ { "param": "text", "type": null }, { "param": "pattern", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "text", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pattern", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def extract_and_replace_one(text, pattern): matches = pattern.findall(text) if matches and len(matches) == 1: return text.replace(matches[0][0], ''), matches[0][1] return text, None
609,859
129
741e2b29b6e8941e57860ee08c469f840e2099fb
Sung-Huan/ANNOgesic
annogesiclib/detect_coverage_term.py
[ "0BSD" ]
Python
first_term
<not_specific>
def first_term(strand, term, detect_terms, detect): '''for the first and latest terminators, we only need to check parent gene for one side of terminator and also need to take care of the terminal end''' if (strand == "+"): if (term["detect_p"]): detect_terms["detect"].append(term) detect = True else: detect_terms["undetect"].append(term) elif (strand == "-"): if (term["detect_m"]): detect_terms["detect"].append(term) detect = True else: detect_terms["undetect"].append(term) return detect
for the first and latest terminators, we only need to check parent gene for one side of terminator and also need to take care of the terminal end
for the first and latest terminators, we only need to check parent gene for one side of terminator and also need to take care of the terminal end
[ "for", "the", "first", "and", "latest", "terminators", "we", "only", "need", "to", "check", "parent", "gene", "for", "one", "side", "of", "terminator", "and", "also", "need", "to", "take", "care", "of", "the", "terminal", "end" ]
def first_term(strand, term, detect_terms, detect): if (strand == "+"): if (term["detect_p"]): detect_terms["detect"].append(term) detect = True else: detect_terms["undetect"].append(term) elif (strand == "-"): if (term["detect_m"]): detect_terms["detect"].append(term) detect = True else: detect_terms["undetect"].append(term) return detect
[ "def", "first_term", "(", "strand", ",", "term", ",", "detect_terms", ",", "detect", ")", ":", "if", "(", "strand", "==", "\"+\"", ")", ":", "if", "(", "term", "[", "\"detect_p\"", "]", ")", ":", "detect_terms", "[", "\"detect\"", "]", ".", "append", "(", "term", ")", "detect", "=", "True", "else", ":", "detect_terms", "[", "\"undetect\"", "]", ".", "append", "(", "term", ")", "elif", "(", "strand", "==", "\"-\"", ")", ":", "if", "(", "term", "[", "\"detect_m\"", "]", ")", ":", "detect_terms", "[", "\"detect\"", "]", ".", "append", "(", "term", ")", "detect", "=", "True", "else", ":", "detect_terms", "[", "\"undetect\"", "]", ".", "append", "(", "term", ")", "return", "detect" ]
for the first and latest terminators, we only need to check parent gene for one side of terminator and also need to take care of the terminal end
[ "for", "the", "first", "and", "latest", "terminators", "we", "only", "need", "to", "check", "parent", "gene", "for", "one", "side", "of", "terminator", "and", "also", "need", "to", "take", "care", "of", "the", "terminal", "end" ]
[ "'''for the first and latest terminators, \n we only need to check parent gene for one side of terminator\n and also need to take care of the terminal end'''" ]
[ { "param": "strand", "type": null }, { "param": "term", "type": null }, { "param": "detect_terms", "type": null }, { "param": "detect", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "strand", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "term", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "detect_terms", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "detect", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def first_term(strand, term, detect_terms, detect): if (strand == "+"): if (term["detect_p"]): detect_terms["detect"].append(term) detect = True else: detect_terms["undetect"].append(term) elif (strand == "-"): if (term["detect_m"]): detect_terms["detect"].append(term) detect = True else: detect_terms["undetect"].append(term) return detect
609,860
601
9b994d3fcb88c0a4ec8d3a65a9bc6b4ab535ebb2
DavidLSmyth/OccupancyGridAgent
Utils/BeliefMap.py
[ "MIT" ]
Python
relative_change_bel_neg_reading
<not_specific>
def relative_change_bel_neg_reading(alpha, beta, prev_belief, prior_at_reading): '''Calculates the relatives change in belief given a positive reading''' beta1 = 1 - alpha - beta numerator = (((1-alpha) * prev_belief) - (beta1 * prior_at_reading)) denominator = (((1-alpha) * prev_belief) - (beta1 * prior_at_reading * prev_belief)) return numerator/denominator
Calculates the relatives change in belief given a positive reading
Calculates the relatives change in belief given a positive reading
[ "Calculates", "the", "relatives", "change", "in", "belief", "given", "a", "positive", "reading" ]
def relative_change_bel_neg_reading(alpha, beta, prev_belief, prior_at_reading): beta1 = 1 - alpha - beta numerator = (((1-alpha) * prev_belief) - (beta1 * prior_at_reading)) denominator = (((1-alpha) * prev_belief) - (beta1 * prior_at_reading * prev_belief)) return numerator/denominator
[ "def", "relative_change_bel_neg_reading", "(", "alpha", ",", "beta", ",", "prev_belief", ",", "prior_at_reading", ")", ":", "beta1", "=", "1", "-", "alpha", "-", "beta", "numerator", "=", "(", "(", "(", "1", "-", "alpha", ")", "*", "prev_belief", ")", "-", "(", "beta1", "*", "prior_at_reading", ")", ")", "denominator", "=", "(", "(", "(", "1", "-", "alpha", ")", "*", "prev_belief", ")", "-", "(", "beta1", "*", "prior_at_reading", "*", "prev_belief", ")", ")", "return", "numerator", "/", "denominator" ]
Calculates the relatives change in belief given a positive reading
[ "Calculates", "the", "relatives", "change", "in", "belief", "given", "a", "positive", "reading" ]
[ "'''Calculates the relatives change in belief given a positive reading'''" ]
[ { "param": "alpha", "type": null }, { "param": "beta", "type": null }, { "param": "prev_belief", "type": null }, { "param": "prior_at_reading", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "alpha", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "beta", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "prev_belief", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "prior_at_reading", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def relative_change_bel_neg_reading(alpha, beta, prev_belief, prior_at_reading): beta1 = 1 - alpha - beta numerator = (((1-alpha) * prev_belief) - (beta1 * prior_at_reading)) denominator = (((1-alpha) * prev_belief) - (beta1 * prior_at_reading * prev_belief)) return numerator/denominator
609,861
204
2321f0abb531fb197eb0c85f8872fbeb4efcbc44
vladisnik/lazy-lxd
lazy_lxd/lib/inquirer/lists.py
[ "MIT" ]
Python
convert_to_list_with_index
list
def convert_to_list_with_index(items: list) -> list: """ Prepare simple list to inquirer list. Convert to dicts list, with 2 keys: index and value from original list Args: items (list): Original items list which needs to convert Return: list: List of dicts with index key and item """ return [{'value': index, 'name': item} for index, item in enumerate(items)]
Prepare simple list to inquirer list. Convert to dicts list, with 2 keys: index and value from original list Args: items (list): Original items list which needs to convert Return: list: List of dicts with index key and item
Prepare simple list to inquirer list. Convert to dicts list, with 2 keys: index and value from original list
[ "Prepare", "simple", "list", "to", "inquirer", "list", ".", "Convert", "to", "dicts", "list", "with", "2", "keys", ":", "index", "and", "value", "from", "original", "list" ]
def convert_to_list_with_index(items: list) -> list: return [{'value': index, 'name': item} for index, item in enumerate(items)]
[ "def", "convert_to_list_with_index", "(", "items", ":", "list", ")", "->", "list", ":", "return", "[", "{", "'value'", ":", "index", ",", "'name'", ":", "item", "}", "for", "index", ",", "item", "in", "enumerate", "(", "items", ")", "]" ]
Prepare simple list to inquirer list.
[ "Prepare", "simple", "list", "to", "inquirer", "list", "." ]
[ "\"\"\"\n Prepare simple list to inquirer list.\n Convert to dicts list, with 2 keys: index and value from original list\n\n Args:\n items (list): Original items list which needs to convert\n\n Return:\n list: List of dicts with index key and item\n \"\"\"" ]
[ { "param": "items", "type": "list" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "items", "type": "list", "docstring": "Original items list which needs to convert", "docstring_tokens": [ "Original", "items", "list", "which", "needs", "to", "convert" ], "default": null, "is_optional": false } ], "outlier_params": [], "others": [] }
def convert_to_list_with_index(items: list) -> list: return [{'value': index, 'name': item} for index, item in enumerate(items)]
609,862
886
bb37b24d930465810165681d51a707f2106de549
rwatson/chromium-capsicum
build/linux/rewrite_dirs.py
[ "BSD-3-Clause" ]
Python
RewritePath
<not_specific>
def RewritePath(path, sysroot): """Rewrites a path by prefixing it with the sysroot if it is absolute.""" if os.path.isabs(path): path = path.lstrip('/') return os.path.join(sysroot, path) else: return path
Rewrites a path by prefixing it with the sysroot if it is absolute.
Rewrites a path by prefixing it with the sysroot if it is absolute.
[ "Rewrites", "a", "path", "by", "prefixing", "it", "with", "the", "sysroot", "if", "it", "is", "absolute", "." ]
def RewritePath(path, sysroot): if os.path.isabs(path): path = path.lstrip('/') return os.path.join(sysroot, path) else: return path
[ "def", "RewritePath", "(", "path", ",", "sysroot", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "path", "=", "path", ".", "lstrip", "(", "'/'", ")", "return", "os", ".", "path", ".", "join", "(", "sysroot", ",", "path", ")", "else", ":", "return", "path" ]
Rewrites a path by prefixing it with the sysroot if it is absolute.
[ "Rewrites", "a", "path", "by", "prefixing", "it", "with", "the", "sysroot", "if", "it", "is", "absolute", "." ]
[ "\"\"\"Rewrites a path by prefixing it with the sysroot if it is absolute.\"\"\"" ]
[ { "param": "path", "type": null }, { "param": "sysroot", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sysroot", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import os def RewritePath(path, sysroot): if os.path.isabs(path): path = path.lstrip('/') return os.path.join(sysroot, path) else: return path
609,864
484
3db07fec04c70b42987cba4fc5430a2759db3440
jabalazs/repeval_rivercorners
repeval/utils/io.py
[ "MIT" ]
Python
write_metrics
null
def write_metrics(log_dir, params): """This code asumes the log_dir directory already exists""" metrics_file = os.path.join(log_dir, 'metrics.json') with open(metrics_file, 'w') as f: f.write(json.dumps(params))
This code asumes the log_dir directory already exists
This code asumes the log_dir directory already exists
[ "This", "code", "asumes", "the", "log_dir", "directory", "already", "exists" ]
def write_metrics(log_dir, params): metrics_file = os.path.join(log_dir, 'metrics.json') with open(metrics_file, 'w') as f: f.write(json.dumps(params))
[ "def", "write_metrics", "(", "log_dir", ",", "params", ")", ":", "metrics_file", "=", "os", ".", "path", ".", "join", "(", "log_dir", ",", "'metrics.json'", ")", "with", "open", "(", "metrics_file", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "json", ".", "dumps", "(", "params", ")", ")" ]
This code asumes the log_dir directory already exists
[ "This", "code", "asumes", "the", "log_dir", "directory", "already", "exists" ]
[ "\"\"\"This code asumes the log_dir directory already exists\"\"\"" ]
[ { "param": "log_dir", "type": null }, { "param": "params", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "log_dir", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "params", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import os import json def write_metrics(log_dir, params): metrics_file = os.path.join(log_dir, 'metrics.json') with open(metrics_file, 'w') as f: f.write(json.dumps(params))
609,866
157
88136359df90a305521c6b86b166fb62e4233214
efeslab/bugbase
lib/hooks.py
[ "BSD-3-Clause" ]
Python
post_install_run
None
def post_install_run(analysis_plugins=None, **kwargs) -> None: """ Calls analysis_plugins after the installation has succeeded :param analysis_plugins: the plugins to call :param kwargs: keyword arguments to pass to plugins """ if analysis_plugins is not None: for plugin in analysis_plugins: plugin().post_install_run(**kwargs)
Calls analysis_plugins after the installation has succeeded :param analysis_plugins: the plugins to call :param kwargs: keyword arguments to pass to plugins
Calls analysis_plugins after the installation has succeeded
[ "Calls", "analysis_plugins", "after", "the", "installation", "has", "succeeded" ]
def post_install_run(analysis_plugins=None, **kwargs) -> None: if analysis_plugins is not None: for plugin in analysis_plugins: plugin().post_install_run(**kwargs)
[ "def", "post_install_run", "(", "analysis_plugins", "=", "None", ",", "**", "kwargs", ")", "->", "None", ":", "if", "analysis_plugins", "is", "not", "None", ":", "for", "plugin", "in", "analysis_plugins", ":", "plugin", "(", ")", ".", "post_install_run", "(", "**", "kwargs", ")" ]
Calls analysis_plugins after the installation has succeeded
[ "Calls", "analysis_plugins", "after", "the", "installation", "has", "succeeded" ]
[ "\"\"\"\n Calls analysis_plugins after the installation has succeeded\n :param analysis_plugins: the plugins to call\n :param kwargs: keyword arguments to pass to plugins\n \"\"\"" ]
[ { "param": "analysis_plugins", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "analysis_plugins", "type": null, "docstring": "the plugins to call", "docstring_tokens": [ "the", "plugins", "to", "call" ], "default": null, "is_optional": null } ], "outlier_params": [ { "identifier": "kwargs", "type": null, "docstring": "keyword arguments to pass to plugins", "docstring_tokens": [ "keyword", "arguments", "to", "pass", "to", "plugins" ], "default": null, "is_optional": null } ], "others": [] }
def post_install_run(analysis_plugins=None, **kwargs) -> None: if analysis_plugins is not None: for plugin in analysis_plugins: plugin().post_install_run(**kwargs)
609,867
748
be6237a119b5bc94150e90b7dacd3b33e02dbc32
Dennisvw99/NeDaGen
roles/3_setup-topology/files/getmail-5.16/getmailcore/utilities.py
[ "MIT" ]
Python
address_no_brackets
<not_specific>
def address_no_brackets(addr): '''Strip surrounding <> on an email address, if present.''' if addr.startswith('<') and addr.endswith('>'): return addr[1:-1] else: return addr
Strip surrounding <> on an email address, if present.
Strip surrounding <> on an email address, if present.
[ "Strip", "surrounding", "<", ">", "on", "an", "email", "address", "if", "present", "." ]
def address_no_brackets(addr): if addr.startswith('<') and addr.endswith('>'): return addr[1:-1] else: return addr
[ "def", "address_no_brackets", "(", "addr", ")", ":", "if", "addr", ".", "startswith", "(", "'<'", ")", "and", "addr", ".", "endswith", "(", "'>'", ")", ":", "return", "addr", "[", "1", ":", "-", "1", "]", "else", ":", "return", "addr" ]
Strip surrounding <> on an email address, if present.
[ "Strip", "surrounding", "<", ">", "on", "an", "email", "address", "if", "present", "." ]
[ "'''Strip surrounding <> on an email address, if present.'''" ]
[ { "param": "addr", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "addr", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def address_no_brackets(addr): if addr.startswith('<') and addr.endswith('>'): return addr[1:-1] else: return addr
609,868
910
76bd590acb2eafc5a16ca50f262ba2547a8a8197
Debanitrkl/FlipkartGrid
CustomDash-master/data preparation/Scraper_vogue.py
[ "MIT" ]
Python
save_to_disk
null
def save_to_disk(text_corpus, entity): """save the scrapped text to csv @params: """ with open("path", 'a') as file: for i in range(len(text_corpus)): row = [i, entity, text_corpus[i]] writer = csv.writer(file) writer.writerow(row) file.close()
save the scrapped text to csv @params:
save the scrapped text to csv
[ "save", "the", "scrapped", "text", "to", "csv" ]
def save_to_disk(text_corpus, entity): with open("path", 'a') as file: for i in range(len(text_corpus)): row = [i, entity, text_corpus[i]] writer = csv.writer(file) writer.writerow(row) file.close()
[ "def", "save_to_disk", "(", "text_corpus", ",", "entity", ")", ":", "with", "open", "(", "\"path\"", ",", "'a'", ")", "as", "file", ":", "for", "i", "in", "range", "(", "len", "(", "text_corpus", ")", ")", ":", "row", "=", "[", "i", ",", "entity", ",", "text_corpus", "[", "i", "]", "]", "writer", "=", "csv", ".", "writer", "(", "file", ")", "writer", ".", "writerow", "(", "row", ")", "file", ".", "close", "(", ")" ]
save the scrapped text to csv
[ "save", "the", "scrapped", "text", "to", "csv" ]
[ "\"\"\"save the scrapped text to csv\n @params:\n \"\"\"" ]
[ { "param": "text_corpus", "type": null }, { "param": "entity", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "text_corpus", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "entity", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "params", "docstring": null, "docstring_tokens": [ "None" ] } ] }
import csv def save_to_disk(text_corpus, entity): with open("path", 'a') as file: for i in range(len(text_corpus)): row = [i, entity, text_corpus[i]] writer = csv.writer(file) writer.writerow(row) file.close()
609,869
585
e79399d4ccf567d834596e0c31cd3a201fffd0b9
roderickmackenzie/gpvdm
gpvdm_gui/gui/inp.py
[ "BSD-3-Clause" ]
Python
inp_read_next_item
<not_specific>
def inp_read_next_item(lines,pos): """Read the next item form an inp file""" token=lines[pos] pos=pos+1 value=lines[pos] pos=pos+1 return token,value,pos
Read the next item form an inp file
Read the next item form an inp file
[ "Read", "the", "next", "item", "form", "an", "inp", "file" ]
def inp_read_next_item(lines,pos): token=lines[pos] pos=pos+1 value=lines[pos] pos=pos+1 return token,value,pos
[ "def", "inp_read_next_item", "(", "lines", ",", "pos", ")", ":", "token", "=", "lines", "[", "pos", "]", "pos", "=", "pos", "+", "1", "value", "=", "lines", "[", "pos", "]", "pos", "=", "pos", "+", "1", "return", "token", ",", "value", ",", "pos" ]
Read the next item form an inp file
[ "Read", "the", "next", "item", "form", "an", "inp", "file" ]
[ "\"\"\"Read the next item form an inp file\"\"\"" ]
[ { "param": "lines", "type": null }, { "param": "pos", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lines", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pos", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def inp_read_next_item(lines,pos): token=lines[pos] pos=pos+1 value=lines[pos] pos=pos+1 return token,value,pos
609,870
865
2c637182684706bc005b3f01dd287f5bac0c78ad
molly/GorillaBot
gorillabot/plugins/link.py
[ "MIT" ]
Python
xkcd_direct
<not_specific>
def xkcd_direct(html, url=None): """Try to return a title and link for a direct link to an xkcd comic.""" if not html: return None if not url: url_match = re.search(r'Permanent link to this comic: ([^\s<>]+)', html) if url_match: url = url_match.group(1) else: return None match = re.search(r'<title>(.+?)</title>', html) if match: return match.group(1) + ": " + url else: return None
Try to return a title and link for a direct link to an xkcd comic.
Try to return a title and link for a direct link to an xkcd comic.
[ "Try", "to", "return", "a", "title", "and", "link", "for", "a", "direct", "link", "to", "an", "xkcd", "comic", "." ]
def xkcd_direct(html, url=None): if not html: return None if not url: url_match = re.search(r'Permanent link to this comic: ([^\s<>]+)', html) if url_match: url = url_match.group(1) else: return None match = re.search(r'<title>(.+?)</title>', html) if match: return match.group(1) + ": " + url else: return None
[ "def", "xkcd_direct", "(", "html", ",", "url", "=", "None", ")", ":", "if", "not", "html", ":", "return", "None", "if", "not", "url", ":", "url_match", "=", "re", ".", "search", "(", "r'Permanent link to this comic: ([^\\s<>]+)'", ",", "html", ")", "if", "url_match", ":", "url", "=", "url_match", ".", "group", "(", "1", ")", "else", ":", "return", "None", "match", "=", "re", ".", "search", "(", "r'<title>(.+?)</title>'", ",", "html", ")", "if", "match", ":", "return", "match", ".", "group", "(", "1", ")", "+", "\": \"", "+", "url", "else", ":", "return", "None" ]
Try to return a title and link for a direct link to an xkcd comic.
[ "Try", "to", "return", "a", "title", "and", "link", "for", "a", "direct", "link", "to", "an", "xkcd", "comic", "." ]
[ "\"\"\"Try to return a title and link for a direct link to an xkcd comic.\"\"\"" ]
[ { "param": "html", "type": null }, { "param": "url", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "html", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "url", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import re def xkcd_direct(html, url=None): if not html: return None if not url: url_match = re.search(r'Permanent link to this comic: ([^\s<>]+)', html) if url_match: url = url_match.group(1) else: return None match = re.search(r'<title>(.+?)</title>', html) if match: return match.group(1) + ": " + url else: return None
609,871
401
ff4eef48bc60a757f3bc6482735ddc0c52797e3f
lucasg/MSVCUnicodeUpdater
sed.py
[ "MIT" ]
Python
backiter
null
def backiter(iterable): ''' Back iterator. Since we insert new text in the line string based on index, we have to read from right to left in order to conserve the indexing. ''' for m in [ m for m in iterable ][::-1]: yield m
Back iterator. Since we insert new text in the line string based on index, we have to read from right to left in order to conserve the indexing.
Back iterator. Since we insert new text in the line string based on index, we have to read from right to left in order to conserve the indexing.
[ "Back", "iterator", ".", "Since", "we", "insert", "new", "text", "in", "the", "line", "string", "based", "on", "index", "we", "have", "to", "read", "from", "right", "to", "left", "in", "order", "to", "conserve", "the", "indexing", "." ]
def backiter(iterable): for m in [ m for m in iterable ][::-1]: yield m
[ "def", "backiter", "(", "iterable", ")", ":", "for", "m", "in", "[", "m", "for", "m", "in", "iterable", "]", "[", ":", ":", "-", "1", "]", ":", "yield", "m" ]
Back iterator.
[ "Back", "iterator", "." ]
[ "'''\r\n\t\tBack iterator. Since we insert new text in the line string based on \r\n\t\tindex, we have to read from right to left in order to conserve the indexing.\r\n\t'''" ]
[ { "param": "iterable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "iterable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def backiter(iterable): for m in [ m for m in iterable ][::-1]: yield m
609,872
541
eea1d331e42d8a04b4c08b135cb86ae620fdd67e
sherilan/tfslurm
tfslurm/tfslurm.py
[ "MIT" ]
Python
create_task_table
<not_specific>
def create_task_table( cls, num_ps, base_port, nodelist, tasklist, gpulist, my_node, my_proc ): ''' Deterministically create a table with task/node/gpu allocations ''' tasktable = [] for node, num_tasks in zip( nodelist, tasklist ): # Generate list of even gpu allocations over the current node gpu_alloc = [int(min(num_tasks,len(gpulist))*task/num_tasks) for task in range( num_tasks )] # Create a config dictionary for each task on the node for task in range( num_tasks ): tasktable.append( dict( # Node the task is being run on node=node, # Local task index on node node_task=task, # Task type role = cls.PARAMETER_SERVER if len(tasktable) < num_ps else cls.WORKER, # Global task index across all nodes global_task_index=len( tasktable ), # Task within role, e.g. ps:0,1,... or worker:0,1,2.. role_index=len(tasktable) if len(tasktable) < num_ps else len(tasktable)-num_ps, # Port for parameter server communication port=base_port + task, # Allocated gpu for this task gpu=gpulist[gpu_alloc[task]], # Fraction of assigned gpu available to this task gpu_frac=1/sum( gpui==gpu_alloc[task] for gpui in gpu_alloc ), # Whether this task is the current process' task me=(node==my_node and len(tasktable)==int(my_proc)) )) return tasktable
Deterministically create a table with task/node/gpu allocations
Deterministically create a table with task/node/gpu allocations
[ "Deterministically", "create", "a", "table", "with", "task", "/", "node", "/", "gpu", "allocations" ]
def create_task_table( cls, num_ps, base_port, nodelist, tasklist, gpulist, my_node, my_proc ): tasktable = [] for node, num_tasks in zip( nodelist, tasklist ): gpu_alloc = [int(min(num_tasks,len(gpulist))*task/num_tasks) for task in range( num_tasks )] for task in range( num_tasks ): tasktable.append( dict( node=node, node_task=task, role = cls.PARAMETER_SERVER if len(tasktable) < num_ps else cls.WORKER, global_task_index=len( tasktable ), role_index=len(tasktable) if len(tasktable) < num_ps else len(tasktable)-num_ps, port=base_port + task, gpu=gpulist[gpu_alloc[task]], gpu_frac=1/sum( gpui==gpu_alloc[task] for gpui in gpu_alloc ), me=(node==my_node and len(tasktable)==int(my_proc)) )) return tasktable
[ "def", "create_task_table", "(", "cls", ",", "num_ps", ",", "base_port", ",", "nodelist", ",", "tasklist", ",", "gpulist", ",", "my_node", ",", "my_proc", ")", ":", "tasktable", "=", "[", "]", "for", "node", ",", "num_tasks", "in", "zip", "(", "nodelist", ",", "tasklist", ")", ":", "gpu_alloc", "=", "[", "int", "(", "min", "(", "num_tasks", ",", "len", "(", "gpulist", ")", ")", "*", "task", "/", "num_tasks", ")", "for", "task", "in", "range", "(", "num_tasks", ")", "]", "for", "task", "in", "range", "(", "num_tasks", ")", ":", "tasktable", ".", "append", "(", "dict", "(", "node", "=", "node", ",", "node_task", "=", "task", ",", "role", "=", "cls", ".", "PARAMETER_SERVER", "if", "len", "(", "tasktable", ")", "<", "num_ps", "else", "cls", ".", "WORKER", ",", "global_task_index", "=", "len", "(", "tasktable", ")", ",", "role_index", "=", "len", "(", "tasktable", ")", "if", "len", "(", "tasktable", ")", "<", "num_ps", "else", "len", "(", "tasktable", ")", "-", "num_ps", ",", "port", "=", "base_port", "+", "task", ",", "gpu", "=", "gpulist", "[", "gpu_alloc", "[", "task", "]", "]", ",", "gpu_frac", "=", "1", "/", "sum", "(", "gpui", "==", "gpu_alloc", "[", "task", "]", "for", "gpui", "in", "gpu_alloc", ")", ",", "me", "=", "(", "node", "==", "my_node", "and", "len", "(", "tasktable", ")", "==", "int", "(", "my_proc", ")", ")", ")", ")", "return", "tasktable" ]
Deterministically create a table with task/node/gpu allocations
[ "Deterministically", "create", "a", "table", "with", "task", "/", "node", "/", "gpu", "allocations" ]
[ "'''\n Deterministically create a table with task/node/gpu allocations\n '''", "# Generate list of even gpu allocations over the current node", "# Create a config dictionary for each task on the node", "# Node the task is being run on", "# Local task index on node", "# Task type ", "# Global task index across all nodes", "# Task within role, e.g. ps:0,1,... or worker:0,1,2..", "# Port for parameter server communication", "# Allocated gpu for this task", "# Fraction of assigned gpu available to this task", "# Whether this task is the current process' task" ]
[ { "param": "cls", "type": null }, { "param": "num_ps", "type": null }, { "param": "base_port", "type": null }, { "param": "nodelist", "type": null }, { "param": "tasklist", "type": null }, { "param": "gpulist", "type": null }, { "param": "my_node", "type": null }, { "param": "my_proc", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "num_ps", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "base_port", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "nodelist", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "tasklist", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "gpulist", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "my_node", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "my_proc", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def create_task_table( cls, num_ps, base_port, nodelist, tasklist, gpulist, my_node, my_proc ): tasktable = [] for node, num_tasks in zip( nodelist, tasklist ): gpu_alloc = [int(min(num_tasks,len(gpulist))*task/num_tasks) for task in range( num_tasks )] for task in range( num_tasks ): tasktable.append( dict( node=node, node_task=task, role = cls.PARAMETER_SERVER if len(tasktable) < num_ps else cls.WORKER, global_task_index=len( tasktable ), role_index=len(tasktable) if len(tasktable) < num_ps else len(tasktable)-num_ps, port=base_port + task, gpu=gpulist[gpu_alloc[task]], gpu_frac=1/sum( gpui==gpu_alloc[task] for gpui in gpu_alloc ), me=(node==my_node and len(tasktable)==int(my_proc)) )) return tasktable
609,873
838
4e36b7da94b7e45ef2f1897369af03bcf19f59f4
vallen-systems/pyWaveLine
src/waveline/spotwave.py
[ "MIT" ]
Python
_multiline_output_to_dict
<not_specific>
def _multiline_output_to_dict(lines: List[bytes]): """Helper function to parse output from get_info, get_status and get_setup.""" return collections.defaultdict( str, [(k.strip(), v.strip()) for k, _, v in [line.decode().partition("=") for line in lines]], )
Helper function to parse output from get_info, get_status and get_setup.
Helper function to parse output from get_info, get_status and get_setup.
[ "Helper", "function", "to", "parse", "output", "from", "get_info", "get_status", "and", "get_setup", "." ]
def _multiline_output_to_dict(lines: List[bytes]): return collections.defaultdict( str, [(k.strip(), v.strip()) for k, _, v in [line.decode().partition("=") for line in lines]], )
[ "def", "_multiline_output_to_dict", "(", "lines", ":", "List", "[", "bytes", "]", ")", ":", "return", "collections", ".", "defaultdict", "(", "str", ",", "[", "(", "k", ".", "strip", "(", ")", ",", "v", ".", "strip", "(", ")", ")", "for", "k", ",", "_", ",", "v", "in", "[", "line", ".", "decode", "(", ")", ".", "partition", "(", "\"=\"", ")", "for", "line", "in", "lines", "]", "]", ",", ")" ]
Helper function to parse output from get_info, get_status and get_setup.
[ "Helper", "function", "to", "parse", "output", "from", "get_info", "get_status", "and", "get_setup", "." ]
[ "\"\"\"Helper function to parse output from get_info, get_status and get_setup.\"\"\"" ]
[ { "param": "lines", "type": "List[bytes]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lines", "type": "List[bytes]", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import collections def _multiline_output_to_dict(lines: List[bytes]): return collections.defaultdict( str, [(k.strip(), v.strip()) for k, _, v in [line.decode().partition("=") for line in lines]], )
609,874
43
0616d471d41af2355d07f2a717da7fc08bd530f0
NASA-Tournament-Lab/CoECI-CMS-Healthcare-Fraud-Prevention
study/hfppnetwork/hfppnetwork/sms/helper.py
[ "Apache-2.0" ]
Python
parseFloat
<not_specific>
def parseFloat(elem, path): """ Parse element text as float Parameters: - elem : the element - path : the element path Return float value if parsable, otherwise None """ text = elem.findtext(path) if text != None: return float(text) else: return None
Parse element text as float Parameters: - elem : the element - path : the element path Return float value if parsable, otherwise None
Parse element text as float Parameters: elem : the element path : the element path Return float value if parsable, otherwise None
[ "Parse", "element", "text", "as", "float", "Parameters", ":", "elem", ":", "the", "element", "path", ":", "the", "element", "path", "Return", "float", "value", "if", "parsable", "otherwise", "None" ]
def parseFloat(elem, path): text = elem.findtext(path) if text != None: return float(text) else: return None
[ "def", "parseFloat", "(", "elem", ",", "path", ")", ":", "text", "=", "elem", ".", "findtext", "(", "path", ")", "if", "text", "!=", "None", ":", "return", "float", "(", "text", ")", "else", ":", "return", "None" ]
Parse element text as float Parameters: elem : the element path : the element path
[ "Parse", "element", "text", "as", "float", "Parameters", ":", "elem", ":", "the", "element", "path", ":", "the", "element", "path" ]
[ "\"\"\"\n Parse element text as float\n Parameters:\n - elem : the element\n - path : the element path \n \n Return float value if parsable, otherwise None\n \"\"\"" ]
[ { "param": "elem", "type": null }, { "param": "path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "elem", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def parseFloat(elem, path): text = elem.findtext(path) if text != None: return float(text) else: return None
609,875
702
1a18b2d669ff4f31292991f5d4d96ea6d257dd22
yixinwang/representation-causal-public
disentanglement_expms/sec3-4-ioss_vae/src/disent_dataset.py
[ "MIT" ]
Python
_batch_to_observation
<not_specific>
def _batch_to_observation(batch, obs_shape): """ Convert a batch of size 1, to a single observation. """ if batch.shape != obs_shape: assert batch.shape == (1, *obs_shape), f'batch.shape={repr(batch.shape)} does not correspond to obs_shape={repr(obs_shape)} with batch dimension added' return batch.reshape(obs_shape) return batch
Convert a batch of size 1, to a single observation.
Convert a batch of size 1, to a single observation.
[ "Convert", "a", "batch", "of", "size", "1", "to", "a", "single", "observation", "." ]
def _batch_to_observation(batch, obs_shape): if batch.shape != obs_shape: assert batch.shape == (1, *obs_shape), f'batch.shape={repr(batch.shape)} does not correspond to obs_shape={repr(obs_shape)} with batch dimension added' return batch.reshape(obs_shape) return batch
[ "def", "_batch_to_observation", "(", "batch", ",", "obs_shape", ")", ":", "if", "batch", ".", "shape", "!=", "obs_shape", ":", "assert", "batch", ".", "shape", "==", "(", "1", ",", "*", "obs_shape", ")", ",", "f'batch.shape={repr(batch.shape)} does not correspond to obs_shape={repr(obs_shape)} with batch dimension added'", "return", "batch", ".", "reshape", "(", "obs_shape", ")", "return", "batch" ]
Convert a batch of size 1, to a single observation.
[ "Convert", "a", "batch", "of", "size", "1", "to", "a", "single", "observation", "." ]
[ "\"\"\"\n Convert a batch of size 1, to a single observation.\n \"\"\"" ]
[ { "param": "batch", "type": null }, { "param": "obs_shape", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "batch", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "obs_shape", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def _batch_to_observation(batch, obs_shape): if batch.shape != obs_shape: assert batch.shape == (1, *obs_shape), f'batch.shape={repr(batch.shape)} does not correspond to obs_shape={repr(obs_shape)} with batch dimension added' return batch.reshape(obs_shape) return batch
609,876
724
741cd28a5e23ce49448f92436f181f4c0b6ce3f8
ptes77/TetrisAI
TetrisAI.py
[ "MIT" ]
Python
_make_child
<not_specific>
def _make_child(parent1, parent2, factor): '''Helps the make_child function inside the Tetris Class create a child genome using a weighted average between the fitnesses of the two parents. Adds a little randomness to avoid a value equaling zero Arguments: parent1: a parent genome dict, usually a random one from the genome parent2: a parent genome dict, usually an elite genome factor: a string representing the feature that will be computed Return Value: An integer value representing the numeric value of the genome ''' fitness1 = parent1['fitness'] fitness2 = parent2['fitness'] factor1 = parent1[factor] factor2 = parent2[factor] normalizingFitness = fitness1 + fitness2 newFitness = (fitness1 * factor1 + fitness2 * factor2) / normalizingFitness return newFitness
Helps the make_child function inside the Tetris Class create a child genome using a weighted average between the fitnesses of the two parents. Adds a little randomness to avoid a value equaling zero Arguments: parent1: a parent genome dict, usually a random one from the genome parent2: a parent genome dict, usually an elite genome factor: a string representing the feature that will be computed Return Value: An integer value representing the numeric value of the genome
Helps the make_child function inside the Tetris Class create a child genome using a weighted average between the fitnesses of the two parents. Adds a little randomness to avoid a value equaling zero
[ "Helps", "the", "make_child", "function", "inside", "the", "Tetris", "Class", "create", "a", "child", "genome", "using", "a", "weighted", "average", "between", "the", "fitnesses", "of", "the", "two", "parents", ".", "Adds", "a", "little", "randomness", "to", "avoid", "a", "value", "equaling", "zero" ]
def _make_child(parent1, parent2, factor): fitness1 = parent1['fitness'] fitness2 = parent2['fitness'] factor1 = parent1[factor] factor2 = parent2[factor] normalizingFitness = fitness1 + fitness2 newFitness = (fitness1 * factor1 + fitness2 * factor2) / normalizingFitness return newFitness
[ "def", "_make_child", "(", "parent1", ",", "parent2", ",", "factor", ")", ":", "fitness1", "=", "parent1", "[", "'fitness'", "]", "fitness2", "=", "parent2", "[", "'fitness'", "]", "factor1", "=", "parent1", "[", "factor", "]", "factor2", "=", "parent2", "[", "factor", "]", "normalizingFitness", "=", "fitness1", "+", "fitness2", "newFitness", "=", "(", "fitness1", "*", "factor1", "+", "fitness2", "*", "factor2", ")", "/", "normalizingFitness", "return", "newFitness" ]
Helps the make_child function inside the Tetris Class create a child genome using a weighted average between the fitnesses of the two parents.
[ "Helps", "the", "make_child", "function", "inside", "the", "Tetris", "Class", "create", "a", "child", "genome", "using", "a", "weighted", "average", "between", "the", "fitnesses", "of", "the", "two", "parents", "." ]
[ "'''Helps the make_child function inside the Tetris Class create a child\r\n genome using a weighted average between the fitnesses of the two parents.\r\n Adds a little randomness to avoid a value equaling zero\r\n \r\n Arguments:\r\n parent1: a parent genome dict, usually a random one from the genome\r\n parent2: a parent genome dict, usually an elite genome\r\n factor: a string representing the feature that will be computed\r\n \r\n Return Value:\r\n An integer value representing the numeric value of the genome\r\n '''" ]
[ { "param": "parent1", "type": null }, { "param": "parent2", "type": null }, { "param": "factor", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "parent1", "type": null, "docstring": "a parent genome dict, usually a random one from the genome", "docstring_tokens": [ "a", "parent", "genome", "dict", "usually", "a", "random", "one", "from", "the", "genome" ], "default": null, "is_optional": null }, { "identifier": "parent2", "type": null, "docstring": "a parent genome dict, usually an elite genome", "docstring_tokens": [ "a", "parent", "genome", "dict", "usually", "an", "elite", "genome" ], "default": null, "is_optional": null }, { "identifier": "factor", "type": null, "docstring": "a string representing the feature that will be computed", "docstring_tokens": [ "a", "string", "representing", "the", "feature", "that", "will", "be", "computed" ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def _make_child(parent1, parent2, factor): fitness1 = parent1['fitness'] fitness2 = parent2['fitness'] factor1 = parent1[factor] factor2 = parent2[factor] normalizingFitness = fitness1 + fitness2 newFitness = (fitness1 * factor1 + fitness2 * factor2) / normalizingFitness return newFitness
609,879
482
424bf3dd9d048dd2c435b4146c385f2d3697d26c
AllanYiin/trident
trident/backend/pytorch_ops.py
[ "MIT" ]
Python
rsqrt
<not_specific>
def rsqrt(x: Tensor): """Computes reciprocal of square root of x element-wise. Args: x: input tensor Returns: output tensor Examples: >>> x = to_tensor([2., 0., -2.]) >>> rsqrt(x) <Tensor: shape=(3,), dtype=float32, numpy=array([0.707, inf, nan], dtype=float32)> """ return x.rsqrt()
Computes reciprocal of square root of x element-wise. Args: x: input tensor Returns: output tensor Examples: >>> x = to_tensor([2., 0., -2.]) >>> rsqrt(x) <Tensor: shape=(3,), dtype=float32, numpy=array([0.707, inf, nan], dtype=float32)>
Computes reciprocal of square root of x element-wise.
[ "Computes", "reciprocal", "of", "square", "root", "of", "x", "element", "-", "wise", "." ]
def rsqrt(x: Tensor): return x.rsqrt()
[ "def", "rsqrt", "(", "x", ":", "Tensor", ")", ":", "return", "x", ".", "rsqrt", "(", ")" ]
Computes reciprocal of square root of x element-wise.
[ "Computes", "reciprocal", "of", "square", "root", "of", "x", "element", "-", "wise", "." ]
[ "\"\"\"Computes reciprocal of square root of x element-wise.\n\n Args:\n x: input tensor\n\n Returns:\n output tensor\n\n\n Examples:\n >>> x = to_tensor([2., 0., -2.])\n >>> rsqrt(x)\n <Tensor: shape=(3,), dtype=float32,\n numpy=array([0.707, inf, nan], dtype=float32)>\n\n \"\"\"" ]
[ { "param": "x", "type": "Tensor" } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "x", "type": "Tensor", "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "examples", "docstring": null, "docstring_tokens": [ "None" ] } ] }
def rsqrt(x: Tensor): return x.rsqrt()
609,880
529
f97b25884a993418e7fa4b9efe5b2e33e138007c
HaolinCMU/Soft_tissue_tracking
nonlinear/HL_parameterization/ANN_HL_parameterization_nonlinear.py
[ "MIT" ]
Python
combinationRecursion
<not_specific>
def combinationRecursion(neuron_num_options_list, layer_num, combination_list_temp, combination_list_total): """ Recursively generate all valid combinations of hidden layers. Parameters: ---------- neuron_num_options_list: List of int. List all possible neuron numbers for a single hidden layer. layer_num: Int. The number of intended hidden layers. combination_list_temp: List of int. A single combination of a hidden layer. Appendable. combination_list_total: Multi-dimentional list of int. Store all possible combinations recursively generated by the function. Returns: ---------- combination_list_temp: List of int. Recursive return. Return the updated combination during recursion process. combination_list_total: Multi-dimentional list of int. Store all possible combinations recursively generated by the function. """ for item in neuron_num_options_list: combination_list_temp.append(item) if len(combination_list_temp) >= layer_num: combination_list_total.append(copy.deepcopy(combination_list_temp)) combination_list_temp = copy.deepcopy(combination_list_temp[:-1]) else: combination_list_temp, combination_list_total = combinationRecursion(neuron_num_options_list, layer_num, combination_list_temp, combination_list_total) combination_list_temp = copy.deepcopy(combination_list_temp[:-1]) return combination_list_temp, combination_list_total
Recursively generate all valid combinations of hidden layers. Parameters: ---------- neuron_num_options_list: List of int. List all possible neuron numbers for a single hidden layer. layer_num: Int. The number of intended hidden layers. combination_list_temp: List of int. A single combination of a hidden layer. Appendable. combination_list_total: Multi-dimentional list of int. Store all possible combinations recursively generated by the function. Returns: ---------- combination_list_temp: List of int. Recursive return. Return the updated combination during recursion process. combination_list_total: Multi-dimentional list of int. Store all possible combinations recursively generated by the function.
Recursively generate all valid combinations of hidden layers. Parameters. List of int. List all possible neuron numbers for a single hidden layer. List of int. Recursive return. Return the updated combination during recursion process. combination_list_total: Multi-dimentional list of int. Store all possible combinations recursively generated by the function.
[ "Recursively", "generate", "all", "valid", "combinations", "of", "hidden", "layers", ".", "Parameters", ".", "List", "of", "int", ".", "List", "all", "possible", "neuron", "numbers", "for", "a", "single", "hidden", "layer", ".", "List", "of", "int", ".", "Recursive", "return", ".", "Return", "the", "updated", "combination", "during", "recursion", "process", ".", "combination_list_total", ":", "Multi", "-", "dimentional", "list", "of", "int", ".", "Store", "all", "possible", "combinations", "recursively", "generated", "by", "the", "function", "." ]
def combinationRecursion(neuron_num_options_list, layer_num, combination_list_temp, combination_list_total): for item in neuron_num_options_list: combination_list_temp.append(item) if len(combination_list_temp) >= layer_num: combination_list_total.append(copy.deepcopy(combination_list_temp)) combination_list_temp = copy.deepcopy(combination_list_temp[:-1]) else: combination_list_temp, combination_list_total = combinationRecursion(neuron_num_options_list, layer_num, combination_list_temp, combination_list_total) combination_list_temp = copy.deepcopy(combination_list_temp[:-1]) return combination_list_temp, combination_list_total
[ "def", "combinationRecursion", "(", "neuron_num_options_list", ",", "layer_num", ",", "combination_list_temp", ",", "combination_list_total", ")", ":", "for", "item", "in", "neuron_num_options_list", ":", "combination_list_temp", ".", "append", "(", "item", ")", "if", "len", "(", "combination_list_temp", ")", ">=", "layer_num", ":", "combination_list_total", ".", "append", "(", "copy", ".", "deepcopy", "(", "combination_list_temp", ")", ")", "combination_list_temp", "=", "copy", ".", "deepcopy", "(", "combination_list_temp", "[", ":", "-", "1", "]", ")", "else", ":", "combination_list_temp", ",", "combination_list_total", "=", "combinationRecursion", "(", "neuron_num_options_list", ",", "layer_num", ",", "combination_list_temp", ",", "combination_list_total", ")", "combination_list_temp", "=", "copy", ".", "deepcopy", "(", "combination_list_temp", "[", ":", "-", "1", "]", ")", "return", "combination_list_temp", ",", "combination_list_total" ]
Recursively generate all valid combinations of hidden layers.
[ "Recursively", "generate", "all", "valid", "combinations", "of", "hidden", "layers", "." ]
[ "\"\"\"\r\n Recursively generate all valid combinations of hidden layers. \r\n\r\n Parameters:\r\n ----------\r\n neuron_num_options_list: List of int. \r\n List all possible neuron numbers for a single hidden layer. \r\n layer_num: Int. \r\n The number of intended hidden layers. \r\n combination_list_temp: List of int. \r\n A single combination of a hidden layer. Appendable. \r\n combination_list_total: Multi-dimentional list of int. \r\n Store all possible combinations recursively generated by the function.\r\n\r\n Returns:\r\n ----------\r\n combination_list_temp: List of int. \r\n Recursive return. \r\n Return the updated combination during recursion process. \r\n combination_list_total: Multi-dimentional list of int. \r\n Store all possible combinations recursively generated by the function.\r\n \"\"\"" ]
[ { "param": "neuron_num_options_list", "type": null }, { "param": "layer_num", "type": null }, { "param": "combination_list_temp", "type": null }, { "param": "combination_list_total", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "neuron_num_options_list", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "layer_num", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "combination_list_temp", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "combination_list_total", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import copy def combinationRecursion(neuron_num_options_list, layer_num, combination_list_temp, combination_list_total): for item in neuron_num_options_list: combination_list_temp.append(item) if len(combination_list_temp) >= layer_num: combination_list_total.append(copy.deepcopy(combination_list_temp)) combination_list_temp = copy.deepcopy(combination_list_temp[:-1]) else: combination_list_temp, combination_list_total = combinationRecursion(neuron_num_options_list, layer_num, combination_list_temp, combination_list_total) combination_list_temp = copy.deepcopy(combination_list_temp[:-1]) return combination_list_temp, combination_list_total
609,881
418
bb82fab13e0ca0761e34b840365b4323caf23568
motional/nuplan-devkit
nuplan/database/nuplan_db/splitters.py
[ "Apache-2.0" ]
Python
_set_location_splits
None
def _set_location_splits( split2samples: DefaultDict[str, List[Sample]], db: NuPlanDB, core_splits_names: List[str] ) -> None: """ Populates split2samples with splits by region and country done on top of core splits. For example: "train" -> "train", "train.United_States", "train.bs", , "train.lv", "train.ptc", "train.Singapore", "train.sg". :param split2samples: Main dictionary containing a mapping from split name to its corresponding data. The data is given as a list of samples. This function assumes core splits already exists (e.g. "train", "val, "test"). :param db: NuPlanDB. :param core_splits_names: Split names on which the location splits should be done. (e.g. "train", "val, "test"). """ for split_name in core_splits_names: region_accumulator = [] for region in db.regions: region_split_name = split_name + '.' + region country_split_name = split_name + '.' + db.country(region) split2samples[region_split_name] = [ rec for rec in split2samples[split_name] if rec.extraction.log.location in db.locations(region) ] if country_split_name not in split2samples: split2samples[country_split_name] = [] split2samples[country_split_name] += split2samples[region_split_name] region_accumulator += split2samples[region_split_name] # Assert that regions covered all samples. assert set(region_accumulator) == set(split2samples[split_name])
Populates split2samples with splits by region and country done on top of core splits. For example: "train" -> "train", "train.United_States", "train.bs", , "train.lv", "train.ptc", "train.Singapore", "train.sg". :param split2samples: Main dictionary containing a mapping from split name to its corresponding data. The data is given as a list of samples. This function assumes core splits already exists (e.g. "train", "val, "test"). :param db: NuPlanDB. :param core_splits_names: Split names on which the location splits should be done. (e.g. "train", "val, "test").
Populates split2samples with splits by region and country done on top of core splits.
[ "Populates", "split2samples", "with", "splits", "by", "region", "and", "country", "done", "on", "top", "of", "core", "splits", "." ]
def _set_location_splits( split2samples: DefaultDict[str, List[Sample]], db: NuPlanDB, core_splits_names: List[str] ) -> None: for split_name in core_splits_names: region_accumulator = [] for region in db.regions: region_split_name = split_name + '.' + region country_split_name = split_name + '.' + db.country(region) split2samples[region_split_name] = [ rec for rec in split2samples[split_name] if rec.extraction.log.location in db.locations(region) ] if country_split_name not in split2samples: split2samples[country_split_name] = [] split2samples[country_split_name] += split2samples[region_split_name] region_accumulator += split2samples[region_split_name] assert set(region_accumulator) == set(split2samples[split_name])
[ "def", "_set_location_splits", "(", "split2samples", ":", "DefaultDict", "[", "str", ",", "List", "[", "Sample", "]", "]", ",", "db", ":", "NuPlanDB", ",", "core_splits_names", ":", "List", "[", "str", "]", ")", "->", "None", ":", "for", "split_name", "in", "core_splits_names", ":", "region_accumulator", "=", "[", "]", "for", "region", "in", "db", ".", "regions", ":", "region_split_name", "=", "split_name", "+", "'.'", "+", "region", "country_split_name", "=", "split_name", "+", "'.'", "+", "db", ".", "country", "(", "region", ")", "split2samples", "[", "region_split_name", "]", "=", "[", "rec", "for", "rec", "in", "split2samples", "[", "split_name", "]", "if", "rec", ".", "extraction", ".", "log", ".", "location", "in", "db", ".", "locations", "(", "region", ")", "]", "if", "country_split_name", "not", "in", "split2samples", ":", "split2samples", "[", "country_split_name", "]", "=", "[", "]", "split2samples", "[", "country_split_name", "]", "+=", "split2samples", "[", "region_split_name", "]", "region_accumulator", "+=", "split2samples", "[", "region_split_name", "]", "assert", "set", "(", "region_accumulator", ")", "==", "set", "(", "split2samples", "[", "split_name", "]", ")" ]
Populates split2samples with splits by region and country done on top of core splits.
[ "Populates", "split2samples", "with", "splits", "by", "region", "and", "country", "done", "on", "top", "of", "core", "splits", "." ]
[ "\"\"\"\n Populates split2samples with splits by region and country done on top of core splits.\n\n For example:\n \"train\" -> \"train\", \"train.United_States\", \"train.bs\", , \"train.lv\", \"train.ptc\", \"train.Singapore\", \"train.sg\".\n\n :param split2samples: Main dictionary containing a mapping from split name to its corresponding data. The data is\n given as a list of samples. This function assumes core splits already exists (e.g. \"train\", \"val, \"test\").\n :param db: NuPlanDB.\n :param core_splits_names: Split names on which the location splits should be done. (e.g. \"train\", \"val, \"test\").\n \"\"\"", "# Assert that regions covered all samples." ]
[ { "param": "split2samples", "type": "DefaultDict[str, List[Sample]]" }, { "param": "db", "type": "NuPlanDB" }, { "param": "core_splits_names", "type": "List[str]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "split2samples", "type": "DefaultDict[str, List[Sample]]", "docstring": "Main dictionary containing a mapping from split name to its corresponding data. The data is\ngiven as a list of samples. This function assumes core splits already exists .", "docstring_tokens": [ "Main", "dictionary", "containing", "a", "mapping", "from", "split", "name", "to", "its", "corresponding", "data", ".", "The", "data", "is", "given", "as", "a", "list", "of", "samples", ".", "This", "function", "assumes", "core", "splits", "already", "exists", "." ], "default": null, "is_optional": null }, { "identifier": "db", "type": "NuPlanDB", "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "core_splits_names", "type": "List[str]", "docstring": "Split names on which the location splits should be done.", "docstring_tokens": [ "Split", "names", "on", "which", "the", "location", "splits", "should", "be", "done", "." ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def _set_location_splits( split2samples: DefaultDict[str, List[Sample]], db: NuPlanDB, core_splits_names: List[str] ) -> None: for split_name in core_splits_names: region_accumulator = [] for region in db.regions: region_split_name = split_name + '.' + region country_split_name = split_name + '.' + db.country(region) split2samples[region_split_name] = [ rec for rec in split2samples[split_name] if rec.extraction.log.location in db.locations(region) ] if country_split_name not in split2samples: split2samples[country_split_name] = [] split2samples[country_split_name] += split2samples[region_split_name] region_accumulator += split2samples[region_split_name] assert set(region_accumulator) == set(split2samples[split_name])
609,883
785
d2ca3de2589fd5ff18ebd273e770335616f66368
Strassengezwitscher/Crowdgezwitscher
crowdgezwitscher/twitter/migrations/0006_auto_20170408_2226.py
[ "MIT" ]
Python
forwards_func
null
def forwards_func(apps, schema_editor): """ Convert Tweet's and TwitterAccount's fields storing ID values to fit UnsignedBigIntegerField. This applies to Tweet's tweet_id and TwitterAccount's account_id and last_known_tweet_id. Do so by substracting 2^63 to have full 64-bit value range. """ Tweet = apps.get_model('twitter', 'Tweet') TwitterAccount = apps.get_model('twitter', 'TwitterAccount') db_alias = schema_editor.connection.alias for tweet in Tweet.objects.using(db_alias).all(): tweet.tweet_id = int(tweet.tweet_id) - 2 ** 63 tweet.save() for account in TwitterAccount.objects.using(db_alias).all(): account.account_id = int(account.account_id) - 2 ** 63 if account.last_known_tweet_id == '': account.last_known_tweet_id = 0 - 2 ** 63 else: account.last_known_tweet_id = int(account.last_known_tweet_id) - 2 ** 63 account.save()
Convert Tweet's and TwitterAccount's fields storing ID values to fit UnsignedBigIntegerField. This applies to Tweet's tweet_id and TwitterAccount's account_id and last_known_tweet_id. Do so by substracting 2^63 to have full 64-bit value range.
Convert Tweet's and TwitterAccount's fields storing ID values to fit UnsignedBigIntegerField.
[ "Convert", "Tweet", "'", "s", "and", "TwitterAccount", "'", "s", "fields", "storing", "ID", "values", "to", "fit", "UnsignedBigIntegerField", "." ]
def forwards_func(apps, schema_editor): Tweet = apps.get_model('twitter', 'Tweet') TwitterAccount = apps.get_model('twitter', 'TwitterAccount') db_alias = schema_editor.connection.alias for tweet in Tweet.objects.using(db_alias).all(): tweet.tweet_id = int(tweet.tweet_id) - 2 ** 63 tweet.save() for account in TwitterAccount.objects.using(db_alias).all(): account.account_id = int(account.account_id) - 2 ** 63 if account.last_known_tweet_id == '': account.last_known_tweet_id = 0 - 2 ** 63 else: account.last_known_tweet_id = int(account.last_known_tweet_id) - 2 ** 63 account.save()
[ "def", "forwards_func", "(", "apps", ",", "schema_editor", ")", ":", "Tweet", "=", "apps", ".", "get_model", "(", "'twitter'", ",", "'Tweet'", ")", "TwitterAccount", "=", "apps", ".", "get_model", "(", "'twitter'", ",", "'TwitterAccount'", ")", "db_alias", "=", "schema_editor", ".", "connection", ".", "alias", "for", "tweet", "in", "Tweet", ".", "objects", ".", "using", "(", "db_alias", ")", ".", "all", "(", ")", ":", "tweet", ".", "tweet_id", "=", "int", "(", "tweet", ".", "tweet_id", ")", "-", "2", "**", "63", "tweet", ".", "save", "(", ")", "for", "account", "in", "TwitterAccount", ".", "objects", ".", "using", "(", "db_alias", ")", ".", "all", "(", ")", ":", "account", ".", "account_id", "=", "int", "(", "account", ".", "account_id", ")", "-", "2", "**", "63", "if", "account", ".", "last_known_tweet_id", "==", "''", ":", "account", ".", "last_known_tweet_id", "=", "0", "-", "2", "**", "63", "else", ":", "account", ".", "last_known_tweet_id", "=", "int", "(", "account", ".", "last_known_tweet_id", ")", "-", "2", "**", "63", "account", ".", "save", "(", ")" ]
Convert Tweet's and TwitterAccount's fields storing ID values to fit UnsignedBigIntegerField.
[ "Convert", "Tweet", "'", "s", "and", "TwitterAccount", "'", "s", "fields", "storing", "ID", "values", "to", "fit", "UnsignedBigIntegerField", "." ]
[ "\"\"\"\n Convert Tweet's and TwitterAccount's fields storing ID values to fit UnsignedBigIntegerField.\n\n This applies to Tweet's tweet_id and TwitterAccount's account_id and last_known_tweet_id.\n Do so by substracting 2^63 to have full 64-bit value range.\n \"\"\"" ]
[ { "param": "apps", "type": null }, { "param": "schema_editor", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "apps", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "schema_editor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def forwards_func(apps, schema_editor): Tweet = apps.get_model('twitter', 'Tweet') TwitterAccount = apps.get_model('twitter', 'TwitterAccount') db_alias = schema_editor.connection.alias for tweet in Tweet.objects.using(db_alias).all(): tweet.tweet_id = int(tweet.tweet_id) - 2 ** 63 tweet.save() for account in TwitterAccount.objects.using(db_alias).all(): account.account_id = int(account.account_id) - 2 ** 63 if account.last_known_tweet_id == '': account.last_known_tweet_id = 0 - 2 ** 63 else: account.last_known_tweet_id = int(account.last_known_tweet_id) - 2 ** 63 account.save()
609,884
396
cf0b7e852570d61d06c4b396674fa33543b155ca
xypron/pyrelayctl
relayctl/__init__.py
[ "BSD-2-Clause" ]
Python
disable
<not_specific>
def disable(dev): """ Disables output to the device. Attaches the kernel driver if available. @param dev: device """ if dev.is_kernel_driver_active(0): return # Disable bitbang mode ret = dev.ctrl_transfer(0x40, 0x0b, 0x0000, 0x01, None, 500) if ret < 0: raise RuntimeError("relayctl: failure to disable bitbang mode") try: dev.attach_kernel_driver(0) except: print ("relayctl: could not attach kernel driver")
Disables output to the device. Attaches the kernel driver if available. @param dev: device
Disables output to the device. Attaches the kernel driver if available.
[ "Disables", "output", "to", "the", "device", ".", "Attaches", "the", "kernel", "driver", "if", "available", "." ]
def disable(dev): if dev.is_kernel_driver_active(0): return ret = dev.ctrl_transfer(0x40, 0x0b, 0x0000, 0x01, None, 500) if ret < 0: raise RuntimeError("relayctl: failure to disable bitbang mode") try: dev.attach_kernel_driver(0) except: print ("relayctl: could not attach kernel driver")
[ "def", "disable", "(", "dev", ")", ":", "if", "dev", ".", "is_kernel_driver_active", "(", "0", ")", ":", "return", "ret", "=", "dev", ".", "ctrl_transfer", "(", "0x40", ",", "0x0b", ",", "0x0000", ",", "0x01", ",", "None", ",", "500", ")", "if", "ret", "<", "0", ":", "raise", "RuntimeError", "(", "\"relayctl: failure to disable bitbang mode\"", ")", "try", ":", "dev", ".", "attach_kernel_driver", "(", "0", ")", "except", ":", "print", "(", "\"relayctl: could not attach kernel driver\"", ")" ]
Disables output to the device.
[ "Disables", "output", "to", "the", "device", "." ]
[ "\"\"\"\n\tDisables output to the device.\n\tAttaches the kernel driver if available.\n\n\t@param dev: device\n\t\"\"\"", "# Disable bitbang mode" ]
[ { "param": "dev", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "dev", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": false } ], "outlier_params": [], "others": [] }
def disable(dev): if dev.is_kernel_driver_active(0): return ret = dev.ctrl_transfer(0x40, 0x0b, 0x0000, 0x01, None, 500) if ret < 0: raise RuntimeError("relayctl: failure to disable bitbang mode") try: dev.attach_kernel_driver(0) except: print ("relayctl: could not attach kernel driver")
609,885
46
8bb84fc46382e3757b05b6c28db6db3ead45f516
bobby891018/Semantic-segmentation-with-toy-data
models.py
[ "MIT" ]
Python
red_star
<not_specific>
def red_star(c2): """ The relation between the color1 and color2 in RED stars assuming that the RED stars are 2 times brighter in color2 ---------- c2: flux in color2 ---------- Returns - flux in color1 """ c1 = 0.5*c2 return c1, c2
The relation between the color1 and color2 in RED stars assuming that the RED stars are 2 times brighter in color2 ---------- c2: flux in color2 ---------- Returns - flux in color1
The relation between the color1 and color2 in RED stars assuming that the RED stars are 2 times brighter in color2 flux in color2 Returns flux in color1
[ "The", "relation", "between", "the", "color1", "and", "color2", "in", "RED", "stars", "assuming", "that", "the", "RED", "stars", "are", "2", "times", "brighter", "in", "color2", "flux", "in", "color2", "Returns", "flux", "in", "color1" ]
def red_star(c2): c1 = 0.5*c2 return c1, c2
[ "def", "red_star", "(", "c2", ")", ":", "c1", "=", "0.5", "*", "c2", "return", "c1", ",", "c2" ]
The relation between the color1 and color2 in RED stars assuming that the RED stars are 2 times brighter in color2
[ "The", "relation", "between", "the", "color1", "and", "color2", "in", "RED", "stars", "assuming", "that", "the", "RED", "stars", "are", "2", "times", "brighter", "in", "color2" ]
[ "\"\"\"\n The relation between the color1 and color2 in RED stars\n assuming that the RED stars are 2 times brighter in color2\n ----------\n c2: flux in color2\n ----------\n Returns\n - flux in color1\n \"\"\"" ]
[ { "param": "c2", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "c2", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def red_star(c2): c1 = 0.5*c2 return c1, c2
609,886
473
495f59a7327c055924c4b64c28b83265363b62da
DmitrTRC/LabTraining
PartI/Lab_1_1/PY/Sum_of_Positives.py
[ "Apache-2.0" ]
Python
sum_positive_numbers
<not_specific>
def sum_positive_numbers(n): """ :returns sum of positive numbers """ if n == 0: return 0 else: return n + sum_positive_numbers(n - 1)
:returns sum of positive numbers
:returns sum of positive numbers
[ ":", "returns", "sum", "of", "positive", "numbers" ]
def sum_positive_numbers(n): if n == 0: return 0 else: return n + sum_positive_numbers(n - 1)
[ "def", "sum_positive_numbers", "(", "n", ")", ":", "if", "n", "==", "0", ":", "return", "0", "else", ":", "return", "n", "+", "sum_positive_numbers", "(", "n", "-", "1", ")" ]
:returns sum of positive numbers
[ ":", "returns", "sum", "of", "positive", "numbers" ]
[ "\"\"\"\n :returns sum of positive numbers\n \"\"\"" ]
[ { "param": "n", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "n", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def sum_positive_numbers(n): if n == 0: return 0 else: return n + sum_positive_numbers(n - 1)
609,887
360
c17c39c377a684c160d7aa3c3360e32014d3a707
newsdev/nyt-entity-service
utils.py
[ "Apache-2.0" ]
Python
valid_uuid
<not_specific>
def valid_uuid(possible_uuid): """ Checks that a possible UUID4 string is a valid UUID4. """ regex = re.compile('^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I) match = regex.match(possible_uuid) return bool(match)
Checks that a possible UUID4 string is a valid UUID4.
Checks that a possible UUID4 string is a valid UUID4.
[ "Checks", "that", "a", "possible", "UUID4", "string", "is", "a", "valid", "UUID4", "." ]
def valid_uuid(possible_uuid): regex = re.compile('^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I) match = regex.match(possible_uuid) return bool(match)
[ "def", "valid_uuid", "(", "possible_uuid", ")", ":", "regex", "=", "re", ".", "compile", "(", "'^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\\Z'", ",", "re", ".", "I", ")", "match", "=", "regex", ".", "match", "(", "possible_uuid", ")", "return", "bool", "(", "match", ")" ]
Checks that a possible UUID4 string is a valid UUID4.
[ "Checks", "that", "a", "possible", "UUID4", "string", "is", "a", "valid", "UUID4", "." ]
[ "\"\"\"\n Checks that a possible UUID4 string is a valid UUID4.\n \"\"\"" ]
[ { "param": "possible_uuid", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "possible_uuid", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import re def valid_uuid(possible_uuid): regex = re.compile('^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I) match = regex.match(possible_uuid) return bool(match)
609,888
69
27f62ad74407ca59b6846ef94b423ef627d891e6
RAIRLab/PAGIapi-python
pagi_api.py
[ "MIT" ]
Python
__process_vision
<not_specific>
def __process_vision(response, column_length): """ Internal method to process returned vision repsonse. Splits the response into a list of lists where each inner list is the length of specified column_length. :param response: :param column_length: :return: """ vision = list() current = list() for j in range(1, len(response)): if (j - 1) % column_length == 0: if len(current) > 0: vision.append(current) current = list() current.append(response[j]) vision.append(current) return vision
Internal method to process returned vision repsonse. Splits the response into a list of lists where each inner list is the length of specified column_length. :param response: :param column_length: :return:
Internal method to process returned vision repsonse. Splits the response into a list of lists where each inner list is the length of specified column_length.
[ "Internal", "method", "to", "process", "returned", "vision", "repsonse", ".", "Splits", "the", "response", "into", "a", "list", "of", "lists", "where", "each", "inner", "list", "is", "the", "length", "of", "specified", "column_length", "." ]
def __process_vision(response, column_length): vision = list() current = list() for j in range(1, len(response)): if (j - 1) % column_length == 0: if len(current) > 0: vision.append(current) current = list() current.append(response[j]) vision.append(current) return vision
[ "def", "__process_vision", "(", "response", ",", "column_length", ")", ":", "vision", "=", "list", "(", ")", "current", "=", "list", "(", ")", "for", "j", "in", "range", "(", "1", ",", "len", "(", "response", ")", ")", ":", "if", "(", "j", "-", "1", ")", "%", "column_length", "==", "0", ":", "if", "len", "(", "current", ")", ">", "0", ":", "vision", ".", "append", "(", "current", ")", "current", "=", "list", "(", ")", "current", ".", "append", "(", "response", "[", "j", "]", ")", "vision", ".", "append", "(", "current", ")", "return", "vision" ]
Internal method to process returned vision repsonse.
[ "Internal", "method", "to", "process", "returned", "vision", "repsonse", "." ]
[ "\"\"\"\n Internal method to process returned vision repsonse. Splits the response into a list of\n lists where each inner list is the length of specified column_length.\n :param response:\n :param column_length:\n :return:\n \"\"\"" ]
[ { "param": "response", "type": null }, { "param": "column_length", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "response", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "column_length", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def __process_vision(response, column_length): vision = list() current = list() for j in range(1, len(response)): if (j - 1) % column_length == 0: if len(current) > 0: vision.append(current) current = list() current.append(response[j]) vision.append(current) return vision
609,889
155
b52ed92fc08424e266b9fa85733ec99b2827c78a
greenwoodms06/raven
framework/Runners/SharedMemoryRunner.py
[ "Apache-2.0" ]
Python
_asyncRaise
null
def _asyncRaise(tid, exceptionType): """ Raises an exception in the threads with id tid @ In, tid, integer, this variable represents the id of the thread to raise an exception @ In, exceptionType, Exception, the type of exception to throw @ Out, None """ if not inspect.isclass(exceptionType): raise TypeError("Only types can be raised (not instances)") res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exceptionType)) if res == 0: raise ValueError("invalid thread id") elif res != 1: # "if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect" ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) raise SystemError("PyThreadState_SetAsyncExc failed")
Raises an exception in the threads with id tid @ In, tid, integer, this variable represents the id of the thread to raise an exception @ In, exceptionType, Exception, the type of exception to throw @ Out, None
Raises an exception in the threads with id tid @ In, tid, integer, this variable represents the id of the thread to raise an exception @ In, exceptionType, Exception, the type of exception to throw @ Out, None
[ "Raises", "an", "exception", "in", "the", "threads", "with", "id", "tid", "@", "In", "tid", "integer", "this", "variable", "represents", "the", "id", "of", "the", "thread", "to", "raise", "an", "exception", "@", "In", "exceptionType", "Exception", "the", "type", "of", "exception", "to", "throw", "@", "Out", "None" ]
def _asyncRaise(tid, exceptionType): if not inspect.isclass(exceptionType): raise TypeError("Only types can be raised (not instances)") res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exceptionType)) if res == 0: raise ValueError("invalid thread id") elif res != 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) raise SystemError("PyThreadState_SetAsyncExc failed")
[ "def", "_asyncRaise", "(", "tid", ",", "exceptionType", ")", ":", "if", "not", "inspect", ".", "isclass", "(", "exceptionType", ")", ":", "raise", "TypeError", "(", "\"Only types can be raised (not instances)\"", ")", "res", "=", "ctypes", ".", "pythonapi", ".", "PyThreadState_SetAsyncExc", "(", "tid", ",", "ctypes", ".", "py_object", "(", "exceptionType", ")", ")", "if", "res", "==", "0", ":", "raise", "ValueError", "(", "\"invalid thread id\"", ")", "elif", "res", "!=", "1", ":", "ctypes", ".", "pythonapi", ".", "PyThreadState_SetAsyncExc", "(", "tid", ",", "0", ")", "raise", "SystemError", "(", "\"PyThreadState_SetAsyncExc failed\"", ")" ]
Raises an exception in the threads with id tid @ In, tid, integer, this variable represents the id of the thread to raise an exception @ In, exceptionType, Exception, the type of exception to throw @ Out, None
[ "Raises", "an", "exception", "in", "the", "threads", "with", "id", "tid", "@", "In", "tid", "integer", "this", "variable", "represents", "the", "id", "of", "the", "thread", "to", "raise", "an", "exception", "@", "In", "exceptionType", "Exception", "the", "type", "of", "exception", "to", "throw", "@", "Out", "None" ]
[ "\"\"\"\n Raises an exception in the threads with id tid\n @ In, tid, integer, this variable represents the id of the thread to raise an exception\n @ In, exceptionType, Exception, the type of exception to throw\n @ Out, None\n \"\"\"", "# \"if it returns a number greater than one, you're in trouble,", "# and you should call it again with exc=NULL to revert the effect\"" ]
[ { "param": "tid", "type": null }, { "param": "exceptionType", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "tid", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "exceptionType", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import inspect import ctypes def _asyncRaise(tid, exceptionType): if not inspect.isclass(exceptionType): raise TypeError("Only types can be raised (not instances)") res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exceptionType)) if res == 0: raise ValueError("invalid thread id") elif res != 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) raise SystemError("PyThreadState_SetAsyncExc failed")
609,890
383
f6776d2cdfb6ebddc939ca5604ac984f2af10415
snelliott/automol
automol/etrans/combine.py
[ "Apache-2.0" ]
Python
sigma
<not_specific>
def sigma(ab_sig, bb_sig): """ Perform combining rule to get A+A sigma parameter. Output units are whatever those are of the input parameters. :param ab_sig: A+B sigma parameter :type ab_sig: float :param ab_sig: B+B sigma parameter :type ab_sig: float :rtype: float """ if ab_sig is not None and bb_sig is not None: aa_sig = 2.0 * ab_sig - bb_sig else: aa_sig = None return aa_sig
Perform combining rule to get A+A sigma parameter. Output units are whatever those are of the input parameters. :param ab_sig: A+B sigma parameter :type ab_sig: float :param ab_sig: B+B sigma parameter :type ab_sig: float :rtype: float
Perform combining rule to get A+A sigma parameter. Output units are whatever those are of the input parameters.
[ "Perform", "combining", "rule", "to", "get", "A", "+", "A", "sigma", "parameter", ".", "Output", "units", "are", "whatever", "those", "are", "of", "the", "input", "parameters", "." ]
def sigma(ab_sig, bb_sig): if ab_sig is not None and bb_sig is not None: aa_sig = 2.0 * ab_sig - bb_sig else: aa_sig = None return aa_sig
[ "def", "sigma", "(", "ab_sig", ",", "bb_sig", ")", ":", "if", "ab_sig", "is", "not", "None", "and", "bb_sig", "is", "not", "None", ":", "aa_sig", "=", "2.0", "*", "ab_sig", "-", "bb_sig", "else", ":", "aa_sig", "=", "None", "return", "aa_sig" ]
Perform combining rule to get A+A sigma parameter.
[ "Perform", "combining", "rule", "to", "get", "A", "+", "A", "sigma", "parameter", "." ]
[ "\"\"\" Perform combining rule to get A+A sigma parameter.\n Output units are whatever those are of the input parameters.\n\n :param ab_sig: A+B sigma parameter\n :type ab_sig: float\n :param ab_sig: B+B sigma parameter\n :type ab_sig: float\n :rtype: float\n \"\"\"" ]
[ { "param": "ab_sig", "type": null }, { "param": "bb_sig", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "float" } ], "raises": [], "params": [ { "identifier": "ab_sig", "type": null, "docstring": "B+B sigma parameter", "docstring_tokens": [ "B", "+", "B", "sigma", "parameter" ], "default": null, "is_optional": null }, { "identifier": "bb_sig", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def sigma(ab_sig, bb_sig): if ab_sig is not None and bb_sig is not None: aa_sig = 2.0 * ab_sig - bb_sig else: aa_sig = None return aa_sig
609,891
405
74cc2ee46326dc29a5f3d824a6686a6b75c64c02
curaloucura/Enso-Ubuntu
ensocommands/random.py
[ "BSD-3-Clause" ]
Python
cmd_footnote
null
def cmd_footnote(ensoapi): "Wrap text in my in-HTML footnote style" seldict = ensoapi.get_selection() text = seldict.get("text", "") html = seldict.get("html", text) if not text: ensoapi.display_message("No selection!") else: result = '<span style="color:red" title="%s">*</span>' % html ensoapi.set_selection({ "text":result })
Wrap text in my in-HTML footnote style
Wrap text in my in-HTML footnote style
[ "Wrap", "text", "in", "my", "in", "-", "HTML", "footnote", "style" ]
def cmd_footnote(ensoapi): seldict = ensoapi.get_selection() text = seldict.get("text", "") html = seldict.get("html", text) if not text: ensoapi.display_message("No selection!") else: result = '<span style="color:red" title="%s">*</span>' % html ensoapi.set_selection({ "text":result })
[ "def", "cmd_footnote", "(", "ensoapi", ")", ":", "seldict", "=", "ensoapi", ".", "get_selection", "(", ")", "text", "=", "seldict", ".", "get", "(", "\"text\"", ",", "\"\"", ")", "html", "=", "seldict", ".", "get", "(", "\"html\"", ",", "text", ")", "if", "not", "text", ":", "ensoapi", ".", "display_message", "(", "\"No selection!\"", ")", "else", ":", "result", "=", "'<span style=\"color:red\" title=\"%s\">*</span>'", "%", "html", "ensoapi", ".", "set_selection", "(", "{", "\"text\"", ":", "result", "}", ")" ]
Wrap text in my in-HTML footnote style
[ "Wrap", "text", "in", "my", "in", "-", "HTML", "footnote", "style" ]
[ "\"Wrap text in my in-HTML footnote style\"" ]
[ { "param": "ensoapi", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ensoapi", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def cmd_footnote(ensoapi): seldict = ensoapi.get_selection() text = seldict.get("text", "") html = seldict.get("html", text) if not text: ensoapi.display_message("No selection!") else: result = '<span style="color:red" title="%s">*</span>' % html ensoapi.set_selection({ "text":result })
609,892
140
4e33b62fe839a9f7526c5085d85aec6b0c68c39f
duxenmx/e_paper_dashboard
modules/d_functions.py
[ "MIT" ]
Python
time_in_range
<not_specific>
def time_in_range(start_hour, end_hour): """Return true if x is in the range [start, end]""" start = datetime.time((start_hour), 0, 0) end = datetime.time((end_hour), 0, 0) current_hour = datetime.datetime.now().strftime('%H') current_min = datetime.datetime.now().strftime('%M') current_sec = datetime.datetime.now().strftime('%S') x = datetime.time(int(current_hour), int(current_min), int(current_sec)) if start <= end: return start <= x <= end else: return start <= x or x <= end
Return true if x is in the range [start, end]
Return true if x is in the range [start, end]
[ "Return", "true", "if", "x", "is", "in", "the", "range", "[", "start", "end", "]" ]
def time_in_range(start_hour, end_hour): start = datetime.time((start_hour), 0, 0) end = datetime.time((end_hour), 0, 0) current_hour = datetime.datetime.now().strftime('%H') current_min = datetime.datetime.now().strftime('%M') current_sec = datetime.datetime.now().strftime('%S') x = datetime.time(int(current_hour), int(current_min), int(current_sec)) if start <= end: return start <= x <= end else: return start <= x or x <= end
[ "def", "time_in_range", "(", "start_hour", ",", "end_hour", ")", ":", "start", "=", "datetime", ".", "time", "(", "(", "start_hour", ")", ",", "0", ",", "0", ")", "end", "=", "datetime", ".", "time", "(", "(", "end_hour", ")", ",", "0", ",", "0", ")", "current_hour", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%H'", ")", "current_min", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%M'", ")", "current_sec", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%S'", ")", "x", "=", "datetime", ".", "time", "(", "int", "(", "current_hour", ")", ",", "int", "(", "current_min", ")", ",", "int", "(", "current_sec", ")", ")", "if", "start", "<=", "end", ":", "return", "start", "<=", "x", "<=", "end", "else", ":", "return", "start", "<=", "x", "or", "x", "<=", "end" ]
Return true if x is in the range [start, end]
[ "Return", "true", "if", "x", "is", "in", "the", "range", "[", "start", "end", "]" ]
[ "\"\"\"Return true if x is in the range [start, end]\"\"\"" ]
[ { "param": "start_hour", "type": null }, { "param": "end_hour", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "start_hour", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "end_hour", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import datetime def time_in_range(start_hour, end_hour): start = datetime.time((start_hour), 0, 0) end = datetime.time((end_hour), 0, 0) current_hour = datetime.datetime.now().strftime('%H') current_min = datetime.datetime.now().strftime('%M') current_sec = datetime.datetime.now().strftime('%S') x = datetime.time(int(current_hour), int(current_min), int(current_sec)) if start <= end: return start <= x <= end else: return start <= x or x <= end
609,893
264
cb54236a90dfded7036fb8beb3d58bb06a10ab08
canvasslabs/canvass_for_security-dependency_checker
vuln_search/find_vulns_maven.py
[ "Apache-2.0" ]
Python
_check_coordinate_length
<not_specific>
def _check_coordinate_length(line): ''' Makes sure that the coordinate length is at least 4 to include group, artifact, type, and version name ''' if len(line.split(":")) < 4: return False else: return True
Makes sure that the coordinate length is at least 4 to include group, artifact, type, and version name
Makes sure that the coordinate length is at least 4 to include group, artifact, type, and version name
[ "Makes", "sure", "that", "the", "coordinate", "length", "is", "at", "least", "4", "to", "include", "group", "artifact", "type", "and", "version", "name" ]
def _check_coordinate_length(line): if len(line.split(":")) < 4: return False else: return True
[ "def", "_check_coordinate_length", "(", "line", ")", ":", "if", "len", "(", "line", ".", "split", "(", "\":\"", ")", ")", "<", "4", ":", "return", "False", "else", ":", "return", "True" ]
Makes sure that the coordinate length is at least 4 to include group, artifact, type, and version name
[ "Makes", "sure", "that", "the", "coordinate", "length", "is", "at", "least", "4", "to", "include", "group", "artifact", "type", "and", "version", "name" ]
[ "'''\n Makes sure that the coordinate length is at least 4 to\n include group, artifact, type, and version name\n '''" ]
[ { "param": "line", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "line", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def _check_coordinate_length(line): if len(line.split(":")) < 4: return False else: return True
609,894
561
534970c95b7d377a58842aaf22e1f677e13d5266
jessicavers/Savu
savu/core/utils.py
[ "Apache-2.0" ]
Python
logfunction
<not_specific>
def logfunction(func): """ Decorator to add logging information around calls for use with . """ def _wrapper(*args, **kwds): logging.info("Start::%s:%s", func.__module__, func.__name__) returnval = func(*args, **kwds) logging.info("Finish::%s:%s", func.__module__, func.__name__) return returnval return _wrapper
Decorator to add logging information around calls for use with .
Decorator to add logging information around calls for use with .
[ "Decorator", "to", "add", "logging", "information", "around", "calls", "for", "use", "with", "." ]
def logfunction(func): def _wrapper(*args, **kwds): logging.info("Start::%s:%s", func.__module__, func.__name__) returnval = func(*args, **kwds) logging.info("Finish::%s:%s", func.__module__, func.__name__) return returnval return _wrapper
[ "def", "logfunction", "(", "func", ")", ":", "def", "_wrapper", "(", "*", "args", ",", "**", "kwds", ")", ":", "logging", ".", "info", "(", "\"Start::%s:%s\"", ",", "func", ".", "__module__", ",", "func", ".", "__name__", ")", "returnval", "=", "func", "(", "*", "args", ",", "**", "kwds", ")", "logging", ".", "info", "(", "\"Finish::%s:%s\"", ",", "func", ".", "__module__", ",", "func", ".", "__name__", ")", "return", "returnval", "return", "_wrapper" ]
Decorator to add logging information around calls for use with .
[ "Decorator", "to", "add", "logging", "information", "around", "calls", "for", "use", "with", "." ]
[ "\"\"\" Decorator to add logging information around calls for use with . \"\"\"" ]
[ { "param": "func", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "func", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import logging def logfunction(func): def _wrapper(*args, **kwds): logging.info("Start::%s:%s", func.__module__, func.__name__) returnval = func(*args, **kwds) logging.info("Finish::%s:%s", func.__module__, func.__name__) return returnval return _wrapper
609,895
435
c861ca887a04b558f0360cb765396a9fc0ddc259
boyeah/cognite-sdk-python
cognite/preprocessing.py
[ "Apache-2.0" ]
Python
remove_nan_columns
<not_specific>
def remove_nan_columns(dataframe): """Removes columns of data frame where any value is NaN. Args: dataframe (pandas.DataFrame): Input dataframe. Returns: tuple: tuple containing: pandas.DataFrame: Dataframe with columns containing NaN values removed. numpy.array: Array of bools indicating which columns were kept. """ df_copy = dataframe.set_index("timestamp") selected_columns_mask = df_copy.notnull().all().values return dataframe.dropna(axis=1, how="any"), selected_columns_mask
Removes columns of data frame where any value is NaN. Args: dataframe (pandas.DataFrame): Input dataframe. Returns: tuple: tuple containing: pandas.DataFrame: Dataframe with columns containing NaN values removed. numpy.array: Array of bools indicating which columns were kept.
Removes columns of data frame where any value is NaN.
[ "Removes", "columns", "of", "data", "frame", "where", "any", "value", "is", "NaN", "." ]
def remove_nan_columns(dataframe): df_copy = dataframe.set_index("timestamp") selected_columns_mask = df_copy.notnull().all().values return dataframe.dropna(axis=1, how="any"), selected_columns_mask
[ "def", "remove_nan_columns", "(", "dataframe", ")", ":", "df_copy", "=", "dataframe", ".", "set_index", "(", "\"timestamp\"", ")", "selected_columns_mask", "=", "df_copy", ".", "notnull", "(", ")", ".", "all", "(", ")", ".", "values", "return", "dataframe", ".", "dropna", "(", "axis", "=", "1", ",", "how", "=", "\"any\"", ")", ",", "selected_columns_mask" ]
Removes columns of data frame where any value is NaN.
[ "Removes", "columns", "of", "data", "frame", "where", "any", "value", "is", "NaN", "." ]
[ "\"\"\"Removes columns of data frame where any value is NaN.\n\n Args:\n dataframe (pandas.DataFrame): Input dataframe.\n\n Returns:\n tuple: tuple containing:\n pandas.DataFrame: Dataframe with columns containing NaN values removed.\n numpy.array: Array of bools indicating which columns were kept.\n \"\"\"" ]
[ { "param": "dataframe", "type": null } ]
{ "returns": [ { "docstring": "tuple containing:\npandas.DataFrame: Dataframe with columns containing NaN values removed.\nnumpy.array: Array of bools indicating which columns were kept.", "docstring_tokens": [ "tuple", "containing", ":", "pandas", ".", "DataFrame", ":", "Dataframe", "with", "columns", "containing", "NaN", "values", "removed", ".", "numpy", ".", "array", ":", "Array", "of", "bools", "indicating", "which", "columns", "were", "kept", "." ], "type": "tuple" } ], "raises": [], "params": [ { "identifier": "dataframe", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": false } ], "outlier_params": [], "others": [] }
def remove_nan_columns(dataframe): df_copy = dataframe.set_index("timestamp") selected_columns_mask = df_copy.notnull().all().values return dataframe.dropna(axis=1, how="any"), selected_columns_mask
609,896
635
aa5414007f15a5f7da5b910f84abfb96c5a5461c
liu-yushan/TLogic
mycode/temporal_walk.py
[ "Apache-2.0" ]
Python
store_edges
<not_specific>
def store_edges(quads): """ Store all edges for each relation. Parameters: quads (np.ndarray): indices of quadruples Returns: edges (dict): edges for each relation """ edges = dict() relations = list(set(quads[:, 1])) for rel in relations: edges[rel] = quads[quads[:, 1] == rel] return edges
Store all edges for each relation. Parameters: quads (np.ndarray): indices of quadruples Returns: edges (dict): edges for each relation
Store all edges for each relation.
[ "Store", "all", "edges", "for", "each", "relation", "." ]
def store_edges(quads): edges = dict() relations = list(set(quads[:, 1])) for rel in relations: edges[rel] = quads[quads[:, 1] == rel] return edges
[ "def", "store_edges", "(", "quads", ")", ":", "edges", "=", "dict", "(", ")", "relations", "=", "list", "(", "set", "(", "quads", "[", ":", ",", "1", "]", ")", ")", "for", "rel", "in", "relations", ":", "edges", "[", "rel", "]", "=", "quads", "[", "quads", "[", ":", ",", "1", "]", "==", "rel", "]", "return", "edges" ]
Store all edges for each relation.
[ "Store", "all", "edges", "for", "each", "relation", "." ]
[ "\"\"\"\n Store all edges for each relation.\n\n Parameters:\n quads (np.ndarray): indices of quadruples\n\n Returns:\n edges (dict): edges for each relation\n \"\"\"" ]
[ { "param": "quads", "type": null } ]
{ "returns": [ { "docstring": "edges (dict): edges for each relation", "docstring_tokens": [ "edges", "(", "dict", ")", ":", "edges", "for", "each", "relation" ], "type": null } ], "raises": [], "params": [ { "identifier": "quads", "type": null, "docstring": "indices of quadruples", "docstring_tokens": [ "indices", "of", "quadruples" ], "default": null, "is_optional": false } ], "outlier_params": [], "others": [] }
def store_edges(quads): edges = dict() relations = list(set(quads[:, 1])) for rel in relations: edges[rel] = quads[quads[:, 1] == rel] return edges
609,897
376
af67d23652996f45d86d1a436b66eaddd9de4529
boghison/SubDaap
subdaap/utils.py
[ "MIT" ]
Python
chunks
null
def chunks(iterator, size): """ Chunk an iterator into blocks of fixed size. Only the last block can be smaller than the specified size. :param iterator iterator: Iterator to exhaust. :param int size: Size of blocks to yield. """ items = [None] * size count = 0 for item in iterator: items[count] = item count += 1 if count == size: yield items count = 0 # Yield remaining yield items[:count]
Chunk an iterator into blocks of fixed size. Only the last block can be smaller than the specified size. :param iterator iterator: Iterator to exhaust. :param int size: Size of blocks to yield.
Chunk an iterator into blocks of fixed size. Only the last block can be smaller than the specified size.
[ "Chunk", "an", "iterator", "into", "blocks", "of", "fixed", "size", ".", "Only", "the", "last", "block", "can", "be", "smaller", "than", "the", "specified", "size", "." ]
def chunks(iterator, size): items = [None] * size count = 0 for item in iterator: items[count] = item count += 1 if count == size: yield items count = 0 yield items[:count]
[ "def", "chunks", "(", "iterator", ",", "size", ")", ":", "items", "=", "[", "None", "]", "*", "size", "count", "=", "0", "for", "item", "in", "iterator", ":", "items", "[", "count", "]", "=", "item", "count", "+=", "1", "if", "count", "==", "size", ":", "yield", "items", "count", "=", "0", "yield", "items", "[", ":", "count", "]" ]
Chunk an iterator into blocks of fixed size.
[ "Chunk", "an", "iterator", "into", "blocks", "of", "fixed", "size", "." ]
[ "\"\"\"\n Chunk an iterator into blocks of fixed size. Only the last block can be\n smaller than the specified size.\n\n :param iterator iterator: Iterator to exhaust.\n :param int size: Size of blocks to yield.\n \"\"\"", "# Yield remaining" ]
[ { "param": "iterator", "type": null }, { "param": "size", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "iterator", "type": null, "docstring": "Iterator to exhaust.", "docstring_tokens": [ "Iterator", "to", "exhaust", "." ], "default": null, "is_optional": false }, { "identifier": "size", "type": null, "docstring": "Size of blocks to yield.", "docstring_tokens": [ "Size", "of", "blocks", "to", "yield", "." ], "default": null, "is_optional": false } ], "outlier_params": [], "others": [] }
def chunks(iterator, size): items = [None] * size count = 0 for item in iterator: items[count] = item count += 1 if count == size: yield items count = 0 yield items[:count]
609,898
105
37aeddae19976563d42fc9ec380c985e3925a626
rafaeldcampbell/fuzzylogic
src/fuzzylogic/combinators.py
[ "MIT" ]
Python
lambda_op
<not_specific>
def lambda_op(l): """A 'compensatoric' operator, combining AND with OR by a weighing factor l. This complicates matters a little, since all combinators promise to just take 2 functions as arguments, so we parametrize this with l. """ # TODO: Expand.. assert (0 <= l <= 1) def e(a, b): def f(z): x, y = a(z), b(z) return l * (x * y) + (1 - l) * (x + y - x * y) return f return e
A 'compensatoric' operator, combining AND with OR by a weighing factor l. This complicates matters a little, since all combinators promise to just take 2 functions as arguments, so we parametrize this with l.
A 'compensatoric' operator, combining AND with OR by a weighing factor l. This complicates matters a little, since all combinators promise to just take 2 functions as arguments, so we parametrize this with l.
[ "A", "'", "compensatoric", "'", "operator", "combining", "AND", "with", "OR", "by", "a", "weighing", "factor", "l", ".", "This", "complicates", "matters", "a", "little", "since", "all", "combinators", "promise", "to", "just", "take", "2", "functions", "as", "arguments", "so", "we", "parametrize", "this", "with", "l", "." ]
def lambda_op(l): assert (0 <= l <= 1) def e(a, b): def f(z): x, y = a(z), b(z) return l * (x * y) + (1 - l) * (x + y - x * y) return f return e
[ "def", "lambda_op", "(", "l", ")", ":", "assert", "(", "0", "<=", "l", "<=", "1", ")", "def", "e", "(", "a", ",", "b", ")", ":", "def", "f", "(", "z", ")", ":", "x", ",", "y", "=", "a", "(", "z", ")", ",", "b", "(", "z", ")", "return", "l", "*", "(", "x", "*", "y", ")", "+", "(", "1", "-", "l", ")", "*", "(", "x", "+", "y", "-", "x", "*", "y", ")", "return", "f", "return", "e" ]
A 'compensatoric' operator, combining AND with OR by a weighing factor l. This complicates matters a little, since all combinators promise to just take 2 functions as arguments, so we parametrize this with l.
[ "A", "'", "compensatoric", "'", "operator", "combining", "AND", "with", "OR", "by", "a", "weighing", "factor", "l", ".", "This", "complicates", "matters", "a", "little", "since", "all", "combinators", "promise", "to", "just", "take", "2", "functions", "as", "arguments", "so", "we", "parametrize", "this", "with", "l", "." ]
[ "\"\"\"A 'compensatoric' operator, combining AND with OR by a weighing factor l.\n \n This complicates matters a little, since all combinators promise to just take \n 2 functions as arguments, so we parametrize this with l.\n \"\"\"", "# TODO: Expand.." ]
[ { "param": "l", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "l", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def lambda_op(l): assert (0 <= l <= 1) def e(a, b): def f(z): x, y = a(z), b(z) return l * (x * y) + (1 - l) * (x + y - x * y) return f return e
609,899
365
454e8684ba21291d3981cd1db495105f910b45be
Klebert-Engineering/deep-spell-9
modules/deepspell/models/modelbase.py
[ "MIT" ]
Python
_print_progress
null
def _print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=10): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) bar_length - Optional : character length of bar (Int) """ str_format = "{0:." + str(decimals) + "f}" percents = str_format.format(100 * (iteration / float(total))) filled_length = int(round(bar_length * iteration / float(total))) bar = '#' * filled_length + '-' * (bar_length - filled_length) sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)), if iteration == total: sys.stdout.write('\n') sys.stdout.flush()
Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) bar_length - Optional : character length of bar (Int)
Call in a loop to create terminal progress bar
[ "Call", "in", "a", "loop", "to", "create", "terminal", "progress", "bar" ]
def _print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=10): str_format = "{0:." + str(decimals) + "f}" percents = str_format.format(100 * (iteration / float(total))) filled_length = int(round(bar_length * iteration / float(total))) bar = '#' * filled_length + '-' * (bar_length - filled_length) sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)), if iteration == total: sys.stdout.write('\n') sys.stdout.flush()
[ "def", "_print_progress", "(", "iteration", ",", "total", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ",", "decimals", "=", "1", ",", "bar_length", "=", "10", ")", ":", "str_format", "=", "\"{0:.\"", "+", "str", "(", "decimals", ")", "+", "\"f}\"", "percents", "=", "str_format", ".", "format", "(", "100", "*", "(", "iteration", "/", "float", "(", "total", ")", ")", ")", "filled_length", "=", "int", "(", "round", "(", "bar_length", "*", "iteration", "/", "float", "(", "total", ")", ")", ")", "bar", "=", "'#'", "*", "filled_length", "+", "'-'", "*", "(", "bar_length", "-", "filled_length", ")", "sys", ".", "stdout", ".", "write", "(", "'\\r%s |%s| %s%s %s'", "%", "(", "prefix", ",", "bar", ",", "percents", ",", "'%'", ",", "suffix", ")", ")", ",", "if", "iteration", "==", "total", ":", "sys", ".", "stdout", ".", "write", "(", "'\\n'", ")", "sys", ".", "stdout", ".", "flush", "(", ")" ]
Call in a loop to create terminal progress bar
[ "Call", "in", "a", "loop", "to", "create", "terminal", "progress", "bar" ]
[ "\"\"\"\n Call in a loop to create terminal progress bar\n @params:\n iteration - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix - Optional : prefix string (Str)\n suffix - Optional : suffix string (Str)\n decimals - Optional : positive number of decimals in percent complete (Int)\n bar_length - Optional : character length of bar (Int)\n \"\"\"" ]
[ { "param": "iteration", "type": null }, { "param": "total", "type": null }, { "param": "prefix", "type": null }, { "param": "suffix", "type": null }, { "param": "decimals", "type": null }, { "param": "bar_length", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "iteration", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "total", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "prefix", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "suffix", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "decimals", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "bar_length", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "params", "docstring": "iteration - Required : current iteration (Int)\ntotal - Required : total iterations (Int)\nprefix - Optional : prefix string (Str)\nsuffix - Optional : suffix string (Str)\ndecimals - Optional : positive number of decimals in percent complete (Int)\nbar_length - Optional : character length of bar (Int)", "docstring_tokens": [ "iteration", "-", "Required", ":", "current", "iteration", "(", "Int", ")", "total", "-", "Required", ":", "total", "iterations", "(", "Int", ")", "prefix", "-", "Optional", ":", "prefix", "string", "(", "Str", ")", "suffix", "-", "Optional", ":", "suffix", "string", "(", "Str", ")", "decimals", "-", "Optional", ":", "positive", "number", "of", "decimals", "in", "percent", "complete", "(", "Int", ")", "bar_length", "-", "Optional", ":", "character", "length", "of", "bar", "(", "Int", ")" ] } ] }
import sys def _print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=10): str_format = "{0:." + str(decimals) + "f}" percents = str_format.format(100 * (iteration / float(total))) filled_length = int(round(bar_length * iteration / float(total))) bar = '#' * filled_length + '-' * (bar_length - filled_length) sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)), if iteration == total: sys.stdout.write('\n') sys.stdout.flush()
609,900
636
5088fe0c66151a7fba354c06b82e3c4b1526fa0a
hansd410/mnemonic
script/preprocess_backup_v2.py
[ "BSD-3-Clause" ]
Python
find_answer
<not_specific>
def find_answer(offsets, begin_offset, end_offset): """Match token offsets with the char begin/end offsets of the answer.""" start = [i for i, tok in enumerate(offsets) if tok[0] == begin_offset] end = [i for i, tok in enumerate(offsets) if tok[1] == end_offset] assert(len(start) <= 1) assert(len(end) <= 1) if len(start) == 1 and len(end) == 1: return start[0], end[0]
Match token offsets with the char begin/end offsets of the answer.
Match token offsets with the char begin/end offsets of the answer.
[ "Match", "token", "offsets", "with", "the", "char", "begin", "/", "end", "offsets", "of", "the", "answer", "." ]
def find_answer(offsets, begin_offset, end_offset): start = [i for i, tok in enumerate(offsets) if tok[0] == begin_offset] end = [i for i, tok in enumerate(offsets) if tok[1] == end_offset] assert(len(start) <= 1) assert(len(end) <= 1) if len(start) == 1 and len(end) == 1: return start[0], end[0]
[ "def", "find_answer", "(", "offsets", ",", "begin_offset", ",", "end_offset", ")", ":", "start", "=", "[", "i", "for", "i", ",", "tok", "in", "enumerate", "(", "offsets", ")", "if", "tok", "[", "0", "]", "==", "begin_offset", "]", "end", "=", "[", "i", "for", "i", ",", "tok", "in", "enumerate", "(", "offsets", ")", "if", "tok", "[", "1", "]", "==", "end_offset", "]", "assert", "(", "len", "(", "start", ")", "<=", "1", ")", "assert", "(", "len", "(", "end", ")", "<=", "1", ")", "if", "len", "(", "start", ")", "==", "1", "and", "len", "(", "end", ")", "==", "1", ":", "return", "start", "[", "0", "]", ",", "end", "[", "0", "]" ]
Match token offsets with the char begin/end offsets of the answer.
[ "Match", "token", "offsets", "with", "the", "char", "begin", "/", "end", "offsets", "of", "the", "answer", "." ]
[ "\"\"\"Match token offsets with the char begin/end offsets of the answer.\"\"\"" ]
[ { "param": "offsets", "type": null }, { "param": "begin_offset", "type": null }, { "param": "end_offset", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "offsets", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "begin_offset", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "end_offset", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def find_answer(offsets, begin_offset, end_offset): start = [i for i, tok in enumerate(offsets) if tok[0] == begin_offset] end = [i for i, tok in enumerate(offsets) if tok[1] == end_offset] assert(len(start) <= 1) assert(len(end) <= 1) if len(start) == 1 and len(end) == 1: return start[0], end[0]
609,902
805
ac0d18c4e0d96da1bb12941956e4ce16b315d8ff
ssin122/test-h
src/memex/search/config.py
[ "MIT" ]
Python
_update_index_analysis
null
def _update_index_analysis(conn, name, analysis): """Attempt to update the index analysis settings.""" settings = conn.indices.get_settings(index=name) existing = settings[name]['settings']['index'].get('analysis', {}) if existing != analysis: try: conn.indices.close(index=name) conn.indices.put_settings(index=name, body={ 'analysis': analysis }) finally: conn.indices.open(index=name)
Attempt to update the index analysis settings.
Attempt to update the index analysis settings.
[ "Attempt", "to", "update", "the", "index", "analysis", "settings", "." ]
def _update_index_analysis(conn, name, analysis): settings = conn.indices.get_settings(index=name) existing = settings[name]['settings']['index'].get('analysis', {}) if existing != analysis: try: conn.indices.close(index=name) conn.indices.put_settings(index=name, body={ 'analysis': analysis }) finally: conn.indices.open(index=name)
[ "def", "_update_index_analysis", "(", "conn", ",", "name", ",", "analysis", ")", ":", "settings", "=", "conn", ".", "indices", ".", "get_settings", "(", "index", "=", "name", ")", "existing", "=", "settings", "[", "name", "]", "[", "'settings'", "]", "[", "'index'", "]", ".", "get", "(", "'analysis'", ",", "{", "}", ")", "if", "existing", "!=", "analysis", ":", "try", ":", "conn", ".", "indices", ".", "close", "(", "index", "=", "name", ")", "conn", ".", "indices", ".", "put_settings", "(", "index", "=", "name", ",", "body", "=", "{", "'analysis'", ":", "analysis", "}", ")", "finally", ":", "conn", ".", "indices", ".", "open", "(", "index", "=", "name", ")" ]
Attempt to update the index analysis settings.
[ "Attempt", "to", "update", "the", "index", "analysis", "settings", "." ]
[ "\"\"\"Attempt to update the index analysis settings.\"\"\"" ]
[ { "param": "conn", "type": null }, { "param": "name", "type": null }, { "param": "analysis", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "conn", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "name", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "analysis", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def _update_index_analysis(conn, name, analysis): settings = conn.indices.get_settings(index=name) existing = settings[name]['settings']['index'].get('analysis', {}) if existing != analysis: try: conn.indices.close(index=name) conn.indices.put_settings(index=name, body={ 'analysis': analysis }) finally: conn.indices.open(index=name)
609,904
1,001
c65e6c1522474bd6020d084520e2a69f3fdfb6f8
DamianSkrzypczak/Remus_FLASK
remus/data_import/create_genes_db.py
[ "MIT" ]
Python
create_db_from_data_frame
null
def create_db_from_data_frame(db_path, summary_df): """ Creates database from whole content which was collected and reformatted as dataframe. :param db_path: full path of future database :param summary_df: content for future database """ conn = sqlite3.connect(db_path) summary_df.to_sql("genes", conn, if_exists="replace")
Creates database from whole content which was collected and reformatted as dataframe. :param db_path: full path of future database :param summary_df: content for future database
Creates database from whole content which was collected and reformatted as dataframe.
[ "Creates", "database", "from", "whole", "content", "which", "was", "collected", "and", "reformatted", "as", "dataframe", "." ]
def create_db_from_data_frame(db_path, summary_df): conn = sqlite3.connect(db_path) summary_df.to_sql("genes", conn, if_exists="replace")
[ "def", "create_db_from_data_frame", "(", "db_path", ",", "summary_df", ")", ":", "conn", "=", "sqlite3", ".", "connect", "(", "db_path", ")", "summary_df", ".", "to_sql", "(", "\"genes\"", ",", "conn", ",", "if_exists", "=", "\"replace\"", ")" ]
Creates database from whole content which was collected and reformatted as dataframe.
[ "Creates", "database", "from", "whole", "content", "which", "was", "collected", "and", "reformatted", "as", "dataframe", "." ]
[ "\"\"\"\n Creates database from whole content which was collected and reformatted as dataframe.\n\n :param db_path: full path of future database\n :param summary_df: content for future database\n \"\"\"" ]
[ { "param": "db_path", "type": null }, { "param": "summary_df", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "db_path", "type": null, "docstring": "full path of future database", "docstring_tokens": [ "full", "path", "of", "future", "database" ], "default": null, "is_optional": null }, { "identifier": "summary_df", "type": null, "docstring": "content for future database", "docstring_tokens": [ "content", "for", "future", "database" ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import sqlite3 def create_db_from_data_frame(db_path, summary_df): conn = sqlite3.connect(db_path) summary_df.to_sql("genes", conn, if_exists="replace")
609,906
729
2dc47ba63d3d9cc95d45b19b4ef1867f3524c196
bcskda/reviewboard
reviewboard/scmtools/core.py
[ "MIT" ]
Python
popen
<not_specific>
def popen(cls, command, local_site_name=None): """Launches an application, capturing output. This wraps subprocess.Popen to provide some common parameters and to pass environment variables that may be needed by rbssh, if indirectly invoked. """ env = os.environ.copy() if local_site_name: env[b'RB_LOCAL_SITE'] = local_site_name.encode('utf-8') env[b'PYTHONPATH'] = (':'.join(sys.path)).encode('utf-8') return subprocess.Popen(command, env=env, stderr=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=(os.name != 'nt'))
Launches an application, capturing output. This wraps subprocess.Popen to provide some common parameters and to pass environment variables that may be needed by rbssh, if indirectly invoked.
Launches an application, capturing output. This wraps subprocess.Popen to provide some common parameters and to pass environment variables that may be needed by rbssh, if indirectly invoked.
[ "Launches", "an", "application", "capturing", "output", ".", "This", "wraps", "subprocess", ".", "Popen", "to", "provide", "some", "common", "parameters", "and", "to", "pass", "environment", "variables", "that", "may", "be", "needed", "by", "rbssh", "if", "indirectly", "invoked", "." ]
def popen(cls, command, local_site_name=None): env = os.environ.copy() if local_site_name: env[b'RB_LOCAL_SITE'] = local_site_name.encode('utf-8') env[b'PYTHONPATH'] = (':'.join(sys.path)).encode('utf-8') return subprocess.Popen(command, env=env, stderr=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=(os.name != 'nt'))
[ "def", "popen", "(", "cls", ",", "command", ",", "local_site_name", "=", "None", ")", ":", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "if", "local_site_name", ":", "env", "[", "b'RB_LOCAL_SITE'", "]", "=", "local_site_name", ".", "encode", "(", "'utf-8'", ")", "env", "[", "b'PYTHONPATH'", "]", "=", "(", "':'", ".", "join", "(", "sys", ".", "path", ")", ")", ".", "encode", "(", "'utf-8'", ")", "return", "subprocess", ".", "Popen", "(", "command", ",", "env", "=", "env", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "close_fds", "=", "(", "os", ".", "name", "!=", "'nt'", ")", ")" ]
Launches an application, capturing output.
[ "Launches", "an", "application", "capturing", "output", "." ]
[ "\"\"\"Launches an application, capturing output.\n\n This wraps subprocess.Popen to provide some common parameters and\n to pass environment variables that may be needed by rbssh, if\n indirectly invoked.\n \"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "command", "type": null }, { "param": "local_site_name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "command", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "local_site_name", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import sys import subprocess import os def popen(cls, command, local_site_name=None): env = os.environ.copy() if local_site_name: env[b'RB_LOCAL_SITE'] = local_site_name.encode('utf-8') env[b'PYTHONPATH'] = (':'.join(sys.path)).encode('utf-8') return subprocess.Popen(command, env=env, stderr=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=(os.name != 'nt'))
609,907
1,002
101d2e4ffe5efbec62e9605c64fca64a3d15f36a
syenpark/Intro2CTandDS
unit1/problem_set1/ps1.py
[ "MIT" ]
Python
greedy_cow_transport
<not_specific>
def greedy_cow_transport(cows,limit=10): """ Uses a greedy heuristic to determine an allocation of cows that attempts to minimize the number of spaceship trips needed to transport all the cows. The returned allocation of cows may or may not be optimal. The greedy heuristic should follow the following method: 1. As long as the current trip can fit another cow, add the largest cow that will fit to the trip 2. Once the trip is full, begin a new trip to transport the remaining cows Does not mutate the given dictionary of cows. Parameters: cows - a dictionary of name (string), weight (int) pairs limit - weight limit of the spaceship (an int) Returns: A list of lists, with each inner list containing the names of cows transported on a particular trip and the overall list containing all the trips """ trip = [] trips = [] trip_weight = 0 # refer: def __getitem__(self, key): return self.data[key] # heaviest_cows = sorted(cows, key=cows.__getitem__, reverse=True) heaviest_cows = sorted(cows.items(), key=lambda x: x[1], reverse=True) heaviest_cows = [name for (name, weight)in heaviest_cows] while heaviest_cows: # To prevent unexpected result caused by the altered list, # use copy of the list for name in heaviest_cows[:]: weight = cows[name] if weight + trip_weight <= limit: # Checks still here (the cow is not loaded yet); # Already gone, just skip; # Still here, load the cow try: heaviest_cows.index(name) except: pass else: trip.append(name) trip_weight += weight heaviest_cows.remove(name) elif weight > limit: heaviest_cows.remove(name) trips.append(trip) trip = [] trip_weight = 0 return trips
Uses a greedy heuristic to determine an allocation of cows that attempts to minimize the number of spaceship trips needed to transport all the cows. The returned allocation of cows may or may not be optimal. The greedy heuristic should follow the following method: 1. As long as the current trip can fit another cow, add the largest cow that will fit to the trip 2. Once the trip is full, begin a new trip to transport the remaining cows Does not mutate the given dictionary of cows. Parameters: cows - a dictionary of name (string), weight (int) pairs limit - weight limit of the spaceship (an int) Returns: A list of lists, with each inner list containing the names of cows transported on a particular trip and the overall list containing all the trips
Uses a greedy heuristic to determine an allocation of cows that attempts to minimize the number of spaceship trips needed to transport all the cows. The returned allocation of cows may or may not be optimal. The greedy heuristic should follow the following method. 1. As long as the current trip can fit another cow, add the largest cow that will fit to the trip 2. Once the trip is full, begin a new trip to transport the remaining cows Does not mutate the given dictionary of cows. a dictionary of name (string), weight (int) pairs limit - weight limit of the spaceship (an int) A list of lists, with each inner list containing the names of cows transported on a particular trip and the overall list containing all the trips
[ "Uses", "a", "greedy", "heuristic", "to", "determine", "an", "allocation", "of", "cows", "that", "attempts", "to", "minimize", "the", "number", "of", "spaceship", "trips", "needed", "to", "transport", "all", "the", "cows", ".", "The", "returned", "allocation", "of", "cows", "may", "or", "may", "not", "be", "optimal", ".", "The", "greedy", "heuristic", "should", "follow", "the", "following", "method", ".", "1", ".", "As", "long", "as", "the", "current", "trip", "can", "fit", "another", "cow", "add", "the", "largest", "cow", "that", "will", "fit", "to", "the", "trip", "2", ".", "Once", "the", "trip", "is", "full", "begin", "a", "new", "trip", "to", "transport", "the", "remaining", "cows", "Does", "not", "mutate", "the", "given", "dictionary", "of", "cows", ".", "a", "dictionary", "of", "name", "(", "string", ")", "weight", "(", "int", ")", "pairs", "limit", "-", "weight", "limit", "of", "the", "spaceship", "(", "an", "int", ")", "A", "list", "of", "lists", "with", "each", "inner", "list", "containing", "the", "names", "of", "cows", "transported", "on", "a", "particular", "trip", "and", "the", "overall", "list", "containing", "all", "the", "trips" ]
def greedy_cow_transport(cows,limit=10): trip = [] trips = [] trip_weight = 0 heaviest_cows = sorted(cows.items(), key=lambda x: x[1], reverse=True) heaviest_cows = [name for (name, weight)in heaviest_cows] while heaviest_cows: for name in heaviest_cows[:]: weight = cows[name] if weight + trip_weight <= limit: try: heaviest_cows.index(name) except: pass else: trip.append(name) trip_weight += weight heaviest_cows.remove(name) elif weight > limit: heaviest_cows.remove(name) trips.append(trip) trip = [] trip_weight = 0 return trips
[ "def", "greedy_cow_transport", "(", "cows", ",", "limit", "=", "10", ")", ":", "trip", "=", "[", "]", "trips", "=", "[", "]", "trip_weight", "=", "0", "heaviest_cows", "=", "sorted", "(", "cows", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", ")", "heaviest_cows", "=", "[", "name", "for", "(", "name", ",", "weight", ")", "in", "heaviest_cows", "]", "while", "heaviest_cows", ":", "for", "name", "in", "heaviest_cows", "[", ":", "]", ":", "weight", "=", "cows", "[", "name", "]", "if", "weight", "+", "trip_weight", "<=", "limit", ":", "try", ":", "heaviest_cows", ".", "index", "(", "name", ")", "except", ":", "pass", "else", ":", "trip", ".", "append", "(", "name", ")", "trip_weight", "+=", "weight", "heaviest_cows", ".", "remove", "(", "name", ")", "elif", "weight", ">", "limit", ":", "heaviest_cows", ".", "remove", "(", "name", ")", "trips", ".", "append", "(", "trip", ")", "trip", "=", "[", "]", "trip_weight", "=", "0", "return", "trips" ]
Uses a greedy heuristic to determine an allocation of cows that attempts to minimize the number of spaceship trips needed to transport all the cows.
[ "Uses", "a", "greedy", "heuristic", "to", "determine", "an", "allocation", "of", "cows", "that", "attempts", "to", "minimize", "the", "number", "of", "spaceship", "trips", "needed", "to", "transport", "all", "the", "cows", "." ]
[ "\"\"\"\r\n Uses a greedy heuristic to determine an allocation of cows that attempts to\r\n minimize the number of spaceship trips needed to transport all the cows. The\r\n returned allocation of cows may or may not be optimal.\r\n The greedy heuristic should follow the following method:\r\n\r\n 1. As long as the current trip can fit another cow, add the largest cow that will fit\r\n to the trip\r\n 2. Once the trip is full, begin a new trip to transport the remaining cows\r\n\r\n Does not mutate the given dictionary of cows.\r\n\r\n Parameters:\r\n cows - a dictionary of name (string), weight (int) pairs\r\n limit - weight limit of the spaceship (an int)\r\n \r\n Returns:\r\n A list of lists, with each inner list containing the names of cows\r\n transported on a particular trip and the overall list containing all the\r\n trips\r\n \"\"\"", "# refer: def __getitem__(self, key): return self.data[key]\r", "# heaviest_cows = sorted(cows, key=cows.__getitem__, reverse=True)\r", "# To prevent unexpected result caused by the altered list,\r", "# use copy of the list\r", "# Checks still here (the cow is not loaded yet);\r", "# Already gone, just skip;\r", "# Still here, load the cow\r" ]
[ { "param": "cows", "type": null }, { "param": "limit", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cows", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "limit", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def greedy_cow_transport(cows,limit=10): trip = [] trips = [] trip_weight = 0 heaviest_cows = sorted(cows.items(), key=lambda x: x[1], reverse=True) heaviest_cows = [name for (name, weight)in heaviest_cows] while heaviest_cows: for name in heaviest_cows[:]: weight = cows[name] if weight + trip_weight <= limit: try: heaviest_cows.index(name) except: pass else: trip.append(name) trip_weight += weight heaviest_cows.remove(name) elif weight > limit: heaviest_cows.remove(name) trips.append(trip) trip = [] trip_weight = 0 return trips
609,908
826
d58cbd7581b0fb25003a5c38698211050c94f384
nickaigi/effective_python_tips
item_46_algos_datastructures.py
[ "Unlicense" ]
Python
example_nine
null
def example_nine(): """ Searching in a list takes linear time O(n) """ x = list(range(10**6)) i = x.index(991234)
Searching in a list takes linear time O(n)
Searching in a list takes linear time O(n)
[ "Searching", "in", "a", "list", "takes", "linear", "time", "O", "(", "n", ")" ]
def example_nine(): x = list(range(10**6)) i = x.index(991234)
[ "def", "example_nine", "(", ")", ":", "x", "=", "list", "(", "range", "(", "10", "**", "6", ")", ")", "i", "=", "x", ".", "index", "(", "991234", ")" ]
Searching in a list takes linear time O(n)
[ "Searching", "in", "a", "list", "takes", "linear", "time", "O", "(", "n", ")" ]
[ "\"\"\"\n Searching in a list takes linear time O(n)\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
def example_nine(): x = list(range(10**6)) i = x.index(991234)
609,909
275
7d6623a2b794203ea1cf300e7ffad642819f1902
ufora/ufora
packages/python/pyfora/pyAst/NodeVisitorBases.py
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
Python
isScopeNode
<not_specific>
def isScopeNode(pyAstNode): """Return true iff argument is a scoped node.""" if isinstance(pyAstNode, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.Lambda, ast.GeneratorExp)): return True else: return False
Return true iff argument is a scoped node.
Return true iff argument is a scoped node.
[ "Return", "true", "iff", "argument", "is", "a", "scoped", "node", "." ]
def isScopeNode(pyAstNode): if isinstance(pyAstNode, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.Lambda, ast.GeneratorExp)): return True else: return False
[ "def", "isScopeNode", "(", "pyAstNode", ")", ":", "if", "isinstance", "(", "pyAstNode", ",", "(", "ast", ".", "Module", ",", "ast", ".", "ClassDef", ",", "ast", ".", "FunctionDef", ",", "ast", ".", "Lambda", ",", "ast", ".", "GeneratorExp", ")", ")", ":", "return", "True", "else", ":", "return", "False" ]
Return true iff argument is a scoped node.
[ "Return", "true", "iff", "argument", "is", "a", "scoped", "node", "." ]
[ "\"\"\"Return true iff argument is a scoped node.\"\"\"" ]
[ { "param": "pyAstNode", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "pyAstNode", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import ast def isScopeNode(pyAstNode): if isinstance(pyAstNode, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.Lambda, ast.GeneratorExp)): return True else: return False
609,910
607
949bda075bdf5325ab84f04864686d0148a099c4
fbiville/python3-function-invoker
invoker/grpc_server.py
[ "Apache-2.0" ]
Python
convert_request_payload
<not_specific>
def convert_request_payload(request): """ Convert the request payload from bytes for a given request's Content Type header :param request: the request Message :return: varies by content type header, e.g., dict or str """ if 'application/json' in request.headers['Content-Type'].values: return json.loads(request.payload) elif 'application/octet-stream' in request.headers['Content-Type'].values: return request.payload elif 'text/plain' in request.headers['Content-Type'].values: return request.payload.decode('UTF-8') return request.payload
Convert the request payload from bytes for a given request's Content Type header :param request: the request Message :return: varies by content type header, e.g., dict or str
Convert the request payload from bytes for a given request's Content Type header
[ "Convert", "the", "request", "payload", "from", "bytes", "for", "a", "given", "request", "'", "s", "Content", "Type", "header" ]
def convert_request_payload(request): if 'application/json' in request.headers['Content-Type'].values: return json.loads(request.payload) elif 'application/octet-stream' in request.headers['Content-Type'].values: return request.payload elif 'text/plain' in request.headers['Content-Type'].values: return request.payload.decode('UTF-8') return request.payload
[ "def", "convert_request_payload", "(", "request", ")", ":", "if", "'application/json'", "in", "request", ".", "headers", "[", "'Content-Type'", "]", ".", "values", ":", "return", "json", ".", "loads", "(", "request", ".", "payload", ")", "elif", "'application/octet-stream'", "in", "request", ".", "headers", "[", "'Content-Type'", "]", ".", "values", ":", "return", "request", ".", "payload", "elif", "'text/plain'", "in", "request", ".", "headers", "[", "'Content-Type'", "]", ".", "values", ":", "return", "request", ".", "payload", ".", "decode", "(", "'UTF-8'", ")", "return", "request", ".", "payload" ]
Convert the request payload from bytes for a given request's Content Type header
[ "Convert", "the", "request", "payload", "from", "bytes", "for", "a", "given", "request", "'", "s", "Content", "Type", "header" ]
[ "\"\"\"\n Convert the request payload from bytes for a given request's Content Type header\n :param request: the request Message\n :return: varies by content type header, e.g., dict or str\n \"\"\"" ]
[ { "param": "request", "type": null } ]
{ "returns": [ { "docstring": "varies by content type header, e.g., dict or str", "docstring_tokens": [ "varies", "by", "content", "type", "header", "e", ".", "g", ".", "dict", "or", "str" ], "type": null } ], "raises": [], "params": [ { "identifier": "request", "type": null, "docstring": "the request Message", "docstring_tokens": [ "the", "request", "Message" ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import json def convert_request_payload(request): if 'application/json' in request.headers['Content-Type'].values: return json.loads(request.payload) elif 'application/octet-stream' in request.headers['Content-Type'].values: return request.payload elif 'text/plain' in request.headers['Content-Type'].values: return request.payload.decode('UTF-8') return request.payload
609,911
740
8371e5b91c770770a31c3a5111aa6755728e51ac
BillMills/AutoQC
util/main.py
[ "MIT" ]
Python
importQC
<not_specific>
def importQC(dir): ''' return a list of names of tests found in <dir>: ''' testFiles = glob.glob(dir+'/[!_]*.py') testNames = [testFile[len(dir)+1:-3] for testFile in testFiles] return testNames
return a list of names of tests found in <dir>:
return a list of names of tests found in .
[ "return", "a", "list", "of", "names", "of", "tests", "found", "in", "." ]
def importQC(dir): testFiles = glob.glob(dir+'/[!_]*.py') testNames = [testFile[len(dir)+1:-3] for testFile in testFiles] return testNames
[ "def", "importQC", "(", "dir", ")", ":", "testFiles", "=", "glob", ".", "glob", "(", "dir", "+", "'/[!_]*.py'", ")", "testNames", "=", "[", "testFile", "[", "len", "(", "dir", ")", "+", "1", ":", "-", "3", "]", "for", "testFile", "in", "testFiles", "]", "return", "testNames" ]
return a list of names of tests found in <dir>:
[ "return", "a", "list", "of", "names", "of", "tests", "found", "in", "<dir", ">", ":" ]
[ "'''\n return a list of names of tests found in <dir>:\n '''" ]
[ { "param": "dir", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "dir", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import glob def importQC(dir): testFiles = glob.glob(dir+'/[!_]*.py') testNames = [testFile[len(dir)+1:-3] for testFile in testFiles] return testNames
609,912
731
1c5cb8a935b647bfd0e575e2fe671416eaccdbf3
sthagen/pwwang-datar
datar/dplyr/recode.py
[ "MIT" ]
Python
_check_length
<not_specific>
def _check_length(val, x, name): """Check the length of the values to recode""" length_x = len(val) n = len(x) if length_x in (1, n): return if n == 1: raise ValueError(f"{name} must be length 1, not {length_x}.") raise ValueError(f"{name} must be length {n}, not {length_x}.")
Check the length of the values to recode
Check the length of the values to recode
[ "Check", "the", "length", "of", "the", "values", "to", "recode" ]
def _check_length(val, x, name): length_x = len(val) n = len(x) if length_x in (1, n): return if n == 1: raise ValueError(f"{name} must be length 1, not {length_x}.") raise ValueError(f"{name} must be length {n}, not {length_x}.")
[ "def", "_check_length", "(", "val", ",", "x", ",", "name", ")", ":", "length_x", "=", "len", "(", "val", ")", "n", "=", "len", "(", "x", ")", "if", "length_x", "in", "(", "1", ",", "n", ")", ":", "return", "if", "n", "==", "1", ":", "raise", "ValueError", "(", "f\"{name} must be length 1, not {length_x}.\"", ")", "raise", "ValueError", "(", "f\"{name} must be length {n}, not {length_x}.\"", ")" ]
Check the length of the values to recode
[ "Check", "the", "length", "of", "the", "values", "to", "recode" ]
[ "\"\"\"Check the length of the values to recode\"\"\"" ]
[ { "param": "val", "type": null }, { "param": "x", "type": null }, { "param": "name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "val", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "x", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "name", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def _check_length(val, x, name): length_x = len(val) n = len(x) if length_x in (1, n): return if n == 1: raise ValueError(f"{name} must be length 1, not {length_x}.") raise ValueError(f"{name} must be length {n}, not {length_x}.")
609,913
599
90ac79848305ae0b0232fc2624728f1887378957
shir-barzel-healthy/CIE_XYZ_NET
PyTorch/pp_code/postprocessing.py
[ "MIT" ]
Python
postprocessing
<not_specific>
def postprocessing(input_img, PP, opt=None): """ Post-processing function; adjust it with your custom pp functions. """ logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') if '+' not in PP: PP = [PP] else: PP = PP.split('+') output = input_img for pp in PP: if pp == "denoise": logging.info('denoising...') # denoising code goes here elif pp == "chrom-adapt": logging.info('chrom adapting...') # chromatic adaptation code goes here elif pp == "deblur": logging.info('deblurring...') # deblurring code goes here elif pp == "dehaze": logging.info('dehazing...') # dehazing code goes here elif pp == "editdetails": logging.info('editing local details...') # local detail enhancement code goes here elif pp == "exposure-fusion": logging.info('exposure fusion...') # exposure fusion code goes here elif pp == "transfer-colors": logging.info('color transfering...') # color transfer code goes here # you may need to use the 'opt' variable here elif pp == "super-res": logging.info('super-resolution processing...') # super resolution code goes here else: logging.info('wrong post-processing task!') return output
Post-processing function; adjust it with your custom pp functions.
Post-processing function; adjust it with your custom pp functions.
[ "Post", "-", "processing", "function", ";", "adjust", "it", "with", "your", "custom", "pp", "functions", "." ]
def postprocessing(input_img, PP, opt=None): logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') if '+' not in PP: PP = [PP] else: PP = PP.split('+') output = input_img for pp in PP: if pp == "denoise": logging.info('denoising...') elif pp == "chrom-adapt": logging.info('chrom adapting...') elif pp == "deblur": logging.info('deblurring...') elif pp == "dehaze": logging.info('dehazing...') elif pp == "editdetails": logging.info('editing local details...') elif pp == "exposure-fusion": logging.info('exposure fusion...') elif pp == "transfer-colors": logging.info('color transfering...') elif pp == "super-res": logging.info('super-resolution processing...') else: logging.info('wrong post-processing task!') return output
[ "def", "postprocessing", "(", "input_img", ",", "PP", ",", "opt", "=", "None", ")", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(levelname)s: %(message)s'", ")", "if", "'+'", "not", "in", "PP", ":", "PP", "=", "[", "PP", "]", "else", ":", "PP", "=", "PP", ".", "split", "(", "'+'", ")", "output", "=", "input_img", "for", "pp", "in", "PP", ":", "if", "pp", "==", "\"denoise\"", ":", "logging", ".", "info", "(", "'denoising...'", ")", "elif", "pp", "==", "\"chrom-adapt\"", ":", "logging", ".", "info", "(", "'chrom adapting...'", ")", "elif", "pp", "==", "\"deblur\"", ":", "logging", ".", "info", "(", "'deblurring...'", ")", "elif", "pp", "==", "\"dehaze\"", ":", "logging", ".", "info", "(", "'dehazing...'", ")", "elif", "pp", "==", "\"editdetails\"", ":", "logging", ".", "info", "(", "'editing local details...'", ")", "elif", "pp", "==", "\"exposure-fusion\"", ":", "logging", ".", "info", "(", "'exposure fusion...'", ")", "elif", "pp", "==", "\"transfer-colors\"", ":", "logging", ".", "info", "(", "'color transfering...'", ")", "elif", "pp", "==", "\"super-res\"", ":", "logging", ".", "info", "(", "'super-resolution processing...'", ")", "else", ":", "logging", ".", "info", "(", "'wrong post-processing task!'", ")", "return", "output" ]
Post-processing function; adjust it with your custom pp functions.
[ "Post", "-", "processing", "function", ";", "adjust", "it", "with", "your", "custom", "pp", "functions", "." ]
[ "\"\"\" Post-processing function; adjust it with your custom pp functions. \"\"\"", "# denoising code goes here\r", "# chromatic adaptation code goes here\r", "# deblurring code goes here\r", "# dehazing code goes here\r", "# local detail enhancement code goes here\r", "# exposure fusion code goes here\r", "# color transfer code goes here\r", "# you may need to use the 'opt' variable here\r", "# super resolution code goes here\r" ]
[ { "param": "input_img", "type": null }, { "param": "PP", "type": null }, { "param": "opt", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input_img", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "PP", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "opt", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import logging def postprocessing(input_img, PP, opt=None): logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') if '+' not in PP: PP = [PP] else: PP = PP.split('+') output = input_img for pp in PP: if pp == "denoise": logging.info('denoising...') elif pp == "chrom-adapt": logging.info('chrom adapting...') elif pp == "deblur": logging.info('deblurring...') elif pp == "dehaze": logging.info('dehazing...') elif pp == "editdetails": logging.info('editing local details...') elif pp == "exposure-fusion": logging.info('exposure fusion...') elif pp == "transfer-colors": logging.info('color transfering...') elif pp == "super-res": logging.info('super-resolution processing...') else: logging.info('wrong post-processing task!') return output
609,914
17
6a5062d5687ea4bdabecd588c5f6ebd25e6a3aa4
joshbduncan/swatcher
swatcher/color.py
[ "MIT" ]
Python
rgb_2_luma
int
def rgb_2_luma(color: tuple) -> int: """ Calculate the "brightness" of a color. ...and, yes I know this is a debated subject but this way works for just fine my purposes. :param color: a tuple of RGB color values eg. (255, 255, 255) :returns: luminance "brightness" value """ r, g, b = color[0] / 255, color[1] / 255, color[2] / 255 l = 0.33 * r + 0.5 * g + 0.16 * b return round(l, 2)
Calculate the "brightness" of a color. ...and, yes I know this is a debated subject but this way works for just fine my purposes. :param color: a tuple of RGB color values eg. (255, 255, 255) :returns: luminance "brightness" value
Calculate the "brightness" of a color. and, yes I know this is a debated subject but this way works for just fine my purposes.
[ "Calculate", "the", "\"", "brightness", "\"", "of", "a", "color", ".", "and", "yes", "I", "know", "this", "is", "a", "debated", "subject", "but", "this", "way", "works", "for", "just", "fine", "my", "purposes", "." ]
def rgb_2_luma(color: tuple) -> int: r, g, b = color[0] / 255, color[1] / 255, color[2] / 255 l = 0.33 * r + 0.5 * g + 0.16 * b return round(l, 2)
[ "def", "rgb_2_luma", "(", "color", ":", "tuple", ")", "->", "int", ":", "r", ",", "g", ",", "b", "=", "color", "[", "0", "]", "/", "255", ",", "color", "[", "1", "]", "/", "255", ",", "color", "[", "2", "]", "/", "255", "l", "=", "0.33", "*", "r", "+", "0.5", "*", "g", "+", "0.16", "*", "b", "return", "round", "(", "l", ",", "2", ")" ]
Calculate the "brightness" of a color.
[ "Calculate", "the", "\"", "brightness", "\"", "of", "a", "color", "." ]
[ "\"\"\"\n Calculate the \"brightness\" of a color.\n\n ...and, yes I know this is a debated subject\n but this way works for just fine my purposes.\n\n :param color: a tuple of RGB color values eg. (255, 255, 255)\n :returns: luminance \"brightness\" value\n \"\"\"" ]
[ { "param": "color", "type": "tuple" } ]
{ "returns": [ { "docstring": "luminance \"brightness\" value", "docstring_tokens": [ "luminance", "\"", "brightness", "\"", "value" ], "type": null } ], "raises": [], "params": [ { "identifier": "color", "type": "tuple", "docstring": "a tuple of RGB color values eg.", "docstring_tokens": [ "a", "tuple", "of", "RGB", "color", "values", "eg", "." ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def rgb_2_luma(color: tuple) -> int: r, g, b = color[0] / 255, color[1] / 255, color[2] / 255 l = 0.33 * r + 0.5 * g + 0.16 * b return round(l, 2)
609,915
805
281faa1714ff4b487ca24b2ab856aaa861d9a011
bo4e/BO4E-python
src/bo4e/validators.py
[ "MIT" ]
Python
check_list_length_is_one_or_two
null
def check_list_length_is_one_or_two(instance, attribute, value): """ Check if list length is one or two. So far only used in StandorteigenschaftenGas. """ if len(value) == 0: raise ValueError(f"{attribute.name} must not be empty.") if len(value) > 2: raise ValueError(f"Maximum number of {attribute.name} is 2.")
Check if list length is one or two. So far only used in StandorteigenschaftenGas.
Check if list length is one or two. So far only used in StandorteigenschaftenGas.
[ "Check", "if", "list", "length", "is", "one", "or", "two", ".", "So", "far", "only", "used", "in", "StandorteigenschaftenGas", "." ]
def check_list_length_is_one_or_two(instance, attribute, value): if len(value) == 0: raise ValueError(f"{attribute.name} must not be empty.") if len(value) > 2: raise ValueError(f"Maximum number of {attribute.name} is 2.")
[ "def", "check_list_length_is_one_or_two", "(", "instance", ",", "attribute", ",", "value", ")", ":", "if", "len", "(", "value", ")", "==", "0", ":", "raise", "ValueError", "(", "f\"{attribute.name} must not be empty.\"", ")", "if", "len", "(", "value", ")", ">", "2", ":", "raise", "ValueError", "(", "f\"Maximum number of {attribute.name} is 2.\"", ")" ]
Check if list length is one or two.
[ "Check", "if", "list", "length", "is", "one", "or", "two", "." ]
[ "\"\"\"\n Check if list length is one or two.\n So far only used in StandorteigenschaftenGas.\n \"\"\"" ]
[ { "param": "instance", "type": null }, { "param": "attribute", "type": null }, { "param": "value", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "instance", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "attribute", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "value", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def check_list_length_is_one_or_two(instance, attribute, value): if len(value) == 0: raise ValueError(f"{attribute.name} must not be empty.") if len(value) > 2: raise ValueError(f"Maximum number of {attribute.name} is 2.")
609,916
813
334e2cf68038f5908fd3609af07d7b850cca64df
kuanhanl/cappresse
nmpc_mhe/dync/.old_/DynGen.py
[ "MIT" ]
Python
journalizer
null
def journalizer(flag, iter, phase, message): """Method that writes a little message Args: flag (str): The flag iter (int): The current iteration phase (str): The phase message (str): The text message to display Returns: None""" iter = str(iter) print("-" * 120) if flag == 'W': print(flag + iter + "[[" + phase + "]]" + message + ".", file=sys.stderr) # print to file warning elif flag == 'E': print(flag + iter + "[[" + phase + "]]" + message + ".", file=sys.stderr) else: print(flag + iter + "[[" + phase + "]]" + message + "." + "-" * 20) # print to file error #print("-" * 120)
Method that writes a little message Args: flag (str): The flag iter (int): The current iteration phase (str): The phase message (str): The text message to display Returns: None
Method that writes a little message
[ "Method", "that", "writes", "a", "little", "message" ]
def journalizer(flag, iter, phase, message): iter = str(iter) print("-" * 120) if flag == 'W': print(flag + iter + "[[" + phase + "]]" + message + ".", file=sys.stderr) elif flag == 'E': print(flag + iter + "[[" + phase + "]]" + message + ".", file=sys.stderr) else: print(flag + iter + "[[" + phase + "]]" + message + "." + "-" * 20)
[ "def", "journalizer", "(", "flag", ",", "iter", ",", "phase", ",", "message", ")", ":", "iter", "=", "str", "(", "iter", ")", "print", "(", "\"-\"", "*", "120", ")", "if", "flag", "==", "'W'", ":", "print", "(", "flag", "+", "iter", "+", "\"[[\"", "+", "phase", "+", "\"]]\"", "+", "message", "+", "\".\"", ",", "file", "=", "sys", ".", "stderr", ")", "elif", "flag", "==", "'E'", ":", "print", "(", "flag", "+", "iter", "+", "\"[[\"", "+", "phase", "+", "\"]]\"", "+", "message", "+", "\".\"", ",", "file", "=", "sys", ".", "stderr", ")", "else", ":", "print", "(", "flag", "+", "iter", "+", "\"[[\"", "+", "phase", "+", "\"]]\"", "+", "message", "+", "\".\"", "+", "\"-\"", "*", "20", ")" ]
Method that writes a little message
[ "Method", "that", "writes", "a", "little", "message" ]
[ "\"\"\"Method that writes a little message\n Args:\n flag (str): The flag\n iter (int): The current iteration\n phase (str): The phase\n message (str): The text message to display\n Returns:\n None\"\"\"", "# print to file warning", "# print to file error", "#print(\"-\" * 120)" ]
[ { "param": "flag", "type": null }, { "param": "iter", "type": null }, { "param": "phase", "type": null }, { "param": "message", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "flag", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": false }, { "identifier": "iter", "type": null, "docstring": "The current iteration", "docstring_tokens": [ "The", "current", "iteration" ], "default": null, "is_optional": false }, { "identifier": "phase", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": false }, { "identifier": "message", "type": null, "docstring": "The text message to display", "docstring_tokens": [ "The", "text", "message", "to", "display" ], "default": null, "is_optional": false } ], "outlier_params": [], "others": [] }
import sys def journalizer(flag, iter, phase, message): iter = str(iter) print("-" * 120) if flag == 'W': print(flag + iter + "[[" + phase + "]]" + message + ".", file=sys.stderr) elif flag == 'E': print(flag + iter + "[[" + phase + "]]" + message + ".", file=sys.stderr) else: print(flag + iter + "[[" + phase + "]]" + message + "." + "-" * 20)
609,917
549
11c541f44370869d5ec41e17ec95c837dc3769b1
NullHypothesis/leekspin
leekspin/crypto.py
[ "MIT" ]
Python
addPKCS1Padding
<not_specific>
def addPKCS1Padding(message): """Add PKCS#1 padding to **message**. .. todo:: What version of PKCS#1? PKCS#1 v1.0? See https://bugs.torproject.org/13042. .. The double-backslashes in the following bytestrings are so that Sphinx renders them properly. Each double-backslash is should actually only be a single backslash in the code. Each block is 128 bytes total in size: * 2 bytes for the type info ('\\x00\\x01') * 1 byte for the separator ('\\x00') * variable length padding ('\\xFF') * variable length for the **message** :param str message: The message will be encoded as bytes before adding PKCS#1 padding. :rtype: bytes :returns: The PKCS#1 padded message. """ #if sys.version_info.major == 3: # if isinstance(message, unicode): # message = codecs.latin_1_encode(message, 'replace')[0] #else: # if isinstance(message, str): # message = codecs.latin_1_encode(message, 'replace')[0] padding = b'' typeinfo = b'\x00\x01' separator = b'\x00' for x in range(125 - len(message)): padding += b'\xFF' PKCS1paddedMessage = typeinfo + padding + separator + message assert len(PKCS1paddedMessage) == 128 return PKCS1paddedMessage
Add PKCS#1 padding to **message**. .. todo:: What version of PKCS#1? PKCS#1 v1.0? See https://bugs.torproject.org/13042. .. The double-backslashes in the following bytestrings are so that Sphinx renders them properly. Each double-backslash is should actually only be a single backslash in the code. Each block is 128 bytes total in size: * 2 bytes for the type info ('\\x00\\x01') * 1 byte for the separator ('\\x00') * variable length padding ('\\xFF') * variable length for the **message** :param str message: The message will be encoded as bytes before adding PKCS#1 padding. :rtype: bytes :returns: The PKCS#1 padded message.
Add PKCS#1 padding to **message**. todo:: What version of PKCS#1. The double-backslashes in the following bytestrings are so that Sphinx renders them properly. Each double-backslash is should actually only be a single backslash in the code. Each block is 128 bytes total in size.
[ "Add", "PKCS#1", "padding", "to", "**", "message", "**", ".", "todo", "::", "What", "version", "of", "PKCS#1", ".", "The", "double", "-", "backslashes", "in", "the", "following", "bytestrings", "are", "so", "that", "Sphinx", "renders", "them", "properly", ".", "Each", "double", "-", "backslash", "is", "should", "actually", "only", "be", "a", "single", "backslash", "in", "the", "code", ".", "Each", "block", "is", "128", "bytes", "total", "in", "size", "." ]
def addPKCS1Padding(message): padding = b'' typeinfo = b'\x00\x01' separator = b'\x00' for x in range(125 - len(message)): padding += b'\xFF' PKCS1paddedMessage = typeinfo + padding + separator + message assert len(PKCS1paddedMessage) == 128 return PKCS1paddedMessage
[ "def", "addPKCS1Padding", "(", "message", ")", ":", "padding", "=", "b''", "typeinfo", "=", "b'\\x00\\x01'", "separator", "=", "b'\\x00'", "for", "x", "in", "range", "(", "125", "-", "len", "(", "message", ")", ")", ":", "padding", "+=", "b'\\xFF'", "PKCS1paddedMessage", "=", "typeinfo", "+", "padding", "+", "separator", "+", "message", "assert", "len", "(", "PKCS1paddedMessage", ")", "==", "128", "return", "PKCS1paddedMessage" ]
Add PKCS#1 padding to **message**.
[ "Add", "PKCS#1", "padding", "to", "**", "message", "**", "." ]
[ "\"\"\"Add PKCS#1 padding to **message**.\n \n .. todo:: What version of PKCS#1? PKCS#1 v1.0? See\n https://bugs.torproject.org/13042.\n \n .. The double-backslashes in the following bytestrings are so that Sphinx\n renders them properly. Each double-backslash is should actually only\n be a single backslash in the code.\n\n Each block is 128 bytes total in size:\n\n * 2 bytes for the type info ('\\\\x00\\\\x01')\n * 1 byte for the separator ('\\\\x00')\n * variable length padding ('\\\\xFF')\n * variable length for the **message**\n\n :param str message: The message will be encoded as bytes before adding\n PKCS#1 padding.\n :rtype: bytes\n :returns: The PKCS#1 padded message.\n \"\"\"", "#if sys.version_info.major == 3:", "# if isinstance(message, unicode):", "# message = codecs.latin_1_encode(message, 'replace')[0]", "#else:", "# if isinstance(message, str):", "# message = codecs.latin_1_encode(message, 'replace')[0]" ]
[ { "param": "message", "type": null } ]
{ "returns": [ { "docstring": "The PKCS#1 padded message.", "docstring_tokens": [ "The", "PKCS#1", "padded", "message", "." ], "type": "bytes" } ], "raises": [], "params": [ { "identifier": "message", "type": null, "docstring": "The message will be encoded as bytes before adding\nPKCS#1 padding.", "docstring_tokens": [ "The", "message", "will", "be", "encoded", "as", "bytes", "before", "adding", "PKCS#1", "padding", "." ], "default": null, "is_optional": false } ], "outlier_params": [], "others": [] }
def addPKCS1Padding(message): padding = b'' typeinfo = b'\x00\x01' separator = b'\x00' for x in range(125 - len(message)): padding += b'\xFF' PKCS1paddedMessage = typeinfo + padding + separator + message assert len(PKCS1paddedMessage) == 128 return PKCS1paddedMessage
609,918
599
b6ef53cdef648be4e9f93a9c02333b435d163688
montoya4476/passphrase-wordlist
utilities/cleanup.py
[ "MIT" ]
Python
write_file
null
def write_file(buffer, outfile): """ Writes choses candidates to an output file """ file_handler = open(outfile, 'w') for line in buffer: file_handler.write(line.strip()+ '\n') file_handler.close() outfile_size = str((int(os.path.getsize(outfile)/1000000))) print("Wrote to {}: {} MB".format(outfile, outfile_size))
Writes choses candidates to an output file
Writes choses candidates to an output file
[ "Writes", "choses", "candidates", "to", "an", "output", "file" ]
def write_file(buffer, outfile): file_handler = open(outfile, 'w') for line in buffer: file_handler.write(line.strip()+ '\n') file_handler.close() outfile_size = str((int(os.path.getsize(outfile)/1000000))) print("Wrote to {}: {} MB".format(outfile, outfile_size))
[ "def", "write_file", "(", "buffer", ",", "outfile", ")", ":", "file_handler", "=", "open", "(", "outfile", ",", "'w'", ")", "for", "line", "in", "buffer", ":", "file_handler", ".", "write", "(", "line", ".", "strip", "(", ")", "+", "'\\n'", ")", "file_handler", ".", "close", "(", ")", "outfile_size", "=", "str", "(", "(", "int", "(", "os", ".", "path", ".", "getsize", "(", "outfile", ")", "/", "1000000", ")", ")", ")", "print", "(", "\"Wrote to {}: {} MB\"", ".", "format", "(", "outfile", ",", "outfile_size", ")", ")" ]
Writes choses candidates to an output file
[ "Writes", "choses", "candidates", "to", "an", "output", "file" ]
[ "\"\"\"\n Writes choses candidates to an output file\n \"\"\"" ]
[ { "param": "buffer", "type": null }, { "param": "outfile", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "buffer", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "outfile", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import os def write_file(buffer, outfile): file_handler = open(outfile, 'w') for line in buffer: file_handler.write(line.strip()+ '\n') file_handler.close() outfile_size = str((int(os.path.getsize(outfile)/1000000))) print("Wrote to {}: {} MB".format(outfile, outfile_size))
609,919
214
e624dcecc6eada3479cd88fbb62056d8dc92467d
ozturkosu/umps_code
utils.py
[ "MIT" ]
Python
no_error
<not_specific>
def no_error(val_foo, give_val=False): """Run val_foo with no inputs, test whether it raises an error""" try: val = val_foo() success = True except: val = None success = False if give_val: return success, val else: return success
Run val_foo with no inputs, test whether it raises an error
Run val_foo with no inputs, test whether it raises an error
[ "Run", "val_foo", "with", "no", "inputs", "test", "whether", "it", "raises", "an", "error" ]
def no_error(val_foo, give_val=False): try: val = val_foo() success = True except: val = None success = False if give_val: return success, val else: return success
[ "def", "no_error", "(", "val_foo", ",", "give_val", "=", "False", ")", ":", "try", ":", "val", "=", "val_foo", "(", ")", "success", "=", "True", "except", ":", "val", "=", "None", "success", "=", "False", "if", "give_val", ":", "return", "success", ",", "val", "else", ":", "return", "success" ]
Run val_foo with no inputs, test whether it raises an error
[ "Run", "val_foo", "with", "no", "inputs", "test", "whether", "it", "raises", "an", "error" ]
[ "\"\"\"Run val_foo with no inputs, test whether it raises an error\"\"\"" ]
[ { "param": "val_foo", "type": null }, { "param": "give_val", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "val_foo", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "give_val", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def no_error(val_foo, give_val=False): try: val = val_foo() success = True except: val = None success = False if give_val: return success, val else: return success
609,920
683
be0322acabc5890a2ce0a93c0618f2f524529b6f
chogba6/ONE
compiler/one-cmds/utils.py
[ "Apache-2.0" ]
Python
_parse_cfg_and_overwrite
<not_specific>
def _parse_cfg_and_overwrite(config_path, section, args): """ parse given section of configuration file and set the values of args. Even if the values parsed from the configuration file already exist in args, the values are overwritten. """ if config_path == None: # DO NOTHING return config = configparser.ConfigParser() # make option names case sensitive config.optionxform = str parsed = config.read(config_path) if not parsed: raise FileNotFoundError('Not found given configuration file') if not config.has_section(section): raise AssertionError('configuration file doesn\'t have \'' + section + '\' section') for key in config[section]: setattr(args, key, config[section][key]) # TODO support accumulated arguments
parse given section of configuration file and set the values of args. Even if the values parsed from the configuration file already exist in args, the values are overwritten.
parse given section of configuration file and set the values of args. Even if the values parsed from the configuration file already exist in args, the values are overwritten.
[ "parse", "given", "section", "of", "configuration", "file", "and", "set", "the", "values", "of", "args", ".", "Even", "if", "the", "values", "parsed", "from", "the", "configuration", "file", "already", "exist", "in", "args", "the", "values", "are", "overwritten", "." ]
def _parse_cfg_and_overwrite(config_path, section, args): if config_path == None: return config = configparser.ConfigParser() config.optionxform = str parsed = config.read(config_path) if not parsed: raise FileNotFoundError('Not found given configuration file') if not config.has_section(section): raise AssertionError('configuration file doesn\'t have \'' + section + '\' section') for key in config[section]: setattr(args, key, config[section][key])
[ "def", "_parse_cfg_and_overwrite", "(", "config_path", ",", "section", ",", "args", ")", ":", "if", "config_path", "==", "None", ":", "return", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "optionxform", "=", "str", "parsed", "=", "config", ".", "read", "(", "config_path", ")", "if", "not", "parsed", ":", "raise", "FileNotFoundError", "(", "'Not found given configuration file'", ")", "if", "not", "config", ".", "has_section", "(", "section", ")", ":", "raise", "AssertionError", "(", "'configuration file doesn\\'t have \\''", "+", "section", "+", "'\\' section'", ")", "for", "key", "in", "config", "[", "section", "]", ":", "setattr", "(", "args", ",", "key", ",", "config", "[", "section", "]", "[", "key", "]", ")" ]
parse given section of configuration file and set the values of args.
[ "parse", "given", "section", "of", "configuration", "file", "and", "set", "the", "values", "of", "args", "." ]
[ "\"\"\"\n parse given section of configuration file and set the values of args.\n Even if the values parsed from the configuration file already exist in args,\n the values are overwritten.\n \"\"\"", "# DO NOTHING", "# make option names case sensitive", "# TODO support accumulated arguments" ]
[ { "param": "config_path", "type": null }, { "param": "section", "type": null }, { "param": "args", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "config_path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "section", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "args", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import configparser def _parse_cfg_and_overwrite(config_path, section, args): if config_path == None: return config = configparser.ConfigParser() config.optionxform = str parsed = config.read(config_path) if not parsed: raise FileNotFoundError('Not found given configuration file') if not config.has_section(section): raise AssertionError('configuration file doesn\'t have \'' + section + '\' section') for key in config[section]: setattr(args, key, config[section][key])
609,921
22
f72bba260dbdc0d48d601f070334e34f0095da0b
dampierch/herv
scripts/gdc_req_legacy.py
[ "MIT" ]
Python
download_xml_manifest
null
def download_xml_manifest(files_res,dest): ''' -- create manifest object -- write manifest to file -- use manifest for bulk download ''' select = ['file_id', 'file_name', 'md5sum', 'file_size', 'state'] manifest = files_res[select] manifest.columns = ['id', 'filename', 'md5', 'size', 'state'] manifest = manifest.sort_values(by=['id']) out_file = dest + 'manifest.tsv' manifest.to_csv(out_file, sep='\t', index=False) cmd = ' '.join(['gdc-client download','-m',out_file,'-d',dest]) subprocess.call(cmd, shell=True) print('manifest downloaded')
-- create manifest object -- write manifest to file -- use manifest for bulk download
create manifest object write manifest to file use manifest for bulk download
[ "create", "manifest", "object", "write", "manifest", "to", "file", "use", "manifest", "for", "bulk", "download" ]
def download_xml_manifest(files_res,dest): select = ['file_id', 'file_name', 'md5sum', 'file_size', 'state'] manifest = files_res[select] manifest.columns = ['id', 'filename', 'md5', 'size', 'state'] manifest = manifest.sort_values(by=['id']) out_file = dest + 'manifest.tsv' manifest.to_csv(out_file, sep='\t', index=False) cmd = ' '.join(['gdc-client download','-m',out_file,'-d',dest]) subprocess.call(cmd, shell=True) print('manifest downloaded')
[ "def", "download_xml_manifest", "(", "files_res", ",", "dest", ")", ":", "select", "=", "[", "'file_id'", ",", "'file_name'", ",", "'md5sum'", ",", "'file_size'", ",", "'state'", "]", "manifest", "=", "files_res", "[", "select", "]", "manifest", ".", "columns", "=", "[", "'id'", ",", "'filename'", ",", "'md5'", ",", "'size'", ",", "'state'", "]", "manifest", "=", "manifest", ".", "sort_values", "(", "by", "=", "[", "'id'", "]", ")", "out_file", "=", "dest", "+", "'manifest.tsv'", "manifest", ".", "to_csv", "(", "out_file", ",", "sep", "=", "'\\t'", ",", "index", "=", "False", ")", "cmd", "=", "' '", ".", "join", "(", "[", "'gdc-client download'", ",", "'-m'", ",", "out_file", ",", "'-d'", ",", "dest", "]", ")", "subprocess", ".", "call", "(", "cmd", ",", "shell", "=", "True", ")", "print", "(", "'manifest downloaded'", ")" ]
create manifest object write manifest to file use manifest for bulk download
[ "create", "manifest", "object", "write", "manifest", "to", "file", "use", "manifest", "for", "bulk", "download" ]
[ "'''\n -- create manifest object\n -- write manifest to file\n -- use manifest for bulk download\n '''" ]
[ { "param": "files_res", "type": null }, { "param": "dest", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "files_res", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "dest", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import subprocess def download_xml_manifest(files_res,dest): select = ['file_id', 'file_name', 'md5sum', 'file_size', 'state'] manifest = files_res[select] manifest.columns = ['id', 'filename', 'md5', 'size', 'state'] manifest = manifest.sort_values(by=['id']) out_file = dest + 'manifest.tsv' manifest.to_csv(out_file, sep='\t', index=False) cmd = ' '.join(['gdc-client download','-m',out_file,'-d',dest]) subprocess.call(cmd, shell=True) print('manifest downloaded')
609,922
701
a911fef544a210a395b2757171caa56357504ea5
thron7/image_loader
src/image_loader/loader.py
[ "MIT" ]
Python
format_date
<not_specific>
def format_date(epocsecs): """Format epoc secs to a time string suitable for If-Modified-Since request header Example: 'Wed, 21 Oct 2015 07:28:00 GMT'""" t = time.gmtime(epocsecs) # rolling own, as time.strftime is in part locale-dependent (e.g. '%a' for short weekday) s = "Mon Tue Wed Thu Fri Sat Sun".split()[t.tm_wday] + ", " s += "%02d " % (t.tm_mday,) s += "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()[t.tm_mon - 1] + " " s += "%d %02d:%02d:%02d GMT" % (t.tm_year, t.tm_hour, t.tm_min, t.tm_sec) return s
Format epoc secs to a time string suitable for If-Modified-Since request header Example: 'Wed, 21 Oct 2015 07:28:00 GMT
Format epoc secs to a time string suitable for If-Modified-Since request header Example: 'Wed, 21 Oct 2015 07:28:00 GMT
[ "Format", "epoc", "secs", "to", "a", "time", "string", "suitable", "for", "If", "-", "Modified", "-", "Since", "request", "header", "Example", ":", "'", "Wed", "21", "Oct", "2015", "07", ":", "28", ":", "00", "GMT" ]
def format_date(epocsecs): t = time.gmtime(epocsecs) s = "Mon Tue Wed Thu Fri Sat Sun".split()[t.tm_wday] + ", " s += "%02d " % (t.tm_mday,) s += "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()[t.tm_mon - 1] + " " s += "%d %02d:%02d:%02d GMT" % (t.tm_year, t.tm_hour, t.tm_min, t.tm_sec) return s
[ "def", "format_date", "(", "epocsecs", ")", ":", "t", "=", "time", ".", "gmtime", "(", "epocsecs", ")", "s", "=", "\"Mon Tue Wed Thu Fri Sat Sun\"", ".", "split", "(", ")", "[", "t", ".", "tm_wday", "]", "+", "\", \"", "s", "+=", "\"%02d \"", "%", "(", "t", ".", "tm_mday", ",", ")", "s", "+=", "\"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec\"", ".", "split", "(", ")", "[", "t", ".", "tm_mon", "-", "1", "]", "+", "\" \"", "s", "+=", "\"%d %02d:%02d:%02d GMT\"", "%", "(", "t", ".", "tm_year", ",", "t", ".", "tm_hour", ",", "t", ".", "tm_min", ",", "t", ".", "tm_sec", ")", "return", "s" ]
Format epoc secs to a time string suitable for If-Modified-Since request header Example: 'Wed, 21 Oct 2015 07:28:00 GMT
[ "Format", "epoc", "secs", "to", "a", "time", "string", "suitable", "for", "If", "-", "Modified", "-", "Since", "request", "header", "Example", ":", "'", "Wed", "21", "Oct", "2015", "07", ":", "28", ":", "00", "GMT" ]
[ "\"\"\"Format epoc secs to a time string suitable for If-Modified-Since request header\n Example: 'Wed, 21 Oct 2015 07:28:00 GMT'\"\"\"", "# rolling own, as time.strftime is in part locale-dependent (e.g. '%a' for short weekday)" ]
[ { "param": "epocsecs", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "epocsecs", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import time def format_date(epocsecs): t = time.gmtime(epocsecs) s = "Mon Tue Wed Thu Fri Sat Sun".split()[t.tm_wday] + ", " s += "%02d " % (t.tm_mday,) s += "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()[t.tm_mon - 1] + " " s += "%d %02d:%02d:%02d GMT" % (t.tm_year, t.tm_hour, t.tm_min, t.tm_sec) return s
609,923
624
80fe892fdfc8112689befea11fa76518295fe145
meaningfy-ws/ted-sws
ted_sws/metadata_normaliser/services/metadata_normalizer.py
[ "Apache-2.0" ]
Python
normalise_form_number
str
def normalise_form_number(cls, value: str) -> str: """ Normalise form number to be F{number} format :param value: :return: """ if value and not value.startswith("F"): return "F" + value return value
Normalise form number to be F{number} format :param value: :return:
Normalise form number to be F{number} format
[ "Normalise", "form", "number", "to", "be", "F", "{", "number", "}", "format" ]
def normalise_form_number(cls, value: str) -> str: if value and not value.startswith("F"): return "F" + value return value
[ "def", "normalise_form_number", "(", "cls", ",", "value", ":", "str", ")", "->", "str", ":", "if", "value", "and", "not", "value", ".", "startswith", "(", "\"F\"", ")", ":", "return", "\"F\"", "+", "value", "return", "value" ]
Normalise form number to be F{number} format
[ "Normalise", "form", "number", "to", "be", "F", "{", "number", "}", "format" ]
[ "\"\"\"\n Normalise form number to be F{number} format\n :param value:\n :return:\n \"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "value", "type": "str" } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "value", "type": "str", "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def normalise_form_number(cls, value: str) -> str: if value and not value.startswith("F"): return "F" + value return value
609,924
372
ea531711bb458fe58da9ab61ab86f0e9155ac5ec
vesche/sickserv
sickserv/util.py
[ "MIT" ]
Python
base64_decode
<not_specific>
def base64_decode(data): """ base64 decode data, will convert given strings to bytes. Returns base64 decoded value as a string or bytes as appropriate. """ if type(data) == str: data = str.encode(data) try: return base64.decodebytes(data).decode('utf-8') except UnicodeDecodeError: return base64.decodebytes(data)
base64 decode data, will convert given strings to bytes. Returns base64 decoded value as a string or bytes as appropriate.
base64 decode data, will convert given strings to bytes. Returns base64 decoded value as a string or bytes as appropriate.
[ "base64", "decode", "data", "will", "convert", "given", "strings", "to", "bytes", ".", "Returns", "base64", "decoded", "value", "as", "a", "string", "or", "bytes", "as", "appropriate", "." ]
def base64_decode(data): if type(data) == str: data = str.encode(data) try: return base64.decodebytes(data).decode('utf-8') except UnicodeDecodeError: return base64.decodebytes(data)
[ "def", "base64_decode", "(", "data", ")", ":", "if", "type", "(", "data", ")", "==", "str", ":", "data", "=", "str", ".", "encode", "(", "data", ")", "try", ":", "return", "base64", ".", "decodebytes", "(", "data", ")", ".", "decode", "(", "'utf-8'", ")", "except", "UnicodeDecodeError", ":", "return", "base64", ".", "decodebytes", "(", "data", ")" ]
base64 decode data, will convert given strings to bytes.
[ "base64", "decode", "data", "will", "convert", "given", "strings", "to", "bytes", "." ]
[ "\"\"\"\n base64 decode data, will convert given strings to bytes.\n Returns base64 decoded value as a string or bytes as appropriate.\n \"\"\"" ]
[ { "param": "data", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "data", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import base64 def base64_decode(data): if type(data) == str: data = str.encode(data) try: return base64.decodebytes(data).decode('utf-8') except UnicodeDecodeError: return base64.decodebytes(data)
609,925
585
360890dccf6b4917ba7a3aa8193f7b1c11411c7b
technobunny/crypto-tax
crypto_taxes.py
[ "MIT" ]
Python
read_file
list[str]
def read_file(file_name: str) -> list[str]: """Read a file and slurp the lines""" logging.debug('Reading from %s', file_name) lines = [] try: with open(file_name, 'rt', encoding='UTF8') as infile: lines = infile.readlines() except FileNotFoundError: logging.error('File not found: %s', file_name) return lines
Read a file and slurp the lines
Read a file and slurp the lines
[ "Read", "a", "file", "and", "slurp", "the", "lines" ]
def read_file(file_name: str) -> list[str]: logging.debug('Reading from %s', file_name) lines = [] try: with open(file_name, 'rt', encoding='UTF8') as infile: lines = infile.readlines() except FileNotFoundError: logging.error('File not found: %s', file_name) return lines
[ "def", "read_file", "(", "file_name", ":", "str", ")", "->", "list", "[", "str", "]", ":", "logging", ".", "debug", "(", "'Reading from %s'", ",", "file_name", ")", "lines", "=", "[", "]", "try", ":", "with", "open", "(", "file_name", ",", "'rt'", ",", "encoding", "=", "'UTF8'", ")", "as", "infile", ":", "lines", "=", "infile", ".", "readlines", "(", ")", "except", "FileNotFoundError", ":", "logging", ".", "error", "(", "'File not found: %s'", ",", "file_name", ")", "return", "lines" ]
Read a file and slurp the lines
[ "Read", "a", "file", "and", "slurp", "the", "lines" ]
[ "\"\"\"Read a file and slurp the lines\"\"\"" ]
[ { "param": "file_name", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "file_name", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import logging def read_file(file_name: str) -> list[str]: logging.debug('Reading from %s', file_name) lines = [] try: with open(file_name, 'rt', encoding='UTF8') as infile: lines = infile.readlines() except FileNotFoundError: logging.error('File not found: %s', file_name) return lines
609,926
678
cb880b9d0d5cda46dcf587c03425e8efe93b3c5c
mattianeroni/2DBinPacking
packing.py
[ "MIT" ]
Python
_split
<not_specific>
def _split (space, overlap): """ This is a private method used only by the Maximal Rectangle algorithms that follow. Given an overlap resulting from a newly placed case and a space, this method split the space in maximum 4 other spaces all around the overlap. :param space: The space :param overlap: The overlap :return: The list of new spaces that will replace the original one. """ x1, y1, sizex1, sizey1 = space x2, y2, sizex2, sizey2 = overlap newspaces = [None, None, None, None] if x1 < x2: newspaces[0] = (x1, y1, x2 - x1, sizey1) if (a := x1 + sizex1) > (b := x2 + sizex2): newspaces[1] = (b, y1, a - b, sizey1) if y1 < y2: newspaces[2] = (x1, y1, sizex1, y2 - y1) if (a := y1 + sizey1) > (b := y2 + sizey2): newspaces[3] = (x1, b, sizex1, a - b) return list(filter(None, newspaces))
This is a private method used only by the Maximal Rectangle algorithms that follow. Given an overlap resulting from a newly placed case and a space, this method split the space in maximum 4 other spaces all around the overlap. :param space: The space :param overlap: The overlap :return: The list of new spaces that will replace the original one.
This is a private method used only by the Maximal Rectangle algorithms that follow. Given an overlap resulting from a newly placed case and a space, this method split the space in maximum 4 other spaces all around the overlap.
[ "This", "is", "a", "private", "method", "used", "only", "by", "the", "Maximal", "Rectangle", "algorithms", "that", "follow", ".", "Given", "an", "overlap", "resulting", "from", "a", "newly", "placed", "case", "and", "a", "space", "this", "method", "split", "the", "space", "in", "maximum", "4", "other", "spaces", "all", "around", "the", "overlap", "." ]
def _split (space, overlap): x1, y1, sizex1, sizey1 = space x2, y2, sizex2, sizey2 = overlap newspaces = [None, None, None, None] if x1 < x2: newspaces[0] = (x1, y1, x2 - x1, sizey1) if (a := x1 + sizex1) > (b := x2 + sizex2): newspaces[1] = (b, y1, a - b, sizey1) if y1 < y2: newspaces[2] = (x1, y1, sizex1, y2 - y1) if (a := y1 + sizey1) > (b := y2 + sizey2): newspaces[3] = (x1, b, sizex1, a - b) return list(filter(None, newspaces))
[ "def", "_split", "(", "space", ",", "overlap", ")", ":", "x1", ",", "y1", ",", "sizex1", ",", "sizey1", "=", "space", "x2", ",", "y2", ",", "sizex2", ",", "sizey2", "=", "overlap", "newspaces", "=", "[", "None", ",", "None", ",", "None", ",", "None", "]", "if", "x1", "<", "x2", ":", "newspaces", "[", "0", "]", "=", "(", "x1", ",", "y1", ",", "x2", "-", "x1", ",", "sizey1", ")", "if", "(", "a", ":=", "x1", "+", "sizex1", ")", ">", "(", "b", ":=", "x2", "+", "sizex2", ")", ":", "newspaces", "[", "1", "]", "=", "(", "b", ",", "y1", ",", "a", "-", "b", ",", "sizey1", ")", "if", "y1", "<", "y2", ":", "newspaces", "[", "2", "]", "=", "(", "x1", ",", "y1", ",", "sizex1", ",", "y2", "-", "y1", ")", "if", "(", "a", ":=", "y1", "+", "sizey1", ")", ">", "(", "b", ":=", "y2", "+", "sizey2", ")", ":", "newspaces", "[", "3", "]", "=", "(", "x1", ",", "b", ",", "sizex1", ",", "a", "-", "b", ")", "return", "list", "(", "filter", "(", "None", ",", "newspaces", ")", ")" ]
This is a private method used only by the Maximal Rectangle algorithms that follow.
[ "This", "is", "a", "private", "method", "used", "only", "by", "the", "Maximal", "Rectangle", "algorithms", "that", "follow", "." ]
[ "\"\"\"\n This is a private method used only by the Maximal Rectangle algorithms that follow.\n\n Given an overlap resulting from a newly placed case and a space, this method\n split the space in maximum 4 other spaces all around the overlap.\n\n :param space: The space\n :param overlap: The overlap\n :return: The list of new spaces that will replace the original one.\n\n \"\"\"" ]
[ { "param": "space", "type": null }, { "param": "overlap", "type": null } ]
{ "returns": [ { "docstring": "The list of new spaces that will replace the original one.", "docstring_tokens": [ "The", "list", "of", "new", "spaces", "that", "will", "replace", "the", "original", "one", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "space", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "overlap", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def _split (space, overlap): x1, y1, sizex1, sizey1 = space x2, y2, sizex2, sizey2 = overlap newspaces = [None, None, None, None] if x1 < x2: newspaces[0] = (x1, y1, x2 - x1, sizey1) if (a := x1 + sizex1) > (b := x2 + sizex2): newspaces[1] = (b, y1, a - b, sizey1) if y1 < y2: newspaces[2] = (x1, y1, sizex1, y2 - y1) if (a := y1 + sizey1) > (b := y2 + sizey2): newspaces[3] = (x1, b, sizex1, a - b) return list(filter(None, newspaces))
609,927
767
190ceab4e101c04d5d428bfab60189e454eb3124
iotile/python_iotile_cloud
iotile_cloud/utils/mock_cloud.py
[ "MIT" ]
Python
mock_cloud_private_nossl
null
def mock_cloud_private_nossl(mock_cloud_nossl): """A Mock cloud instance that is reset after each test function without ssl.""" domain, cloud = mock_cloud_nossl cloud.reset() yield domain, cloud cloud.reset()
A Mock cloud instance that is reset after each test function without ssl.
A Mock cloud instance that is reset after each test function without ssl.
[ "A", "Mock", "cloud", "instance", "that", "is", "reset", "after", "each", "test", "function", "without", "ssl", "." ]
def mock_cloud_private_nossl(mock_cloud_nossl): domain, cloud = mock_cloud_nossl cloud.reset() yield domain, cloud cloud.reset()
[ "def", "mock_cloud_private_nossl", "(", "mock_cloud_nossl", ")", ":", "domain", ",", "cloud", "=", "mock_cloud_nossl", "cloud", ".", "reset", "(", ")", "yield", "domain", ",", "cloud", "cloud", ".", "reset", "(", ")" ]
A Mock cloud instance that is reset after each test function without ssl.
[ "A", "Mock", "cloud", "instance", "that", "is", "reset", "after", "each", "test", "function", "without", "ssl", "." ]
[ "\"\"\"A Mock cloud instance that is reset after each test function without ssl.\"\"\"" ]
[ { "param": "mock_cloud_nossl", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "mock_cloud_nossl", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def mock_cloud_private_nossl(mock_cloud_nossl): domain, cloud = mock_cloud_nossl cloud.reset() yield domain, cloud cloud.reset()
609,928
610
f09219b3d28d15160cb321829babb7a1ed4b548e
robcxyz/tackle-box
tackle/repository.py
[ "BSD-3-Clause" ]
Python
is_repo_url
<not_specific>
def is_repo_url(value): """Return True if value is a repository URL.""" REPO_REGEX = re.compile( r""" # something like git:// ssh:// file:// etc. ((((git|hg)\+)?(git|ssh|file|https?):(//)?) | # or (\w+@[\w\.]+) # something like user@... ) """, re.VERBOSE, ) return bool(REPO_REGEX.match(value))
Return True if value is a repository URL.
Return True if value is a repository URL.
[ "Return", "True", "if", "value", "is", "a", "repository", "URL", "." ]
def is_repo_url(value): REPO_REGEX = re.compile( r""" # something like git:// ssh:// file:// etc. ((((git|hg)\+)?(git|ssh|file|https?):(//)?) | # or (\w+@[\w\.]+) # something like user@... ) """, re.VERBOSE, ) return bool(REPO_REGEX.match(value))
[ "def", "is_repo_url", "(", "value", ")", ":", "REPO_REGEX", "=", "re", ".", "compile", "(", "r\"\"\"\n # something like git:// ssh:// file:// etc.\n ((((git|hg)\\+)?(git|ssh|file|https?):(//)?)\n | # or\n (\\w+@[\\w\\.]+) # something like user@...\n )\n \"\"\"", ",", "re", ".", "VERBOSE", ",", ")", "return", "bool", "(", "REPO_REGEX", ".", "match", "(", "value", ")", ")" ]
Return True if value is a repository URL.
[ "Return", "True", "if", "value", "is", "a", "repository", "URL", "." ]
[ "\"\"\"Return True if value is a repository URL.\"\"\"" ]
[ { "param": "value", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "value", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import re def is_repo_url(value): REPO_REGEX = re.compile( r""" # something like git:// ssh:// file:// etc. ((((git|hg)\+)?(git|ssh|file|https?):(//)?) | # or (\w+@[\w\.]+) # something like user@... ) """, re.VERBOSE, ) return bool(REPO_REGEX.match(value))
609,929
337
f20b9af06952e58f53f3dd39736bf9c9cbf21b11
kbjunky/MacroPact
src/kmk/handlers/layers.py
[ "MIT" ]
Python
tg_pressed
<not_specific>
def tg_pressed(key, state, *args, **kwargs): ''' Toggles the layer (enables it if not active, and vise versa) ''' # See mo_released for implementation details around this try: del_idx = state.active_layers.index(key.meta.layer) del state.active_layers[del_idx] except ValueError: state.active_layers.insert(0, key.meta.layer) return state
Toggles the layer (enables it if not active, and vise versa)
Toggles the layer (enables it if not active, and vise versa)
[ "Toggles", "the", "layer", "(", "enables", "it", "if", "not", "active", "and", "vise", "versa", ")" ]
def tg_pressed(key, state, *args, **kwargs): try: del_idx = state.active_layers.index(key.meta.layer) del state.active_layers[del_idx] except ValueError: state.active_layers.insert(0, key.meta.layer) return state
[ "def", "tg_pressed", "(", "key", ",", "state", ",", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "del_idx", "=", "state", ".", "active_layers", ".", "index", "(", "key", ".", "meta", ".", "layer", ")", "del", "state", ".", "active_layers", "[", "del_idx", "]", "except", "ValueError", ":", "state", ".", "active_layers", ".", "insert", "(", "0", ",", "key", ".", "meta", ".", "layer", ")", "return", "state" ]
Toggles the layer (enables it if not active, and vise versa)
[ "Toggles", "the", "layer", "(", "enables", "it", "if", "not", "active", "and", "vise", "versa", ")" ]
[ "'''\n Toggles the layer (enables it if not active, and vise versa)\n '''", "# See mo_released for implementation details around this" ]
[ { "param": "key", "type": null }, { "param": "state", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "key", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "state", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def tg_pressed(key, state, *args, **kwargs): try: del_idx = state.active_layers.index(key.meta.layer) del state.active_layers[del_idx] except ValueError: state.active_layers.insert(0, key.meta.layer) return state
609,930
864
bdca899daf06b868fd1d3af392e3239d858fb711
sdpython/csharpy
csharpy/notebook/csmagics.py
[ "MIT" ]
Python
_linearise_args
<not_specific>
def _linearise_args(ll): "Makes the list of lists into a list." if ll is None: return None res = [] for el in ll: if isinstance(el, list): res.extend(el) else: res.append(el) return res
Makes the list of lists into a list.
Makes the list of lists into a list.
[ "Makes", "the", "list", "of", "lists", "into", "a", "list", "." ]
def _linearise_args(ll): if ll is None: return None res = [] for el in ll: if isinstance(el, list): res.extend(el) else: res.append(el) return res
[ "def", "_linearise_args", "(", "ll", ")", ":", "if", "ll", "is", "None", ":", "return", "None", "res", "=", "[", "]", "for", "el", "in", "ll", ":", "if", "isinstance", "(", "el", ",", "list", ")", ":", "res", ".", "extend", "(", "el", ")", "else", ":", "res", ".", "append", "(", "el", ")", "return", "res" ]
Makes the list of lists into a list.
[ "Makes", "the", "list", "of", "lists", "into", "a", "list", "." ]
[ "\"Makes the list of lists into a list.\"" ]
[ { "param": "ll", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ll", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def _linearise_args(ll): if ll is None: return None res = [] for el in ll: if isinstance(el, list): res.extend(el) else: res.append(el) return res
609,931
296
0d278e6412254b7dea8174bfe6eae9c27471c3de
mianmian3/kaldi
egs/madcat_ar/v1/local/tl/process_waldo_data.py
[ "Apache-2.0" ]
Python
read_image_text
<not_specific>
def read_image_text(image_text_path): """ Given the file path containing, mapping information of line image and transcription, it returns a dict. The dict contains this mapping info. It can be accessed via line_id and will provide transcription. Returns: -------- dict: line_id and transcription mapping """ image_transcription_dict = dict() with open(image_text_path, encoding='utf-8') as f: for line in f: line_vect = line.strip().split(' ') image_path = line_vect[0] line_id = os.path.basename(image_path).split('.png')[0] transcription = line_vect[1:] joined_transcription = list() for word in transcription: joined_transcription.append(word) joined_transcription = " ".join(joined_transcription) image_transcription_dict[line_id] = joined_transcription return image_transcription_dict
Given the file path containing, mapping information of line image and transcription, it returns a dict. The dict contains this mapping info. It can be accessed via line_id and will provide transcription. Returns: -------- dict: line_id and transcription mapping
Given the file path containing, mapping information of line image and transcription, it returns a dict. The dict contains this mapping info. It can be accessed via line_id and will provide transcription.
[ "Given", "the", "file", "path", "containing", "mapping", "information", "of", "line", "image", "and", "transcription", "it", "returns", "a", "dict", ".", "The", "dict", "contains", "this", "mapping", "info", ".", "It", "can", "be", "accessed", "via", "line_id", "and", "will", "provide", "transcription", "." ]
def read_image_text(image_text_path): image_transcription_dict = dict() with open(image_text_path, encoding='utf-8') as f: for line in f: line_vect = line.strip().split(' ') image_path = line_vect[0] line_id = os.path.basename(image_path).split('.png')[0] transcription = line_vect[1:] joined_transcription = list() for word in transcription: joined_transcription.append(word) joined_transcription = " ".join(joined_transcription) image_transcription_dict[line_id] = joined_transcription return image_transcription_dict
[ "def", "read_image_text", "(", "image_text_path", ")", ":", "image_transcription_dict", "=", "dict", "(", ")", "with", "open", "(", "image_text_path", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "line_vect", "=", "line", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", "image_path", "=", "line_vect", "[", "0", "]", "line_id", "=", "os", ".", "path", ".", "basename", "(", "image_path", ")", ".", "split", "(", "'.png'", ")", "[", "0", "]", "transcription", "=", "line_vect", "[", "1", ":", "]", "joined_transcription", "=", "list", "(", ")", "for", "word", "in", "transcription", ":", "joined_transcription", ".", "append", "(", "word", ")", "joined_transcription", "=", "\" \"", ".", "join", "(", "joined_transcription", ")", "image_transcription_dict", "[", "line_id", "]", "=", "joined_transcription", "return", "image_transcription_dict" ]
Given the file path containing, mapping information of line image and transcription, it returns a dict.
[ "Given", "the", "file", "path", "containing", "mapping", "information", "of", "line", "image", "and", "transcription", "it", "returns", "a", "dict", "." ]
[ "\"\"\" Given the file path containing, mapping information of line image\n and transcription, it returns a dict. The dict contains this mapping\n info. It can be accessed via line_id and will provide transcription.\n Returns:\n --------\n dict: line_id and transcription mapping\n \"\"\"" ]
[ { "param": "image_text_path", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "image_text_path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import os def read_image_text(image_text_path): image_transcription_dict = dict() with open(image_text_path, encoding='utf-8') as f: for line in f: line_vect = line.strip().split(' ') image_path = line_vect[0] line_id = os.path.basename(image_path).split('.png')[0] transcription = line_vect[1:] joined_transcription = list() for word in transcription: joined_transcription.append(word) joined_transcription = " ".join(joined_transcription) image_transcription_dict[line_id] = joined_transcription return image_transcription_dict
609,932
256
6e113e6fab38430504da502afb8883f6968984b5
Cologler/py.jasily.cologler
jasily/format/utils.py
[ "MIT" ]
Python
object_to_primitive
<not_specific>
def object_to_primitive(obj): ''' convert object to primitive type so we can serialize it to data format like python. all primitive types: dict, list, int, float, bool, str, None ''' if obj is None: return obj if isinstance(obj, (int, float, bool, str)): return obj if isinstance(obj, (list, frozenset, set)): return [object_to_primitive(x) for x in obj] if isinstance(obj, dict): return dict([(object_to_primitive(k), object_to_primitive(v)) for k, v in obj.items()]) data = vars(obj) assert isinstance(data, dict) return object_to_primitive(data)
convert object to primitive type so we can serialize it to data format like python. all primitive types: dict, list, int, float, bool, str, None
convert object to primitive type so we can serialize it to data format like python. all primitive types: dict, list, int, float, bool, str, None
[ "convert", "object", "to", "primitive", "type", "so", "we", "can", "serialize", "it", "to", "data", "format", "like", "python", ".", "all", "primitive", "types", ":", "dict", "list", "int", "float", "bool", "str", "None" ]
def object_to_primitive(obj): if obj is None: return obj if isinstance(obj, (int, float, bool, str)): return obj if isinstance(obj, (list, frozenset, set)): return [object_to_primitive(x) for x in obj] if isinstance(obj, dict): return dict([(object_to_primitive(k), object_to_primitive(v)) for k, v in obj.items()]) data = vars(obj) assert isinstance(data, dict) return object_to_primitive(data)
[ "def", "object_to_primitive", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "obj", "if", "isinstance", "(", "obj", ",", "(", "int", ",", "float", ",", "bool", ",", "str", ")", ")", ":", "return", "obj", "if", "isinstance", "(", "obj", ",", "(", "list", ",", "frozenset", ",", "set", ")", ")", ":", "return", "[", "object_to_primitive", "(", "x", ")", "for", "x", "in", "obj", "]", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "dict", "(", "[", "(", "object_to_primitive", "(", "k", ")", ",", "object_to_primitive", "(", "v", ")", ")", "for", "k", ",", "v", "in", "obj", ".", "items", "(", ")", "]", ")", "data", "=", "vars", "(", "obj", ")", "assert", "isinstance", "(", "data", ",", "dict", ")", "return", "object_to_primitive", "(", "data", ")" ]
convert object to primitive type so we can serialize it to data format like python.
[ "convert", "object", "to", "primitive", "type", "so", "we", "can", "serialize", "it", "to", "data", "format", "like", "python", "." ]
[ "'''\n convert object to primitive type so we can serialize it to data format like python.\n\n all primitive types: dict, list, int, float, bool, str, None\n '''" ]
[ { "param": "obj", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "obj", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def object_to_primitive(obj): if obj is None: return obj if isinstance(obj, (int, float, bool, str)): return obj if isinstance(obj, (list, frozenset, set)): return [object_to_primitive(x) for x in obj] if isinstance(obj, dict): return dict([(object_to_primitive(k), object_to_primitive(v)) for k, v in obj.items()]) data = vars(obj) assert isinstance(data, dict) return object_to_primitive(data)
609,933
644
2344027eec123f7471a0431fd4f4fafbfc3b7da4
euro-hpc-pl/omnisolver-pt
omnisolver/pt/algorithm.py
[ "Apache-2.0" ]
Python
exchange_states
null
def exchange_states(replica_1, replica_2): """Exchange state and energies of two replicas. This function exchanges current states and energies between replicas. All other properties of replicas stay the same. In particular, best energies and best states found so far by each replica remain unchanged. Temperatures (beta) also remain unchanged. This is important for the implementation of PTSampler. """ replica_1.current_energy, replica_2.current_energy = ( replica_2.current_energy, replica_1.current_energy, ) replica_1.current_state, replica_2.current_state = ( replica_2.current_state, replica_1.current_state, )
Exchange state and energies of two replicas. This function exchanges current states and energies between replicas. All other properties of replicas stay the same. In particular, best energies and best states found so far by each replica remain unchanged. Temperatures (beta) also remain unchanged. This is important for the implementation of PTSampler.
Exchange state and energies of two replicas. This function exchanges current states and energies between replicas. All other properties of replicas stay the same. In particular, best energies and best states found so far by each replica remain unchanged. Temperatures (beta) also remain unchanged. This is important for the implementation of PTSampler.
[ "Exchange", "state", "and", "energies", "of", "two", "replicas", ".", "This", "function", "exchanges", "current", "states", "and", "energies", "between", "replicas", ".", "All", "other", "properties", "of", "replicas", "stay", "the", "same", ".", "In", "particular", "best", "energies", "and", "best", "states", "found", "so", "far", "by", "each", "replica", "remain", "unchanged", ".", "Temperatures", "(", "beta", ")", "also", "remain", "unchanged", ".", "This", "is", "important", "for", "the", "implementation", "of", "PTSampler", "." ]
def exchange_states(replica_1, replica_2): replica_1.current_energy, replica_2.current_energy = ( replica_2.current_energy, replica_1.current_energy, ) replica_1.current_state, replica_2.current_state = ( replica_2.current_state, replica_1.current_state, )
[ "def", "exchange_states", "(", "replica_1", ",", "replica_2", ")", ":", "replica_1", ".", "current_energy", ",", "replica_2", ".", "current_energy", "=", "(", "replica_2", ".", "current_energy", ",", "replica_1", ".", "current_energy", ",", ")", "replica_1", ".", "current_state", ",", "replica_2", ".", "current_state", "=", "(", "replica_2", ".", "current_state", ",", "replica_1", ".", "current_state", ",", ")" ]
Exchange state and energies of two replicas.
[ "Exchange", "state", "and", "energies", "of", "two", "replicas", "." ]
[ "\"\"\"Exchange state and energies of two replicas.\n\n This function exchanges current states and energies between replicas.\n All other properties of replicas stay the same. In particular, best energies\n and best states found so far by each replica remain unchanged. Temperatures (beta)\n also remain unchanged. This is important for the implementation of PTSampler.\n \"\"\"" ]
[ { "param": "replica_1", "type": null }, { "param": "replica_2", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "replica_1", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "replica_2", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def exchange_states(replica_1, replica_2): replica_1.current_energy, replica_2.current_energy = ( replica_2.current_energy, replica_1.current_energy, ) replica_1.current_state, replica_2.current_state = ( replica_2.current_state, replica_1.current_state, )
609,935
937
09e71da28751551d728c545afccb4f1a8dc61b19
ritikramuka/python-teos
common/appointment.py
[ "MIT" ]
Python
from_dict
<not_specific>
def from_dict(cls, appointment_data): """ Builds an appointment from a dictionary. Args: appointment_data (:obj:`dict`): a dictionary containing the following keys: ``{locator, to_self_delay, encrypted_blob}`` Returns: :obj:`Appointment`: An appointment initialized using the provided data. Raises: ValueError: If one of the mandatory keys is missing in ``appointment_data``. """ locator = appointment_data.get("locator") encrypted_blob = appointment_data.get("encrypted_blob") to_self_delay = appointment_data.get("to_self_delay") if any(v is None for v in [locator, to_self_delay, encrypted_blob]): raise ValueError("Wrong appointment data, some fields are missing") return cls(locator, encrypted_blob, to_self_delay)
Builds an appointment from a dictionary. Args: appointment_data (:obj:`dict`): a dictionary containing the following keys: ``{locator, to_self_delay, encrypted_blob}`` Returns: :obj:`Appointment`: An appointment initialized using the provided data. Raises: ValueError: If one of the mandatory keys is missing in ``appointment_data``.
Builds an appointment from a dictionary.
[ "Builds", "an", "appointment", "from", "a", "dictionary", "." ]
def from_dict(cls, appointment_data): locator = appointment_data.get("locator") encrypted_blob = appointment_data.get("encrypted_blob") to_self_delay = appointment_data.get("to_self_delay") if any(v is None for v in [locator, to_self_delay, encrypted_blob]): raise ValueError("Wrong appointment data, some fields are missing") return cls(locator, encrypted_blob, to_self_delay)
[ "def", "from_dict", "(", "cls", ",", "appointment_data", ")", ":", "locator", "=", "appointment_data", ".", "get", "(", "\"locator\"", ")", "encrypted_blob", "=", "appointment_data", ".", "get", "(", "\"encrypted_blob\"", ")", "to_self_delay", "=", "appointment_data", ".", "get", "(", "\"to_self_delay\"", ")", "if", "any", "(", "v", "is", "None", "for", "v", "in", "[", "locator", ",", "to_self_delay", ",", "encrypted_blob", "]", ")", ":", "raise", "ValueError", "(", "\"Wrong appointment data, some fields are missing\"", ")", "return", "cls", "(", "locator", ",", "encrypted_blob", ",", "to_self_delay", ")" ]
Builds an appointment from a dictionary.
[ "Builds", "an", "appointment", "from", "a", "dictionary", "." ]
[ "\"\"\"\n Builds an appointment from a dictionary.\n\n Args:\n appointment_data (:obj:`dict`): a dictionary containing the following keys:\n ``{locator, to_self_delay, encrypted_blob}``\n\n Returns:\n :obj:`Appointment`: An appointment initialized using the provided data.\n\n Raises:\n ValueError: If one of the mandatory keys is missing in ``appointment_data``.\n \"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "appointment_data", "type": null } ]
{ "returns": [ { "docstring": ":obj:`Appointment`: An appointment initialized using the provided data.", "docstring_tokens": [ ":", "obj", ":", "`", "Appointment", "`", ":", "An", "appointment", "initialized", "using", "the", "provided", "data", "." ], "type": null } ], "raises": [ { "docstring": "If one of the mandatory keys is missing in ``appointment_data``.", "docstring_tokens": [ "If", "one", "of", "the", "mandatory", "keys", "is", "missing", "in", "`", "`", "appointment_data", "`", "`", "." ], "type": "ValueError" } ], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "appointment_data", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [ { "identifier": "appointment_data (", "type": null, "docstring": "`dict`): a dictionary containing the following keys:\n``{locator, to_self_delay, encrypted_blob}``", "docstring_tokens": [ "`", "dict", "`", ")", ":", "a", "dictionary", "containing", "the", "following", "keys", ":", "`", "`", "{", "locator", "to_self_delay", "encrypted_blob", "}", "`", "`" ], "default": null, "is_optional": null } ], "others": [] }
def from_dict(cls, appointment_data): locator = appointment_data.get("locator") encrypted_blob = appointment_data.get("encrypted_blob") to_self_delay = appointment_data.get("to_self_delay") if any(v is None for v in [locator, to_self_delay, encrypted_blob]): raise ValueError("Wrong appointment data, some fields are missing") return cls(locator, encrypted_blob, to_self_delay)
609,936
424
7aea3108df3ea09087bdf3733f96b84d390c5c62
jduanen/avuePTZ
avueLogger.py
[ "MIT" ]
Python
macAddress
<not_specific>
def macAddress(hostname): """Return the MAC address and interface name used to reach the given host Returns usable strings on error. Inputs: hostname: string name of the target host Returns: string name and string form of MAC address of interface used to reach the given host """ ipAddr = socket.gethostbyname(hostname) match = re.search(r"^.* dev (.*?) .*$", str(subprocess.check_output(["ip", "route", "get", ipAddr]))) if not match: logging.warning(f"Unable to find interface for {ipAddr}") return "n/a", "00:00:00:00:00:00" intf = match.group(1) try: macAddr = subprocess.check_output(["cat", f"/sys/class/net/{intf}/address"]).strip().decode("utf-8") except Exception as ex: logging.warning("Failed to get MAC address for '{hostname}': {ex}") return "n/a", "00:00:00:00:00:00" return intf, macAddr
Return the MAC address and interface name used to reach the given host Returns usable strings on error. Inputs: hostname: string name of the target host Returns: string name and string form of MAC address of interface used to reach the given host
Return the MAC address and interface name used to reach the given host Returns usable strings on error. string name of the target host Returns: string name and string form of MAC address of interface used to reach the given host
[ "Return", "the", "MAC", "address", "and", "interface", "name", "used", "to", "reach", "the", "given", "host", "Returns", "usable", "strings", "on", "error", ".", "string", "name", "of", "the", "target", "host", "Returns", ":", "string", "name", "and", "string", "form", "of", "MAC", "address", "of", "interface", "used", "to", "reach", "the", "given", "host" ]
def macAddress(hostname): ipAddr = socket.gethostbyname(hostname) match = re.search(r"^.* dev (.*?) .*$", str(subprocess.check_output(["ip", "route", "get", ipAddr]))) if not match: logging.warning(f"Unable to find interface for {ipAddr}") return "n/a", "00:00:00:00:00:00" intf = match.group(1) try: macAddr = subprocess.check_output(["cat", f"/sys/class/net/{intf}/address"]).strip().decode("utf-8") except Exception as ex: logging.warning("Failed to get MAC address for '{hostname}': {ex}") return "n/a", "00:00:00:00:00:00" return intf, macAddr
[ "def", "macAddress", "(", "hostname", ")", ":", "ipAddr", "=", "socket", ".", "gethostbyname", "(", "hostname", ")", "match", "=", "re", ".", "search", "(", "r\"^.* dev (.*?) .*$\"", ",", "str", "(", "subprocess", ".", "check_output", "(", "[", "\"ip\"", ",", "\"route\"", ",", "\"get\"", ",", "ipAddr", "]", ")", ")", ")", "if", "not", "match", ":", "logging", ".", "warning", "(", "f\"Unable to find interface for {ipAddr}\"", ")", "return", "\"n/a\"", ",", "\"00:00:00:00:00:00\"", "intf", "=", "match", ".", "group", "(", "1", ")", "try", ":", "macAddr", "=", "subprocess", ".", "check_output", "(", "[", "\"cat\"", ",", "f\"/sys/class/net/{intf}/address\"", "]", ")", ".", "strip", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", "except", "Exception", "as", "ex", ":", "logging", ".", "warning", "(", "\"Failed to get MAC address for '{hostname}': {ex}\"", ")", "return", "\"n/a\"", ",", "\"00:00:00:00:00:00\"", "return", "intf", ",", "macAddr" ]
Return the MAC address and interface name used to reach the given host Returns usable strings on error.
[ "Return", "the", "MAC", "address", "and", "interface", "name", "used", "to", "reach", "the", "given", "host", "Returns", "usable", "strings", "on", "error", "." ]
[ "\"\"\"Return the MAC address and interface name used to reach the given host\n\n Returns usable strings on error.\n\n Inputs:\n hostname: string name of the target host\n Returns: string name and string form of MAC address of interface used to\n reach the given host\n \"\"\"" ]
[ { "param": "hostname", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "hostname", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import logging import subprocess import re import socket def macAddress(hostname): ipAddr = socket.gethostbyname(hostname) match = re.search(r"^.* dev (.*?) .*$", str(subprocess.check_output(["ip", "route", "get", ipAddr]))) if not match: logging.warning(f"Unable to find interface for {ipAddr}") return "n/a", "00:00:00:00:00:00" intf = match.group(1) try: macAddr = subprocess.check_output(["cat", f"/sys/class/net/{intf}/address"]).strip().decode("utf-8") except Exception as ex: logging.warning("Failed to get MAC address for '{hostname}': {ex}") return "n/a", "00:00:00:00:00:00" return intf, macAddr
609,937
268
5dc5c09187e9c46c5a522ae32662d1f765b564bb
LAL/openstack-lease-it
openstack_lease_it/lease_it/notification/MailNotification.py
[ "Apache-2.0" ]
Python
format_user_instances
<not_specific>
def format_user_instances(user): """ Create a string w/ the list of instance formatted to be mailed :param user: user we currently notify :return: string """ text = "" for instance in user: text += " - {name} started {created_at} and expire {lease_end} \n".format(**instance) return text
Create a string w/ the list of instance formatted to be mailed :param user: user we currently notify :return: string
Create a string w/ the list of instance formatted to be mailed
[ "Create", "a", "string", "w", "/", "the", "list", "of", "instance", "formatted", "to", "be", "mailed" ]
def format_user_instances(user): text = "" for instance in user: text += " - {name} started {created_at} and expire {lease_end} \n".format(**instance) return text
[ "def", "format_user_instances", "(", "user", ")", ":", "text", "=", "\"\"", "for", "instance", "in", "user", ":", "text", "+=", "\" - {name} started {created_at} and expire {lease_end} \\n\"", ".", "format", "(", "**", "instance", ")", "return", "text" ]
Create a string w/ the list of instance formatted to be mailed
[ "Create", "a", "string", "w", "/", "the", "list", "of", "instance", "formatted", "to", "be", "mailed" ]
[ "\"\"\"\n Create a string w/ the list of instance formatted to be mailed\n :param user: user we currently notify\n :return: string\n \"\"\"" ]
[ { "param": "user", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "user", "type": null, "docstring": "user we currently notify", "docstring_tokens": [ "user", "we", "currently", "notify" ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def format_user_instances(user): text = "" for instance in user: text += " - {name} started {created_at} and expire {lease_end} \n".format(**instance) return text
609,938
410
2586409b0a2ebc8e17d79b2b1185879037447613
jphuart/swatplus-automatic-workflow
qswatplus/swatgraph.py
[ "MIT" ]
Python
makeFloat
<not_specific>
def makeFloat(s): """Parse string s as float and return; return nan on failure.""" try: return float(s) except Exception: return float('nan')
Parse string s as float and return; return nan on failure.
Parse string s as float and return; return nan on failure.
[ "Parse", "string", "s", "as", "float", "and", "return", ";", "return", "nan", "on", "failure", "." ]
def makeFloat(s): try: return float(s) except Exception: return float('nan')
[ "def", "makeFloat", "(", "s", ")", ":", "try", ":", "return", "float", "(", "s", ")", "except", "Exception", ":", "return", "float", "(", "'nan'", ")" ]
Parse string s as float and return; return nan on failure.
[ "Parse", "string", "s", "as", "float", "and", "return", ";", "return", "nan", "on", "failure", "." ]
[ "\"\"\"Parse string s as float and return; return nan on failure.\"\"\"" ]
[ { "param": "s", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "s", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def makeFloat(s): try: return float(s) except Exception: return float('nan')
609,939
469
e32ebde377855f04f641a5beb6450f6dc0e8b553
benmcbenben/netmiko
netmiko/utilities.py
[ "MIT" ]
Python
ensure_dir_exists
null
def ensure_dir_exists(verify_dir): """Ensure directory exists. Create if necessary.""" if not os.path.exists(verify_dir): # Doesn't exist create dir os.makedirs(verify_dir) else: # Exists if not os.path.isdir(verify_dir): # Not a dir, raise an exception raise ValueError(f"{verify_dir} is not a directory")
Ensure directory exists. Create if necessary.
Ensure directory exists. Create if necessary.
[ "Ensure", "directory", "exists", ".", "Create", "if", "necessary", "." ]
def ensure_dir_exists(verify_dir): if not os.path.exists(verify_dir): os.makedirs(verify_dir) else: if not os.path.isdir(verify_dir): raise ValueError(f"{verify_dir} is not a directory")
[ "def", "ensure_dir_exists", "(", "verify_dir", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "verify_dir", ")", ":", "os", ".", "makedirs", "(", "verify_dir", ")", "else", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "verify_dir", ")", ":", "raise", "ValueError", "(", "f\"{verify_dir} is not a directory\"", ")" ]
Ensure directory exists.
[ "Ensure", "directory", "exists", "." ]
[ "\"\"\"Ensure directory exists. Create if necessary.\"\"\"", "# Doesn't exist create dir", "# Exists", "# Not a dir, raise an exception" ]
[ { "param": "verify_dir", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "verify_dir", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import os def ensure_dir_exists(verify_dir): if not os.path.exists(verify_dir): os.makedirs(verify_dir) else: if not os.path.isdir(verify_dir): raise ValueError(f"{verify_dir} is not a directory")
609,940
270
a9192e06275924e7e7bf932e933fa596aa3f55cd
phillipmacon/xcloud
utils/db_utils.py
[ "MIT" ]
Python
query_api_hist
<not_specific>
def query_api_hist(conn, username): """ query API call details via hist :param conn: :param username: :return: """ cursor = conn.cursor() sql = "SELECT api_name, COUNT(api_name) FROM api WHERE 1=1" if username is not None and username != '': sql += " AND username='{0}'".format(username) cursor.execute(sql) results = cursor.fetchall() db_result = {} for k, v in results: db_result[k] = v conn.close() return db_result
query API call details via hist :param conn: :param username: :return:
query API call details via hist
[ "query", "API", "call", "details", "via", "hist" ]
def query_api_hist(conn, username): cursor = conn.cursor() sql = "SELECT api_name, COUNT(api_name) FROM api WHERE 1=1" if username is not None and username != '': sql += " AND username='{0}'".format(username) cursor.execute(sql) results = cursor.fetchall() db_result = {} for k, v in results: db_result[k] = v conn.close() return db_result
[ "def", "query_api_hist", "(", "conn", ",", "username", ")", ":", "cursor", "=", "conn", ".", "cursor", "(", ")", "sql", "=", "\"SELECT api_name, COUNT(api_name) FROM api WHERE 1=1\"", "if", "username", "is", "not", "None", "and", "username", "!=", "''", ":", "sql", "+=", "\" AND username='{0}'\"", ".", "format", "(", "username", ")", "cursor", ".", "execute", "(", "sql", ")", "results", "=", "cursor", ".", "fetchall", "(", ")", "db_result", "=", "{", "}", "for", "k", ",", "v", "in", "results", ":", "db_result", "[", "k", "]", "=", "v", "conn", ".", "close", "(", ")", "return", "db_result" ]
query API call details via hist
[ "query", "API", "call", "details", "via", "hist" ]
[ "\"\"\"\n query API call details via hist\n :param conn:\n :param username:\n :return:\n \"\"\"" ]
[ { "param": "conn", "type": null }, { "param": "username", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "conn", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "username", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def query_api_hist(conn, username): cursor = conn.cursor() sql = "SELECT api_name, COUNT(api_name) FROM api WHERE 1=1" if username is not None and username != '': sql += " AND username='{0}'".format(username) cursor.execute(sql) results = cursor.fetchall() db_result = {} for k, v in results: db_result[k] = v conn.close() return db_result
609,941
324
c01638e17a9c3561534faa9ad8a9a54fcb4b91a0
mcljot/pantheon
uploader/pantheon.py
[ "MIT" ]
Python
_info
null
def _info(message, colored=True): """ Print an info message on the console. Warning messages are cyan """ if colored: print('\033[96m{}\033[00m'.format(message)) else: print(message)
Print an info message on the console. Warning messages are cyan
Print an info message on the console. Warning messages are cyan
[ "Print", "an", "info", "message", "on", "the", "console", ".", "Warning", "messages", "are", "cyan" ]
def _info(message, colored=True): if colored: print('\033[96m{}\033[00m'.format(message)) else: print(message)
[ "def", "_info", "(", "message", ",", "colored", "=", "True", ")", ":", "if", "colored", ":", "print", "(", "'\\033[96m{}\\033[00m'", ".", "format", "(", "message", ")", ")", "else", ":", "print", "(", "message", ")" ]
Print an info message on the console.
[ "Print", "an", "info", "message", "on", "the", "console", "." ]
[ "\"\"\"\n Print an info message on the console. Warning messages are cyan\n \"\"\"" ]
[ { "param": "message", "type": null }, { "param": "colored", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "message", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "colored", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def _info(message, colored=True): if colored: print('\033[96m{}\033[00m'.format(message)) else: print(message)
609,942
561
2f173cd168a52a9e791d6ea371d763b7db8c651d
JcZou/rotors_simulator
mavlink/pymavlink/mavextra.py
[ "MIT" ]
Python
downsample
<not_specific>
def downsample(N): '''conditional that is true on every Nth sample''' global _downsample_N _downsample_N = (_downsample_N + 1) % N return _downsample_N == 0
conditional that is true on every Nth sample
conditional that is true on every Nth sample
[ "conditional", "that", "is", "true", "on", "every", "Nth", "sample" ]
def downsample(N): global _downsample_N _downsample_N = (_downsample_N + 1) % N return _downsample_N == 0
[ "def", "downsample", "(", "N", ")", ":", "global", "_downsample_N", "_downsample_N", "=", "(", "_downsample_N", "+", "1", ")", "%", "N", "return", "_downsample_N", "==", "0" ]
conditional that is true on every Nth sample
[ "conditional", "that", "is", "true", "on", "every", "Nth", "sample" ]
[ "'''conditional that is true on every Nth sample'''" ]
[ { "param": "N", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "N", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def downsample(N): global _downsample_N _downsample_N = (_downsample_N + 1) % N return _downsample_N == 0
609,943
554
db2db0ed5b8decbe51aa4818a7d562d681461586
wy-go/google-research
goemotions/extract_words.py
[ "Apache-2.0" ]
Python
CheckAgreement
<not_specific>
def CheckAgreement(ex, min_agreement, all_emotions, max_agreement=100): """Return the labels that at least min_agreement raters agree on.""" sum_ratings = ex[all_emotions].sum(axis=0) agreement = ((sum_ratings >= min_agreement) & (sum_ratings <= max_agreement)) return ",".join(sum_ratings.index[agreement].tolist())
Return the labels that at least min_agreement raters agree on.
Return the labels that at least min_agreement raters agree on.
[ "Return", "the", "labels", "that", "at", "least", "min_agreement", "raters", "agree", "on", "." ]
def CheckAgreement(ex, min_agreement, all_emotions, max_agreement=100): sum_ratings = ex[all_emotions].sum(axis=0) agreement = ((sum_ratings >= min_agreement) & (sum_ratings <= max_agreement)) return ",".join(sum_ratings.index[agreement].tolist())
[ "def", "CheckAgreement", "(", "ex", ",", "min_agreement", ",", "all_emotions", ",", "max_agreement", "=", "100", ")", ":", "sum_ratings", "=", "ex", "[", "all_emotions", "]", ".", "sum", "(", "axis", "=", "0", ")", "agreement", "=", "(", "(", "sum_ratings", ">=", "min_agreement", ")", "&", "(", "sum_ratings", "<=", "max_agreement", ")", ")", "return", "\",\"", ".", "join", "(", "sum_ratings", ".", "index", "[", "agreement", "]", ".", "tolist", "(", ")", ")" ]
Return the labels that at least min_agreement raters agree on.
[ "Return", "the", "labels", "that", "at", "least", "min_agreement", "raters", "agree", "on", "." ]
[ "\"\"\"Return the labels that at least min_agreement raters agree on.\"\"\"" ]
[ { "param": "ex", "type": null }, { "param": "min_agreement", "type": null }, { "param": "all_emotions", "type": null }, { "param": "max_agreement", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ex", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "min_agreement", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "all_emotions", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "max_agreement", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def CheckAgreement(ex, min_agreement, all_emotions, max_agreement=100): sum_ratings = ex[all_emotions].sum(axis=0) agreement = ((sum_ratings >= min_agreement) & (sum_ratings <= max_agreement)) return ",".join(sum_ratings.index[agreement].tolist())
609,945
260
e601f6f476e4dfb42bfbdd4f0a861da6f83d611c
daobook/cpython
Lib/ipaddress.py
[ "0BSD" ]
Python
_parse_octet
<not_specific>
def _parse_octet(cls, octet_str): """Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255]. """ if not octet_str: raise ValueError("Empty octet not permitted") # Reject non-ASCII digits. if not (octet_str.isascii() and octet_str.isdigit()): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Handle leading zeros as strict as glibc's inet_pton() # See security bug bpo-36384 if octet_str != '0' and octet_str[0] == '0': msg = "Leading zeros are not permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int
Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255].
Convert a decimal octet into an integer.
[ "Convert", "a", "decimal", "octet", "into", "an", "integer", "." ]
def _parse_octet(cls, octet_str): if not octet_str: raise ValueError("Empty octet not permitted") if not (octet_str.isascii() and octet_str.isdigit()): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) if octet_str != '0' and octet_str[0] == '0': msg = "Leading zeros are not permitted in %r" raise ValueError(msg % octet_str) octet_int = int(octet_str, 10) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int
[ "def", "_parse_octet", "(", "cls", ",", "octet_str", ")", ":", "if", "not", "octet_str", ":", "raise", "ValueError", "(", "\"Empty octet not permitted\"", ")", "if", "not", "(", "octet_str", ".", "isascii", "(", ")", "and", "octet_str", ".", "isdigit", "(", ")", ")", ":", "msg", "=", "\"Only decimal digits permitted in %r\"", "raise", "ValueError", "(", "msg", "%", "octet_str", ")", "if", "len", "(", "octet_str", ")", ">", "3", ":", "msg", "=", "\"At most 3 characters permitted in %r\"", "raise", "ValueError", "(", "msg", "%", "octet_str", ")", "if", "octet_str", "!=", "'0'", "and", "octet_str", "[", "0", "]", "==", "'0'", ":", "msg", "=", "\"Leading zeros are not permitted in %r\"", "raise", "ValueError", "(", "msg", "%", "octet_str", ")", "octet_int", "=", "int", "(", "octet_str", ",", "10", ")", "if", "octet_int", ">", "255", ":", "raise", "ValueError", "(", "\"Octet %d (> 255) not permitted\"", "%", "octet_int", ")", "return", "octet_int" ]
Convert a decimal octet into an integer.
[ "Convert", "a", "decimal", "octet", "into", "an", "integer", "." ]
[ "\"\"\"Convert a decimal octet into an integer.\n\n Args:\n octet_str: A string, the number to parse.\n\n Returns:\n The octet as an integer.\n\n Raises:\n ValueError: if the octet isn't strictly a decimal from [0..255].\n\n \"\"\"", "# Reject non-ASCII digits.", "# We do the length check second, since the invalid character error", "# is likely to be more informative for the user", "# Handle leading zeros as strict as glibc's inet_pton()", "# See security bug bpo-36384", "# Convert to integer (we know digits are legal)" ]
[ { "param": "cls", "type": null }, { "param": "octet_str", "type": null } ]
{ "returns": [ { "docstring": "The octet as an integer.", "docstring_tokens": [ "The", "octet", "as", "an", "integer", "." ], "type": null } ], "raises": [ { "docstring": "if the octet isn't strictly a decimal from [0..255].", "docstring_tokens": [ "if", "the", "octet", "isn", "'", "t", "strictly", "a", "decimal", "from", "[", "0", "..", "255", "]", "." ], "type": "ValueError" } ], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "octet_str", "type": null, "docstring": "A string, the number to parse.", "docstring_tokens": [ "A", "string", "the", "number", "to", "parse", "." ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def _parse_octet(cls, octet_str): if not octet_str: raise ValueError("Empty octet not permitted") if not (octet_str.isascii() and octet_str.isdigit()): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) if octet_str != '0' and octet_str[0] == '0': msg = "Leading zeros are not permitted in %r" raise ValueError(msg % octet_str) octet_int = int(octet_str, 10) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int
609,946
256
a6446e470d345d971addc7b036ed126954dfa2bc
miguel-osuna/Quotes-API
tests/conftest.py
[ "MIT" ]
Python
new_quote
<not_specific>
def new_quote(quote): """ Create new quote for testing. """ Quote = quote # Quote mock data quote_data = { "quote_text": "Quote.", "author_name": "Author", "author_image": "URL", "tags": ["test-tag"], } new_quote = Quote(**quote_data) new_quote.save() return new_quote
Create new quote for testing.
Create new quote for testing.
[ "Create", "new", "quote", "for", "testing", "." ]
def new_quote(quote): Quote = quote quote_data = { "quote_text": "Quote.", "author_name": "Author", "author_image": "URL", "tags": ["test-tag"], } new_quote = Quote(**quote_data) new_quote.save() return new_quote
[ "def", "new_quote", "(", "quote", ")", ":", "Quote", "=", "quote", "quote_data", "=", "{", "\"quote_text\"", ":", "\"Quote.\"", ",", "\"author_name\"", ":", "\"Author\"", ",", "\"author_image\"", ":", "\"URL\"", ",", "\"tags\"", ":", "[", "\"test-tag\"", "]", ",", "}", "new_quote", "=", "Quote", "(", "**", "quote_data", ")", "new_quote", ".", "save", "(", ")", "return", "new_quote" ]
Create new quote for testing.
[ "Create", "new", "quote", "for", "testing", "." ]
[ "\"\"\" Create new quote for testing. \"\"\"", "# Quote mock data" ]
[ { "param": "quote", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "quote", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def new_quote(quote): Quote = quote quote_data = { "quote_text": "Quote.", "author_name": "Author", "author_image": "URL", "tags": ["test-tag"], } new_quote = Quote(**quote_data) new_quote.save() return new_quote
609,947
673
1c71c8ed12780b1185d62f2d439c753da2d0d856
ooici/pyon
pyon/container/management.py
[ "BSD-2-Clause" ]
Python
from_object
<not_specific>
def from_object(cls, obj): """ get peer type from Ion object """ mod = obj.get_decorator_value('peer', 'module') clazz = obj.get_decorator_value('peer', 'class') or obj.__class__.__name__ subclass = getattr(sys.modules[mod], clazz) return subclass(obj)
get peer type from Ion object
get peer type from Ion object
[ "get", "peer", "type", "from", "Ion", "object" ]
def from_object(cls, obj): mod = obj.get_decorator_value('peer', 'module') clazz = obj.get_decorator_value('peer', 'class') or obj.__class__.__name__ subclass = getattr(sys.modules[mod], clazz) return subclass(obj)
[ "def", "from_object", "(", "cls", ",", "obj", ")", ":", "mod", "=", "obj", ".", "get_decorator_value", "(", "'peer'", ",", "'module'", ")", "clazz", "=", "obj", ".", "get_decorator_value", "(", "'peer'", ",", "'class'", ")", "or", "obj", ".", "__class__", ".", "__name__", "subclass", "=", "getattr", "(", "sys", ".", "modules", "[", "mod", "]", ",", "clazz", ")", "return", "subclass", "(", "obj", ")" ]
get peer type from Ion object
[ "get", "peer", "type", "from", "Ion", "object" ]
[ "\"\"\" get peer type from Ion object \"\"\"" ]
[ { "param": "cls", "type": null }, { "param": "obj", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "obj", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
import sys def from_object(cls, obj): mod = obj.get_decorator_value('peer', 'module') clazz = obj.get_decorator_value('peer', 'class') or obj.__class__.__name__ subclass = getattr(sys.modules[mod], clazz) return subclass(obj)
609,949
590
fb33ad919b20b00474f36522502c1b076e17696f
gradientzero/dq0-sdk
dq0/sdk/cli/utils/code.py
[ "0BSD" ]
Python
_get_code_spaces
<not_specific>
def _get_code_spaces(code_line, space_char, number_of_leading_chars=0): """Helper function to get leading spaces.""" num_code_spaces = len(code_line) - len(code_line.lstrip()) num_code_spaces = num_code_spaces + number_of_leading_chars if space_char == '\t': if code_line[:1] == ' ': num_code_spaces = int(num_code_spaces / 4) num_code_spaces = num_code_spaces + 1 else: num_code_spaces = num_code_spaces + 4 return space_char.join(['' for i in range(num_code_spaces + 1)])
Helper function to get leading spaces.
Helper function to get leading spaces.
[ "Helper", "function", "to", "get", "leading", "spaces", "." ]
def _get_code_spaces(code_line, space_char, number_of_leading_chars=0): num_code_spaces = len(code_line) - len(code_line.lstrip()) num_code_spaces = num_code_spaces + number_of_leading_chars if space_char == '\t': if code_line[:1] == ' ': num_code_spaces = int(num_code_spaces / 4) num_code_spaces = num_code_spaces + 1 else: num_code_spaces = num_code_spaces + 4 return space_char.join(['' for i in range(num_code_spaces + 1)])
[ "def", "_get_code_spaces", "(", "code_line", ",", "space_char", ",", "number_of_leading_chars", "=", "0", ")", ":", "num_code_spaces", "=", "len", "(", "code_line", ")", "-", "len", "(", "code_line", ".", "lstrip", "(", ")", ")", "num_code_spaces", "=", "num_code_spaces", "+", "number_of_leading_chars", "if", "space_char", "==", "'\\t'", ":", "if", "code_line", "[", ":", "1", "]", "==", "' '", ":", "num_code_spaces", "=", "int", "(", "num_code_spaces", "/", "4", ")", "num_code_spaces", "=", "num_code_spaces", "+", "1", "else", ":", "num_code_spaces", "=", "num_code_spaces", "+", "4", "return", "space_char", ".", "join", "(", "[", "''", "for", "i", "in", "range", "(", "num_code_spaces", "+", "1", ")", "]", ")" ]
Helper function to get leading spaces.
[ "Helper", "function", "to", "get", "leading", "spaces", "." ]
[ "\"\"\"Helper function to get leading spaces.\"\"\"" ]
[ { "param": "code_line", "type": null }, { "param": "space_char", "type": null }, { "param": "number_of_leading_chars", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "code_line", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "space_char", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "number_of_leading_chars", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def _get_code_spaces(code_line, space_char, number_of_leading_chars=0): num_code_spaces = len(code_line) - len(code_line.lstrip()) num_code_spaces = num_code_spaces + number_of_leading_chars if space_char == '\t': if code_line[:1] == ' ': num_code_spaces = int(num_code_spaces / 4) num_code_spaces = num_code_spaces + 1 else: num_code_spaces = num_code_spaces + 4 return space_char.join(['' for i in range(num_code_spaces + 1)])
609,950
229
ee757fc4cb1eedeb200de9131326c5376e9c6c53
k-vinogradov/favink
tests/test_fa.py
[ "MIT" ]
Python
compare_lists
<not_specific>
def compare_lists(list_a, list_b): """Compare the content of tho lists regardless items order.""" if len(list_a) != len(list_b): return False if not list_a: return True value, *new_a = list_a if value not in list_b: return False new_b = list(filter(lambda x: x != value, list_b)) return compare_lists(new_a, new_b)
Compare the content of tho lists regardless items order.
Compare the content of tho lists regardless items order.
[ "Compare", "the", "content", "of", "tho", "lists", "regardless", "items", "order", "." ]
def compare_lists(list_a, list_b): if len(list_a) != len(list_b): return False if not list_a: return True value, *new_a = list_a if value not in list_b: return False new_b = list(filter(lambda x: x != value, list_b)) return compare_lists(new_a, new_b)
[ "def", "compare_lists", "(", "list_a", ",", "list_b", ")", ":", "if", "len", "(", "list_a", ")", "!=", "len", "(", "list_b", ")", ":", "return", "False", "if", "not", "list_a", ":", "return", "True", "value", ",", "*", "new_a", "=", "list_a", "if", "value", "not", "in", "list_b", ":", "return", "False", "new_b", "=", "list", "(", "filter", "(", "lambda", "x", ":", "x", "!=", "value", ",", "list_b", ")", ")", "return", "compare_lists", "(", "new_a", ",", "new_b", ")" ]
Compare the content of tho lists regardless items order.
[ "Compare", "the", "content", "of", "tho", "lists", "regardless", "items", "order", "." ]
[ "\"\"\"Compare the content of tho lists regardless items order.\"\"\"" ]
[ { "param": "list_a", "type": null }, { "param": "list_b", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "list_a", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "list_b", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def compare_lists(list_a, list_b): if len(list_a) != len(list_b): return False if not list_a: return True value, *new_a = list_a if value not in list_b: return False new_b = list(filter(lambda x: x != value, list_b)) return compare_lists(new_a, new_b)
609,951
12
0616d471d41af2355d07f2a717da7fc08bd530f0
NASA-Tournament-Lab/CoECI-CMS-Healthcare-Fraud-Prevention
study/hfppnetwork/hfppnetwork/sms/helper.py
[ "Apache-2.0" ]
Python
check_not_none_or_empty
null
def check_not_none_or_empty(val, name): ''' Check if the given value is None or empty string. @param val: the given value to check @param name: name of val @raise TypeError: if val is not of type string @raise ValueError: if val is None or empty string ''' if val == None: raise ValueError('Object ' + name + ' should not be None.') if not isinstance(val, str): raise TypeError('Object ' + name + ' should be a string.') if len(val.strip()) == 0: raise ValueError('Object ' + name + ' should not empty string.')
Check if the given value is None or empty string. @param val: the given value to check @param name: name of val @raise TypeError: if val is not of type string @raise ValueError: if val is None or empty string
Check if the given value is None or empty string.
[ "Check", "if", "the", "given", "value", "is", "None", "or", "empty", "string", "." ]
def check_not_none_or_empty(val, name): if val == None: raise ValueError('Object ' + name + ' should not be None.') if not isinstance(val, str): raise TypeError('Object ' + name + ' should be a string.') if len(val.strip()) == 0: raise ValueError('Object ' + name + ' should not empty string.')
[ "def", "check_not_none_or_empty", "(", "val", ",", "name", ")", ":", "if", "val", "==", "None", ":", "raise", "ValueError", "(", "'Object '", "+", "name", "+", "' should not be None.'", ")", "if", "not", "isinstance", "(", "val", ",", "str", ")", ":", "raise", "TypeError", "(", "'Object '", "+", "name", "+", "' should be a string.'", ")", "if", "len", "(", "val", ".", "strip", "(", ")", ")", "==", "0", ":", "raise", "ValueError", "(", "'Object '", "+", "name", "+", "' should not empty string.'", ")" ]
Check if the given value is None or empty string.
[ "Check", "if", "the", "given", "value", "is", "None", "or", "empty", "string", "." ]
[ "'''\n Check if the given value is None or empty string.\n\n @param val: the given value to check\n @param name: name of val\n @raise TypeError: if val is not of type string\n @raise ValueError: if val is None or empty string\n '''" ]
[ { "param": "val", "type": null }, { "param": "name", "type": null } ]
{ "returns": [], "raises": [ { "docstring": "if val is not of type string", "docstring_tokens": [ "if", "val", "is", "not", "of", "type", "string" ], "type": "TypeError" }, { "docstring": "if val is None or empty string", "docstring_tokens": [ "if", "val", "is", "None", "or", "empty", "string" ], "type": "ValueError" } ], "params": [ { "identifier": "val", "type": null, "docstring": "the given value to check", "docstring_tokens": [ "the", "given", "value", "to", "check" ], "default": null, "is_optional": false }, { "identifier": "name", "type": null, "docstring": "name of val", "docstring_tokens": [ "name", "of", "val" ], "default": null, "is_optional": false } ], "outlier_params": [], "others": [] }
def check_not_none_or_empty(val, name): if val == None: raise ValueError('Object ' + name + ' should not be None.') if not isinstance(val, str): raise TypeError('Object ' + name + ' should be a string.') if len(val.strip()) == 0: raise ValueError('Object ' + name + ' should not empty string.')
609,953
41
6412d39e9ef6060146a7bb134294fb4701d5eb8f
jainris/FreeByrd
ML/output.py
[ "MIT" ]
Python
convert_to_letters
<not_specific>
def convert_to_letters(num): """Converts number to string of capital letters in Excel column name fashion, i.e. 1 -> A, 26 -> Z, 27 -> AA ....""" string_equiv = "" while num > 0: currNum = (num - 1) % 26 num = (num - 1) // 26 string_equiv = chr(currNum + ord("A")) + string_equiv return string_equiv
Converts number to string of capital letters in Excel column name fashion, i.e. 1 -> A, 26 -> Z, 27 -> AA ....
Converts number to string of capital letters in Excel column name fashion, i.e.
[ "Converts", "number", "to", "string", "of", "capital", "letters", "in", "Excel", "column", "name", "fashion", "i", ".", "e", "." ]
def convert_to_letters(num): string_equiv = "" while num > 0: currNum = (num - 1) % 26 num = (num - 1) // 26 string_equiv = chr(currNum + ord("A")) + string_equiv return string_equiv
[ "def", "convert_to_letters", "(", "num", ")", ":", "string_equiv", "=", "\"\"", "while", "num", ">", "0", ":", "currNum", "=", "(", "num", "-", "1", ")", "%", "26", "num", "=", "(", "num", "-", "1", ")", "//", "26", "string_equiv", "=", "chr", "(", "currNum", "+", "ord", "(", "\"A\"", ")", ")", "+", "string_equiv", "return", "string_equiv" ]
Converts number to string of capital letters in Excel column name fashion, i.e.
[ "Converts", "number", "to", "string", "of", "capital", "letters", "in", "Excel", "column", "name", "fashion", "i", ".", "e", "." ]
[ "\"\"\"Converts number to string of capital letters in Excel column name\n fashion, i.e. 1 -> A, 26 -> Z, 27 -> AA ....\"\"\"" ]
[ { "param": "num", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "num", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def convert_to_letters(num): string_equiv = "" while num > 0: currNum = (num - 1) % 26 num = (num - 1) // 26 string_equiv = chr(currNum + ord("A")) + string_equiv return string_equiv
609,954
556
42db1f832215f9061ba847ec2b50b0a939bfd74d
autodataming/rdkit
rdkit/Dbase/DbUtils.py
[ "BSD-3-Clause" ]
Python
_AdjustColHeadings
<not_specific>
def _AdjustColHeadings(colHeadings, maxColLabelLen): """ *For Internal Use* removes illegal characters from column headings and truncates those which are too long. """ for i in range(len(colHeadings)): # replace unallowed characters and strip extra white space colHeadings[i] = colHeadings[i].strip() colHeadings[i] = colHeadings[i].replace(' ', '_') colHeadings[i] = colHeadings[i].replace('-', '_') colHeadings[i] = colHeadings[i].replace('.', '_') if len(colHeadings[i]) > maxColLabelLen: # interbase (at least) has a limit on the maximum length of a column name newHead = colHeadings[i].replace('_', '') newHead = newHead[:maxColLabelLen] print('\tHeading %s too long, changed to %s' % (colHeadings[i], newHead)) colHeadings[i] = newHead return colHeadings
*For Internal Use* removes illegal characters from column headings and truncates those which are too long.
For Internal Use removes illegal characters from column headings and truncates those which are too long.
[ "For", "Internal", "Use", "removes", "illegal", "characters", "from", "column", "headings", "and", "truncates", "those", "which", "are", "too", "long", "." ]
def _AdjustColHeadings(colHeadings, maxColLabelLen): for i in range(len(colHeadings)): colHeadings[i] = colHeadings[i].strip() colHeadings[i] = colHeadings[i].replace(' ', '_') colHeadings[i] = colHeadings[i].replace('-', '_') colHeadings[i] = colHeadings[i].replace('.', '_') if len(colHeadings[i]) > maxColLabelLen: newHead = colHeadings[i].replace('_', '') newHead = newHead[:maxColLabelLen] print('\tHeading %s too long, changed to %s' % (colHeadings[i], newHead)) colHeadings[i] = newHead return colHeadings
[ "def", "_AdjustColHeadings", "(", "colHeadings", ",", "maxColLabelLen", ")", ":", "for", "i", "in", "range", "(", "len", "(", "colHeadings", ")", ")", ":", "colHeadings", "[", "i", "]", "=", "colHeadings", "[", "i", "]", ".", "strip", "(", ")", "colHeadings", "[", "i", "]", "=", "colHeadings", "[", "i", "]", ".", "replace", "(", "' '", ",", "'_'", ")", "colHeadings", "[", "i", "]", "=", "colHeadings", "[", "i", "]", ".", "replace", "(", "'-'", ",", "'_'", ")", "colHeadings", "[", "i", "]", "=", "colHeadings", "[", "i", "]", ".", "replace", "(", "'.'", ",", "'_'", ")", "if", "len", "(", "colHeadings", "[", "i", "]", ")", ">", "maxColLabelLen", ":", "newHead", "=", "colHeadings", "[", "i", "]", ".", "replace", "(", "'_'", ",", "''", ")", "newHead", "=", "newHead", "[", ":", "maxColLabelLen", "]", "print", "(", "'\\tHeading %s too long, changed to %s'", "%", "(", "colHeadings", "[", "i", "]", ",", "newHead", ")", ")", "colHeadings", "[", "i", "]", "=", "newHead", "return", "colHeadings" ]
For Internal Use removes illegal characters from column headings and truncates those which are too long.
[ "For", "Internal", "Use", "removes", "illegal", "characters", "from", "column", "headings", "and", "truncates", "those", "which", "are", "too", "long", "." ]
[ "\"\"\" *For Internal Use*\n\n removes illegal characters from column headings\n and truncates those which are too long.\n\n \"\"\"", "# replace unallowed characters and strip extra white space", "# interbase (at least) has a limit on the maximum length of a column name" ]
[ { "param": "colHeadings", "type": null }, { "param": "maxColLabelLen", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "colHeadings", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "maxColLabelLen", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def _AdjustColHeadings(colHeadings, maxColLabelLen): for i in range(len(colHeadings)): colHeadings[i] = colHeadings[i].strip() colHeadings[i] = colHeadings[i].replace(' ', '_') colHeadings[i] = colHeadings[i].replace('-', '_') colHeadings[i] = colHeadings[i].replace('.', '_') if len(colHeadings[i]) > maxColLabelLen: newHead = colHeadings[i].replace('_', '') newHead = newHead[:maxColLabelLen] print('\tHeading %s too long, changed to %s' % (colHeadings[i], newHead)) colHeadings[i] = newHead return colHeadings
609,955
478
863122edbc39fb903606e300142c00fa65309c7e
bernie-skipole/skipole
skipole/ski/read_json.py
[ "MIT" ]
Python
_allparts
<not_specific>
def _allparts(toplist, part_type): """Return list of all part dictionaries within toplist that are of type part_type Where toplist is the list of [part_type,part_dict] items as read by read_project()""" # search through parts part_list = [] for item in toplist: item_type, item_dict = item if item_type == part_type: part_list.append(item_dict) if item_type == 'Widget': for key in item_dict.keys(): if "container_" in key: part_list.extend(_allparts(item_dict[key], part_type)) elif item_type == 'Part': part_list.extend(_allparts(item_dict['parts'], part_type)) elif item_type == 'Widget': for key in item_dict.keys(): if "container_" in key: part_list.extend(_allparts(item_dict[key], part_type)) return part_list
Return list of all part dictionaries within toplist that are of type part_type Where toplist is the list of [part_type,part_dict] items as read by read_project()
Return list of all part dictionaries within toplist that are of type part_type Where toplist is the list of [part_type,part_dict] items as read by read_project()
[ "Return", "list", "of", "all", "part", "dictionaries", "within", "toplist", "that", "are", "of", "type", "part_type", "Where", "toplist", "is", "the", "list", "of", "[", "part_type", "part_dict", "]", "items", "as", "read", "by", "read_project", "()" ]
def _allparts(toplist, part_type): part_list = [] for item in toplist: item_type, item_dict = item if item_type == part_type: part_list.append(item_dict) if item_type == 'Widget': for key in item_dict.keys(): if "container_" in key: part_list.extend(_allparts(item_dict[key], part_type)) elif item_type == 'Part': part_list.extend(_allparts(item_dict['parts'], part_type)) elif item_type == 'Widget': for key in item_dict.keys(): if "container_" in key: part_list.extend(_allparts(item_dict[key], part_type)) return part_list
[ "def", "_allparts", "(", "toplist", ",", "part_type", ")", ":", "part_list", "=", "[", "]", "for", "item", "in", "toplist", ":", "item_type", ",", "item_dict", "=", "item", "if", "item_type", "==", "part_type", ":", "part_list", ".", "append", "(", "item_dict", ")", "if", "item_type", "==", "'Widget'", ":", "for", "key", "in", "item_dict", ".", "keys", "(", ")", ":", "if", "\"container_\"", "in", "key", ":", "part_list", ".", "extend", "(", "_allparts", "(", "item_dict", "[", "key", "]", ",", "part_type", ")", ")", "elif", "item_type", "==", "'Part'", ":", "part_list", ".", "extend", "(", "_allparts", "(", "item_dict", "[", "'parts'", "]", ",", "part_type", ")", ")", "elif", "item_type", "==", "'Widget'", ":", "for", "key", "in", "item_dict", ".", "keys", "(", ")", ":", "if", "\"container_\"", "in", "key", ":", "part_list", ".", "extend", "(", "_allparts", "(", "item_dict", "[", "key", "]", ",", "part_type", ")", ")", "return", "part_list" ]
Return list of all part dictionaries within toplist that are of type part_type Where toplist is the list of [part_type,part_dict] items as read by read_project()
[ "Return", "list", "of", "all", "part", "dictionaries", "within", "toplist", "that", "are", "of", "type", "part_type", "Where", "toplist", "is", "the", "list", "of", "[", "part_type", "part_dict", "]", "items", "as", "read", "by", "read_project", "()" ]
[ "\"\"\"Return list of all part dictionaries within toplist that are of type part_type\n Where toplist is the list of [part_type,part_dict] items as read by read_project()\"\"\"", "# search through parts" ]
[ { "param": "toplist", "type": null }, { "param": "part_type", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "toplist", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "part_type", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def _allparts(toplist, part_type): part_list = [] for item in toplist: item_type, item_dict = item if item_type == part_type: part_list.append(item_dict) if item_type == 'Widget': for key in item_dict.keys(): if "container_" in key: part_list.extend(_allparts(item_dict[key], part_type)) elif item_type == 'Part': part_list.extend(_allparts(item_dict['parts'], part_type)) elif item_type == 'Widget': for key in item_dict.keys(): if "container_" in key: part_list.extend(_allparts(item_dict[key], part_type)) return part_list
609,956
27
d3736c237c568e5e18b1b3cc54d8d41ef95a1df2
yiwamura/cta-lstchain
reco/Disp.py
[ "BSD-3-Clause" ]
Python
az_to_phi
<not_specific>
def az_to_phi(az): """transforms azimuth (angle from north towards east) to phi (angle from x-axis towards y-axis) for simtel array coordinate systems """ return -az
transforms azimuth (angle from north towards east) to phi (angle from x-axis towards y-axis) for simtel array coordinate systems
transforms azimuth (angle from north towards east) to phi (angle from x-axis towards y-axis) for simtel array coordinate systems
[ "transforms", "azimuth", "(", "angle", "from", "north", "towards", "east", ")", "to", "phi", "(", "angle", "from", "x", "-", "axis", "towards", "y", "-", "axis", ")", "for", "simtel", "array", "coordinate", "systems" ]
def az_to_phi(az): return -az
[ "def", "az_to_phi", "(", "az", ")", ":", "return", "-", "az" ]
transforms azimuth (angle from north towards east) to phi (angle from x-axis towards y-axis) for simtel array coordinate systems
[ "transforms", "azimuth", "(", "angle", "from", "north", "towards", "east", ")", "to", "phi", "(", "angle", "from", "x", "-", "axis", "towards", "y", "-", "axis", ")", "for", "simtel", "array", "coordinate", "systems" ]
[ "\"\"\"transforms azimuth (angle from north towards east) \n to phi (angle from x-axis towards y-axis) \n for simtel array coordinate systems \n \"\"\"" ]
[ { "param": "az", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "az", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def az_to_phi(az): return -az
609,957
529
7d52ece77065f09b4985494759735e10f9e1b6d5
kdwarn/wyr
app/native.py
[ "MIT" ]
Python
format_authors
<not_specific>
def format_authors(authors): """ Input: string of (possibly comma- and semi-colon-separated) authors Output: list of dicts, stripped of empty authors and whitesapce """ list_of_authors = [] for author in authors[:].split(";"): if any(char.isalnum() for char in author): author = author.split(",", maxsplit=1) try: a = {"last_name": author[0].strip(), "first_name": author[1].strip()} except IndexError: a = {"last_name": author[0].strip(), "first_name": ""} list_of_authors.append(a) return list_of_authors
Input: string of (possibly comma- and semi-colon-separated) authors Output: list of dicts, stripped of empty authors and whitesapce
string of (possibly comma- and semi-colon-separated) authors Output: list of dicts, stripped of empty authors and whitesapce
[ "string", "of", "(", "possibly", "comma", "-", "and", "semi", "-", "colon", "-", "separated", ")", "authors", "Output", ":", "list", "of", "dicts", "stripped", "of", "empty", "authors", "and", "whitesapce" ]
def format_authors(authors): list_of_authors = [] for author in authors[:].split(";"): if any(char.isalnum() for char in author): author = author.split(",", maxsplit=1) try: a = {"last_name": author[0].strip(), "first_name": author[1].strip()} except IndexError: a = {"last_name": author[0].strip(), "first_name": ""} list_of_authors.append(a) return list_of_authors
[ "def", "format_authors", "(", "authors", ")", ":", "list_of_authors", "=", "[", "]", "for", "author", "in", "authors", "[", ":", "]", ".", "split", "(", "\";\"", ")", ":", "if", "any", "(", "char", ".", "isalnum", "(", ")", "for", "char", "in", "author", ")", ":", "author", "=", "author", ".", "split", "(", "\",\"", ",", "maxsplit", "=", "1", ")", "try", ":", "a", "=", "{", "\"last_name\"", ":", "author", "[", "0", "]", ".", "strip", "(", ")", ",", "\"first_name\"", ":", "author", "[", "1", "]", ".", "strip", "(", ")", "}", "except", "IndexError", ":", "a", "=", "{", "\"last_name\"", ":", "author", "[", "0", "]", ".", "strip", "(", ")", ",", "\"first_name\"", ":", "\"\"", "}", "list_of_authors", ".", "append", "(", "a", ")", "return", "list_of_authors" ]
Input: string of (possibly comma- and semi-colon-separated) authors Output: list of dicts, stripped of empty authors and whitesapce
[ "Input", ":", "string", "of", "(", "possibly", "comma", "-", "and", "semi", "-", "colon", "-", "separated", ")", "authors", "Output", ":", "list", "of", "dicts", "stripped", "of", "empty", "authors", "and", "whitesapce" ]
[ "\"\"\" Input: string of (possibly comma- and semi-colon-separated) authors\n Output: list of dicts, stripped of empty authors and whitesapce\n \"\"\"" ]
[ { "param": "authors", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "authors", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def format_authors(authors): list_of_authors = [] for author in authors[:].split(";"): if any(char.isalnum() for char in author): author = author.split(",", maxsplit=1) try: a = {"last_name": author[0].strip(), "first_name": author[1].strip()} except IndexError: a = {"last_name": author[0].strip(), "first_name": ""} list_of_authors.append(a) return list_of_authors
609,958
550
dd02f00183505f1f4a906776a751d317da039f41
aivoyagers/Helmet_Mask_RCNN
helmet.py
[ "MIT" ]
Python
isSegmentConnector
<not_specific>
def isSegmentConnector(r) : """ Parameters ---------- r : region type with format : { "shape_attributes": { "name": "polygon", "all_points_x": [ 229,231, ], "all_points_y": [ 272,268, ] }, "region_attributes": { "name": "Motorcyclist", "segment_connector": " " } "ignore" : False "with_helmet" : False } DESCRIPTION : checks if the given region is Connected Segment or not. Returns ------- True if it the given region is a valid connected segment False if it is a stand-alone segment """ if ('segment_connector' in r['region_attributes'] and r['region_attributes']['segment_connector'].strip()) : return True else: return False
Parameters ---------- r : region type with format : { "shape_attributes": { "name": "polygon", "all_points_x": [ 229,231, ], "all_points_y": [ 272,268, ] }, "region_attributes": { "name": "Motorcyclist", "segment_connector": " " } "ignore" : False "with_helmet" : False } DESCRIPTION : checks if the given region is Connected Segment or not. Returns ------- True if it the given region is a valid connected segment False if it is a stand-alone segment
DESCRIPTION : checks if the given region is Connected Segment or not. Returns True if it the given region is a valid connected segment False if it is a stand-alone segment
[ "DESCRIPTION", ":", "checks", "if", "the", "given", "region", "is", "Connected", "Segment", "or", "not", ".", "Returns", "True", "if", "it", "the", "given", "region", "is", "a", "valid", "connected", "segment", "False", "if", "it", "is", "a", "stand", "-", "alone", "segment" ]
def isSegmentConnector(r) : if ('segment_connector' in r['region_attributes'] and r['region_attributes']['segment_connector'].strip()) : return True else: return False
[ "def", "isSegmentConnector", "(", "r", ")", ":", "if", "(", "'segment_connector'", "in", "r", "[", "'region_attributes'", "]", "and", "r", "[", "'region_attributes'", "]", "[", "'segment_connector'", "]", ".", "strip", "(", ")", ")", ":", "return", "True", "else", ":", "return", "False" ]
Parameters r : region type with format : { "shape_attributes": { "name": "polygon", "all_points_x": [ 229,231, ], "all_points_y": [ 272,268, ] }, "region_attributes": { "name": "Motorcyclist", "segment_connector": " " } "ignore" : False "with_helmet" : False }
[ "Parameters", "r", ":", "region", "type", "with", "format", ":", "{", "\"", "shape_attributes", "\"", ":", "{", "\"", "name", "\"", ":", "\"", "polygon", "\"", "\"", "all_points_x", "\"", ":", "[", "229", "231", "]", "\"", "all_points_y", "\"", ":", "[", "272", "268", "]", "}", "\"", "region_attributes", "\"", ":", "{", "\"", "name", "\"", ":", "\"", "Motorcyclist", "\"", "\"", "segment_connector", "\"", ":", "\"", "\"", "}", "\"", "ignore", "\"", ":", "False", "\"", "with_helmet", "\"", ":", "False", "}" ]
[ "\"\"\"\n\n Parameters\n ----------\n r : region type with format :\n {\n \t\"shape_attributes\": {\n \t\t\"name\": \"polygon\",\n \t\t\"all_points_x\": [\n \t\t\t229,231,\n \t\t],\n \t\t\"all_points_y\": [\n \t\t\t272,268,\n \t\t]\n \t},\n \t\"region_attributes\": {\n \t\t\"name\": \"Motorcyclist\",\n \t\t\"segment_connector\": \" \"\n \t}\n \"ignore\" : False\n \"with_helmet\" : False\n }\n \n DESCRIPTION : checks if the given region is Connected Segment or not.\n\n Returns\n -------\n True if it the given region is a valid connected segment\n False if it is a stand-alone segment\n\n \"\"\"" ]
[ { "param": "r", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "r", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def isSegmentConnector(r) : if ('segment_connector' in r['region_attributes'] and r['region_attributes']['segment_connector'].strip()) : return True else: return False
609,959
1,015
d96676eed1b7ec9d4aaf62f23888d60ae0814eeb
mursaleenfrt/pyorient_customized
pyorient/ogm/declarative.py
[ "Apache-2.0" ]
Python
declarative_base
<not_specific>
def declarative_base(decl_type, name, cls, metaclass, **kwargs): """Create base class for defining new database classes. :param decl_type: DeclarativeType enum value. :param name: Metaclass name :param cls: Base class(es) for returned class :param metaclass: Metaclass for registering type information """ bases = cls if isinstance(cls, tuple) else (cls, ) class_dict = dict(decl_type=decl_type) class_dict.update(kwargs) return metaclass(name, bases, class_dict)
Create base class for defining new database classes. :param decl_type: DeclarativeType enum value. :param name: Metaclass name :param cls: Base class(es) for returned class :param metaclass: Metaclass for registering type information
Create base class for defining new database classes.
[ "Create", "base", "class", "for", "defining", "new", "database", "classes", "." ]
def declarative_base(decl_type, name, cls, metaclass, **kwargs): bases = cls if isinstance(cls, tuple) else (cls, ) class_dict = dict(decl_type=decl_type) class_dict.update(kwargs) return metaclass(name, bases, class_dict)
[ "def", "declarative_base", "(", "decl_type", ",", "name", ",", "cls", ",", "metaclass", ",", "**", "kwargs", ")", ":", "bases", "=", "cls", "if", "isinstance", "(", "cls", ",", "tuple", ")", "else", "(", "cls", ",", ")", "class_dict", "=", "dict", "(", "decl_type", "=", "decl_type", ")", "class_dict", ".", "update", "(", "kwargs", ")", "return", "metaclass", "(", "name", ",", "bases", ",", "class_dict", ")" ]
Create base class for defining new database classes.
[ "Create", "base", "class", "for", "defining", "new", "database", "classes", "." ]
[ "\"\"\"Create base class for defining new database classes.\n\n :param decl_type: DeclarativeType enum value.\n :param name: Metaclass name\n :param cls: Base class(es) for returned class\n :param metaclass: Metaclass for registering type information\n \"\"\"" ]
[ { "param": "decl_type", "type": null }, { "param": "name", "type": null }, { "param": "cls", "type": null }, { "param": "metaclass", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "decl_type", "type": null, "docstring": "DeclarativeType enum value.", "docstring_tokens": [ "DeclarativeType", "enum", "value", "." ], "default": null, "is_optional": null }, { "identifier": "name", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "cls", "type": null, "docstring": "Base class(es) for returned class", "docstring_tokens": [ "Base", "class", "(", "es", ")", "for", "returned", "class" ], "default": null, "is_optional": null }, { "identifier": "metaclass", "type": null, "docstring": "Metaclass for registering type information", "docstring_tokens": [ "Metaclass", "for", "registering", "type", "information" ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def declarative_base(decl_type, name, cls, metaclass, **kwargs): bases = cls if isinstance(cls, tuple) else (cls, ) class_dict = dict(decl_type=decl_type) class_dict.update(kwargs) return metaclass(name, bases, class_dict)
609,960
917
5f52956f8ba6c654af1b7e71b2a04a9039db7400
Themoaningpirate/Tinychat-Bot--Discontinued
util/string_util.py
[ "MIT" ]
Python
convert_to_millisecond
<not_specific>
def convert_to_millisecond(duration): """ Converts a ISO 8601 unicode duration str to milliseconds. :param duration: The ISO 8601 unicode duration str :return: int milliseconds """ duration_string = duration.replace('PT', '').upper() seconds = 0 number_string = '' for char in duration_string: if char.isnumeric(): number_string += char try: if char == 'H': seconds += (int(number_string) * 60) * 60 number_string = '' if char == 'M': seconds += int(number_string) * 60 number_string = '' if char == 'S': seconds += int(number_string) except ValueError: return 0 return seconds * 1000
Converts a ISO 8601 unicode duration str to milliseconds. :param duration: The ISO 8601 unicode duration str :return: int milliseconds
Converts a ISO 8601 unicode duration str to milliseconds.
[ "Converts", "a", "ISO", "8601", "unicode", "duration", "str", "to", "milliseconds", "." ]
def convert_to_millisecond(duration): duration_string = duration.replace('PT', '').upper() seconds = 0 number_string = '' for char in duration_string: if char.isnumeric(): number_string += char try: if char == 'H': seconds += (int(number_string) * 60) * 60 number_string = '' if char == 'M': seconds += int(number_string) * 60 number_string = '' if char == 'S': seconds += int(number_string) except ValueError: return 0 return seconds * 1000
[ "def", "convert_to_millisecond", "(", "duration", ")", ":", "duration_string", "=", "duration", ".", "replace", "(", "'PT'", ",", "''", ")", ".", "upper", "(", ")", "seconds", "=", "0", "number_string", "=", "''", "for", "char", "in", "duration_string", ":", "if", "char", ".", "isnumeric", "(", ")", ":", "number_string", "+=", "char", "try", ":", "if", "char", "==", "'H'", ":", "seconds", "+=", "(", "int", "(", "number_string", ")", "*", "60", ")", "*", "60", "number_string", "=", "''", "if", "char", "==", "'M'", ":", "seconds", "+=", "int", "(", "number_string", ")", "*", "60", "number_string", "=", "''", "if", "char", "==", "'S'", ":", "seconds", "+=", "int", "(", "number_string", ")", "except", "ValueError", ":", "return", "0", "return", "seconds", "*", "1000" ]
Converts a ISO 8601 unicode duration str to milliseconds.
[ "Converts", "a", "ISO", "8601", "unicode", "duration", "str", "to", "milliseconds", "." ]
[ "\"\"\"\r\n Converts a ISO 8601 unicode duration str to milliseconds.\r\n :param duration: The ISO 8601 unicode duration str\r\n :return: int milliseconds\r\n \"\"\"" ]
[ { "param": "duration", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "duration", "type": null, "docstring": "The ISO 8601 unicode duration str", "docstring_tokens": [ "The", "ISO", "8601", "unicode", "duration", "str" ], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def convert_to_millisecond(duration): duration_string = duration.replace('PT', '').upper() seconds = 0 number_string = '' for char in duration_string: if char.isnumeric(): number_string += char try: if char == 'H': seconds += (int(number_string) * 60) * 60 number_string = '' if char == 'M': seconds += int(number_string) * 60 number_string = '' if char == 'S': seconds += int(number_string) except ValueError: return 0 return seconds * 1000
609,961
151
bfb305c3b03e0465d1edd98e3a12bae88372e04b
arthurrinaldi/grimsel
grimsel/auxiliary/aux_m_func.py
[ "BSD-2-Clause" ]
Python
pdef
<not_specific>
def pdef(df, sets=[], val='value', fixnan=0): ''' Transform a dataframe into a dictionary; primarily used for parameter setting. Keyword arguments: df -- input dataframe sets -- selection of columns (default all columns except val) val -- value column (default "value") fixnan -- If not False: used as keyword argument for fillna; if False: drop rows with null values ''' df = df.reset_index(drop=True) sets = [c for c in df.columns if not c == val] if len(sets) == 0 else sets df = df[sets + [val]] if not (type(fixnan) == bool and fixnan == False): df = df.fillna(fixnan) else: df = df.loc[-df[val].isnull()] dct = df.set_index(sets)[val].to_dict() return dct
Transform a dataframe into a dictionary; primarily used for parameter setting. Keyword arguments: df -- input dataframe sets -- selection of columns (default all columns except val) val -- value column (default "value") fixnan -- If not False: used as keyword argument for fillna; if False: drop rows with null values
Transform a dataframe into a dictionary; primarily used for parameter setting.
[ "Transform", "a", "dataframe", "into", "a", "dictionary", ";", "primarily", "used", "for", "parameter", "setting", "." ]
def pdef(df, sets=[], val='value', fixnan=0): df = df.reset_index(drop=True) sets = [c for c in df.columns if not c == val] if len(sets) == 0 else sets df = df[sets + [val]] if not (type(fixnan) == bool and fixnan == False): df = df.fillna(fixnan) else: df = df.loc[-df[val].isnull()] dct = df.set_index(sets)[val].to_dict() return dct
[ "def", "pdef", "(", "df", ",", "sets", "=", "[", "]", ",", "val", "=", "'value'", ",", "fixnan", "=", "0", ")", ":", "df", "=", "df", ".", "reset_index", "(", "drop", "=", "True", ")", "sets", "=", "[", "c", "for", "c", "in", "df", ".", "columns", "if", "not", "c", "==", "val", "]", "if", "len", "(", "sets", ")", "==", "0", "else", "sets", "df", "=", "df", "[", "sets", "+", "[", "val", "]", "]", "if", "not", "(", "type", "(", "fixnan", ")", "==", "bool", "and", "fixnan", "==", "False", ")", ":", "df", "=", "df", ".", "fillna", "(", "fixnan", ")", "else", ":", "df", "=", "df", ".", "loc", "[", "-", "df", "[", "val", "]", ".", "isnull", "(", ")", "]", "dct", "=", "df", ".", "set_index", "(", "sets", ")", "[", "val", "]", ".", "to_dict", "(", ")", "return", "dct" ]
Transform a dataframe into a dictionary; primarily used for parameter setting.
[ "Transform", "a", "dataframe", "into", "a", "dictionary", ";", "primarily", "used", "for", "parameter", "setting", "." ]
[ "'''\r\n Transform a dataframe into a dictionary;\r\n primarily used for parameter setting.\r\n\r\n Keyword arguments:\r\n df -- input dataframe\r\n sets -- selection of columns (default all columns except val)\r\n val -- value column (default \"value\")\r\n fixnan -- If not False: used as keyword argument for fillna;\r\n if False: drop rows with null values\r\n '''" ]
[ { "param": "df", "type": null }, { "param": "sets", "type": null }, { "param": "val", "type": null }, { "param": "fixnan", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "df", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sets", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "val", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "fixnan", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
def pdef(df, sets=[], val='value', fixnan=0): df = df.reset_index(drop=True) sets = [c for c in df.columns if not c == val] if len(sets) == 0 else sets df = df[sets + [val]] if not (type(fixnan) == bool and fixnan == False): df = df.fillna(fixnan) else: df = df.loc[-df[val].isnull()] dct = df.set_index(sets)[val].to_dict() return dct
609,963
423