repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
rhayes777/PyAutoFit
autofit/tools/fit_util.py
chi_squared_map_from_residual_map_noise_map_and_mask
def chi_squared_map_from_residual_map_noise_map_and_mask(residual_map, noise_map, mask): """Computes the chi-squared map between a masked residual-map and noise-map, where: Chi_Squared = ((Residuals) / (Noise)) ** 2.0 = ((Data - Model)**2.0)/(Variances) Although noise-maps should not contain zero values, ...
python
def chi_squared_map_from_residual_map_noise_map_and_mask(residual_map, noise_map, mask): """Computes the chi-squared map between a masked residual-map and noise-map, where: Chi_Squared = ((Residuals) / (Noise)) ** 2.0 = ((Data - Model)**2.0)/(Variances) Although noise-maps should not contain zero values, ...
[ "def", "chi_squared_map_from_residual_map_noise_map_and_mask", "(", "residual_map", ",", "noise_map", ",", "mask", ")", ":", "return", "np", ".", "square", "(", "np", ".", "divide", "(", "residual_map", ",", "noise_map", ",", "out", "=", "np", ".", "zeros_like",...
Computes the chi-squared map between a masked residual-map and noise-map, where: Chi_Squared = ((Residuals) / (Noise)) ** 2.0 = ((Data - Model)**2.0)/(Variances) Although noise-maps should not contain zero values, it is possible that masking leads to zeros which when \ divided by create NaNs. Thus, nan_to...
[ "Computes", "the", "chi", "-", "squared", "map", "between", "a", "masked", "residual", "-", "map", "and", "noise", "-", "map", "where", ":" ]
a9e6144abb08edfc6a6906c4030d7119bf8d3e14
https://github.com/rhayes777/PyAutoFit/blob/a9e6144abb08edfc6a6906c4030d7119bf8d3e14/autofit/tools/fit_util.py#L21-L39
train
Computes the chi - squared map between a residual - map and a noise - map and a mask.
NikolayDachev/jadm
lib/ipaddress-1.0.6/ipaddress.py
IPv4Address.is_private
def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per RFC 1918. """ private_10 = IPv4Network(u'10.0.0.0/8') private_172 = IPv4Network(u'172.16.0.0/12') private_192 = IPv4Netwo...
python
def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per RFC 1918. """ private_10 = IPv4Network(u'10.0.0.0/8') private_172 = IPv4Network(u'172.16.0.0/12') private_192 = IPv4Netwo...
[ "def", "is_private", "(", "self", ")", ":", "private_10", "=", "IPv4Network", "(", "u'10.0.0.0/8'", ")", "private_172", "=", "IPv4Network", "(", "u'172.16.0.0/12'", ")", "private_192", "=", "IPv4Network", "(", "u'192.168.0.0/16'", ")", "return", "(", "self", "in...
Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per RFC 1918.
[ "Test", "if", "this", "address", "is", "allocated", "for", "private", "networks", "." ]
12bb550445edfcd87506f7cba7a6a35d413c5511
https://github.com/NikolayDachev/jadm/blob/12bb550445edfcd87506f7cba7a6a35d413c5511/lib/ipaddress-1.0.6/ipaddress.py#L1297-L1309
train
Test if this address is allocated for private networks.
NikolayDachev/jadm
lib/ipaddress-1.0.6/ipaddress.py
IPv6Address.is_reserved
def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ reserved_nets = [IPv6Network(u'::/8'), IPv6Network(u'100::/8'), IPv6...
python
def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ reserved_nets = [IPv6Network(u'::/8'), IPv6Network(u'100::/8'), IPv6...
[ "def", "is_reserved", "(", "self", ")", ":", "reserved_nets", "=", "[", "IPv6Network", "(", "u'::/8'", ")", ",", "IPv6Network", "(", "u'100::/8'", ")", ",", "IPv6Network", "(", "u'200::/7'", ")", ",", "IPv6Network", "(", "u'400::/6'", ")", ",", "IPv6Network"...
Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges.
[ "Test", "if", "the", "address", "is", "otherwise", "IETF", "reserved", "." ]
12bb550445edfcd87506f7cba7a6a35d413c5511
https://github.com/NikolayDachev/jadm/blob/12bb550445edfcd87506f7cba7a6a35d413c5511/lib/ipaddress-1.0.6/ipaddress.py#L1854-L1871
train
Test if the address is otherwise IETF reserved.
KnightConan/sspdatatables
src/sspdatatables/utils/data_type_ensure.py
ensure
def ensure(data_type, check_value, default_value=None): """ function to ensure the given check value is in the given data type, if yes, return the check value directly, otherwise return the default value :param data_type: different data type: can be int, str, list, tuple etc, must be python suppo...
python
def ensure(data_type, check_value, default_value=None): """ function to ensure the given check value is in the given data type, if yes, return the check value directly, otherwise return the default value :param data_type: different data type: can be int, str, list, tuple etc, must be python suppo...
[ "def", "ensure", "(", "data_type", ",", "check_value", ",", "default_value", "=", "None", ")", ":", "if", "default_value", "is", "not", "None", "and", "not", "isinstance", "(", "default_value", ",", "data_type", ")", ":", "raise", "ValueError", "(", "\"defau...
function to ensure the given check value is in the given data type, if yes, return the check value directly, otherwise return the default value :param data_type: different data type: can be int, str, list, tuple etc, must be python supportable data type or new defined data type :param check_value: di...
[ "function", "to", "ensure", "the", "given", "check", "value", "is", "in", "the", "given", "data", "type", "if", "yes", "return", "the", "check", "value", "directly", "otherwise", "return", "the", "default", "value" ]
1179a11358734e5e472e5eee703e8d34fa49e9bf
https://github.com/KnightConan/sspdatatables/blob/1179a11358734e5e472e5eee703e8d34fa49e9bf/src/sspdatatables/utils/data_type_ensure.py#L7-L27
train
function to ensure the given check value is in the given data type and return the default value if no value is given
NikolayDachev/jadm
lib/paramiko-1.14.1/paramiko/util.py
inflate_long
def inflate_long(s, always_positive=False): """turns a normalized byte string into a long-int (adapted from Crypto.Util.number)""" out = long(0) negative = 0 if not always_positive and (len(s) > 0) and (byte_ord(s[0]) >= 0x80): negative = 1 if len(s) % 4: filler = zero_byte i...
python
def inflate_long(s, always_positive=False): """turns a normalized byte string into a long-int (adapted from Crypto.Util.number)""" out = long(0) negative = 0 if not always_positive and (len(s) > 0) and (byte_ord(s[0]) >= 0x80): negative = 1 if len(s) % 4: filler = zero_byte i...
[ "def", "inflate_long", "(", "s", ",", "always_positive", "=", "False", ")", ":", "out", "=", "long", "(", "0", ")", "negative", "=", "0", "if", "not", "always_positive", "and", "(", "len", "(", "s", ")", ">", "0", ")", "and", "(", "byte_ord", "(", ...
turns a normalized byte string into a long-int (adapted from Crypto.Util.number)
[ "turns", "a", "normalized", "byte", "string", "into", "a", "long", "-", "int", "(", "adapted", "from", "Crypto", ".", "Util", ".", "number", ")" ]
12bb550445edfcd87506f7cba7a6a35d413c5511
https://github.com/NikolayDachev/jadm/blob/12bb550445edfcd87506f7cba7a6a35d413c5511/lib/paramiko-1.14.1/paramiko/util.py#L39-L56
train
turns a normalized byte string into a long - int
NikolayDachev/jadm
lib/paramiko-1.14.1/paramiko/util.py
deflate_long
def deflate_long(n, add_sign_padding=True): """turns a long-int into a normalized byte string (adapted from Crypto.Util.number)""" # after much testing, this algorithm was deemed to be the fastest s = bytes() n = long(n) while (n != 0) and (n != -1): s = struct.pack('>I', n & xffffffff) + s ...
python
def deflate_long(n, add_sign_padding=True): """turns a long-int into a normalized byte string (adapted from Crypto.Util.number)""" # after much testing, this algorithm was deemed to be the fastest s = bytes() n = long(n) while (n != 0) and (n != -1): s = struct.pack('>I', n & xffffffff) + s ...
[ "def", "deflate_long", "(", "n", ",", "add_sign_padding", "=", "True", ")", ":", "# after much testing, this algorithm was deemed to be the fastest", "s", "=", "bytes", "(", ")", "n", "=", "long", "(", "n", ")", "while", "(", "n", "!=", "0", ")", "and", "(",...
turns a long-int into a normalized byte string (adapted from Crypto.Util.number)
[ "turns", "a", "long", "-", "int", "into", "a", "normalized", "byte", "string", "(", "adapted", "from", "Crypto", ".", "Util", ".", "number", ")" ]
12bb550445edfcd87506f7cba7a6a35d413c5511
https://github.com/NikolayDachev/jadm/blob/12bb550445edfcd87506f7cba7a6a35d413c5511/lib/paramiko-1.14.1/paramiko/util.py#L62-L89
train
turns a long - int into a normalized byte string
NikolayDachev/jadm
lib/paramiko-1.14.1/paramiko/util.py
log_to_file
def log_to_file(filename, level=DEBUG): """send paramiko logs to a logfile, if they're not already going somewhere""" l = logging.getLogger("paramiko") if len(l.handlers) > 0: return l.setLevel(level) f = open(filename, 'w') lh = logging.StreamHandler(f) lh.setFormatter(logging.Forma...
python
def log_to_file(filename, level=DEBUG): """send paramiko logs to a logfile, if they're not already going somewhere""" l = logging.getLogger("paramiko") if len(l.handlers) > 0: return l.setLevel(level) f = open(filename, 'w') lh = logging.StreamHandler(f) lh.setFormatter(logging.Forma...
[ "def", "log_to_file", "(", "filename", ",", "level", "=", "DEBUG", ")", ":", "l", "=", "logging", ".", "getLogger", "(", "\"paramiko\"", ")", "if", "len", "(", "l", ".", "handlers", ")", ">", "0", ":", "return", "l", ".", "setLevel", "(", "level", ...
send paramiko logs to a logfile, if they're not already going somewhere
[ "send", "paramiko", "logs", "to", "a", "logfile", "if", "they", "re", "not", "already", "going", "somewhere" ]
12bb550445edfcd87506f7cba7a6a35d413c5511
https://github.com/NikolayDachev/jadm/blob/12bb550445edfcd87506f7cba7a6a35d413c5511/lib/paramiko-1.14.1/paramiko/util.py#L247-L257
train
send paramiko logs to a logfile if they are not already going somewhere
edx/edx-celeryutils
celery_utils/tasks.py
mark_resolved
def mark_resolved(task_id): """ Mark the specified task as resolved in the FailedTask table. If more than one record exists with the specified task id, they will all be marked resolved. """ from . import models models.FailedTask.objects.filter(task_id=task_id, datetime_resolved=None).update...
python
def mark_resolved(task_id): """ Mark the specified task as resolved in the FailedTask table. If more than one record exists with the specified task id, they will all be marked resolved. """ from . import models models.FailedTask.objects.filter(task_id=task_id, datetime_resolved=None).update...
[ "def", "mark_resolved", "(", "task_id", ")", ":", "from", ".", "import", "models", "models", ".", "FailedTask", ".", "objects", ".", "filter", "(", "task_id", "=", "task_id", ",", "datetime_resolved", "=", "None", ")", ".", "update", "(", "datetime_resolved"...
Mark the specified task as resolved in the FailedTask table. If more than one record exists with the specified task id, they will all be marked resolved.
[ "Mark", "the", "specified", "task", "as", "resolved", "in", "the", "FailedTask", "table", "." ]
d8745f5f0929ad154fad779a19fbefe7f51e9498
https://github.com/edx/edx-celeryutils/blob/d8745f5f0929ad154fad779a19fbefe7f51e9498/celery_utils/tasks.py#L13-L21
train
Mark the specified task as resolved in the FailedTask table.
grundprinzip/pyxplorer
pyxplorer/manager.py
Database.tables
def tables(self): """ :return: all tables stored in this database """ cursor = self.connection.cursor() cursor.execute("show tables in %s" % self.db) self._tables = [t.Table(r[0], con=self.connection, db=self.db) for r in cursor.fetchall()] return self._tables
python
def tables(self): """ :return: all tables stored in this database """ cursor = self.connection.cursor() cursor.execute("show tables in %s" % self.db) self._tables = [t.Table(r[0], con=self.connection, db=self.db) for r in cursor.fetchall()] return self._tables
[ "def", "tables", "(", "self", ")", ":", "cursor", "=", "self", ".", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "\"show tables in %s\"", "%", "self", ".", "db", ")", "self", ".", "_tables", "=", "[", "t", ".", "Table", "(", ...
:return: all tables stored in this database
[ ":", "return", ":", "all", "tables", "stored", "in", "this", "database" ]
34c1d166cfef4a94aeb6d5fcb3cbb726d48146e2
https://github.com/grundprinzip/pyxplorer/blob/34c1d166cfef4a94aeb6d5fcb3cbb726d48146e2/pyxplorer/manager.py#L22-L29
train
Returns all tables stored in this database
grundprinzip/pyxplorer
pyxplorer/manager.py
Database.tcounts
def tcounts(self): """ :return: a data frame containing the names and sizes for all tables """ df = pd.DataFrame([[t.name(), t.size()] for t in self.tables()], columns=["name", "size"]) df.index = df.name return df
python
def tcounts(self): """ :return: a data frame containing the names and sizes for all tables """ df = pd.DataFrame([[t.name(), t.size()] for t in self.tables()], columns=["name", "size"]) df.index = df.name return df
[ "def", "tcounts", "(", "self", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "[", "[", "t", ".", "name", "(", ")", ",", "t", ".", "size", "(", ")", "]", "for", "t", "in", "self", ".", "tables", "(", ")", "]", ",", "columns", "=", "[", ...
:return: a data frame containing the names and sizes for all tables
[ ":", "return", ":", "a", "data", "frame", "containing", "the", "names", "and", "sizes", "for", "all", "tables" ]
34c1d166cfef4a94aeb6d5fcb3cbb726d48146e2
https://github.com/grundprinzip/pyxplorer/blob/34c1d166cfef4a94aeb6d5fcb3cbb726d48146e2/pyxplorer/manager.py#L35-L41
train
Returns a data frame containing the names and sizes for all tables in this database.
grundprinzip/pyxplorer
pyxplorer/manager.py
Database.dcounts
def dcounts(self): """ :return: a data frame with names and distinct counts and fractions for all columns in the database """ print("WARNING: Distinct value count for all tables can take a long time...", file=sys.stderr) sys.stderr.flush() data = [] for t in self...
python
def dcounts(self): """ :return: a data frame with names and distinct counts and fractions for all columns in the database """ print("WARNING: Distinct value count for all tables can take a long time...", file=sys.stderr) sys.stderr.flush() data = [] for t in self...
[ "def", "dcounts", "(", "self", ")", ":", "print", "(", "\"WARNING: Distinct value count for all tables can take a long time...\"", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "data", "=", "[", "]", "for", "t", "...
:return: a data frame with names and distinct counts and fractions for all columns in the database
[ ":", "return", ":", "a", "data", "frame", "with", "names", "and", "distinct", "counts", "and", "fractions", "for", "all", "columns", "in", "the", "database" ]
34c1d166cfef4a94aeb6d5fcb3cbb726d48146e2
https://github.com/grundprinzip/pyxplorer/blob/34c1d166cfef4a94aeb6d5fcb3cbb726d48146e2/pyxplorer/manager.py#L44-L56
train
Returns a data frame with names distinct counts and fractions for all columns in the database.
flo-compbio/xlmhg
xlmhg/mhg.py
is_equal
def is_equal(a, b, tol): """Ratio test to check if two floating point numbers are equal. Parameters ---------- a: float The first floating point number. b: float The second floating point number. tol: float The tolerance used. Returns ------- bool Wh...
python
def is_equal(a, b, tol): """Ratio test to check if two floating point numbers are equal. Parameters ---------- a: float The first floating point number. b: float The second floating point number. tol: float The tolerance used. Returns ------- bool Wh...
[ "def", "is_equal", "(", "a", ",", "b", ",", "tol", ")", ":", "if", "a", "==", "b", "or", "abs", "(", "a", "-", "b", ")", "<=", "tol", "*", "max", "(", "abs", "(", "a", ")", ",", "abs", "(", "b", ")", ")", ":", "return", "True", "else", ...
Ratio test to check if two floating point numbers are equal. Parameters ---------- a: float The first floating point number. b: float The second floating point number. tol: float The tolerance used. Returns ------- bool Whether or not the two numbers are...
[ "Ratio", "test", "to", "check", "if", "two", "floating", "point", "numbers", "are", "equal", "." ]
8e5929ee1dc91b95e343b7a2b1b1d6664c4540a1
https://github.com/flo-compbio/xlmhg/blob/8e5929ee1dc91b95e343b7a2b1b1d6664c4540a1/xlmhg/mhg.py#L28-L48
train
Ratio test to check if two floating point numbers are equal.
flo-compbio/xlmhg
xlmhg/mhg.py
get_hgp
def get_hgp(p, k, N, K, n): """Calculate the hypergeometric p-value when p = f(k; N,K,n) is already known. """ pval = p while k < min(K, n): p *= (float((n-k)*(K-k) / float((k+1)*(N-K-n+k+1)))) pval += p k += 1 return pval
python
def get_hgp(p, k, N, K, n): """Calculate the hypergeometric p-value when p = f(k; N,K,n) is already known. """ pval = p while k < min(K, n): p *= (float((n-k)*(K-k) / float((k+1)*(N-K-n+k+1)))) pval += p k += 1 return pval
[ "def", "get_hgp", "(", "p", ",", "k", ",", "N", ",", "K", ",", "n", ")", ":", "pval", "=", "p", "while", "k", "<", "min", "(", "K", ",", "n", ")", ":", "p", "*=", "(", "float", "(", "(", "n", "-", "k", ")", "*", "(", "K", "-", "k", ...
Calculate the hypergeometric p-value when p = f(k; N,K,n) is already known.
[ "Calculate", "the", "hypergeometric", "p", "-", "value", "when", "p", "=", "f", "(", "k", ";", "N", "K", "n", ")", "is", "already", "known", "." ]
8e5929ee1dc91b95e343b7a2b1b1d6664c4540a1
https://github.com/flo-compbio/xlmhg/blob/8e5929ee1dc91b95e343b7a2b1b1d6664c4540a1/xlmhg/mhg.py#L50-L58
train
Calculate the hypergeometric p - value when p = f k ; N K n is already known.
flo-compbio/xlmhg
xlmhg/mhg.py
get_xlmhg_stat
def get_xlmhg_stat(v, X, L, tol=DEFAULT_TOL): """Calculate the XL-mHG test statistic using recurrence relations. Parameters ---------- v: np.ndarray with dtype=np.uint8 The ranked list. X: int The XL-mHG ``X`` parameter. L: int The XL-mHG ``L`` parameter. tol: fl...
python
def get_xlmhg_stat(v, X, L, tol=DEFAULT_TOL): """Calculate the XL-mHG test statistic using recurrence relations. Parameters ---------- v: np.ndarray with dtype=np.uint8 The ranked list. X: int The XL-mHG ``X`` parameter. L: int The XL-mHG ``L`` parameter. tol: fl...
[ "def", "get_xlmhg_stat", "(", "v", ",", "X", ",", "L", ",", "tol", "=", "DEFAULT_TOL", ")", ":", "assert", "isinstance", "(", "v", ",", "np", ".", "ndarray", ")", "and", "v", ".", "ndim", "==", "1", "and", "np", ".", "issubdtype", "(", "v", ".", ...
Calculate the XL-mHG test statistic using recurrence relations. Parameters ---------- v: np.ndarray with dtype=np.uint8 The ranked list. X: int The XL-mHG ``X`` parameter. L: int The XL-mHG ``L`` parameter. tol: float, optional The tolerance used for comparin...
[ "Calculate", "the", "XL", "-", "mHG", "test", "statistic", "using", "recurrence", "relations", ".", "Parameters", "----------", "v", ":", "np", ".", "ndarray", "with", "dtype", "=", "np", ".", "uint8", "The", "ranked", "list", ".", "X", ":", "int", "The"...
8e5929ee1dc91b95e343b7a2b1b1d6664c4540a1
https://github.com/flo-compbio/xlmhg/blob/8e5929ee1dc91b95e343b7a2b1b1d6664c4540a1/xlmhg/mhg.py#L60-L127
train
Calculate the XL - mHG test statistic using recurrence relations.
flo-compbio/xlmhg
xlmhg/mhg.py
get_xlmhg_pval2
def get_xlmhg_pval2(N, K, X, L, stat, tol=DEFAULT_TOL): """Calculate the XL-mHG p-value using "Algorithm 2". Parameters ---------- N: int The length of the list. K: int The number of 1's in the list. X: int The XL-mHG ``X`` parameter. L: int The XL-mHG ``L`` ...
python
def get_xlmhg_pval2(N, K, X, L, stat, tol=DEFAULT_TOL): """Calculate the XL-mHG p-value using "Algorithm 2". Parameters ---------- N: int The length of the list. K: int The number of 1's in the list. X: int The XL-mHG ``X`` parameter. L: int The XL-mHG ``L`` ...
[ "def", "get_xlmhg_pval2", "(", "N", ",", "K", ",", "X", ",", "L", ",", "stat", ",", "tol", "=", "DEFAULT_TOL", ")", ":", "# type checking", "assert", "isinstance", "(", "N", ",", "int", ")", "assert", "isinstance", "(", "X", ",", "int", ")", "assert"...
Calculate the XL-mHG p-value using "Algorithm 2". Parameters ---------- N: int The length of the list. K: int The number of 1's in the list. X: int The XL-mHG ``X`` parameter. L: int The XL-mHG ``L`` parameter. stat: float The XL-mHG test statistic. ...
[ "Calculate", "the", "XL", "-", "mHG", "p", "-", "value", "using", "Algorithm", "2", "." ]
8e5929ee1dc91b95e343b7a2b1b1d6664c4540a1
https://github.com/flo-compbio/xlmhg/blob/8e5929ee1dc91b95e343b7a2b1b1d6664c4540a1/xlmhg/mhg.py#L246-L378
train
Calculate the XL - mHG p - value using Algorithm 2.
Nic30/hwtGraph
hwtGraph/elk/containers/lNode.py
LNode.getPortSideView
def getPortSideView(self, side) -> List["LPort"]: """ Returns a sublist view for all ports of given side. :attention: Use this only after port sides are fixed! This is currently the case after running the {@link org.eclipse.elk.alg.layered.intermediate.PortListSorter}. Non-stru...
python
def getPortSideView(self, side) -> List["LPort"]: """ Returns a sublist view for all ports of given side. :attention: Use this only after port sides are fixed! This is currently the case after running the {@link org.eclipse.elk.alg.layered.intermediate.PortListSorter}. Non-stru...
[ "def", "getPortSideView", "(", "self", ",", "side", ")", "->", "List", "[", "\"LPort\"", "]", ":", "if", "side", "==", "PortSide", ".", "WEST", ":", "return", "self", ".", "west", "elif", "side", "==", "PortSide", ".", "EAST", ":", "return", "self", ...
Returns a sublist view for all ports of given side. :attention: Use this only after port sides are fixed! This is currently the case after running the {@link org.eclipse.elk.alg.layered.intermediate.PortListSorter}. Non-structural changes to this list are reflected in the original list. A stru...
[ "Returns", "a", "sublist", "view", "for", "all", "ports", "of", "given", "side", "." ]
6b7d4fdd759f263a0fdd2736f02f123e44e4354f
https://github.com/Nic30/hwtGraph/blob/6b7d4fdd759f263a0fdd2736f02f123e44e4354f/hwtGraph/elk/containers/lNode.py#L53-L76
train
Returns a list of all ports of given side.
Nic30/hwtGraph
hwtGraph/elk/containers/lNode.py
LNode.iterEdges
def iterEdges(self, filterSelfLoops=False): """ Iter edges connected from outside of this unit """ for p in self.iterPorts(): yield from p.iterEdges(filterSelfLoops=filterSelfLoops)
python
def iterEdges(self, filterSelfLoops=False): """ Iter edges connected from outside of this unit """ for p in self.iterPorts(): yield from p.iterEdges(filterSelfLoops=filterSelfLoops)
[ "def", "iterEdges", "(", "self", ",", "filterSelfLoops", "=", "False", ")", ":", "for", "p", "in", "self", ".", "iterPorts", "(", ")", ":", "yield", "from", "p", ".", "iterEdges", "(", "filterSelfLoops", "=", "filterSelfLoops", ")" ]
Iter edges connected from outside of this unit
[ "Iter", "edges", "connected", "from", "outside", "of", "this", "unit" ]
6b7d4fdd759f263a0fdd2736f02f123e44e4354f
https://github.com/Nic30/hwtGraph/blob/6b7d4fdd759f263a0fdd2736f02f123e44e4354f/hwtGraph/elk/containers/lNode.py#L94-L99
train
Iterate edges connected from outside of this unit.
Nic30/hwtGraph
hwtGraph/elk/containers/lNode.py
LNode.toElkJson_registerPorts
def toElkJson_registerPorts(self, idStore): """ The index of a port in the fixed order around a node. The order is assumed as clockwise, starting with the leftmost port on the top side. This option must be set if ‘Port Constraints’ is set to FIXED_ORDER and no specific positions ...
python
def toElkJson_registerPorts(self, idStore): """ The index of a port in the fixed order around a node. The order is assumed as clockwise, starting with the leftmost port on the top side. This option must be set if ‘Port Constraints’ is set to FIXED_ORDER and no specific positions ...
[ "def", "toElkJson_registerPorts", "(", "self", ",", "idStore", ")", ":", "addIndex", "=", "self", ".", "portConstraints", "==", "PortConstraints", ".", "FIXED_ORDER", "for", "i", ",", "p", "in", "enumerate", "(", "self", ".", "iterPorts", "(", ")", ")", ":...
The index of a port in the fixed order around a node. The order is assumed as clockwise, starting with the leftmost port on the top side. This option must be set if ‘Port Constraints’ is set to FIXED_ORDER and no specific positions are given for the ports. Additionally, the option ‘Port ...
[ "The", "index", "of", "a", "port", "in", "the", "fixed", "order", "around", "a", "node", ".", "The", "order", "is", "assumed", "as", "clockwise", "starting", "with", "the", "leftmost", "port", "on", "the", "top", "side", ".", "This", "option", "must", ...
6b7d4fdd759f263a0fdd2736f02f123e44e4354f
https://github.com/Nic30/hwtGraph/blob/6b7d4fdd759f263a0fdd2736f02f123e44e4354f/hwtGraph/elk/containers/lNode.py#L114-L129
train
This method will register all ports in the idStore with the index of the ports in the idStore.
albert12132/templar
templar/linker.py
link
def link(source_path): """Links the content found at source_path and represents a Block that represents the content.""" if not os.path.isfile(source_path): raise SourceNotFound(source_path) with open(source_path, 'r') as f: content = f.read() block_map = BlockMap() # The map will be pop...
python
def link(source_path): """Links the content found at source_path and represents a Block that represents the content.""" if not os.path.isfile(source_path): raise SourceNotFound(source_path) with open(source_path, 'r') as f: content = f.read() block_map = BlockMap() # The map will be pop...
[ "def", "link", "(", "source_path", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "source_path", ")", ":", "raise", "SourceNotFound", "(", "source_path", ")", "with", "open", "(", "source_path", ",", "'r'", ")", "as", "f", ":", "content"...
Links the content found at source_path and represents a Block that represents the content.
[ "Links", "the", "content", "found", "at", "source_path", "and", "represents", "a", "Block", "that", "represents", "the", "content", "." ]
39851c89730ab69e5c73d0a46adca2a44ecc4165
https://github.com/albert12132/templar/blob/39851c89730ab69e5c73d0a46adca2a44ecc4165/templar/linker.py#L10-L19
train
Links the content found at source_path and represents a Block that represents the content.
albert12132/templar
templar/linker.py
get_block_dict
def get_block_dict(top_level_block): """Returns a dictionary of block names (str) to block contents (str) for all child blocks, as well as the original block itself. The block_dict argument is only used for recursive calls and should not """ block_stack = [top_level_block] block_dict = {} ...
python
def get_block_dict(top_level_block): """Returns a dictionary of block names (str) to block contents (str) for all child blocks, as well as the original block itself. The block_dict argument is only used for recursive calls and should not """ block_stack = [top_level_block] block_dict = {} ...
[ "def", "get_block_dict", "(", "top_level_block", ")", ":", "block_stack", "=", "[", "top_level_block", "]", "block_dict", "=", "{", "}", "while", "block_stack", ":", "block", "=", "block_stack", ".", "pop", "(", ")", "block_dict", "[", "block", ".", "name", ...
Returns a dictionary of block names (str) to block contents (str) for all child blocks, as well as the original block itself. The block_dict argument is only used for recursive calls and should not
[ "Returns", "a", "dictionary", "of", "block", "names", "(", "str", ")", "to", "block", "contents", "(", "str", ")", "for", "all", "child", "blocks", "as", "well", "as", "the", "original", "block", "itself", "." ]
39851c89730ab69e5c73d0a46adca2a44ecc4165
https://github.com/albert12132/templar/blob/39851c89730ab69e5c73d0a46adca2a44ecc4165/templar/linker.py#L22-L36
train
Returns a dictionary of block names to block contents for all child blocks as well as the original block itself.
albert12132/templar
templar/linker.py
convert_lines_to_block
def convert_lines_to_block(lines, block_map, link_stack, source_path, block_name=ALL_BLOCK_NAME): """Converts the specified block content lines (list of strings) into a Block object. Nested blocks are recursively converted into strings and cached in the block_map. Include tags are processed as well. The re...
python
def convert_lines_to_block(lines, block_map, link_stack, source_path, block_name=ALL_BLOCK_NAME): """Converts the specified block content lines (list of strings) into a Block object. Nested blocks are recursively converted into strings and cached in the block_map. Include tags are processed as well. The re...
[ "def", "convert_lines_to_block", "(", "lines", ",", "block_map", ",", "link_stack", ",", "source_path", ",", "block_name", "=", "ALL_BLOCK_NAME", ")", ":", "found_closing_block", "=", "False", "segments", "=", "[", "]", "while", "lines", ":", "line", "=", "lin...
Converts the specified block content lines (list of strings) into a Block object. Nested blocks are recursively converted into strings and cached in the block_map. Include tags are processed as well. The resulting block string is also added to the block_map, along with any nested blocks. PARAMETERS: ...
[ "Converts", "the", "specified", "block", "content", "lines", "(", "list", "of", "strings", ")", "into", "a", "Block", "object", "." ]
39851c89730ab69e5c73d0a46adca2a44ecc4165
https://github.com/albert12132/templar/blob/39851c89730ab69e5c73d0a46adca2a44ecc4165/templar/linker.py#L139-L216
train
Converts the specified list of lines into a single block object.
albert12132/templar
templar/linker.py
process_links
def process_links(include_match, block_map, link_stack, source_path): """Process a string of content for include tags. This function assumes there are no blocks in the content. The content is split into segments, with include tags being replaced by Block objects. PARAMETERS: content -- str; co...
python
def process_links(include_match, block_map, link_stack, source_path): """Process a string of content for include tags. This function assumes there are no blocks in the content. The content is split into segments, with include tags being replaced by Block objects. PARAMETERS: content -- str; co...
[ "def", "process_links", "(", "include_match", ",", "block_map", ",", "link_stack", ",", "source_path", ")", ":", "leading_whitespace", "=", "include_match", ".", "group", "(", "1", ")", "include_path", "=", "include_match", ".", "group", "(", "2", ")", "# Opti...
Process a string of content for include tags. This function assumes there are no blocks in the content. The content is split into segments, with include tags being replaced by Block objects. PARAMETERS: content -- str; content to be converted into a Block. block_map -- BlockMap link_stac...
[ "Process", "a", "string", "of", "content", "for", "include", "tags", "." ]
39851c89730ab69e5c73d0a46adca2a44ecc4165
https://github.com/albert12132/templar/blob/39851c89730ab69e5c73d0a46adca2a44ecc4165/templar/linker.py#L232-L263
train
Process a string of content for include tags.
albert12132/templar
templar/linker.py
retrieve_block_from_map
def retrieve_block_from_map( source_path, include_path, block_name, leading_whitespace, block_map, link_stack): """Given a source directory, the path specified in an include tag, and the block name, retrieve the corresponding Block from the block_map (adding it to...
python
def retrieve_block_from_map( source_path, include_path, block_name, leading_whitespace, block_map, link_stack): """Given a source directory, the path specified in an include tag, and the block name, retrieve the corresponding Block from the block_map (adding it to...
[ "def", "retrieve_block_from_map", "(", "source_path", ",", "include_path", ",", "block_name", ",", "leading_whitespace", ",", "block_map", ",", "link_stack", ")", ":", "# Check if the included file exists.", "relative_to_source", "=", "os", ".", "path", ".", "join", "...
Given a source directory, the path specified in an include tag, and the block name, retrieve the corresponding Block from the block_map (adding it to the map if necessary). The paths in include tags are interpreted as follows: 1. relative to the directory of source_path. 2. relative to the current wor...
[ "Given", "a", "source", "directory", "the", "path", "specified", "in", "an", "include", "tag", "and", "the", "block", "name", "retrieve", "the", "corresponding", "Block", "from", "the", "block_map", "(", "adding", "it", "to", "the", "map", "if", "necessary",...
39851c89730ab69e5c73d0a46adca2a44ecc4165
https://github.com/albert12132/templar/blob/39851c89730ab69e5c73d0a46adca2a44ecc4165/templar/linker.py#L266-L310
train
Given a source directory and a path specified in an include tag and a block name retrieve the corresponding Block from the block_map.
gofed/gofedlib
gofedlib/repository/bitbucketclient.py
BitbucketClient.branches
def branches(self): """Return a list of branches for given repository :return: [str] """ req_message = 'https://api.bitbucket.org/1.0/repositories/' + self.reponame + '/branches' response_data = self._bitbucketAPIRequest(req_message) return response_data.keys()
python
def branches(self): """Return a list of branches for given repository :return: [str] """ req_message = 'https://api.bitbucket.org/1.0/repositories/' + self.reponame + '/branches' response_data = self._bitbucketAPIRequest(req_message) return response_data.keys()
[ "def", "branches", "(", "self", ")", ":", "req_message", "=", "'https://api.bitbucket.org/1.0/repositories/'", "+", "self", ".", "reponame", "+", "'/branches'", "response_data", "=", "self", ".", "_bitbucketAPIRequest", "(", "req_message", ")", "return", "response_dat...
Return a list of branches for given repository :return: [str]
[ "Return", "a", "list", "of", "branches", "for", "given", "repository" ]
0674c248fe3d8706f98f912996b65af469f96b10
https://github.com/gofed/gofedlib/blob/0674c248fe3d8706f98f912996b65af469f96b10/gofedlib/repository/bitbucketclient.py#L22-L29
train
Return a list of branches for given repository
gofed/gofedlib
gofedlib/repository/bitbucketclient.py
BitbucketClient._commitData
def _commitData(self, commit): """Get data from a commit object :param commit: commit object :type commit: git.objects.commit.Commit """ return { "hexsha": commit['hash'], "adate": time.mktime(time.strptime(commit['date'][:19], '%Y-%m-%dT%H:%M:%S')), "cdate": time.mktime(time.strptime(commit['date'...
python
def _commitData(self, commit): """Get data from a commit object :param commit: commit object :type commit: git.objects.commit.Commit """ return { "hexsha": commit['hash'], "adate": time.mktime(time.strptime(commit['date'][:19], '%Y-%m-%dT%H:%M:%S')), "cdate": time.mktime(time.strptime(commit['date'...
[ "def", "_commitData", "(", "self", ",", "commit", ")", ":", "return", "{", "\"hexsha\"", ":", "commit", "[", "'hash'", "]", ",", "\"adate\"", ":", "time", ".", "mktime", "(", "time", ".", "strptime", "(", "commit", "[", "'date'", "]", "[", ":", "19",...
Get data from a commit object :param commit: commit object :type commit: git.objects.commit.Commit
[ "Get", "data", "from", "a", "commit", "object" ]
0674c248fe3d8706f98f912996b65af469f96b10
https://github.com/gofed/gofedlib/blob/0674c248fe3d8706f98f912996b65af469f96b10/gofedlib/repository/bitbucketclient.py#L31-L43
train
Get data from a commit object
gofed/gofedlib
gofedlib/repository/bitbucketclient.py
BitbucketClient.commits
def commits(self, branch, since=0, to=int(time.time()) + 86400): """For given branch return a list of commits. Each commit contains basic information about itself. :param branch: git branch :type branch: [str]{} :param since: minimal timestamp for commit's commit date :type since: int :param to: maxima...
python
def commits(self, branch, since=0, to=int(time.time()) + 86400): """For given branch return a list of commits. Each commit contains basic information about itself. :param branch: git branch :type branch: [str]{} :param since: minimal timestamp for commit's commit date :type since: int :param to: maxima...
[ "def", "commits", "(", "self", ",", "branch", ",", "since", "=", "0", ",", "to", "=", "int", "(", "time", ".", "time", "(", ")", ")", "+", "86400", ")", ":", "since_str", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "since", ")", ...
For given branch return a list of commits. Each commit contains basic information about itself. :param branch: git branch :type branch: [str]{} :param since: minimal timestamp for commit's commit date :type since: int :param to: maximal timestamp for commit's commit date :type to: int
[ "For", "given", "branch", "return", "a", "list", "of", "commits", ".", "Each", "commit", "contains", "basic", "information", "about", "itself", "." ]
0674c248fe3d8706f98f912996b65af469f96b10
https://github.com/gofed/gofedlib/blob/0674c248fe3d8706f98f912996b65af469f96b10/gofedlib/repository/bitbucketclient.py#L45-L78
train
For given branch return a list of commits.
gofed/gofedlib
gofedlib/repository/bitbucketclient.py
BitbucketClient.commit
def commit(self, commit): """Get data for a given commit Raises KeyError if a commit is not found or not parsed. :param commit: repository commit :type commit: string """ req_message = 'https://api.bitbucket.org/2.0/repositories/atlassian/aui/commit/' + commit response_data = self._bitbucketAPIRequest(...
python
def commit(self, commit): """Get data for a given commit Raises KeyError if a commit is not found or not parsed. :param commit: repository commit :type commit: string """ req_message = 'https://api.bitbucket.org/2.0/repositories/atlassian/aui/commit/' + commit response_data = self._bitbucketAPIRequest(...
[ "def", "commit", "(", "self", ",", "commit", ")", ":", "req_message", "=", "'https://api.bitbucket.org/2.0/repositories/atlassian/aui/commit/'", "+", "commit", "response_data", "=", "self", ".", "_bitbucketAPIRequest", "(", "req_message", ")", "try", ":", "return", "s...
Get data for a given commit Raises KeyError if a commit is not found or not parsed. :param commit: repository commit :type commit: string
[ "Get", "data", "for", "a", "given", "commit" ]
0674c248fe3d8706f98f912996b65af469f96b10
https://github.com/gofed/gofedlib/blob/0674c248fe3d8706f98f912996b65af469f96b10/gofedlib/repository/bitbucketclient.py#L80-L93
train
Get data for a given commit
althonos/moclo
moclo/moclo/_utils.py
catch_warnings
def catch_warnings(action, category=Warning, lineno=0, append=False): """Wrap the function in a `warnings.catch_warnings` context. It can be used to silence some particular specific warnings, or instead to treat them as errors within the function body. Example: >>> import warnings >>> ...
python
def catch_warnings(action, category=Warning, lineno=0, append=False): """Wrap the function in a `warnings.catch_warnings` context. It can be used to silence some particular specific warnings, or instead to treat them as errors within the function body. Example: >>> import warnings >>> ...
[ "def", "catch_warnings", "(", "action", ",", "category", "=", "Warning", ",", "lineno", "=", "0", ",", "append", "=", "False", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "newfunc", "(...
Wrap the function in a `warnings.catch_warnings` context. It can be used to silence some particular specific warnings, or instead to treat them as errors within the function body. Example: >>> import warnings >>> from moclo.utils import catch_warnings >>> @catch_warnings('ignore') ...
[ "Wrap", "the", "function", "in", "a", "warnings", ".", "catch_warnings", "context", "." ]
28a03748df8a2fa43f0c0c8098ca64d11559434e
https://github.com/althonos/moclo/blob/28a03748df8a2fa43f0c0c8098ca64d11559434e/moclo/moclo/_utils.py#L27-L54
train
Decorator that wraps a function in a warnings. catch_warnings context.
reorx/torext
torext/app.py
_guess_caller
def _guess_caller(): """ try to guess which module import app.py """ import inspect global _caller_path caller = inspect.stack()[1] caller_module = inspect.getmodule(caller[0]) if hasattr(caller_module, '__file__'): _caller_path = os.path.abspath(caller_module.__file__) retu...
python
def _guess_caller(): """ try to guess which module import app.py """ import inspect global _caller_path caller = inspect.stack()[1] caller_module = inspect.getmodule(caller[0]) if hasattr(caller_module, '__file__'): _caller_path = os.path.abspath(caller_module.__file__) retu...
[ "def", "_guess_caller", "(", ")", ":", "import", "inspect", "global", "_caller_path", "caller", "=", "inspect", ".", "stack", "(", ")", "[", "1", "]", "caller_module", "=", "inspect", ".", "getmodule", "(", "caller", "[", "0", "]", ")", "if", "hasattr", ...
try to guess which module import app.py
[ "try", "to", "guess", "which", "module", "import", "app", ".", "py" ]
84c4300ebc7fab0dbd11cf8b020bc7d4d1570171
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/app.py#L564-L575
train
Try to guess which module is the caller
reorx/torext
torext/app.py
TorextApp.set_root_path
def set_root_path(self, root_path=None, settings_module=None): """ root_path will only be used for 3 situations: 1. fix ``static_path`` and ``template_path`` 2. check project's directory name with the value in settings.PROJECT 3. append parent path to sys.path """ ...
python
def set_root_path(self, root_path=None, settings_module=None): """ root_path will only be used for 3 situations: 1. fix ``static_path`` and ``template_path`` 2. check project's directory name with the value in settings.PROJECT 3. append parent path to sys.path """ ...
[ "def", "set_root_path", "(", "self", ",", "root_path", "=", "None", ",", "settings_module", "=", "None", ")", ":", "if", "root_path", ":", "self", ".", "root_path", "=", "root_path", "return", "if", "settings_module", ":", "self", ".", "root_path", "=", "o...
root_path will only be used for 3 situations: 1. fix ``static_path`` and ``template_path`` 2. check project's directory name with the value in settings.PROJECT 3. append parent path to sys.path
[ "root_path", "will", "only", "be", "used", "for", "3", "situations", ":", "1", ".", "fix", "static_path", "and", "template_path", "2", ".", "check", "project", "s", "directory", "name", "with", "the", "value", "in", "settings", ".", "PROJECT", "3", ".", ...
84c4300ebc7fab0dbd11cf8b020bc7d4d1570171
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/app.py#L132-L153
train
Set the root path for the current project.
reorx/torext
torext/app.py
TorextApp._fix_paths
def _fix_paths(self, options): """ fix `static_path` and `template_path` to be absolute path according to self.root_path so that PWD can be ignoreed. """ for k in ('template_path', 'static_path'): if k in options: v = options.pop(k) if ...
python
def _fix_paths(self, options): """ fix `static_path` and `template_path` to be absolute path according to self.root_path so that PWD can be ignoreed. """ for k in ('template_path', 'static_path'): if k in options: v = options.pop(k) if ...
[ "def", "_fix_paths", "(", "self", ",", "options", ")", ":", "for", "k", "in", "(", "'template_path'", ",", "'static_path'", ")", ":", "if", "k", "in", "options", ":", "v", "=", "options", ".", "pop", "(", "k", ")", "if", "v", "is", "None", ":", "...
fix `static_path` and `template_path` to be absolute path according to self.root_path so that PWD can be ignoreed.
[ "fix", "static_path", "and", "template_path", "to", "be", "absolute", "path", "according", "to", "self", ".", "root_path", "so", "that", "PWD", "can", "be", "ignoreed", "." ]
84c4300ebc7fab0dbd11cf8b020bc7d4d1570171
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/app.py#L190-L204
train
Fix static_path and template_path to be absolute
reorx/torext
torext/app.py
TorextApp.route
def route(self, url, host=None): """This is a decorator """ def fn(handler_cls): handlers = self._get_handlers_on_host(host) handlers.insert(0, (url, handler_cls)) return handler_cls return fn
python
def route(self, url, host=None): """This is a decorator """ def fn(handler_cls): handlers = self._get_handlers_on_host(host) handlers.insert(0, (url, handler_cls)) return handler_cls return fn
[ "def", "route", "(", "self", ",", "url", ",", "host", "=", "None", ")", ":", "def", "fn", "(", "handler_cls", ")", ":", "handlers", "=", "self", ".", "_get_handlers_on_host", "(", "host", ")", "handlers", ".", "insert", "(", "0", ",", "(", "url", "...
This is a decorator
[ "This", "is", "a", "decorator" ]
84c4300ebc7fab0dbd11cf8b020bc7d4d1570171
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/app.py#L214-L221
train
This is a decorator that adds a new handler to the list of handlers that match the given URL.
reorx/torext
torext/app.py
TorextApp.route_many
def route_many(self, *args, **kwargs): """ >>> from torext.route import include >>> app = TorextApp() >>> app.route_many([ ... ('/account', include('account.views')), ... ('/account', include('account.views')), ... ], '^account.example.com$') """ ...
python
def route_many(self, *args, **kwargs): """ >>> from torext.route import include >>> app = TorextApp() >>> app.route_many([ ... ('/account', include('account.views')), ... ('/account', include('account.views')), ... ], '^account.example.com$') """ ...
[ "def", "route_many", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "2", ":", "prefix", ",", "rules", "=", "args", "elif", "len", "(", "args", ")", "==", "1", ":", "prefix", "=", "None", ...
>>> from torext.route import include >>> app = TorextApp() >>> app.route_many([ ... ('/account', include('account.views')), ... ('/account', include('account.views')), ... ], '^account.example.com$')
[ ">>>", "from", "torext", ".", "route", "import", "include", ">>>", "app", "=", "TorextApp", "()", ">>>", "app", ".", "route_many", "(", "[", "...", "(", "/", "account", "include", "(", "account", ".", "views", "))", "...", "(", "/", "account", "include...
84c4300ebc7fab0dbd11cf8b020bc7d4d1570171
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/app.py#L223-L240
train
Route many to the specified routes.
reorx/torext
torext/app.py
TorextApp.module_config
def module_config(self, settings_module): """ Optional function """ assert hasattr(settings_module, '__file__'), 'settings must be a module' # set root_path according to module file self.set_root_path(settings_module=settings_module) app_log.debug('Set root_path: ...
python
def module_config(self, settings_module): """ Optional function """ assert hasattr(settings_module, '__file__'), 'settings must be a module' # set root_path according to module file self.set_root_path(settings_module=settings_module) app_log.debug('Set root_path: ...
[ "def", "module_config", "(", "self", ",", "settings_module", ")", ":", "assert", "hasattr", "(", "settings_module", ",", "'__file__'", ")", ",", "'settings must be a module'", "# set root_path according to module file", "self", ".", "set_root_path", "(", "settings_module"...
Optional function
[ "Optional", "function" ]
84c4300ebc7fab0dbd11cf8b020bc7d4d1570171
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/app.py#L246-L264
train
Configure the settings object based on the module settings object.
reorx/torext
torext/app.py
TorextApp.command_line_config
def command_line_config(self): """ settings.py is the basis if wants to change them by command line arguments, the existing option will be transformed to the value type in settings.py the unexisting option will be treated as string by default, and transform to certain ty...
python
def command_line_config(self): """ settings.py is the basis if wants to change them by command line arguments, the existing option will be transformed to the value type in settings.py the unexisting option will be treated as string by default, and transform to certain ty...
[ "def", "command_line_config", "(", "self", ")", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "args_dict", "=", "{", "}", "existed_keys", "=", "[", "]", "new_keys", "=", "[", "]", "for", "t", "in", "args", ":", "if", "not", "t", ".", ...
settings.py is the basis if wants to change them by command line arguments, the existing option will be transformed to the value type in settings.py the unexisting option will be treated as string by default, and transform to certain type if `!<type>` was added after the value. ...
[ "settings", ".", "py", "is", "the", "basis" ]
84c4300ebc7fab0dbd11cf8b020bc7d4d1570171
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/app.py#L266-L325
train
Parse command line arguments and apply them to settings. py
reorx/torext
torext/app.py
TorextApp.setup
def setup(self): """This function will be called both before `run` and testing started. """ testing = settings.get('TESTING') if testing: # Fix nose handler in testing situation. config = settings['LOGGERS'].get('', {}) set_nose_formatter(config) ...
python
def setup(self): """This function will be called both before `run` and testing started. """ testing = settings.get('TESTING') if testing: # Fix nose handler in testing situation. config = settings['LOGGERS'].get('', {}) set_nose_formatter(config) ...
[ "def", "setup", "(", "self", ")", ":", "testing", "=", "settings", ".", "get", "(", "'TESTING'", ")", "if", "testing", ":", "# Fix nose handler in testing situation.", "config", "=", "settings", "[", "'LOGGERS'", "]", ".", "get", "(", "''", ",", "{", "}", ...
This function will be called both before `run` and testing started.
[ "This", "function", "will", "be", "called", "both", "before", "run", "and", "testing", "started", "." ]
84c4300ebc7fab0dbd11cf8b020bc7d4d1570171
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/app.py#L327-L367
train
This function will be called both before run and testing started.
reorx/torext
torext/app.py
TorextApp._init_application
def _init_application(self, application=None): """Initialize application object for torext app, if a existed application is passed, then just use this one without make a new one""" if application: self.application = application else: self.application = self.make_a...
python
def _init_application(self, application=None): """Initialize application object for torext app, if a existed application is passed, then just use this one without make a new one""" if application: self.application = application else: self.application = self.make_a...
[ "def", "_init_application", "(", "self", ",", "application", "=", "None", ")", ":", "if", "application", ":", "self", ".", "application", "=", "application", "else", ":", "self", ".", "application", "=", "self", ".", "make_application", "(", ")" ]
Initialize application object for torext app, if a existed application is passed, then just use this one without make a new one
[ "Initialize", "application", "object", "for", "torext", "app", "if", "a", "existed", "application", "is", "passed", "then", "just", "use", "this", "one", "without", "make", "a", "new", "one" ]
84c4300ebc7fab0dbd11cf8b020bc7d4d1570171
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/app.py#L530-L536
train
Initialize application object for torext app
reorx/torext
torext/app.py
TorextApp._log_function
def _log_function(self, handler): """Override Application.log_function so that what to log can be controlled. """ if handler.get_status() < 400: log_method = request_log.info elif handler.get_status() < 500: log_method = request_log.warning else: ...
python
def _log_function(self, handler): """Override Application.log_function so that what to log can be controlled. """ if handler.get_status() < 400: log_method = request_log.info elif handler.get_status() < 500: log_method = request_log.warning else: ...
[ "def", "_log_function", "(", "self", ",", "handler", ")", ":", "if", "handler", ".", "get_status", "(", ")", "<", "400", ":", "log_method", "=", "request_log", ".", "info", "elif", "handler", ".", "get_status", "(", ")", "<", "500", ":", "log_method", ...
Override Application.log_function so that what to log can be controlled.
[ "Override", "Application", ".", "log_function", "so", "that", "what", "to", "log", "can", "be", "controlled", "." ]
84c4300ebc7fab0dbd11cf8b020bc7d4d1570171
https://github.com/reorx/torext/blob/84c4300ebc7fab0dbd11cf8b020bc7d4d1570171/torext/app.py#L542-L558
train
Override Application. log_function so that what to log can be controlled.
255BITS/hyperchamber
examples/shared/variational_autoencoder.py
xavier_init
def xavier_init(fan_in, fan_out, constant=1): """ Xavier initialization of network weights""" # https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow low = -constant*np.sqrt(6.0/(fan_in + fan_out)) high = constant*np.sqrt(6.0/(fan_in + fan_out)) return tf.rando...
python
def xavier_init(fan_in, fan_out, constant=1): """ Xavier initialization of network weights""" # https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow low = -constant*np.sqrt(6.0/(fan_in + fan_out)) high = constant*np.sqrt(6.0/(fan_in + fan_out)) return tf.rando...
[ "def", "xavier_init", "(", "fan_in", ",", "fan_out", ",", "constant", "=", "1", ")", ":", "# https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow", "low", "=", "-", "constant", "*", "np", ".", "sqrt", "(", "6.0", "/", "(", "fan_...
Xavier initialization of network weights
[ "Xavier", "initialization", "of", "network", "weights" ]
4d5774bde9ea6ce1113f77a069ffc605148482b8
https://github.com/255BITS/hyperchamber/blob/4d5774bde9ea6ce1113f77a069ffc605148482b8/examples/shared/variational_autoencoder.py#L8-L15
train
Initialize the Xavier network weights.
255BITS/hyperchamber
examples/shared/variational_autoencoder.py
VariationalAutoencoder.partial_fit
def partial_fit(self, X): """Train model based on mini-batch of input data. Return cost of mini-batch. """ opt, cost = self.sess.run((self.optimizer, self.cost), feed_dict={self.x: X}) return cost
python
def partial_fit(self, X): """Train model based on mini-batch of input data. Return cost of mini-batch. """ opt, cost = self.sess.run((self.optimizer, self.cost), feed_dict={self.x: X}) return cost
[ "def", "partial_fit", "(", "self", ",", "X", ")", ":", "opt", ",", "cost", "=", "self", ".", "sess", ".", "run", "(", "(", "self", ".", "optimizer", ",", "self", ".", "cost", ")", ",", "feed_dict", "=", "{", "self", ".", "x", ":", "X", "}", "...
Train model based on mini-batch of input data. Return cost of mini-batch.
[ "Train", "model", "based", "on", "mini", "-", "batch", "of", "input", "data", ".", "Return", "cost", "of", "mini", "-", "batch", "." ]
4d5774bde9ea6ce1113f77a069ffc605148482b8
https://github.com/255BITS/hyperchamber/blob/4d5774bde9ea6ce1113f77a069ffc605148482b8/examples/shared/variational_autoencoder.py#L155-L162
train
Train model based on mini - batch of input data. Return cost of mini - batch.
255BITS/hyperchamber
examples/shared/variational_autoencoder.py
VariationalAutoencoder.transform
def transform(self, X): """Transform data by mapping it into the latent space.""" # Note: This maps to mean of distribution, we could alternatively # sample from Gaussian distribution return self.sess.run(self.z_mean, feed_dict={self.x: X})
python
def transform(self, X): """Transform data by mapping it into the latent space.""" # Note: This maps to mean of distribution, we could alternatively # sample from Gaussian distribution return self.sess.run(self.z_mean, feed_dict={self.x: X})
[ "def", "transform", "(", "self", ",", "X", ")", ":", "# Note: This maps to mean of distribution, we could alternatively", "# sample from Gaussian distribution", "return", "self", ".", "sess", ".", "run", "(", "self", ".", "z_mean", ",", "feed_dict", "=", "{", "self", ...
Transform data by mapping it into the latent space.
[ "Transform", "data", "by", "mapping", "it", "into", "the", "latent", "space", "." ]
4d5774bde9ea6ce1113f77a069ffc605148482b8
https://github.com/255BITS/hyperchamber/blob/4d5774bde9ea6ce1113f77a069ffc605148482b8/examples/shared/variational_autoencoder.py#L164-L168
train
Transform data by mapping it into the latent space.
255BITS/hyperchamber
examples/shared/variational_autoencoder.py
VariationalAutoencoder.generate
def generate(self, z_mu=None): """ Generate data by sampling from latent space. If z_mu is not None, data for this point in latent space is generated. Otherwise, z_mu is drawn from prior in latent space. """ if z_mu is None: z_mu = np.random....
python
def generate(self, z_mu=None): """ Generate data by sampling from latent space. If z_mu is not None, data for this point in latent space is generated. Otherwise, z_mu is drawn from prior in latent space. """ if z_mu is None: z_mu = np.random....
[ "def", "generate", "(", "self", ",", "z_mu", "=", "None", ")", ":", "if", "z_mu", "is", "None", ":", "z_mu", "=", "np", ".", "random", ".", "normal", "(", "size", "=", "self", ".", "network_architecture", "[", "\"n_z\"", "]", ")", "# Note: This maps to...
Generate data by sampling from latent space. If z_mu is not None, data for this point in latent space is generated. Otherwise, z_mu is drawn from prior in latent space.
[ "Generate", "data", "by", "sampling", "from", "latent", "space", ".", "If", "z_mu", "is", "not", "None", "data", "for", "this", "point", "in", "latent", "space", "is", "generated", ".", "Otherwise", "z_mu", "is", "drawn", "from", "prior", "in", "latent", ...
4d5774bde9ea6ce1113f77a069ffc605148482b8
https://github.com/255BITS/hyperchamber/blob/4d5774bde9ea6ce1113f77a069ffc605148482b8/examples/shared/variational_autoencoder.py#L170-L182
train
Generate data by sampling from latent space.
255BITS/hyperchamber
examples/shared/variational_autoencoder.py
VariationalAutoencoder.reconstruct
def reconstruct(self, X): """ Use VAE to reconstruct given data. """ return self.sess.run(self.x_reconstr_mean, feed_dict={self.x: X})
python
def reconstruct(self, X): """ Use VAE to reconstruct given data. """ return self.sess.run(self.x_reconstr_mean, feed_dict={self.x: X})
[ "def", "reconstruct", "(", "self", ",", "X", ")", ":", "return", "self", ".", "sess", ".", "run", "(", "self", ".", "x_reconstr_mean", ",", "feed_dict", "=", "{", "self", ".", "x", ":", "X", "}", ")" ]
Use VAE to reconstruct given data.
[ "Use", "VAE", "to", "reconstruct", "given", "data", "." ]
4d5774bde9ea6ce1113f77a069ffc605148482b8
https://github.com/255BITS/hyperchamber/blob/4d5774bde9ea6ce1113f77a069ffc605148482b8/examples/shared/variational_autoencoder.py#L184-L187
train
Use VAE to reconstruct given data.
geophysics-ubonn/crtomo_tools
src/cr_trig_parse_gmsh.py
parse_gmsh
def parse_gmsh(filename, boundary_file): """ Parse a GMSH .msh file and return a dictionary containing the data neccessary to create CRTomo grids """ mesh = {} fid = open(filename, 'r') line = fid.readline() while(line): if(line.startswith('$MeshFormat')): pass ...
python
def parse_gmsh(filename, boundary_file): """ Parse a GMSH .msh file and return a dictionary containing the data neccessary to create CRTomo grids """ mesh = {} fid = open(filename, 'r') line = fid.readline() while(line): if(line.startswith('$MeshFormat')): pass ...
[ "def", "parse_gmsh", "(", "filename", ",", "boundary_file", ")", ":", "mesh", "=", "{", "}", "fid", "=", "open", "(", "filename", ",", "'r'", ")", "line", "=", "fid", ".", "readline", "(", ")", "while", "(", "line", ")", ":", "if", "(", "line", "...
Parse a GMSH .msh file and return a dictionary containing the data neccessary to create CRTomo grids
[ "Parse", "a", "GMSH", ".", "msh", "file", "and", "return", "a", "dictionary", "containing", "the", "data", "neccessary", "to", "create", "CRTomo", "grids" ]
27c3e21a557f8df1c12455b96c4c2e00e08a5b4a
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/src/cr_trig_parse_gmsh.py#L22-L199
train
Parse a GMSH file and return a dictionary containing the data and the CRTomo grids that are part of the GMSH file.
geophysics-ubonn/crtomo_tools
src/cr_trig_parse_gmsh.py
get_header
def get_header(mesh): """ For now we only know Element types 1 (line) and 2 (triangle) """ nr_all_nodes = len(mesh['nodes']) nr_types = 1 # triangles # compute bandwidth bandwidth = -1 for triangle in mesh['elements']['2']: diff1 = abs(triangle[0] - triangle[1]) diff2 =...
python
def get_header(mesh): """ For now we only know Element types 1 (line) and 2 (triangle) """ nr_all_nodes = len(mesh['nodes']) nr_types = 1 # triangles # compute bandwidth bandwidth = -1 for triangle in mesh['elements']['2']: diff1 = abs(triangle[0] - triangle[1]) diff2 =...
[ "def", "get_header", "(", "mesh", ")", ":", "nr_all_nodes", "=", "len", "(", "mesh", "[", "'nodes'", "]", ")", "nr_types", "=", "1", "# triangles", "# compute bandwidth", "bandwidth", "=", "-", "1", "for", "triangle", "in", "mesh", "[", "'elements'", "]", ...
For now we only know Element types 1 (line) and 2 (triangle)
[ "For", "now", "we", "only", "know", "Element", "types", "1", "(", "line", ")", "and", "2", "(", "triangle", ")" ]
27c3e21a557f8df1c12455b96c4c2e00e08a5b4a
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/src/cr_trig_parse_gmsh.py#L304-L347
train
This function returns the header of the current node list.
geophysics-ubonn/crtomo_tools
src/cr_trig_parse_gmsh.py
get_ajd_bound
def get_ajd_bound(mesh): """ Determine triangular elements adjacend to the boundary elements """ print('Get elements adjacent to boundaries') boundary_elements = [] str_adj_boundaries = '' # for boundary in mesh['elements']['1']: boundaries = mesh['boundaries']['12'] + mesh['boundaries']...
python
def get_ajd_bound(mesh): """ Determine triangular elements adjacend to the boundary elements """ print('Get elements adjacent to boundaries') boundary_elements = [] str_adj_boundaries = '' # for boundary in mesh['elements']['1']: boundaries = mesh['boundaries']['12'] + mesh['boundaries']...
[ "def", "get_ajd_bound", "(", "mesh", ")", ":", "print", "(", "'Get elements adjacent to boundaries'", ")", "boundary_elements", "=", "[", "]", "str_adj_boundaries", "=", "''", "# for boundary in mesh['elements']['1']:", "boundaries", "=", "mesh", "[", "'boundaries'", "]...
Determine triangular elements adjacend to the boundary elements
[ "Determine", "triangular", "elements", "adjacend", "to", "the", "boundary", "elements" ]
27c3e21a557f8df1c12455b96c4c2e00e08a5b4a
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/src/cr_trig_parse_gmsh.py#L385-L405
train
Determine triangular elements adjacent to the boundary elements
geophysics-ubonn/crtomo_tools
src/cr_trig_parse_gmsh.py
write_elec_file
def write_elec_file(filename, mesh): """ Read in the electrode positions and return the indices of the electrodes # TODO: Check if you find all electrodes """ elecs = [] # print('Write electrodes') electrodes = np.loadtxt(filename) for i in electrodes: # find for nr, j i...
python
def write_elec_file(filename, mesh): """ Read in the electrode positions and return the indices of the electrodes # TODO: Check if you find all electrodes """ elecs = [] # print('Write electrodes') electrodes = np.loadtxt(filename) for i in electrodes: # find for nr, j i...
[ "def", "write_elec_file", "(", "filename", ",", "mesh", ")", ":", "elecs", "=", "[", "]", "# print('Write electrodes')", "electrodes", "=", "np", ".", "loadtxt", "(", "filename", ")", "for", "i", "in", "electrodes", ":", "# find", "for", "nr", ",", "j", ...
Read in the electrode positions and return the indices of the electrodes # TODO: Check if you find all electrodes
[ "Read", "in", "the", "electrode", "positions", "and", "return", "the", "indices", "of", "the", "electrodes" ]
27c3e21a557f8df1c12455b96c4c2e00e08a5b4a
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/src/cr_trig_parse_gmsh.py#L408-L427
train
Write the electrode positions and indices of the electrodes in the file.
geophysics-ubonn/crtomo_tools
src/cr_trig_parse_gmsh.py
main
def main(): mesh = parse_gmsh('../commands.msh', '../boundary_lines.dat') # now create the CRTomo grid """ 1. Header 2. Nodes 3. Elements: Triangles, Boundary elements 4. Element ids for adjoining boundary elements """ str_header = get_header(mesh) str_nodes = get_nodes(mesh) ...
python
def main(): mesh = parse_gmsh('../commands.msh', '../boundary_lines.dat') # now create the CRTomo grid """ 1. Header 2. Nodes 3. Elements: Triangles, Boundary elements 4. Element ids for adjoining boundary elements """ str_header = get_header(mesh) str_nodes = get_nodes(mesh) ...
[ "def", "main", "(", ")", ":", "mesh", "=", "parse_gmsh", "(", "'../commands.msh'", ",", "'../boundary_lines.dat'", ")", "# now create the CRTomo grid", "str_header", "=", "get_header", "(", "mesh", ")", "str_nodes", "=", "get_nodes", "(", "mesh", ")", "str_element...
1. Header 2. Nodes 3. Elements: Triangles, Boundary elements 4. Element ids for adjoining boundary elements
[ "1", ".", "Header", "2", ".", "Nodes", "3", ".", "Elements", ":", "Triangles", "Boundary", "elements", "4", ".", "Element", "ids", "for", "adjoining", "boundary", "elements" ]
27c3e21a557f8df1c12455b96c4c2e00e08a5b4a
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/src/cr_trig_parse_gmsh.py#L430-L453
train
main function for the boundary elements plot
geophysics-ubonn/crtomo_tools
src/cr_trig_parse_gmsh.py
_line.get_center
def get_center(self): """ Return (x,y) coordinate of central point """ dist = self.get_distance() diff = self.get_diff() direction = diff / dist center_x = self.p2_x + (dist * 0.5) * direction[0] center_y = self.p2_y + (dist * 0.5) * direction[1] ...
python
def get_center(self): """ Return (x,y) coordinate of central point """ dist = self.get_distance() diff = self.get_diff() direction = diff / dist center_x = self.p2_x + (dist * 0.5) * direction[0] center_y = self.p2_y + (dist * 0.5) * direction[1] ...
[ "def", "get_center", "(", "self", ")", ":", "dist", "=", "self", ".", "get_distance", "(", ")", "diff", "=", "self", ".", "get_diff", "(", ")", "direction", "=", "diff", "/", "dist", "center_x", "=", "self", ".", "p2_x", "+", "(", "dist", "*", "0.5...
Return (x,y) coordinate of central point
[ "Return", "(", "x", "y", ")", "coordinate", "of", "central", "point" ]
27c3e21a557f8df1c12455b96c4c2e00e08a5b4a
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/src/cr_trig_parse_gmsh.py#L221-L232
train
Return x y coordinate of central point of the current species
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulationCell.state_size
def state_size(self) -> Sequence[Shape]: '''Returns the MDP state size.''' return self._sizes(self._compiler.rddl.state_size)
python
def state_size(self) -> Sequence[Shape]: '''Returns the MDP state size.''' return self._sizes(self._compiler.rddl.state_size)
[ "def", "state_size", "(", "self", ")", "->", "Sequence", "[", "Shape", "]", ":", "return", "self", ".", "_sizes", "(", "self", ".", "_compiler", ".", "rddl", ".", "state_size", ")" ]
Returns the MDP state size.
[ "Returns", "the", "MDP", "state", "size", "." ]
d7102a0ad37d179dbb23141640254ea383d3b43f
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L77-L79
train
Returns the MDP state size.
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulationCell.action_size
def action_size(self) -> Sequence[Shape]: '''Returns the MDP action size.''' return self._sizes(self._compiler.rddl.action_size)
python
def action_size(self) -> Sequence[Shape]: '''Returns the MDP action size.''' return self._sizes(self._compiler.rddl.action_size)
[ "def", "action_size", "(", "self", ")", "->", "Sequence", "[", "Shape", "]", ":", "return", "self", ".", "_sizes", "(", "self", ".", "_compiler", ".", "rddl", ".", "action_size", ")" ]
Returns the MDP action size.
[ "Returns", "the", "MDP", "action", "size", "." ]
d7102a0ad37d179dbb23141640254ea383d3b43f
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L82-L84
train
Returns the MDP action size.
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulationCell.interm_size
def interm_size(self) -> Sequence[Shape]: '''Returns the MDP intermediate state size.''' return self._sizes(self._compiler.rddl.interm_size)
python
def interm_size(self) -> Sequence[Shape]: '''Returns the MDP intermediate state size.''' return self._sizes(self._compiler.rddl.interm_size)
[ "def", "interm_size", "(", "self", ")", "->", "Sequence", "[", "Shape", "]", ":", "return", "self", ".", "_sizes", "(", "self", ".", "_compiler", ".", "rddl", ".", "interm_size", ")" ]
Returns the MDP intermediate state size.
[ "Returns", "the", "MDP", "intermediate", "state", "size", "." ]
d7102a0ad37d179dbb23141640254ea383d3b43f
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L87-L89
train
Returns the MDP intermediate state size.
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulationCell.output_size
def output_size(self) -> Tuple[Sequence[Shape], Sequence[Shape], Sequence[Shape], int]: '''Returns the simulation cell output size.''' return (self.state_size, self.action_size, self.interm_size, 1)
python
def output_size(self) -> Tuple[Sequence[Shape], Sequence[Shape], Sequence[Shape], int]: '''Returns the simulation cell output size.''' return (self.state_size, self.action_size, self.interm_size, 1)
[ "def", "output_size", "(", "self", ")", "->", "Tuple", "[", "Sequence", "[", "Shape", "]", ",", "Sequence", "[", "Shape", "]", ",", "Sequence", "[", "Shape", "]", ",", "int", "]", ":", "return", "(", "self", ".", "state_size", ",", "self", ".", "ac...
Returns the simulation cell output size.
[ "Returns", "the", "simulation", "cell", "output", "size", "." ]
d7102a0ad37d179dbb23141640254ea383d3b43f
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L92-L94
train
Returns the simulation cell output size.
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulationCell.initial_state
def initial_state(self) -> StateTensor: '''Returns the initial state tensor.''' s0 = [] for fluent in self._compiler.compile_initial_state(self._batch_size): s0.append(self._output_size(fluent)) s0 = tuple(s0) return s0
python
def initial_state(self) -> StateTensor: '''Returns the initial state tensor.''' s0 = [] for fluent in self._compiler.compile_initial_state(self._batch_size): s0.append(self._output_size(fluent)) s0 = tuple(s0) return s0
[ "def", "initial_state", "(", "self", ")", "->", "StateTensor", ":", "s0", "=", "[", "]", "for", "fluent", "in", "self", ".", "_compiler", ".", "compile_initial_state", "(", "self", ".", "_batch_size", ")", ":", "s0", ".", "append", "(", "self", ".", "_...
Returns the initial state tensor.
[ "Returns", "the", "initial", "state", "tensor", "." ]
d7102a0ad37d179dbb23141640254ea383d3b43f
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L96-L102
train
Returns the initial state tensor.
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulationCell._tensors
def _tensors(cls, fluents: Sequence[FluentPair]) -> Iterable[tf.Tensor]: '''Yields the `fluents`' tensors.''' for _, fluent in fluents: tensor = cls._output_size(fluent.tensor) yield tensor
python
def _tensors(cls, fluents: Sequence[FluentPair]) -> Iterable[tf.Tensor]: '''Yields the `fluents`' tensors.''' for _, fluent in fluents: tensor = cls._output_size(fluent.tensor) yield tensor
[ "def", "_tensors", "(", "cls", ",", "fluents", ":", "Sequence", "[", "FluentPair", "]", ")", "->", "Iterable", "[", "tf", ".", "Tensor", "]", ":", "for", "_", ",", "fluent", "in", "fluents", ":", "tensor", "=", "cls", ".", "_output_size", "(", "fluen...
Yields the `fluents`' tensors.
[ "Yields", "the", "fluents", "tensors", "." ]
d7102a0ad37d179dbb23141640254ea383d3b43f
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L157-L161
train
Yields the fluents tensors.
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulationCell._dtype
def _dtype(cls, tensor: tf.Tensor) -> tf.Tensor: '''Converts `tensor` to tf.float32 datatype if needed.''' if tensor.dtype != tf.float32: tensor = tf.cast(tensor, tf.float32) return tensor
python
def _dtype(cls, tensor: tf.Tensor) -> tf.Tensor: '''Converts `tensor` to tf.float32 datatype if needed.''' if tensor.dtype != tf.float32: tensor = tf.cast(tensor, tf.float32) return tensor
[ "def", "_dtype", "(", "cls", ",", "tensor", ":", "tf", ".", "Tensor", ")", "->", "tf", ".", "Tensor", ":", "if", "tensor", ".", "dtype", "!=", "tf", ".", "float32", ":", "tensor", "=", "tf", ".", "cast", "(", "tensor", ",", "tf", ".", "float32", ...
Converts `tensor` to tf.float32 datatype if needed.
[ "Converts", "tensor", "to", "tf", ".", "float32", "datatype", "if", "needed", "." ]
d7102a0ad37d179dbb23141640254ea383d3b43f
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L164-L168
train
Converts tensor to tf. float32 datatype if needed.
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulationCell._output
def _output(cls, fluents: Sequence[FluentPair]) -> Sequence[tf.Tensor]: '''Returns output tensors for `fluents`.''' return tuple(cls._dtype(t) for t in cls._tensors(fluents))
python
def _output(cls, fluents: Sequence[FluentPair]) -> Sequence[tf.Tensor]: '''Returns output tensors for `fluents`.''' return tuple(cls._dtype(t) for t in cls._tensors(fluents))
[ "def", "_output", "(", "cls", ",", "fluents", ":", "Sequence", "[", "FluentPair", "]", ")", "->", "Sequence", "[", "tf", ".", "Tensor", "]", ":", "return", "tuple", "(", "cls", ".", "_dtype", "(", "t", ")", "for", "t", "in", "cls", ".", "_tensors",...
Returns output tensors for `fluents`.
[ "Returns", "output", "tensors", "for", "fluents", "." ]
d7102a0ad37d179dbb23141640254ea383d3b43f
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L171-L173
train
Returns output tensors for fluents.
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulator.output_size
def output_size(self) -> Tuple[Sequence[Shape], Sequence[Shape], Sequence[Shape], int]: '''Returns the simulation output size.''' return self._cell.output_size
python
def output_size(self) -> Tuple[Sequence[Shape], Sequence[Shape], Sequence[Shape], int]: '''Returns the simulation output size.''' return self._cell.output_size
[ "def", "output_size", "(", "self", ")", "->", "Tuple", "[", "Sequence", "[", "Shape", "]", ",", "Sequence", "[", "Shape", "]", ",", "Sequence", "[", "Shape", "]", ",", "int", "]", ":", "return", "self", ".", "_cell", ".", "output_size" ]
Returns the simulation output size.
[ "Returns", "the", "simulation", "output", "size", "." ]
d7102a0ad37d179dbb23141640254ea383d3b43f
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L214-L216
train
Returns the simulation output size.
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulator.timesteps
def timesteps(self, horizon: int) -> tf.Tensor: '''Returns the input tensor for the given `horizon`.''' start, limit, delta = horizon - 1, -1, -1 timesteps_range = tf.range(start, limit, delta, dtype=tf.float32) timesteps_range = tf.expand_dims(timesteps_range, -1) batch_timestep...
python
def timesteps(self, horizon: int) -> tf.Tensor: '''Returns the input tensor for the given `horizon`.''' start, limit, delta = horizon - 1, -1, -1 timesteps_range = tf.range(start, limit, delta, dtype=tf.float32) timesteps_range = tf.expand_dims(timesteps_range, -1) batch_timestep...
[ "def", "timesteps", "(", "self", ",", "horizon", ":", "int", ")", "->", "tf", ".", "Tensor", ":", "start", ",", "limit", ",", "delta", "=", "horizon", "-", "1", ",", "-", "1", ",", "-", "1", "timesteps_range", "=", "tf", ".", "range", "(", "start...
Returns the input tensor for the given `horizon`.
[ "Returns", "the", "input", "tensor", "for", "the", "given", "horizon", "." ]
d7102a0ad37d179dbb23141640254ea383d3b43f
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L218-L224
train
Returns the input tensor for the given horizon.
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulator.trajectory
def trajectory(self, horizon: int, initial_state: Optional[StateTensor] = None) -> TrajectoryOutput: '''Returns the ops for the trajectory generation with given `horizon` and `initial_state`. The simulation returns states, actions and interms as a sequence of ten...
python
def trajectory(self, horizon: int, initial_state: Optional[StateTensor] = None) -> TrajectoryOutput: '''Returns the ops for the trajectory generation with given `horizon` and `initial_state`. The simulation returns states, actions and interms as a sequence of ten...
[ "def", "trajectory", "(", "self", ",", "horizon", ":", "int", ",", "initial_state", ":", "Optional", "[", "StateTensor", "]", "=", "None", ")", "->", "TrajectoryOutput", ":", "if", "initial_state", "is", "None", ":", "initial_state", "=", "self", ".", "_ce...
Returns the ops for the trajectory generation with given `horizon` and `initial_state`. The simulation returns states, actions and interms as a sequence of tensors (i.e., all representations are factored). The reward is a batch sized tensor. The trajectoty output is a tuple: (in...
[ "Returns", "the", "ops", "for", "the", "trajectory", "generation", "with", "given", "horizon", "and", "initial_state", "." ]
d7102a0ad37d179dbb23141640254ea383d3b43f
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L226-L272
train
Returns the ops for the trajectory generation with given horizon and initial_state.
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulator.run
def run(self, horizon: int, initial_state: Optional[StateTensor] = None) -> SimulationOutput: '''Builds the MDP graph and simulates in batch the trajectories with given `horizon`. Returns the non-fluents, states, actions, interms and rewards. Fluents and non-fluents are r...
python
def run(self, horizon: int, initial_state: Optional[StateTensor] = None) -> SimulationOutput: '''Builds the MDP graph and simulates in batch the trajectories with given `horizon`. Returns the non-fluents, states, actions, interms and rewards. Fluents and non-fluents are r...
[ "def", "run", "(", "self", ",", "horizon", ":", "int", ",", "initial_state", ":", "Optional", "[", "StateTensor", "]", "=", "None", ")", "->", "SimulationOutput", ":", "trajectory", "=", "self", ".", "trajectory", "(", "horizon", ",", "initial_state", ")",...
Builds the MDP graph and simulates in batch the trajectories with given `horizon`. Returns the non-fluents, states, actions, interms and rewards. Fluents and non-fluents are returned in factored form. Note: All output arrays have shape: (batch_size, horizon, fluent_shape). ...
[ "Builds", "the", "MDP", "graph", "and", "simulates", "in", "batch", "the", "trajectories", "with", "given", "horizon", ".", "Returns", "the", "non", "-", "fluents", "states", "actions", "interms", "and", "rewards", ".", "Fluents", "and", "non", "-", "fluents...
d7102a0ad37d179dbb23141640254ea383d3b43f
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L274-L320
train
Builds the MDP graph and simulates in batch the trajectories with given horizon.
thiagopbueno/tf-rddlsim
tfrddlsim/simulation/policy_simulator.py
PolicySimulator._output
def _output(cls, tensors: Sequence[tf.Tensor], dtypes: Sequence[tf.DType]) -> Sequence[tf.Tensor]: '''Converts `tensors` to the corresponding `dtypes`.''' outputs = [] for tensor, dtype in zip(tensors, dtypes): tensor = tensor[0] if tensor.dtype !=...
python
def _output(cls, tensors: Sequence[tf.Tensor], dtypes: Sequence[tf.DType]) -> Sequence[tf.Tensor]: '''Converts `tensors` to the corresponding `dtypes`.''' outputs = [] for tensor, dtype in zip(tensors, dtypes): tensor = tensor[0] if tensor.dtype !=...
[ "def", "_output", "(", "cls", ",", "tensors", ":", "Sequence", "[", "tf", ".", "Tensor", "]", ",", "dtypes", ":", "Sequence", "[", "tf", ".", "DType", "]", ")", "->", "Sequence", "[", "tf", ".", "Tensor", "]", ":", "outputs", "=", "[", "]", "for"...
Converts `tensors` to the corresponding `dtypes`.
[ "Converts", "tensors", "to", "the", "corresponding", "dtypes", "." ]
d7102a0ad37d179dbb23141640254ea383d3b43f
https://github.com/thiagopbueno/tf-rddlsim/blob/d7102a0ad37d179dbb23141640254ea383d3b43f/tfrddlsim/simulation/policy_simulator.py#L323-L333
train
Converts tensors to the corresponding dtypes.
pgxcentre/geneparse
geneparse/readers/impute2.py
Impute2Reader.get_variant_genotypes
def get_variant_genotypes(self, variant): """Get the genotypes from a well formed variant instance. Args: marker (Variant): A Variant instance. Returns: A list of Genotypes instance containing a pointer to the variant as well as a vector of encoded genotypes...
python
def get_variant_genotypes(self, variant): """Get the genotypes from a well formed variant instance. Args: marker (Variant): A Variant instance. Returns: A list of Genotypes instance containing a pointer to the variant as well as a vector of encoded genotypes...
[ "def", "get_variant_genotypes", "(", "self", ",", "variant", ")", ":", "if", "not", "self", ".", "has_index", ":", "raise", "NotImplementedError", "(", "\"Not implemented when IMPUTE2 file is \"", "\"not indexed (see genipe)\"", ")", "# Find the variant in the index", "try"...
Get the genotypes from a well formed variant instance. Args: marker (Variant): A Variant instance. Returns: A list of Genotypes instance containing a pointer to the variant as well as a vector of encoded genotypes.
[ "Get", "the", "genotypes", "from", "a", "well", "formed", "variant", "instance", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/impute2.py#L184-L220
train
Returns a list of Genotypes instances containing a pointer to the variant as well as a vector of encoded genotypes.
pgxcentre/geneparse
geneparse/readers/impute2.py
Impute2Reader._get_biallelic_variant
def _get_biallelic_variant(self, variant, info, _check_alleles=True): """Creates a bi-allelic variant.""" info = info.iloc[0, :] assert not info.multiallelic # Seeking and parsing the file self._impute2_file.seek(info.seek) genotypes = self._parse_impute2_line(self._impu...
python
def _get_biallelic_variant(self, variant, info, _check_alleles=True): """Creates a bi-allelic variant.""" info = info.iloc[0, :] assert not info.multiallelic # Seeking and parsing the file self._impute2_file.seek(info.seek) genotypes = self._parse_impute2_line(self._impu...
[ "def", "_get_biallelic_variant", "(", "self", ",", "variant", ",", "info", ",", "_check_alleles", "=", "True", ")", ":", "info", "=", "info", ".", "iloc", "[", "0", ",", ":", "]", "assert", "not", "info", ".", "multiallelic", "# Seeking and parsing the file"...
Creates a bi-allelic variant.
[ "Creates", "a", "bi", "-", "allelic", "variant", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/impute2.py#L222-L239
train
Creates a bi - alleles variant.
pgxcentre/geneparse
geneparse/readers/impute2.py
Impute2Reader.iter_genotypes
def iter_genotypes(self): """Iterates on available markers. Returns: Genotypes instances. """ # Seeking at the beginning of the file self._impute2_file.seek(0) # Parsing each lines of the IMPUTE2 file for i, line in enumerate(self._impute2_file): ...
python
def iter_genotypes(self): """Iterates on available markers. Returns: Genotypes instances. """ # Seeking at the beginning of the file self._impute2_file.seek(0) # Parsing each lines of the IMPUTE2 file for i, line in enumerate(self._impute2_file): ...
[ "def", "iter_genotypes", "(", "self", ")", ":", "# Seeking at the beginning of the file", "self", ".", "_impute2_file", ".", "seek", "(", "0", ")", "# Parsing each lines of the IMPUTE2 file", "for", "i", ",", "line", "in", "enumerate", "(", "self", ".", "_impute2_fi...
Iterates on available markers. Returns: Genotypes instances.
[ "Iterates", "on", "available", "markers", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/impute2.py#L283-L302
train
Iterates on available markers.
pgxcentre/geneparse
geneparse/readers/impute2.py
Impute2Reader.iter_variants
def iter_variants(self): """Iterate over marker information.""" if not self.has_index: raise NotImplementedError("Not implemented when IMPUTE2 file is " "not indexed (see genipe)") for name, row in self._impute2_index.iterrows(): # S...
python
def iter_variants(self): """Iterate over marker information.""" if not self.has_index: raise NotImplementedError("Not implemented when IMPUTE2 file is " "not indexed (see genipe)") for name, row in self._impute2_index.iterrows(): # S...
[ "def", "iter_variants", "(", "self", ")", ":", "if", "not", "self", ".", "has_index", ":", "raise", "NotImplementedError", "(", "\"Not implemented when IMPUTE2 file is \"", "\"not indexed (see genipe)\"", ")", "for", "name", ",", "row", "in", "self", ".", "_impute2_...
Iterate over marker information.
[ "Iterate", "over", "marker", "information", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/impute2.py#L304-L318
train
Iterate over the variants in the IMPUTE2 file.
pgxcentre/geneparse
geneparse/readers/impute2.py
Impute2Reader.get_variants_in_region
def get_variants_in_region(self, chrom, start, end): """Iterate over variants in a region.""" if not self.has_index: raise NotImplementedError("Not implemented when IMPUTE2 file is " "not indexed (see genipe)") if not self._index_has_location: ...
python
def get_variants_in_region(self, chrom, start, end): """Iterate over variants in a region.""" if not self.has_index: raise NotImplementedError("Not implemented when IMPUTE2 file is " "not indexed (see genipe)") if not self._index_has_location: ...
[ "def", "get_variants_in_region", "(", "self", ",", "chrom", ",", "start", ",", "end", ")", ":", "if", "not", "self", ".", "has_index", ":", "raise", "NotImplementedError", "(", "\"Not implemented when IMPUTE2 file is \"", "\"not indexed (see genipe)\"", ")", "if", "...
Iterate over variants in a region.
[ "Iterate", "over", "variants", "in", "a", "region", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/impute2.py#L320-L340
train
Iterate over the variants in a region.
pgxcentre/geneparse
geneparse/readers/impute2.py
Impute2Reader.get_variant_by_name
def get_variant_by_name(self, name, variant_info=None): """Get the genotype of a marker using it's name. Args: name (str): The name of the marker. variant_info (pandas.Series): The marker information (e.g. seek). Returns: list: A list of Genotypes (only one ...
python
def get_variant_by_name(self, name, variant_info=None): """Get the genotype of a marker using it's name. Args: name (str): The name of the marker. variant_info (pandas.Series): The marker information (e.g. seek). Returns: list: A list of Genotypes (only one ...
[ "def", "get_variant_by_name", "(", "self", ",", "name", ",", "variant_info", "=", "None", ")", ":", "# From 1.3.2 onwards, PyPlink sets unique names.", "if", "not", "self", ".", "has_index", ":", "raise", "NotImplementedError", "(", "\"Not implemented when IMPUTE2 file is...
Get the genotype of a marker using it's name. Args: name (str): The name of the marker. variant_info (pandas.Series): The marker information (e.g. seek). Returns: list: A list of Genotypes (only one for PyPlink, see note below). Note ==== ...
[ "Get", "the", "genotype", "of", "a", "marker", "using", "it", "s", "name", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/impute2.py#L342-L392
train
Get the genotype of a specific variant using it s name.
pgxcentre/geneparse
geneparse/readers/impute2.py
Impute2Reader._fix_genotypes_object
def _fix_genotypes_object(self, genotypes, variant_info): """Fixes a genotypes object (variant name, multi-allelic value.""" # Checking the name (if there were duplications) if self.has_index and variant_info.name != genotypes.variant.name: if not variant_info.name.startswith(genotyp...
python
def _fix_genotypes_object(self, genotypes, variant_info): """Fixes a genotypes object (variant name, multi-allelic value.""" # Checking the name (if there were duplications) if self.has_index and variant_info.name != genotypes.variant.name: if not variant_info.name.startswith(genotyp...
[ "def", "_fix_genotypes_object", "(", "self", ",", "genotypes", ",", "variant_info", ")", ":", "# Checking the name (if there were duplications)", "if", "self", ".", "has_index", "and", "variant_info", ".", "name", "!=", "genotypes", ".", "variant", ".", "name", ":",...
Fixes a genotypes object (variant name, multi-allelic value.
[ "Fixes", "a", "genotypes", "object", "(", "variant", "name", "multi", "-", "allelic", "value", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/impute2.py#L394-L412
train
Fixes a genotypes object.
pgxcentre/geneparse
geneparse/readers/impute2.py
Impute2Reader._parse_impute2_line
def _parse_impute2_line(self, line): """Parses the current IMPUTE2 line (a single variant). Args: line (str): An IMPUTE2 line. Returns: Genotypes: The genotype in dosage format. Warning ======= By default, the genotypes object has multiallel...
python
def _parse_impute2_line(self, line): """Parses the current IMPUTE2 line (a single variant). Args: line (str): An IMPUTE2 line. Returns: Genotypes: The genotype in dosage format. Warning ======= By default, the genotypes object has multiallel...
[ "def", "_parse_impute2_line", "(", "self", ",", "line", ")", ":", "# Splitting", "row", "=", "line", ".", "rstrip", "(", "\"\\r\\n\"", ")", ".", "split", "(", "\" \"", ")", "# Constructing the probabilities", "prob", "=", "np", ".", "array", "(", "row", "[...
Parses the current IMPUTE2 line (a single variant). Args: line (str): An IMPUTE2 line. Returns: Genotypes: The genotype in dosage format. Warning ======= By default, the genotypes object has multiallelic set to False.
[ "Parses", "the", "current", "IMPUTE2", "line", "(", "a", "single", "variant", ")", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/impute2.py#L438-L471
train
Parses the current IMPUTE2 line and returns a Genotypes object.
ghukill/pyfc4
pyfc4/plugins/pcdm/models.py
PCDMCollection._post_create
def _post_create(self, auto_refresh=False): ''' resource.create() hook For PCDM Collections, post creation, also create ''' # set PCDM triple as Collection self.add_triple(self.rdf.prefixes.rdf.type, self.rdf.prefixes.pcdm.Collection) self.update(auto_refresh=auto_refresh) # create /members child re...
python
def _post_create(self, auto_refresh=False): ''' resource.create() hook For PCDM Collections, post creation, also create ''' # set PCDM triple as Collection self.add_triple(self.rdf.prefixes.rdf.type, self.rdf.prefixes.pcdm.Collection) self.update(auto_refresh=auto_refresh) # create /members child re...
[ "def", "_post_create", "(", "self", ",", "auto_refresh", "=", "False", ")", ":", "# set PCDM triple as Collection", "self", ".", "add_triple", "(", "self", ".", "rdf", ".", "prefixes", ".", "rdf", ".", "type", ",", "self", ".", "rdf", ".", "prefixes", ".",...
resource.create() hook For PCDM Collections, post creation, also create
[ "resource", ".", "create", "()", "hook" ]
59011df592f08978c4a901a908862d112a5dcf02
https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/plugins/pcdm/models.py#L56-L84
train
Hook the create method of the PCDM Collection resource.
ghukill/pyfc4
pyfc4/plugins/pcdm/models.py
PCDMCollection.get_related
def get_related(self): ''' get ore:aggregates for this resource, optionally retrieving resource payload Args: retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload ''' if self.exists and hasattr(self.rdf.triples, 'ore') and hasattr(self.rdf.triples.or...
python
def get_related(self): ''' get ore:aggregates for this resource, optionally retrieving resource payload Args: retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload ''' if self.exists and hasattr(self.rdf.triples, 'ore') and hasattr(self.rdf.triples.or...
[ "def", "get_related", "(", "self", ")", ":", "if", "self", ".", "exists", "and", "hasattr", "(", "self", ".", "rdf", ".", "triples", ",", "'ore'", ")", "and", "hasattr", "(", "self", ".", "rdf", ".", "triples", ".", "ore", ",", "'aggregates'", ")", ...
get ore:aggregates for this resource, optionally retrieving resource payload Args: retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload
[ "get", "ore", ":", "aggregates", "for", "this", "resource", "optionally", "retrieving", "resource", "payload" ]
59011df592f08978c4a901a908862d112a5dcf02
https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/plugins/pcdm/models.py#L106-L122
train
Returns a list of related resources for this resource optionally retrieving resource payload
ghukill/pyfc4
pyfc4/plugins/pcdm/models.py
PCDMObject._post_create
def _post_create(self, auto_refresh=False): ''' resource.create() hook ''' # set PCDM triple as Object self.add_triple(self.rdf.prefixes.rdf.type, self.rdf.prefixes.pcdm.Object) self.update(auto_refresh=auto_refresh) # create /files child resource files_child = PCDMFilesContainer( self.repo, '%...
python
def _post_create(self, auto_refresh=False): ''' resource.create() hook ''' # set PCDM triple as Object self.add_triple(self.rdf.prefixes.rdf.type, self.rdf.prefixes.pcdm.Object) self.update(auto_refresh=auto_refresh) # create /files child resource files_child = PCDMFilesContainer( self.repo, '%...
[ "def", "_post_create", "(", "self", ",", "auto_refresh", "=", "False", ")", ":", "# set PCDM triple as Object", "self", ".", "add_triple", "(", "self", ".", "rdf", ".", "prefixes", ".", "rdf", ".", "type", ",", "self", ".", "rdf", ".", "prefixes", ".", "...
resource.create() hook
[ "resource", ".", "create", "()", "hook" ]
59011df592f08978c4a901a908862d112a5dcf02
https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/plugins/pcdm/models.py#L232-L274
train
create the object in the repository
ghukill/pyfc4
pyfc4/plugins/pcdm/models.py
PCDMObject.get_members
def get_members(self, retrieve=False): ''' get pcdm:hasMember for this resource Args: retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload ''' if self.exists and hasattr(self.rdf.triples, 'pcdm') and hasattr(self.rdf.triples.pcdm, 'hasMember'): me...
python
def get_members(self, retrieve=False): ''' get pcdm:hasMember for this resource Args: retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload ''' if self.exists and hasattr(self.rdf.triples, 'pcdm') and hasattr(self.rdf.triples.pcdm, 'hasMember'): me...
[ "def", "get_members", "(", "self", ",", "retrieve", "=", "False", ")", ":", "if", "self", ".", "exists", "and", "hasattr", "(", "self", ".", "rdf", ".", "triples", ",", "'pcdm'", ")", "and", "hasattr", "(", "self", ".", "rdf", ".", "triples", ".", ...
get pcdm:hasMember for this resource Args: retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload
[ "get", "pcdm", ":", "hasMember", "for", "this", "resource" ]
59011df592f08978c4a901a908862d112a5dcf02
https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/plugins/pcdm/models.py#L277-L293
train
get members of this resource
ghukill/pyfc4
pyfc4/plugins/pcdm/models.py
PCDMObject.get_files
def get_files(self, retrieve=False): ''' get pcdm:hasFile for this resource Args: retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload ''' if self.exists and hasattr(self.rdf.triples, 'pcdm') and hasattr(self.rdf.triples.pcdm, 'hasFile'): files = ...
python
def get_files(self, retrieve=False): ''' get pcdm:hasFile for this resource Args: retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload ''' if self.exists and hasattr(self.rdf.triples, 'pcdm') and hasattr(self.rdf.triples.pcdm, 'hasFile'): files = ...
[ "def", "get_files", "(", "self", ",", "retrieve", "=", "False", ")", ":", "if", "self", ".", "exists", "and", "hasattr", "(", "self", ".", "rdf", ".", "triples", ",", "'pcdm'", ")", "and", "hasattr", "(", "self", ".", "rdf", ".", "triples", ".", "p...
get pcdm:hasFile for this resource Args: retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload
[ "get", "pcdm", ":", "hasFile", "for", "this", "resource" ]
59011df592f08978c4a901a908862d112a5dcf02
https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/plugins/pcdm/models.py#L296-L312
train
get the list of files in the resource
ghukill/pyfc4
pyfc4/plugins/pcdm/models.py
PCDMObject.get_associated
def get_associated(self, retrieve=False): ''' get pcdm:hasRelatedFile for this resource Args: retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload ''' if self.exists and hasattr(self.rdf.triples, 'pcdm') and hasattr(self.rdf.triples.pcdm, 'hasRelated...
python
def get_associated(self, retrieve=False): ''' get pcdm:hasRelatedFile for this resource Args: retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload ''' if self.exists and hasattr(self.rdf.triples, 'pcdm') and hasattr(self.rdf.triples.pcdm, 'hasRelated...
[ "def", "get_associated", "(", "self", ",", "retrieve", "=", "False", ")", ":", "if", "self", ".", "exists", "and", "hasattr", "(", "self", ".", "rdf", ".", "triples", ",", "'pcdm'", ")", "and", "hasattr", "(", "self", ".", "rdf", ".", "triples", ".",...
get pcdm:hasRelatedFile for this resource Args: retrieve (bool): if True, issue .refresh() on resource thereby confirming existence and retrieving payload
[ "get", "pcdm", ":", "hasRelatedFile", "for", "this", "resource" ]
59011df592f08978c4a901a908862d112a5dcf02
https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/plugins/pcdm/models.py#L315-L331
train
get the list of files that are associated with this resource
ghukill/pyfc4
pyfc4/plugins/pcdm/models.py
PCDMFile._post_create
def _post_create(self, auto_refresh=False): ''' resource.create() hook For PCDM File ''' # set PCDM triple as Collection self.add_triple(self.rdf.prefixes.rdf.type, self.rdf.prefixes.pcdm.File) self.update(auto_refresh=auto_refresh)
python
def _post_create(self, auto_refresh=False): ''' resource.create() hook For PCDM File ''' # set PCDM triple as Collection self.add_triple(self.rdf.prefixes.rdf.type, self.rdf.prefixes.pcdm.File) self.update(auto_refresh=auto_refresh)
[ "def", "_post_create", "(", "self", ",", "auto_refresh", "=", "False", ")", ":", "# set PCDM triple as Collection", "self", ".", "add_triple", "(", "self", ".", "rdf", ".", "prefixes", ".", "rdf", ".", "type", ",", "self", ".", "rdf", ".", "prefixes", ".",...
resource.create() hook For PCDM File
[ "resource", ".", "create", "()", "hook" ]
59011df592f08978c4a901a908862d112a5dcf02
https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/plugins/pcdm/models.py#L435-L445
train
Hook to create the resource.
ghukill/pyfc4
pyfc4/plugins/pcdm/models.py
PCDMProxyObject._post_create
def _post_create(self, auto_refresh=False): ''' resource.create() hook ''' # set rdf type self.add_triple(self.rdf.prefixes.rdf.type, self.rdf.prefixes.ore.Proxy) # set triple for what this resource is a proxy for if self.proxyForURI: self.add_triple(self.rdf.prefixes.ore.proxyFor, self.proxyForURI)...
python
def _post_create(self, auto_refresh=False): ''' resource.create() hook ''' # set rdf type self.add_triple(self.rdf.prefixes.rdf.type, self.rdf.prefixes.ore.Proxy) # set triple for what this resource is a proxy for if self.proxyForURI: self.add_triple(self.rdf.prefixes.ore.proxyFor, self.proxyForURI)...
[ "def", "_post_create", "(", "self", ",", "auto_refresh", "=", "False", ")", ":", "# set rdf type", "self", ".", "add_triple", "(", "self", ".", "rdf", ".", "prefixes", ".", "rdf", ".", "type", ",", "self", ".", "rdf", ".", "prefixes", ".", "ore", ".", ...
resource.create() hook
[ "resource", ".", "create", "()", "hook" ]
59011df592f08978c4a901a908862d112a5dcf02
https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/plugins/pcdm/models.py#L471-L489
train
Hook the resource creation and update the object
pgxcentre/geneparse
geneparse/readers/plink.py
PlinkReader.get_variant_genotypes
def get_variant_genotypes(self, variant): """Get the genotypes from a well formed variant instance. Args: marker (Variant): A Variant instance. Returns: A list of Genotypes instance containing a pointer to the variant as well as a vector of encoded genotypes...
python
def get_variant_genotypes(self, variant): """Get the genotypes from a well formed variant instance. Args: marker (Variant): A Variant instance. Returns: A list of Genotypes instance containing a pointer to the variant as well as a vector of encoded genotypes...
[ "def", "get_variant_genotypes", "(", "self", ",", "variant", ")", ":", "# Find the variant in the bim.", "try", ":", "plink_chrom", "=", "CHROM_STR_TO_INT", "[", "variant", ".", "chrom", ".", "name", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\...
Get the genotypes from a well formed variant instance. Args: marker (Variant): A Variant instance. Returns: A list of Genotypes instance containing a pointer to the variant as well as a vector of encoded genotypes. Note ==== If the sampl...
[ "Get", "the", "genotypes", "from", "a", "well", "formed", "variant", "instance", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/plink.py#L82-L119
train
Get the genotypes from a well formed variant instance.
pgxcentre/geneparse
geneparse/readers/plink.py
PlinkReader.iter_genotypes
def iter_genotypes(self): """Iterates on available markers. Returns: Genotypes instances. Note ==== If the sample IDs are not unique, the index is changed to be the sample family ID and individual ID (i.e. fid_iid). """ # Iterating o...
python
def iter_genotypes(self): """Iterates on available markers. Returns: Genotypes instances. Note ==== If the sample IDs are not unique, the index is changed to be the sample family ID and individual ID (i.e. fid_iid). """ # Iterating o...
[ "def", "iter_genotypes", "(", "self", ")", ":", "# Iterating over all markers", "for", "i", ",", "(", "_", ",", "genotypes", ")", "in", "enumerate", "(", "self", ".", "bed", ".", "iter_geno", "(", ")", ")", ":", "info", "=", "self", ".", "bim", ".", ...
Iterates on available markers. Returns: Genotypes instances. Note ==== If the sample IDs are not unique, the index is changed to be the sample family ID and individual ID (i.e. fid_iid).
[ "Iterates", "on", "available", "markers", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/plink.py#L159-L182
train
Iterates over all available genotypes.
pgxcentre/geneparse
geneparse/readers/plink.py
PlinkReader.iter_variants
def iter_variants(self): """Iterate over marker information.""" for idx, row in self.bim.iterrows(): yield Variant( row.name, CHROM_INT_TO_STR[row.chrom], row.pos, [row.a1, row.a2] )
python
def iter_variants(self): """Iterate over marker information.""" for idx, row in self.bim.iterrows(): yield Variant( row.name, CHROM_INT_TO_STR[row.chrom], row.pos, [row.a1, row.a2] )
[ "def", "iter_variants", "(", "self", ")", ":", "for", "idx", ",", "row", "in", "self", ".", "bim", ".", "iterrows", "(", ")", ":", "yield", "Variant", "(", "row", ".", "name", ",", "CHROM_INT_TO_STR", "[", "row", ".", "chrom", "]", ",", "row", ".",...
Iterate over marker information.
[ "Iterate", "over", "marker", "information", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/plink.py#L184-L190
train
Iterate over all the variants in the BIM file.
pgxcentre/geneparse
geneparse/readers/plink.py
PlinkReader.get_variants_in_region
def get_variants_in_region(self, chrom, start, end): """Iterate over variants in a region.""" bim = self.bim.loc[ (self.bim["chrom"] == CHROM_STR_TO_INT[chrom]) & (start <= self.bim["pos"]) & (self.bim["pos"] <= end) ] for i, g in enumerate(self.bed.it...
python
def get_variants_in_region(self, chrom, start, end): """Iterate over variants in a region.""" bim = self.bim.loc[ (self.bim["chrom"] == CHROM_STR_TO_INT[chrom]) & (start <= self.bim["pos"]) & (self.bim["pos"] <= end) ] for i, g in enumerate(self.bed.it...
[ "def", "get_variants_in_region", "(", "self", ",", "chrom", ",", "start", ",", "end", ")", ":", "bim", "=", "self", ".", "bim", ".", "loc", "[", "(", "self", ".", "bim", "[", "\"chrom\"", "]", "==", "CHROM_STR_TO_INT", "[", "chrom", "]", ")", "&", ...
Iterate over variants in a region.
[ "Iterate", "over", "variants", "in", "a", "region", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/plink.py#L192-L209
train
Iterate over variants in a region.
pgxcentre/geneparse
geneparse/readers/plink.py
PlinkReader.get_variant_by_name
def get_variant_by_name(self, name): """Get the genotype of a marker using it's name. Args: name (str): The name of the marker. Returns: list: A list of Genotypes (only one for PyPlink, see note below). Note ==== From PyPlink version 1.3.2 a...
python
def get_variant_by_name(self, name): """Get the genotype of a marker using it's name. Args: name (str): The name of the marker. Returns: list: A list of Genotypes (only one for PyPlink, see note below). Note ==== From PyPlink version 1.3.2 a...
[ "def", "get_variant_by_name", "(", "self", ",", "name", ")", ":", "# From 1.3.2 onwards, PyPlink sets unique names.", "# Getting the genotypes", "try", ":", "geno", ",", "i", "=", "self", ".", "bed", ".", "get_geno_marker", "(", "name", ",", "return_index", "=", "...
Get the genotype of a marker using it's name. Args: name (str): The name of the marker. Returns: list: A list of Genotypes (only one for PyPlink, see note below). Note ==== From PyPlink version 1.3.2 and onwards, each name is unique in the ...
[ "Get", "the", "genotype", "of", "a", "marker", "using", "it", "s", "name", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/plink.py#L211-L256
train
Get the genotype of a specific variant using it s name.
pgxcentre/geneparse
geneparse/readers/plink.py
PlinkReader._normalize_missing
def _normalize_missing(g): """Normalize a plink genotype vector.""" g = g.astype(float) g[g == -1.0] = np.nan return g
python
def _normalize_missing(g): """Normalize a plink genotype vector.""" g = g.astype(float) g[g == -1.0] = np.nan return g
[ "def", "_normalize_missing", "(", "g", ")", ":", "g", "=", "g", ".", "astype", "(", "float", ")", "g", "[", "g", "==", "-", "1.0", "]", "=", "np", ".", "nan", "return", "g" ]
Normalize a plink genotype vector.
[ "Normalize", "a", "plink", "genotype", "vector", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/readers/plink.py#L276-L280
train
Normalize a plink genotype vector to have missing values.
255BITS/hyperchamber
hyperchamber/__init__.py
configs
def configs(max_configs=1, offset=None, serial=False, create_uuid=True): """Generate max configs, each one a dictionary. e.g. [{'x': 1}] Will also add a config UUID, useful for tracking configs. You can turn this off by passing create_uuid=False. """ global default_selector return defau...
python
def configs(max_configs=1, offset=None, serial=False, create_uuid=True): """Generate max configs, each one a dictionary. e.g. [{'x': 1}] Will also add a config UUID, useful for tracking configs. You can turn this off by passing create_uuid=False. """ global default_selector return defau...
[ "def", "configs", "(", "max_configs", "=", "1", ",", "offset", "=", "None", ",", "serial", "=", "False", ",", "create_uuid", "=", "True", ")", ":", "global", "default_selector", "return", "default_selector", ".", "configs", "(", "max_configs", ",", "offset",...
Generate max configs, each one a dictionary. e.g. [{'x': 1}] Will also add a config UUID, useful for tracking configs. You can turn this off by passing create_uuid=False.
[ "Generate", "max", "configs", "each", "one", "a", "dictionary", ".", "e", ".", "g", ".", "[", "{", "x", ":", "1", "}", "]" ]
4d5774bde9ea6ce1113f77a069ffc605148482b8
https://github.com/255BITS/hyperchamber/blob/4d5774bde9ea6ce1113f77a069ffc605148482b8/hyperchamber/__init__.py#L24-L31
train
Generate max_configs configs in a sequence
255BITS/hyperchamber
examples/shared/cifar_utils.py
maybe_download_and_extract
def maybe_download_and_extract(): """Download and extract the tarball from Alex's website.""" dest_directory = "/tmp/cifar" if not os.path.exists(dest_directory): os.makedirs(dest_directory) filename = DATA_URL.split('/')[-1] filepath = os.path.join(dest_directory, filename) if not os.path.exists(filepa...
python
def maybe_download_and_extract(): """Download and extract the tarball from Alex's website.""" dest_directory = "/tmp/cifar" if not os.path.exists(dest_directory): os.makedirs(dest_directory) filename = DATA_URL.split('/')[-1] filepath = os.path.join(dest_directory, filename) if not os.path.exists(filepa...
[ "def", "maybe_download_and_extract", "(", ")", ":", "dest_directory", "=", "\"/tmp/cifar\"", "if", "not", "os", ".", "path", ".", "exists", "(", "dest_directory", ")", ":", "os", ".", "makedirs", "(", "dest_directory", ")", "filename", "=", "DATA_URL", ".", ...
Download and extract the tarball from Alex's website.
[ "Download", "and", "extract", "the", "tarball", "from", "Alex", "s", "website", "." ]
4d5774bde9ea6ce1113f77a069ffc605148482b8
https://github.com/255BITS/hyperchamber/blob/4d5774bde9ea6ce1113f77a069ffc605148482b8/examples/shared/cifar_utils.py#L73-L89
train
Download and extract the tarball from Alex s website.
255BITS/hyperchamber
examples/shared/cifar_utils.py
plot
def plot(config, image, file): """ Plot a single CIFAR image.""" image = np.squeeze(image) print(file, image.shape) imsave(file, image)
python
def plot(config, image, file): """ Plot a single CIFAR image.""" image = np.squeeze(image) print(file, image.shape) imsave(file, image)
[ "def", "plot", "(", "config", ",", "image", ",", "file", ")", ":", "image", "=", "np", ".", "squeeze", "(", "image", ")", "print", "(", "file", ",", "image", ".", "shape", ")", "imsave", "(", "file", ",", "image", ")" ]
Plot a single CIFAR image.
[ "Plot", "a", "single", "CIFAR", "image", "." ]
4d5774bde9ea6ce1113f77a069ffc605148482b8
https://github.com/255BITS/hyperchamber/blob/4d5774bde9ea6ce1113f77a069ffc605148482b8/examples/shared/cifar_utils.py#L91-L95
train
Plot a single CIFAR image.
kblin/bioinf-helperlibs
helperlibs/bio/seqio.py
_get_seqtype_from_ext
def _get_seqtype_from_ext(handle): '''Predict the filetype from a handle's name''' if isinstance(handle, basestring): name = handle elif hasattr(handle, 'filename'): name = handle.filename elif hasattr(handle, 'name'): name = handle.name else: raise ValueError("Unknow...
python
def _get_seqtype_from_ext(handle): '''Predict the filetype from a handle's name''' if isinstance(handle, basestring): name = handle elif hasattr(handle, 'filename'): name = handle.filename elif hasattr(handle, 'name'): name = handle.name else: raise ValueError("Unknow...
[ "def", "_get_seqtype_from_ext", "(", "handle", ")", ":", "if", "isinstance", "(", "handle", ",", "basestring", ")", ":", "name", "=", "handle", "elif", "hasattr", "(", "handle", ",", "'filename'", ")", ":", "name", "=", "handle", ".", "filename", "elif", ...
Predict the filetype from a handle's name
[ "Predict", "the", "filetype", "from", "a", "handle", "s", "name" ]
3a732d62b4b3cc42675631db886ba534672cb134
https://github.com/kblin/bioinf-helperlibs/blob/3a732d62b4b3cc42675631db886ba534672cb134/helperlibs/bio/seqio.py#L28-L55
train
Predict the filetype from a handle s name
kblin/bioinf-helperlibs
helperlibs/bio/seqio.py
_guess_seqtype_from_file
def _guess_seqtype_from_file(handle): "Guess the sequence type from the file's contents" if isinstance(handle, basestring): handle = StringIO(handle) for line in handle: if not line.strip(): continue if line.lstrip().split()[0] in ('LOCUS', 'FEATURES', 'source', 'CDS', ...
python
def _guess_seqtype_from_file(handle): "Guess the sequence type from the file's contents" if isinstance(handle, basestring): handle = StringIO(handle) for line in handle: if not line.strip(): continue if line.lstrip().split()[0] in ('LOCUS', 'FEATURES', 'source', 'CDS', ...
[ "def", "_guess_seqtype_from_file", "(", "handle", ")", ":", "if", "isinstance", "(", "handle", ",", "basestring", ")", ":", "handle", "=", "StringIO", "(", "handle", ")", "for", "line", "in", "handle", ":", "if", "not", "line", ".", "strip", "(", ")", ...
Guess the sequence type from the file's contents
[ "Guess", "the", "sequence", "type", "from", "the", "file", "s", "contents" ]
3a732d62b4b3cc42675631db886ba534672cb134
https://github.com/kblin/bioinf-helperlibs/blob/3a732d62b4b3cc42675631db886ba534672cb134/helperlibs/bio/seqio.py#L58-L84
train
Guess the sequence type from the file s contents
kblin/bioinf-helperlibs
helperlibs/bio/seqio.py
_unzip_handle
def _unzip_handle(handle): """Transparently unzip the file handle""" if isinstance(handle, basestring): handle = _gzip_open_filename(handle) else: handle = _gzip_open_handle(handle) return handle
python
def _unzip_handle(handle): """Transparently unzip the file handle""" if isinstance(handle, basestring): handle = _gzip_open_filename(handle) else: handle = _gzip_open_handle(handle) return handle
[ "def", "_unzip_handle", "(", "handle", ")", ":", "if", "isinstance", "(", "handle", ",", "basestring", ")", ":", "handle", "=", "_gzip_open_filename", "(", "handle", ")", "else", ":", "handle", "=", "_gzip_open_handle", "(", "handle", ")", "return", "handle"...
Transparently unzip the file handle
[ "Transparently", "unzip", "the", "file", "handle" ]
3a732d62b4b3cc42675631db886ba534672cb134
https://github.com/kblin/bioinf-helperlibs/blob/3a732d62b4b3cc42675631db886ba534672cb134/helperlibs/bio/seqio.py#L87-L93
train
Transparently unzip the file handle
kblin/bioinf-helperlibs
helperlibs/bio/seqio.py
_gzip_open_filename
def _gzip_open_filename(handle): """Hide Python 2 vs. 3 differences in gzip.open()""" import gzip if sys.version_info[0] > 2: handle = gzip.open(handle, mode='rt', encoding="UTF-8") else: handle = gzip.open(handle) return handle
python
def _gzip_open_filename(handle): """Hide Python 2 vs. 3 differences in gzip.open()""" import gzip if sys.version_info[0] > 2: handle = gzip.open(handle, mode='rt', encoding="UTF-8") else: handle = gzip.open(handle) return handle
[ "def", "_gzip_open_filename", "(", "handle", ")", ":", "import", "gzip", "if", "sys", ".", "version_info", "[", "0", "]", ">", "2", ":", "handle", "=", "gzip", ".", "open", "(", "handle", ",", "mode", "=", "'rt'", ",", "encoding", "=", "\"UTF-8\"", "...
Hide Python 2 vs. 3 differences in gzip.open()
[ "Hide", "Python", "2", "vs", ".", "3", "differences", "in", "gzip", ".", "open", "()" ]
3a732d62b4b3cc42675631db886ba534672cb134
https://github.com/kblin/bioinf-helperlibs/blob/3a732d62b4b3cc42675631db886ba534672cb134/helperlibs/bio/seqio.py#L96-L103
train
Hide Python 2 vs. 3 differences in gzip. open
kblin/bioinf-helperlibs
helperlibs/bio/seqio.py
_gzip_open_handle
def _gzip_open_handle(handle): """"Hide Python 2 vs. 3 differences in gzip.GzipFile()""" import gzip if sys.version_info[0] > 2: import io handle = io.TextIOWrapper(gzip.GzipFile(fileobj=handle), encoding="UTF-8") else: handle = gzip.GzipFile(fileobj=handle) return handle
python
def _gzip_open_handle(handle): """"Hide Python 2 vs. 3 differences in gzip.GzipFile()""" import gzip if sys.version_info[0] > 2: import io handle = io.TextIOWrapper(gzip.GzipFile(fileobj=handle), encoding="UTF-8") else: handle = gzip.GzipFile(fileobj=handle) return handle
[ "def", "_gzip_open_handle", "(", "handle", ")", ":", "import", "gzip", "if", "sys", ".", "version_info", "[", "0", "]", ">", "2", ":", "import", "io", "handle", "=", "io", ".", "TextIOWrapper", "(", "gzip", ".", "GzipFile", "(", "fileobj", "=", "handle...
Hide Python 2 vs. 3 differences in gzip.GzipFile()
[ "Hide", "Python", "2", "vs", ".", "3", "differences", "in", "gzip", ".", "GzipFile", "()" ]
3a732d62b4b3cc42675631db886ba534672cb134
https://github.com/kblin/bioinf-helperlibs/blob/3a732d62b4b3cc42675631db886ba534672cb134/helperlibs/bio/seqio.py#L106-L114
train
Hide Python 2 vs. 3 differences in gzip. GzipFile
kblin/bioinf-helperlibs
helperlibs/bio/seqio.py
sanity_check_insdcio
def sanity_check_insdcio(handle, id_marker, fake_id_line): """Sanity check for insdcio style files""" found_id = False found_end_marker = False for line in handle: line = line.strip() if not line: continue if line.startswith(id_marker): found_id = True ...
python
def sanity_check_insdcio(handle, id_marker, fake_id_line): """Sanity check for insdcio style files""" found_id = False found_end_marker = False for line in handle: line = line.strip() if not line: continue if line.startswith(id_marker): found_id = True ...
[ "def", "sanity_check_insdcio", "(", "handle", ",", "id_marker", ",", "fake_id_line", ")", ":", "found_id", "=", "False", "found_end_marker", "=", "False", "for", "line", "in", "handle", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line",...
Sanity check for insdcio style files
[ "Sanity", "check", "for", "insdcio", "style", "files" ]
3a732d62b4b3cc42675631db886ba534672cb134
https://github.com/kblin/bioinf-helperlibs/blob/3a732d62b4b3cc42675631db886ba534672cb134/helperlibs/bio/seqio.py#L117-L146
train
Sanity check for insdcio style files
kblin/bioinf-helperlibs
helperlibs/bio/seqio.py
sanity_check_fasta
def sanity_check_fasta(handle): """Sanity check FASTA files.""" header_found = False for line in handle: if line.startswith('>'): header_found = True break handle.seek(0) if header_found: return handle fake_header_line = ">DUMMY" new_handle = String...
python
def sanity_check_fasta(handle): """Sanity check FASTA files.""" header_found = False for line in handle: if line.startswith('>'): header_found = True break handle.seek(0) if header_found: return handle fake_header_line = ">DUMMY" new_handle = String...
[ "def", "sanity_check_fasta", "(", "handle", ")", ":", "header_found", "=", "False", "for", "line", "in", "handle", ":", "if", "line", ".", "startswith", "(", "'>'", ")", ":", "header_found", "=", "True", "break", "handle", ".", "seek", "(", "0", ")", "...
Sanity check FASTA files.
[ "Sanity", "check", "FASTA", "files", "." ]
3a732d62b4b3cc42675631db886ba534672cb134
https://github.com/kblin/bioinf-helperlibs/blob/3a732d62b4b3cc42675631db886ba534672cb134/helperlibs/bio/seqio.py#L163-L181
train
Sanity check FASTA files.
kblin/bioinf-helperlibs
helperlibs/bio/seqio.py
parse
def parse(handle, seqtype=None, robust=False): '''Wrap SeqIO.parse''' if seqtype is None: seqtype = _get_seqtype_from_ext(handle) if seqtype.startswith('gz-'): handle = _unzip_handle(handle) seqtype = seqtype[3:] # False positive from pylint, both handles are fileobj-like #...
python
def parse(handle, seqtype=None, robust=False): '''Wrap SeqIO.parse''' if seqtype is None: seqtype = _get_seqtype_from_ext(handle) if seqtype.startswith('gz-'): handle = _unzip_handle(handle) seqtype = seqtype[3:] # False positive from pylint, both handles are fileobj-like #...
[ "def", "parse", "(", "handle", ",", "seqtype", "=", "None", ",", "robust", "=", "False", ")", ":", "if", "seqtype", "is", "None", ":", "seqtype", "=", "_get_seqtype_from_ext", "(", "handle", ")", "if", "seqtype", ".", "startswith", "(", "'gz-'", ")", "...
Wrap SeqIO.parse
[ "Wrap", "SeqIO", ".", "parse" ]
3a732d62b4b3cc42675631db886ba534672cb134
https://github.com/kblin/bioinf-helperlibs/blob/3a732d62b4b3cc42675631db886ba534672cb134/helperlibs/bio/seqio.py#L184-L204
train
Wrap SeqIO. parse to handle and return a new object.
Nic30/hwtGraph
hwtGraph/elk/containers/constants.py
PortConstraints.isOrderFixed
def isOrderFixed(self): """ Returns whether the order of ports is fixed. @return true if the order of ports is fixed """ return (self == PortConstraints.FIXED_ORDER or self == PortConstraints.FIXED_RATIO or self == PortConstraints.FIXED_POS)
python
def isOrderFixed(self): """ Returns whether the order of ports is fixed. @return true if the order of ports is fixed """ return (self == PortConstraints.FIXED_ORDER or self == PortConstraints.FIXED_RATIO or self == PortConstraints.FIXED_POS)
[ "def", "isOrderFixed", "(", "self", ")", ":", "return", "(", "self", "==", "PortConstraints", ".", "FIXED_ORDER", "or", "self", "==", "PortConstraints", ".", "FIXED_RATIO", "or", "self", "==", "PortConstraints", ".", "FIXED_POS", ")" ]
Returns whether the order of ports is fixed. @return true if the order of ports is fixed
[ "Returns", "whether", "the", "order", "of", "ports", "is", "fixed", "." ]
6b7d4fdd759f263a0fdd2736f02f123e44e4354f
https://github.com/Nic30/hwtGraph/blob/6b7d4fdd759f263a0fdd2736f02f123e44e4354f/hwtGraph/elk/containers/constants.py#L98-L106
train
Returns whether the order of ports is fixed.
testedminds/sand
sand/graph.py
_dicts_to_columns
def _dicts_to_columns(dicts): """ Given a List of Dictionaries with uniform keys, returns a single Dictionary with keys holding a List of values matching the key in the original List. [{'name': 'Field Museum', 'location': 'Chicago'}, {'name': 'Epcot', 'location': 'Orlando'}] => {'name': ...
python
def _dicts_to_columns(dicts): """ Given a List of Dictionaries with uniform keys, returns a single Dictionary with keys holding a List of values matching the key in the original List. [{'name': 'Field Museum', 'location': 'Chicago'}, {'name': 'Epcot', 'location': 'Orlando'}] => {'name': ...
[ "def", "_dicts_to_columns", "(", "dicts", ")", ":", "keys", "=", "dicts", "[", "0", "]", ".", "keys", "(", ")", "result", "=", "dict", "(", "(", "k", ",", "[", "]", ")", "for", "k", "in", "keys", ")", "for", "d", "in", "dicts", ":", "for", "k...
Given a List of Dictionaries with uniform keys, returns a single Dictionary with keys holding a List of values matching the key in the original List. [{'name': 'Field Museum', 'location': 'Chicago'}, {'name': 'Epcot', 'location': 'Orlando'}] => {'name': ['Field Museum', 'Epcot'], 'location'...
[ "Given", "a", "List", "of", "Dictionaries", "with", "uniform", "keys", "returns", "a", "single", "Dictionary", "with", "keys", "holding", "a", "List", "of", "values", "matching", "the", "key", "in", "the", "original", "List", "." ]
234f0eedb0742920cdf26da9bc84bf3f863a2f02
https://github.com/testedminds/sand/blob/234f0eedb0742920cdf26da9bc84bf3f863a2f02/sand/graph.py#L25-L43
train
Given a list of dictionaries with uniform keys returns a single Dictionary with keys holding a List of values matching the key in the original List.
testedminds/sand
sand/graph.py
from_vertices_and_edges
def from_vertices_and_edges(vertices, edges, vertex_name_key='name', vertex_id_key='id', edge_foreign_keys=('source', 'target'), directed=True): """ This representation assumes that vertices and edges are encoded in two lists, each list containing a Python dict for each vertex an...
python
def from_vertices_and_edges(vertices, edges, vertex_name_key='name', vertex_id_key='id', edge_foreign_keys=('source', 'target'), directed=True): """ This representation assumes that vertices and edges are encoded in two lists, each list containing a Python dict for each vertex an...
[ "def", "from_vertices_and_edges", "(", "vertices", ",", "edges", ",", "vertex_name_key", "=", "'name'", ",", "vertex_id_key", "=", "'id'", ",", "edge_foreign_keys", "=", "(", "'source'", ",", "'target'", ")", ",", "directed", "=", "True", ")", ":", "vertex_dat...
This representation assumes that vertices and edges are encoded in two lists, each list containing a Python dict for each vertex and each edge, respectively. A distinguished element of the vertex dicts contain a vertex ID which is used in the edge dicts to refer to source and target vertices. All the re...
[ "This", "representation", "assumes", "that", "vertices", "and", "edges", "are", "encoded", "in", "two", "lists", "each", "list", "containing", "a", "Python", "dict", "for", "each", "vertex", "and", "each", "edge", "respectively", ".", "A", "distinguished", "el...
234f0eedb0742920cdf26da9bc84bf3f863a2f02
https://github.com/testedminds/sand/blob/234f0eedb0742920cdf26da9bc84bf3f863a2f02/sand/graph.py#L46-L84
train
Creates a new IGraph instance from a list of vertices and edges.
testedminds/sand
sand/graph.py
from_edges
def from_edges(edges, source_key='source', target_key='target', weight_key='weight', directed=True): """ Given a List of Dictionaries with source, target, and weight attributes, return a weighted, directed graph. """ raw = list(map(lambda x: [x[source_key], x[target_key], int(x[weight_key])], edges)) ...
python
def from_edges(edges, source_key='source', target_key='target', weight_key='weight', directed=True): """ Given a List of Dictionaries with source, target, and weight attributes, return a weighted, directed graph. """ raw = list(map(lambda x: [x[source_key], x[target_key], int(x[weight_key])], edges)) ...
[ "def", "from_edges", "(", "edges", ",", "source_key", "=", "'source'", ",", "target_key", "=", "'target'", ",", "weight_key", "=", "'weight'", ",", "directed", "=", "True", ")", ":", "raw", "=", "list", "(", "map", "(", "lambda", "x", ":", "[", "x", ...
Given a List of Dictionaries with source, target, and weight attributes, return a weighted, directed graph.
[ "Given", "a", "List", "of", "Dictionaries", "with", "source", "target", "and", "weight", "attributes", "return", "a", "weighted", "directed", "graph", "." ]
234f0eedb0742920cdf26da9bc84bf3f863a2f02
https://github.com/testedminds/sand/blob/234f0eedb0742920cdf26da9bc84bf3f863a2f02/sand/graph.py#L87-L98
train
Given a list of Dictionaries with source target and weight attributes return a weighted directed graph.
pgxcentre/geneparse
geneparse/utils.py
flip_alleles
def flip_alleles(genotypes): """Flip the alleles of an Genotypes instance.""" warnings.warn("deprecated: use 'Genotypes.flip_coded'", DeprecationWarning) genotypes.reference, genotypes.coded = (genotypes.coded, genotypes.reference) genotypes.genotypes = 2 - ge...
python
def flip_alleles(genotypes): """Flip the alleles of an Genotypes instance.""" warnings.warn("deprecated: use 'Genotypes.flip_coded'", DeprecationWarning) genotypes.reference, genotypes.coded = (genotypes.coded, genotypes.reference) genotypes.genotypes = 2 - ge...
[ "def", "flip_alleles", "(", "genotypes", ")", ":", "warnings", ".", "warn", "(", "\"deprecated: use 'Genotypes.flip_coded'\"", ",", "DeprecationWarning", ")", "genotypes", ".", "reference", ",", "genotypes", ".", "coded", "=", "(", "genotypes", ".", "coded", ",", ...
Flip the alleles of an Genotypes instance.
[ "Flip", "the", "alleles", "of", "an", "Genotypes", "instance", "." ]
f698f9708af4c7962d384a70a5a14006b1cb7108
https://github.com/pgxcentre/geneparse/blob/f698f9708af4c7962d384a70a5a14006b1cb7108/geneparse/utils.py#L45-L51
train
Flip the alleles of an Genotypes instance.