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
Genida/dependenpy
src/dependenpy/dsm.py
Package.build_tree
def build_tree(self): """Build the tree for this package.""" for m in listdir(self.path): abs_m = join(self.path, m) if isfile(abs_m) and m.endswith('.py'): name = splitext(m)[0] if not self.limit_to or name in self.limit_to: se...
python
def build_tree(self): """Build the tree for this package.""" for m in listdir(self.path): abs_m = join(self.path, m) if isfile(abs_m) and m.endswith('.py'): name = splitext(m)[0] if not self.limit_to or name in self.limit_to: se...
[ "def", "build_tree", "(", "self", ")", ":", "for", "m", "in", "listdir", "(", "self", ".", "path", ")", ":", "abs_m", "=", "join", "(", "self", ".", "path", ",", "m", ")", "if", "isfile", "(", "abs_m", ")", "and", "m", ".", "endswith", "(", "'....
Build the tree for this package.
[ "Build", "the", "tree", "for", "this", "package", "." ]
df099c17cbe735c990eca9197e39cfc5eb8a4c8e
https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/dsm.py#L189-L205
train
Build the tree for this package.
Genida/dependenpy
src/dependenpy/dsm.py
Package.cardinal
def cardinal(self, to): """ Return the number of dependencies of this package to the given node. Args: to (Package/Module): target node. Returns: int: number of dependencies. """ return sum(m.cardinal(to) for m in self.submodules)
python
def cardinal(self, to): """ Return the number of dependencies of this package to the given node. Args: to (Package/Module): target node. Returns: int: number of dependencies. """ return sum(m.cardinal(to) for m in self.submodules)
[ "def", "cardinal", "(", "self", ",", "to", ")", ":", "return", "sum", "(", "m", ".", "cardinal", "(", "to", ")", "for", "m", "in", "self", ".", "submodules", ")" ]
Return the number of dependencies of this package to the given node. Args: to (Package/Module): target node. Returns: int: number of dependencies.
[ "Return", "the", "number", "of", "dependencies", "of", "this", "package", "to", "the", "given", "node", "." ]
df099c17cbe735c990eca9197e39cfc5eb8a4c8e
https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/dsm.py#L207-L217
train
Returns the number of dependencies of this package to the given node.
Genida/dependenpy
src/dependenpy/dsm.py
Module.as_dict
def as_dict(self, absolute=False): """ Return the dependencies as a dictionary. Returns: dict: dictionary of dependencies. """ return { 'name': self.absolute_name() if absolute else self.name, 'path': self.path, 'dependencies': [{ ...
python
def as_dict(self, absolute=False): """ Return the dependencies as a dictionary. Returns: dict: dictionary of dependencies. """ return { 'name': self.absolute_name() if absolute else self.name, 'path': self.path, 'dependencies': [{ ...
[ "def", "as_dict", "(", "self", ",", "absolute", "=", "False", ")", ":", "return", "{", "'name'", ":", "self", ".", "absolute_name", "(", ")", "if", "absolute", "else", "self", ".", "name", ",", "'path'", ":", "self", ".", "path", ",", "'dependencies'",...
Return the dependencies as a dictionary. Returns: dict: dictionary of dependencies.
[ "Return", "the", "dependencies", "as", "a", "dictionary", "." ]
df099c17cbe735c990eca9197e39cfc5eb8a4c8e
https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/dsm.py#L271-L288
train
Return the dependencies as a dictionary.
Genida/dependenpy
src/dependenpy/dsm.py
Module.build_dependencies
def build_dependencies(self): """ Build the dependencies for this module. Parse the code with ast, find all the import statements, convert them into Dependency objects. """ highest = self.dsm or self.root if self is highest: highest = LeafNode() ...
python
def build_dependencies(self): """ Build the dependencies for this module. Parse the code with ast, find all the import statements, convert them into Dependency objects. """ highest = self.dsm or self.root if self is highest: highest = LeafNode() ...
[ "def", "build_dependencies", "(", "self", ")", ":", "highest", "=", "self", ".", "dsm", "or", "self", ".", "root", "if", "self", "is", "highest", ":", "highest", "=", "LeafNode", "(", ")", "for", "_import", "in", "self", ".", "parse_code", "(", ")", ...
Build the dependencies for this module. Parse the code with ast, find all the import statements, convert them into Dependency objects.
[ "Build", "the", "dependencies", "for", "this", "module", "." ]
df099c17cbe735c990eca9197e39cfc5eb8a4c8e
https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/dsm.py#L319-L336
train
Build the dependencies for this module.
Genida/dependenpy
src/dependenpy/dsm.py
Module.parse_code
def parse_code(self): """ Read the source code and return all the import statements. Returns: list of dict: the import statements. """ code = open(self.path, encoding='utf-8').read() try: body = ast.parse(code).body except SyntaxError: ...
python
def parse_code(self): """ Read the source code and return all the import statements. Returns: list of dict: the import statements. """ code = open(self.path, encoding='utf-8').read() try: body = ast.parse(code).body except SyntaxError: ...
[ "def", "parse_code", "(", "self", ")", ":", "code", "=", "open", "(", "self", ".", "path", ",", "encoding", "=", "'utf-8'", ")", ".", "read", "(", ")", "try", ":", "body", "=", "ast", ".", "parse", "(", "code", ")", ".", "body", "except", "Syntax...
Read the source code and return all the import statements. Returns: list of dict: the import statements.
[ "Read", "the", "source", "code", "and", "return", "all", "the", "import", "statements", "." ]
df099c17cbe735c990eca9197e39cfc5eb8a4c8e
https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/dsm.py#L338-L354
train
Read the source code and return all the import statements.
Genida/dependenpy
src/dependenpy/dsm.py
Module.get_imports
def get_imports(self, ast_body): """ Return all the import statements given an AST body (AST nodes). Args: ast_body (compiled code's body): the body to filter. Returns: list of dict: the import statements. """ imports = [] for node in ast...
python
def get_imports(self, ast_body): """ Return all the import statements given an AST body (AST nodes). Args: ast_body (compiled code's body): the body to filter. Returns: list of dict: the import statements. """ imports = [] for node in ast...
[ "def", "get_imports", "(", "self", ",", "ast_body", ")", ":", "imports", "=", "[", "]", "for", "node", "in", "ast_body", ":", "if", "isinstance", "(", "node", ",", "ast", ".", "Import", ")", ":", "imports", ".", "extend", "(", "{", "'target'", ":", ...
Return all the import statements given an AST body (AST nodes). Args: ast_body (compiled code's body): the body to filter. Returns: list of dict: the import statements.
[ "Return", "all", "the", "import", "statements", "given", "an", "AST", "body", "(", "AST", "nodes", ")", "." ]
df099c17cbe735c990eca9197e39cfc5eb8a4c8e
https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/dsm.py#L356-L384
train
Returns all the import statements given an AST body.
Genida/dependenpy
src/dependenpy/dsm.py
Module.cardinal
def cardinal(self, to): """ Return the number of dependencies of this module to the given node. Args: to (Package/Module): the target node. Returns: int: number of dependencies. """ return sum(1 for _ in filter( lambda d: not d.extern...
python
def cardinal(self, to): """ Return the number of dependencies of this module to the given node. Args: to (Package/Module): the target node. Returns: int: number of dependencies. """ return sum(1 for _ in filter( lambda d: not d.extern...
[ "def", "cardinal", "(", "self", ",", "to", ")", ":", "return", "sum", "(", "1", "for", "_", "in", "filter", "(", "lambda", "d", ":", "not", "d", ".", "external", "and", "d", ".", "target", "in", "to", ",", "self", ".", "dependencies", ")", ")" ]
Return the number of dependencies of this module to the given node. Args: to (Package/Module): the target node. Returns: int: number of dependencies.
[ "Return", "the", "number", "of", "dependencies", "of", "this", "module", "to", "the", "given", "node", "." ]
df099c17cbe735c990eca9197e39cfc5eb8a4c8e
https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/dsm.py#L386-L397
train
Returns the number of dependencies of this module to the given node.
romanorac/discomll
discomll/dataset.py
Data.generate_urls
def generate_urls(self, first_url, last_url): """ Function generates URLs in split command fashion. If first_url is xaaaaa and last_url is xaaaac, it will automatically generate xaaaab. """ first_url = first_url.split("/") last_url = last_url.split("/") if first_url[0].lo...
python
def generate_urls(self, first_url, last_url): """ Function generates URLs in split command fashion. If first_url is xaaaaa and last_url is xaaaac, it will automatically generate xaaaab. """ first_url = first_url.split("/") last_url = last_url.split("/") if first_url[0].lo...
[ "def", "generate_urls", "(", "self", ",", "first_url", ",", "last_url", ")", ":", "first_url", "=", "first_url", ".", "split", "(", "\"/\"", ")", "last_url", "=", "last_url", ".", "split", "(", "\"/\"", ")", "if", "first_url", "[", "0", "]", ".", "lowe...
Function generates URLs in split command fashion. If first_url is xaaaaa and last_url is xaaaac, it will automatically generate xaaaab.
[ "Function", "generates", "URLs", "in", "split", "command", "fashion", ".", "If", "first_url", "is", "xaaaaa", "and", "last_url", "is", "xaaaac", "it", "will", "automatically", "generate", "xaaaab", "." ]
a4703daffb2ba3c9f614bc3dbe45ae55884aea00
https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/dataset.py#L160-L194
train
Function generates URLs in split command fashion.
oemof/oemof.db
oemof/db/coastdat.py
get_weather
def get_weather(conn, geometry, year): r""" Get the weather data for the given geometry and create an oemof weather object. """ rename_dc = { 'ASWDIFD_S': 'dhi', 'ASWDIR_S': 'dirhi', 'PS': 'pressure', 'T_2M': 'temp_air', 'WSS_10M': 'v_wind', 'Z0': 'z0'...
python
def get_weather(conn, geometry, year): r""" Get the weather data for the given geometry and create an oemof weather object. """ rename_dc = { 'ASWDIFD_S': 'dhi', 'ASWDIR_S': 'dirhi', 'PS': 'pressure', 'T_2M': 'temp_air', 'WSS_10M': 'v_wind', 'Z0': 'z0'...
[ "def", "get_weather", "(", "conn", ",", "geometry", ",", "year", ")", ":", "rename_dc", "=", "{", "'ASWDIFD_S'", ":", "'dhi'", ",", "'ASWDIR_S'", ":", "'dirhi'", ",", "'PS'", ":", "'pressure'", ",", "'T_2M'", ":", "'temp_air'", ",", "'WSS_10M'", ":", "'v...
r""" Get the weather data for the given geometry and create an oemof weather object.
[ "r", "Get", "the", "weather", "data", "for", "the", "given", "geometry", "and", "create", "an", "oemof", "weather", "object", "." ]
d51ac50187f03a875bd7ce5991ed4772e8b77b93
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/coastdat.py#L14-L51
train
r Get the weather data for the given geometry and create an oemof object.
oemof/oemof.db
oemof/db/coastdat.py
fetch_raw_data
def fetch_raw_data(sql, connection, geometry): """ Fetch the coastdat2 from the database, adapt it to the local time zone and create a time index. """ tmp_dc = {} weather_df = pd.DataFrame( connection.execute(sql).fetchall(), columns=[ 'gid', 'geom_point', 'geom_polygon', 'da...
python
def fetch_raw_data(sql, connection, geometry): """ Fetch the coastdat2 from the database, adapt it to the local time zone and create a time index. """ tmp_dc = {} weather_df = pd.DataFrame( connection.execute(sql).fetchall(), columns=[ 'gid', 'geom_point', 'geom_polygon', 'da...
[ "def", "fetch_raw_data", "(", "sql", ",", "connection", ",", "geometry", ")", ":", "tmp_dc", "=", "{", "}", "weather_df", "=", "pd", ".", "DataFrame", "(", "connection", ".", "execute", "(", "sql", ")", ".", "fetchall", "(", ")", ",", "columns", "=", ...
Fetch the coastdat2 from the database, adapt it to the local time zone and create a time index.
[ "Fetch", "the", "coastdat2", "from", "the", "database", "adapt", "it", "to", "the", "local", "time", "zone", "and", "create", "a", "time", "index", "." ]
d51ac50187f03a875bd7ce5991ed4772e8b77b93
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/coastdat.py#L92-L128
train
Fetch the coastdat2 from the database adapt it to the local time zone and create a time index.
oemof/oemof.db
oemof/db/coastdat.py
create_single_weather
def create_single_weather(df, rename_dc): """Create an oemof weather object for the given geometry""" my_weather = weather.FeedinWeather() data_height = {} name = None # Create a pandas.DataFrame with the time series of the weather data set weather_df = pd.DataFrame(index=df.time_series.iloc[0]....
python
def create_single_weather(df, rename_dc): """Create an oemof weather object for the given geometry""" my_weather = weather.FeedinWeather() data_height = {} name = None # Create a pandas.DataFrame with the time series of the weather data set weather_df = pd.DataFrame(index=df.time_series.iloc[0]....
[ "def", "create_single_weather", "(", "df", ",", "rename_dc", ")", ":", "my_weather", "=", "weather", ".", "FeedinWeather", "(", ")", "data_height", "=", "{", "}", "name", "=", "None", "# Create a pandas.DataFrame with the time series of the weather data set", "weather_d...
Create an oemof weather object for the given geometry
[ "Create", "an", "oemof", "weather", "object", "for", "the", "given", "geometry" ]
d51ac50187f03a875bd7ce5991ed4772e8b77b93
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/coastdat.py#L131-L150
train
Create an oemof weather object for the given geometry
oemof/oemof.db
oemof/db/coastdat.py
create_multi_weather
def create_multi_weather(df, rename_dc): """Create a list of oemof weather objects if the given geometry is a polygon """ weather_list = [] # Create a pandas.DataFrame with the time series of the weather data set # for each data set and append them to a list. for gid in df.gid.unique(): ...
python
def create_multi_weather(df, rename_dc): """Create a list of oemof weather objects if the given geometry is a polygon """ weather_list = [] # Create a pandas.DataFrame with the time series of the weather data set # for each data set and append them to a list. for gid in df.gid.unique(): ...
[ "def", "create_multi_weather", "(", "df", ",", "rename_dc", ")", ":", "weather_list", "=", "[", "]", "# Create a pandas.DataFrame with the time series of the weather data set", "# for each data set and append them to a list.", "for", "gid", "in", "df", ".", "gid", ".", "uni...
Create a list of oemof weather objects if the given geometry is a polygon
[ "Create", "a", "list", "of", "oemof", "weather", "objects", "if", "the", "given", "geometry", "is", "a", "polygon" ]
d51ac50187f03a875bd7ce5991ed4772e8b77b93
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/coastdat.py#L153-L163
train
Create a list of oemof weather objects if the given geometry is a polygon
djaodjin/djaodjin-deployutils
deployutils/crypt.py
_openssl_key_iv
def _openssl_key_iv(passphrase, salt): """ Returns a (key, iv) tuple that can be used in AES symmetric encryption from a *passphrase* (a byte or unicode string) and *salt* (a byte array). """ def _openssl_kdf(req): if hasattr(passphrase, 'encode'): passwd = passphrase.encode('asc...
python
def _openssl_key_iv(passphrase, salt): """ Returns a (key, iv) tuple that can be used in AES symmetric encryption from a *passphrase* (a byte or unicode string) and *salt* (a byte array). """ def _openssl_kdf(req): if hasattr(passphrase, 'encode'): passwd = passphrase.encode('asc...
[ "def", "_openssl_key_iv", "(", "passphrase", ",", "salt", ")", ":", "def", "_openssl_kdf", "(", "req", ")", ":", "if", "hasattr", "(", "passphrase", ",", "'encode'", ")", ":", "passwd", "=", "passphrase", ".", "encode", "(", "'ascii'", ",", "'ignore'", "...
Returns a (key, iv) tuple that can be used in AES symmetric encryption from a *passphrase* (a byte or unicode string) and *salt* (a byte array).
[ "Returns", "a", "(", "key", "iv", ")", "tuple", "that", "can", "be", "used", "in", "AES", "symmetric", "encryption", "from", "a", "*", "passphrase", "*", "(", "a", "byte", "or", "unicode", "string", ")", "and", "*", "salt", "*", "(", "a", "byte", "...
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/crypt.py#L80-L101
train
Generate a key and IV tuple from a passphrase and a salt.
djaodjin/djaodjin-deployutils
deployutils/crypt.py
decrypt
def decrypt(source_text, passphrase, debug_stmt=None): """ Returns plain text from *source_text*, a base64 AES encrypted string as generated with openssl. $ echo '_source_text_' | openssl aes-256-cbc -a -k _passphrase_ -p salt=... key=... iv=... _full_encrypted_ ...
python
def decrypt(source_text, passphrase, debug_stmt=None): """ Returns plain text from *source_text*, a base64 AES encrypted string as generated with openssl. $ echo '_source_text_' | openssl aes-256-cbc -a -k _passphrase_ -p salt=... key=... iv=... _full_encrypted_ ...
[ "def", "decrypt", "(", "source_text", ",", "passphrase", ",", "debug_stmt", "=", "None", ")", ":", "if", "debug_stmt", "is", "None", ":", "debug_stmt", "=", "\"decrypt\"", "full_encrypted", "=", "b64decode", "(", "source_text", ")", "salt", "=", "full_encrypte...
Returns plain text from *source_text*, a base64 AES encrypted string as generated with openssl. $ echo '_source_text_' | openssl aes-256-cbc -a -k _passphrase_ -p salt=... key=... iv=... _full_encrypted_
[ "Returns", "plain", "text", "from", "*", "source_text", "*", "a", "base64", "AES", "encrypted", "string", "as", "generated", "with", "openssl", "." ]
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/crypt.py#L104-L136
train
Decrypt a base64 - encoded string of source_text using the given passphrase.
djaodjin/djaodjin-deployutils
deployutils/crypt.py
encrypt
def encrypt(source_text, passphrase, debug_stmt=None): """ Returns *source_text* as a base64 AES encrypted string. The full encrypted text is special crafted to be compatible with openssl. It can be decrypted with: $ echo _full_encypted_ | openssl aes-256-cbc -d -a -k _passphrase_ -p s...
python
def encrypt(source_text, passphrase, debug_stmt=None): """ Returns *source_text* as a base64 AES encrypted string. The full encrypted text is special crafted to be compatible with openssl. It can be decrypted with: $ echo _full_encypted_ | openssl aes-256-cbc -d -a -k _passphrase_ -p s...
[ "def", "encrypt", "(", "source_text", ",", "passphrase", ",", "debug_stmt", "=", "None", ")", ":", "if", "debug_stmt", "is", "None", ":", "debug_stmt", "=", "\"encrypt\"", "prefix", "=", "b'Salted__'", "salt", "=", "os", ".", "urandom", "(", "IV_BLOCK_SIZE",...
Returns *source_text* as a base64 AES encrypted string. The full encrypted text is special crafted to be compatible with openssl. It can be decrypted with: $ echo _full_encypted_ | openssl aes-256-cbc -d -a -k _passphrase_ -p salt=... key=... iv=... _source_text_
[ "Returns", "*", "source_text", "*", "as", "a", "base64", "AES", "encrypted", "string", "." ]
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/crypt.py#L139-L176
train
Encrypt a string of source_text with a passphrase.
romanorac/discomll
discomll/ensemble/core/decision_tree.py
rand_indices
def rand_indices(x, rand_attr): """ Function randomly selects features without replacement. It used with random forest. Selected features must have more than one distinct value. x: numpy array - dataset rand_attr - parameter defines number of randomly selected features """ loop = True in...
python
def rand_indices(x, rand_attr): """ Function randomly selects features without replacement. It used with random forest. Selected features must have more than one distinct value. x: numpy array - dataset rand_attr - parameter defines number of randomly selected features """ loop = True in...
[ "def", "rand_indices", "(", "x", ",", "rand_attr", ")", ":", "loop", "=", "True", "indices", "=", "range", "(", "len", "(", "x", "[", "0", "]", ")", ")", "while", "loop", ":", "loop", "=", "False", "# randomly selected features without replacement", "rand_...
Function randomly selects features without replacement. It used with random forest. Selected features must have more than one distinct value. x: numpy array - dataset rand_attr - parameter defines number of randomly selected features
[ "Function", "randomly", "selects", "features", "without", "replacement", ".", "It", "used", "with", "random", "forest", ".", "Selected", "features", "must", "have", "more", "than", "one", "distinct", "value", ".", "x", ":", "numpy", "array", "-", "dataset", ...
a4703daffb2ba3c9f614bc3dbe45ae55884aea00
https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/ensemble/core/decision_tree.py#L17-L38
train
Function randomly selects features without replacement. It used with random forest.
romanorac/discomll
discomll/ensemble/core/decision_tree.py
fit
def fit(x, y, t, randomized, max_tree_nodes, min_samples_leaf, min_samples_split, class_majority, measure, accuracy, separate_max): """ Function builds a binary decision tree with given dataset and it expand tree nodes in priority order. Tree model is stored in a dictionary and it has following stru...
python
def fit(x, y, t, randomized, max_tree_nodes, min_samples_leaf, min_samples_split, class_majority, measure, accuracy, separate_max): """ Function builds a binary decision tree with given dataset and it expand tree nodes in priority order. Tree model is stored in a dictionary and it has following stru...
[ "def", "fit", "(", "x", ",", "y", ",", "t", ",", "randomized", ",", "max_tree_nodes", ",", "min_samples_leaf", ",", "min_samples_split", ",", "class_majority", ",", "measure", ",", "accuracy", ",", "separate_max", ")", ":", "depth", "=", "0", "# depth of the...
Function builds a binary decision tree with given dataset and it expand tree nodes in priority order. Tree model is stored in a dictionary and it has following structure: {parent_identifier: [(child_identifier, highest_estimated_feature_index , split_value, distribution_of_labels, depth, feature_type)]} ...
[ "Function", "builds", "a", "binary", "decision", "tree", "with", "given", "dataset", "and", "it", "expand", "tree", "nodes", "in", "priority", "order", ".", "Tree", "model", "is", "stored", "in", "a", "dictionary", "and", "it", "has", "following", "structure...
a4703daffb2ba3c9f614bc3dbe45ae55884aea00
https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/ensemble/core/decision_tree.py#L41-L139
train
Function builds a binary decision tree with given dataset and it expands tree nodes in priority order.
romanorac/discomll
discomll/ensemble/core/decision_tree.py
predict
def predict(tree, x, y=[], dist=False): """ Function makes a prediction of one sample with a tree model. If y label is defined it returns node identifier and margin. tree: dictionary - tree model x: numpy array - one sample from the dataset y: string, integer or float - sample label """ # ...
python
def predict(tree, x, y=[], dist=False): """ Function makes a prediction of one sample with a tree model. If y label is defined it returns node identifier and margin. tree: dictionary - tree model x: numpy array - one sample from the dataset y: string, integer or float - sample label """ # ...
[ "def", "predict", "(", "tree", ",", "x", ",", "y", "=", "[", "]", ",", "dist", "=", "False", ")", ":", "# conditions of continuous and discrete features", "node_id", "=", "1", "# initialize node identifier as first node under the root", "while", "1", ":", "nodes", ...
Function makes a prediction of one sample with a tree model. If y label is defined it returns node identifier and margin. tree: dictionary - tree model x: numpy array - one sample from the dataset y: string, integer or float - sample label
[ "Function", "makes", "a", "prediction", "of", "one", "sample", "with", "a", "tree", "model", ".", "If", "y", "label", "is", "defined", "it", "returns", "node", "identifier", "and", "margin", "." ]
a4703daffb2ba3c9f614bc3dbe45ae55884aea00
https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/ensemble/core/decision_tree.py#L142-L193
train
Function makes a prediction of one sample with a tree model. If y is not defined it returns node identifier and margin.
mgoral/subconvert
src/subconvert/gui/SubtitleCommands.py
SubtitleChangeCommand.setup
def setup(self): """When subclassing remember to call SubtitleChangeCommand::setup() to perform generic checks.""" if not isinstance(self.filePath, str): raise TypeError("File path is not a string!") if self.controller is None: raise ValueError("Command controller...
python
def setup(self): """When subclassing remember to call SubtitleChangeCommand::setup() to perform generic checks.""" if not isinstance(self.filePath, str): raise TypeError("File path is not a string!") if self.controller is None: raise ValueError("Command controller...
[ "def", "setup", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "filePath", ",", "str", ")", ":", "raise", "TypeError", "(", "\"File path is not a string!\"", ")", "if", "self", ".", "controller", "is", "None", ":", "raise", "ValueError...
When subclassing remember to call SubtitleChangeCommand::setup() to perform generic checks.
[ "When", "subclassing", "remember", "to", "call", "SubtitleChangeCommand", "::", "setup", "()", "to", "perform", "generic", "checks", "." ]
59701e5e69ef1ca26ce7d1d766c936664aa2cb32
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/gui/SubtitleCommands.py#L60-L66
train
When subclassing remember to call generic checks.
mgoral/subconvert
src/subconvert/gui/SubtitleWindow.py
SubTabWidget.__addTab
def __addTab(self, filePath): """Returns existing tab index. Creates a new one if it isn't opened and returns its index otherwise.""" for i in range(self.tabBar.count()): widget = self.pages.widget(i) if not widget.isStatic and filePath == widget.filePath: ...
python
def __addTab(self, filePath): """Returns existing tab index. Creates a new one if it isn't opened and returns its index otherwise.""" for i in range(self.tabBar.count()): widget = self.pages.widget(i) if not widget.isStatic and filePath == widget.filePath: ...
[ "def", "__addTab", "(", "self", ",", "filePath", ")", ":", "for", "i", "in", "range", "(", "self", ".", "tabBar", ".", "count", "(", ")", ")", ":", "widget", "=", "self", ".", "pages", ".", "widget", "(", "i", ")", "if", "not", "widget", ".", "...
Returns existing tab index. Creates a new one if it isn't opened and returns its index otherwise.
[ "Returns", "existing", "tab", "index", ".", "Creates", "a", "new", "one", "if", "it", "isn", "t", "opened", "and", "returns", "its", "index", "otherwise", "." ]
59701e5e69ef1ca26ce7d1d766c936664aa2cb32
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/gui/SubtitleWindow.py#L119-L131
train
Creates a new tab index. Creates a new one if it isn t opened and returns its index otherwise.
iLampard/x-utils
xutils/config_utils.py
merge_configs
def merge_configs(to_be_merged, default): """Merges two configuration dictionaries by overwriting values with same keys, with the priority on values given on the 'left' side, so the to_be_merged dict. Notice that with lists in the configuration, it skips from the default (right side) the tuples in t...
python
def merge_configs(to_be_merged, default): """Merges two configuration dictionaries by overwriting values with same keys, with the priority on values given on the 'left' side, so the to_be_merged dict. Notice that with lists in the configuration, it skips from the default (right side) the tuples in t...
[ "def", "merge_configs", "(", "to_be_merged", ",", "default", ")", ":", "if", "isinstance", "(", "to_be_merged", ",", "dict", ")", "and", "isinstance", "(", "default", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "default", ".", "items", "(", ")",...
Merges two configuration dictionaries by overwriting values with same keys, with the priority on values given on the 'left' side, so the to_be_merged dict. Notice that with lists in the configuration, it skips from the default (right side) the tuples in that which already exist in the left side to_b...
[ "Merges", "two", "configuration", "dictionaries", "by", "overwriting", "values", "with", "same", "keys", "with", "the", "priority", "on", "values", "given", "on", "the", "left", "side", "so", "the", "to_be_merged", "dict", ".", "Notice", "that", "with", "lists...
291d92832ee0e0c89bc22e10ecf2f44445e0d300
https://github.com/iLampard/x-utils/blob/291d92832ee0e0c89bc22e10ecf2f44445e0d300/xutils/config_utils.py#L38-L73
train
Merges two configuration dictionaries by overwriting values with the priority on values given on the left side of the database.
iLampard/x-utils
xutils/config_utils.py
find_and_parse_config
def find_and_parse_config(config, default_config='default.yaml'): """Finds the service configuration file and parses it. Checks also a directory called default, to check for default configuration values, that will be overwritten by the actual configuration found on given path. """ def load_config(p...
python
def find_and_parse_config(config, default_config='default.yaml'): """Finds the service configuration file and parses it. Checks also a directory called default, to check for default configuration values, that will be overwritten by the actual configuration found on given path. """ def load_config(p...
[ "def", "find_and_parse_config", "(", "config", ",", "default_config", "=", "'default.yaml'", ")", ":", "def", "load_config", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ...
Finds the service configuration file and parses it. Checks also a directory called default, to check for default configuration values, that will be overwritten by the actual configuration found on given path.
[ "Finds", "the", "service", "configuration", "file", "and", "parses", "it", ".", "Checks", "also", "a", "directory", "called", "default", "to", "check", "for", "default", "configuration", "values", "that", "will", "be", "overwritten", "by", "the", "actual", "co...
291d92832ee0e0c89bc22e10ecf2f44445e0d300
https://github.com/iLampard/x-utils/blob/291d92832ee0e0c89bc22e10ecf2f44445e0d300/xutils/config_utils.py#L76-L101
train
Finds the service configuration file and parses it.
mgoral/subconvert
src/subconvert/cli/syncparse.py
parse
def parse(s, subs): """Parses a given string and creates a list of SyncPoints.""" if len(subs) == 0: return [] points = [] requests = _tokenize_request(s) if len(requests) == 1 and requests[0].type_ == _Request.Type.OFFSET: return _offset_subtitles(requests[0], subs) return _sy...
python
def parse(s, subs): """Parses a given string and creates a list of SyncPoints.""" if len(subs) == 0: return [] points = [] requests = _tokenize_request(s) if len(requests) == 1 and requests[0].type_ == _Request.Type.OFFSET: return _offset_subtitles(requests[0], subs) return _sy...
[ "def", "parse", "(", "s", ",", "subs", ")", ":", "if", "len", "(", "subs", ")", "==", "0", ":", "return", "[", "]", "points", "=", "[", "]", "requests", "=", "_tokenize_request", "(", "s", ")", "if", "len", "(", "requests", ")", "==", "1", "and...
Parses a given string and creates a list of SyncPoints.
[ "Parses", "a", "given", "string", "and", "creates", "a", "list", "of", "SyncPoints", "." ]
59701e5e69ef1ca26ce7d1d766c936664aa2cb32
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/cli/syncparse.py#L172-L182
train
Parses a given string and creates a list of SyncPoints.
djaodjin/djaodjin-deployutils
deployutils/helpers.py
full_name_natural_split
def full_name_natural_split(full_name): """ This function splits a full name into a natural first name, last name and middle initials. """ parts = full_name.strip().split(' ') first_name = "" if parts: first_name = parts.pop(0) if first_name.lower() == "el" and parts: fir...
python
def full_name_natural_split(full_name): """ This function splits a full name into a natural first name, last name and middle initials. """ parts = full_name.strip().split(' ') first_name = "" if parts: first_name = parts.pop(0) if first_name.lower() == "el" and parts: fir...
[ "def", "full_name_natural_split", "(", "full_name", ")", ":", "parts", "=", "full_name", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", "first_name", "=", "\"\"", "if", "parts", ":", "first_name", "=", "parts", ".", "pop", "(", "0", ")", "if", ...
This function splits a full name into a natural first name, last name and middle initials.
[ "This", "function", "splits", "a", "full", "name", "into", "a", "natural", "first", "name", "last", "name", "and", "middle", "initials", "." ]
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/helpers.py#L45-L66
train
This function splits a full name into a natural first name last name and middle initials.
djaodjin/djaodjin-deployutils
deployutils/helpers.py
start_of_day
def start_of_day(dtime_at=None): """ Returns the local (user timezone) start of day, that's, time 00:00:00 for a given datetime """ dtime_at = datetime_or_now(dtime_at) return datetime.datetime(dtime_at.year, dtime_at.month, dtime_at.day, tzinfo=tzlocal())
python
def start_of_day(dtime_at=None): """ Returns the local (user timezone) start of day, that's, time 00:00:00 for a given datetime """ dtime_at = datetime_or_now(dtime_at) return datetime.datetime(dtime_at.year, dtime_at.month, dtime_at.day, tzinfo=tzlocal())
[ "def", "start_of_day", "(", "dtime_at", "=", "None", ")", ":", "dtime_at", "=", "datetime_or_now", "(", "dtime_at", ")", "return", "datetime", ".", "datetime", "(", "dtime_at", ".", "year", ",", "dtime_at", ".", "month", ",", "dtime_at", ".", "day", ",", ...
Returns the local (user timezone) start of day, that's, time 00:00:00 for a given datetime
[ "Returns", "the", "local", "(", "user", "timezone", ")", "start", "of", "day", "that", "s", "time", "00", ":", "00", ":", "00", "for", "a", "given", "datetime" ]
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/helpers.py#L69-L76
train
Returns the local time that s the user s start of day for a given datetime
pneff/wsgiservice
wsgiservice/xmlserializer.py
dumps
def dumps(obj, root_tag): """Serialize :arg:`obj` to an XML :class:`str`. """ xml = _get_xml_value(obj) if xml: # Remove invalid XML xml = RE_ILLEGAL_XML.sub('', xml) if root_tag is None: return xml else: root = root_tag return '<' + root + '>' + xml + '</...
python
def dumps(obj, root_tag): """Serialize :arg:`obj` to an XML :class:`str`. """ xml = _get_xml_value(obj) if xml: # Remove invalid XML xml = RE_ILLEGAL_XML.sub('', xml) if root_tag is None: return xml else: root = root_tag return '<' + root + '>' + xml + '</...
[ "def", "dumps", "(", "obj", ",", "root_tag", ")", ":", "xml", "=", "_get_xml_value", "(", "obj", ")", "if", "xml", ":", "# Remove invalid XML", "xml", "=", "RE_ILLEGAL_XML", ".", "sub", "(", "''", ",", "xml", ")", "if", "root_tag", "is", "None", ":", ...
Serialize :arg:`obj` to an XML :class:`str`.
[ "Serialize", ":", "arg", ":", "obj", "to", "an", "XML", ":", "class", ":", "str", "." ]
03c064ac2e8c53a1aac9c7b99970f23cf79e20f4
https://github.com/pneff/wsgiservice/blob/03c064ac2e8c53a1aac9c7b99970f23cf79e20f4/wsgiservice/xmlserializer.py#L16-L27
train
Serialize obj to an XML.
pneff/wsgiservice
wsgiservice/xmlserializer.py
_get_xml_value
def _get_xml_value(value): """Convert an individual value to an XML string. Calls itself recursively for dictionaries and lists. Uses some heuristics to convert the data to XML: - In dictionaries, the keys become the tag name. - In lists the tag name is 'child' with an order-attribute givin...
python
def _get_xml_value(value): """Convert an individual value to an XML string. Calls itself recursively for dictionaries and lists. Uses some heuristics to convert the data to XML: - In dictionaries, the keys become the tag name. - In lists the tag name is 'child' with an order-attribute givin...
[ "def", "_get_xml_value", "(", "value", ")", ":", "retval", "=", "[", "]", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "for", "key", ",", "value", "in", "value", ".", "iteritems", "(", ")", ":", "retval", ".", "append", "(", "'<'", "+",...
Convert an individual value to an XML string. Calls itself recursively for dictionaries and lists. Uses some heuristics to convert the data to XML: - In dictionaries, the keys become the tag name. - In lists the tag name is 'child' with an order-attribute giving the list index. ...
[ "Convert", "an", "individual", "value", "to", "an", "XML", "string", ".", "Calls", "itself", "recursively", "for", "dictionaries", "and", "lists", "." ]
03c064ac2e8c53a1aac9c7b99970f23cf79e20f4
https://github.com/pneff/wsgiservice/blob/03c064ac2e8c53a1aac9c7b99970f23cf79e20f4/wsgiservice/xmlserializer.py#L30-L63
train
Convert an individual value to an XML string.
djaodjin/djaodjin-deployutils
deployutils/apps/django/management/commands/pullapp.py
fetch_changes
def fetch_changes(repo_path, up_commit='master'): """ Fetch latest changes from stage and touch .timestamp if any python sources have been modified. """ last_up_commit = None prevcwd = os.getcwd() try: gitexe = 'git' os.chdir(repo_path) old_sources_timestamp = sources...
python
def fetch_changes(repo_path, up_commit='master'): """ Fetch latest changes from stage and touch .timestamp if any python sources have been modified. """ last_up_commit = None prevcwd = os.getcwd() try: gitexe = 'git' os.chdir(repo_path) old_sources_timestamp = sources...
[ "def", "fetch_changes", "(", "repo_path", ",", "up_commit", "=", "'master'", ")", ":", "last_up_commit", "=", "None", "prevcwd", "=", "os", ".", "getcwd", "(", ")", "try", ":", "gitexe", "=", "'git'", "os", ".", "chdir", "(", "repo_path", ")", "old_sourc...
Fetch latest changes from stage and touch .timestamp if any python sources have been modified.
[ "Fetch", "latest", "changes", "from", "stage", "and", "touch", ".", "timestamp", "if", "any", "python", "sources", "have", "been", "modified", "." ]
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/apps/django/management/commands/pullapp.py#L114-L135
train
Fetch latest changes from stage and touch. timestamp if any python sources have been modified.
djaodjin/djaodjin-deployutils
deployutils/apps/django/management/commands/pullapp.py
migrate_all
def migrate_all(): """ Create schema migrations for all apps specified in INSTALLED_APPS, then run a migrate command. """ if 'south' in settings.INSTALLED_APPS: return _south_migrate_all() from django.core.management.commands import makemigrations, migrate schema_args = [sys.executab...
python
def migrate_all(): """ Create schema migrations for all apps specified in INSTALLED_APPS, then run a migrate command. """ if 'south' in settings.INSTALLED_APPS: return _south_migrate_all() from django.core.management.commands import makemigrations, migrate schema_args = [sys.executab...
[ "def", "migrate_all", "(", ")", ":", "if", "'south'", "in", "settings", ".", "INSTALLED_APPS", ":", "return", "_south_migrate_all", "(", ")", "from", "django", ".", "core", ".", "management", ".", "commands", "import", "makemigrations", ",", "migrate", "schema...
Create schema migrations for all apps specified in INSTALLED_APPS, then run a migrate command.
[ "Create", "schema", "migrations", "for", "all", "apps", "specified", "in", "INSTALLED_APPS", "then", "run", "a", "migrate", "command", "." ]
a0fe3cf3030dbbf09025c69ce75a69b326565dd8
https://github.com/djaodjin/djaodjin-deployutils/blob/a0fe3cf3030dbbf09025c69ce75a69b326565dd8/deployutils/apps/django/management/commands/pullapp.py#L200-L217
train
Create schema migrations for all apps specified in INSTALLED_APPS then run a migrate command.
carta/ldap_tools
src/ldap_tools/key.py
API.add
def add(self, username, user_api, filename=None): """ Add SSH public key to a user's profile. Args: username: Username to attach SSH public key to filename: Filename containing keys to add (optional) Raises: ldap3.core.exceptions.LDAPNoSuchAttributeR...
python
def add(self, username, user_api, filename=None): """ Add SSH public key to a user's profile. Args: username: Username to attach SSH public key to filename: Filename containing keys to add (optional) Raises: ldap3.core.exceptions.LDAPNoSuchAttributeR...
[ "def", "add", "(", "self", ",", "username", ",", "user_api", ",", "filename", "=", "None", ")", ":", "keys", "=", "API", ".", "__get_keys", "(", "filename", ")", "user", "=", "user_api", ".", "find", "(", "username", ")", "[", "0", "]", "distinguishe...
Add SSH public key to a user's profile. Args: username: Username to attach SSH public key to filename: Filename containing keys to add (optional) Raises: ldap3.core.exceptions.LDAPNoSuchAttributeResult: ldapPublicKey isn't attached to objectClass
[ "Add", "SSH", "public", "key", "to", "a", "user", "s", "profile", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/key.py#L22-L51
train
Adds an SSH public key to a user s profile.
carta/ldap_tools
src/ldap_tools/key.py
API.remove
def remove(self, username, user_api, filename=None, force=False): """Remove specified SSH public key from specified user.""" self.keys = API.__get_keys(filename) self.username = username user = user_api.find(username)[0] if not force: # pragma: no cover self.__confi...
python
def remove(self, username, user_api, filename=None, force=False): """Remove specified SSH public key from specified user.""" self.keys = API.__get_keys(filename) self.username = username user = user_api.find(username)[0] if not force: # pragma: no cover self.__confi...
[ "def", "remove", "(", "self", ",", "username", ",", "user_api", ",", "filename", "=", "None", ",", "force", "=", "False", ")", ":", "self", ".", "keys", "=", "API", ".", "__get_keys", "(", "filename", ")", "self", ".", "username", "=", "username", "u...
Remove specified SSH public key from specified user.
[ "Remove", "specified", "SSH", "public", "key", "from", "specified", "user", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/key.py#L53-L64
train
Remove specified SSH public key from specified user.
carta/ldap_tools
src/ldap_tools/key.py
API.install
def install(self): # pragma: no cover """Install/download ssh keys from LDAP for consumption by SSH.""" keys = self.get_keys_from_ldap() for user, ssh_keys in keys.items(): user_dir = API.__authorized_keys_path(user) if not os.path.isdir(user_dir): os.mak...
python
def install(self): # pragma: no cover """Install/download ssh keys from LDAP for consumption by SSH.""" keys = self.get_keys_from_ldap() for user, ssh_keys in keys.items(): user_dir = API.__authorized_keys_path(user) if not os.path.isdir(user_dir): os.mak...
[ "def", "install", "(", "self", ")", ":", "# pragma: no cover", "keys", "=", "self", ".", "get_keys_from_ldap", "(", ")", "for", "user", ",", "ssh_keys", "in", "keys", ".", "items", "(", ")", ":", "user_dir", "=", "API", ".", "__authorized_keys_path", "(", ...
Install/download ssh keys from LDAP for consumption by SSH.
[ "Install", "/", "download", "ssh", "keys", "from", "LDAP", "for", "consumption", "by", "SSH", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/key.py#L66-L75
train
Installs SSH keys from LDAP for consumption by SSH.
carta/ldap_tools
src/ldap_tools/key.py
API.get_keys_from_ldap
def get_keys_from_ldap(self, username=None): """ Fetch keys from ldap. Args: username Username associated with keys to fetch (optional) Returns: Array of dictionaries in '{username: [public keys]}' format """ result_dict = {} filter = ['...
python
def get_keys_from_ldap(self, username=None): """ Fetch keys from ldap. Args: username Username associated with keys to fetch (optional) Returns: Array of dictionaries in '{username: [public keys]}' format """ result_dict = {} filter = ['...
[ "def", "get_keys_from_ldap", "(", "self", ",", "username", "=", "None", ")", ":", "result_dict", "=", "{", "}", "filter", "=", "[", "'(sshPublicKey=*)'", "]", "if", "username", "is", "not", "None", ":", "filter", ".", "append", "(", "'(uid={})'", ".", "f...
Fetch keys from ldap. Args: username Username associated with keys to fetch (optional) Returns: Array of dictionaries in '{username: [public keys]}' format
[ "Fetch", "keys", "from", "ldap", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/key.py#L77-L96
train
Fetch keys from ldap.
carta/ldap_tools
src/ldap_tools/key.py
CLI.add
def add(config, username, filename): """Add user's SSH public key to their LDAP entry.""" try: client = Client() client.prepare_connection() user_api = UserApi(client) key_api = API(client) key_api.add(username, user_api, filename) exce...
python
def add(config, username, filename): """Add user's SSH public key to their LDAP entry.""" try: client = Client() client.prepare_connection() user_api = UserApi(client) key_api = API(client) key_api.add(username, user_api, filename) exce...
[ "def", "add", "(", "config", ",", "username", ",", "filename", ")", ":", "try", ":", "client", "=", "Client", "(", ")", "client", ".", "prepare_connection", "(", ")", "user_api", "=", "UserApi", "(", "client", ")", "key_api", "=", "API", "(", "client",...
Add user's SSH public key to their LDAP entry.
[ "Add", "user", "s", "SSH", "public", "key", "to", "their", "LDAP", "entry", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/key.py#L170-L184
train
Add user s SSH public key to their LDAP entry.
carta/ldap_tools
src/ldap_tools/key.py
CLI.remove
def remove(config, username, filename, force): """Remove user's SSH public key from their LDAP entry.""" client = Client() client.prepare_connection() user_api = UserApi(client) key_api = API(client) key_api.remove(username, user_api, filename, force)
python
def remove(config, username, filename, force): """Remove user's SSH public key from their LDAP entry.""" client = Client() client.prepare_connection() user_api = UserApi(client) key_api = API(client) key_api.remove(username, user_api, filename, force)
[ "def", "remove", "(", "config", ",", "username", ",", "filename", ",", "force", ")", ":", "client", "=", "Client", "(", ")", "client", ".", "prepare_connection", "(", ")", "user_api", "=", "UserApi", "(", "client", ")", "key_api", "=", "API", "(", "cli...
Remove user's SSH public key from their LDAP entry.
[ "Remove", "user", "s", "SSH", "public", "key", "from", "their", "LDAP", "entry", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/key.py#L195-L201
train
Remove user s SSH public key from their LDAP entry.
carta/ldap_tools
src/ldap_tools/key.py
CLI.install
def install(config): # pragma: no cover """Install user's SSH public key to the local system.""" client = Client() client.prepare_connection() key_api = API(client) key_api.install()
python
def install(config): # pragma: no cover """Install user's SSH public key to the local system.""" client = Client() client.prepare_connection() key_api = API(client) key_api.install()
[ "def", "install", "(", "config", ")", ":", "# pragma: no cover", "client", "=", "Client", "(", ")", "client", ".", "prepare_connection", "(", ")", "key_api", "=", "API", "(", "client", ")", "key_api", ".", "install", "(", ")" ]
Install user's SSH public key to the local system.
[ "Install", "user", "s", "SSH", "public", "key", "to", "the", "local", "system", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/key.py#L205-L210
train
Install user s SSH public key to the local system.
carta/ldap_tools
src/ldap_tools/key.py
CLI.list
def list(config): # pragma: no cover """List SSH public key(s) from LDAP.""" client = Client() client.prepare_connection() key_api = API(client) for key, values in key_api.get_keys_from_ldap().items(): print("{}: ".format(key)) for value in [v.decode() fo...
python
def list(config): # pragma: no cover """List SSH public key(s) from LDAP.""" client = Client() client.prepare_connection() key_api = API(client) for key, values in key_api.get_keys_from_ldap().items(): print("{}: ".format(key)) for value in [v.decode() fo...
[ "def", "list", "(", "config", ")", ":", "# pragma: no cover", "client", "=", "Client", "(", ")", "client", ".", "prepare_connection", "(", ")", "key_api", "=", "API", "(", "client", ")", "for", "key", ",", "values", "in", "key_api", ".", "get_keys_from_lda...
List SSH public key(s) from LDAP.
[ "List", "SSH", "public", "key", "(", "s", ")", "from", "LDAP", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/key.py#L214-L222
train
List SSH public key from LDAP.
carta/ldap_tools
src/ldap_tools/key.py
CLI.show
def show(config, username): # pragma: no cover """Show a user's SSH public key from their LDAP entry.""" client = Client() client.prepare_connection() key_api = API(client) for key, value in key_api.get_keys_from_ldap(username).items(): print(value)
python
def show(config, username): # pragma: no cover """Show a user's SSH public key from their LDAP entry.""" client = Client() client.prepare_connection() key_api = API(client) for key, value in key_api.get_keys_from_ldap(username).items(): print(value)
[ "def", "show", "(", "config", ",", "username", ")", ":", "# pragma: no cover", "client", "=", "Client", "(", ")", "client", ".", "prepare_connection", "(", ")", "key_api", "=", "API", "(", "client", ")", "for", "key", ",", "value", "in", "key_api", ".", ...
Show a user's SSH public key from their LDAP entry.
[ "Show", "a", "user", "s", "SSH", "public", "key", "from", "their", "LDAP", "entry", "." ]
7c039304a5abaf836c7afc35cf068b4471306264
https://github.com/carta/ldap_tools/blob/7c039304a5abaf836c7afc35cf068b4471306264/src/ldap_tools/key.py#L232-L238
train
Show a user s SSH public key from their LDAP entry.
ludeeus/GHLocalApi
ghlocalapi/device_settings.py
DeviceSettings.reboot
async def reboot(self): """Reboot the device.""" endpoint = '/setup/reboot' url = API.format(ip=self._ipaddress, endpoint=endpoint) data = {'params': 'now'} returnvalue = False try: async with async_timeout.timeout(5, loop=self._loop): result =...
python
async def reboot(self): """Reboot the device.""" endpoint = '/setup/reboot' url = API.format(ip=self._ipaddress, endpoint=endpoint) data = {'params': 'now'} returnvalue = False try: async with async_timeout.timeout(5, loop=self._loop): result =...
[ "async", "def", "reboot", "(", "self", ")", ":", "endpoint", "=", "'/setup/reboot'", "url", "=", "API", ".", "format", "(", "ip", "=", "self", ".", "_ipaddress", ",", "endpoint", "=", "endpoint", ")", "data", "=", "{", "'params'", ":", "'now'", "}", ...
Reboot the device.
[ "Reboot", "the", "device", "." ]
93abdee299c4a4b65aa9dd03c77ec34e174e3c56
https://github.com/ludeeus/GHLocalApi/blob/93abdee299c4a4b65aa9dd03c77ec34e174e3c56/ghlocalapi/device_settings.py#L28-L43
train
Reboot the device.
openearth/mmi-python
mmi/runner_legacy.py
main
def main(): """run mmi runner""" logging.basicConfig() logger.info("mmi-runner") warnings.warn( "You are using the mmi-runner script, please switch to `mmi runner`", DeprecationWarning ) arguments = docopt.docopt(__doc__) kwargs = parse_args(arguments) runner = mmi.runner...
python
def main(): """run mmi runner""" logging.basicConfig() logger.info("mmi-runner") warnings.warn( "You are using the mmi-runner script, please switch to `mmi runner`", DeprecationWarning ) arguments = docopt.docopt(__doc__) kwargs = parse_args(arguments) runner = mmi.runner...
[ "def", "main", "(", ")", ":", "logging", ".", "basicConfig", "(", ")", "logger", ".", "info", "(", "\"mmi-runner\"", ")", "warnings", ".", "warn", "(", "\"You are using the mmi-runner script, please switch to `mmi runner`\"", ",", "DeprecationWarning", ")", "arguments...
run mmi runner
[ "run", "mmi", "runner" ]
a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d
https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner_legacy.py#L34-L47
train
run mmi - runner
openearth/mmi-python
mmi/runner_legacy.py
parse_args
def parse_args(arguments, wrapper_kwargs={}): """ MMI Runner """ # make a socket that replies to message with the grid # if we are running mpi we want to know the rank args = {} positional = [ 'engine', 'configfile', ] for key in positional: args[key] = argum...
python
def parse_args(arguments, wrapper_kwargs={}): """ MMI Runner """ # make a socket that replies to message with the grid # if we are running mpi we want to know the rank args = {} positional = [ 'engine', 'configfile', ] for key in positional: args[key] = argum...
[ "def", "parse_args", "(", "arguments", ",", "wrapper_kwargs", "=", "{", "}", ")", ":", "# make a socket that replies to message with the grid", "# if we are running mpi we want to know the rank", "args", "=", "{", "}", "positional", "=", "[", "'engine'", ",", "'configfile...
MMI Runner
[ "MMI", "Runner" ]
a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d
https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner_legacy.py#L50-L78
train
parse the arguments for the MMI
rgmining/common
setup.py
load_requires_from_file
def load_requires_from_file(filepath): """Read a package list from a given file path. Args: filepath: file path of the package list. Returns: a list of package names. """ with open(filepath) as fp: return [pkg_name.strip() for pkg_name in fp.readlines()]
python
def load_requires_from_file(filepath): """Read a package list from a given file path. Args: filepath: file path of the package list. Returns: a list of package names. """ with open(filepath) as fp: return [pkg_name.strip() for pkg_name in fp.readlines()]
[ "def", "load_requires_from_file", "(", "filepath", ")", ":", "with", "open", "(", "filepath", ")", "as", "fp", ":", "return", "[", "pkg_name", ".", "strip", "(", ")", "for", "pkg_name", "in", "fp", ".", "readlines", "(", ")", "]" ]
Read a package list from a given file path. Args: filepath: file path of the package list. Returns: a list of package names.
[ "Read", "a", "package", "list", "from", "a", "given", "file", "path", "." ]
2462a4d54f32a82eadd7b1e28675b3c8bcd172b2
https://github.com/rgmining/common/blob/2462a4d54f32a82eadd7b1e28675b3c8bcd172b2/setup.py#L34-L44
train
Read a list of package names from a given file path.
mgoral/subconvert
src/subconvert/utils/SubtitleSearch.py
SearchIterator.last
def last(self): """Returns the last element accessed via next() or prev(). Returns the first element of range() if neither of these was called.""" if len(self._range) == 0: raise IndexError("range is empty") if self._idx == -1: return self._range[0] return...
python
def last(self): """Returns the last element accessed via next() or prev(). Returns the first element of range() if neither of these was called.""" if len(self._range) == 0: raise IndexError("range is empty") if self._idx == -1: return self._range[0] return...
[ "def", "last", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_range", ")", "==", "0", ":", "raise", "IndexError", "(", "\"range is empty\"", ")", "if", "self", ".", "_idx", "==", "-", "1", ":", "return", "self", ".", "_range", "[", "0", ...
Returns the last element accessed via next() or prev(). Returns the first element of range() if neither of these was called.
[ "Returns", "the", "last", "element", "accessed", "via", "next", "()", "or", "prev", "()", ".", "Returns", "the", "first", "element", "of", "range", "()", "if", "neither", "of", "these", "was", "called", "." ]
59701e5e69ef1ca26ce7d1d766c936664aa2cb32
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/SubtitleSearch.py#L45-L52
train
Returns the last element accessed via next or prev.
JoMingyu/TourAPI
tourapi/api.py
TourAPI.get_tour_list
def get_tour_list(self): """ Inquire all tour list :rtype: list """ resp = json.loads(urlopen(self.tour_list_url.format(1)).read().decode('utf-8')) total_count = resp['response']['body']['totalCount'] # Get total count resp = json.loads(urlopen(self.tour...
python
def get_tour_list(self): """ Inquire all tour list :rtype: list """ resp = json.loads(urlopen(self.tour_list_url.format(1)).read().decode('utf-8')) total_count = resp['response']['body']['totalCount'] # Get total count resp = json.loads(urlopen(self.tour...
[ "def", "get_tour_list", "(", "self", ")", ":", "resp", "=", "json", ".", "loads", "(", "urlopen", "(", "self", ".", "tour_list_url", ".", "format", "(", "1", ")", ")", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", ")", "total_count", "...
Inquire all tour list :rtype: list
[ "Inquire", "all", "tour", "list" ]
d4b2a6415e01efaa0ddddd55126e2f4ae9d19d33
https://github.com/JoMingyu/TourAPI/blob/d4b2a6415e01efaa0ddddd55126e2f4ae9d19d33/tourapi/api.py#L61-L103
train
Get all tour list.
JoMingyu/TourAPI
tourapi/api.py
TourAPI.get_detail_common
def get_detail_common(self, content_id): """ Inquire common detail data :param content_id: Content ID to inquire :type content_id: str :rtype: dict """ resp = json.loads(urlopen(self.detail_common_url.format(str(content_id))).read().decode('utf-8')) data...
python
def get_detail_common(self, content_id): """ Inquire common detail data :param content_id: Content ID to inquire :type content_id: str :rtype: dict """ resp = json.loads(urlopen(self.detail_common_url.format(str(content_id))).read().decode('utf-8')) data...
[ "def", "get_detail_common", "(", "self", ",", "content_id", ")", ":", "resp", "=", "json", ".", "loads", "(", "urlopen", "(", "self", ".", "detail_common_url", ".", "format", "(", "str", "(", "content_id", ")", ")", ")", ".", "read", "(", ")", ".", "...
Inquire common detail data :param content_id: Content ID to inquire :type content_id: str :rtype: dict
[ "Inquire", "common", "detail", "data" ]
d4b2a6415e01efaa0ddddd55126e2f4ae9d19d33
https://github.com/JoMingyu/TourAPI/blob/d4b2a6415e01efaa0ddddd55126e2f4ae9d19d33/tourapi/api.py#L105-L138
train
Get common detail data for a specific content_id.
JoMingyu/TourAPI
tourapi/api.py
TourAPI.get_detail_intro
def get_detail_intro(self, content_id): """ Inquire detail introduction :param content_id: Content ID to inquire :type content_id: str :rtype: dict """ content_type_id = self.get_detail_common(content_id)['content_type_id'] # Get content type id ...
python
def get_detail_intro(self, content_id): """ Inquire detail introduction :param content_id: Content ID to inquire :type content_id: str :rtype: dict """ content_type_id = self.get_detail_common(content_id)['content_type_id'] # Get content type id ...
[ "def", "get_detail_intro", "(", "self", ",", "content_id", ")", ":", "content_type_id", "=", "self", ".", "get_detail_common", "(", "content_id", ")", "[", "'content_type_id'", "]", "# Get content type id", "resp", "=", "json", ".", "loads", "(", "urlopen", "(",...
Inquire detail introduction :param content_id: Content ID to inquire :type content_id: str :rtype: dict
[ "Inquire", "detail", "introduction" ]
d4b2a6415e01efaa0ddddd55126e2f4ae9d19d33
https://github.com/JoMingyu/TourAPI/blob/d4b2a6415e01efaa0ddddd55126e2f4ae9d19d33/tourapi/api.py#L140-L323
train
Get detail introduction for a specific content_id.
JoMingyu/TourAPI
tourapi/api.py
TourAPI.get_detail_images
def get_detail_images(self, content_id): """ Inquire detail images :param content_id: Content ID to inquire :type content_id: str :rtype: list """ resp = json.loads(urlopen(self.additional_images_url.format(content_id, 1)).read().decode('utf-8')) total_c...
python
def get_detail_images(self, content_id): """ Inquire detail images :param content_id: Content ID to inquire :type content_id: str :rtype: list """ resp = json.loads(urlopen(self.additional_images_url.format(content_id, 1)).read().decode('utf-8')) total_c...
[ "def", "get_detail_images", "(", "self", ",", "content_id", ")", ":", "resp", "=", "json", ".", "loads", "(", "urlopen", "(", "self", ".", "additional_images_url", ".", "format", "(", "content_id", ",", "1", ")", ")", ".", "read", "(", ")", ".", "decod...
Inquire detail images :param content_id: Content ID to inquire :type content_id: str :rtype: list
[ "Inquire", "detail", "images" ]
d4b2a6415e01efaa0ddddd55126e2f4ae9d19d33
https://github.com/JoMingyu/TourAPI/blob/d4b2a6415e01efaa0ddddd55126e2f4ae9d19d33/tourapi/api.py#L325-L361
train
Get the detail images for a specific content_id.
mgoral/subconvert
src/subconvert/utils/SubFile.py
File._writeFile
def _writeFile(cls, filePath, content, encoding = None): """Safe file writing. Most common mistakes are checked against and reported before write operation. After that, if anything unexpected happens, user won't be left without data or with corrupted one as this method writes to a temporary file...
python
def _writeFile(cls, filePath, content, encoding = None): """Safe file writing. Most common mistakes are checked against and reported before write operation. After that, if anything unexpected happens, user won't be left without data or with corrupted one as this method writes to a temporary file...
[ "def", "_writeFile", "(", "cls", ",", "filePath", ",", "content", ",", "encoding", "=", "None", ")", ":", "filePath", "=", "os", ".", "path", ".", "realpath", "(", "filePath", ")", "log", ".", "debug", "(", "_", "(", "\"Real file path to write: %s\"", "%...
Safe file writing. Most common mistakes are checked against and reported before write operation. After that, if anything unexpected happens, user won't be left without data or with corrupted one as this method writes to a temporary file and then simply renames it (which should be atomic operatio...
[ "Safe", "file", "writing", ".", "Most", "common", "mistakes", "are", "checked", "against", "and", "reported", "before", "write", "operation", ".", "After", "that", "if", "anything", "unexpected", "happens", "user", "won", "t", "be", "left", "without", "data", ...
59701e5e69ef1ca26ce7d1d766c936664aa2cb32
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/SubFile.py#L117-L159
train
Safe file writing.
mgoral/subconvert
src/subconvert/utils/SubFile.py
File.detectFps
def detectFps(self, movieFile = None, default = 23.976): """Fetch movie FPS from MPlayer output or return given default.""" if movieFile is None: movieFile = self._searchForMovieFile() return File.detectFpsFromMovie(movieFile, default)
python
def detectFps(self, movieFile = None, default = 23.976): """Fetch movie FPS from MPlayer output or return given default.""" if movieFile is None: movieFile = self._searchForMovieFile() return File.detectFpsFromMovie(movieFile, default)
[ "def", "detectFps", "(", "self", ",", "movieFile", "=", "None", ",", "default", "=", "23.976", ")", ":", "if", "movieFile", "is", "None", ":", "movieFile", "=", "self", ".", "_searchForMovieFile", "(", ")", "return", "File", ".", "detectFpsFromMovie", "(",...
Fetch movie FPS from MPlayer output or return given default.
[ "Fetch", "movie", "FPS", "from", "MPlayer", "output", "or", "return", "given", "default", "." ]
59701e5e69ef1ca26ce7d1d766c936664aa2cb32
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/SubFile.py#L189-L194
train
Fetch movie FPS from MPlayer output or return given default.
mgoral/subconvert
src/subconvert/utils/SubFile.py
File.detectFpsFromMovie
def detectFpsFromMovie(cls, movieFile, default = 23.976): """Fetch movie FPS from MPlayer output or return given default.""" # initialize with a default FPS value, but not with a movieFile videoInfo = VideoInfo(float(default)) command = ['mplayer', '-really-quiet', '-vo', '...
python
def detectFpsFromMovie(cls, movieFile, default = 23.976): """Fetch movie FPS from MPlayer output or return given default.""" # initialize with a default FPS value, but not with a movieFile videoInfo = VideoInfo(float(default)) command = ['mplayer', '-really-quiet', '-vo', '...
[ "def", "detectFpsFromMovie", "(", "cls", ",", "movieFile", ",", "default", "=", "23.976", ")", ":", "# initialize with a default FPS value, but not with a movieFile", "videoInfo", "=", "VideoInfo", "(", "float", "(", "default", ")", ")", "command", "=", "[", "'mplay...
Fetch movie FPS from MPlayer output or return given default.
[ "Fetch", "movie", "FPS", "from", "MPlayer", "output", "or", "return", "given", "default", "." ]
59701e5e69ef1ca26ce7d1d766c936664aa2cb32
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/SubFile.py#L197-L229
train
Detect FPS from a movie file.
skioo/django-customer-billing
billing/actions/invoices.py
pay_with_account_credit_cards
def pay_with_account_credit_cards(invoice_id) -> Optional[Transaction]: """ Get paid for the invoice, trying the valid credit cards on record for the account. If successful attaches the payment to the invoice and marks the invoice as paid. :param invoice_id: the id of the invoice to pay. :return: ...
python
def pay_with_account_credit_cards(invoice_id) -> Optional[Transaction]: """ Get paid for the invoice, trying the valid credit cards on record for the account. If successful attaches the payment to the invoice and marks the invoice as paid. :param invoice_id: the id of the invoice to pay. :return: ...
[ "def", "pay_with_account_credit_cards", "(", "invoice_id", ")", "->", "Optional", "[", "Transaction", "]", ":", "logger", ".", "debug", "(", "'invoice-payment-started'", ",", "invoice_id", "=", "invoice_id", ")", "with", "transaction", ".", "atomic", "(", ")", "...
Get paid for the invoice, trying the valid credit cards on record for the account. If successful attaches the payment to the invoice and marks the invoice as paid. :param invoice_id: the id of the invoice to pay. :return: A successful transaction, or None if we weren't able to pay the invoice.
[ "Get", "paid", "for", "the", "invoice", "trying", "the", "valid", "credit", "cards", "on", "record", "for", "the", "account", "." ]
6ac1ed9ef9d1d7eee0379de7f0c4b76919ae1f2d
https://github.com/skioo/django-customer-billing/blob/6ac1ed9ef9d1d7eee0379de7f0c4b76919ae1f2d/billing/actions/invoices.py#L16-L77
train
Get paid for the invoice and try the valid credit cards on the account.
davidfokkema/artist
artist/recursive_smooth.py
smooth
def smooth(x, y, degree=1, logx=False, logy=False): """Smooth y-values and return new x, y pair. :param x,y: data values :param degree: degree of smoothing Smooth data by using a recursive linear interpolation technique. For degree = 0, return the original values. For degree = 1, generate a ...
python
def smooth(x, y, degree=1, logx=False, logy=False): """Smooth y-values and return new x, y pair. :param x,y: data values :param degree: degree of smoothing Smooth data by using a recursive linear interpolation technique. For degree = 0, return the original values. For degree = 1, generate a ...
[ "def", "smooth", "(", "x", ",", "y", ",", "degree", "=", "1", ",", "logx", "=", "False", ",", "logy", "=", "False", ")", ":", "if", "degree", "==", "0", ":", "return", "x", ",", "y", "else", ":", "if", "logx", ":", "x", "=", "np", ".", "log...
Smooth y-values and return new x, y pair. :param x,y: data values :param degree: degree of smoothing Smooth data by using a recursive linear interpolation technique. For degree = 0, return the original values. For degree = 1, generate a evenly spaced sequence of x-values, with the length equal t...
[ "Smooth", "y", "-", "values", "and", "return", "new", "x", "y", "pair", "." ]
26ae7987522622710f2910980770c50012fda47d
https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/artist/recursive_smooth.py#L6-L46
train
Smooth y - values and return new x y pair.
mgoral/subconvert
src/subconvert/gui/ToolBox.py
ToolBox.setContentFor
def setContentFor(self, widget): """Updates toolbox contents with a data corresponding to a given tab.""" for i in range(self.count()): item = self.widget(i) if widget.isStatic: item.setStaticContent(widget) else: item.setContent(widget...
python
def setContentFor(self, widget): """Updates toolbox contents with a data corresponding to a given tab.""" for i in range(self.count()): item = self.widget(i) if widget.isStatic: item.setStaticContent(widget) else: item.setContent(widget...
[ "def", "setContentFor", "(", "self", ",", "widget", ")", ":", "for", "i", "in", "range", "(", "self", ".", "count", "(", ")", ")", ":", "item", "=", "self", ".", "widget", "(", "i", ")", "if", "widget", ".", "isStatic", ":", "item", ".", "setStat...
Updates toolbox contents with a data corresponding to a given tab.
[ "Updates", "toolbox", "contents", "with", "a", "data", "corresponding", "to", "a", "given", "tab", "." ]
59701e5e69ef1ca26ce7d1d766c936664aa2cb32
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/gui/ToolBox.py#L37-L44
train
Updates toolbox contents with a data corresponding to a given tab.
mgoral/subconvert
src/subconvert/gui/ToolBox.py
Tool.clear
def clear(self): """Removes all child widgets.""" layout = self.layout() for index in reversed(range(layout.count())): item = layout.takeAt(index) try: item.widget().deleteLater() except AttributeError: item = None
python
def clear(self): """Removes all child widgets.""" layout = self.layout() for index in reversed(range(layout.count())): item = layout.takeAt(index) try: item.widget().deleteLater() except AttributeError: item = None
[ "def", "clear", "(", "self", ")", ":", "layout", "=", "self", ".", "layout", "(", ")", "for", "index", "in", "reversed", "(", "range", "(", "layout", ".", "count", "(", ")", ")", ")", ":", "item", "=", "layout", ".", "takeAt", "(", "index", ")", ...
Removes all child widgets.
[ "Removes", "all", "child", "widgets", "." ]
59701e5e69ef1ca26ce7d1d766c936664aa2cb32
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/gui/ToolBox.py#L79-L87
train
Removes all child widgets.
mgoral/subconvert
src/subconvert/gui/ToolBox.py
Tool.setStaticContent
def setStaticContent(self, widget=None): """Set content for static widget (FileList).""" self.clear() self.addTitle(_("No subtitle data")) self.addLabel(_("Open subtitles in a new tab to see their details.")) self.addStretch()
python
def setStaticContent(self, widget=None): """Set content for static widget (FileList).""" self.clear() self.addTitle(_("No subtitle data")) self.addLabel(_("Open subtitles in a new tab to see their details.")) self.addStretch()
[ "def", "setStaticContent", "(", "self", ",", "widget", "=", "None", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "addTitle", "(", "_", "(", "\"No subtitle data\"", ")", ")", "self", ".", "addLabel", "(", "_", "(", "\"Open subtitles in a new tab t...
Set content for static widget (FileList).
[ "Set", "content", "for", "static", "widget", "(", "FileList", ")", "." ]
59701e5e69ef1ca26ce7d1d766c936664aa2cb32
https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/gui/ToolBox.py#L89-L94
train
Set content for static widget.
stylight/python-fastbill
fastbill/wrapper.py
_abort_http
def _abort_http(method, http_resp): """ >>> class FakeResp(object): ... content = 'Wohoo!' ... headers = {'foo': 'bar'} ... status_code = 200 ... reason = 'OK' >>> _abort_http("foo.get", FakeResp()) Traceback (most recent call last): ... FastbillResponseError...
python
def _abort_http(method, http_resp): """ >>> class FakeResp(object): ... content = 'Wohoo!' ... headers = {'foo': 'bar'} ... status_code = 200 ... reason = 'OK' >>> _abort_http("foo.get", FakeResp()) Traceback (most recent call last): ... FastbillResponseError...
[ "def", "_abort_http", "(", "method", ",", "http_resp", ")", ":", "exc_template", "=", "\"\"\"POST {method} {0.status_code} {0.reason}\nHeaders:\n{headers}\nContent:\n{0.content!r}\nSummary: POST {method} {0.status_code} {0.reason}\"\"\"", "headers", "=", "_pp", ".", "pformat", "(", ...
>>> class FakeResp(object): ... content = 'Wohoo!' ... headers = {'foo': 'bar'} ... status_code = 200 ... reason = 'OK' >>> _abort_http("foo.get", FakeResp()) Traceback (most recent call last): ... FastbillResponseError: POST foo.get 200 OK Headers: {'foo': '...
[ ">>>", "class", "FakeResp", "(", "object", ")", ":", "...", "content", "=", "Wohoo!", "...", "headers", "=", "{", "foo", ":", "bar", "}", "...", "status_code", "=", "200", "...", "reason", "=", "OK" ]
e0cea5cc931df4a7b64c2f877ff3b9a4cf56e5bc
https://github.com/stylight/python-fastbill/blob/e0cea5cc931df4a7b64c2f877ff3b9a4cf56e5bc/fastbill/wrapper.py#L182-L215
train
Abort the HTTP request.
stylight/python-fastbill
fastbill/wrapper.py
FastbillWrapper._request
def _request(self, service, **kw): """Do the actual request to Fastbill's API server. If successful returns the RESPONSE section the of response, in case of an error raises a subclass of FastbillError. """ fb_request = { 'service': service, } for key ...
python
def _request(self, service, **kw): """Do the actual request to Fastbill's API server. If successful returns the RESPONSE section the of response, in case of an error raises a subclass of FastbillError. """ fb_request = { 'service': service, } for key ...
[ "def", "_request", "(", "self", ",", "service", ",", "*", "*", "kw", ")", ":", "fb_request", "=", "{", "'service'", ":", "service", ",", "}", "for", "key", "in", "[", "'limit'", ",", "'offset'", ",", "'filter'", ",", "'data'", "]", ":", "fb_request",...
Do the actual request to Fastbill's API server. If successful returns the RESPONSE section the of response, in case of an error raises a subclass of FastbillError.
[ "Do", "the", "actual", "request", "to", "Fastbill", "s", "API", "server", "." ]
e0cea5cc931df4a7b64c2f877ff3b9a4cf56e5bc
https://github.com/stylight/python-fastbill/blob/e0cea5cc931df4a7b64c2f877ff3b9a4cf56e5bc/fastbill/wrapper.py#L117-L164
train
Perform the actual request to Fastbill s API server.
PythonOptimizers/cygenja
cygenja/treemap/treemap_node.py
TreeMapNode.set_parent
def set_parent(self, node): """ Attach node to its parent. Args: node: Parent node. Note: ``node`` can be ``None``. In that case, the node is detached from its previous parent. """ self._parent = node if node is None: # deta...
python
def set_parent(self, node): """ Attach node to its parent. Args: node: Parent node. Note: ``node`` can be ``None``. In that case, the node is detached from its previous parent. """ self._parent = node if node is None: # deta...
[ "def", "set_parent", "(", "self", ",", "node", ")", ":", "self", ".", "_parent", "=", "node", "if", "node", "is", "None", ":", "# detach from parent", "self", ".", "_depth", "=", "0", "else", ":", "self", ".", "_depth", "=", "node", ".", "get_depth", ...
Attach node to its parent. Args: node: Parent node. Note: ``node`` can be ``None``. In that case, the node is detached from its previous parent.
[ "Attach", "node", "to", "its", "parent", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/treemap/treemap_node.py#L35-L52
train
Attach node to its parent.
PythonOptimizers/cygenja
cygenja/treemap/treemap_node.py
TreeMapNode.set_child_node
def set_child_node(self, name, node): """ Add one child node to this node. Args: name (str): Name of the child. node (TreeMapNode): Node to add. Warning: No test is done to see whether or not a node was already attached with that name. If this is the...
python
def set_child_node(self, name, node): """ Add one child node to this node. Args: name (str): Name of the child. node (TreeMapNode): Node to add. Warning: No test is done to see whether or not a node was already attached with that name. If this is the...
[ "def", "set_child_node", "(", "self", ",", "name", ",", "node", ")", ":", "assert", "isinstance", "(", "node", ",", "TreeMapNode", ")", "self", ".", "_nodes", "[", "name", "]", "=", "node", "node", ".", "set_parent", "(", "self", ")" ]
Add one child node to this node. Args: name (str): Name of the child. node (TreeMapNode): Node to add. Warning: No test is done to see whether or not a node was already attached with that name. If this is the case, the new node takes the place of the old...
[ "Add", "one", "child", "node", "to", "this", "node", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/treemap/treemap_node.py#L54-L68
train
Adds one child node to this node.
PythonOptimizers/cygenja
cygenja/treemap/treemap_node.py
TreeMapNode.set_unique_child_node
def set_unique_child_node(self, name, node): """ Add one child node to this node. Args: name (str): Name of the child. node (TreeMapNode): Node to add. Note: The name must **not** be in use. """ try: temp = self._nodes[nam...
python
def set_unique_child_node(self, name, node): """ Add one child node to this node. Args: name (str): Name of the child. node (TreeMapNode): Node to add. Note: The name must **not** be in use. """ try: temp = self._nodes[nam...
[ "def", "set_unique_child_node", "(", "self", ",", "name", ",", "node", ")", ":", "try", ":", "temp", "=", "self", ".", "_nodes", "[", "name", "]", "raise", "RuntimeError", "(", "\"Name '%s' is already used for child node\"", "%", "name", ")", "except", "KeyErr...
Add one child node to this node. Args: name (str): Name of the child. node (TreeMapNode): Node to add. Note: The name must **not** be in use.
[ "Add", "one", "child", "node", "to", "this", "node", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/treemap/treemap_node.py#L70-L87
train
Add one child node to this node.
PythonOptimizers/cygenja
cygenja/treemap/treemap_node.py
TreeMapNode.generate_child_leaf_nodes
def generate_child_leaf_nodes(self): """ Generate leaf nodes of this node. """ def _yield_child_leaf_nodes(node): """ Args: node: Yields: """ if not node.has_children(): yield node ...
python
def generate_child_leaf_nodes(self): """ Generate leaf nodes of this node. """ def _yield_child_leaf_nodes(node): """ Args: node: Yields: """ if not node.has_children(): yield node ...
[ "def", "generate_child_leaf_nodes", "(", "self", ")", ":", "def", "_yield_child_leaf_nodes", "(", "node", ")", ":", "\"\"\"\n\n Args:\n node:\n\n Yields:\n \"\"\"", "if", "not", "node", ".", "has_children", "(", ")", ":", "yie...
Generate leaf nodes of this node.
[ "Generate", "leaf", "nodes", "of", "this", "node", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/treemap/treemap_node.py#L149-L171
train
Generate leaf nodes of this node.
PythonOptimizers/cygenja
cygenja/treemap/treemap_node.py
TreeMapNode.detach_children
def detach_children(self): """ Erase references to children without deleting them. These children might be used somewhere else, otherwise they will be taken care by ``Python``'s garbage collector. """ for node in self.get_child_nodes(): node.set_parent(None) ...
python
def detach_children(self): """ Erase references to children without deleting them. These children might be used somewhere else, otherwise they will be taken care by ``Python``'s garbage collector. """ for node in self.get_child_nodes(): node.set_parent(None) ...
[ "def", "detach_children", "(", "self", ")", ":", "for", "node", "in", "self", ".", "get_child_nodes", "(", ")", ":", "node", ".", "set_parent", "(", "None", ")", "self", ".", "_nodes", "=", "dict", "(", ")" ]
Erase references to children without deleting them. These children might be used somewhere else, otherwise they will be taken care by ``Python``'s garbage collector.
[ "Erase", "references", "to", "children", "without", "deleting", "them", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/treemap/treemap_node.py#L173-L181
train
Detaches all children from the current node.
ngmarchant/oasis
oasis/experiments.py
repeat_expt
def repeat_expt(smplr, n_expts, n_labels, output_file = None): """ Parameters ---------- smplr : sub-class of PassiveSampler sampler must have a sample_distinct method, reset method and ... n_expts : int number of expts to run n_labels : int number of labels to query fr...
python
def repeat_expt(smplr, n_expts, n_labels, output_file = None): """ Parameters ---------- smplr : sub-class of PassiveSampler sampler must have a sample_distinct method, reset method and ... n_expts : int number of expts to run n_labels : int number of labels to query fr...
[ "def", "repeat_expt", "(", "smplr", ",", "n_expts", ",", "n_labels", ",", "output_file", "=", "None", ")", ":", "FILTERS", "=", "tables", ".", "Filters", "(", "complib", "=", "'zlib'", ",", "complevel", "=", "5", ")", "max_iter", "=", "smplr", ".", "_m...
Parameters ---------- smplr : sub-class of PassiveSampler sampler must have a sample_distinct method, reset method and ... n_expts : int number of expts to run n_labels : int number of labels to query from the oracle in each expt
[ "Parameters", "----------", "smplr", ":", "sub", "-", "class", "of", "PassiveSampler", "sampler", "must", "have", "a", "sample_distinct", "method", "reset", "method", "and", "..." ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/experiments.py#L7-L59
train
This function is used to repeat a single experiment in a single passive sampler.
ngmarchant/oasis
oasis/experiments.py
process_expt
def process_expt(h5_path, inmemory = True, ignorenan = False): """ Assumes h5 file has table called `F_measure` Parameters ---------- h5_path : string path to HDF file containing the experimental data. The file is expected to have been generated from the `repeat_expt` function. ...
python
def process_expt(h5_path, inmemory = True, ignorenan = False): """ Assumes h5 file has table called `F_measure` Parameters ---------- h5_path : string path to HDF file containing the experimental data. The file is expected to have been generated from the `repeat_expt` function. ...
[ "def", "process_expt", "(", "h5_path", ",", "inmemory", "=", "True", ",", "ignorenan", "=", "False", ")", ":", "logging", ".", "info", "(", "\"Reading file at {}\"", ".", "format", "(", "h5_path", ")", ")", "h5_file", "=", "tables", ".", "open_file", "(", ...
Assumes h5 file has table called `F_measure` Parameters ---------- h5_path : string path to HDF file containing the experimental data. The file is expected to have been generated from the `repeat_expt` function. inmemory : bool whether to process the experiments in memory ...
[ "Assumes", "h5", "file", "has", "table", "called", "F_measure" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/experiments.py#L61-L138
train
This function processes the experimental data in the HDF5 file and returns a dictionary containing the mean and variance of the experiments.
ngmarchant/oasis
oasis/experiments.py
Data.scores_to_preds
def scores_to_preds(self, threshold, use_probs = True): """ use_probs : boolean, default True if True, use probabilities for predictions, else use scores. """ self.threshold = threshold if use_probs: if self.probs is None: raise DataError(...
python
def scores_to_preds(self, threshold, use_probs = True): """ use_probs : boolean, default True if True, use probabilities for predictions, else use scores. """ self.threshold = threshold if use_probs: if self.probs is None: raise DataError(...
[ "def", "scores_to_preds", "(", "self", ",", "threshold", ",", "use_probs", "=", "True", ")", ":", "self", ".", "threshold", "=", "threshold", "if", "use_probs", ":", "if", "self", ".", "probs", "is", "None", ":", "raise", "DataError", "(", "\"Probabilities...
use_probs : boolean, default True if True, use probabilities for predictions, else use scores.
[ "use_probs", ":", "boolean", "default", "True", "if", "True", "use", "probabilities", "for", "predictions", "else", "use", "scores", "." ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/experiments.py#L187-L214
train
Set self. scores to predictions.
ngmarchant/oasis
oasis/experiments.py
Data.calc_confusion_matrix
def calc_confusion_matrix(self, printout = False): """ Calculates number of TP, FP, TN, FN """ if self.labels is None: raise DataError("Cannot calculate confusion matrix before data " "has been read.") if self.preds is None: ra...
python
def calc_confusion_matrix(self, printout = False): """ Calculates number of TP, FP, TN, FN """ if self.labels is None: raise DataError("Cannot calculate confusion matrix before data " "has been read.") if self.preds is None: ra...
[ "def", "calc_confusion_matrix", "(", "self", ",", "printout", "=", "False", ")", ":", "if", "self", ".", "labels", "is", "None", ":", "raise", "DataError", "(", "\"Cannot calculate confusion matrix before data \"", "\"has been read.\"", ")", "if", "self", ".", "pr...
Calculates number of TP, FP, TN, FN
[ "Calculates", "number", "of", "TP", "FP", "TN", "FN" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/experiments.py#L216-L239
train
Calculates the confusion matrix for the current class.
ngmarchant/oasis
oasis/experiments.py
Data.calc_true_performance
def calc_true_performance(self, printout = False): """ Evaluate precision, recall and balanced F-measure """ try: self.calc_confusion_matrix(printout = False) except DataError as e: print(e.msg) raise if self.TP + self.FP == 0: ...
python
def calc_true_performance(self, printout = False): """ Evaluate precision, recall and balanced F-measure """ try: self.calc_confusion_matrix(printout = False) except DataError as e: print(e.msg) raise if self.TP + self.FP == 0: ...
[ "def", "calc_true_performance", "(", "self", ",", "printout", "=", "False", ")", ":", "try", ":", "self", ".", "calc_confusion_matrix", "(", "printout", "=", "False", ")", "except", "DataError", "as", "e", ":", "print", "(", "e", ".", "msg", ")", "raise"...
Evaluate precision, recall and balanced F-measure
[ "Evaluate", "precision", "recall", "and", "balanced", "F", "-", "measure" ]
28a037a8924b85ae97db8a93960a910a219d6a4a
https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/experiments.py#L242-L271
train
Evaluate precision recall and balanced F - measure and calculate true performance.
praekeltfoundation/seed-message-sender
message_sender/migrations/0020_outboundsendfailure_db_backed_fk_constraint.py
modify_fk_constraint
def modify_fk_constraint(apps, schema_editor): """ Delete's the current foreign key contraint on the outbound field, and adds it again, but this time with an ON DELETE clause """ model = apps.get_model("message_sender", "OutboundSendFailure") table = model._meta.db_table with schema_editor....
python
def modify_fk_constraint(apps, schema_editor): """ Delete's the current foreign key contraint on the outbound field, and adds it again, but this time with an ON DELETE clause """ model = apps.get_model("message_sender", "OutboundSendFailure") table = model._meta.db_table with schema_editor....
[ "def", "modify_fk_constraint", "(", "apps", ",", "schema_editor", ")", ":", "model", "=", "apps", ".", "get_model", "(", "\"message_sender\"", ",", "\"OutboundSendFailure\"", ")", "table", "=", "model", ".", "_meta", ".", "db_table", "with", "schema_editor", "."...
Delete's the current foreign key contraint on the outbound field, and adds it again, but this time with an ON DELETE clause
[ "Delete", "s", "the", "current", "foreign", "key", "contraint", "on", "the", "outbound", "field", "and", "adds", "it", "again", "but", "this", "time", "with", "an", "ON", "DELETE", "clause" ]
257b01635171b9dbe1f5f13baa810c971bb2620e
https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/migrations/0020_outboundsendfailure_db_backed_fk_constraint.py#L10-L47
train
Modify the foreign key constraint on the outbound field.
PythonOptimizers/cygenja
cygenja/generator.py
GeneratorActionContainer.add_generator_action
def add_generator_action(self, action): """ Attach/add one :class:`GeneratorAction`. Warning: The order in which you add :class:`GeneratorAction` objects **is** important in case of conflicting :class:`GeneratorAction` objects: **only** the **first compatible** :class:`G...
python
def add_generator_action(self, action): """ Attach/add one :class:`GeneratorAction`. Warning: The order in which you add :class:`GeneratorAction` objects **is** important in case of conflicting :class:`GeneratorAction` objects: **only** the **first compatible** :class:`G...
[ "def", "add_generator_action", "(", "self", ",", "action", ")", ":", "if", "not", "isinstance", "(", "action", ",", "GeneratorAction", ")", ":", "raise", "RuntimeError", "(", "'Can not add a none GeneratorAction object.'", ")", "self", ".", "__generator_actions", "....
Attach/add one :class:`GeneratorAction`. Warning: The order in which you add :class:`GeneratorAction` objects **is** important in case of conflicting :class:`GeneratorAction` objects: **only** the **first compatible** :class:`GeneratorAction` object will be used to generate the (source ...
[ "Attach", "/", "add", "one", ":", "class", ":", "GeneratorAction", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L49-L60
train
Add a generator action.
PythonOptimizers/cygenja
cygenja/generator.py
GeneratorActionContainer.get_compatible_generator_action
def get_compatible_generator_action(self, filename): """ Return the **first** compatible :class:`GeneratorAction` for a given filename or ``None`` if none is found. Args: filename (str): The filename of the template to process. """ # find first compatible generator a...
python
def get_compatible_generator_action(self, filename): """ Return the **first** compatible :class:`GeneratorAction` for a given filename or ``None`` if none is found. Args: filename (str): The filename of the template to process. """ # find first compatible generator a...
[ "def", "get_compatible_generator_action", "(", "self", ",", "filename", ")", ":", "# find first compatible generator action", "for", "action", "in", "self", ".", "__generator_actions", ":", "if", "action", ".", "act_on_file", "(", "filename", ")", ":", "return", "ac...
Return the **first** compatible :class:`GeneratorAction` for a given filename or ``None`` if none is found. Args: filename (str): The filename of the template to process.
[ "Return", "the", "**", "first", "**", "compatible", ":", "class", ":", "GeneratorAction", "for", "a", "given", "filename", "or", "None", "if", "none", "is", "found", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L62-L74
train
Returns the first compatible generator action for a given filename.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.log_warning
def log_warning(self, msg): """ Log a warning if ``logger`` exists. Args: msg: Warning to log. Warning: Can raise a ``RuntimeError`` if this was asked in the constructor. """ if self.__logger: self.__logger.warning(msg) if s...
python
def log_warning(self, msg): """ Log a warning if ``logger`` exists. Args: msg: Warning to log. Warning: Can raise a ``RuntimeError`` if this was asked in the constructor. """ if self.__logger: self.__logger.warning(msg) if s...
[ "def", "log_warning", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "__logger", ":", "self", ".", "__logger", ".", "warning", "(", "msg", ")", "if", "self", ".", "__raise_exception_on_warning", ":", "raise", "RuntimeError", "(", "msg", ")" ]
Log a warning if ``logger`` exists. Args: msg: Warning to log. Warning: Can raise a ``RuntimeError`` if this was asked in the constructor.
[ "Log", "a", "warning", "if", "logger", "exists", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L133-L148
train
Log a warning if logger exists.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.log_error
def log_error(self, msg): """ Log an error and raise an exception. Args: msg: Error message to log. Raises: RuntimeError: With the message. """ if self.__logger: self.__logger.error(msg) raise RuntimeError(msg)
python
def log_error(self, msg): """ Log an error and raise an exception. Args: msg: Error message to log. Raises: RuntimeError: With the message. """ if self.__logger: self.__logger.error(msg) raise RuntimeError(msg)
[ "def", "log_error", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "__logger", ":", "self", ".", "__logger", ".", "error", "(", "msg", ")", "raise", "RuntimeError", "(", "msg", ")" ]
Log an error and raise an exception. Args: msg: Error message to log. Raises: RuntimeError: With the message.
[ "Log", "an", "error", "and", "raise", "an", "exception", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L150-L163
train
Log an error and raise an exception.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.register_filter
def register_filter(self, filter_name, filter_ref, force=False): """ Add/register one filter. Args: filter_name (str): Filter name used inside :program:`Jinja2` tags. filter_ref: Reference to the filter itself, i.e. the corresponding :program:`Python` function. ...
python
def register_filter(self, filter_name, filter_ref, force=False): """ Add/register one filter. Args: filter_name (str): Filter name used inside :program:`Jinja2` tags. filter_ref: Reference to the filter itself, i.e. the corresponding :program:`Python` function. ...
[ "def", "register_filter", "(", "self", ",", "filter_name", ",", "filter_ref", ",", "force", "=", "False", ")", ":", "if", "not", "force", "and", "(", "filter_name", "in", "self", ".", "filters_list", "(", ")", ")", ":", "self", ".", "log_warning", "(", ...
Add/register one filter. Args: filter_name (str): Filter name used inside :program:`Jinja2` tags. filter_ref: Reference to the filter itself, i.e. the corresponding :program:`Python` function. force (bool): If set to ``True``, forces the registration of a filter no matter if...
[ "Add", "/", "register", "one", "filter", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L178-L194
train
Register a filter in the Jinja2 environment.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.register_filters
def register_filters(self, filters, force=False): """ Add/register filters. Args: filters (dict): Dictionary of Python functions to use as :program:`Jinja2` filters. force (bool): If set to ``True``, forces the registration of a filter no matter if it already exists or n...
python
def register_filters(self, filters, force=False): """ Add/register filters. Args: filters (dict): Dictionary of Python functions to use as :program:`Jinja2` filters. force (bool): If set to ``True``, forces the registration of a filter no matter if it already exists or n...
[ "def", "register_filters", "(", "self", ",", "filters", ",", "force", "=", "False", ")", ":", "for", "filter_name", ",", "filter_ref", "in", "filters", ".", "items", "(", ")", ":", "self", ".", "register_filter", "(", "filter_name", ",", "filter_ref", ",",...
Add/register filters. Args: filters (dict): Dictionary of Python functions to use as :program:`Jinja2` filters. force (bool): If set to ``True``, forces the registration of a filter no matter if it already exists or not.
[ "Add", "/", "register", "filters", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L196-L206
train
Add or register filters.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.registered_filters_list
def registered_filters_list(self): """ Return the list of registered filters (as a list of strings). The list **only** includes registered filters (**not** the predefined :program:`Jinja2` filters). """ return [filter_name for filter_name in self.__jinja2_environment.filters.ke...
python
def registered_filters_list(self): """ Return the list of registered filters (as a list of strings). The list **only** includes registered filters (**not** the predefined :program:`Jinja2` filters). """ return [filter_name for filter_name in self.__jinja2_environment.filters.ke...
[ "def", "registered_filters_list", "(", "self", ")", ":", "return", "[", "filter_name", "for", "filter_name", "in", "self", ".", "__jinja2_environment", ".", "filters", ".", "keys", "(", ")", "if", "filter_name", "not", "in", "self", ".", "__jinja2_predefined_fil...
Return the list of registered filters (as a list of strings). The list **only** includes registered filters (**not** the predefined :program:`Jinja2` filters).
[ "Return", "the", "list", "of", "registered", "filters", "(", "as", "a", "list", "of", "strings", ")", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L218-L225
train
Return the list of registered filters as a list of strings.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.register_common_type_filters
def register_common_type_filters(self): """ Add/register common type filters for the :program:`CySparse` project. """ self.register_filter('type2enum', type2enum) self.register_filter('cysparse_type_to_numpy_c_type', cysparse_type_to_numpy_c_type) self.register_filter('c...
python
def register_common_type_filters(self): """ Add/register common type filters for the :program:`CySparse` project. """ self.register_filter('type2enum', type2enum) self.register_filter('cysparse_type_to_numpy_c_type', cysparse_type_to_numpy_c_type) self.register_filter('c...
[ "def", "register_common_type_filters", "(", "self", ")", ":", "self", ".", "register_filter", "(", "'type2enum'", ",", "type2enum", ")", "self", ".", "register_filter", "(", "'cysparse_type_to_numpy_c_type'", ",", "cysparse_type_to_numpy_c_type", ")", "self", ".", "re...
Add/register common type filters for the :program:`CySparse` project.
[ "Add", "/", "register", "common", "type", "filters", "for", "the", ":", "program", ":", "CySparse", "project", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L228-L238
train
Add common type filters for the CysParse project.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.register_extension
def register_extension(self, ext_in, ext_out, force=False): """ Add/register a file extension. Args: ext_in (str): Extension of input files. ext_out (str): Extension of corresponding output files. force (bool): If ``force`` is set to ``True``, simply overwri...
python
def register_extension(self, ext_in, ext_out, force=False): """ Add/register a file extension. Args: ext_in (str): Extension of input files. ext_out (str): Extension of corresponding output files. force (bool): If ``force`` is set to ``True``, simply overwri...
[ "def", "register_extension", "(", "self", ",", "ext_in", ",", "ext_out", ",", "force", "=", "False", ")", ":", "if", "not", "force", "and", "(", "ext_in", "in", "self", ".", "__extensions", ".", "keys", "(", ")", ")", ":", "self", ".", "log_warning", ...
Add/register a file extension. Args: ext_in (str): Extension of input files. ext_out (str): Extension of corresponding output files. force (bool): If ``force`` is set to ``True``, simply overwrite existing extensions, otherwise do nothing. If the ``logger`` ...
[ "Add", "/", "register", "a", "file", "extension", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L243-L260
train
Add or register a file extension.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.register_extensions
def register_extensions(self, exts, force=False): """ Add/register extensions. Args: exts (dict): force (bool): If ``force`` is set to ``True``, simply overwrite existing extensions, otherwise do nothing. If the ``logger`` is set, log a warning about the ...
python
def register_extensions(self, exts, force=False): """ Add/register extensions. Args: exts (dict): force (bool): If ``force`` is set to ``True``, simply overwrite existing extensions, otherwise do nothing. If the ``logger`` is set, log a warning about the ...
[ "def", "register_extensions", "(", "self", ",", "exts", ",", "force", "=", "False", ")", ":", "for", "ext_in", ",", "ext_out", "in", "exts", ".", "items", "(", ")", ":", "self", ".", "register_extension", "(", "ext_in", ",", "ext_out", ",", "force", ")...
Add/register extensions. Args: exts (dict): force (bool): If ``force`` is set to ``True``, simply overwrite existing extensions, otherwise do nothing. If the ``logger`` is set, log a warning about the duplicate extension if ``force == False``.
[ "Add", "/", "register", "extensions", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L262-L272
train
Add or register extensions.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.__add_action
def __add_action(self, relative_directory, action): """ Add action into the dictionary of actions. Args: relative_directory: action: """ generator_action_container = self.__actions.retrieve_element_or_default(relative_directory, None) if generat...
python
def __add_action(self, relative_directory, action): """ Add action into the dictionary of actions. Args: relative_directory: action: """ generator_action_container = self.__actions.retrieve_element_or_default(relative_directory, None) if generat...
[ "def", "__add_action", "(", "self", ",", "relative_directory", ",", "action", ")", ":", "generator_action_container", "=", "self", ".", "__actions", ".", "retrieve_element_or_default", "(", "relative_directory", ",", "None", ")", "if", "generator_action_container", "i...
Add action into the dictionary of actions. Args: relative_directory: action:
[ "Add", "action", "into", "the", "dictionary", "of", "actions", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L285-L301
train
Add action into the dictionary of actions.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.__is_function_action
def __is_function_action(self, action_function): """ Detect if given function is really an action function. Args: action_function: Function to test. Note: We don't care if the variable refer to a function but rather if it is callable or not. """ ...
python
def __is_function_action(self, action_function): """ Detect if given function is really an action function. Args: action_function: Function to test. Note: We don't care if the variable refer to a function but rather if it is callable or not. """ ...
[ "def", "__is_function_action", "(", "self", ",", "action_function", ")", ":", "# test if function returns a couple of values", "is_function_action", "=", "True", "if", "not", "hasattr", "(", "action_function", ",", "'__call__'", ")", ":", "return", "False", "# OK, calla...
Detect if given function is really an action function. Args: action_function: Function to test. Note: We don't care if the variable refer to a function but rather if it is callable or not.
[ "Detect", "if", "given", "function", "is", "really", "an", "action", "function", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L313-L341
train
Test if given function is really an action function.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.register_action
def register_action(self, relative_directory, file_pattern, action_function): """ Add/register an "action". Args: relative_directory (str): Relative directory from root directory. Separator is OS dependent. For instance, under linux, you can register the following: ...
python
def register_action(self, relative_directory, file_pattern, action_function): """ Add/register an "action". Args: relative_directory (str): Relative directory from root directory. Separator is OS dependent. For instance, under linux, you can register the following: ...
[ "def", "register_action", "(", "self", ",", "relative_directory", ",", "file_pattern", ",", "action_function", ")", ":", "# test if directory exists", "if", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "self", ".", "__roo...
Add/register an "action". Args: relative_directory (str): Relative directory from root directory. Separator is OS dependent. For instance, under linux, you can register the following: >>> register_action('cysparse/sparse/utils', 'find*.cpy', action_function) ...
[ "Add", "/", "register", "an", "action", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L343-L371
train
Add an action to the list of available modules.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.register_default_action
def register_default_action(self, file_pattern, action_function): """ Default action used if no compatible action is found. Args: file_pattern: A :program:`fnmatch` pattern for the files concerned by this action. action_function: Warning: Be careful...
python
def register_default_action(self, file_pattern, action_function): """ Default action used if no compatible action is found. Args: file_pattern: A :program:`fnmatch` pattern for the files concerned by this action. action_function: Warning: Be careful...
[ "def", "register_default_action", "(", "self", ",", "file_pattern", ",", "action_function", ")", ":", "if", "self", ".", "__default_action", "is", "not", "None", ":", "self", ".", "log_error", "(", "'Default action function already exist.'", ")", "if", "not", "sel...
Default action used if no compatible action is found. Args: file_pattern: A :program:`fnmatch` pattern for the files concerned by this action. action_function: Warning: Be careful when defining a default action. This action is be applied to **all** template files fo...
[ "Default", "action", "used", "if", "no", "compatible", "action", "is", "found", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L373-L393
train
Register a default action for the given file pattern.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.__generate_file
def __generate_file(self, template_filename, context, generated_filename, force=False): """ Generate **one** (source code) file from a template. The file is **only** generated if needed, i.e. if ``force`` is set to ``True`` or if generated file is older than the template file. The gener...
python
def __generate_file(self, template_filename, context, generated_filename, force=False): """ Generate **one** (source code) file from a template. The file is **only** generated if needed, i.e. if ``force`` is set to ``True`` or if generated file is older than the template file. The gener...
[ "def", "__generate_file", "(", "self", ",", "template_filename", ",", "context", ",", "generated_filename", ",", "force", "=", "False", ")", ":", "# TODO: maybe avoid reading same template file again and again... i.e. parse it once and generate all needed files without reparsing the ...
Generate **one** (source code) file from a template. The file is **only** generated if needed, i.e. if ``force`` is set to ``True`` or if generated file is older than the template file. The generated file is written in the same directory as the template file. Args: template_filenam...
[ "Generate", "**", "one", "**", "(", "source", "code", ")", "file", "from", "a", "template", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L406-L429
train
Generate one file from a template file.
PythonOptimizers/cygenja
cygenja/generator.py
Generator.generate
def generate(self, dir_pattern, file_pattern, action_ch='g', recursively=False, force=False): """ Main method to generate (source code) files from templates. See documentation about the directory and file patterns and their possible combinations. Args: dir_pattern: ``glob``...
python
def generate(self, dir_pattern, file_pattern, action_ch='g', recursively=False, force=False): """ Main method to generate (source code) files from templates. See documentation about the directory and file patterns and their possible combinations. Args: dir_pattern: ``glob``...
[ "def", "generate", "(", "self", ",", "dir_pattern", ",", "file_pattern", ",", "action_ch", "=", "'g'", ",", "recursively", "=", "False", ",", "force", "=", "False", ")", ":", "# directories to visit", "# using heavy machinery to extract absolute cleaned paths... to avoi...
Main method to generate (source code) files from templates. See documentation about the directory and file patterns and their possible combinations. Args: dir_pattern: ``glob`` pattern taken from the root directory. **Only** used for directories. file_pattern: ``fnmatch`` patte...
[ "Main", "method", "to", "generate", "(", "source", "code", ")", "files", "from", "templates", "." ]
a9ef91cdfa8452beeeec4f050f928b830379f91c
https://github.com/PythonOptimizers/cygenja/blob/a9ef91cdfa8452beeeec4f050f928b830379f91c/cygenja/generator.py#L431-L497
train
This method generates source code files from templates.
ckcollab/polished
polished/backends/simple.py
SimpleBackend.prepare_page
def prepare_page(self, *args, **kwargs): ''' This is called after the page has been loaded, good time to do extra polishing ''' super(BaseBackend, self).prepare_page(*args, **kwargs)
python
def prepare_page(self, *args, **kwargs): ''' This is called after the page has been loaded, good time to do extra polishing ''' super(BaseBackend, self).prepare_page(*args, **kwargs)
[ "def", "prepare_page", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "BaseBackend", ",", "self", ")", ".", "prepare_page", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
This is called after the page has been loaded, good time to do extra polishing
[ "This", "is", "called", "after", "the", "page", "has", "been", "loaded", "good", "time", "to", "do", "extra", "polishing" ]
5a00b2fbe569bc957d1647c0849fd344db29b644
https://github.com/ckcollab/polished/blob/5a00b2fbe569bc957d1647c0849fd344db29b644/polished/backends/simple.py#L23-L27
train
This is called before the page has been loaded.
minimind/dispatch-on-value-for-python
dispatchonvalue/dispatchonvalue.py
DispatchOnValue.add
def add(self, pattern): """Decorator to add new dispatch functions.""" def wrap(f): self.functions.append((f, pattern)) return f return wrap
python
def add(self, pattern): """Decorator to add new dispatch functions.""" def wrap(f): self.functions.append((f, pattern)) return f return wrap
[ "def", "add", "(", "self", ",", "pattern", ")", ":", "def", "wrap", "(", "f", ")", ":", "self", ".", "functions", ".", "append", "(", "(", "f", ",", "pattern", ")", ")", "return", "f", "return", "wrap" ]
Decorator to add new dispatch functions.
[ "Decorator", "to", "add", "new", "dispatch", "functions", "." ]
87e510ee00948854752dfca65264a3eefda365ca
https://github.com/minimind/dispatch-on-value-for-python/blob/87e510ee00948854752dfca65264a3eefda365ca/dispatchonvalue/dispatchonvalue.py#L67-L73
train
Decorator to add new dispatch functions.
minimind/dispatch-on-value-for-python
dispatchonvalue/dispatchonvalue.py
DispatchOnValue.add_method
def add_method(self, pattern): """Decorator to add new dispatch functions.""" def wrap(f): def frozen_function(class_instance, f): def _(pattern, *args, **kwargs): return f(class_instance, pattern, *args, **kwargs) return _ se...
python
def add_method(self, pattern): """Decorator to add new dispatch functions.""" def wrap(f): def frozen_function(class_instance, f): def _(pattern, *args, **kwargs): return f(class_instance, pattern, *args, **kwargs) return _ se...
[ "def", "add_method", "(", "self", ",", "pattern", ")", ":", "def", "wrap", "(", "f", ")", ":", "def", "frozen_function", "(", "class_instance", ",", "f", ")", ":", "def", "_", "(", "pattern", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "...
Decorator to add new dispatch functions.
[ "Decorator", "to", "add", "new", "dispatch", "functions", "." ]
87e510ee00948854752dfca65264a3eefda365ca
https://github.com/minimind/dispatch-on-value-for-python/blob/87e510ee00948854752dfca65264a3eefda365ca/dispatchonvalue/dispatchonvalue.py#L75-L87
train
Decorator to add new dispatch functions.
minimind/dispatch-on-value-for-python
dispatchonvalue/dispatchonvalue.py
DispatchOnValue.dispatch
def dispatch(self, stream, *args, **kwargs): """ Dispatch to function held internally depending upon the value of stream. Matching on directories is partial. This means dictionaries will match if all the key/value pairs in the pattern are matched - any extra pairs will be ignore...
python
def dispatch(self, stream, *args, **kwargs): """ Dispatch to function held internally depending upon the value of stream. Matching on directories is partial. This means dictionaries will match if all the key/value pairs in the pattern are matched - any extra pairs will be ignore...
[ "def", "dispatch", "(", "self", ",", "stream", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "f", ",", "pat", "in", "self", ".", "functions", ":", "matched", ",", "matched_stream", "=", "self", ".", "_match", "(", "stream", ",", "pat"...
Dispatch to function held internally depending upon the value of stream. Matching on directories is partial. This means dictionaries will match if all the key/value pairs in the pattern are matched - any extra pairs will be ignored.
[ "Dispatch", "to", "function", "held", "internally", "depending", "upon", "the", "value", "of", "stream", "." ]
87e510ee00948854752dfca65264a3eefda365ca
https://github.com/minimind/dispatch-on-value-for-python/blob/87e510ee00948854752dfca65264a3eefda365ca/dispatchonvalue/dispatchonvalue.py#L89-L103
train
Dispatch to functions held internally depending upon the value of stream.
minimind/dispatch-on-value-for-python
dispatchonvalue/dispatchonvalue.py
DispatchOnValue.dispatch_strict
def dispatch_strict(self, stream, *args, **kwargs): """ Dispatch to function held internally depending upon the value of stream. Matching on directories is strict. This means dictionaries will match if they are exactly the same. """ for f, pat in self.functions: ...
python
def dispatch_strict(self, stream, *args, **kwargs): """ Dispatch to function held internally depending upon the value of stream. Matching on directories is strict. This means dictionaries will match if they are exactly the same. """ for f, pat in self.functions: ...
[ "def", "dispatch_strict", "(", "self", ",", "stream", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "f", ",", "pat", "in", "self", ".", "functions", ":", "matched", ",", "matched_stream", "=", "self", ".", "_match", "(", "stream", ",", ...
Dispatch to function held internally depending upon the value of stream. Matching on directories is strict. This means dictionaries will match if they are exactly the same.
[ "Dispatch", "to", "function", "held", "internally", "depending", "upon", "the", "value", "of", "stream", "." ]
87e510ee00948854752dfca65264a3eefda365ca
https://github.com/minimind/dispatch-on-value-for-python/blob/87e510ee00948854752dfca65264a3eefda365ca/dispatchonvalue/dispatchonvalue.py#L105-L119
train
Dispatch to function held internally depending upon the value of stream.
DeV1doR/aioethereum
aioethereum/management/txpool.py
TxpoolMixin.txpool_status
def txpool_status(self): """https://github.com/ethereum/go-ethereum/wiki/Management-APIs#txpool_status :rtype: dict """ result = yield from self.rpc_call('txpool_status') return {k: hex_to_dec(v) for k, v in result.items()}
python
def txpool_status(self): """https://github.com/ethereum/go-ethereum/wiki/Management-APIs#txpool_status :rtype: dict """ result = yield from self.rpc_call('txpool_status') return {k: hex_to_dec(v) for k, v in result.items()}
[ "def", "txpool_status", "(", "self", ")", ":", "result", "=", "yield", "from", "self", ".", "rpc_call", "(", "'txpool_status'", ")", "return", "{", "k", ":", "hex_to_dec", "(", "v", ")", "for", "k", ",", "v", "in", "result", ".", "items", "(", ")", ...
https://github.com/ethereum/go-ethereum/wiki/Management-APIs#txpool_status :rtype: dict
[ "https", ":", "//", "github", ".", "com", "/", "ethereum", "/", "go", "-", "ethereum", "/", "wiki", "/", "Management", "-", "APIs#txpool_status" ]
85eb46550d862b3ccc309914ea871ca1c7b42157
https://github.com/DeV1doR/aioethereum/blob/85eb46550d862b3ccc309914ea871ca1c7b42157/aioethereum/management/txpool.py#L29-L35
train
Get the current status of the current txpool.
Jaymon/decorators
decorators.py
Decorator.is_wrapped_arg
def is_wrapped_arg(self, *args, **kwargs): """decide if this decorator was called with arguments (eg, @dec(...)) or without (eg, @dec) so we can take the correct path when the decorator is invoked for the most part this works except for the case where you have one callback or cl...
python
def is_wrapped_arg(self, *args, **kwargs): """decide if this decorator was called with arguments (eg, @dec(...)) or without (eg, @dec) so we can take the correct path when the decorator is invoked for the most part this works except for the case where you have one callback or cl...
[ "def", "is_wrapped_arg", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "False", "if", "len", "(", "args", ")", "==", "1", "and", "len", "(", "kwargs", ")", "==", "0", ":", "#pout.v(args, self, isinstance(args[0], type), is...
decide if this decorator was called with arguments (eg, @dec(...)) or without (eg, @dec) so we can take the correct path when the decorator is invoked for the most part this works except for the case where you have one callback or class as the only passed in method to the decorator (eg,...
[ "decide", "if", "this", "decorator", "was", "called", "with", "arguments", "(", "eg", "@dec", "(", "...", "))", "or", "without", "(", "eg", "@dec", ")", "so", "we", "can", "take", "the", "correct", "path", "when", "the", "decorator", "is", "invoked" ]
20525e93b5d259cfa9be771c43279825724c109e
https://github.com/Jaymon/decorators/blob/20525e93b5d259cfa9be771c43279825724c109e/decorators.py#L85-L124
train
decide if this decorator was called with arguments
Jaymon/decorators
decorators.py
Decorator.set_wrapped
def set_wrapped(self, wrapped): """This will decide what wrapped is and set .wrapped_func or .wrapped_class accordingly :param wrapped: either a function or class """ self.wrapped = wrapped functools.update_wrapper(self, self.wrapped, updated=()) self.wrapped_fun...
python
def set_wrapped(self, wrapped): """This will decide what wrapped is and set .wrapped_func or .wrapped_class accordingly :param wrapped: either a function or class """ self.wrapped = wrapped functools.update_wrapper(self, self.wrapped, updated=()) self.wrapped_fun...
[ "def", "set_wrapped", "(", "self", ",", "wrapped", ")", ":", "self", ".", "wrapped", "=", "wrapped", "functools", ".", "update_wrapper", "(", "self", ",", "self", ".", "wrapped", ",", "updated", "=", "(", ")", ")", "self", ".", "wrapped_func", "=", "Fa...
This will decide what wrapped is and set .wrapped_func or .wrapped_class accordingly :param wrapped: either a function or class
[ "This", "will", "decide", "what", "wrapped", "is", "and", "set", ".", "wrapped_func", "or", ".", "wrapped_class", "accordingly" ]
20525e93b5d259cfa9be771c43279825724c109e
https://github.com/Jaymon/decorators/blob/20525e93b5d259cfa9be771c43279825724c109e/decorators.py#L126-L141
train
This will decide what is wrapped and set. wrapped_func or. wrapped_class accordingly.
Jaymon/decorators
decorators.py
Decorator.decorate_func
def decorate_func(self, func, *decorator_args, **decorator_kwargs): """override this in a child class with your own logic, it must return a function that calls self.func :param func: callback -- the function being decorated :param decorator_args: tuple -- the arguments passed into the d...
python
def decorate_func(self, func, *decorator_args, **decorator_kwargs): """override this in a child class with your own logic, it must return a function that calls self.func :param func: callback -- the function being decorated :param decorator_args: tuple -- the arguments passed into the d...
[ "def", "decorate_func", "(", "self", ",", "func", ",", "*", "decorator_args", ",", "*", "*", "decorator_kwargs", ")", ":", "raise", "RuntimeError", "(", "\"decorator {} does not support function decoration\"", ".", "format", "(", "self", ".", "__class__", ".", "__...
override this in a child class with your own logic, it must return a function that calls self.func :param func: callback -- the function being decorated :param decorator_args: tuple -- the arguments passed into the decorator (eg, @dec(1, 2)) :param decorator_kwargs: dict -- the named ar...
[ "override", "this", "in", "a", "child", "class", "with", "your", "own", "logic", "it", "must", "return", "a", "function", "that", "calls", "self", ".", "func" ]
20525e93b5d259cfa9be771c43279825724c109e
https://github.com/Jaymon/decorators/blob/20525e93b5d259cfa9be771c43279825724c109e/decorators.py#L198-L210
train
decorator for the function that returns a function that calls func with the decorated arguments and keyword arguments
Jaymon/decorators
decorators.py
Decorator.decorate_class
def decorate_class(self, klass, *decorator_args, **decorator_kwargs): """override this in a child class with your own logic, it must return a function that returns klass or the like :param klass: the class object that is being decorated :param decorator_args: tuple -- the arguments pass...
python
def decorate_class(self, klass, *decorator_args, **decorator_kwargs): """override this in a child class with your own logic, it must return a function that returns klass or the like :param klass: the class object that is being decorated :param decorator_args: tuple -- the arguments pass...
[ "def", "decorate_class", "(", "self", ",", "klass", ",", "*", "decorator_args", ",", "*", "*", "decorator_kwargs", ")", ":", "raise", "RuntimeError", "(", "\"decorator {} does not support class decoration\"", ".", "format", "(", "self", ".", "__class__", ".", "__n...
override this in a child class with your own logic, it must return a function that returns klass or the like :param klass: the class object that is being decorated :param decorator_args: tuple -- the arguments passed into the decorator (eg, @dec(1, 2)) :param decorator_kwargs: dict -- t...
[ "override", "this", "in", "a", "child", "class", "with", "your", "own", "logic", "it", "must", "return", "a", "function", "that", "returns", "klass", "or", "the", "like" ]
20525e93b5d259cfa9be771c43279825724c109e
https://github.com/Jaymon/decorators/blob/20525e93b5d259cfa9be771c43279825724c109e/decorators.py#L212-L222
train
override this in a child class with your own logic it must return a function that returns klass or the like function that returns klass
Jaymon/decorators
decorators.py
InstanceDecorator.decorate_class
def decorate_class(self, klass, *decorator_args, **decorator_kwargs): """where the magic happens, this wraps a class to call our decorate method in the init of the class """ class ChildClass(klass): def __init__(slf, *args, **kwargs): super(ChildClass, slf).__...
python
def decorate_class(self, klass, *decorator_args, **decorator_kwargs): """where the magic happens, this wraps a class to call our decorate method in the init of the class """ class ChildClass(klass): def __init__(slf, *args, **kwargs): super(ChildClass, slf).__...
[ "def", "decorate_class", "(", "self", ",", "klass", ",", "*", "decorator_args", ",", "*", "*", "decorator_kwargs", ")", ":", "class", "ChildClass", "(", "klass", ")", ":", "def", "__init__", "(", "slf", ",", "*", "args", ",", "*", "*", "kwargs", ")", ...
where the magic happens, this wraps a class to call our decorate method in the init of the class
[ "where", "the", "magic", "happens", "this", "wraps", "a", "class", "to", "call", "our", "decorate", "method", "in", "the", "init", "of", "the", "class" ]
20525e93b5d259cfa9be771c43279825724c109e
https://github.com/Jaymon/decorators/blob/20525e93b5d259cfa9be771c43279825724c109e/decorators.py#L238-L255
train
this is a class decorator that will be used to decorate the class with the decorated method
Jaymon/decorators
decorators.py
FuncDecorator.decorate
def decorate(self, func, *decorator_args, **decorator_kwargs): """ override this in a child class with your own logic, it must return a function that calls self.func :param func: callback -- the function being decorated :param decorator_args: tuple -- the arguments passed into t...
python
def decorate(self, func, *decorator_args, **decorator_kwargs): """ override this in a child class with your own logic, it must return a function that calls self.func :param func: callback -- the function being decorated :param decorator_args: tuple -- the arguments passed into t...
[ "def", "decorate", "(", "self", ",", "func", ",", "*", "decorator_args", ",", "*", "*", "decorator_kwargs", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs"...
override this in a child class with your own logic, it must return a function that calls self.func :param func: callback -- the function being decorated :param decorator_args: tuple -- the arguments passed into the decorator (eg, @dec(1, 2)) :param decorator_kwargs: dict -- the named ar...
[ "override", "this", "in", "a", "child", "class", "with", "your", "own", "logic", "it", "must", "return", "a", "function", "that", "calls", "self", ".", "func" ]
20525e93b5d259cfa9be771c43279825724c109e
https://github.com/Jaymon/decorators/blob/20525e93b5d259cfa9be771c43279825724c109e/decorators.py#L277-L288
train
Decorator for the a method
ludeeus/GHLocalApi
examples/get_device_info.py
device_info
async def device_info(): """Get device info from GH.""" async with aiohttp.ClientSession() as session: ghlocalapi = DeviceInfo(LOOP, session, IPADDRESS) await ghlocalapi.get_device_info() print("Device info:", ghlocalapi.device_info)
python
async def device_info(): """Get device info from GH.""" async with aiohttp.ClientSession() as session: ghlocalapi = DeviceInfo(LOOP, session, IPADDRESS) await ghlocalapi.get_device_info() print("Device info:", ghlocalapi.device_info)
[ "async", "def", "device_info", "(", ")", ":", "async", "with", "aiohttp", ".", "ClientSession", "(", ")", "as", "session", ":", "ghlocalapi", "=", "DeviceInfo", "(", "LOOP", ",", "session", ",", "IPADDRESS", ")", "await", "ghlocalapi", ".", "get_device_info"...
Get device info from GH.
[ "Get", "device", "info", "from", "GH", "." ]
93abdee299c4a4b65aa9dd03c77ec34e174e3c56
https://github.com/ludeeus/GHLocalApi/blob/93abdee299c4a4b65aa9dd03c77ec34e174e3c56/examples/get_device_info.py#L9-L15
train
Get device info from GH.
noahbenson/pimms
pimms/calculation.py
plan
def plan(*args, **kwargs): ''' plan(name1=calcs1, name2=calc2...) yields a new calculation plan (object of type Plan) that is itself a constructor for the calculation dictionary that is implied by the given calc functionss given. The names that are given are used as identifiers for updating th...
python
def plan(*args, **kwargs): ''' plan(name1=calcs1, name2=calc2...) yields a new calculation plan (object of type Plan) that is itself a constructor for the calculation dictionary that is implied by the given calc functionss given. The names that are given are used as identifiers for updating th...
[ "def", "plan", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "1", "and", "len", "(", "kwargs", ")", "==", "0", "and", "is_imap", "(", "args", "[", "0", "]", ")", ":", "return", "args", "[", "0", "...
plan(name1=calcs1, name2=calc2...) yields a new calculation plan (object of type Plan) that is itself a constructor for the calculation dictionary that is implied by the given calc functionss given. The names that are given are used as identifiers for updating the calc plan (using the without and usin...
[ "plan", "(", "name1", "=", "calcs1", "name2", "=", "calc2", "...", ")", "yields", "a", "new", "calculation", "plan", "(", "object", "of", "type", "Plan", ")", "that", "is", "itself", "a", "constructor", "for", "the", "calculation", "dictionary", "that", ...
9051b86d6b858a7a13511b72c48dc21bc903dab2
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/calculation.py#L697-L712
train
Returns a new calculation plan object that is a constructor for the given calculation dictionary and the given arguments.
noahbenson/pimms
pimms/calculation.py
planfn
def planfn(*args, **kwargs): ''' planfn(val1=fn1, val2=fn2...) uses the pimms plan mechanism to yield a function f that produces an immutable imap when called with the correct paramters. Unlike in plan(), planfn() does not care about the names of the calculation units; instead the val1, val2, etc. a...
python
def planfn(*args, **kwargs): ''' planfn(val1=fn1, val2=fn2...) uses the pimms plan mechanism to yield a function f that produces an immutable imap when called with the correct paramters. Unlike in plan(), planfn() does not care about the names of the calculation units; instead the val1, val2, etc. a...
[ "def", "planfn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# first: parse options", "if", "len", "(", "args", ")", ">", "2", ":", "raise", "ValueError", "(", "'no more than 2 non-keyword arguments allowed'", ")", "elif", "len", "(", "args", ")", ...
planfn(val1=fn1, val2=fn2...) uses the pimms plan mechanism to yield a function f that produces an immutable imap when called with the correct paramters. Unlike in plan(), planfn() does not care about the names of the calculation units; instead the val1, val2, etc. are names of the efferent values whi...
[ "planfn", "(", "val1", "=", "fn1", "val2", "=", "fn2", "...", ")", "uses", "the", "pimms", "plan", "mechanism", "to", "yield", "a", "function", "f", "that", "produces", "an", "immutable", "imap", "when", "called", "with", "the", "correct", "paramters", "...
9051b86d6b858a7a13511b72c48dc21bc903dab2
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/calculation.py#L713-L758
train
This function provides a function f that produces a immutable imap when called with the correct paramters.
noahbenson/pimms
pimms/calculation.py
imap
def imap(p, *args, **kwargs): ''' imap(p, args...) yields an immutable map object made from the plan object p and the given arguments, which may be any number of mappings followed by any number of keyword arguments, all of which are merged left-to-right then interpreted as the parameters of the given pl...
python
def imap(p, *args, **kwargs): ''' imap(p, args...) yields an immutable map object made from the plan object p and the given arguments, which may be any number of mappings followed by any number of keyword arguments, all of which are merged left-to-right then interpreted as the parameters of the given pl...
[ "def", "imap", "(", "p", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "p", "=", "p", "if", "is_plan", "(", "p", ")", "else", "plan", "(", "p", ")", "params", "=", "merge", "(", "args", ",", "kwargs", ")", "return", "p", "(", "params",...
imap(p, args...) yields an immutable map object made from the plan object p and the given arguments, which may be any number of mappings followed by any number of keyword arguments, all of which are merged left-to-right then interpreted as the parameters of the given plan p.
[ "imap", "(", "p", "args", "...", ")", "yields", "an", "immutable", "map", "object", "made", "from", "the", "plan", "object", "p", "and", "the", "given", "arguments", "which", "may", "be", "any", "number", "of", "mappings", "followed", "by", "any", "numbe...
9051b86d6b858a7a13511b72c48dc21bc903dab2
https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/calculation.py#L759-L767
train
Returns an immutable map object made from a plan object p and the given arguments.