id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
249,800
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.choose_schema
def choose_schema(self, out_file): """ Finds all schema templates and prompts to choose one. Copies the file to self.lazy_folder. """ path = os.path.dirname(lazyconf.__file__) + '/schema/' self.prompt.header('Choose a template for your config file: ') i = 0 choices = [] for filename in os.listdir(path): if filename.endswith('.json'): try: template = self._load(path + filename) description = template.get('_meta.description') prompt_string = str(i + 1) + '. ' + filename i += 1 if description: self.prompt.notice(prompt_string + ': ' + description) else: self.prompt.notice(prompt_string) choices.append(template) except IOError as e: print self.prompt.error(str(e)) val = 0 while val is 0 or val > i: val = self.prompt.int('Choice', default = 1) if val is 0 or val > i: self.prompt.error('Please choose a value between 1 and ' + str(i) + '.') schema = choices[val-1] if '_meta' in schema.data.keys(): del(schema.data['_meta']) schema.save(out_file, as_schema=True) sp, sf = os.path.split(out_file) self.prompt.success('Saved to ' + self.lazy_folder + sf + '.') return schema
python
def choose_schema(self, out_file): """ Finds all schema templates and prompts to choose one. Copies the file to self.lazy_folder. """ path = os.path.dirname(lazyconf.__file__) + '/schema/' self.prompt.header('Choose a template for your config file: ') i = 0 choices = [] for filename in os.listdir(path): if filename.endswith('.json'): try: template = self._load(path + filename) description = template.get('_meta.description') prompt_string = str(i + 1) + '. ' + filename i += 1 if description: self.prompt.notice(prompt_string + ': ' + description) else: self.prompt.notice(prompt_string) choices.append(template) except IOError as e: print self.prompt.error(str(e)) val = 0 while val is 0 or val > i: val = self.prompt.int('Choice', default = 1) if val is 0 or val > i: self.prompt.error('Please choose a value between 1 and ' + str(i) + '.') schema = choices[val-1] if '_meta' in schema.data.keys(): del(schema.data['_meta']) schema.save(out_file, as_schema=True) sp, sf = os.path.split(out_file) self.prompt.success('Saved to ' + self.lazy_folder + sf + '.') return schema
[ "def", "choose_schema", "(", "self", ",", "out_file", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "lazyconf", ".", "__file__", ")", "+", "'/schema/'", "self", ".", "prompt", ".", "header", "(", "'Choose a template for your config file: '", ")", "i", "=", "0", "choices", "=", "[", "]", "for", "filename", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", "filename", ".", "endswith", "(", "'.json'", ")", ":", "try", ":", "template", "=", "self", ".", "_load", "(", "path", "+", "filename", ")", "description", "=", "template", ".", "get", "(", "'_meta.description'", ")", "prompt_string", "=", "str", "(", "i", "+", "1", ")", "+", "'. '", "+", "filename", "i", "+=", "1", "if", "description", ":", "self", ".", "prompt", ".", "notice", "(", "prompt_string", "+", "': '", "+", "description", ")", "else", ":", "self", ".", "prompt", ".", "notice", "(", "prompt_string", ")", "choices", ".", "append", "(", "template", ")", "except", "IOError", "as", "e", ":", "print", "self", ".", "prompt", ".", "error", "(", "str", "(", "e", ")", ")", "val", "=", "0", "while", "val", "is", "0", "or", "val", ">", "i", ":", "val", "=", "self", ".", "prompt", ".", "int", "(", "'Choice'", ",", "default", "=", "1", ")", "if", "val", "is", "0", "or", "val", ">", "i", ":", "self", ".", "prompt", ".", "error", "(", "'Please choose a value between 1 and '", "+", "str", "(", "i", ")", "+", "'.'", ")", "schema", "=", "choices", "[", "val", "-", "1", "]", "if", "'_meta'", "in", "schema", ".", "data", ".", "keys", "(", ")", ":", "del", "(", "schema", ".", "data", "[", "'_meta'", "]", ")", "schema", ".", "save", "(", "out_file", ",", "as_schema", "=", "True", ")", "sp", ",", "sf", "=", "os", ".", "path", ".", "split", "(", "out_file", ")", "self", ".", "prompt", ".", "success", "(", "'Saved to '", "+", "self", ".", "lazy_folder", "+", "sf", "+", "'.'", ")", "return", "schema" ]
Finds all schema templates and prompts to choose one. Copies the file to self.lazy_folder.
[ "Finds", "all", "schema", "templates", "and", "prompts", "to", "choose", "one", ".", "Copies", "the", "file", "to", "self", ".", "lazy_folder", "." ]
78e94320c7ff2c08988df04b4e43968f0a7ae06e
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L56-L97
249,801
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.configure_data
def configure_data(self, data, key_string = ''): """ Goes through all the options in `data`, and prompts new values. This function calls itself recursively if it finds an inner dictionary. Arguments: data -- The dictionary to loop through. key_string -- The dot-notated key of the dictionary being checked through. """ # If there's no keys in this dictionary, we have nothing to do. if len(data.keys()) == 0: return # Split the key string by its dots to find out how deep we are. key_parts = key_string.rsplit('.') prefix = ' ' * (len(key_parts) - 1) # Attempt to get a label for this key string. label = self.data.get_label(key_string) # If we are have any key string or label, write the header for this section. if label: p = prefix if len(p) > 0: p += ' ' self.prompt.header(p + '[' + label + ']') # Add to the prefix to indicate options on this level. prefix = prefix + ' ' # If this section has an '_enabled' key, process it first, as it could enable or disable this whole section. if '_enabled' in data.keys(): s = self.data.get_key_string(key_string, '_enabled') #Prompt whether to enable this section. Use the existing value as the default. data['_enabled'] = self.prompt.bool(prefix + self.data.get_label(s), None, data['_enabled']) # Return if this section is now disabled. if data['_enabled'] is False: return # Loop through the rest of the dictionary and prompt for every key. If the value is a dictionary, call this function again for the next level. for k, v in data.iteritems(): # If we hit the '_enabled' key, we've already processed it (but still need it in the dictionary for saving). Ignore it. if k == '_enabled': continue # Get the type of the value at this key, and the dot-noted format of this key. t = type(v) s = self.data.get_key_string(key_string, k) # If the value type is a dictionary, call this function. if t is dict: self.configure_data(v, s) # Otherwise, parse the value. else: label = prefix + self.data.get_label(s) self.parse_value(data, label, s, None, v)
python
def configure_data(self, data, key_string = ''): """ Goes through all the options in `data`, and prompts new values. This function calls itself recursively if it finds an inner dictionary. Arguments: data -- The dictionary to loop through. key_string -- The dot-notated key of the dictionary being checked through. """ # If there's no keys in this dictionary, we have nothing to do. if len(data.keys()) == 0: return # Split the key string by its dots to find out how deep we are. key_parts = key_string.rsplit('.') prefix = ' ' * (len(key_parts) - 1) # Attempt to get a label for this key string. label = self.data.get_label(key_string) # If we are have any key string or label, write the header for this section. if label: p = prefix if len(p) > 0: p += ' ' self.prompt.header(p + '[' + label + ']') # Add to the prefix to indicate options on this level. prefix = prefix + ' ' # If this section has an '_enabled' key, process it first, as it could enable or disable this whole section. if '_enabled' in data.keys(): s = self.data.get_key_string(key_string, '_enabled') #Prompt whether to enable this section. Use the existing value as the default. data['_enabled'] = self.prompt.bool(prefix + self.data.get_label(s), None, data['_enabled']) # Return if this section is now disabled. if data['_enabled'] is False: return # Loop through the rest of the dictionary and prompt for every key. If the value is a dictionary, call this function again for the next level. for k, v in data.iteritems(): # If we hit the '_enabled' key, we've already processed it (but still need it in the dictionary for saving). Ignore it. if k == '_enabled': continue # Get the type of the value at this key, and the dot-noted format of this key. t = type(v) s = self.data.get_key_string(key_string, k) # If the value type is a dictionary, call this function. if t is dict: self.configure_data(v, s) # Otherwise, parse the value. else: label = prefix + self.data.get_label(s) self.parse_value(data, label, s, None, v)
[ "def", "configure_data", "(", "self", ",", "data", ",", "key_string", "=", "''", ")", ":", "# If there's no keys in this dictionary, we have nothing to do.", "if", "len", "(", "data", ".", "keys", "(", ")", ")", "==", "0", ":", "return", "# Split the key string by its dots to find out how deep we are.", "key_parts", "=", "key_string", ".", "rsplit", "(", "'.'", ")", "prefix", "=", "' '", "*", "(", "len", "(", "key_parts", ")", "-", "1", ")", "# Attempt to get a label for this key string.", "label", "=", "self", ".", "data", ".", "get_label", "(", "key_string", ")", "# If we are have any key string or label, write the header for this section.", "if", "label", ":", "p", "=", "prefix", "if", "len", "(", "p", ")", ">", "0", ":", "p", "+=", "' '", "self", ".", "prompt", ".", "header", "(", "p", "+", "'['", "+", "label", "+", "']'", ")", "# Add to the prefix to indicate options on this level.", "prefix", "=", "prefix", "+", "' '", "# If this section has an '_enabled' key, process it first, as it could enable or disable this whole section.", "if", "'_enabled'", "in", "data", ".", "keys", "(", ")", ":", "s", "=", "self", ".", "data", ".", "get_key_string", "(", "key_string", ",", "'_enabled'", ")", "#Prompt whether to enable this section. Use the existing value as the default.", "data", "[", "'_enabled'", "]", "=", "self", ".", "prompt", ".", "bool", "(", "prefix", "+", "self", ".", "data", ".", "get_label", "(", "s", ")", ",", "None", ",", "data", "[", "'_enabled'", "]", ")", "# Return if this section is now disabled.", "if", "data", "[", "'_enabled'", "]", "is", "False", ":", "return", "# Loop through the rest of the dictionary and prompt for every key. If the value is a dictionary, call this function again for the next level.", "for", "k", ",", "v", "in", "data", ".", "iteritems", "(", ")", ":", "# If we hit the '_enabled' key, we've already processed it (but still need it in the dictionary for saving). Ignore it.", "if", "k", "==", "'_enabled'", ":", "continue", "# Get the type of the value at this key, and the dot-noted format of this key.", "t", "=", "type", "(", "v", ")", "s", "=", "self", ".", "data", ".", "get_key_string", "(", "key_string", ",", "k", ")", "# If the value type is a dictionary, call this function.", "if", "t", "is", "dict", ":", "self", ".", "configure_data", "(", "v", ",", "s", ")", "# Otherwise, parse the value.", "else", ":", "label", "=", "prefix", "+", "self", ".", "data", ".", "get_label", "(", "s", ")", "self", ".", "parse_value", "(", "data", ",", "label", ",", "s", ",", "None", ",", "v", ")" ]
Goes through all the options in `data`, and prompts new values. This function calls itself recursively if it finds an inner dictionary. Arguments: data -- The dictionary to loop through. key_string -- The dot-notated key of the dictionary being checked through.
[ "Goes", "through", "all", "the", "options", "in", "data", "and", "prompts", "new", "values", ".", "This", "function", "calls", "itself", "recursively", "if", "it", "finds", "an", "inner", "dictionary", "." ]
78e94320c7ff2c08988df04b4e43968f0a7ae06e
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L99-L158
249,802
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.configure
def configure(self): """ The main configure function. Uses a schema file and an optional data file, and combines them with user prompts to write a new data file. """ # Make the lazy folder if it doesn't already exist. path = os.getcwd() + '/' + self.lazy_folder if not os.path.exists(path): os.makedirs(path) schema_file = self.schema_file data_file = self.data_file # Initialise the schema and data objects. schema, data = Schema(), Schema() # Load the schema from a file. try: schema.load(schema_file) except IOError as e: # If we can't load the schema, choose from templates. self.prompt.error("Could not find schema in " + schema_file + " - Choosing from default templates...") schema = self.choose_schema(schema_file) except (Exception, ValueError) as e: self.prompt.error("Error: " + str(e) + " - Aborting...") return False else: sp, sf = os.path.split(schema_file) self.prompt.success('Loaded schema from ' + self.lazy_folder + sf) # Load the data from a file. try: data.load(data_file) except (Exception, IOError, ValueError) as e: self.prompt.error('Could not find data file. Copying from schema...') else: sp, sf = os.path.split(data_file) self.prompt.success('Loaded data from ' + self.lazy_folder + sf) # Store the internals of the schema (labels, selects, etc.) in data. data.internal = schema.internal # If we have data from a data file, merge the schema file into it. if data.data: # Create a new Merge instance using the data from the schema and data files. m = Merge(schema.data, data.data) mods = m.merge() for a in mods['added']: self.prompt.success('Added ' + a + ' to data.') for r in mods['removed']: self.prompt.error('Removed ' + r + ' from data.') for k,m in mods['modified']: self.prompt.notice('Modified ' + k + ': ' + m[0] + ' became ' + m[1] + '.' ) # Otherwise, reference the data from the schema file verbatim. else: data.data = schema.data # Store the data. self.data = data # Configure the data. self.configure_data(data.data) # Save the data to the out file. self.data.save(self.data_file) self.add_ignore() sp, sf = os.path.split(self.data_file) self.prompt.success('Saved to ' + self.lazy_folder + sf + '.')
python
def configure(self): """ The main configure function. Uses a schema file and an optional data file, and combines them with user prompts to write a new data file. """ # Make the lazy folder if it doesn't already exist. path = os.getcwd() + '/' + self.lazy_folder if not os.path.exists(path): os.makedirs(path) schema_file = self.schema_file data_file = self.data_file # Initialise the schema and data objects. schema, data = Schema(), Schema() # Load the schema from a file. try: schema.load(schema_file) except IOError as e: # If we can't load the schema, choose from templates. self.prompt.error("Could not find schema in " + schema_file + " - Choosing from default templates...") schema = self.choose_schema(schema_file) except (Exception, ValueError) as e: self.prompt.error("Error: " + str(e) + " - Aborting...") return False else: sp, sf = os.path.split(schema_file) self.prompt.success('Loaded schema from ' + self.lazy_folder + sf) # Load the data from a file. try: data.load(data_file) except (Exception, IOError, ValueError) as e: self.prompt.error('Could not find data file. Copying from schema...') else: sp, sf = os.path.split(data_file) self.prompt.success('Loaded data from ' + self.lazy_folder + sf) # Store the internals of the schema (labels, selects, etc.) in data. data.internal = schema.internal # If we have data from a data file, merge the schema file into it. if data.data: # Create a new Merge instance using the data from the schema and data files. m = Merge(schema.data, data.data) mods = m.merge() for a in mods['added']: self.prompt.success('Added ' + a + ' to data.') for r in mods['removed']: self.prompt.error('Removed ' + r + ' from data.') for k,m in mods['modified']: self.prompt.notice('Modified ' + k + ': ' + m[0] + ' became ' + m[1] + '.' ) # Otherwise, reference the data from the schema file verbatim. else: data.data = schema.data # Store the data. self.data = data # Configure the data. self.configure_data(data.data) # Save the data to the out file. self.data.save(self.data_file) self.add_ignore() sp, sf = os.path.split(self.data_file) self.prompt.success('Saved to ' + self.lazy_folder + sf + '.')
[ "def", "configure", "(", "self", ")", ":", "# Make the lazy folder if it doesn't already exist.", "path", "=", "os", ".", "getcwd", "(", ")", "+", "'/'", "+", "self", ".", "lazy_folder", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "schema_file", "=", "self", ".", "schema_file", "data_file", "=", "self", ".", "data_file", "# Initialise the schema and data objects.", "schema", ",", "data", "=", "Schema", "(", ")", ",", "Schema", "(", ")", "# Load the schema from a file.", "try", ":", "schema", ".", "load", "(", "schema_file", ")", "except", "IOError", "as", "e", ":", "# If we can't load the schema, choose from templates.", "self", ".", "prompt", ".", "error", "(", "\"Could not find schema in \"", "+", "schema_file", "+", "\" - Choosing from default templates...\"", ")", "schema", "=", "self", ".", "choose_schema", "(", "schema_file", ")", "except", "(", "Exception", ",", "ValueError", ")", "as", "e", ":", "self", ".", "prompt", ".", "error", "(", "\"Error: \"", "+", "str", "(", "e", ")", "+", "\" - Aborting...\"", ")", "return", "False", "else", ":", "sp", ",", "sf", "=", "os", ".", "path", ".", "split", "(", "schema_file", ")", "self", ".", "prompt", ".", "success", "(", "'Loaded schema from '", "+", "self", ".", "lazy_folder", "+", "sf", ")", "# Load the data from a file.", "try", ":", "data", ".", "load", "(", "data_file", ")", "except", "(", "Exception", ",", "IOError", ",", "ValueError", ")", "as", "e", ":", "self", ".", "prompt", ".", "error", "(", "'Could not find data file. Copying from schema...'", ")", "else", ":", "sp", ",", "sf", "=", "os", ".", "path", ".", "split", "(", "data_file", ")", "self", ".", "prompt", ".", "success", "(", "'Loaded data from '", "+", "self", ".", "lazy_folder", "+", "sf", ")", "# Store the internals of the schema (labels, selects, etc.) in data.", "data", ".", "internal", "=", "schema", ".", "internal", "# If we have data from a data file, merge the schema file into it.", "if", "data", ".", "data", ":", "# Create a new Merge instance using the data from the schema and data files.", "m", "=", "Merge", "(", "schema", ".", "data", ",", "data", ".", "data", ")", "mods", "=", "m", ".", "merge", "(", ")", "for", "a", "in", "mods", "[", "'added'", "]", ":", "self", ".", "prompt", ".", "success", "(", "'Added '", "+", "a", "+", "' to data.'", ")", "for", "r", "in", "mods", "[", "'removed'", "]", ":", "self", ".", "prompt", ".", "error", "(", "'Removed '", "+", "r", "+", "' from data.'", ")", "for", "k", ",", "m", "in", "mods", "[", "'modified'", "]", ":", "self", ".", "prompt", ".", "notice", "(", "'Modified '", "+", "k", "+", "': '", "+", "m", "[", "0", "]", "+", "' became '", "+", "m", "[", "1", "]", "+", "'.'", ")", "# Otherwise, reference the data from the schema file verbatim.", "else", ":", "data", ".", "data", "=", "schema", ".", "data", "# Store the data.", "self", ".", "data", "=", "data", "# Configure the data.", "self", ".", "configure_data", "(", "data", ".", "data", ")", "# Save the data to the out file.", "self", ".", "data", ".", "save", "(", "self", ".", "data_file", ")", "self", ".", "add_ignore", "(", ")", "sp", ",", "sf", "=", "os", ".", "path", ".", "split", "(", "self", ".", "data_file", ")", "self", ".", "prompt", ".", "success", "(", "'Saved to '", "+", "self", ".", "lazy_folder", "+", "sf", "+", "'.'", ")" ]
The main configure function. Uses a schema file and an optional data file, and combines them with user prompts to write a new data file.
[ "The", "main", "configure", "function", ".", "Uses", "a", "schema", "file", "and", "an", "optional", "data", "file", "and", "combines", "them", "with", "user", "prompts", "to", "write", "a", "new", "data", "file", "." ]
78e94320c7ff2c08988df04b4e43968f0a7ae06e
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L160-L234
249,803
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.parse_value
def parse_value(self, inner_dict, label, key, value, default): """ Parses a single value and sets it in an inner dictionary. Arguments: inner_dict -- The dictionary containing the value to set label -- The label to show for the prompt. key -- The key in the dictionary to set the value for. value -- The value to set. If there is a value, don't prompt for one. default -- The default value in the prompt. This is taken from the schema and defines the type of the value. """ t = type(default) if t is dict: return select = self.data.get_select(key) k = key.split('.')[-1] if select: inner_dict[k] = self.prompt.select(label, select, value, default = default) # If the value type is a boolean, prompt a boolean. elif t is bool: inner_dict[k] = self.prompt.bool(label, value, default = default) # If the value is an int, prompt and int. elif t is int: inner_dict[k] = self.prompt.int(label, value, default = default) # If someone has put a list in data, we default it to an empty string. If it had come from the schema, it would already be a string. elif t is list: inner_dict[k] = self.prompt.prompt(label + ':', value, default = '') # If none of the above are true, it's a string. else: inner_dict[k] = self.prompt.prompt(label + ':', value, default = default)
python
def parse_value(self, inner_dict, label, key, value, default): """ Parses a single value and sets it in an inner dictionary. Arguments: inner_dict -- The dictionary containing the value to set label -- The label to show for the prompt. key -- The key in the dictionary to set the value for. value -- The value to set. If there is a value, don't prompt for one. default -- The default value in the prompt. This is taken from the schema and defines the type of the value. """ t = type(default) if t is dict: return select = self.data.get_select(key) k = key.split('.')[-1] if select: inner_dict[k] = self.prompt.select(label, select, value, default = default) # If the value type is a boolean, prompt a boolean. elif t is bool: inner_dict[k] = self.prompt.bool(label, value, default = default) # If the value is an int, prompt and int. elif t is int: inner_dict[k] = self.prompt.int(label, value, default = default) # If someone has put a list in data, we default it to an empty string. If it had come from the schema, it would already be a string. elif t is list: inner_dict[k] = self.prompt.prompt(label + ':', value, default = '') # If none of the above are true, it's a string. else: inner_dict[k] = self.prompt.prompt(label + ':', value, default = default)
[ "def", "parse_value", "(", "self", ",", "inner_dict", ",", "label", ",", "key", ",", "value", ",", "default", ")", ":", "t", "=", "type", "(", "default", ")", "if", "t", "is", "dict", ":", "return", "select", "=", "self", ".", "data", ".", "get_select", "(", "key", ")", "k", "=", "key", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "if", "select", ":", "inner_dict", "[", "k", "]", "=", "self", ".", "prompt", ".", "select", "(", "label", ",", "select", ",", "value", ",", "default", "=", "default", ")", "# If the value type is a boolean, prompt a boolean.", "elif", "t", "is", "bool", ":", "inner_dict", "[", "k", "]", "=", "self", ".", "prompt", ".", "bool", "(", "label", ",", "value", ",", "default", "=", "default", ")", "# If the value is an int, prompt and int.", "elif", "t", "is", "int", ":", "inner_dict", "[", "k", "]", "=", "self", ".", "prompt", ".", "int", "(", "label", ",", "value", ",", "default", "=", "default", ")", "# If someone has put a list in data, we default it to an empty string. If it had come from the schema, it would already be a string.", "elif", "t", "is", "list", ":", "inner_dict", "[", "k", "]", "=", "self", ".", "prompt", ".", "prompt", "(", "label", "+", "':'", ",", "value", ",", "default", "=", "''", ")", "# If none of the above are true, it's a string.", "else", ":", "inner_dict", "[", "k", "]", "=", "self", ".", "prompt", ".", "prompt", "(", "label", "+", "':'", ",", "value", ",", "default", "=", "default", ")" ]
Parses a single value and sets it in an inner dictionary. Arguments: inner_dict -- The dictionary containing the value to set label -- The label to show for the prompt. key -- The key in the dictionary to set the value for. value -- The value to set. If there is a value, don't prompt for one. default -- The default value in the prompt. This is taken from the schema and defines the type of the value.
[ "Parses", "a", "single", "value", "and", "sets", "it", "in", "an", "inner", "dictionary", "." ]
78e94320c7ff2c08988df04b4e43968f0a7ae06e
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L236-L271
249,804
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.set
def set(self, key, value): """ Sets a single value in a preconfigured data file. Arguments: key -- The full dot-notated key to set the value for. value -- The value to set. """ d = self.data.data keys = key.split('.') latest = keys.pop() for k in keys: d = d.setdefault(k, {}) schema = Schema().load(self.schema_file) self.data.internal = schema.internal self.parse_value(d, '', key, value, schema.get(key)) self.data.save(self.data_file)
python
def set(self, key, value): """ Sets a single value in a preconfigured data file. Arguments: key -- The full dot-notated key to set the value for. value -- The value to set. """ d = self.data.data keys = key.split('.') latest = keys.pop() for k in keys: d = d.setdefault(k, {}) schema = Schema().load(self.schema_file) self.data.internal = schema.internal self.parse_value(d, '', key, value, schema.get(key)) self.data.save(self.data_file)
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "d", "=", "self", ".", "data", ".", "data", "keys", "=", "key", ".", "split", "(", "'.'", ")", "latest", "=", "keys", ".", "pop", "(", ")", "for", "k", "in", "keys", ":", "d", "=", "d", ".", "setdefault", "(", "k", ",", "{", "}", ")", "schema", "=", "Schema", "(", ")", ".", "load", "(", "self", ".", "schema_file", ")", "self", ".", "data", ".", "internal", "=", "schema", ".", "internal", "self", ".", "parse_value", "(", "d", ",", "''", ",", "key", ",", "value", ",", "schema", ".", "get", "(", "key", ")", ")", "self", ".", "data", ".", "save", "(", "self", ".", "data_file", ")" ]
Sets a single value in a preconfigured data file. Arguments: key -- The full dot-notated key to set the value for. value -- The value to set.
[ "Sets", "a", "single", "value", "in", "a", "preconfigured", "data", "file", "." ]
78e94320c7ff2c08988df04b4e43968f0a7ae06e
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L273-L290
249,805
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf._load
def _load(self, data_file): """ Internal load function. Creates the object and returns it. Arguments: data_file -- The filename to load. """ # Load the data from a file. try: data = Schema().load(data_file) except (Exception, IOError, ValueError) as e: raise e return data
python
def _load(self, data_file): """ Internal load function. Creates the object and returns it. Arguments: data_file -- The filename to load. """ # Load the data from a file. try: data = Schema().load(data_file) except (Exception, IOError, ValueError) as e: raise e return data
[ "def", "_load", "(", "self", ",", "data_file", ")", ":", "# Load the data from a file.", "try", ":", "data", "=", "Schema", "(", ")", ".", "load", "(", "data_file", ")", "except", "(", "Exception", ",", "IOError", ",", "ValueError", ")", "as", "e", ":", "raise", "e", "return", "data" ]
Internal load function. Creates the object and returns it. Arguments: data_file -- The filename to load.
[ "Internal", "load", "function", ".", "Creates", "the", "object", "and", "returns", "it", "." ]
78e94320c7ff2c08988df04b4e43968f0a7ae06e
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L301-L314
249,806
fmd/lazyconf
lazyconf/lazyconf.py
Lazyconf.load
def load(self, data_file = None): """ Loads a data file and sets it to self.data. Arguments: data_file -- The filename to load. """ if not data_file: data_file = '' elif data_file[-1] != '/': data_file += '/' if data_file[-6:] != self.lazy_folder: data_file += self.lazy_folder data_file += self.data_filename self.data = self._load(data_file) return self
python
def load(self, data_file = None): """ Loads a data file and sets it to self.data. Arguments: data_file -- The filename to load. """ if not data_file: data_file = '' elif data_file[-1] != '/': data_file += '/' if data_file[-6:] != self.lazy_folder: data_file += self.lazy_folder data_file += self.data_filename self.data = self._load(data_file) return self
[ "def", "load", "(", "self", ",", "data_file", "=", "None", ")", ":", "if", "not", "data_file", ":", "data_file", "=", "''", "elif", "data_file", "[", "-", "1", "]", "!=", "'/'", ":", "data_file", "+=", "'/'", "if", "data_file", "[", "-", "6", ":", "]", "!=", "self", ".", "lazy_folder", ":", "data_file", "+=", "self", ".", "lazy_folder", "data_file", "+=", "self", ".", "data_filename", "self", ".", "data", "=", "self", ".", "_load", "(", "data_file", ")", "return", "self" ]
Loads a data file and sets it to self.data. Arguments: data_file -- The filename to load.
[ "Loads", "a", "data", "file", "and", "sets", "it", "to", "self", ".", "data", "." ]
78e94320c7ff2c08988df04b4e43968f0a7ae06e
https://github.com/fmd/lazyconf/blob/78e94320c7ff2c08988df04b4e43968f0a7ae06e/lazyconf/lazyconf.py#L317-L335
249,807
minhhoit/yacms
yacms/twitter/managers.py
TweetManager.get_for
def get_for(self, query_type, value): """ Create a query and run it for the given arg if it doesn't exist, and return the tweets for the query. """ from yacms.twitter.models import Query lookup = {"type": query_type, "value": value} query, created = Query.objects.get_or_create(**lookup) if created: query.run() elif not query.interested: query.interested = True query.save() return query.tweets.all()
python
def get_for(self, query_type, value): """ Create a query and run it for the given arg if it doesn't exist, and return the tweets for the query. """ from yacms.twitter.models import Query lookup = {"type": query_type, "value": value} query, created = Query.objects.get_or_create(**lookup) if created: query.run() elif not query.interested: query.interested = True query.save() return query.tweets.all()
[ "def", "get_for", "(", "self", ",", "query_type", ",", "value", ")", ":", "from", "yacms", ".", "twitter", ".", "models", "import", "Query", "lookup", "=", "{", "\"type\"", ":", "query_type", ",", "\"value\"", ":", "value", "}", "query", ",", "created", "=", "Query", ".", "objects", ".", "get_or_create", "(", "*", "*", "lookup", ")", "if", "created", ":", "query", ".", "run", "(", ")", "elif", "not", "query", ".", "interested", ":", "query", ".", "interested", "=", "True", "query", ".", "save", "(", ")", "return", "query", ".", "tweets", ".", "all", "(", ")" ]
Create a query and run it for the given arg if it doesn't exist, and return the tweets for the query.
[ "Create", "a", "query", "and", "run", "it", "for", "the", "given", "arg", "if", "it", "doesn", "t", "exist", "and", "return", "the", "tweets", "for", "the", "query", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/twitter/managers.py#L12-L25
249,808
inspirehep/plotextractor
plotextractor/converter.py
untar
def untar(original_tarball, output_directory): """Untar given tarball file into directory. Here we decide if our file is actually a tarball, then we untar it and return a list of extracted files. :param: tarball (string): the name of the tar file from arXiv :param: output_directory (string): the directory to untar in :return: list of absolute file paths """ if not tarfile.is_tarfile(original_tarball): raise InvalidTarball tarball = tarfile.open(original_tarball) # set mtimes of members to now epochsecs = int(time()) for member in tarball.getmembers(): member.mtime = epochsecs tarball.extractall(output_directory) file_list = [] for extracted_file in tarball.getnames(): if extracted_file == '': break if extracted_file.startswith('./'): extracted_file = extracted_file[2:] # ensure we are actually looking at the right file extracted_file = os.path.join(output_directory, extracted_file) # Add to full list of extracted files file_list.append(extracted_file) return file_list
python
def untar(original_tarball, output_directory): """Untar given tarball file into directory. Here we decide if our file is actually a tarball, then we untar it and return a list of extracted files. :param: tarball (string): the name of the tar file from arXiv :param: output_directory (string): the directory to untar in :return: list of absolute file paths """ if not tarfile.is_tarfile(original_tarball): raise InvalidTarball tarball = tarfile.open(original_tarball) # set mtimes of members to now epochsecs = int(time()) for member in tarball.getmembers(): member.mtime = epochsecs tarball.extractall(output_directory) file_list = [] for extracted_file in tarball.getnames(): if extracted_file == '': break if extracted_file.startswith('./'): extracted_file = extracted_file[2:] # ensure we are actually looking at the right file extracted_file = os.path.join(output_directory, extracted_file) # Add to full list of extracted files file_list.append(extracted_file) return file_list
[ "def", "untar", "(", "original_tarball", ",", "output_directory", ")", ":", "if", "not", "tarfile", ".", "is_tarfile", "(", "original_tarball", ")", ":", "raise", "InvalidTarball", "tarball", "=", "tarfile", ".", "open", "(", "original_tarball", ")", "# set mtimes of members to now", "epochsecs", "=", "int", "(", "time", "(", ")", ")", "for", "member", "in", "tarball", ".", "getmembers", "(", ")", ":", "member", ".", "mtime", "=", "epochsecs", "tarball", ".", "extractall", "(", "output_directory", ")", "file_list", "=", "[", "]", "for", "extracted_file", "in", "tarball", ".", "getnames", "(", ")", ":", "if", "extracted_file", "==", "''", ":", "break", "if", "extracted_file", ".", "startswith", "(", "'./'", ")", ":", "extracted_file", "=", "extracted_file", "[", "2", ":", "]", "# ensure we are actually looking at the right file", "extracted_file", "=", "os", ".", "path", ".", "join", "(", "output_directory", ",", "extracted_file", ")", "# Add to full list of extracted files", "file_list", ".", "append", "(", "extracted_file", ")", "return", "file_list" ]
Untar given tarball file into directory. Here we decide if our file is actually a tarball, then we untar it and return a list of extracted files. :param: tarball (string): the name of the tar file from arXiv :param: output_directory (string): the directory to untar in :return: list of absolute file paths
[ "Untar", "given", "tarball", "file", "into", "directory", "." ]
12a65350fb9f32d496f9ea57908d9a2771b20474
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L45-L79
249,809
inspirehep/plotextractor
plotextractor/converter.py
detect_images_and_tex
def detect_images_and_tex( file_list, allowed_image_types=('eps', 'png', 'ps', 'jpg', 'pdf'), timeout=20): """Detect from a list of files which are TeX or images. :param: file_list (list): list of absolute file paths :param: allowed_image_types (list): list of allows image formats :param: timeout (int): the timeout value on shell commands. :return: (image_list, tex_file) (([string, string, ...], string)): list of images in the tarball and the name of the TeX file in the tarball. """ tex_file_extension = 'tex' image_list = [] might_be_tex = [] for extracted_file in file_list: # Ignore directories and hidden (metadata) files if os.path.isdir(extracted_file) \ or os.path.basename(extracted_file).startswith('.'): continue magic_str = magic.from_file(extracted_file, mime=True) if magic_str == "application/x-tex": might_be_tex.append(extracted_file) elif magic_str.startswith('image/') \ or magic_str == "application/postscript": image_list.append(extracted_file) # If neither, maybe it is TeX or an image anyway, otherwise, # we don't care. else: _, dotted_file_extension = os.path.splitext(extracted_file) file_extension = dotted_file_extension[1:] if file_extension == tex_file_extension: might_be_tex.append(extracted_file) elif file_extension in allowed_image_types: image_list.append(extracted_file) return image_list, might_be_tex
python
def detect_images_and_tex( file_list, allowed_image_types=('eps', 'png', 'ps', 'jpg', 'pdf'), timeout=20): """Detect from a list of files which are TeX or images. :param: file_list (list): list of absolute file paths :param: allowed_image_types (list): list of allows image formats :param: timeout (int): the timeout value on shell commands. :return: (image_list, tex_file) (([string, string, ...], string)): list of images in the tarball and the name of the TeX file in the tarball. """ tex_file_extension = 'tex' image_list = [] might_be_tex = [] for extracted_file in file_list: # Ignore directories and hidden (metadata) files if os.path.isdir(extracted_file) \ or os.path.basename(extracted_file).startswith('.'): continue magic_str = magic.from_file(extracted_file, mime=True) if magic_str == "application/x-tex": might_be_tex.append(extracted_file) elif magic_str.startswith('image/') \ or magic_str == "application/postscript": image_list.append(extracted_file) # If neither, maybe it is TeX or an image anyway, otherwise, # we don't care. else: _, dotted_file_extension = os.path.splitext(extracted_file) file_extension = dotted_file_extension[1:] if file_extension == tex_file_extension: might_be_tex.append(extracted_file) elif file_extension in allowed_image_types: image_list.append(extracted_file) return image_list, might_be_tex
[ "def", "detect_images_and_tex", "(", "file_list", ",", "allowed_image_types", "=", "(", "'eps'", ",", "'png'", ",", "'ps'", ",", "'jpg'", ",", "'pdf'", ")", ",", "timeout", "=", "20", ")", ":", "tex_file_extension", "=", "'tex'", "image_list", "=", "[", "]", "might_be_tex", "=", "[", "]", "for", "extracted_file", "in", "file_list", ":", "# Ignore directories and hidden (metadata) files", "if", "os", ".", "path", ".", "isdir", "(", "extracted_file", ")", "or", "os", ".", "path", ".", "basename", "(", "extracted_file", ")", ".", "startswith", "(", "'.'", ")", ":", "continue", "magic_str", "=", "magic", ".", "from_file", "(", "extracted_file", ",", "mime", "=", "True", ")", "if", "magic_str", "==", "\"application/x-tex\"", ":", "might_be_tex", ".", "append", "(", "extracted_file", ")", "elif", "magic_str", ".", "startswith", "(", "'image/'", ")", "or", "magic_str", "==", "\"application/postscript\"", ":", "image_list", ".", "append", "(", "extracted_file", ")", "# If neither, maybe it is TeX or an image anyway, otherwise,", "# we don't care.", "else", ":", "_", ",", "dotted_file_extension", "=", "os", ".", "path", ".", "splitext", "(", "extracted_file", ")", "file_extension", "=", "dotted_file_extension", "[", "1", ":", "]", "if", "file_extension", "==", "tex_file_extension", ":", "might_be_tex", ".", "append", "(", "extracted_file", ")", "elif", "file_extension", "in", "allowed_image_types", ":", "image_list", ".", "append", "(", "extracted_file", ")", "return", "image_list", ",", "might_be_tex" ]
Detect from a list of files which are TeX or images. :param: file_list (list): list of absolute file paths :param: allowed_image_types (list): list of allows image formats :param: timeout (int): the timeout value on shell commands. :return: (image_list, tex_file) (([string, string, ...], string)): list of images in the tarball and the name of the TeX file in the tarball.
[ "Detect", "from", "a", "list", "of", "files", "which", "are", "TeX", "or", "images", "." ]
12a65350fb9f32d496f9ea57908d9a2771b20474
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L82-L126
249,810
inspirehep/plotextractor
plotextractor/converter.py
convert_images
def convert_images(image_list, image_format="png", timeout=20): """Convert images from list of images to given format, if needed. Figure out the types of the images that were extracted from the tarball and determine how to convert them into PNG. :param: image_list ([string, string, ...]): the list of image files extracted from the tarball in step 1 :param: image_format (string): which image format to convert to. (PNG by default) :param: timeout (int): the timeout value on shell commands. :return: image_mapping ({new_image: original_image, ...]): The mapping of image files when all have been converted to PNG format. """ png_output_contains = 'PNG image' image_mapping = {} for image_file in image_list: if os.path.isdir(image_file): continue if not os.path.exists(image_file): continue cmd_out = check_output(['file', image_file], timeout=timeout) if cmd_out.find(png_output_contains) > -1: # Already PNG image_mapping[image_file] = image_file else: # we're just going to assume that ImageMagick can convert all # the image types that we may be faced with # for sure it can do EPS->PNG and JPG->PNG and PS->PNG # and PSTEX->PNG converted_image_file = get_converted_image_name(image_file) try: convert_image(image_file, converted_image_file, image_format) except (MissingDelegateError, ResourceLimitError): # Too bad, cannot convert image format. continue if os.path.exists(converted_image_file): image_mapping[converted_image_file] = image_file return image_mapping
python
def convert_images(image_list, image_format="png", timeout=20): """Convert images from list of images to given format, if needed. Figure out the types of the images that were extracted from the tarball and determine how to convert them into PNG. :param: image_list ([string, string, ...]): the list of image files extracted from the tarball in step 1 :param: image_format (string): which image format to convert to. (PNG by default) :param: timeout (int): the timeout value on shell commands. :return: image_mapping ({new_image: original_image, ...]): The mapping of image files when all have been converted to PNG format. """ png_output_contains = 'PNG image' image_mapping = {} for image_file in image_list: if os.path.isdir(image_file): continue if not os.path.exists(image_file): continue cmd_out = check_output(['file', image_file], timeout=timeout) if cmd_out.find(png_output_contains) > -1: # Already PNG image_mapping[image_file] = image_file else: # we're just going to assume that ImageMagick can convert all # the image types that we may be faced with # for sure it can do EPS->PNG and JPG->PNG and PS->PNG # and PSTEX->PNG converted_image_file = get_converted_image_name(image_file) try: convert_image(image_file, converted_image_file, image_format) except (MissingDelegateError, ResourceLimitError): # Too bad, cannot convert image format. continue if os.path.exists(converted_image_file): image_mapping[converted_image_file] = image_file return image_mapping
[ "def", "convert_images", "(", "image_list", ",", "image_format", "=", "\"png\"", ",", "timeout", "=", "20", ")", ":", "png_output_contains", "=", "'PNG image'", "image_mapping", "=", "{", "}", "for", "image_file", "in", "image_list", ":", "if", "os", ".", "path", ".", "isdir", "(", "image_file", ")", ":", "continue", "if", "not", "os", ".", "path", ".", "exists", "(", "image_file", ")", ":", "continue", "cmd_out", "=", "check_output", "(", "[", "'file'", ",", "image_file", "]", ",", "timeout", "=", "timeout", ")", "if", "cmd_out", ".", "find", "(", "png_output_contains", ")", ">", "-", "1", ":", "# Already PNG", "image_mapping", "[", "image_file", "]", "=", "image_file", "else", ":", "# we're just going to assume that ImageMagick can convert all", "# the image types that we may be faced with", "# for sure it can do EPS->PNG and JPG->PNG and PS->PNG", "# and PSTEX->PNG", "converted_image_file", "=", "get_converted_image_name", "(", "image_file", ")", "try", ":", "convert_image", "(", "image_file", ",", "converted_image_file", ",", "image_format", ")", "except", "(", "MissingDelegateError", ",", "ResourceLimitError", ")", ":", "# Too bad, cannot convert image format.", "continue", "if", "os", ".", "path", ".", "exists", "(", "converted_image_file", ")", ":", "image_mapping", "[", "converted_image_file", "]", "=", "image_file", "return", "image_mapping" ]
Convert images from list of images to given format, if needed. Figure out the types of the images that were extracted from the tarball and determine how to convert them into PNG. :param: image_list ([string, string, ...]): the list of image files extracted from the tarball in step 1 :param: image_format (string): which image format to convert to. (PNG by default) :param: timeout (int): the timeout value on shell commands. :return: image_mapping ({new_image: original_image, ...]): The mapping of image files when all have been converted to PNG format.
[ "Convert", "images", "from", "list", "of", "images", "to", "given", "format", "if", "needed", "." ]
12a65350fb9f32d496f9ea57908d9a2771b20474
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L129-L171
249,811
inspirehep/plotextractor
plotextractor/converter.py
convert_image
def convert_image(from_file, to_file, image_format): """Convert an image to given format.""" with Image(filename=from_file) as original: with original.convert(image_format) as converted: converted.save(filename=to_file) return to_file
python
def convert_image(from_file, to_file, image_format): """Convert an image to given format.""" with Image(filename=from_file) as original: with original.convert(image_format) as converted: converted.save(filename=to_file) return to_file
[ "def", "convert_image", "(", "from_file", ",", "to_file", ",", "image_format", ")", ":", "with", "Image", "(", "filename", "=", "from_file", ")", "as", "original", ":", "with", "original", ".", "convert", "(", "image_format", ")", "as", "converted", ":", "converted", ".", "save", "(", "filename", "=", "to_file", ")", "return", "to_file" ]
Convert an image to given format.
[ "Convert", "an", "image", "to", "given", "format", "." ]
12a65350fb9f32d496f9ea57908d9a2771b20474
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L174-L179
249,812
inspirehep/plotextractor
plotextractor/converter.py
rotate_image
def rotate_image(filename, line, sdir, image_list): """Rotate a image. Given a filename and a line, figure out what it is that the author wanted to do wrt changing the rotation of the image and convert the file so that this rotation is reflected in its presentation. :param: filename (string): the name of the file as specified in the TeX :param: line (string): the line where the rotate command was found :output: the image file rotated in accordance with the rotate command :return: True if something was rotated """ file_loc = get_image_location(filename, sdir, image_list) degrees = re.findall('(angle=[-\\d]+|rotate=[-\\d]+)', line) if len(degrees) < 1: return False degrees = degrees[0].split('=')[-1].strip() if file_loc is None or file_loc == 'ERROR' or\ not re.match('-*\\d+', degrees): return False if degrees: try: degrees = int(degrees) except (ValueError, TypeError): return False if not os.path.exists(file_loc): return False with Image(filename=file_loc) as image: with image.clone() as rotated: rotated.rotate(degrees) rotated.save(filename=file_loc) return True return False
python
def rotate_image(filename, line, sdir, image_list): """Rotate a image. Given a filename and a line, figure out what it is that the author wanted to do wrt changing the rotation of the image and convert the file so that this rotation is reflected in its presentation. :param: filename (string): the name of the file as specified in the TeX :param: line (string): the line where the rotate command was found :output: the image file rotated in accordance with the rotate command :return: True if something was rotated """ file_loc = get_image_location(filename, sdir, image_list) degrees = re.findall('(angle=[-\\d]+|rotate=[-\\d]+)', line) if len(degrees) < 1: return False degrees = degrees[0].split('=')[-1].strip() if file_loc is None or file_loc == 'ERROR' or\ not re.match('-*\\d+', degrees): return False if degrees: try: degrees = int(degrees) except (ValueError, TypeError): return False if not os.path.exists(file_loc): return False with Image(filename=file_loc) as image: with image.clone() as rotated: rotated.rotate(degrees) rotated.save(filename=file_loc) return True return False
[ "def", "rotate_image", "(", "filename", ",", "line", ",", "sdir", ",", "image_list", ")", ":", "file_loc", "=", "get_image_location", "(", "filename", ",", "sdir", ",", "image_list", ")", "degrees", "=", "re", ".", "findall", "(", "'(angle=[-\\\\d]+|rotate=[-\\\\d]+)'", ",", "line", ")", "if", "len", "(", "degrees", ")", "<", "1", ":", "return", "False", "degrees", "=", "degrees", "[", "0", "]", ".", "split", "(", "'='", ")", "[", "-", "1", "]", ".", "strip", "(", ")", "if", "file_loc", "is", "None", "or", "file_loc", "==", "'ERROR'", "or", "not", "re", ".", "match", "(", "'-*\\\\d+'", ",", "degrees", ")", ":", "return", "False", "if", "degrees", ":", "try", ":", "degrees", "=", "int", "(", "degrees", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "False", "if", "not", "os", ".", "path", ".", "exists", "(", "file_loc", ")", ":", "return", "False", "with", "Image", "(", "filename", "=", "file_loc", ")", "as", "image", ":", "with", "image", ".", "clone", "(", ")", "as", "rotated", ":", "rotated", ".", "rotate", "(", "degrees", ")", "rotated", ".", "save", "(", "filename", "=", "file_loc", ")", "return", "True", "return", "False" ]
Rotate a image. Given a filename and a line, figure out what it is that the author wanted to do wrt changing the rotation of the image and convert the file so that this rotation is reflected in its presentation. :param: filename (string): the name of the file as specified in the TeX :param: line (string): the line where the rotate command was found :output: the image file rotated in accordance with the rotate command :return: True if something was rotated
[ "Rotate", "a", "image", "." ]
12a65350fb9f32d496f9ea57908d9a2771b20474
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/converter.py#L182-L221
249,813
Othernet-Project/ndb-utils
ndb_utils/models.py
OwnershipMixin.get_by_owner
def get_by_owner(cls, owner): """ get all entities owned by specified owner """ return cls.query(cls.owner==cls._get_key(owner))
python
def get_by_owner(cls, owner): """ get all entities owned by specified owner """ return cls.query(cls.owner==cls._get_key(owner))
[ "def", "get_by_owner", "(", "cls", ",", "owner", ")", ":", "return", "cls", ".", "query", "(", "cls", ".", "owner", "==", "cls", ".", "_get_key", "(", "owner", ")", ")" ]
get all entities owned by specified owner
[ "get", "all", "entities", "owned", "by", "specified", "owner" ]
7804a5e305a4ed280742e22dad1dd10756cbe695
https://github.com/Othernet-Project/ndb-utils/blob/7804a5e305a4ed280742e22dad1dd10756cbe695/ndb_utils/models.py#L113-L115
249,814
Othernet-Project/ndb-utils
ndb_utils/models.py
ValidatingMixin.clean
def clean(self): """ Cleans the data and throws ValidationError on failure """ errors = {} cleaned = {} for name, validator in self.validate_schema.items(): val = getattr(self, name, None) try: cleaned[name] = validator.to_python(val) except formencode.api.Invalid, err: errors[name] = err if errors: raise ValidationError('Invalid data', errors) return cleaned
python
def clean(self): """ Cleans the data and throws ValidationError on failure """ errors = {} cleaned = {} for name, validator in self.validate_schema.items(): val = getattr(self, name, None) try: cleaned[name] = validator.to_python(val) except formencode.api.Invalid, err: errors[name] = err if errors: raise ValidationError('Invalid data', errors) return cleaned
[ "def", "clean", "(", "self", ")", ":", "errors", "=", "{", "}", "cleaned", "=", "{", "}", "for", "name", ",", "validator", "in", "self", ".", "validate_schema", ".", "items", "(", ")", ":", "val", "=", "getattr", "(", "self", ",", "name", ",", "None", ")", "try", ":", "cleaned", "[", "name", "]", "=", "validator", ".", "to_python", "(", "val", ")", "except", "formencode", ".", "api", ".", "Invalid", ",", "err", ":", "errors", "[", "name", "]", "=", "err", "if", "errors", ":", "raise", "ValidationError", "(", "'Invalid data'", ",", "errors", ")", "return", "cleaned" ]
Cleans the data and throws ValidationError on failure
[ "Cleans", "the", "data", "and", "throws", "ValidationError", "on", "failure" ]
7804a5e305a4ed280742e22dad1dd10756cbe695
https://github.com/Othernet-Project/ndb-utils/blob/7804a5e305a4ed280742e22dad1dd10756cbe695/ndb_utils/models.py#L130-L144
249,815
calvinku96/labreporthelper
labreporthelper/bestfit/bestfit.py
BestFit.set_defaults
def set_defaults(self, **defaults): """ Add all keyword arguments to self.args args: **defaults: key and value represents dictionary key and value """ try: defaults_items = defaults.iteritems() except AttributeError: defaults_items = defaults.items() for key, val in defaults_items: if key not in self.args.keys(): self.args[key] = val
python
def set_defaults(self, **defaults): """ Add all keyword arguments to self.args args: **defaults: key and value represents dictionary key and value """ try: defaults_items = defaults.iteritems() except AttributeError: defaults_items = defaults.items() for key, val in defaults_items: if key not in self.args.keys(): self.args[key] = val
[ "def", "set_defaults", "(", "self", ",", "*", "*", "defaults", ")", ":", "try", ":", "defaults_items", "=", "defaults", ".", "iteritems", "(", ")", "except", "AttributeError", ":", "defaults_items", "=", "defaults", ".", "items", "(", ")", "for", "key", ",", "val", "in", "defaults_items", ":", "if", "key", "not", "in", "self", ".", "args", ".", "keys", "(", ")", ":", "self", ".", "args", "[", "key", "]", "=", "val" ]
Add all keyword arguments to self.args args: **defaults: key and value represents dictionary key and value
[ "Add", "all", "keyword", "arguments", "to", "self", ".", "args" ]
4d436241f389c02eb188c313190df62ab28c3763
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L25-L39
249,816
calvinku96/labreporthelper
labreporthelper/bestfit/bestfit.py
BestFit.set_args
def set_args(self, **kwargs): """ Set more arguments to self.args args: **kwargs: key and value represents dictionary key and value """ try: kwargs_items = kwargs.iteritems() except AttributeError: kwargs_items = kwargs.items() for key, val in kwargs_items: self.args[key] = val
python
def set_args(self, **kwargs): """ Set more arguments to self.args args: **kwargs: key and value represents dictionary key and value """ try: kwargs_items = kwargs.iteritems() except AttributeError: kwargs_items = kwargs.items() for key, val in kwargs_items: self.args[key] = val
[ "def", "set_args", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "kwargs_items", "=", "kwargs", ".", "iteritems", "(", ")", "except", "AttributeError", ":", "kwargs_items", "=", "kwargs", ".", "items", "(", ")", "for", "key", ",", "val", "in", "kwargs_items", ":", "self", ".", "args", "[", "key", "]", "=", "val" ]
Set more arguments to self.args args: **kwargs: key and value represents dictionary key and value
[ "Set", "more", "arguments", "to", "self", ".", "args" ]
4d436241f389c02eb188c313190df62ab28c3763
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L42-L55
249,817
calvinku96/labreporthelper
labreporthelper/bestfit/bestfit.py
BestFit.check_important_variables
def check_important_variables(self): """ Check all the variables needed are defined """ if len(self.important_variables - set(self.args.keys())): raise TypeError("Some important variables are not set")
python
def check_important_variables(self): """ Check all the variables needed are defined """ if len(self.important_variables - set(self.args.keys())): raise TypeError("Some important variables are not set")
[ "def", "check_important_variables", "(", "self", ")", ":", "if", "len", "(", "self", ".", "important_variables", "-", "set", "(", "self", ".", "args", ".", "keys", "(", ")", ")", ")", ":", "raise", "TypeError", "(", "\"Some important variables are not set\"", ")" ]
Check all the variables needed are defined
[ "Check", "all", "the", "variables", "needed", "are", "defined" ]
4d436241f389c02eb188c313190df62ab28c3763
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L57-L62
249,818
calvinku96/labreporthelper
labreporthelper/bestfit/bestfit.py
BestFit.get_bestfit_line
def get_bestfit_line(self, x_min=None, x_max=None, resolution=None): """ Method to get bestfit line using the defined self.bestfit_func method args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) maximum x value of the line resolution: int, default=1000 how many steps between x_min and x_max returns: [bestfit_x, bestfit_y] """ x = self.args["x"] if x_min is None: x_min = min(x) if x_max is None: x_max = max(x) if resolution is None: resolution = self.args.get("resolution", 1000) bestfit_x = np.linspace(x_min, x_max, resolution) return [bestfit_x, self.bestfit_func(bestfit_x)]
python
def get_bestfit_line(self, x_min=None, x_max=None, resolution=None): """ Method to get bestfit line using the defined self.bestfit_func method args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) maximum x value of the line resolution: int, default=1000 how many steps between x_min and x_max returns: [bestfit_x, bestfit_y] """ x = self.args["x"] if x_min is None: x_min = min(x) if x_max is None: x_max = max(x) if resolution is None: resolution = self.args.get("resolution", 1000) bestfit_x = np.linspace(x_min, x_max, resolution) return [bestfit_x, self.bestfit_func(bestfit_x)]
[ "def", "get_bestfit_line", "(", "self", ",", "x_min", "=", "None", ",", "x_max", "=", "None", ",", "resolution", "=", "None", ")", ":", "x", "=", "self", ".", "args", "[", "\"x\"", "]", "if", "x_min", "is", "None", ":", "x_min", "=", "min", "(", "x", ")", "if", "x_max", "is", "None", ":", "x_max", "=", "max", "(", "x", ")", "if", "resolution", "is", "None", ":", "resolution", "=", "self", ".", "args", ".", "get", "(", "\"resolution\"", ",", "1000", ")", "bestfit_x", "=", "np", ".", "linspace", "(", "x_min", ",", "x_max", ",", "resolution", ")", "return", "[", "bestfit_x", ",", "self", ".", "bestfit_func", "(", "bestfit_x", ")", "]" ]
Method to get bestfit line using the defined self.bestfit_func method args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) maximum x value of the line resolution: int, default=1000 how many steps between x_min and x_max returns: [bestfit_x, bestfit_y]
[ "Method", "to", "get", "bestfit", "line", "using", "the", "defined", "self", ".", "bestfit_func", "method" ]
4d436241f389c02eb188c313190df62ab28c3763
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L83-L106
249,819
calvinku96/labreporthelper
labreporthelper/bestfit/bestfit.py
BestFit.get_rmse
def get_rmse(self, data_x=None, data_y=None): """ Get Root Mean Square Error using self.bestfit_func args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) maximum x value of the line resolution: int, default=1000 how many steps between x_min and x_max """ if data_x is None: data_x = np.array(self.args["x"]) if data_y is None: data_y = np.array(self.args["y"]) if len(data_x) != len(data_y): raise ValueError("Lengths of data_x and data_y are different") rmse_y = self.bestfit_func(data_x) return np.sqrt(np.mean((rmse_y - data_y) ** 2))
python
def get_rmse(self, data_x=None, data_y=None): """ Get Root Mean Square Error using self.bestfit_func args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) maximum x value of the line resolution: int, default=1000 how many steps between x_min and x_max """ if data_x is None: data_x = np.array(self.args["x"]) if data_y is None: data_y = np.array(self.args["y"]) if len(data_x) != len(data_y): raise ValueError("Lengths of data_x and data_y are different") rmse_y = self.bestfit_func(data_x) return np.sqrt(np.mean((rmse_y - data_y) ** 2))
[ "def", "get_rmse", "(", "self", ",", "data_x", "=", "None", ",", "data_y", "=", "None", ")", ":", "if", "data_x", "is", "None", ":", "data_x", "=", "np", ".", "array", "(", "self", ".", "args", "[", "\"x\"", "]", ")", "if", "data_y", "is", "None", ":", "data_y", "=", "np", ".", "array", "(", "self", ".", "args", "[", "\"y\"", "]", ")", "if", "len", "(", "data_x", ")", "!=", "len", "(", "data_y", ")", ":", "raise", "ValueError", "(", "\"Lengths of data_x and data_y are different\"", ")", "rmse_y", "=", "self", ".", "bestfit_func", "(", "data_x", ")", "return", "np", ".", "sqrt", "(", "np", ".", "mean", "(", "(", "rmse_y", "-", "data_y", ")", "**", "2", ")", ")" ]
Get Root Mean Square Error using self.bestfit_func args: x_min: scalar, default=min(x) minimum x value of the line x_max: scalar, default=max(x) maximum x value of the line resolution: int, default=1000 how many steps between x_min and x_max
[ "Get", "Root", "Mean", "Square", "Error", "using", "self", ".", "bestfit_func" ]
4d436241f389c02eb188c313190df62ab28c3763
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L108-L128
249,820
calvinku96/labreporthelper
labreporthelper/bestfit/bestfit.py
BestFit.get_mae
def get_mae(self, data_x=None, data_y=None): """ Get Mean Absolute Error using self.bestfit_func args: data_x: array_like, default=x x value used to determine rmse, used if only a section of x is to be calculated data_y: array_like, default=y y value used to determine rmse, used if only a section of y is to be calculated """ if data_x is None: data_x = np.array(self.args["x"]) if data_y is None: data_y = np.array(self.args["y"]) if len(data_x) != len(data_y): raise ValueError("Lengths of data_x and data_y are different") mae_y = self.bestfit_func(data_x) return np.mean(abs(mae_y - data_y))
python
def get_mae(self, data_x=None, data_y=None): """ Get Mean Absolute Error using self.bestfit_func args: data_x: array_like, default=x x value used to determine rmse, used if only a section of x is to be calculated data_y: array_like, default=y y value used to determine rmse, used if only a section of y is to be calculated """ if data_x is None: data_x = np.array(self.args["x"]) if data_y is None: data_y = np.array(self.args["y"]) if len(data_x) != len(data_y): raise ValueError("Lengths of data_x and data_y are different") mae_y = self.bestfit_func(data_x) return np.mean(abs(mae_y - data_y))
[ "def", "get_mae", "(", "self", ",", "data_x", "=", "None", ",", "data_y", "=", "None", ")", ":", "if", "data_x", "is", "None", ":", "data_x", "=", "np", ".", "array", "(", "self", ".", "args", "[", "\"x\"", "]", ")", "if", "data_y", "is", "None", ":", "data_y", "=", "np", ".", "array", "(", "self", ".", "args", "[", "\"y\"", "]", ")", "if", "len", "(", "data_x", ")", "!=", "len", "(", "data_y", ")", ":", "raise", "ValueError", "(", "\"Lengths of data_x and data_y are different\"", ")", "mae_y", "=", "self", ".", "bestfit_func", "(", "data_x", ")", "return", "np", ".", "mean", "(", "abs", "(", "mae_y", "-", "data_y", ")", ")" ]
Get Mean Absolute Error using self.bestfit_func args: data_x: array_like, default=x x value used to determine rmse, used if only a section of x is to be calculated data_y: array_like, default=y y value used to determine rmse, used if only a section of y is to be calculated
[ "Get", "Mean", "Absolute", "Error", "using", "self", ".", "bestfit_func" ]
4d436241f389c02eb188c313190df62ab28c3763
https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/bestfit.py#L130-L150
249,821
leonjza/filesmudge
filesmudge/smudge.py
_backup_bytes
def _backup_bytes(target, offset, length): """ Read bytes from one file and write it to a backup file with the .bytes_backup suffix """ click.echo('Backup {l} byes at position {offset} on file {file} to .bytes_backup'.format( l=length, offset=offset, file=target)) with open(target, 'r+b') as f: f.seek(offset) with open(target + '.bytes_backup', 'w+b') as b: for _ in xrange(length): byte = f.read(1) b.write(byte) b.flush() f.flush()
python
def _backup_bytes(target, offset, length): """ Read bytes from one file and write it to a backup file with the .bytes_backup suffix """ click.echo('Backup {l} byes at position {offset} on file {file} to .bytes_backup'.format( l=length, offset=offset, file=target)) with open(target, 'r+b') as f: f.seek(offset) with open(target + '.bytes_backup', 'w+b') as b: for _ in xrange(length): byte = f.read(1) b.write(byte) b.flush() f.flush()
[ "def", "_backup_bytes", "(", "target", ",", "offset", ",", "length", ")", ":", "click", ".", "echo", "(", "'Backup {l} byes at position {offset} on file {file} to .bytes_backup'", ".", "format", "(", "l", "=", "length", ",", "offset", "=", "offset", ",", "file", "=", "target", ")", ")", "with", "open", "(", "target", ",", "'r+b'", ")", "as", "f", ":", "f", ".", "seek", "(", "offset", ")", "with", "open", "(", "target", "+", "'.bytes_backup'", ",", "'w+b'", ")", "as", "b", ":", "for", "_", "in", "xrange", "(", "length", ")", ":", "byte", "=", "f", ".", "read", "(", "1", ")", "b", ".", "write", "(", "byte", ")", "b", ".", "flush", "(", ")", "f", ".", "flush", "(", ")" ]
Read bytes from one file and write it to a backup file with the .bytes_backup suffix
[ "Read", "bytes", "from", "one", "file", "and", "write", "it", "to", "a", "backup", "file", "with", "the", ".", "bytes_backup", "suffix" ]
ba519aa4df85751458faf68220964d3e2480b9fc
https://github.com/leonjza/filesmudge/blob/ba519aa4df85751458faf68220964d3e2480b9fc/filesmudge/smudge.py#L68-L85
249,822
leonjza/filesmudge
filesmudge/smudge.py
_smudge_bytes
def _smudge_bytes(target, offset, magic_bytes): """ Write magic bytes to a file relative from offset """ click.echo('Writing {c} magic byes at position {offset} on file {file}'.format( c=len(magic_bytes), offset=offset, file=target)) with open(target, 'r+b') as f: f.seek(offset) f.write(magic_bytes) f.flush() click.echo('Changes written')
python
def _smudge_bytes(target, offset, magic_bytes): """ Write magic bytes to a file relative from offset """ click.echo('Writing {c} magic byes at position {offset} on file {file}'.format( c=len(magic_bytes), offset=offset, file=target)) with open(target, 'r+b') as f: f.seek(offset) f.write(magic_bytes) f.flush() click.echo('Changes written')
[ "def", "_smudge_bytes", "(", "target", ",", "offset", ",", "magic_bytes", ")", ":", "click", ".", "echo", "(", "'Writing {c} magic byes at position {offset} on file {file}'", ".", "format", "(", "c", "=", "len", "(", "magic_bytes", ")", ",", "offset", "=", "offset", ",", "file", "=", "target", ")", ")", "with", "open", "(", "target", ",", "'r+b'", ")", "as", "f", ":", "f", ".", "seek", "(", "offset", ")", "f", ".", "write", "(", "magic_bytes", ")", "f", ".", "flush", "(", ")", "click", ".", "echo", "(", "'Changes written'", ")" ]
Write magic bytes to a file relative from offset
[ "Write", "magic", "bytes", "to", "a", "file", "relative", "from", "offset" ]
ba519aa4df85751458faf68220964d3e2480b9fc
https://github.com/leonjza/filesmudge/blob/ba519aa4df85751458faf68220964d3e2480b9fc/filesmudge/smudge.py#L88-L101
249,823
leonjza/filesmudge
filesmudge/smudge.py
smudge
def smudge(newtype, target): """ Smudge magic bytes with a known type """ db = smudge_db.get() magic_bytes = db[newtype]['magic'] magic_offset = db[newtype]['offset'] _backup_bytes(target, magic_offset, len(magic_bytes)) _smudge_bytes(target, magic_offset, magic_bytes)
python
def smudge(newtype, target): """ Smudge magic bytes with a known type """ db = smudge_db.get() magic_bytes = db[newtype]['magic'] magic_offset = db[newtype]['offset'] _backup_bytes(target, magic_offset, len(magic_bytes)) _smudge_bytes(target, magic_offset, magic_bytes)
[ "def", "smudge", "(", "newtype", ",", "target", ")", ":", "db", "=", "smudge_db", ".", "get", "(", ")", "magic_bytes", "=", "db", "[", "newtype", "]", "[", "'magic'", "]", "magic_offset", "=", "db", "[", "newtype", "]", "[", "'offset'", "]", "_backup_bytes", "(", "target", ",", "magic_offset", ",", "len", "(", "magic_bytes", ")", ")", "_smudge_bytes", "(", "target", ",", "magic_offset", ",", "magic_bytes", ")" ]
Smudge magic bytes with a known type
[ "Smudge", "magic", "bytes", "with", "a", "known", "type" ]
ba519aa4df85751458faf68220964d3e2480b9fc
https://github.com/leonjza/filesmudge/blob/ba519aa4df85751458faf68220964d3e2480b9fc/filesmudge/smudge.py#L107-L118
249,824
leonjza/filesmudge
filesmudge/smudge.py
smudgeraw
def smudgeraw(target, offset, magicbytes): """ Smudge magic bytes with raw bytes """ magicbytes = magicbytes.replace('\\x', '').decode('hex') _backup_bytes(target, offset, len(magicbytes)) _smudge_bytes(target, offset, magicbytes)
python
def smudgeraw(target, offset, magicbytes): """ Smudge magic bytes with raw bytes """ magicbytes = magicbytes.replace('\\x', '').decode('hex') _backup_bytes(target, offset, len(magicbytes)) _smudge_bytes(target, offset, magicbytes)
[ "def", "smudgeraw", "(", "target", ",", "offset", ",", "magicbytes", ")", ":", "magicbytes", "=", "magicbytes", ".", "replace", "(", "'\\\\x'", ",", "''", ")", ".", "decode", "(", "'hex'", ")", "_backup_bytes", "(", "target", ",", "offset", ",", "len", "(", "magicbytes", ")", ")", "_smudge_bytes", "(", "target", ",", "offset", ",", "magicbytes", ")" ]
Smudge magic bytes with raw bytes
[ "Smudge", "magic", "bytes", "with", "raw", "bytes" ]
ba519aa4df85751458faf68220964d3e2480b9fc
https://github.com/leonjza/filesmudge/blob/ba519aa4df85751458faf68220964d3e2480b9fc/filesmudge/smudge.py#L125-L132
249,825
leonjza/filesmudge
filesmudge/smudge.py
restore
def restore(source, offset): """ Restore a smudged file from .bytes_backup """ backup_location = os.path.join( os.path.dirname(os.path.abspath(source)), source + '.bytes_backup') click.echo('Reading backup from: {location}'.format(location=backup_location)) if not os.path.isfile(backup_location): click.echo('No backup found for: {source}'.format(source=source)) return with open(backup_location, 'r+b') as b: data = b.read() click.echo('Restoring {c} bytes from offset {o}'.format(c=len(data), o=offset)) with open(source, 'r+b') as f: f.seek(offset) f.write(data) f.flush() click.echo('Changes written')
python
def restore(source, offset): """ Restore a smudged file from .bytes_backup """ backup_location = os.path.join( os.path.dirname(os.path.abspath(source)), source + '.bytes_backup') click.echo('Reading backup from: {location}'.format(location=backup_location)) if not os.path.isfile(backup_location): click.echo('No backup found for: {source}'.format(source=source)) return with open(backup_location, 'r+b') as b: data = b.read() click.echo('Restoring {c} bytes from offset {o}'.format(c=len(data), o=offset)) with open(source, 'r+b') as f: f.seek(offset) f.write(data) f.flush() click.echo('Changes written')
[ "def", "restore", "(", "source", ",", "offset", ")", ":", "backup_location", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "source", ")", ")", ",", "source", "+", "'.bytes_backup'", ")", "click", ".", "echo", "(", "'Reading backup from: {location}'", ".", "format", "(", "location", "=", "backup_location", ")", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "backup_location", ")", ":", "click", ".", "echo", "(", "'No backup found for: {source}'", ".", "format", "(", "source", "=", "source", ")", ")", "return", "with", "open", "(", "backup_location", ",", "'r+b'", ")", "as", "b", ":", "data", "=", "b", ".", "read", "(", ")", "click", ".", "echo", "(", "'Restoring {c} bytes from offset {o}'", ".", "format", "(", "c", "=", "len", "(", "data", ")", ",", "o", "=", "offset", ")", ")", "with", "open", "(", "source", ",", "'r+b'", ")", "as", "f", ":", "f", ".", "seek", "(", "offset", ")", "f", ".", "write", "(", "data", ")", "f", ".", "flush", "(", ")", "click", ".", "echo", "(", "'Changes written'", ")" ]
Restore a smudged file from .bytes_backup
[ "Restore", "a", "smudged", "file", "from", ".", "bytes_backup" ]
ba519aa4df85751458faf68220964d3e2480b9fc
https://github.com/leonjza/filesmudge/blob/ba519aa4df85751458faf68220964d3e2480b9fc/filesmudge/smudge.py#L138-L159
249,826
leonjza/filesmudge
filesmudge/smudge.py
available
def available(): """ List available types for 'smudge' """ db = smudge_db.get() click.echo('{:<6} {:<6} {:<50}'.format('Type', 'Offset', 'Magic')) for k, v in db.items(): click.echo('{type:<6} {offset:<6} {magic}'.format( type=k, magic=v['magic'].encode('hex'), offset=v['offset']))
python
def available(): """ List available types for 'smudge' """ db = smudge_db.get() click.echo('{:<6} {:<6} {:<50}'.format('Type', 'Offset', 'Magic')) for k, v in db.items(): click.echo('{type:<6} {offset:<6} {magic}'.format( type=k, magic=v['magic'].encode('hex'), offset=v['offset']))
[ "def", "available", "(", ")", ":", "db", "=", "smudge_db", ".", "get", "(", ")", "click", ".", "echo", "(", "'{:<6} {:<6} {:<50}'", ".", "format", "(", "'Type'", ",", "'Offset'", ",", "'Magic'", ")", ")", "for", "k", ",", "v", "in", "db", ".", "items", "(", ")", ":", "click", ".", "echo", "(", "'{type:<6} {offset:<6} {magic}'", ".", "format", "(", "type", "=", "k", ",", "magic", "=", "v", "[", "'magic'", "]", ".", "encode", "(", "'hex'", ")", ",", "offset", "=", "v", "[", "'offset'", "]", ")", ")" ]
List available types for 'smudge'
[ "List", "available", "types", "for", "smudge" ]
ba519aa4df85751458faf68220964d3e2480b9fc
https://github.com/leonjza/filesmudge/blob/ba519aa4df85751458faf68220964d3e2480b9fc/filesmudge/smudge.py#L163-L173
249,827
ktdreyer/txproductpages
txproductpages/connection.py
Connection.upcoming_releases
def upcoming_releases(self, product): """ Get upcoming releases for this product. Specifically we search for releases with a GA date greater-than or equal to today's date. :param product: str, eg. "ceph" :returns: deferred that when fired returns a list of Munch (dict-like) objects representing all releases, sorted by shortname. """ url = 'api/v6/releases/' url = url + '?product__shortname=' + product url = url + '&ga_date__gte=' + date.today().strftime('%Y-%m-%d') url = url + '&ordering=shortname_sort' releases = yield self._get(url) result = munchify(releases) defer.returnValue(result)
python
def upcoming_releases(self, product): """ Get upcoming releases for this product. Specifically we search for releases with a GA date greater-than or equal to today's date. :param product: str, eg. "ceph" :returns: deferred that when fired returns a list of Munch (dict-like) objects representing all releases, sorted by shortname. """ url = 'api/v6/releases/' url = url + '?product__shortname=' + product url = url + '&ga_date__gte=' + date.today().strftime('%Y-%m-%d') url = url + '&ordering=shortname_sort' releases = yield self._get(url) result = munchify(releases) defer.returnValue(result)
[ "def", "upcoming_releases", "(", "self", ",", "product", ")", ":", "url", "=", "'api/v6/releases/'", "url", "=", "url", "+", "'?product__shortname='", "+", "product", "url", "=", "url", "+", "'&ga_date__gte='", "+", "date", ".", "today", "(", ")", ".", "strftime", "(", "'%Y-%m-%d'", ")", "url", "=", "url", "+", "'&ordering=shortname_sort'", "releases", "=", "yield", "self", ".", "_get", "(", "url", ")", "result", "=", "munchify", "(", "releases", ")", "defer", ".", "returnValue", "(", "result", ")" ]
Get upcoming releases for this product. Specifically we search for releases with a GA date greater-than or equal to today's date. :param product: str, eg. "ceph" :returns: deferred that when fired returns a list of Munch (dict-like) objects representing all releases, sorted by shortname.
[ "Get", "upcoming", "releases", "for", "this", "product", "." ]
96c85c498c0eef1d37cddb031db32e8b885fcbd9
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/connection.py#L26-L43
249,828
ktdreyer/txproductpages
txproductpages/connection.py
Connection.newest_release
def newest_release(self, product): """ Get the shortname of the newest upcoming release for a product. :param product: str, eg. "ceph" :returns: deferred that when fired returns the shortname of the newest release. """ releases = yield self.upcoming_releases(product) if not releases: raise ProductPagesException('no upcoming releases') defer.returnValue(releases[0].shortname)
python
def newest_release(self, product): """ Get the shortname of the newest upcoming release for a product. :param product: str, eg. "ceph" :returns: deferred that when fired returns the shortname of the newest release. """ releases = yield self.upcoming_releases(product) if not releases: raise ProductPagesException('no upcoming releases') defer.returnValue(releases[0].shortname)
[ "def", "newest_release", "(", "self", ",", "product", ")", ":", "releases", "=", "yield", "self", ".", "upcoming_releases", "(", "product", ")", "if", "not", "releases", ":", "raise", "ProductPagesException", "(", "'no upcoming releases'", ")", "defer", ".", "returnValue", "(", "releases", "[", "0", "]", ".", "shortname", ")" ]
Get the shortname of the newest upcoming release for a product. :param product: str, eg. "ceph" :returns: deferred that when fired returns the shortname of the newest release.
[ "Get", "the", "shortname", "of", "the", "newest", "upcoming", "release", "for", "a", "product", "." ]
96c85c498c0eef1d37cddb031db32e8b885fcbd9
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/connection.py#L46-L57
249,829
ktdreyer/txproductpages
txproductpages/connection.py
Connection.product_url
def product_url(self, product): """ Return a human-friendly URL for this product. :param product: str, eg. "ceph" :returns: str, URL """ url = 'product/%s' % product return posixpath.join(self.url, url)
python
def product_url(self, product): """ Return a human-friendly URL for this product. :param product: str, eg. "ceph" :returns: str, URL """ url = 'product/%s' % product return posixpath.join(self.url, url)
[ "def", "product_url", "(", "self", ",", "product", ")", ":", "url", "=", "'product/%s'", "%", "product", "return", "posixpath", ".", "join", "(", "self", ".", "url", ",", "url", ")" ]
Return a human-friendly URL for this product. :param product: str, eg. "ceph" :returns: str, URL
[ "Return", "a", "human", "-", "friendly", "URL", "for", "this", "product", "." ]
96c85c498c0eef1d37cddb031db32e8b885fcbd9
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/connection.py#L59-L67
249,830
ktdreyer/txproductpages
txproductpages/connection.py
Connection.release
def release(self, shortname): """ Get a specific release by its shortname. :param shortname: str, eg. "ceph-3-0" :returns: deferred that when fired returns a Release (Munch, dict-like) object representing this release. :raises: ReleaseNotFoundException if this release does not exist. """ url = 'api/v6/releases/?shortname=%s' % shortname releases = yield self._get(url) # Note, even if this shortname does not exist, _get() will not errback # for this url. It simply returns an empty list. So check that here: if not releases: raise ReleaseNotFoundException('no release %s' % shortname) release = Release.fromDict(releases[0]) release.connection = self defer.returnValue(release)
python
def release(self, shortname): """ Get a specific release by its shortname. :param shortname: str, eg. "ceph-3-0" :returns: deferred that when fired returns a Release (Munch, dict-like) object representing this release. :raises: ReleaseNotFoundException if this release does not exist. """ url = 'api/v6/releases/?shortname=%s' % shortname releases = yield self._get(url) # Note, even if this shortname does not exist, _get() will not errback # for this url. It simply returns an empty list. So check that here: if not releases: raise ReleaseNotFoundException('no release %s' % shortname) release = Release.fromDict(releases[0]) release.connection = self defer.returnValue(release)
[ "def", "release", "(", "self", ",", "shortname", ")", ":", "url", "=", "'api/v6/releases/?shortname=%s'", "%", "shortname", "releases", "=", "yield", "self", ".", "_get", "(", "url", ")", "# Note, even if this shortname does not exist, _get() will not errback", "# for this url. It simply returns an empty list. So check that here:", "if", "not", "releases", ":", "raise", "ReleaseNotFoundException", "(", "'no release %s'", "%", "shortname", ")", "release", "=", "Release", ".", "fromDict", "(", "releases", "[", "0", "]", ")", "release", ".", "connection", "=", "self", "defer", ".", "returnValue", "(", "release", ")" ]
Get a specific release by its shortname. :param shortname: str, eg. "ceph-3-0" :returns: deferred that when fired returns a Release (Munch, dict-like) object representing this release. :raises: ReleaseNotFoundException if this release does not exist.
[ "Get", "a", "specific", "release", "by", "its", "shortname", "." ]
96c85c498c0eef1d37cddb031db32e8b885fcbd9
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/connection.py#L70-L87
249,831
ktdreyer/txproductpages
txproductpages/connection.py
Connection.schedule_url
def schedule_url(self, release): """ Return a human-friendly URL for this release. :param release: str, release shortname eg. "ceph-3-0" :returns: str, URL """ product, _ = release.split('-', 1) url = 'product/%s/release/%s/schedule/tasks' % (product, release) return posixpath.join(self.url, url)
python
def schedule_url(self, release): """ Return a human-friendly URL for this release. :param release: str, release shortname eg. "ceph-3-0" :returns: str, URL """ product, _ = release.split('-', 1) url = 'product/%s/release/%s/schedule/tasks' % (product, release) return posixpath.join(self.url, url)
[ "def", "schedule_url", "(", "self", ",", "release", ")", ":", "product", ",", "_", "=", "release", ".", "split", "(", "'-'", ",", "1", ")", "url", "=", "'product/%s/release/%s/schedule/tasks'", "%", "(", "product", ",", "release", ")", "return", "posixpath", ".", "join", "(", "self", ".", "url", ",", "url", ")" ]
Return a human-friendly URL for this release. :param release: str, release shortname eg. "ceph-3-0" :returns: str, URL
[ "Return", "a", "human", "-", "friendly", "URL", "for", "this", "release", "." ]
96c85c498c0eef1d37cddb031db32e8b885fcbd9
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/connection.py#L89-L98
249,832
ktdreyer/txproductpages
txproductpages/connection.py
Connection._get
def _get(self, url, headers={}): """ Get a JSON API endpoint and return the parsed data. :param url: str, *relative* URL (relative to pp-admin/ api endpoint) :param headers: dict (optional) :returns: deferred that when fired returns the parsed data from JSON or errbacks with ProductPagesException """ # print('getting %s' % url) headers = headers.copy() headers['Accept'] = 'application/json' url = posixpath.join(self.url, url) try: response = yield treq.get(url, headers=headers, timeout=5) if response.code != 200: err = '%s returned %s' % (url, response.code) raise ProductPagesException(err) else: content = yield treq.json_content(response) defer.returnValue(content) except Exception as e: # For example, if treq.get() timed out, or if treq.json_content() # could not parse the JSON, etc. # TODO: better handling here for the specific errors? # I suspect it's not good to catch Exception with inlineCallbacks raise ProductPagesException('treq error: %s' % e.message)
python
def _get(self, url, headers={}): """ Get a JSON API endpoint and return the parsed data. :param url: str, *relative* URL (relative to pp-admin/ api endpoint) :param headers: dict (optional) :returns: deferred that when fired returns the parsed data from JSON or errbacks with ProductPagesException """ # print('getting %s' % url) headers = headers.copy() headers['Accept'] = 'application/json' url = posixpath.join(self.url, url) try: response = yield treq.get(url, headers=headers, timeout=5) if response.code != 200: err = '%s returned %s' % (url, response.code) raise ProductPagesException(err) else: content = yield treq.json_content(response) defer.returnValue(content) except Exception as e: # For example, if treq.get() timed out, or if treq.json_content() # could not parse the JSON, etc. # TODO: better handling here for the specific errors? # I suspect it's not good to catch Exception with inlineCallbacks raise ProductPagesException('treq error: %s' % e.message)
[ "def", "_get", "(", "self", ",", "url", ",", "headers", "=", "{", "}", ")", ":", "# print('getting %s' % url)", "headers", "=", "headers", ".", "copy", "(", ")", "headers", "[", "'Accept'", "]", "=", "'application/json'", "url", "=", "posixpath", ".", "join", "(", "self", ".", "url", ",", "url", ")", "try", ":", "response", "=", "yield", "treq", ".", "get", "(", "url", ",", "headers", "=", "headers", ",", "timeout", "=", "5", ")", "if", "response", ".", "code", "!=", "200", ":", "err", "=", "'%s returned %s'", "%", "(", "url", ",", "response", ".", "code", ")", "raise", "ProductPagesException", "(", "err", ")", "else", ":", "content", "=", "yield", "treq", ".", "json_content", "(", "response", ")", "defer", ".", "returnValue", "(", "content", ")", "except", "Exception", "as", "e", ":", "# For example, if treq.get() timed out, or if treq.json_content()", "# could not parse the JSON, etc.", "# TODO: better handling here for the specific errors?", "# I suspect it's not good to catch Exception with inlineCallbacks", "raise", "ProductPagesException", "(", "'treq error: %s'", "%", "e", ".", "message", ")" ]
Get a JSON API endpoint and return the parsed data. :param url: str, *relative* URL (relative to pp-admin/ api endpoint) :param headers: dict (optional) :returns: deferred that when fired returns the parsed data from JSON or errbacks with ProductPagesException
[ "Get", "a", "JSON", "API", "endpoint", "and", "return", "the", "parsed", "data", "." ]
96c85c498c0eef1d37cddb031db32e8b885fcbd9
https://github.com/ktdreyer/txproductpages/blob/96c85c498c0eef1d37cddb031db32e8b885fcbd9/txproductpages/connection.py#L101-L126
249,833
jmgilman/Neolib
neolib/pyamf/util/__init__.py
get_datetime
def get_datetime(secs): """ Return a UTC date from a timestamp. @type secs: C{long} @param secs: Seconds since 1970. @return: UTC timestamp. @rtype: C{datetime.datetime} """ if negative_timestamp_broken and secs < 0: return datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=secs) return datetime.datetime.utcfromtimestamp(secs)
python
def get_datetime(secs): """ Return a UTC date from a timestamp. @type secs: C{long} @param secs: Seconds since 1970. @return: UTC timestamp. @rtype: C{datetime.datetime} """ if negative_timestamp_broken and secs < 0: return datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=secs) return datetime.datetime.utcfromtimestamp(secs)
[ "def", "get_datetime", "(", "secs", ")", ":", "if", "negative_timestamp_broken", "and", "secs", "<", "0", ":", "return", "datetime", ".", "datetime", "(", "1970", ",", "1", ",", "1", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "secs", ")", "return", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "secs", ")" ]
Return a UTC date from a timestamp. @type secs: C{long} @param secs: Seconds since 1970. @return: UTC timestamp. @rtype: C{datetime.datetime}
[ "Return", "a", "UTC", "date", "from", "a", "timestamp", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/__init__.py#L46-L58
249,834
jmgilman/Neolib
neolib/pyamf/util/__init__.py
is_class_sealed
def is_class_sealed(klass): """ Whether or not the supplied class can accept dynamic properties. @rtype: C{bool} @since: 0.5 """ mro = inspect.getmro(klass) new = False if mro[-1] is object: mro = mro[:-1] new = True for kls in mro: if new and '__dict__' in kls.__dict__: return False if not hasattr(kls, '__slots__'): return False return True
python
def is_class_sealed(klass): """ Whether or not the supplied class can accept dynamic properties. @rtype: C{bool} @since: 0.5 """ mro = inspect.getmro(klass) new = False if mro[-1] is object: mro = mro[:-1] new = True for kls in mro: if new and '__dict__' in kls.__dict__: return False if not hasattr(kls, '__slots__'): return False return True
[ "def", "is_class_sealed", "(", "klass", ")", ":", "mro", "=", "inspect", ".", "getmro", "(", "klass", ")", "new", "=", "False", "if", "mro", "[", "-", "1", "]", "is", "object", ":", "mro", "=", "mro", "[", ":", "-", "1", "]", "new", "=", "True", "for", "kls", "in", "mro", ":", "if", "new", "and", "'__dict__'", "in", "kls", ".", "__dict__", ":", "return", "False", "if", "not", "hasattr", "(", "kls", ",", "'__slots__'", ")", ":", "return", "False", "return", "True" ]
Whether or not the supplied class can accept dynamic properties. @rtype: C{bool} @since: 0.5
[ "Whether", "or", "not", "the", "supplied", "class", "can", "accept", "dynamic", "properties", "." ]
228fafeaed0f3195676137732384a14820ae285c
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/util/__init__.py#L108-L129
249,835
nathforge/pydentifier
src/pydentifier/__init__.py
lower_underscore
def lower_underscore(string, prefix='', suffix=''): """ Generate an underscore-separated lower-case identifier, given English text, a prefix, and an optional suffix. Useful for function names and variable names. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> lower_underscore("This is an identifier", prefix='') 'this_is_an_identifier' """ return require_valid(append_underscore_if_keyword('_'.join( word.lower() for word in en.words(' '.join([prefix, string, suffix]))) ))
python
def lower_underscore(string, prefix='', suffix=''): """ Generate an underscore-separated lower-case identifier, given English text, a prefix, and an optional suffix. Useful for function names and variable names. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> lower_underscore("This is an identifier", prefix='') 'this_is_an_identifier' """ return require_valid(append_underscore_if_keyword('_'.join( word.lower() for word in en.words(' '.join([prefix, string, suffix]))) ))
[ "def", "lower_underscore", "(", "string", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ")", ":", "return", "require_valid", "(", "append_underscore_if_keyword", "(", "'_'", ".", "join", "(", "word", ".", "lower", "(", ")", "for", "word", "in", "en", ".", "words", "(", "' '", ".", "join", "(", "[", "prefix", ",", "string", ",", "suffix", "]", ")", ")", ")", ")", ")" ]
Generate an underscore-separated lower-case identifier, given English text, a prefix, and an optional suffix. Useful for function names and variable names. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> lower_underscore("This is an identifier", prefix='') 'this_is_an_identifier'
[ "Generate", "an", "underscore", "-", "separated", "lower", "-", "case", "identifier", "given", "English", "text", "a", "prefix", "and", "an", "optional", "suffix", "." ]
b8d27076254c65cfd7893c1401e2a198abd6afb4
https://github.com/nathforge/pydentifier/blob/b8d27076254c65cfd7893c1401e2a198abd6afb4/src/pydentifier/__init__.py#L11-L30
249,836
nathforge/pydentifier
src/pydentifier/__init__.py
upper_underscore
def upper_underscore(string, prefix='', suffix=''): """ Generate an underscore-separated upper-case identifier. Useful for constants. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> upper_underscore("This is a constant", prefix='') 'THIS_IS_A_CONSTANT' """ return require_valid(append_underscore_if_keyword('_'.join( word.upper() for word in en.words(' '.join([prefix, string, suffix]))) ))
python
def upper_underscore(string, prefix='', suffix=''): """ Generate an underscore-separated upper-case identifier. Useful for constants. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> upper_underscore("This is a constant", prefix='') 'THIS_IS_A_CONSTANT' """ return require_valid(append_underscore_if_keyword('_'.join( word.upper() for word in en.words(' '.join([prefix, string, suffix]))) ))
[ "def", "upper_underscore", "(", "string", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ")", ":", "return", "require_valid", "(", "append_underscore_if_keyword", "(", "'_'", ".", "join", "(", "word", ".", "upper", "(", ")", "for", "word", "in", "en", ".", "words", "(", "' '", ".", "join", "(", "[", "prefix", ",", "string", ",", "suffix", "]", ")", ")", ")", ")", ")" ]
Generate an underscore-separated upper-case identifier. Useful for constants. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> upper_underscore("This is a constant", prefix='') 'THIS_IS_A_CONSTANT'
[ "Generate", "an", "underscore", "-", "separated", "upper", "-", "case", "identifier", ".", "Useful", "for", "constants", "." ]
b8d27076254c65cfd7893c1401e2a198abd6afb4
https://github.com/nathforge/pydentifier/blob/b8d27076254c65cfd7893c1401e2a198abd6afb4/src/pydentifier/__init__.py#L32-L51
249,837
nathforge/pydentifier
src/pydentifier/__init__.py
upper_camel
def upper_camel(string, prefix='', suffix=''): """ Generate a camel-case identifier with the first word capitalised. Useful for class names. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> upper_camel("I'm a class", prefix='') 'IAmAClass' """ return require_valid(append_underscore_if_keyword(''.join( upper_case_first_char(word) for word in en.words(' '.join([prefix, string, suffix]))) ))
python
def upper_camel(string, prefix='', suffix=''): """ Generate a camel-case identifier with the first word capitalised. Useful for class names. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> upper_camel("I'm a class", prefix='') 'IAmAClass' """ return require_valid(append_underscore_if_keyword(''.join( upper_case_first_char(word) for word in en.words(' '.join([prefix, string, suffix]))) ))
[ "def", "upper_camel", "(", "string", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ")", ":", "return", "require_valid", "(", "append_underscore_if_keyword", "(", "''", ".", "join", "(", "upper_case_first_char", "(", "word", ")", "for", "word", "in", "en", ".", "words", "(", "' '", ".", "join", "(", "[", "prefix", ",", "string", ",", "suffix", "]", ")", ")", ")", ")", ")" ]
Generate a camel-case identifier with the first word capitalised. Useful for class names. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> upper_camel("I'm a class", prefix='') 'IAmAClass'
[ "Generate", "a", "camel", "-", "case", "identifier", "with", "the", "first", "word", "capitalised", ".", "Useful", "for", "class", "names", "." ]
b8d27076254c65cfd7893c1401e2a198abd6afb4
https://github.com/nathforge/pydentifier/blob/b8d27076254c65cfd7893c1401e2a198abd6afb4/src/pydentifier/__init__.py#L53-L72
249,838
nathforge/pydentifier
src/pydentifier/__init__.py
lower_camel
def lower_camel(string, prefix='', suffix=''): """ Generate a camel-case identifier. Useful for unit test methods. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> lower_camel("User can login", prefix='test') 'testUserCanLogin' """ return require_valid(append_underscore_if_keyword(''.join( word.lower() if index == 0 else upper_case_first_char(word) for index, word in enumerate(en.words(' '.join([prefix, string, suffix])))) ))
python
def lower_camel(string, prefix='', suffix=''): """ Generate a camel-case identifier. Useful for unit test methods. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> lower_camel("User can login", prefix='test') 'testUserCanLogin' """ return require_valid(append_underscore_if_keyword(''.join( word.lower() if index == 0 else upper_case_first_char(word) for index, word in enumerate(en.words(' '.join([prefix, string, suffix])))) ))
[ "def", "lower_camel", "(", "string", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ")", ":", "return", "require_valid", "(", "append_underscore_if_keyword", "(", "''", ".", "join", "(", "word", ".", "lower", "(", ")", "if", "index", "==", "0", "else", "upper_case_first_char", "(", "word", ")", "for", "index", ",", "word", "in", "enumerate", "(", "en", ".", "words", "(", "' '", ".", "join", "(", "[", "prefix", ",", "string", ",", "suffix", "]", ")", ")", ")", ")", ")", ")" ]
Generate a camel-case identifier. Useful for unit test methods. Takes a string, prefix, and optional suffix. `prefix` can be set to `''`, though be careful - without a prefix, the function will throw `InvalidIdentifier` when your string starts with a number. Example: >>> lower_camel("User can login", prefix='test') 'testUserCanLogin'
[ "Generate", "a", "camel", "-", "case", "identifier", ".", "Useful", "for", "unit", "test", "methods", "." ]
b8d27076254c65cfd7893c1401e2a198abd6afb4
https://github.com/nathforge/pydentifier/blob/b8d27076254c65cfd7893c1401e2a198abd6afb4/src/pydentifier/__init__.py#L74-L93
249,839
nathforge/pydentifier
src/pydentifier/__init__.py
is_valid
def is_valid(identifier): """ If the identifier is valid for Python, return True, otherwise False. """ return ( isinstance(identifier, six.string_types) and bool(NAME_RE.search(identifier)) and not keyword.iskeyword(identifier) )
python
def is_valid(identifier): """ If the identifier is valid for Python, return True, otherwise False. """ return ( isinstance(identifier, six.string_types) and bool(NAME_RE.search(identifier)) and not keyword.iskeyword(identifier) )
[ "def", "is_valid", "(", "identifier", ")", ":", "return", "(", "isinstance", "(", "identifier", ",", "six", ".", "string_types", ")", "and", "bool", "(", "NAME_RE", ".", "search", "(", "identifier", ")", ")", "and", "not", "keyword", ".", "iskeyword", "(", "identifier", ")", ")" ]
If the identifier is valid for Python, return True, otherwise False.
[ "If", "the", "identifier", "is", "valid", "for", "Python", "return", "True", "otherwise", "False", "." ]
b8d27076254c65cfd7893c1401e2a198abd6afb4
https://github.com/nathforge/pydentifier/blob/b8d27076254c65cfd7893c1401e2a198abd6afb4/src/pydentifier/__init__.py#L106-L115
249,840
20c/xbahn
xbahn/connection/__init__.py
receiver
def receiver(url, **kwargs): """ Return receiver instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080' """ res = url_to_resources(url) fnc = res["receiver"] return fnc(res.get("url"), **kwargs)
python
def receiver(url, **kwargs): """ Return receiver instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080' """ res = url_to_resources(url) fnc = res["receiver"] return fnc(res.get("url"), **kwargs)
[ "def", "receiver", "(", "url", ",", "*", "*", "kwargs", ")", ":", "res", "=", "url_to_resources", "(", "url", ")", "fnc", "=", "res", "[", "\"receiver\"", "]", "return", "fnc", "(", "res", ".", "get", "(", "\"url\"", ")", ",", "*", "*", "kwargs", ")" ]
Return receiver instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080'
[ "Return", "receiver", "instance", "from", "connection", "url", "string" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/__init__.py#L289-L297
249,841
20c/xbahn
xbahn/connection/__init__.py
sender
def sender(url, **kwargs): """ Return sender instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080' """ res = url_to_resources(url) fnc = res["sender"] return fnc(res.get("url"), **kwargs)
python
def sender(url, **kwargs): """ Return sender instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080' """ res = url_to_resources(url) fnc = res["sender"] return fnc(res.get("url"), **kwargs)
[ "def", "sender", "(", "url", ",", "*", "*", "kwargs", ")", ":", "res", "=", "url_to_resources", "(", "url", ")", "fnc", "=", "res", "[", "\"sender\"", "]", "return", "fnc", "(", "res", ".", "get", "(", "\"url\"", ")", ",", "*", "*", "kwargs", ")" ]
Return sender instance from connection url string url <str> connection url eg. 'tcp://0.0.0.0:8080'
[ "Return", "sender", "instance", "from", "connection", "url", "string" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/__init__.py#L299-L308
249,842
20c/xbahn
xbahn/connection/__init__.py
listen
def listen(url, prefix=None, **kwargs): """ bind and return a connection instance from url arguments: - url (str): xbahn connection url """ return listener(url, prefix=get_prefix(prefix), **kwargs)
python
def listen(url, prefix=None, **kwargs): """ bind and return a connection instance from url arguments: - url (str): xbahn connection url """ return listener(url, prefix=get_prefix(prefix), **kwargs)
[ "def", "listen", "(", "url", ",", "prefix", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "listener", "(", "url", ",", "prefix", "=", "get_prefix", "(", "prefix", ")", ",", "*", "*", "kwargs", ")" ]
bind and return a connection instance from url arguments: - url (str): xbahn connection url
[ "bind", "and", "return", "a", "connection", "instance", "from", "url" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/__init__.py#L320-L327
249,843
20c/xbahn
xbahn/connection/__init__.py
connect
def connect(url, prefix=None, **kwargs): """ connect and return a connection instance from url arguments: - url (str): xbahn connection url """ return connection(url, prefix=get_prefix(prefix), **kwargs)
python
def connect(url, prefix=None, **kwargs): """ connect and return a connection instance from url arguments: - url (str): xbahn connection url """ return connection(url, prefix=get_prefix(prefix), **kwargs)
[ "def", "connect", "(", "url", ",", "prefix", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "connection", "(", "url", ",", "prefix", "=", "get_prefix", "(", "prefix", ")", ",", "*", "*", "kwargs", ")" ]
connect and return a connection instance from url arguments: - url (str): xbahn connection url
[ "connect", "and", "return", "a", "connection", "instance", "from", "url" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/__init__.py#L329-L336
249,844
20c/xbahn
xbahn/connection/__init__.py
Connection.make_data
def make_data(self, message): """ make data string from message according to transport_content_type Returns: str: message data """ if not isinstance(message, Message): return message return message.export(self.transport_content_type)
python
def make_data(self, message): """ make data string from message according to transport_content_type Returns: str: message data """ if not isinstance(message, Message): return message return message.export(self.transport_content_type)
[ "def", "make_data", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "Message", ")", ":", "return", "message", "return", "message", ".", "export", "(", "self", ".", "transport_content_type", ")" ]
make data string from message according to transport_content_type Returns: str: message data
[ "make", "data", "string", "from", "message", "according", "to", "transport_content_type" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/__init__.py#L122-L134
249,845
20c/xbahn
xbahn/connection/__init__.py
Connection.make_message
def make_message(self, data): """ Create a Message instance from data, data will be loaded via munge according to the codec specified in the transport_content_type attribute Returns: Message: message object """ data = self.codec.loads(data) msg = Message( data.get("data"), *data.get("args",[]), **data.get("kwargs",{}) ) msg.meta.update(data.get("meta")) self.trigger("make_message", data, msg) return msg
python
def make_message(self, data): """ Create a Message instance from data, data will be loaded via munge according to the codec specified in the transport_content_type attribute Returns: Message: message object """ data = self.codec.loads(data) msg = Message( data.get("data"), *data.get("args",[]), **data.get("kwargs",{}) ) msg.meta.update(data.get("meta")) self.trigger("make_message", data, msg) return msg
[ "def", "make_message", "(", "self", ",", "data", ")", ":", "data", "=", "self", ".", "codec", ".", "loads", "(", "data", ")", "msg", "=", "Message", "(", "data", ".", "get", "(", "\"data\"", ")", ",", "*", "data", ".", "get", "(", "\"args\"", ",", "[", "]", ")", ",", "*", "*", "data", ".", "get", "(", "\"kwargs\"", ",", "{", "}", ")", ")", "msg", ".", "meta", ".", "update", "(", "data", ".", "get", "(", "\"meta\"", ")", ")", "self", ".", "trigger", "(", "\"make_message\"", ",", "data", ",", "msg", ")", "return", "msg" ]
Create a Message instance from data, data will be loaded via munge according to the codec specified in the transport_content_type attribute Returns: Message: message object
[ "Create", "a", "Message", "instance", "from", "data", "data", "will", "be", "loaded", "via", "munge", "according", "to", "the", "codec", "specified", "in", "the", "transport_content_type", "attribute" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/__init__.py#L136-L156
249,846
kshlm/gant
gant/utils/gant_docker.py
check_permissions
def check_permissions(): """ Checks if current user can access docker """ if ( not grp.getgrnam('docker').gr_gid in os.getgroups() and not os.geteuid() == 0 ): exitStr = """ User doesn't have permission to use docker. You can do either of the following, 1. Add user to the 'docker' group (preferred) 2. Run command as superuser using either 'sudo' or 'su -c' """ exit(exitStr)
python
def check_permissions(): """ Checks if current user can access docker """ if ( not grp.getgrnam('docker').gr_gid in os.getgroups() and not os.geteuid() == 0 ): exitStr = """ User doesn't have permission to use docker. You can do either of the following, 1. Add user to the 'docker' group (preferred) 2. Run command as superuser using either 'sudo' or 'su -c' """ exit(exitStr)
[ "def", "check_permissions", "(", ")", ":", "if", "(", "not", "grp", ".", "getgrnam", "(", "'docker'", ")", ".", "gr_gid", "in", "os", ".", "getgroups", "(", ")", "and", "not", "os", ".", "geteuid", "(", ")", "==", "0", ")", ":", "exitStr", "=", "\"\"\"\n User doesn't have permission to use docker.\n You can do either of the following,\n 1. Add user to the 'docker' group (preferred)\n 2. Run command as superuser using either 'sudo' or 'su -c'\n \"\"\"", "exit", "(", "exitStr", ")" ]
Checks if current user can access docker
[ "Checks", "if", "current", "user", "can", "access", "docker" ]
eabaa17ebfd31b1654ee1f27e7026f6d7b370609
https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L14-L28
249,847
kshlm/gant
gant/utils/gant_docker.py
GantDocker.build_base_image_cmd
def build_base_image_cmd(self, force): """ Build the glusterbase image """ check_permissions() basetag = self.conf.basetag basedir = self.conf.basedir verbose = self.conf.verbose if self.image_exists(tag=basetag): if not force: echo("Image with tag '{0}' already exists".format(basetag)) return self.image_by_tag(basetag) else: self.remove_image(basetag) echo("Building base image") stream = self.build(path=basedir, rm=True, tag=basetag) err = self.__handle_build_stream(stream, verbose) if err: echo("Building base image failed with following error:") echo(err) return None image = self.image_by_tag(basetag) echo("Built base image {0} (Id: {1})".format(basetag, image['Id'])) return image
python
def build_base_image_cmd(self, force): """ Build the glusterbase image """ check_permissions() basetag = self.conf.basetag basedir = self.conf.basedir verbose = self.conf.verbose if self.image_exists(tag=basetag): if not force: echo("Image with tag '{0}' already exists".format(basetag)) return self.image_by_tag(basetag) else: self.remove_image(basetag) echo("Building base image") stream = self.build(path=basedir, rm=True, tag=basetag) err = self.__handle_build_stream(stream, verbose) if err: echo("Building base image failed with following error:") echo(err) return None image = self.image_by_tag(basetag) echo("Built base image {0} (Id: {1})".format(basetag, image['Id'])) return image
[ "def", "build_base_image_cmd", "(", "self", ",", "force", ")", ":", "check_permissions", "(", ")", "basetag", "=", "self", ".", "conf", ".", "basetag", "basedir", "=", "self", ".", "conf", ".", "basedir", "verbose", "=", "self", ".", "conf", ".", "verbose", "if", "self", ".", "image_exists", "(", "tag", "=", "basetag", ")", ":", "if", "not", "force", ":", "echo", "(", "\"Image with tag '{0}' already exists\"", ".", "format", "(", "basetag", ")", ")", "return", "self", ".", "image_by_tag", "(", "basetag", ")", "else", ":", "self", ".", "remove_image", "(", "basetag", ")", "echo", "(", "\"Building base image\"", ")", "stream", "=", "self", ".", "build", "(", "path", "=", "basedir", ",", "rm", "=", "True", ",", "tag", "=", "basetag", ")", "err", "=", "self", ".", "__handle_build_stream", "(", "stream", ",", "verbose", ")", "if", "err", ":", "echo", "(", "\"Building base image failed with following error:\"", ")", "echo", "(", "err", ")", "return", "None", "image", "=", "self", ".", "image_by_tag", "(", "basetag", ")", "echo", "(", "\"Built base image {0} (Id: {1})\"", ".", "format", "(", "basetag", ",", "image", "[", "'Id'", "]", ")", ")", "return", "image" ]
Build the glusterbase image
[ "Build", "the", "glusterbase", "image" ]
eabaa17ebfd31b1654ee1f27e7026f6d7b370609
https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L50-L76
249,848
kshlm/gant
gant/utils/gant_docker.py
GantDocker.build_main_image_cmd
def build_main_image_cmd(self, srcdir, force): """ Build the main image to be used for launching containers """ check_permissions() basetag = self.conf.basetag basedir = self.conf.basedir maintag = self.conf.maintag if not self.image_exists(tag=basetag): if not force: exit("Base image with tag {0} does not exist".format(basetag)) else: echo("FORCE given. Forcefully building the base image.") self.build_base_image_cmd(force) if self.image_exists(tag=maintag): self.remove_image(tag=maintag) build_command = "/build/make-install-gluster.sh" container = self.create_container(image=basetag, command=build_command, volumes=["/build", "/src"]) self.start(container, binds={basedir: "/build", srcdir: "/src"}) echo('Building main image') while self.inspect_container(container)["State"]["Running"]: time.sleep(5) if not self.inspect_container(container)["State"]["ExitCode"] == 0: echo("Build failed") echo("Dumping logs") echo(self.logs(container)) exit() # The docker remote api expects the repository and tag to be seperate # items for commit repo = maintag.split(':')[0] tag = maintag.split(':')[1] image = self.commit(container['Id'], repository=repo, tag=tag) echo("Built main image {0} (Id: {1})".format(maintag, image['Id']))
python
def build_main_image_cmd(self, srcdir, force): """ Build the main image to be used for launching containers """ check_permissions() basetag = self.conf.basetag basedir = self.conf.basedir maintag = self.conf.maintag if not self.image_exists(tag=basetag): if not force: exit("Base image with tag {0} does not exist".format(basetag)) else: echo("FORCE given. Forcefully building the base image.") self.build_base_image_cmd(force) if self.image_exists(tag=maintag): self.remove_image(tag=maintag) build_command = "/build/make-install-gluster.sh" container = self.create_container(image=basetag, command=build_command, volumes=["/build", "/src"]) self.start(container, binds={basedir: "/build", srcdir: "/src"}) echo('Building main image') while self.inspect_container(container)["State"]["Running"]: time.sleep(5) if not self.inspect_container(container)["State"]["ExitCode"] == 0: echo("Build failed") echo("Dumping logs") echo(self.logs(container)) exit() # The docker remote api expects the repository and tag to be seperate # items for commit repo = maintag.split(':')[0] tag = maintag.split(':')[1] image = self.commit(container['Id'], repository=repo, tag=tag) echo("Built main image {0} (Id: {1})".format(maintag, image['Id']))
[ "def", "build_main_image_cmd", "(", "self", ",", "srcdir", ",", "force", ")", ":", "check_permissions", "(", ")", "basetag", "=", "self", ".", "conf", ".", "basetag", "basedir", "=", "self", ".", "conf", ".", "basedir", "maintag", "=", "self", ".", "conf", ".", "maintag", "if", "not", "self", ".", "image_exists", "(", "tag", "=", "basetag", ")", ":", "if", "not", "force", ":", "exit", "(", "\"Base image with tag {0} does not exist\"", ".", "format", "(", "basetag", ")", ")", "else", ":", "echo", "(", "\"FORCE given. Forcefully building the base image.\"", ")", "self", ".", "build_base_image_cmd", "(", "force", ")", "if", "self", ".", "image_exists", "(", "tag", "=", "maintag", ")", ":", "self", ".", "remove_image", "(", "tag", "=", "maintag", ")", "build_command", "=", "\"/build/make-install-gluster.sh\"", "container", "=", "self", ".", "create_container", "(", "image", "=", "basetag", ",", "command", "=", "build_command", ",", "volumes", "=", "[", "\"/build\"", ",", "\"/src\"", "]", ")", "self", ".", "start", "(", "container", ",", "binds", "=", "{", "basedir", ":", "\"/build\"", ",", "srcdir", ":", "\"/src\"", "}", ")", "echo", "(", "'Building main image'", ")", "while", "self", ".", "inspect_container", "(", "container", ")", "[", "\"State\"", "]", "[", "\"Running\"", "]", ":", "time", ".", "sleep", "(", "5", ")", "if", "not", "self", ".", "inspect_container", "(", "container", ")", "[", "\"State\"", "]", "[", "\"ExitCode\"", "]", "==", "0", ":", "echo", "(", "\"Build failed\"", ")", "echo", "(", "\"Dumping logs\"", ")", "echo", "(", "self", ".", "logs", "(", "container", ")", ")", "exit", "(", ")", "# The docker remote api expects the repository and tag to be seperate", "# items for commit", "repo", "=", "maintag", ".", "split", "(", "':'", ")", "[", "0", "]", "tag", "=", "maintag", ".", "split", "(", "':'", ")", "[", "1", "]", "image", "=", "self", ".", "commit", "(", "container", "[", "'Id'", "]", ",", "repository", "=", "repo", ",", "tag", "=", "tag", ")", "echo", "(", "\"Built main image {0} (Id: {1})\"", ".", "format", "(", "maintag", ",", "image", "[", "'Id'", "]", ")", ")" ]
Build the main image to be used for launching containers
[ "Build", "the", "main", "image", "to", "be", "used", "for", "launching", "containers" ]
eabaa17ebfd31b1654ee1f27e7026f6d7b370609
https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L78-L118
249,849
kshlm/gant
gant/utils/gant_docker.py
GantDocker.launch_cmd
def launch_cmd(self, n, force): """ Launch the specified docker containers using the main image """ check_permissions() prefix = self.conf.prefix maintag = self.conf.maintag commandStr = "supervisord -c /etc/supervisor/conf.d/supervisord.conf" for i in range(1, n+1): cName = "{0}-{1}".format(prefix, i) if self.container_exists(name=cName): if not force: exit("Container with name {0} already " "exists.".format(cName)) else: if self.container_running(name=cName): self.stop(cName) self.remove_container(cName, v=True) c = self.create_container(image=maintag, name=cName, command=commandStr, volumes=["/bricks"]) self.start(c['Id'], privileged=True) time.sleep(2) # Wait for container to startup echo("Launched {0} (Id: {1})".format(cName, c['Id'])) c = None cName = None
python
def launch_cmd(self, n, force): """ Launch the specified docker containers using the main image """ check_permissions() prefix = self.conf.prefix maintag = self.conf.maintag commandStr = "supervisord -c /etc/supervisor/conf.d/supervisord.conf" for i in range(1, n+1): cName = "{0}-{1}".format(prefix, i) if self.container_exists(name=cName): if not force: exit("Container with name {0} already " "exists.".format(cName)) else: if self.container_running(name=cName): self.stop(cName) self.remove_container(cName, v=True) c = self.create_container(image=maintag, name=cName, command=commandStr, volumes=["/bricks"]) self.start(c['Id'], privileged=True) time.sleep(2) # Wait for container to startup echo("Launched {0} (Id: {1})".format(cName, c['Id'])) c = None cName = None
[ "def", "launch_cmd", "(", "self", ",", "n", ",", "force", ")", ":", "check_permissions", "(", ")", "prefix", "=", "self", ".", "conf", ".", "prefix", "maintag", "=", "self", ".", "conf", ".", "maintag", "commandStr", "=", "\"supervisord -c /etc/supervisor/conf.d/supervisord.conf\"", "for", "i", "in", "range", "(", "1", ",", "n", "+", "1", ")", ":", "cName", "=", "\"{0}-{1}\"", ".", "format", "(", "prefix", ",", "i", ")", "if", "self", ".", "container_exists", "(", "name", "=", "cName", ")", ":", "if", "not", "force", ":", "exit", "(", "\"Container with name {0} already \"", "\"exists.\"", ".", "format", "(", "cName", ")", ")", "else", ":", "if", "self", ".", "container_running", "(", "name", "=", "cName", ")", ":", "self", ".", "stop", "(", "cName", ")", "self", ".", "remove_container", "(", "cName", ",", "v", "=", "True", ")", "c", "=", "self", ".", "create_container", "(", "image", "=", "maintag", ",", "name", "=", "cName", ",", "command", "=", "commandStr", ",", "volumes", "=", "[", "\"/bricks\"", "]", ")", "self", ".", "start", "(", "c", "[", "'Id'", "]", ",", "privileged", "=", "True", ")", "time", ".", "sleep", "(", "2", ")", "# Wait for container to startup", "echo", "(", "\"Launched {0} (Id: {1})\"", ".", "format", "(", "cName", ",", "c", "[", "'Id'", "]", ")", ")", "c", "=", "None", "cName", "=", "None" ]
Launch the specified docker containers using the main image
[ "Launch", "the", "specified", "docker", "containers", "using", "the", "main", "image" ]
eabaa17ebfd31b1654ee1f27e7026f6d7b370609
https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L120-L150
249,850
kshlm/gant
gant/utils/gant_docker.py
GantDocker.stop_cmd
def stop_cmd(self, name, force): """ Stop the specified or all docker containers launched by us """ check_permissions() if name: echo("Would stop container {0}".format(name)) else: echo("Would stop all containers") echo("For now use 'docker stop' to stop the containers")
python
def stop_cmd(self, name, force): """ Stop the specified or all docker containers launched by us """ check_permissions() if name: echo("Would stop container {0}".format(name)) else: echo("Would stop all containers") echo("For now use 'docker stop' to stop the containers")
[ "def", "stop_cmd", "(", "self", ",", "name", ",", "force", ")", ":", "check_permissions", "(", ")", "if", "name", ":", "echo", "(", "\"Would stop container {0}\"", ".", "format", "(", "name", ")", ")", "else", ":", "echo", "(", "\"Would stop all containers\"", ")", "echo", "(", "\"For now use 'docker stop' to stop the containers\"", ")" ]
Stop the specified or all docker containers launched by us
[ "Stop", "the", "specified", "or", "all", "docker", "containers", "launched", "by", "us" ]
eabaa17ebfd31b1654ee1f27e7026f6d7b370609
https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L152-L162
249,851
kshlm/gant
gant/utils/gant_docker.py
GantDocker.ssh_cmd
def ssh_cmd(self, name, ssh_command): """ SSH into given container and executre command if given """ if not self.container_exists(name=name): exit("Unknown container {0}".format(name)) if not self.container_running(name=name): exit("Container {0} is not running".format(name)) ip = self.get_container_ip(name) if not ip: exit("Failed to get network address for " "container {0}".format(name)) if ssh_command: ssh.do_cmd('root', ip, 'password', " ".join(ssh_command)) else: ssh.launch_shell('root', ip, 'password')
python
def ssh_cmd(self, name, ssh_command): """ SSH into given container and executre command if given """ if not self.container_exists(name=name): exit("Unknown container {0}".format(name)) if not self.container_running(name=name): exit("Container {0} is not running".format(name)) ip = self.get_container_ip(name) if not ip: exit("Failed to get network address for " "container {0}".format(name)) if ssh_command: ssh.do_cmd('root', ip, 'password', " ".join(ssh_command)) else: ssh.launch_shell('root', ip, 'password')
[ "def", "ssh_cmd", "(", "self", ",", "name", ",", "ssh_command", ")", ":", "if", "not", "self", ".", "container_exists", "(", "name", "=", "name", ")", ":", "exit", "(", "\"Unknown container {0}\"", ".", "format", "(", "name", ")", ")", "if", "not", "self", ".", "container_running", "(", "name", "=", "name", ")", ":", "exit", "(", "\"Container {0} is not running\"", ".", "format", "(", "name", ")", ")", "ip", "=", "self", ".", "get_container_ip", "(", "name", ")", "if", "not", "ip", ":", "exit", "(", "\"Failed to get network address for \"", "\"container {0}\"", ".", "format", "(", "name", ")", ")", "if", "ssh_command", ":", "ssh", ".", "do_cmd", "(", "'root'", ",", "ip", ",", "'password'", ",", "\" \"", ".", "join", "(", "ssh_command", ")", ")", "else", ":", "ssh", ".", "launch_shell", "(", "'root'", ",", "ip", ",", "'password'", ")" ]
SSH into given container and executre command if given
[ "SSH", "into", "given", "container", "and", "executre", "command", "if", "given" ]
eabaa17ebfd31b1654ee1f27e7026f6d7b370609
https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L170-L187
249,852
kshlm/gant
gant/utils/gant_docker.py
GantDocker.ip_cmd
def ip_cmd(self, name): """ Print ip of given container """ if not self.container_exists(name=name): exit('Unknown container {0}'.format(name)) ip = self.get_container_ip(name) if not ip: exit("Failed to get network address for" " container {0}".format(name)) else: echo(ip)
python
def ip_cmd(self, name): """ Print ip of given container """ if not self.container_exists(name=name): exit('Unknown container {0}'.format(name)) ip = self.get_container_ip(name) if not ip: exit("Failed to get network address for" " container {0}".format(name)) else: echo(ip)
[ "def", "ip_cmd", "(", "self", ",", "name", ")", ":", "if", "not", "self", ".", "container_exists", "(", "name", "=", "name", ")", ":", "exit", "(", "'Unknown container {0}'", ".", "format", "(", "name", ")", ")", "ip", "=", "self", ".", "get_container_ip", "(", "name", ")", "if", "not", "ip", ":", "exit", "(", "\"Failed to get network address for\"", "\" container {0}\"", ".", "format", "(", "name", ")", ")", "else", ":", "echo", "(", "ip", ")" ]
Print ip of given container
[ "Print", "ip", "of", "given", "container" ]
eabaa17ebfd31b1654ee1f27e7026f6d7b370609
https://github.com/kshlm/gant/blob/eabaa17ebfd31b1654ee1f27e7026f6d7b370609/gant/utils/gant_docker.py#L189-L201
249,853
florianpaquet/mease
mease/backends/base.py
BasePublisher.pack
def pack(self, message_type, client_id, client_storage, args, kwargs): """ Packs a message """ return pickle.dumps( (message_type, client_id, client_storage, args, kwargs), protocol=2)
python
def pack(self, message_type, client_id, client_storage, args, kwargs): """ Packs a message """ return pickle.dumps( (message_type, client_id, client_storage, args, kwargs), protocol=2)
[ "def", "pack", "(", "self", ",", "message_type", ",", "client_id", ",", "client_storage", ",", "args", ",", "kwargs", ")", ":", "return", "pickle", ".", "dumps", "(", "(", "message_type", ",", "client_id", ",", "client_storage", ",", "args", ",", "kwargs", ")", ",", "protocol", "=", "2", ")" ]
Packs a message
[ "Packs", "a", "message" ]
b9fbd08bbe162c8890c2a2124674371170c319ef
https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/base.py#L37-L42
249,854
florianpaquet/mease
mease/backends/base.py
BaseSubscriber.dispatch_message
def dispatch_message(self, message_type, client_id, client_storage, args, kwargs): """ Calls callback functions """ logger.debug("Backend message ({message_type}) : {args} {kwargs}".format( message_type=dict(MESSAGES_TYPES)[message_type], args=args, kwargs=kwargs)) if message_type in [ON_OPEN, ON_CLOSE, ON_RECEIVE]: # Find if client exists in clients_list client = next( (c for c in self.factory.clients_list if c._client_id == client_id), None) # Create a fake client if it doesn't exists if not client: client = FakeClient(storage=client_storage, factory=self.factory) if message_type == ON_OPEN: reactor.callInThread( self.factory.mease.call_openers, client, self.factory.clients_list) elif message_type == ON_CLOSE: reactor.callInThread( self.factory.mease.call_closers, client, self.factory.clients_list) elif message_type == ON_RECEIVE: reactor.callInThread( self.factory.mease.call_receivers, client, self.factory.clients_list, kwargs.get('message', '')) elif message_type == ON_SEND: routing = kwargs.pop('routing') reactor.callInThread( self.factory.mease.call_senders, routing, self.factory.clients_list, *args, **kwargs)
python
def dispatch_message(self, message_type, client_id, client_storage, args, kwargs): """ Calls callback functions """ logger.debug("Backend message ({message_type}) : {args} {kwargs}".format( message_type=dict(MESSAGES_TYPES)[message_type], args=args, kwargs=kwargs)) if message_type in [ON_OPEN, ON_CLOSE, ON_RECEIVE]: # Find if client exists in clients_list client = next( (c for c in self.factory.clients_list if c._client_id == client_id), None) # Create a fake client if it doesn't exists if not client: client = FakeClient(storage=client_storage, factory=self.factory) if message_type == ON_OPEN: reactor.callInThread( self.factory.mease.call_openers, client, self.factory.clients_list) elif message_type == ON_CLOSE: reactor.callInThread( self.factory.mease.call_closers, client, self.factory.clients_list) elif message_type == ON_RECEIVE: reactor.callInThread( self.factory.mease.call_receivers, client, self.factory.clients_list, kwargs.get('message', '')) elif message_type == ON_SEND: routing = kwargs.pop('routing') reactor.callInThread( self.factory.mease.call_senders, routing, self.factory.clients_list, *args, **kwargs)
[ "def", "dispatch_message", "(", "self", ",", "message_type", ",", "client_id", ",", "client_storage", ",", "args", ",", "kwargs", ")", ":", "logger", ".", "debug", "(", "\"Backend message ({message_type}) : {args} {kwargs}\"", ".", "format", "(", "message_type", "=", "dict", "(", "MESSAGES_TYPES", ")", "[", "message_type", "]", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", ")", "if", "message_type", "in", "[", "ON_OPEN", ",", "ON_CLOSE", ",", "ON_RECEIVE", "]", ":", "# Find if client exists in clients_list", "client", "=", "next", "(", "(", "c", "for", "c", "in", "self", ".", "factory", ".", "clients_list", "if", "c", ".", "_client_id", "==", "client_id", ")", ",", "None", ")", "# Create a fake client if it doesn't exists", "if", "not", "client", ":", "client", "=", "FakeClient", "(", "storage", "=", "client_storage", ",", "factory", "=", "self", ".", "factory", ")", "if", "message_type", "==", "ON_OPEN", ":", "reactor", ".", "callInThread", "(", "self", ".", "factory", ".", "mease", ".", "call_openers", ",", "client", ",", "self", ".", "factory", ".", "clients_list", ")", "elif", "message_type", "==", "ON_CLOSE", ":", "reactor", ".", "callInThread", "(", "self", ".", "factory", ".", "mease", ".", "call_closers", ",", "client", ",", "self", ".", "factory", ".", "clients_list", ")", "elif", "message_type", "==", "ON_RECEIVE", ":", "reactor", ".", "callInThread", "(", "self", ".", "factory", ".", "mease", ".", "call_receivers", ",", "client", ",", "self", ".", "factory", ".", "clients_list", ",", "kwargs", ".", "get", "(", "'message'", ",", "''", ")", ")", "elif", "message_type", "==", "ON_SEND", ":", "routing", "=", "kwargs", ".", "pop", "(", "'routing'", ")", "reactor", ".", "callInThread", "(", "self", ".", "factory", ".", "mease", ".", "call_senders", ",", "routing", ",", "self", ".", "factory", ".", "clients_list", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Calls callback functions
[ "Calls", "callback", "functions" ]
b9fbd08bbe162c8890c2a2124674371170c319ef
https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/backends/base.py#L71-L110
249,855
Zaeb0s/loop-function
loopfunction/loopfunction.py
Loop._loop
def _loop(self, *args, **kwargs): """Loops the target function :param args: The args specified on initiation :param kwargs: The kwargs specified on initiation """ self.on_start(*self.on_start_args, **self.on_start_kwargs) try: while not self._stop_signal: self.target(*args, **kwargs) finally: self.on_stop(*self.on_stop_args, **self.on_stop_kwargs) self._stop_signal = False self._lock.set()
python
def _loop(self, *args, **kwargs): """Loops the target function :param args: The args specified on initiation :param kwargs: The kwargs specified on initiation """ self.on_start(*self.on_start_args, **self.on_start_kwargs) try: while not self._stop_signal: self.target(*args, **kwargs) finally: self.on_stop(*self.on_stop_args, **self.on_stop_kwargs) self._stop_signal = False self._lock.set()
[ "def", "_loop", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "on_start", "(", "*", "self", ".", "on_start_args", ",", "*", "*", "self", ".", "on_start_kwargs", ")", "try", ":", "while", "not", "self", ".", "_stop_signal", ":", "self", ".", "target", "(", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "self", ".", "on_stop", "(", "*", "self", ".", "on_stop_args", ",", "*", "*", "self", ".", "on_stop_kwargs", ")", "self", ".", "_stop_signal", "=", "False", "self", ".", "_lock", ".", "set", "(", ")" ]
Loops the target function :param args: The args specified on initiation :param kwargs: The kwargs specified on initiation
[ "Loops", "the", "target", "function" ]
5999132aca5cf79b34e4ad5c05f9185712f1b583
https://github.com/Zaeb0s/loop-function/blob/5999132aca5cf79b34e4ad5c05f9185712f1b583/loopfunction/loopfunction.py#L48-L61
249,856
Zaeb0s/loop-function
loopfunction/loopfunction.py
Loop.start
def start(self, subthread=True): """Starts the loop Tries to start the loop. Raises RuntimeError if the loop is currently running. :param subthread: True/False value that specifies whether or not to start the loop within a subthread. If True the threading.Thread object is found in Loop._loop_thread. """ if self.is_running(): raise RuntimeError('Loop is currently running') else: self._lock.clear() self._stop_signal = False # just in case self._in_subthread = subthread if subthread: self._loop_thread = threading.Thread(target=self._loop, args=self.args, kwargs=self.kwargs) self._loop_thread.start() else: self._loop(*self.args, **self.kwargs)
python
def start(self, subthread=True): """Starts the loop Tries to start the loop. Raises RuntimeError if the loop is currently running. :param subthread: True/False value that specifies whether or not to start the loop within a subthread. If True the threading.Thread object is found in Loop._loop_thread. """ if self.is_running(): raise RuntimeError('Loop is currently running') else: self._lock.clear() self._stop_signal = False # just in case self._in_subthread = subthread if subthread: self._loop_thread = threading.Thread(target=self._loop, args=self.args, kwargs=self.kwargs) self._loop_thread.start() else: self._loop(*self.args, **self.kwargs)
[ "def", "start", "(", "self", ",", "subthread", "=", "True", ")", ":", "if", "self", ".", "is_running", "(", ")", ":", "raise", "RuntimeError", "(", "'Loop is currently running'", ")", "else", ":", "self", ".", "_lock", ".", "clear", "(", ")", "self", ".", "_stop_signal", "=", "False", "# just in case", "self", ".", "_in_subthread", "=", "subthread", "if", "subthread", ":", "self", ".", "_loop_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_loop", ",", "args", "=", "self", ".", "args", ",", "kwargs", "=", "self", ".", "kwargs", ")", "self", ".", "_loop_thread", ".", "start", "(", ")", "else", ":", "self", ".", "_loop", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwargs", ")" ]
Starts the loop Tries to start the loop. Raises RuntimeError if the loop is currently running. :param subthread: True/False value that specifies whether or not to start the loop within a subthread. If True the threading.Thread object is found in Loop._loop_thread.
[ "Starts", "the", "loop" ]
5999132aca5cf79b34e4ad5c05f9185712f1b583
https://github.com/Zaeb0s/loop-function/blob/5999132aca5cf79b34e4ad5c05f9185712f1b583/loopfunction/loopfunction.py#L63-L83
249,857
Zaeb0s/loop-function
loopfunction/loopfunction.py
Loop.stop
def stop(self, silent=False): """Sends a stop signal to the loop thread and waits until it stops A stop signal is sent using Loop.send_stop_signal(silent) (see docs for Loop.send_stop_signal) :param silent: True/False same parameter as in Loop.send_stop_signal(silent) """ self.send_stop_signal(silent) self._lock.wait()
python
def stop(self, silent=False): """Sends a stop signal to the loop thread and waits until it stops A stop signal is sent using Loop.send_stop_signal(silent) (see docs for Loop.send_stop_signal) :param silent: True/False same parameter as in Loop.send_stop_signal(silent) """ self.send_stop_signal(silent) self._lock.wait()
[ "def", "stop", "(", "self", ",", "silent", "=", "False", ")", ":", "self", ".", "send_stop_signal", "(", "silent", ")", "self", ".", "_lock", ".", "wait", "(", ")" ]
Sends a stop signal to the loop thread and waits until it stops A stop signal is sent using Loop.send_stop_signal(silent) (see docs for Loop.send_stop_signal) :param silent: True/False same parameter as in Loop.send_stop_signal(silent)
[ "Sends", "a", "stop", "signal", "to", "the", "loop", "thread", "and", "waits", "until", "it", "stops" ]
5999132aca5cf79b34e4ad5c05f9185712f1b583
https://github.com/Zaeb0s/loop-function/blob/5999132aca5cf79b34e4ad5c05f9185712f1b583/loopfunction/loopfunction.py#L85-L93
249,858
Zaeb0s/loop-function
loopfunction/loopfunction.py
Loop.send_stop_signal
def send_stop_signal(self, silent=False): """Sends a stop signal to the loop thread :param silent: True/False value that specifies whether or not to raise RuntimeError if the loop is currently not running :return: """ if self.is_running(): self._stop_signal = True elif not silent: raise RuntimeError('Loop is currently not running')
python
def send_stop_signal(self, silent=False): """Sends a stop signal to the loop thread :param silent: True/False value that specifies whether or not to raise RuntimeError if the loop is currently not running :return: """ if self.is_running(): self._stop_signal = True elif not silent: raise RuntimeError('Loop is currently not running')
[ "def", "send_stop_signal", "(", "self", ",", "silent", "=", "False", ")", ":", "if", "self", ".", "is_running", "(", ")", ":", "self", ".", "_stop_signal", "=", "True", "elif", "not", "silent", ":", "raise", "RuntimeError", "(", "'Loop is currently not running'", ")" ]
Sends a stop signal to the loop thread :param silent: True/False value that specifies whether or not to raise RuntimeError if the loop is currently not running :return:
[ "Sends", "a", "stop", "signal", "to", "the", "loop", "thread" ]
5999132aca5cf79b34e4ad5c05f9185712f1b583
https://github.com/Zaeb0s/loop-function/blob/5999132aca5cf79b34e4ad5c05f9185712f1b583/loopfunction/loopfunction.py#L95-L105
249,859
Zaeb0s/loop-function
loopfunction/loopfunction.py
Loop.restart
def restart(self, subthread=None): """Restarts the loop function Tries to restart the loop thread using the current thread. Raises RuntimeError if a previous call to Loop.start was not made. :param subthread: True/False value used when calling Loop.start(subthread=subthread). If set to None it uses the same value as the last call to Loop.start. """ if self._in_subthread is None: raise RuntimeError('A call to start must first be placed before restart') self.stop(silent=True) if subthread is None: subthread = self._in_subthread self.__init__(self.target, self.args, self.kwargs, self.on_stop) self.start(subthread=subthread)
python
def restart(self, subthread=None): """Restarts the loop function Tries to restart the loop thread using the current thread. Raises RuntimeError if a previous call to Loop.start was not made. :param subthread: True/False value used when calling Loop.start(subthread=subthread). If set to None it uses the same value as the last call to Loop.start. """ if self._in_subthread is None: raise RuntimeError('A call to start must first be placed before restart') self.stop(silent=True) if subthread is None: subthread = self._in_subthread self.__init__(self.target, self.args, self.kwargs, self.on_stop) self.start(subthread=subthread)
[ "def", "restart", "(", "self", ",", "subthread", "=", "None", ")", ":", "if", "self", ".", "_in_subthread", "is", "None", ":", "raise", "RuntimeError", "(", "'A call to start must first be placed before restart'", ")", "self", ".", "stop", "(", "silent", "=", "True", ")", "if", "subthread", "is", "None", ":", "subthread", "=", "self", ".", "_in_subthread", "self", ".", "__init__", "(", "self", ".", "target", ",", "self", ".", "args", ",", "self", ".", "kwargs", ",", "self", ".", "on_stop", ")", "self", ".", "start", "(", "subthread", "=", "subthread", ")" ]
Restarts the loop function Tries to restart the loop thread using the current thread. Raises RuntimeError if a previous call to Loop.start was not made. :param subthread: True/False value used when calling Loop.start(subthread=subthread). If set to None it uses the same value as the last call to Loop.start.
[ "Restarts", "the", "loop", "function" ]
5999132aca5cf79b34e4ad5c05f9185712f1b583
https://github.com/Zaeb0s/loop-function/blob/5999132aca5cf79b34e4ad5c05f9185712f1b583/loopfunction/loopfunction.py#L107-L122
249,860
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdfproperty.py
make_property
def make_property(prop_defs, prop_name, cls_names=[], hierarchy=[]): """ Generates a property class from the defintion dictionary args: prop_defs: the dictionary defining the property prop_name: the base name of the property cls_name: the name of the rdf_class with which the property is associated """ register = False try: cls_names.remove('RdfClassBase') except ValueError: pass if cls_names: new_name = "%s_%s" % (prop_name.pyuri, "_".join(cls_names)) prop_defs['kds_appliesToClass'] = cls_names elif not cls_names: cls_names = [Uri('kdr_AllClasses')] register = True new_name = prop_name else: new_name = prop_name new_prop = types.new_class(new_name, (RdfPropertyBase, list,), {'metaclass': RdfPropertyMeta, 'prop_defs': prop_defs, 'class_names': cls_names, 'prop_name': prop_name, 'hierarchy': hierarchy}) if register: global properties global domain_props properties[new_name] = new_prop for domain in new_prop.rdfs_domain: try: # domain_props[domain].append(new_prop) domain_props[domain][prop_name] = prop_defs except KeyError: # domain_props[domain] = [new_prop] domain_props[domain] = {} domain_props[domain][prop_name] = prop_defs except TypeError: pass return new_prop
python
def make_property(prop_defs, prop_name, cls_names=[], hierarchy=[]): """ Generates a property class from the defintion dictionary args: prop_defs: the dictionary defining the property prop_name: the base name of the property cls_name: the name of the rdf_class with which the property is associated """ register = False try: cls_names.remove('RdfClassBase') except ValueError: pass if cls_names: new_name = "%s_%s" % (prop_name.pyuri, "_".join(cls_names)) prop_defs['kds_appliesToClass'] = cls_names elif not cls_names: cls_names = [Uri('kdr_AllClasses')] register = True new_name = prop_name else: new_name = prop_name new_prop = types.new_class(new_name, (RdfPropertyBase, list,), {'metaclass': RdfPropertyMeta, 'prop_defs': prop_defs, 'class_names': cls_names, 'prop_name': prop_name, 'hierarchy': hierarchy}) if register: global properties global domain_props properties[new_name] = new_prop for domain in new_prop.rdfs_domain: try: # domain_props[domain].append(new_prop) domain_props[domain][prop_name] = prop_defs except KeyError: # domain_props[domain] = [new_prop] domain_props[domain] = {} domain_props[domain][prop_name] = prop_defs except TypeError: pass return new_prop
[ "def", "make_property", "(", "prop_defs", ",", "prop_name", ",", "cls_names", "=", "[", "]", ",", "hierarchy", "=", "[", "]", ")", ":", "register", "=", "False", "try", ":", "cls_names", ".", "remove", "(", "'RdfClassBase'", ")", "except", "ValueError", ":", "pass", "if", "cls_names", ":", "new_name", "=", "\"%s_%s\"", "%", "(", "prop_name", ".", "pyuri", ",", "\"_\"", ".", "join", "(", "cls_names", ")", ")", "prop_defs", "[", "'kds_appliesToClass'", "]", "=", "cls_names", "elif", "not", "cls_names", ":", "cls_names", "=", "[", "Uri", "(", "'kdr_AllClasses'", ")", "]", "register", "=", "True", "new_name", "=", "prop_name", "else", ":", "new_name", "=", "prop_name", "new_prop", "=", "types", ".", "new_class", "(", "new_name", ",", "(", "RdfPropertyBase", ",", "list", ",", ")", ",", "{", "'metaclass'", ":", "RdfPropertyMeta", ",", "'prop_defs'", ":", "prop_defs", ",", "'class_names'", ":", "cls_names", ",", "'prop_name'", ":", "prop_name", ",", "'hierarchy'", ":", "hierarchy", "}", ")", "if", "register", ":", "global", "properties", "global", "domain_props", "properties", "[", "new_name", "]", "=", "new_prop", "for", "domain", "in", "new_prop", ".", "rdfs_domain", ":", "try", ":", "# domain_props[domain].append(new_prop)", "domain_props", "[", "domain", "]", "[", "prop_name", "]", "=", "prop_defs", "except", "KeyError", ":", "# domain_props[domain] = [new_prop]", "domain_props", "[", "domain", "]", "=", "{", "}", "domain_props", "[", "domain", "]", "[", "prop_name", "]", "=", "prop_defs", "except", "TypeError", ":", "pass", "return", "new_prop" ]
Generates a property class from the defintion dictionary args: prop_defs: the dictionary defining the property prop_name: the base name of the property cls_name: the name of the rdf_class with which the property is associated
[ "Generates", "a", "property", "class", "from", "the", "defintion", "dictionary" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdfproperty.py#L313-L358
249,861
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdfproperty.py
link_property
def link_property(prop, cls_object): """ Generates a property class linked to the rdfclass args: prop: unlinked property class cls_name: the name of the rdf_class with which the property is associated cls_object: the rdf_class """ register = False cls_name = cls_object.__name__ if cls_name and cls_name != 'RdfBaseClass': new_name = "%s_%s" % (prop._prop_name, cls_name) else: new_name = prop._prop_name new_prop = types.new_class(new_name, (prop,), {'metaclass': RdfLinkedPropertyMeta, 'cls_name': cls_name, 'prop_name': prop._prop_name, 'linked_cls': cls_object}) return new_prop
python
def link_property(prop, cls_object): """ Generates a property class linked to the rdfclass args: prop: unlinked property class cls_name: the name of the rdf_class with which the property is associated cls_object: the rdf_class """ register = False cls_name = cls_object.__name__ if cls_name and cls_name != 'RdfBaseClass': new_name = "%s_%s" % (prop._prop_name, cls_name) else: new_name = prop._prop_name new_prop = types.new_class(new_name, (prop,), {'metaclass': RdfLinkedPropertyMeta, 'cls_name': cls_name, 'prop_name': prop._prop_name, 'linked_cls': cls_object}) return new_prop
[ "def", "link_property", "(", "prop", ",", "cls_object", ")", ":", "register", "=", "False", "cls_name", "=", "cls_object", ".", "__name__", "if", "cls_name", "and", "cls_name", "!=", "'RdfBaseClass'", ":", "new_name", "=", "\"%s_%s\"", "%", "(", "prop", ".", "_prop_name", ",", "cls_name", ")", "else", ":", "new_name", "=", "prop", ".", "_prop_name", "new_prop", "=", "types", ".", "new_class", "(", "new_name", ",", "(", "prop", ",", ")", ",", "{", "'metaclass'", ":", "RdfLinkedPropertyMeta", ",", "'cls_name'", ":", "cls_name", ",", "'prop_name'", ":", "prop", ".", "_prop_name", ",", "'linked_cls'", ":", "cls_object", "}", ")", "return", "new_prop" ]
Generates a property class linked to the rdfclass args: prop: unlinked property class cls_name: the name of the rdf_class with which the property is associated cls_object: the rdf_class
[ "Generates", "a", "property", "class", "linked", "to", "the", "rdfclass" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdfproperty.py#L361-L383
249,862
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdfproperty.py
get_properties
def get_properties(cls_def): """ cycles through the class definiton and returns all properties """ # pdb.set_trace() prop_list = {prop: value for prop, value in cls_def.items() \ if 'rdf_Property' in value.get('rdf_type', "") or \ value.get('rdfs_domain')} return prop_list
python
def get_properties(cls_def): """ cycles through the class definiton and returns all properties """ # pdb.set_trace() prop_list = {prop: value for prop, value in cls_def.items() \ if 'rdf_Property' in value.get('rdf_type', "") or \ value.get('rdfs_domain')} return prop_list
[ "def", "get_properties", "(", "cls_def", ")", ":", "# pdb.set_trace()", "prop_list", "=", "{", "prop", ":", "value", "for", "prop", ",", "value", "in", "cls_def", ".", "items", "(", ")", "if", "'rdf_Property'", "in", "value", ".", "get", "(", "'rdf_type'", ",", "\"\"", ")", "or", "value", ".", "get", "(", "'rdfs_domain'", ")", "}", "return", "prop_list" ]
cycles through the class definiton and returns all properties
[ "cycles", "through", "the", "class", "definiton", "and", "returns", "all", "properties" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdfproperty.py#L385-L392
249,863
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdfproperty.py
filter_prop_defs
def filter_prop_defs(prop_defs, hierarchy, cls_names): """ Reads through the prop_defs and returns a dictionary filtered by the current class args: prop_defs: the defintions from the rdf vocabulary defintion cls_object: the class object to tie the property cls_names: the name of the classes """ def _is_valid(test_list, valid_list): """ reads the list of classes in appliesToClass and returns whether the test_list matches args: test_list: the list of clasees to test against valid_list: list of possible matches """ for test in test_list: if test in valid_list: return True return False new_dict = {} valid_classes = [Uri('kdr_AllClasses')] + cls_names + hierarchy for def_name, value in prop_defs.items(): new_dict[def_name] = [] empty_def = [] try: for item in value: if item.get('kds_appliesToClass'): if _is_valid(item['kds_appliesToClass'], valid_classes): new_dict[def_name].append(item) else: empty_def.append(item) if not new_dict[def_name]: new_dict[def_name] = empty_def except AttributeError: new_dict[def_name] = value return new_dict
python
def filter_prop_defs(prop_defs, hierarchy, cls_names): """ Reads through the prop_defs and returns a dictionary filtered by the current class args: prop_defs: the defintions from the rdf vocabulary defintion cls_object: the class object to tie the property cls_names: the name of the classes """ def _is_valid(test_list, valid_list): """ reads the list of classes in appliesToClass and returns whether the test_list matches args: test_list: the list of clasees to test against valid_list: list of possible matches """ for test in test_list: if test in valid_list: return True return False new_dict = {} valid_classes = [Uri('kdr_AllClasses')] + cls_names + hierarchy for def_name, value in prop_defs.items(): new_dict[def_name] = [] empty_def = [] try: for item in value: if item.get('kds_appliesToClass'): if _is_valid(item['kds_appliesToClass'], valid_classes): new_dict[def_name].append(item) else: empty_def.append(item) if not new_dict[def_name]: new_dict[def_name] = empty_def except AttributeError: new_dict[def_name] = value return new_dict
[ "def", "filter_prop_defs", "(", "prop_defs", ",", "hierarchy", ",", "cls_names", ")", ":", "def", "_is_valid", "(", "test_list", ",", "valid_list", ")", ":", "\"\"\" reads the list of classes in appliesToClass and returns whether\n the test_list matches\n\n args:\n test_list: the list of clasees to test against\n valid_list: list of possible matches\n \"\"\"", "for", "test", "in", "test_list", ":", "if", "test", "in", "valid_list", ":", "return", "True", "return", "False", "new_dict", "=", "{", "}", "valid_classes", "=", "[", "Uri", "(", "'kdr_AllClasses'", ")", "]", "+", "cls_names", "+", "hierarchy", "for", "def_name", ",", "value", "in", "prop_defs", ".", "items", "(", ")", ":", "new_dict", "[", "def_name", "]", "=", "[", "]", "empty_def", "=", "[", "]", "try", ":", "for", "item", "in", "value", ":", "if", "item", ".", "get", "(", "'kds_appliesToClass'", ")", ":", "if", "_is_valid", "(", "item", "[", "'kds_appliesToClass'", "]", ",", "valid_classes", ")", ":", "new_dict", "[", "def_name", "]", ".", "append", "(", "item", ")", "else", ":", "empty_def", ".", "append", "(", "item", ")", "if", "not", "new_dict", "[", "def_name", "]", ":", "new_dict", "[", "def_name", "]", "=", "empty_def", "except", "AttributeError", ":", "new_dict", "[", "def_name", "]", "=", "value", "return", "new_dict" ]
Reads through the prop_defs and returns a dictionary filtered by the current class args: prop_defs: the defintions from the rdf vocabulary defintion cls_object: the class object to tie the property cls_names: the name of the classes
[ "Reads", "through", "the", "prop_defs", "and", "returns", "a", "dictionary", "filtered", "by", "the", "current", "class" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdfproperty.py#L423-L463
249,864
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdfproperty.py
get_processors
def get_processors(processor_cat, prop_defs, data_attr=None): """ reads the prop defs and adds applicable processors for the property Args: processor_cat(str): The category of processors to retreive prop_defs: property defintions as defined by the rdf defintions data_attr: the attr to manipulate during processing. Returns: list: a list of processors """ processor_defs = prop_defs.get(processor_cat,[]) processor_list = [] for processor in processor_defs: proc_class = PropertyProcessor[processor['rdf_type'][0]] processor_list.append(proc_class(processor.get('kds_params', [{}]), data_attr)) return processor_list
python
def get_processors(processor_cat, prop_defs, data_attr=None): """ reads the prop defs and adds applicable processors for the property Args: processor_cat(str): The category of processors to retreive prop_defs: property defintions as defined by the rdf defintions data_attr: the attr to manipulate during processing. Returns: list: a list of processors """ processor_defs = prop_defs.get(processor_cat,[]) processor_list = [] for processor in processor_defs: proc_class = PropertyProcessor[processor['rdf_type'][0]] processor_list.append(proc_class(processor.get('kds_params', [{}]), data_attr)) return processor_list
[ "def", "get_processors", "(", "processor_cat", ",", "prop_defs", ",", "data_attr", "=", "None", ")", ":", "processor_defs", "=", "prop_defs", ".", "get", "(", "processor_cat", ",", "[", "]", ")", "processor_list", "=", "[", "]", "for", "processor", "in", "processor_defs", ":", "proc_class", "=", "PropertyProcessor", "[", "processor", "[", "'rdf_type'", "]", "[", "0", "]", "]", "processor_list", ".", "append", "(", "proc_class", "(", "processor", ".", "get", "(", "'kds_params'", ",", "[", "{", "}", "]", ")", ",", "data_attr", ")", ")", "return", "processor_list" ]
reads the prop defs and adds applicable processors for the property Args: processor_cat(str): The category of processors to retreive prop_defs: property defintions as defined by the rdf defintions data_attr: the attr to manipulate during processing. Returns: list: a list of processors
[ "reads", "the", "prop", "defs", "and", "adds", "applicable", "processors", "for", "the", "property" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdfproperty.py#L601-L618
249,865
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdfproperty.py
merge_rdf_list
def merge_rdf_list(rdf_list): """ takes an rdf list and merges it into a python list args: rdf_list: the RdfDataset object with the list values returns: list of values """ # pdb.set_trace() if isinstance(rdf_list, list): rdf_list = rdf_list[0] rtn_list = [] # for item in rdf_list: item = rdf_list if item.get('rdf_rest') and item.get('rdf_rest',[1])[0] != 'rdf_nil': rtn_list += merge_rdf_list(item['rdf_rest'][0]) if item.get('rdf_first'): rtn_list += item['rdf_first'] rtn_list.reverse() return rtn_list
python
def merge_rdf_list(rdf_list): """ takes an rdf list and merges it into a python list args: rdf_list: the RdfDataset object with the list values returns: list of values """ # pdb.set_trace() if isinstance(rdf_list, list): rdf_list = rdf_list[0] rtn_list = [] # for item in rdf_list: item = rdf_list if item.get('rdf_rest') and item.get('rdf_rest',[1])[0] != 'rdf_nil': rtn_list += merge_rdf_list(item['rdf_rest'][0]) if item.get('rdf_first'): rtn_list += item['rdf_first'] rtn_list.reverse() return rtn_list
[ "def", "merge_rdf_list", "(", "rdf_list", ")", ":", "# pdb.set_trace()", "if", "isinstance", "(", "rdf_list", ",", "list", ")", ":", "rdf_list", "=", "rdf_list", "[", "0", "]", "rtn_list", "=", "[", "]", "# for item in rdf_list:", "item", "=", "rdf_list", "if", "item", ".", "get", "(", "'rdf_rest'", ")", "and", "item", ".", "get", "(", "'rdf_rest'", ",", "[", "1", "]", ")", "[", "0", "]", "!=", "'rdf_nil'", ":", "rtn_list", "+=", "merge_rdf_list", "(", "item", "[", "'rdf_rest'", "]", "[", "0", "]", ")", "if", "item", ".", "get", "(", "'rdf_first'", ")", ":", "rtn_list", "+=", "item", "[", "'rdf_first'", "]", "rtn_list", ".", "reverse", "(", ")", "return", "rtn_list" ]
takes an rdf list and merges it into a python list args: rdf_list: the RdfDataset object with the list values returns: list of values
[ "takes", "an", "rdf", "list", "and", "merges", "it", "into", "a", "python", "list" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdfproperty.py#L621-L641
249,866
KnowledgeLinks/rdfframework
rdfframework/rdfclass/rdfproperty.py
RdfPropertyBase.es_json
def es_json(self, **kwargs): """ Returns a JSON object of the property for insertion into es """ rtn_list = [] rng_defs = get_prop_range_defs(self.class_names, self.kds_rangeDef) # if self.__class__._prop_name == 'bf_partOf': # pdb.set_trace() rng_def = get_prop_range_def(rng_defs) idx_types = rng_def.get('kds_esIndexType', []).copy() if 'es_Ignore' in idx_types: return rtn_list ranges = self.rdfs_range # pylint: disable=no-member # copy the current data into the es_values attribute then run # the es_processors to manipulate that data self.es_values = self.copy() # determine if using inverseOf object if rng_def.get('kds_esLookup'): self.es_values += self.dataset.json_qry("%s.$" % getattr(self, rng_def['kds_esLookup'][0])[0].pyuri, {'$':self.bound_class.subject}) self.es_values = list(set(self.es_values)) self._run_processors(self._es_processors) if not idx_types: nested = False for rng in ranges: if range_is_obj(rng, MODULE.rdfclass): nested = True break value_class = [value.__class__ for value in self.es_values if isinstance(value, MODULE.rdfclass.RdfClassBase)] if value_class or nested: nested = True else: nested = False if nested: idx_types.append('es_Nested') rtn_obj = {} if 'es_Nested' in idx_types: if kwargs.get('depth', 0) > 6: return [val.subject.sparql_uri for val in self] for value in self.es_values: try: new_value = value.es_json('es_Nested', **kwargs) except AttributeError: new_value = convert_value_to_es(value, ranges, self, "missing_obj") rtn_list.append(new_value) if rng_def.get("kds_esField"): es_value_fld = rng_def['kds_esValue'][0] \ if rng_def['kds_esValue'] else None es_field = rng_def['kds_esField'][0] for item in value.get(es_field): if new_value.get(es_value_fld): val = new_value.get(es_value_fld , []) try: rtn_obj[item.pyuri] += val except KeyError: rtn_obj[item.pyuri] = val else: for value in self.es_values: rtn_list.append(convert_value_to_es(value, ranges, self)) if rtn_obj: return rtn_obj return rtn_list
python
def es_json(self, **kwargs): """ Returns a JSON object of the property for insertion into es """ rtn_list = [] rng_defs = get_prop_range_defs(self.class_names, self.kds_rangeDef) # if self.__class__._prop_name == 'bf_partOf': # pdb.set_trace() rng_def = get_prop_range_def(rng_defs) idx_types = rng_def.get('kds_esIndexType', []).copy() if 'es_Ignore' in idx_types: return rtn_list ranges = self.rdfs_range # pylint: disable=no-member # copy the current data into the es_values attribute then run # the es_processors to manipulate that data self.es_values = self.copy() # determine if using inverseOf object if rng_def.get('kds_esLookup'): self.es_values += self.dataset.json_qry("%s.$" % getattr(self, rng_def['kds_esLookup'][0])[0].pyuri, {'$':self.bound_class.subject}) self.es_values = list(set(self.es_values)) self._run_processors(self._es_processors) if not idx_types: nested = False for rng in ranges: if range_is_obj(rng, MODULE.rdfclass): nested = True break value_class = [value.__class__ for value in self.es_values if isinstance(value, MODULE.rdfclass.RdfClassBase)] if value_class or nested: nested = True else: nested = False if nested: idx_types.append('es_Nested') rtn_obj = {} if 'es_Nested' in idx_types: if kwargs.get('depth', 0) > 6: return [val.subject.sparql_uri for val in self] for value in self.es_values: try: new_value = value.es_json('es_Nested', **kwargs) except AttributeError: new_value = convert_value_to_es(value, ranges, self, "missing_obj") rtn_list.append(new_value) if rng_def.get("kds_esField"): es_value_fld = rng_def['kds_esValue'][0] \ if rng_def['kds_esValue'] else None es_field = rng_def['kds_esField'][0] for item in value.get(es_field): if new_value.get(es_value_fld): val = new_value.get(es_value_fld , []) try: rtn_obj[item.pyuri] += val except KeyError: rtn_obj[item.pyuri] = val else: for value in self.es_values: rtn_list.append(convert_value_to_es(value, ranges, self)) if rtn_obj: return rtn_obj return rtn_list
[ "def", "es_json", "(", "self", ",", "*", "*", "kwargs", ")", ":", "rtn_list", "=", "[", "]", "rng_defs", "=", "get_prop_range_defs", "(", "self", ".", "class_names", ",", "self", ".", "kds_rangeDef", ")", "# if self.__class__._prop_name == 'bf_partOf':", "# pdb.set_trace()", "rng_def", "=", "get_prop_range_def", "(", "rng_defs", ")", "idx_types", "=", "rng_def", ".", "get", "(", "'kds_esIndexType'", ",", "[", "]", ")", ".", "copy", "(", ")", "if", "'es_Ignore'", "in", "idx_types", ":", "return", "rtn_list", "ranges", "=", "self", ".", "rdfs_range", "# pylint: disable=no-member", "# copy the current data into the es_values attribute then run", "# the es_processors to manipulate that data", "self", ".", "es_values", "=", "self", ".", "copy", "(", ")", "# determine if using inverseOf object", "if", "rng_def", ".", "get", "(", "'kds_esLookup'", ")", ":", "self", ".", "es_values", "+=", "self", ".", "dataset", ".", "json_qry", "(", "\"%s.$\"", "%", "getattr", "(", "self", ",", "rng_def", "[", "'kds_esLookup'", "]", "[", "0", "]", ")", "[", "0", "]", ".", "pyuri", ",", "{", "'$'", ":", "self", ".", "bound_class", ".", "subject", "}", ")", "self", ".", "es_values", "=", "list", "(", "set", "(", "self", ".", "es_values", ")", ")", "self", ".", "_run_processors", "(", "self", ".", "_es_processors", ")", "if", "not", "idx_types", ":", "nested", "=", "False", "for", "rng", "in", "ranges", ":", "if", "range_is_obj", "(", "rng", ",", "MODULE", ".", "rdfclass", ")", ":", "nested", "=", "True", "break", "value_class", "=", "[", "value", ".", "__class__", "for", "value", "in", "self", ".", "es_values", "if", "isinstance", "(", "value", ",", "MODULE", ".", "rdfclass", ".", "RdfClassBase", ")", "]", "if", "value_class", "or", "nested", ":", "nested", "=", "True", "else", ":", "nested", "=", "False", "if", "nested", ":", "idx_types", ".", "append", "(", "'es_Nested'", ")", "rtn_obj", "=", "{", "}", "if", "'es_Nested'", "in", "idx_types", ":", "if", "kwargs", ".", "get", "(", "'depth'", ",", "0", ")", ">", "6", ":", "return", "[", "val", ".", "subject", ".", "sparql_uri", "for", "val", "in", "self", "]", "for", "value", "in", "self", ".", "es_values", ":", "try", ":", "new_value", "=", "value", ".", "es_json", "(", "'es_Nested'", ",", "*", "*", "kwargs", ")", "except", "AttributeError", ":", "new_value", "=", "convert_value_to_es", "(", "value", ",", "ranges", ",", "self", ",", "\"missing_obj\"", ")", "rtn_list", ".", "append", "(", "new_value", ")", "if", "rng_def", ".", "get", "(", "\"kds_esField\"", ")", ":", "es_value_fld", "=", "rng_def", "[", "'kds_esValue'", "]", "[", "0", "]", "if", "rng_def", "[", "'kds_esValue'", "]", "else", "None", "es_field", "=", "rng_def", "[", "'kds_esField'", "]", "[", "0", "]", "for", "item", "in", "value", ".", "get", "(", "es_field", ")", ":", "if", "new_value", ".", "get", "(", "es_value_fld", ")", ":", "val", "=", "new_value", ".", "get", "(", "es_value_fld", ",", "[", "]", ")", "try", ":", "rtn_obj", "[", "item", ".", "pyuri", "]", "+=", "val", "except", "KeyError", ":", "rtn_obj", "[", "item", ".", "pyuri", "]", "=", "val", "else", ":", "for", "value", "in", "self", ".", "es_values", ":", "rtn_list", ".", "append", "(", "convert_value_to_es", "(", "value", ",", "ranges", ",", "self", ")", ")", "if", "rtn_obj", ":", "return", "rtn_obj", "return", "rtn_list" ]
Returns a JSON object of the property for insertion into es
[ "Returns", "a", "JSON", "object", "of", "the", "property", "for", "insertion", "into", "es" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/rdfproperty.py#L242-L310
249,867
laysakura/relshell
relshell/batch_command.py
BatchCommand._parse_in_batches
def _parse_in_batches(cmd_array): """Find patterns that match to `in_batches_pat` and replace them into `STDIN` or `TMPFILE`. :param cmd_array: `shlex.split`-ed command :rtype: ([cmd_array], ( batch_to_file, batch_to_file, ... ) ) :returns: Modified `cmd_array` and tuple to show how each IN_BATCH is instantiated (TMPFILE or STDIN). Returned `cmd_array` drops IN_BATCH related tokens. :raises: `IndexError` if IN_BATCHes don't have sequential ID starting from 0 """ res_cmd_array = cmd_array[:] res_batch_to_file_s = [] in_batches_cmdidx = BatchCommand._in_batches_cmdidx(cmd_array) for batch_id, cmdidx in enumerate(in_batches_cmdidx): if cmdidx > 0 and cmd_array[cmdidx - 1] == '<': # e.g. `< IN_BATCH0` res_batch_to_file_s.append(BatchToFile('STDIN')) del res_cmd_array[cmdidx], res_cmd_array[cmdidx - 1] else: # IN_BATCHx is TMPFILE batch_to_file = BatchToFile('TMPFILE') res_batch_to_file_s.append(batch_to_file) res_cmd_array[cmdidx] = batch_to_file.tmpfile_path() return (res_cmd_array, tuple(res_batch_to_file_s))
python
def _parse_in_batches(cmd_array): """Find patterns that match to `in_batches_pat` and replace them into `STDIN` or `TMPFILE`. :param cmd_array: `shlex.split`-ed command :rtype: ([cmd_array], ( batch_to_file, batch_to_file, ... ) ) :returns: Modified `cmd_array` and tuple to show how each IN_BATCH is instantiated (TMPFILE or STDIN). Returned `cmd_array` drops IN_BATCH related tokens. :raises: `IndexError` if IN_BATCHes don't have sequential ID starting from 0 """ res_cmd_array = cmd_array[:] res_batch_to_file_s = [] in_batches_cmdidx = BatchCommand._in_batches_cmdidx(cmd_array) for batch_id, cmdidx in enumerate(in_batches_cmdidx): if cmdidx > 0 and cmd_array[cmdidx - 1] == '<': # e.g. `< IN_BATCH0` res_batch_to_file_s.append(BatchToFile('STDIN')) del res_cmd_array[cmdidx], res_cmd_array[cmdidx - 1] else: # IN_BATCHx is TMPFILE batch_to_file = BatchToFile('TMPFILE') res_batch_to_file_s.append(batch_to_file) res_cmd_array[cmdidx] = batch_to_file.tmpfile_path() return (res_cmd_array, tuple(res_batch_to_file_s))
[ "def", "_parse_in_batches", "(", "cmd_array", ")", ":", "res_cmd_array", "=", "cmd_array", "[", ":", "]", "res_batch_to_file_s", "=", "[", "]", "in_batches_cmdidx", "=", "BatchCommand", ".", "_in_batches_cmdidx", "(", "cmd_array", ")", "for", "batch_id", ",", "cmdidx", "in", "enumerate", "(", "in_batches_cmdidx", ")", ":", "if", "cmdidx", ">", "0", "and", "cmd_array", "[", "cmdidx", "-", "1", "]", "==", "'<'", ":", "# e.g. `< IN_BATCH0`", "res_batch_to_file_s", ".", "append", "(", "BatchToFile", "(", "'STDIN'", ")", ")", "del", "res_cmd_array", "[", "cmdidx", "]", ",", "res_cmd_array", "[", "cmdidx", "-", "1", "]", "else", ":", "# IN_BATCHx is TMPFILE", "batch_to_file", "=", "BatchToFile", "(", "'TMPFILE'", ")", "res_batch_to_file_s", ".", "append", "(", "batch_to_file", ")", "res_cmd_array", "[", "cmdidx", "]", "=", "batch_to_file", ".", "tmpfile_path", "(", ")", "return", "(", "res_cmd_array", ",", "tuple", "(", "res_batch_to_file_s", ")", ")" ]
Find patterns that match to `in_batches_pat` and replace them into `STDIN` or `TMPFILE`. :param cmd_array: `shlex.split`-ed command :rtype: ([cmd_array], ( batch_to_file, batch_to_file, ... ) ) :returns: Modified `cmd_array` and tuple to show how each IN_BATCH is instantiated (TMPFILE or STDIN). Returned `cmd_array` drops IN_BATCH related tokens. :raises: `IndexError` if IN_BATCHes don't have sequential ID starting from 0
[ "Find", "patterns", "that", "match", "to", "in_batches_pat", "and", "replace", "them", "into", "STDIN", "or", "TMPFILE", "." ]
9ca5c03a34c11cb763a4a75595f18bf4383aa8cc
https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch_command.py#L60-L83
249,868
laysakura/relshell
relshell/batch_command.py
BatchCommand._parse_out_batch
def _parse_out_batch(cmd_array): """Find patterns that match to `out_batch_pat` and replace them into `STDOUT` or `TMPFILE`. :param cmd_array: `shlex.split`-ed command :rtype: ([cmd_array], batch_from_file) :returns: Modified `cmd_array` and tuple to show how OUT_BATCH is instantiated (TMPFILE or STDOUT). Returned `cmd_array` drops OUT_BATCH related tokens. :raises: `IndexError` if multiple OUT_BATCH are found """ res_cmd_array = cmd_array[:] res_batch_from_file = None out_batch_cmdidx = BatchCommand._out_batch_cmdidx(cmd_array) if out_batch_cmdidx is None: return (res_cmd_array, res_batch_from_file) if out_batch_cmdidx > 0 and cmd_array[out_batch_cmdidx - 1] == '>': # e.g. `> OUT_BATCH` res_batch_from_file = BatchFromFile('STDOUT') del res_cmd_array[out_batch_cmdidx], res_cmd_array[out_batch_cmdidx - 1] else: # OUT_BATCH is TMPFILE res_batch_from_file = BatchFromFile('TMPFILE') res_cmd_array[out_batch_cmdidx] = res_batch_from_file.tmpfile_path() return (res_cmd_array, res_batch_from_file)
python
def _parse_out_batch(cmd_array): """Find patterns that match to `out_batch_pat` and replace them into `STDOUT` or `TMPFILE`. :param cmd_array: `shlex.split`-ed command :rtype: ([cmd_array], batch_from_file) :returns: Modified `cmd_array` and tuple to show how OUT_BATCH is instantiated (TMPFILE or STDOUT). Returned `cmd_array` drops OUT_BATCH related tokens. :raises: `IndexError` if multiple OUT_BATCH are found """ res_cmd_array = cmd_array[:] res_batch_from_file = None out_batch_cmdidx = BatchCommand._out_batch_cmdidx(cmd_array) if out_batch_cmdidx is None: return (res_cmd_array, res_batch_from_file) if out_batch_cmdidx > 0 and cmd_array[out_batch_cmdidx - 1] == '>': # e.g. `> OUT_BATCH` res_batch_from_file = BatchFromFile('STDOUT') del res_cmd_array[out_batch_cmdidx], res_cmd_array[out_batch_cmdidx - 1] else: # OUT_BATCH is TMPFILE res_batch_from_file = BatchFromFile('TMPFILE') res_cmd_array[out_batch_cmdidx] = res_batch_from_file.tmpfile_path() return (res_cmd_array, res_batch_from_file)
[ "def", "_parse_out_batch", "(", "cmd_array", ")", ":", "res_cmd_array", "=", "cmd_array", "[", ":", "]", "res_batch_from_file", "=", "None", "out_batch_cmdidx", "=", "BatchCommand", ".", "_out_batch_cmdidx", "(", "cmd_array", ")", "if", "out_batch_cmdidx", "is", "None", ":", "return", "(", "res_cmd_array", ",", "res_batch_from_file", ")", "if", "out_batch_cmdidx", ">", "0", "and", "cmd_array", "[", "out_batch_cmdidx", "-", "1", "]", "==", "'>'", ":", "# e.g. `> OUT_BATCH`", "res_batch_from_file", "=", "BatchFromFile", "(", "'STDOUT'", ")", "del", "res_cmd_array", "[", "out_batch_cmdidx", "]", ",", "res_cmd_array", "[", "out_batch_cmdidx", "-", "1", "]", "else", ":", "# OUT_BATCH is TMPFILE", "res_batch_from_file", "=", "BatchFromFile", "(", "'TMPFILE'", ")", "res_cmd_array", "[", "out_batch_cmdidx", "]", "=", "res_batch_from_file", ".", "tmpfile_path", "(", ")", "return", "(", "res_cmd_array", ",", "res_batch_from_file", ")" ]
Find patterns that match to `out_batch_pat` and replace them into `STDOUT` or `TMPFILE`. :param cmd_array: `shlex.split`-ed command :rtype: ([cmd_array], batch_from_file) :returns: Modified `cmd_array` and tuple to show how OUT_BATCH is instantiated (TMPFILE or STDOUT). Returned `cmd_array` drops OUT_BATCH related tokens. :raises: `IndexError` if multiple OUT_BATCH are found
[ "Find", "patterns", "that", "match", "to", "out_batch_pat", "and", "replace", "them", "into", "STDOUT", "or", "TMPFILE", "." ]
9ca5c03a34c11cb763a4a75595f18bf4383aa8cc
https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch_command.py#L86-L110
249,869
laysakura/relshell
relshell/batch_command.py
BatchCommand._in_batches_cmdidx
def _in_batches_cmdidx(cmd_array): """Raise `IndexError` if IN_BATCH0 - IN_BATCHx is not used sequentially in `cmd_array` :returns: (IN_BATCH0's cmdidx, IN_BATCH1's cmdidx, ...) $ cat a.txt IN_BATCH1 IN_BATCH0 b.txt c.txt IN_BATCH2 => (3, 2, 5) """ in_batches_cmdidx_dict = {} for cmdidx, tok in enumerate(cmd_array): mat = BatchCommand.in_batches_pat.match(tok) if mat: batch_idx = int(mat.group(1)) if batch_idx in in_batches_cmdidx_dict: raise IndexError( 'IN_BATCH%d is used multiple times in command below, while IN_BATCH0 - IN_BATCH%d must be used:%s$ %s' % (batch_idx, len(in_batches_cmdidx_dict) - 1, os.linesep, list2cmdline(cmd_array))) in_batches_cmdidx_dict[batch_idx] = cmdidx in_batches_cmdidx = [] for batch_idx in range(len(in_batches_cmdidx_dict)): try: cmdidx = in_batches_cmdidx_dict[batch_idx] in_batches_cmdidx.append(cmdidx) except KeyError: raise IndexError('IN_BATCH%d is not found in command below, while IN_BATCH0 - IN_BATCH%d must be used:%s$ %s' % (batch_idx, len(in_batches_cmdidx_dict) - 1, os.linesep, list2cmdline(cmd_array))) return tuple(in_batches_cmdidx)
python
def _in_batches_cmdidx(cmd_array): """Raise `IndexError` if IN_BATCH0 - IN_BATCHx is not used sequentially in `cmd_array` :returns: (IN_BATCH0's cmdidx, IN_BATCH1's cmdidx, ...) $ cat a.txt IN_BATCH1 IN_BATCH0 b.txt c.txt IN_BATCH2 => (3, 2, 5) """ in_batches_cmdidx_dict = {} for cmdidx, tok in enumerate(cmd_array): mat = BatchCommand.in_batches_pat.match(tok) if mat: batch_idx = int(mat.group(1)) if batch_idx in in_batches_cmdidx_dict: raise IndexError( 'IN_BATCH%d is used multiple times in command below, while IN_BATCH0 - IN_BATCH%d must be used:%s$ %s' % (batch_idx, len(in_batches_cmdidx_dict) - 1, os.linesep, list2cmdline(cmd_array))) in_batches_cmdidx_dict[batch_idx] = cmdidx in_batches_cmdidx = [] for batch_idx in range(len(in_batches_cmdidx_dict)): try: cmdidx = in_batches_cmdidx_dict[batch_idx] in_batches_cmdidx.append(cmdidx) except KeyError: raise IndexError('IN_BATCH%d is not found in command below, while IN_BATCH0 - IN_BATCH%d must be used:%s$ %s' % (batch_idx, len(in_batches_cmdidx_dict) - 1, os.linesep, list2cmdline(cmd_array))) return tuple(in_batches_cmdidx)
[ "def", "_in_batches_cmdidx", "(", "cmd_array", ")", ":", "in_batches_cmdidx_dict", "=", "{", "}", "for", "cmdidx", ",", "tok", "in", "enumerate", "(", "cmd_array", ")", ":", "mat", "=", "BatchCommand", ".", "in_batches_pat", ".", "match", "(", "tok", ")", "if", "mat", ":", "batch_idx", "=", "int", "(", "mat", ".", "group", "(", "1", ")", ")", "if", "batch_idx", "in", "in_batches_cmdidx_dict", ":", "raise", "IndexError", "(", "'IN_BATCH%d is used multiple times in command below, while IN_BATCH0 - IN_BATCH%d must be used:%s$ %s'", "%", "(", "batch_idx", ",", "len", "(", "in_batches_cmdidx_dict", ")", "-", "1", ",", "os", ".", "linesep", ",", "list2cmdline", "(", "cmd_array", ")", ")", ")", "in_batches_cmdidx_dict", "[", "batch_idx", "]", "=", "cmdidx", "in_batches_cmdidx", "=", "[", "]", "for", "batch_idx", "in", "range", "(", "len", "(", "in_batches_cmdidx_dict", ")", ")", ":", "try", ":", "cmdidx", "=", "in_batches_cmdidx_dict", "[", "batch_idx", "]", "in_batches_cmdidx", ".", "append", "(", "cmdidx", ")", "except", "KeyError", ":", "raise", "IndexError", "(", "'IN_BATCH%d is not found in command below, while IN_BATCH0 - IN_BATCH%d must be used:%s$ %s'", "%", "(", "batch_idx", ",", "len", "(", "in_batches_cmdidx_dict", ")", "-", "1", ",", "os", ".", "linesep", ",", "list2cmdline", "(", "cmd_array", ")", ")", ")", "return", "tuple", "(", "in_batches_cmdidx", ")" ]
Raise `IndexError` if IN_BATCH0 - IN_BATCHx is not used sequentially in `cmd_array` :returns: (IN_BATCH0's cmdidx, IN_BATCH1's cmdidx, ...) $ cat a.txt IN_BATCH1 IN_BATCH0 b.txt c.txt IN_BATCH2 => (3, 2, 5)
[ "Raise", "IndexError", "if", "IN_BATCH0", "-", "IN_BATCHx", "is", "not", "used", "sequentially", "in", "cmd_array" ]
9ca5c03a34c11cb763a4a75595f18bf4383aa8cc
https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch_command.py#L113-L139
249,870
laysakura/relshell
relshell/batch_command.py
BatchCommand._out_batch_cmdidx
def _out_batch_cmdidx(cmd_array): """Raise `IndexError` if OUT_BATCH is used multiple time :returns: OUT_BATCH cmdidx (None if OUT_BATCH is not in `cmd_array`) $ cat a.txt > OUT_BATCH => 3 """ out_batch_cmdidx = None for cmdidx, tok in enumerate(cmd_array): mat = BatchCommand.out_batch_pat.match(tok) if mat: if out_batch_cmdidx: raise IndexError( 'OUT_BATCH is used multiple times in command below:%s$ %s' % (os.linesep, list2cmdline(cmd_array))) out_batch_cmdidx = cmdidx return out_batch_cmdidx
python
def _out_batch_cmdidx(cmd_array): """Raise `IndexError` if OUT_BATCH is used multiple time :returns: OUT_BATCH cmdidx (None if OUT_BATCH is not in `cmd_array`) $ cat a.txt > OUT_BATCH => 3 """ out_batch_cmdidx = None for cmdidx, tok in enumerate(cmd_array): mat = BatchCommand.out_batch_pat.match(tok) if mat: if out_batch_cmdidx: raise IndexError( 'OUT_BATCH is used multiple times in command below:%s$ %s' % (os.linesep, list2cmdline(cmd_array))) out_batch_cmdidx = cmdidx return out_batch_cmdidx
[ "def", "_out_batch_cmdidx", "(", "cmd_array", ")", ":", "out_batch_cmdidx", "=", "None", "for", "cmdidx", ",", "tok", "in", "enumerate", "(", "cmd_array", ")", ":", "mat", "=", "BatchCommand", ".", "out_batch_pat", ".", "match", "(", "tok", ")", "if", "mat", ":", "if", "out_batch_cmdidx", ":", "raise", "IndexError", "(", "'OUT_BATCH is used multiple times in command below:%s$ %s'", "%", "(", "os", ".", "linesep", ",", "list2cmdline", "(", "cmd_array", ")", ")", ")", "out_batch_cmdidx", "=", "cmdidx", "return", "out_batch_cmdidx" ]
Raise `IndexError` if OUT_BATCH is used multiple time :returns: OUT_BATCH cmdidx (None if OUT_BATCH is not in `cmd_array`) $ cat a.txt > OUT_BATCH => 3
[ "Raise", "IndexError", "if", "OUT_BATCH", "is", "used", "multiple", "time" ]
9ca5c03a34c11cb763a4a75595f18bf4383aa8cc
https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/batch_command.py#L142-L157
249,871
mouse-reeve/nomina-flora
nominaflora/NominaFlora.py
NominaFlora.get_builder
def get_builder(self, corpus): ''' creates a builder object for a wordlist ''' builder = WordBuilder(chunk_size=self.chunk_size) builder.ingest(corpus) return builder
python
def get_builder(self, corpus): ''' creates a builder object for a wordlist ''' builder = WordBuilder(chunk_size=self.chunk_size) builder.ingest(corpus) return builder
[ "def", "get_builder", "(", "self", ",", "corpus", ")", ":", "builder", "=", "WordBuilder", "(", "chunk_size", "=", "self", ".", "chunk_size", ")", "builder", ".", "ingest", "(", "corpus", ")", "return", "builder" ]
creates a builder object for a wordlist
[ "creates", "a", "builder", "object", "for", "a", "wordlist" ]
d99723b95d169dc38021a38c1f9d1f9f2b04c46b
https://github.com/mouse-reeve/nomina-flora/blob/d99723b95d169dc38021a38c1f9d1f9f2b04c46b/nominaflora/NominaFlora.py#L19-L23
249,872
mouse-reeve/nomina-flora
nominaflora/NominaFlora.py
NominaFlora.get_common
def get_common(self, filename): ''' Process lists of common name words ''' word_list = [] words = open(filename) for word in words.readlines(): word_list.append(word.strip()) return word_list
python
def get_common(self, filename): ''' Process lists of common name words ''' word_list = [] words = open(filename) for word in words.readlines(): word_list.append(word.strip()) return word_list
[ "def", "get_common", "(", "self", ",", "filename", ")", ":", "word_list", "=", "[", "]", "words", "=", "open", "(", "filename", ")", "for", "word", "in", "words", ".", "readlines", "(", ")", ":", "word_list", ".", "append", "(", "word", ".", "strip", "(", ")", ")", "return", "word_list" ]
Process lists of common name words
[ "Process", "lists", "of", "common", "name", "words" ]
d99723b95d169dc38021a38c1f9d1f9f2b04c46b
https://github.com/mouse-reeve/nomina-flora/blob/d99723b95d169dc38021a38c1f9d1f9f2b04c46b/nominaflora/NominaFlora.py#L26-L32
249,873
mouse-reeve/nomina-flora
nominaflora/NominaFlora.py
NominaFlora.get_scientific_name
def get_scientific_name(self): ''' Get a new flower name ''' genus = self.genus_builder.get_word() species = self.species_builder.get_word() return '%s %s' % (genus, species)
python
def get_scientific_name(self): ''' Get a new flower name ''' genus = self.genus_builder.get_word() species = self.species_builder.get_word() return '%s %s' % (genus, species)
[ "def", "get_scientific_name", "(", "self", ")", ":", "genus", "=", "self", ".", "genus_builder", ".", "get_word", "(", ")", "species", "=", "self", ".", "species_builder", ".", "get_word", "(", ")", "return", "'%s %s'", "%", "(", "genus", ",", "species", ")" ]
Get a new flower name
[ "Get", "a", "new", "flower", "name" ]
d99723b95d169dc38021a38c1f9d1f9f2b04c46b
https://github.com/mouse-reeve/nomina-flora/blob/d99723b95d169dc38021a38c1f9d1f9f2b04c46b/nominaflora/NominaFlora.py#L35-L39
249,874
mouse-reeve/nomina-flora
nominaflora/NominaFlora.py
NominaFlora.get_common_name
def get_common_name(self): ''' Get a flower's common name ''' name = random.choice(self.common_first) if random.randint(0, 1) == 1: name += ' ' + random.choice(self.common_first).lower() name += ' ' + random.choice(self.common_second).lower() return name
python
def get_common_name(self): ''' Get a flower's common name ''' name = random.choice(self.common_first) if random.randint(0, 1) == 1: name += ' ' + random.choice(self.common_first).lower() name += ' ' + random.choice(self.common_second).lower() return name
[ "def", "get_common_name", "(", "self", ")", ":", "name", "=", "random", ".", "choice", "(", "self", ".", "common_first", ")", "if", "random", ".", "randint", "(", "0", ",", "1", ")", "==", "1", ":", "name", "+=", "' '", "+", "random", ".", "choice", "(", "self", ".", "common_first", ")", ".", "lower", "(", ")", "name", "+=", "' '", "+", "random", ".", "choice", "(", "self", ".", "common_second", ")", ".", "lower", "(", ")", "return", "name" ]
Get a flower's common name
[ "Get", "a", "flower", "s", "common", "name" ]
d99723b95d169dc38021a38c1f9d1f9f2b04c46b
https://github.com/mouse-reeve/nomina-flora/blob/d99723b95d169dc38021a38c1f9d1f9f2b04c46b/nominaflora/NominaFlora.py#L42-L48
249,875
sys-git/certifiable
certifiable/complex.py
certify_dict_schema
def certify_dict_schema( value, schema=None, key_certifier=None, value_certifier=None, required=None, allow_extra=None, ): """ Certify the dictionary schema. :param dict|Mapping|MutableMapping value: The mapping value to certify against the schema. :param object schema: The schema to validate with. :param callable key_certifier: A certifier to use on the dictionary's keys. :param callable value_certifier: A certifier to use on the dictionary's values. :param bool required: Whether the value can't be `None`. Defaults to True. :param bool allow_extra: Set to `True` to ignore extra keys. :return: The certified mapping :rtype: dict|Mapping|MutableMapping """ if key_certifier is not None or value_certifier is not None: for key, val in value.items(): if key_certifier is not None: key_certifier(key) if value_certifier is not None: value_certifier(val) if schema: if not isinstance(schema, dict): raise CertifierParamError( name='schema', value=schema, ) for key, certifier in schema.items(): if key not in value: raise CertifierValueError( message="key \'{key}\' missing from dictionary".format( key=key), required=required, ) val = value[key] certifier(value=val) if not allow_extra and set(schema) != set(value): values = set(value) - set(schema) raise CertifierValueError( message="encountered unexpected keys: {unexpected!r}".format( unexpected=values), value=values, required=required, )
python
def certify_dict_schema( value, schema=None, key_certifier=None, value_certifier=None, required=None, allow_extra=None, ): """ Certify the dictionary schema. :param dict|Mapping|MutableMapping value: The mapping value to certify against the schema. :param object schema: The schema to validate with. :param callable key_certifier: A certifier to use on the dictionary's keys. :param callable value_certifier: A certifier to use on the dictionary's values. :param bool required: Whether the value can't be `None`. Defaults to True. :param bool allow_extra: Set to `True` to ignore extra keys. :return: The certified mapping :rtype: dict|Mapping|MutableMapping """ if key_certifier is not None or value_certifier is not None: for key, val in value.items(): if key_certifier is not None: key_certifier(key) if value_certifier is not None: value_certifier(val) if schema: if not isinstance(schema, dict): raise CertifierParamError( name='schema', value=schema, ) for key, certifier in schema.items(): if key not in value: raise CertifierValueError( message="key \'{key}\' missing from dictionary".format( key=key), required=required, ) val = value[key] certifier(value=val) if not allow_extra and set(schema) != set(value): values = set(value) - set(schema) raise CertifierValueError( message="encountered unexpected keys: {unexpected!r}".format( unexpected=values), value=values, required=required, )
[ "def", "certify_dict_schema", "(", "value", ",", "schema", "=", "None", ",", "key_certifier", "=", "None", ",", "value_certifier", "=", "None", ",", "required", "=", "None", ",", "allow_extra", "=", "None", ",", ")", ":", "if", "key_certifier", "is", "not", "None", "or", "value_certifier", "is", "not", "None", ":", "for", "key", ",", "val", "in", "value", ".", "items", "(", ")", ":", "if", "key_certifier", "is", "not", "None", ":", "key_certifier", "(", "key", ")", "if", "value_certifier", "is", "not", "None", ":", "value_certifier", "(", "val", ")", "if", "schema", ":", "if", "not", "isinstance", "(", "schema", ",", "dict", ")", ":", "raise", "CertifierParamError", "(", "name", "=", "'schema'", ",", "value", "=", "schema", ",", ")", "for", "key", ",", "certifier", "in", "schema", ".", "items", "(", ")", ":", "if", "key", "not", "in", "value", ":", "raise", "CertifierValueError", "(", "message", "=", "\"key \\'{key}\\' missing from dictionary\"", ".", "format", "(", "key", "=", "key", ")", ",", "required", "=", "required", ",", ")", "val", "=", "value", "[", "key", "]", "certifier", "(", "value", "=", "val", ")", "if", "not", "allow_extra", "and", "set", "(", "schema", ")", "!=", "set", "(", "value", ")", ":", "values", "=", "set", "(", "value", ")", "-", "set", "(", "schema", ")", "raise", "CertifierValueError", "(", "message", "=", "\"encountered unexpected keys: {unexpected!r}\"", ".", "format", "(", "unexpected", "=", "values", ")", ",", "value", "=", "values", ",", "required", "=", "required", ",", ")" ]
Certify the dictionary schema. :param dict|Mapping|MutableMapping value: The mapping value to certify against the schema. :param object schema: The schema to validate with. :param callable key_certifier: A certifier to use on the dictionary's keys. :param callable value_certifier: A certifier to use on the dictionary's values. :param bool required: Whether the value can't be `None`. Defaults to True. :param bool allow_extra: Set to `True` to ignore extra keys. :return: The certified mapping :rtype: dict|Mapping|MutableMapping
[ "Certify", "the", "dictionary", "schema", "." ]
a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8
https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/complex.py#L26-L80
249,876
sys-git/certifiable
certifiable/complex.py
certify_dict
def certify_dict( value, schema=None, allow_extra=False, required=True, key_certifier=None, value_certifier=None, include_collections=False, ): """ Certifies a dictionary, checking it against an optional schema. The schema should be a dictionary, with keys corresponding to the expected keys in `value`, but with the values replaced by functions which will be called to with the corresponding value in the input. A simple example: >>> certifier = certify_dict(schema={ ... 'id': certify_key(kind='Model'), ... 'count': certify_int(min=0), ... }) >>> certifier({'id': self.key, 'count': self.count}) :param dict|Mapping|MutableMapping value: The value to be certified. :param dict schema: The schema against which the value should be checked. :param bool allow_extra: Set to `True` to ignore extra keys. :param bool required: Whether the value can't be `None`. Defaults to True. :param callable key_certifier: callable that receives the key to certify (ignoring schema keys). :param callable value_certifier: callable that receives the value to certify (ignoring schema values). :param bool include_collections: Include types from collections. :return: The certified dict. :rtype: dict|Mapping|MutableMapping :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The value is invalid """ cls = dict # Certify our kwargs: certify_params( (certify_bool, 'allow_extra', allow_extra), (certify_bool, 'include_collections', include_collections), ) if certify_required( value=value, required=required, ): return # Check the type(s): types = [cls] if include_collections: types.extend([Mapping, MutableMapping]) types = tuple(types) if not isinstance(value, types): raise CertifierTypeError( message="Expected {t} but the type is {cls!r}".format( cls=cls, t=value.__class__.__name__, ), value=value, required=required, ) certify_dict_schema( value=value, schema=schema, key_certifier=key_certifier, value_certifier=value_certifier, required=required, allow_extra=allow_extra, )
python
def certify_dict( value, schema=None, allow_extra=False, required=True, key_certifier=None, value_certifier=None, include_collections=False, ): """ Certifies a dictionary, checking it against an optional schema. The schema should be a dictionary, with keys corresponding to the expected keys in `value`, but with the values replaced by functions which will be called to with the corresponding value in the input. A simple example: >>> certifier = certify_dict(schema={ ... 'id': certify_key(kind='Model'), ... 'count': certify_int(min=0), ... }) >>> certifier({'id': self.key, 'count': self.count}) :param dict|Mapping|MutableMapping value: The value to be certified. :param dict schema: The schema against which the value should be checked. :param bool allow_extra: Set to `True` to ignore extra keys. :param bool required: Whether the value can't be `None`. Defaults to True. :param callable key_certifier: callable that receives the key to certify (ignoring schema keys). :param callable value_certifier: callable that receives the value to certify (ignoring schema values). :param bool include_collections: Include types from collections. :return: The certified dict. :rtype: dict|Mapping|MutableMapping :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The value is invalid """ cls = dict # Certify our kwargs: certify_params( (certify_bool, 'allow_extra', allow_extra), (certify_bool, 'include_collections', include_collections), ) if certify_required( value=value, required=required, ): return # Check the type(s): types = [cls] if include_collections: types.extend([Mapping, MutableMapping]) types = tuple(types) if not isinstance(value, types): raise CertifierTypeError( message="Expected {t} but the type is {cls!r}".format( cls=cls, t=value.__class__.__name__, ), value=value, required=required, ) certify_dict_schema( value=value, schema=schema, key_certifier=key_certifier, value_certifier=value_certifier, required=required, allow_extra=allow_extra, )
[ "def", "certify_dict", "(", "value", ",", "schema", "=", "None", ",", "allow_extra", "=", "False", ",", "required", "=", "True", ",", "key_certifier", "=", "None", ",", "value_certifier", "=", "None", ",", "include_collections", "=", "False", ",", ")", ":", "cls", "=", "dict", "# Certify our kwargs:", "certify_params", "(", "(", "certify_bool", ",", "'allow_extra'", ",", "allow_extra", ")", ",", "(", "certify_bool", ",", "'include_collections'", ",", "include_collections", ")", ",", ")", "if", "certify_required", "(", "value", "=", "value", ",", "required", "=", "required", ",", ")", ":", "return", "# Check the type(s):", "types", "=", "[", "cls", "]", "if", "include_collections", ":", "types", ".", "extend", "(", "[", "Mapping", ",", "MutableMapping", "]", ")", "types", "=", "tuple", "(", "types", ")", "if", "not", "isinstance", "(", "value", ",", "types", ")", ":", "raise", "CertifierTypeError", "(", "message", "=", "\"Expected {t} but the type is {cls!r}\"", ".", "format", "(", "cls", "=", "cls", ",", "t", "=", "value", ".", "__class__", ".", "__name__", ",", ")", ",", "value", "=", "value", ",", "required", "=", "required", ",", ")", "certify_dict_schema", "(", "value", "=", "value", ",", "schema", "=", "schema", ",", "key_certifier", "=", "key_certifier", ",", "value_certifier", "=", "value_certifier", ",", "required", "=", "required", ",", "allow_extra", "=", "allow_extra", ",", ")" ]
Certifies a dictionary, checking it against an optional schema. The schema should be a dictionary, with keys corresponding to the expected keys in `value`, but with the values replaced by functions which will be called to with the corresponding value in the input. A simple example: >>> certifier = certify_dict(schema={ ... 'id': certify_key(kind='Model'), ... 'count': certify_int(min=0), ... }) >>> certifier({'id': self.key, 'count': self.count}) :param dict|Mapping|MutableMapping value: The value to be certified. :param dict schema: The schema against which the value should be checked. :param bool allow_extra: Set to `True` to ignore extra keys. :param bool required: Whether the value can't be `None`. Defaults to True. :param callable key_certifier: callable that receives the key to certify (ignoring schema keys). :param callable value_certifier: callable that receives the value to certify (ignoring schema values). :param bool include_collections: Include types from collections. :return: The certified dict. :rtype: dict|Mapping|MutableMapping :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The value is invalid
[ "Certifies", "a", "dictionary", "checking", "it", "against", "an", "optional", "schema", "." ]
a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8
https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/complex.py#L84-L160
249,877
sys-git/certifiable
certifiable/complex.py
certify_iterable_schema
def certify_iterable_schema(value, schema=None, required=True): """ Certify an iterable against a schema. :param iterable value: The iterable to certify against the schema. :param iterable schema: The schema to use :param bool required: Whether the value can't be `None`. Defaults to True. :return: The validated iterable. :rtype: iterable """ if schema is not None: if len(schema) != len(value): raise CertifierValueError( "encountered {extra} extra items".format( extra=len(value) - len(schema)), value=value, required=required, ) for index, certifier in enumerate(schema): try: certifier(value=value[index]) except CertifierError as exc: six.raise_from( CertifierValueError( message="invalid value {value!r} for item {index}".format( index=index, value=value[index]), value=value, required=required, ), exc, )
python
def certify_iterable_schema(value, schema=None, required=True): """ Certify an iterable against a schema. :param iterable value: The iterable to certify against the schema. :param iterable schema: The schema to use :param bool required: Whether the value can't be `None`. Defaults to True. :return: The validated iterable. :rtype: iterable """ if schema is not None: if len(schema) != len(value): raise CertifierValueError( "encountered {extra} extra items".format( extra=len(value) - len(schema)), value=value, required=required, ) for index, certifier in enumerate(schema): try: certifier(value=value[index]) except CertifierError as exc: six.raise_from( CertifierValueError( message="invalid value {value!r} for item {index}".format( index=index, value=value[index]), value=value, required=required, ), exc, )
[ "def", "certify_iterable_schema", "(", "value", ",", "schema", "=", "None", ",", "required", "=", "True", ")", ":", "if", "schema", "is", "not", "None", ":", "if", "len", "(", "schema", ")", "!=", "len", "(", "value", ")", ":", "raise", "CertifierValueError", "(", "\"encountered {extra} extra items\"", ".", "format", "(", "extra", "=", "len", "(", "value", ")", "-", "len", "(", "schema", ")", ")", ",", "value", "=", "value", ",", "required", "=", "required", ",", ")", "for", "index", ",", "certifier", "in", "enumerate", "(", "schema", ")", ":", "try", ":", "certifier", "(", "value", "=", "value", "[", "index", "]", ")", "except", "CertifierError", "as", "exc", ":", "six", ".", "raise_from", "(", "CertifierValueError", "(", "message", "=", "\"invalid value {value!r} for item {index}\"", ".", "format", "(", "index", "=", "index", ",", "value", "=", "value", "[", "index", "]", ")", ",", "value", "=", "value", ",", "required", "=", "required", ",", ")", ",", "exc", ",", ")" ]
Certify an iterable against a schema. :param iterable value: The iterable to certify against the schema. :param iterable schema: The schema to use :param bool required: Whether the value can't be `None`. Defaults to True. :return: The validated iterable. :rtype: iterable
[ "Certify", "an", "iterable", "against", "a", "schema", "." ]
a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8
https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/complex.py#L164-L200
249,878
sys-git/certifiable
certifiable/complex.py
certify_iterable
def certify_iterable( value, types, certifier=None, min_len=None, max_len=None, schema=None, required=True ): """ Validates an iterable sequence, checking it against an optional schema. The schema should be a list of expected values replaced by functions which will be called to with the corresponding value in the input. :param iterable value: The value to be certified. :param tuple(object) types: A tuple of types of the expected iterable. :param func|None certifier: A function to be called on each value in the iterable to check that it is valid. :param int|None min_len: The minimum acceptable length for the iterable. If None, the minimum length is not checked. :param int|None max_len: The maximum acceptable length for the iterable. If None, the maximum length is not checked. :param tuple|None schema: The schema against which the value should be checked. For single-item tuple make sure to add comma at the end of schema tuple, that is, for example: schema=(certify_int(),) :param bool required: Whether the value can't be `None`. Defaults to True. :return: The certified iterable. :rtype: iterable :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid. """ certify_required( value=value, required=required, ) certify_params( (_certify_int_param, 'max_len', max_len, dict(negative=False, required=False)), (_certify_int_param, 'min_len', min_len, dict(negative=False, required=False)), ) # Check the type(s): if types and not isinstance(value, types): raise CertifierTypeError( message="value is not an expected type ({value_type!r})".format( value_type=value.__class__.__name__ ), value=value, required=required, ) if min_len is not None and len(value) < min_len: raise CertifierValueError( message="expected at least {expected} elements, " "but set is of length {actual}".format(expected=min_len, actual=len(value)), value=value, required=required, ) if max_len is not None and len(value) > max_len: raise CertifierValueError( message=("expected at most {expected} elements, " "but {cls} is of length {actual}").format( expected=max_len, actual=len(value), cls=types, ), value=value, required=required, ) # Apply the certifier to all values: if certifier is not None: map(certifier, value) certify_iterable_schema( value=value, schema=schema, required=required, )
python
def certify_iterable( value, types, certifier=None, min_len=None, max_len=None, schema=None, required=True ): """ Validates an iterable sequence, checking it against an optional schema. The schema should be a list of expected values replaced by functions which will be called to with the corresponding value in the input. :param iterable value: The value to be certified. :param tuple(object) types: A tuple of types of the expected iterable. :param func|None certifier: A function to be called on each value in the iterable to check that it is valid. :param int|None min_len: The minimum acceptable length for the iterable. If None, the minimum length is not checked. :param int|None max_len: The maximum acceptable length for the iterable. If None, the maximum length is not checked. :param tuple|None schema: The schema against which the value should be checked. For single-item tuple make sure to add comma at the end of schema tuple, that is, for example: schema=(certify_int(),) :param bool required: Whether the value can't be `None`. Defaults to True. :return: The certified iterable. :rtype: iterable :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid. """ certify_required( value=value, required=required, ) certify_params( (_certify_int_param, 'max_len', max_len, dict(negative=False, required=False)), (_certify_int_param, 'min_len', min_len, dict(negative=False, required=False)), ) # Check the type(s): if types and not isinstance(value, types): raise CertifierTypeError( message="value is not an expected type ({value_type!r})".format( value_type=value.__class__.__name__ ), value=value, required=required, ) if min_len is not None and len(value) < min_len: raise CertifierValueError( message="expected at least {expected} elements, " "but set is of length {actual}".format(expected=min_len, actual=len(value)), value=value, required=required, ) if max_len is not None and len(value) > max_len: raise CertifierValueError( message=("expected at most {expected} elements, " "but {cls} is of length {actual}").format( expected=max_len, actual=len(value), cls=types, ), value=value, required=required, ) # Apply the certifier to all values: if certifier is not None: map(certifier, value) certify_iterable_schema( value=value, schema=schema, required=required, )
[ "def", "certify_iterable", "(", "value", ",", "types", ",", "certifier", "=", "None", ",", "min_len", "=", "None", ",", "max_len", "=", "None", ",", "schema", "=", "None", ",", "required", "=", "True", ")", ":", "certify_required", "(", "value", "=", "value", ",", "required", "=", "required", ",", ")", "certify_params", "(", "(", "_certify_int_param", ",", "'max_len'", ",", "max_len", ",", "dict", "(", "negative", "=", "False", ",", "required", "=", "False", ")", ")", ",", "(", "_certify_int_param", ",", "'min_len'", ",", "min_len", ",", "dict", "(", "negative", "=", "False", ",", "required", "=", "False", ")", ")", ",", ")", "# Check the type(s):", "if", "types", "and", "not", "isinstance", "(", "value", ",", "types", ")", ":", "raise", "CertifierTypeError", "(", "message", "=", "\"value is not an expected type ({value_type!r})\"", ".", "format", "(", "value_type", "=", "value", ".", "__class__", ".", "__name__", ")", ",", "value", "=", "value", ",", "required", "=", "required", ",", ")", "if", "min_len", "is", "not", "None", "and", "len", "(", "value", ")", "<", "min_len", ":", "raise", "CertifierValueError", "(", "message", "=", "\"expected at least {expected} elements, \"", "\"but set is of length {actual}\"", ".", "format", "(", "expected", "=", "min_len", ",", "actual", "=", "len", "(", "value", ")", ")", ",", "value", "=", "value", ",", "required", "=", "required", ",", ")", "if", "max_len", "is", "not", "None", "and", "len", "(", "value", ")", ">", "max_len", ":", "raise", "CertifierValueError", "(", "message", "=", "(", "\"expected at most {expected} elements, \"", "\"but {cls} is of length {actual}\"", ")", ".", "format", "(", "expected", "=", "max_len", ",", "actual", "=", "len", "(", "value", ")", ",", "cls", "=", "types", ",", ")", ",", "value", "=", "value", ",", "required", "=", "required", ",", ")", "# Apply the certifier to all values:", "if", "certifier", "is", "not", "None", ":", "map", "(", "certifier", ",", "value", ")", "certify_iterable_schema", "(", "value", "=", "value", ",", "schema", "=", "schema", ",", "required", "=", "required", ",", ")" ]
Validates an iterable sequence, checking it against an optional schema. The schema should be a list of expected values replaced by functions which will be called to with the corresponding value in the input. :param iterable value: The value to be certified. :param tuple(object) types: A tuple of types of the expected iterable. :param func|None certifier: A function to be called on each value in the iterable to check that it is valid. :param int|None min_len: The minimum acceptable length for the iterable. If None, the minimum length is not checked. :param int|None max_len: The maximum acceptable length for the iterable. If None, the maximum length is not checked. :param tuple|None schema: The schema against which the value should be checked. For single-item tuple make sure to add comma at the end of schema tuple, that is, for example: schema=(certify_int(),) :param bool required: Whether the value can't be `None`. Defaults to True. :return: The certified iterable. :rtype: iterable :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid.
[ "Validates", "an", "iterable", "sequence", "checking", "it", "against", "an", "optional", "schema", "." ]
a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8
https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/complex.py#L203-L281
249,879
sys-git/certifiable
certifiable/complex.py
certify_set
def certify_set( value, certifier=None, min_len=None, max_len=None, include_collections=False, required=True, ): """ Certifier for a set. :param set value: The set to be certified. :param func certifier: A function to be called on each value in the list to check that it is valid. :param int min_len: The minimum acceptable length for the list. If None, the minimum length is not checked. :param int max_len: The maximum acceptable length for the list. If None, the maximum length is not checked. :param bool include_collections: Include types from collections. :param bool required: Whether the value can be `None`. Defaults to True. :return: The certified set. :rtype: set :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid """ certify_bool(include_collections, required=True) certify_iterable( value=value, types=tuple([set, MutableSet, Set]) if include_collections else tuple([set]), certifier=certifier, min_len=min_len, max_len=max_len, schema=None, required=required, )
python
def certify_set( value, certifier=None, min_len=None, max_len=None, include_collections=False, required=True, ): """ Certifier for a set. :param set value: The set to be certified. :param func certifier: A function to be called on each value in the list to check that it is valid. :param int min_len: The minimum acceptable length for the list. If None, the minimum length is not checked. :param int max_len: The maximum acceptable length for the list. If None, the maximum length is not checked. :param bool include_collections: Include types from collections. :param bool required: Whether the value can be `None`. Defaults to True. :return: The certified set. :rtype: set :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid """ certify_bool(include_collections, required=True) certify_iterable( value=value, types=tuple([set, MutableSet, Set]) if include_collections else tuple([set]), certifier=certifier, min_len=min_len, max_len=max_len, schema=None, required=required, )
[ "def", "certify_set", "(", "value", ",", "certifier", "=", "None", ",", "min_len", "=", "None", ",", "max_len", "=", "None", ",", "include_collections", "=", "False", ",", "required", "=", "True", ",", ")", ":", "certify_bool", "(", "include_collections", ",", "required", "=", "True", ")", "certify_iterable", "(", "value", "=", "value", ",", "types", "=", "tuple", "(", "[", "set", ",", "MutableSet", ",", "Set", "]", ")", "if", "include_collections", "else", "tuple", "(", "[", "set", "]", ")", ",", "certifier", "=", "certifier", ",", "min_len", "=", "min_len", ",", "max_len", "=", "max_len", ",", "schema", "=", "None", ",", "required", "=", "required", ",", ")" ]
Certifier for a set. :param set value: The set to be certified. :param func certifier: A function to be called on each value in the list to check that it is valid. :param int min_len: The minimum acceptable length for the list. If None, the minimum length is not checked. :param int max_len: The maximum acceptable length for the list. If None, the maximum length is not checked. :param bool include_collections: Include types from collections. :param bool required: Whether the value can be `None`. Defaults to True. :return: The certified set. :rtype: set :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid
[ "Certifier", "for", "a", "set", "." ]
a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8
https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/complex.py#L285-L322
249,880
sys-git/certifiable
certifiable/complex.py
certify_tuple
def certify_tuple(value, certifier=None, min_len=None, max_len=None, required=True, schema=None): """ Validates a tuple, checking it against an optional schema. The schema should be a list of expected values replaced by functions which will be called to with the corresponding value in the input. A simple example: >>> certifier = certify_tuple(schema=( ... certify_key(kind='Model'), ... certify_int(min=0), ... )) >>> certifier((self.key, self.count)) :param tuple value: The value to be certified. :param func certifier: A function to be called on each value in the iterable to check that it is valid. :param int min_len: The minimum acceptable length for the iterable. If None, the minimum length is not checked. :param int max_len: The maximum acceptable length for the iterable. If None, the maximum length is not checked. :param bool required: Whether the value can't be `None`. Defaults to True. :param tuple schema: The schema against which the value should be checked. For single-item tuple make sure to add comma at the end of schema tuple, that is, for example: schema=(certify_int(),) :return: The certified tuple. :rtype: tuple :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid """ certify_iterable( value=value, types=tuple([tuple]), certifier=certifier, min_len=min_len, max_len=max_len, schema=schema, required=required, )
python
def certify_tuple(value, certifier=None, min_len=None, max_len=None, required=True, schema=None): """ Validates a tuple, checking it against an optional schema. The schema should be a list of expected values replaced by functions which will be called to with the corresponding value in the input. A simple example: >>> certifier = certify_tuple(schema=( ... certify_key(kind='Model'), ... certify_int(min=0), ... )) >>> certifier((self.key, self.count)) :param tuple value: The value to be certified. :param func certifier: A function to be called on each value in the iterable to check that it is valid. :param int min_len: The minimum acceptable length for the iterable. If None, the minimum length is not checked. :param int max_len: The maximum acceptable length for the iterable. If None, the maximum length is not checked. :param bool required: Whether the value can't be `None`. Defaults to True. :param tuple schema: The schema against which the value should be checked. For single-item tuple make sure to add comma at the end of schema tuple, that is, for example: schema=(certify_int(),) :return: The certified tuple. :rtype: tuple :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid """ certify_iterable( value=value, types=tuple([tuple]), certifier=certifier, min_len=min_len, max_len=max_len, schema=schema, required=required, )
[ "def", "certify_tuple", "(", "value", ",", "certifier", "=", "None", ",", "min_len", "=", "None", ",", "max_len", "=", "None", ",", "required", "=", "True", ",", "schema", "=", "None", ")", ":", "certify_iterable", "(", "value", "=", "value", ",", "types", "=", "tuple", "(", "[", "tuple", "]", ")", ",", "certifier", "=", "certifier", ",", "min_len", "=", "min_len", ",", "max_len", "=", "max_len", ",", "schema", "=", "schema", ",", "required", "=", "required", ",", ")" ]
Validates a tuple, checking it against an optional schema. The schema should be a list of expected values replaced by functions which will be called to with the corresponding value in the input. A simple example: >>> certifier = certify_tuple(schema=( ... certify_key(kind='Model'), ... certify_int(min=0), ... )) >>> certifier((self.key, self.count)) :param tuple value: The value to be certified. :param func certifier: A function to be called on each value in the iterable to check that it is valid. :param int min_len: The minimum acceptable length for the iterable. If None, the minimum length is not checked. :param int max_len: The maximum acceptable length for the iterable. If None, the maximum length is not checked. :param bool required: Whether the value can't be `None`. Defaults to True. :param tuple schema: The schema against which the value should be checked. For single-item tuple make sure to add comma at the end of schema tuple, that is, for example: schema=(certify_int(),) :return: The certified tuple. :rtype: tuple :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid
[ "Validates", "a", "tuple", "checking", "it", "against", "an", "optional", "schema", "." ]
a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8
https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/complex.py#L326-L372
249,881
sys-git/certifiable
certifiable/complex.py
certify_list
def certify_list( value, certifier=None, min_len=None, max_len=None, required=True, schema=None, include_collections=False, ): """ Certifier for a list. :param list value: The array to be certified. :param func certifier: A function to be called on each value in the iterable to check that it is valid. :param int min_len: The minimum acceptable length for the iterable. If None, the minimum length is not checked. :param int max_len: The maximum acceptable length for the iterable. If None, the maximum length is not checked. :param bool required: Whether the value can't be `None`. Defaults to True. :param tuple schema: The schema against which the value should be checked. For single-item tuple make sure to add comma at the end of schema tuple, that is, for example: schema=(certify_int(),) :param bool include_collections: Include types from collections. :return: The certified list. :rtype: list :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid """ certify_bool(include_collections, required=True) certify_iterable( value=value, types=tuple([list, MutableSequence, Sequence]) if include_collections else tuple([list]), certifier=certifier, min_len=min_len, max_len=max_len, schema=schema, required=required, )
python
def certify_list( value, certifier=None, min_len=None, max_len=None, required=True, schema=None, include_collections=False, ): """ Certifier for a list. :param list value: The array to be certified. :param func certifier: A function to be called on each value in the iterable to check that it is valid. :param int min_len: The minimum acceptable length for the iterable. If None, the minimum length is not checked. :param int max_len: The maximum acceptable length for the iterable. If None, the maximum length is not checked. :param bool required: Whether the value can't be `None`. Defaults to True. :param tuple schema: The schema against which the value should be checked. For single-item tuple make sure to add comma at the end of schema tuple, that is, for example: schema=(certify_int(),) :param bool include_collections: Include types from collections. :return: The certified list. :rtype: list :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid """ certify_bool(include_collections, required=True) certify_iterable( value=value, types=tuple([list, MutableSequence, Sequence]) if include_collections else tuple([list]), certifier=certifier, min_len=min_len, max_len=max_len, schema=schema, required=required, )
[ "def", "certify_list", "(", "value", ",", "certifier", "=", "None", ",", "min_len", "=", "None", ",", "max_len", "=", "None", ",", "required", "=", "True", ",", "schema", "=", "None", ",", "include_collections", "=", "False", ",", ")", ":", "certify_bool", "(", "include_collections", ",", "required", "=", "True", ")", "certify_iterable", "(", "value", "=", "value", ",", "types", "=", "tuple", "(", "[", "list", ",", "MutableSequence", ",", "Sequence", "]", ")", "if", "include_collections", "else", "tuple", "(", "[", "list", "]", ")", ",", "certifier", "=", "certifier", ",", "min_len", "=", "min_len", ",", "max_len", "=", "max_len", ",", "schema", "=", "schema", ",", "required", "=", "required", ",", ")" ]
Certifier for a list. :param list value: The array to be certified. :param func certifier: A function to be called on each value in the iterable to check that it is valid. :param int min_len: The minimum acceptable length for the iterable. If None, the minimum length is not checked. :param int max_len: The maximum acceptable length for the iterable. If None, the maximum length is not checked. :param bool required: Whether the value can't be `None`. Defaults to True. :param tuple schema: The schema against which the value should be checked. For single-item tuple make sure to add comma at the end of schema tuple, that is, for example: schema=(certify_int(),) :param bool include_collections: Include types from collections. :return: The certified list. :rtype: list :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid
[ "Certifier", "for", "a", "list", "." ]
a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8
https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/complex.py#L376-L417
249,882
sys-git/certifiable
certifiable/complex.py
certify_email
def certify_email(value, required=True): """ Certifier which verifies that email addresses are well-formed. Does not check that the address exists. :param six.string_types value: The email address to certify. **Should be normalized!** :param bool required: Whether the value can be `None`. Defaults to True. :return: The certified email address. :rtype: six.string_types :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid """ certify_required( value=value, required=required, ) certify_string(value, min_length=3, max_length=320) try: certification_result = email_validator.validate_email( value, check_deliverability=False, ) except email_validator.EmailNotValidError as ex: six.raise_from( CertifierValueError( message="{value!r} is not a valid email address: {ex}".format( value=value, # email_validator returns unicode characters in exception string ex=six.u(repr(ex)) ), value=value, required=required, ), ex ) else: if certification_result['email'] != value: raise CertifierValueError( message="{value!r} is not normalized, should be {normalized!r}".format( value=value, normalized=certification_result['email']), value=value, required=required, )
python
def certify_email(value, required=True): """ Certifier which verifies that email addresses are well-formed. Does not check that the address exists. :param six.string_types value: The email address to certify. **Should be normalized!** :param bool required: Whether the value can be `None`. Defaults to True. :return: The certified email address. :rtype: six.string_types :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid """ certify_required( value=value, required=required, ) certify_string(value, min_length=3, max_length=320) try: certification_result = email_validator.validate_email( value, check_deliverability=False, ) except email_validator.EmailNotValidError as ex: six.raise_from( CertifierValueError( message="{value!r} is not a valid email address: {ex}".format( value=value, # email_validator returns unicode characters in exception string ex=six.u(repr(ex)) ), value=value, required=required, ), ex ) else: if certification_result['email'] != value: raise CertifierValueError( message="{value!r} is not normalized, should be {normalized!r}".format( value=value, normalized=certification_result['email']), value=value, required=required, )
[ "def", "certify_email", "(", "value", ",", "required", "=", "True", ")", ":", "certify_required", "(", "value", "=", "value", ",", "required", "=", "required", ",", ")", "certify_string", "(", "value", ",", "min_length", "=", "3", ",", "max_length", "=", "320", ")", "try", ":", "certification_result", "=", "email_validator", ".", "validate_email", "(", "value", ",", "check_deliverability", "=", "False", ",", ")", "except", "email_validator", ".", "EmailNotValidError", "as", "ex", ":", "six", ".", "raise_from", "(", "CertifierValueError", "(", "message", "=", "\"{value!r} is not a valid email address: {ex}\"", ".", "format", "(", "value", "=", "value", ",", "# email_validator returns unicode characters in exception string", "ex", "=", "six", ".", "u", "(", "repr", "(", "ex", ")", ")", ")", ",", "value", "=", "value", ",", "required", "=", "required", ",", ")", ",", "ex", ")", "else", ":", "if", "certification_result", "[", "'email'", "]", "!=", "value", ":", "raise", "CertifierValueError", "(", "message", "=", "\"{value!r} is not normalized, should be {normalized!r}\"", ".", "format", "(", "value", "=", "value", ",", "normalized", "=", "certification_result", "[", "'email'", "]", ")", ",", "value", "=", "value", ",", "required", "=", "required", ",", ")" ]
Certifier which verifies that email addresses are well-formed. Does not check that the address exists. :param six.string_types value: The email address to certify. **Should be normalized!** :param bool required: Whether the value can be `None`. Defaults to True. :return: The certified email address. :rtype: six.string_types :raises CertifierTypeError: The type is invalid :raises CertifierValueError: The valid is invalid
[ "Certifier", "which", "verifies", "that", "email", "addresses", "are", "well", "-", "formed", "." ]
a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8
https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/complex.py#L421-L471
249,883
treycucco/bidon
bidon/db/model/validation.py
Validation.is_valid
def is_valid(self, model, validator=None): """Returns true if the model passes the validation, and false if not. Validator must be present_optional if validation is not 'simple'. """ if self.property_name and self.is_property_specific: arg0 = getattr(model, self.property_name) else: arg0 = model if self.is_simple: is_valid = self.callback(arg0) else: is_valid = self.callback(arg0, validator) return (is_valid, None if is_valid else (self.message or "is invalid"))
python
def is_valid(self, model, validator=None): """Returns true if the model passes the validation, and false if not. Validator must be present_optional if validation is not 'simple'. """ if self.property_name and self.is_property_specific: arg0 = getattr(model, self.property_name) else: arg0 = model if self.is_simple: is_valid = self.callback(arg0) else: is_valid = self.callback(arg0, validator) return (is_valid, None if is_valid else (self.message or "is invalid"))
[ "def", "is_valid", "(", "self", ",", "model", ",", "validator", "=", "None", ")", ":", "if", "self", ".", "property_name", "and", "self", ".", "is_property_specific", ":", "arg0", "=", "getattr", "(", "model", ",", "self", ".", "property_name", ")", "else", ":", "arg0", "=", "model", "if", "self", ".", "is_simple", ":", "is_valid", "=", "self", ".", "callback", "(", "arg0", ")", "else", ":", "is_valid", "=", "self", ".", "callback", "(", "arg0", ",", "validator", ")", "return", "(", "is_valid", ",", "None", "if", "is_valid", "else", "(", "self", ".", "message", "or", "\"is invalid\"", ")", ")" ]
Returns true if the model passes the validation, and false if not. Validator must be present_optional if validation is not 'simple'.
[ "Returns", "true", "if", "the", "model", "passes", "the", "validation", "and", "false", "if", "not", ".", "Validator", "must", "be", "present_optional", "if", "validation", "is", "not", "simple", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/validation.py#L41-L55
249,884
treycucco/bidon
bidon/db/model/validation.py
Validation.validate
def validate(self, model, validator=None): """Checks the model against all filters, and if it shoud be validated, runs the validation. if the model is invalid, an error is added to the model. Then the validity value is returned. """ for filter_ in self.filters: if not filter_(model): return True is_valid, message = self.is_valid(model, validator) if not is_valid: model.add_error(self.pretty_property_name or self.property_name, message) return is_valid
python
def validate(self, model, validator=None): """Checks the model against all filters, and if it shoud be validated, runs the validation. if the model is invalid, an error is added to the model. Then the validity value is returned. """ for filter_ in self.filters: if not filter_(model): return True is_valid, message = self.is_valid(model, validator) if not is_valid: model.add_error(self.pretty_property_name or self.property_name, message) return is_valid
[ "def", "validate", "(", "self", ",", "model", ",", "validator", "=", "None", ")", ":", "for", "filter_", "in", "self", ".", "filters", ":", "if", "not", "filter_", "(", "model", ")", ":", "return", "True", "is_valid", ",", "message", "=", "self", ".", "is_valid", "(", "model", ",", "validator", ")", "if", "not", "is_valid", ":", "model", ".", "add_error", "(", "self", ".", "pretty_property_name", "or", "self", ".", "property_name", ",", "message", ")", "return", "is_valid" ]
Checks the model against all filters, and if it shoud be validated, runs the validation. if the model is invalid, an error is added to the model. Then the validity value is returned.
[ "Checks", "the", "model", "against", "all", "filters", "and", "if", "it", "shoud", "be", "validated", "runs", "the", "validation", ".", "if", "the", "model", "is", "invalid", "an", "error", "is", "added", "to", "the", "model", ".", "Then", "the", "validity", "value", "is", "returned", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/validation.py#L57-L68
249,885
treycucco/bidon
bidon/db/model/validation.py
Validation._is_present
def _is_present(val): """Returns True if the value is not None, and if it is either not a string, or a string with length > 0. """ if val is None: return False if isinstance(val, str): return len(val) > 0 return True
python
def _is_present(val): """Returns True if the value is not None, and if it is either not a string, or a string with length > 0. """ if val is None: return False if isinstance(val, str): return len(val) > 0 return True
[ "def", "_is_present", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "False", "if", "isinstance", "(", "val", ",", "str", ")", ":", "return", "len", "(", "val", ")", ">", "0", "return", "True" ]
Returns True if the value is not None, and if it is either not a string, or a string with length > 0.
[ "Returns", "True", "if", "the", "value", "is", "not", "None", "and", "if", "it", "is", "either", "not", "a", "string", "or", "a", "string", "with", "length", ">", "0", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/validation.py#L71-L79
249,886
treycucco/bidon
bidon/db/model/validation.py
Validation.is_length
def is_length(property_name, *, min_length=1, max_length=None, present_optional=False): """Returns a Validation that checks the length of a string.""" def check(val): """Checks that a value matches a scope-enclosed set of length parameters.""" if not val: return present_optional else: if len(val) >= min_length: if max_length is None: return True else: return len(val) <= max_length else: return False if max_length: message = "must be at least {0} characters long".format(min_length) else: message = "must be between {0} and {1} characters long".format(min_length, max_length) return Validation(check, property_name, message)
python
def is_length(property_name, *, min_length=1, max_length=None, present_optional=False): """Returns a Validation that checks the length of a string.""" def check(val): """Checks that a value matches a scope-enclosed set of length parameters.""" if not val: return present_optional else: if len(val) >= min_length: if max_length is None: return True else: return len(val) <= max_length else: return False if max_length: message = "must be at least {0} characters long".format(min_length) else: message = "must be between {0} and {1} characters long".format(min_length, max_length) return Validation(check, property_name, message)
[ "def", "is_length", "(", "property_name", ",", "*", ",", "min_length", "=", "1", ",", "max_length", "=", "None", ",", "present_optional", "=", "False", ")", ":", "def", "check", "(", "val", ")", ":", "\"\"\"Checks that a value matches a scope-enclosed set of length parameters.\"\"\"", "if", "not", "val", ":", "return", "present_optional", "else", ":", "if", "len", "(", "val", ")", ">=", "min_length", ":", "if", "max_length", "is", "None", ":", "return", "True", "else", ":", "return", "len", "(", "val", ")", "<=", "max_length", "else", ":", "return", "False", "if", "max_length", ":", "message", "=", "\"must be at least {0} characters long\"", ".", "format", "(", "min_length", ")", "else", ":", "message", "=", "\"must be between {0} and {1} characters long\"", ".", "format", "(", "min_length", ",", "max_length", ")", "return", "Validation", "(", "check", ",", "property_name", ",", "message", ")" ]
Returns a Validation that checks the length of a string.
[ "Returns", "a", "Validation", "that", "checks", "the", "length", "of", "a", "string", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/validation.py#L87-L107
249,887
treycucco/bidon
bidon/db/model/validation.py
Validation.matches
def matches(property_name, regex, *, present_optional=False, message=None): """Returns a Validation that checks a property against a regex.""" def check(val): """Checks that a value matches a scope-enclosed regex.""" if not val: return present_optional else: return True if regex.search(val) else False return Validation(check, property_name, message)
python
def matches(property_name, regex, *, present_optional=False, message=None): """Returns a Validation that checks a property against a regex.""" def check(val): """Checks that a value matches a scope-enclosed regex.""" if not val: return present_optional else: return True if regex.search(val) else False return Validation(check, property_name, message)
[ "def", "matches", "(", "property_name", ",", "regex", ",", "*", ",", "present_optional", "=", "False", ",", "message", "=", "None", ")", ":", "def", "check", "(", "val", ")", ":", "\"\"\"Checks that a value matches a scope-enclosed regex.\"\"\"", "if", "not", "val", ":", "return", "present_optional", "else", ":", "return", "True", "if", "regex", ".", "search", "(", "val", ")", "else", "False", "return", "Validation", "(", "check", ",", "property_name", ",", "message", ")" ]
Returns a Validation that checks a property against a regex.
[ "Returns", "a", "Validation", "that", "checks", "a", "property", "against", "a", "regex", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/validation.py#L110-L119
249,888
treycucco/bidon
bidon/db/model/validation.py
Validation.is_numeric
def is_numeric(property_name, *, numtype="float", min=None, max=None, present_optional=False, message=None): """Returns a Validation that checks a property as a number, with optional range constraints.""" if numtype == "int": cast = util.try_parse_int elif numtype == "decimal": cast = util.try_parse_decimal elif numtype == "float": cast = util.try_parse_float else: raise ValueError("numtype argument must be one of: int, decimal, float") def check(val): """Checks that a value can be parsed as a number.""" if val is None: return present_optional else: is_num, new_val = cast(val) if not is_num: return False else: if min is not None and new_val < min: return False if max is not None and new_val > max: return False return True if not message: msg = ["must be a"] if numtype == "int": msg.append("whole number") else: msg.append("number") if min is not None and max is not None: msg.append("between {0} and {1}".format(min, max)) elif min is not None: msg.append("greater than or equal to {0}".format(min)) elif max is not None: msg.append("less than or equal to {0}".format(max)) message = " ".join(msg) return Validation(check, property_name, message)
python
def is_numeric(property_name, *, numtype="float", min=None, max=None, present_optional=False, message=None): """Returns a Validation that checks a property as a number, with optional range constraints.""" if numtype == "int": cast = util.try_parse_int elif numtype == "decimal": cast = util.try_parse_decimal elif numtype == "float": cast = util.try_parse_float else: raise ValueError("numtype argument must be one of: int, decimal, float") def check(val): """Checks that a value can be parsed as a number.""" if val is None: return present_optional else: is_num, new_val = cast(val) if not is_num: return False else: if min is not None and new_val < min: return False if max is not None and new_val > max: return False return True if not message: msg = ["must be a"] if numtype == "int": msg.append("whole number") else: msg.append("number") if min is not None and max is not None: msg.append("between {0} and {1}".format(min, max)) elif min is not None: msg.append("greater than or equal to {0}".format(min)) elif max is not None: msg.append("less than or equal to {0}".format(max)) message = " ".join(msg) return Validation(check, property_name, message)
[ "def", "is_numeric", "(", "property_name", ",", "*", ",", "numtype", "=", "\"float\"", ",", "min", "=", "None", ",", "max", "=", "None", ",", "present_optional", "=", "False", ",", "message", "=", "None", ")", ":", "if", "numtype", "==", "\"int\"", ":", "cast", "=", "util", ".", "try_parse_int", "elif", "numtype", "==", "\"decimal\"", ":", "cast", "=", "util", ".", "try_parse_decimal", "elif", "numtype", "==", "\"float\"", ":", "cast", "=", "util", ".", "try_parse_float", "else", ":", "raise", "ValueError", "(", "\"numtype argument must be one of: int, decimal, float\"", ")", "def", "check", "(", "val", ")", ":", "\"\"\"Checks that a value can be parsed as a number.\"\"\"", "if", "val", "is", "None", ":", "return", "present_optional", "else", ":", "is_num", ",", "new_val", "=", "cast", "(", "val", ")", "if", "not", "is_num", ":", "return", "False", "else", ":", "if", "min", "is", "not", "None", "and", "new_val", "<", "min", ":", "return", "False", "if", "max", "is", "not", "None", "and", "new_val", ">", "max", ":", "return", "False", "return", "True", "if", "not", "message", ":", "msg", "=", "[", "\"must be a\"", "]", "if", "numtype", "==", "\"int\"", ":", "msg", ".", "append", "(", "\"whole number\"", ")", "else", ":", "msg", ".", "append", "(", "\"number\"", ")", "if", "min", "is", "not", "None", "and", "max", "is", "not", "None", ":", "msg", ".", "append", "(", "\"between {0} and {1}\"", ".", "format", "(", "min", ",", "max", ")", ")", "elif", "min", "is", "not", "None", ":", "msg", ".", "append", "(", "\"greater than or equal to {0}\"", ".", "format", "(", "min", ")", ")", "elif", "max", "is", "not", "None", ":", "msg", ".", "append", "(", "\"less than or equal to {0}\"", ".", "format", "(", "max", ")", ")", "message", "=", "\" \"", ".", "join", "(", "msg", ")", "return", "Validation", "(", "check", ",", "property_name", ",", "message", ")" ]
Returns a Validation that checks a property as a number, with optional range constraints.
[ "Returns", "a", "Validation", "that", "checks", "a", "property", "as", "a", "number", "with", "optional", "range", "constraints", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/validation.py#L122-L163
249,889
treycucco/bidon
bidon/db/model/validation.py
Validation.is_date
def is_date(property_name, *, format=None, present_optional=False, message=None): """Returns a Validation that checks a value as a date.""" # NOTE: Not currently using format param def check(val): """Checks that a value can be parsed as a date.""" if val is None: return present_optional else: is_date, _ = util.try_parse_date(val) return is_date return Validation(check, property_name, message)
python
def is_date(property_name, *, format=None, present_optional=False, message=None): """Returns a Validation that checks a value as a date.""" # NOTE: Not currently using format param def check(val): """Checks that a value can be parsed as a date.""" if val is None: return present_optional else: is_date, _ = util.try_parse_date(val) return is_date return Validation(check, property_name, message)
[ "def", "is_date", "(", "property_name", ",", "*", ",", "format", "=", "None", ",", "present_optional", "=", "False", ",", "message", "=", "None", ")", ":", "# NOTE: Not currently using format param", "def", "check", "(", "val", ")", ":", "\"\"\"Checks that a value can be parsed as a date.\"\"\"", "if", "val", "is", "None", ":", "return", "present_optional", "else", ":", "is_date", ",", "_", "=", "util", ".", "try_parse_date", "(", "val", ")", "return", "is_date", "return", "Validation", "(", "check", ",", "property_name", ",", "message", ")" ]
Returns a Validation that checks a value as a date.
[ "Returns", "a", "Validation", "that", "checks", "a", "value", "as", "a", "date", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/validation.py#L166-L177
249,890
treycucco/bidon
bidon/db/model/validation.py
Validation.is_datetime
def is_datetime(property_name, *, format=None, present_optional=False, message=None): """Returns a Validation that checks a value as a datetime.""" # NOTE: Not currently using format param def check(val): """Checks that a value can be parsed as a datetime.""" if val is None: return present_optional else: is_date, _ = util.try_parse_datetime(val) return is_date return Validation(check, property_name, message)
python
def is_datetime(property_name, *, format=None, present_optional=False, message=None): """Returns a Validation that checks a value as a datetime.""" # NOTE: Not currently using format param def check(val): """Checks that a value can be parsed as a datetime.""" if val is None: return present_optional else: is_date, _ = util.try_parse_datetime(val) return is_date return Validation(check, property_name, message)
[ "def", "is_datetime", "(", "property_name", ",", "*", ",", "format", "=", "None", ",", "present_optional", "=", "False", ",", "message", "=", "None", ")", ":", "# NOTE: Not currently using format param", "def", "check", "(", "val", ")", ":", "\"\"\"Checks that a value can be parsed as a datetime.\"\"\"", "if", "val", "is", "None", ":", "return", "present_optional", "else", ":", "is_date", ",", "_", "=", "util", ".", "try_parse_datetime", "(", "val", ")", "return", "is_date", "return", "Validation", "(", "check", ",", "property_name", ",", "message", ")" ]
Returns a Validation that checks a value as a datetime.
[ "Returns", "a", "Validation", "that", "checks", "a", "value", "as", "a", "datetime", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/validation.py#L180-L191
249,891
treycucco/bidon
bidon/db/model/validation.py
Validation.is_in
def is_in(property_name, set_values, *, present_optional=False, message=None): """Returns a Validation that checks that a value is contained within a given set.""" def check(val): """Checks that a value is contained within a scope-enclosed set.""" if val is None: return present_optional else: return val in set_values return Validation(check, property_name, message)
python
def is_in(property_name, set_values, *, present_optional=False, message=None): """Returns a Validation that checks that a value is contained within a given set.""" def check(val): """Checks that a value is contained within a scope-enclosed set.""" if val is None: return present_optional else: return val in set_values return Validation(check, property_name, message)
[ "def", "is_in", "(", "property_name", ",", "set_values", ",", "*", ",", "present_optional", "=", "False", ",", "message", "=", "None", ")", ":", "def", "check", "(", "val", ")", ":", "\"\"\"Checks that a value is contained within a scope-enclosed set.\"\"\"", "if", "val", "is", "None", ":", "return", "present_optional", "else", ":", "return", "val", "in", "set_values", "return", "Validation", "(", "check", ",", "property_name", ",", "message", ")" ]
Returns a Validation that checks that a value is contained within a given set.
[ "Returns", "a", "Validation", "that", "checks", "that", "a", "value", "is", "contained", "within", "a", "given", "set", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/validation.py#L194-L203
249,892
treycucco/bidon
bidon/db/model/validation.py
Validation.is_unique
def is_unique(keys, *, scope=None, comparison_operators=None, present_optional=False, message=None): """Returns a Validation that makes sure the given value is unique for a table and optionally a scope. """ def check(pname, validator): """Checks that a value is unique in its column, with an optional scope.""" # pylint: disable=too-many-branches model = validator.model data_access = validator.data_access pkname = model.primary_key_name pkey = model.primary_key if isinstance(keys, str): key = getattr(model, keys) if present_optional and key is None: return True if comparison_operators: if isinstance(comparison_operators, str): op = comparison_operators else: op = comparison_operators[0] else: op = " = " constraints = [(keys, key, op)] else: if comparison_operators: ops = comparison_operators else: ops = [" = "] * len(keys) constraints = list(zip(keys, [getattr(model, key) for key in keys], ops)) if scope: if comparison_operators: ops = comparison_operators[len(constraints):] else: ops = [" = "] * len(scope) constraints.extend(zip(scope, [getattr(model, col) for col in scope], ops)) dupe = data_access.find(model.table_name, constraints, columns=pkname) if dupe is None: return True if isinstance(pkname, str): return dupe[0] == pkey else: return tuple(dupe) == tuple(pkey) return Validation(check, keys, message or "is already taken", is_simple=False)
python
def is_unique(keys, *, scope=None, comparison_operators=None, present_optional=False, message=None): """Returns a Validation that makes sure the given value is unique for a table and optionally a scope. """ def check(pname, validator): """Checks that a value is unique in its column, with an optional scope.""" # pylint: disable=too-many-branches model = validator.model data_access = validator.data_access pkname = model.primary_key_name pkey = model.primary_key if isinstance(keys, str): key = getattr(model, keys) if present_optional and key is None: return True if comparison_operators: if isinstance(comparison_operators, str): op = comparison_operators else: op = comparison_operators[0] else: op = " = " constraints = [(keys, key, op)] else: if comparison_operators: ops = comparison_operators else: ops = [" = "] * len(keys) constraints = list(zip(keys, [getattr(model, key) for key in keys], ops)) if scope: if comparison_operators: ops = comparison_operators[len(constraints):] else: ops = [" = "] * len(scope) constraints.extend(zip(scope, [getattr(model, col) for col in scope], ops)) dupe = data_access.find(model.table_name, constraints, columns=pkname) if dupe is None: return True if isinstance(pkname, str): return dupe[0] == pkey else: return tuple(dupe) == tuple(pkey) return Validation(check, keys, message or "is already taken", is_simple=False)
[ "def", "is_unique", "(", "keys", ",", "*", ",", "scope", "=", "None", ",", "comparison_operators", "=", "None", ",", "present_optional", "=", "False", ",", "message", "=", "None", ")", ":", "def", "check", "(", "pname", ",", "validator", ")", ":", "\"\"\"Checks that a value is unique in its column, with an optional scope.\"\"\"", "# pylint: disable=too-many-branches", "model", "=", "validator", ".", "model", "data_access", "=", "validator", ".", "data_access", "pkname", "=", "model", ".", "primary_key_name", "pkey", "=", "model", ".", "primary_key", "if", "isinstance", "(", "keys", ",", "str", ")", ":", "key", "=", "getattr", "(", "model", ",", "keys", ")", "if", "present_optional", "and", "key", "is", "None", ":", "return", "True", "if", "comparison_operators", ":", "if", "isinstance", "(", "comparison_operators", ",", "str", ")", ":", "op", "=", "comparison_operators", "else", ":", "op", "=", "comparison_operators", "[", "0", "]", "else", ":", "op", "=", "\" = \"", "constraints", "=", "[", "(", "keys", ",", "key", ",", "op", ")", "]", "else", ":", "if", "comparison_operators", ":", "ops", "=", "comparison_operators", "else", ":", "ops", "=", "[", "\" = \"", "]", "*", "len", "(", "keys", ")", "constraints", "=", "list", "(", "zip", "(", "keys", ",", "[", "getattr", "(", "model", ",", "key", ")", "for", "key", "in", "keys", "]", ",", "ops", ")", ")", "if", "scope", ":", "if", "comparison_operators", ":", "ops", "=", "comparison_operators", "[", "len", "(", "constraints", ")", ":", "]", "else", ":", "ops", "=", "[", "\" = \"", "]", "*", "len", "(", "scope", ")", "constraints", ".", "extend", "(", "zip", "(", "scope", ",", "[", "getattr", "(", "model", ",", "col", ")", "for", "col", "in", "scope", "]", ",", "ops", ")", ")", "dupe", "=", "data_access", ".", "find", "(", "model", ".", "table_name", ",", "constraints", ",", "columns", "=", "pkname", ")", "if", "dupe", "is", "None", ":", "return", "True", "if", "isinstance", "(", "pkname", ",", "str", ")", ":", "return", "dupe", "[", "0", "]", "==", "pkey", "else", ":", "return", "tuple", "(", "dupe", ")", "==", "tuple", "(", "pkey", ")", "return", "Validation", "(", "check", ",", "keys", ",", "message", "or", "\"is already taken\"", ",", "is_simple", "=", "False", ")" ]
Returns a Validation that makes sure the given value is unique for a table and optionally a scope.
[ "Returns", "a", "Validation", "that", "makes", "sure", "the", "given", "value", "is", "unique", "for", "a", "table", "and", "optionally", "a", "scope", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/validation.py#L206-L259
249,893
treycucco/bidon
bidon/db/model/validation.py
Validator.validate
def validate(self, model, data_access=None, *, fail_fast=None): """Validates a model against the collection of Validations. Returns True if all Validations pass, or False if one or more do not. """ if fail_fast is None: fail_fast = self.fail_fast self.model = model self.data_access = data_access is_valid = True for validation in self.validations: if not validation.validate(model, self): is_valid = False if fail_fast: break return is_valid
python
def validate(self, model, data_access=None, *, fail_fast=None): """Validates a model against the collection of Validations. Returns True if all Validations pass, or False if one or more do not. """ if fail_fast is None: fail_fast = self.fail_fast self.model = model self.data_access = data_access is_valid = True for validation in self.validations: if not validation.validate(model, self): is_valid = False if fail_fast: break return is_valid
[ "def", "validate", "(", "self", ",", "model", ",", "data_access", "=", "None", ",", "*", ",", "fail_fast", "=", "None", ")", ":", "if", "fail_fast", "is", "None", ":", "fail_fast", "=", "self", ".", "fail_fast", "self", ".", "model", "=", "model", "self", ".", "data_access", "=", "data_access", "is_valid", "=", "True", "for", "validation", "in", "self", ".", "validations", ":", "if", "not", "validation", ".", "validate", "(", "model", ",", "self", ")", ":", "is_valid", "=", "False", "if", "fail_fast", ":", "break", "return", "is_valid" ]
Validates a model against the collection of Validations. Returns True if all Validations pass, or False if one or more do not.
[ "Validates", "a", "model", "against", "the", "collection", "of", "Validations", "." ]
d9f24596841d0e69e8ac70a1d1a1deecea95e340
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/model/validation.py#L275-L291
249,894
techdragon/python-git-repo-info
src/git_repo_info/git_repo_info.py
GitRepo.configured_options
def configured_options(self): """What are the configured options in the git repo.""" stdout_lines = self._check_output(['config', '--list']).splitlines() return {key: value for key, value in [line.split('=') for line in stdout_lines]}
python
def configured_options(self): """What are the configured options in the git repo.""" stdout_lines = self._check_output(['config', '--list']).splitlines() return {key: value for key, value in [line.split('=') for line in stdout_lines]}
[ "def", "configured_options", "(", "self", ")", ":", "stdout_lines", "=", "self", ".", "_check_output", "(", "[", "'config'", ",", "'--list'", "]", ")", ".", "splitlines", "(", ")", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "[", "line", ".", "split", "(", "'='", ")", "for", "line", "in", "stdout_lines", "]", "}" ]
What are the configured options in the git repo.
[ "What", "are", "the", "configured", "options", "in", "the", "git", "repo", "." ]
f840ad83fe349abac96002e55c153f55d77b1cc9
https://github.com/techdragon/python-git-repo-info/blob/f840ad83fe349abac96002e55c153f55d77b1cc9/src/git_repo_info/git_repo_info.py#L67-L70
249,895
KnowledgeLinks/rdfframework
rdfframework/search/esutilities.py
get_es_action_item
def get_es_action_item(data_item, action_settings, es_type, id_field=None): ''' This method will return an item formated and ready to append to the action list ''' action_item = dict.copy(action_settings) if id_field is not None: id_val = first(list(get_dict_key(data_item, id_field))) if id_val is not None: action_item['_id'] = id_val elif data_item.get('id'): if data_item['id'].startswith("%s/" % action_settings['_index']): action_item['_id'] = "/".join(data_item['id'].split("/")[2:]) else: action_item['_id'] = data_item['id'] if data_item.get('data'): action_item['_source'] = data_item['data'] else: action_item['_source'] = data_item action_item['_type'] = es_type return action_item
python
def get_es_action_item(data_item, action_settings, es_type, id_field=None): ''' This method will return an item formated and ready to append to the action list ''' action_item = dict.copy(action_settings) if id_field is not None: id_val = first(list(get_dict_key(data_item, id_field))) if id_val is not None: action_item['_id'] = id_val elif data_item.get('id'): if data_item['id'].startswith("%s/" % action_settings['_index']): action_item['_id'] = "/".join(data_item['id'].split("/")[2:]) else: action_item['_id'] = data_item['id'] if data_item.get('data'): action_item['_source'] = data_item['data'] else: action_item['_source'] = data_item action_item['_type'] = es_type return action_item
[ "def", "get_es_action_item", "(", "data_item", ",", "action_settings", ",", "es_type", ",", "id_field", "=", "None", ")", ":", "action_item", "=", "dict", ".", "copy", "(", "action_settings", ")", "if", "id_field", "is", "not", "None", ":", "id_val", "=", "first", "(", "list", "(", "get_dict_key", "(", "data_item", ",", "id_field", ")", ")", ")", "if", "id_val", "is", "not", "None", ":", "action_item", "[", "'_id'", "]", "=", "id_val", "elif", "data_item", ".", "get", "(", "'id'", ")", ":", "if", "data_item", "[", "'id'", "]", ".", "startswith", "(", "\"%s/\"", "%", "action_settings", "[", "'_index'", "]", ")", ":", "action_item", "[", "'_id'", "]", "=", "\"/\"", ".", "join", "(", "data_item", "[", "'id'", "]", ".", "split", "(", "\"/\"", ")", "[", "2", ":", "]", ")", "else", ":", "action_item", "[", "'_id'", "]", "=", "data_item", "[", "'id'", "]", "if", "data_item", ".", "get", "(", "'data'", ")", ":", "action_item", "[", "'_source'", "]", "=", "data_item", "[", "'data'", "]", "else", ":", "action_item", "[", "'_source'", "]", "=", "data_item", "action_item", "[", "'_type'", "]", "=", "es_type", "return", "action_item" ]
This method will return an item formated and ready to append to the action list
[ "This", "method", "will", "return", "an", "item", "formated", "and", "ready", "to", "append", "to", "the", "action", "list" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/search/esutilities.py#L1-L20
249,896
KnowledgeLinks/rdfframework
rdfframework/search/esutilities.py
es_field_sort
def es_field_sort(fld_name): """ Used with lambda to sort fields """ parts = fld_name.split(".") if "_" not in parts[-1]: parts[-1] = "_" + parts[-1] return ".".join(parts)
python
def es_field_sort(fld_name): """ Used with lambda to sort fields """ parts = fld_name.split(".") if "_" not in parts[-1]: parts[-1] = "_" + parts[-1] return ".".join(parts)
[ "def", "es_field_sort", "(", "fld_name", ")", ":", "parts", "=", "fld_name", ".", "split", "(", "\".\"", ")", "if", "\"_\"", "not", "in", "parts", "[", "-", "1", "]", ":", "parts", "[", "-", "1", "]", "=", "\"_\"", "+", "parts", "[", "-", "1", "]", "return", "\".\"", ".", "join", "(", "parts", ")" ]
Used with lambda to sort fields
[ "Used", "with", "lambda", "to", "sort", "fields" ]
9ec32dcc4bed51650a4b392cc5c15100fef7923a
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/search/esutilities.py#L111-L116
249,897
kodexlab/reliure
reliure/web.py
app_routes
def app_routes(app): """ list of route of an app """ _routes = [] for rule in app.url_map.iter_rules(): _routes.append({ 'path': rule.rule, 'name': rule.endpoint, 'methods': list(rule.methods) }) return jsonify({'routes': _routes})
python
def app_routes(app): """ list of route of an app """ _routes = [] for rule in app.url_map.iter_rules(): _routes.append({ 'path': rule.rule, 'name': rule.endpoint, 'methods': list(rule.methods) }) return jsonify({'routes': _routes})
[ "def", "app_routes", "(", "app", ")", ":", "_routes", "=", "[", "]", "for", "rule", "in", "app", ".", "url_map", ".", "iter_rules", "(", ")", ":", "_routes", ".", "append", "(", "{", "'path'", ":", "rule", ".", "rule", ",", "'name'", ":", "rule", ".", "endpoint", ",", "'methods'", ":", "list", "(", "rule", ".", "methods", ")", "}", ")", "return", "jsonify", "(", "{", "'routes'", ":", "_routes", "}", ")" ]
list of route of an app
[ "list", "of", "route", "of", "an", "app" ]
0450c7a9254c5c003162738458bbe0c49e777ba5
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/web.py#L28-L38
249,898
kodexlab/reliure
reliure/web.py
EngineView.set_input_type
def set_input_type(self, type_or_parse): """ Set an unique input type. If you use this then you have only one input for the play. """ self._inputs = OrderedDict() default_inputs = self.engine.in_name if len(default_inputs) > 1: raise ValueError("Need more than one input, you sould use `add_input` for each of them") self.add_input(default_inputs[0], type_or_parse)
python
def set_input_type(self, type_or_parse): """ Set an unique input type. If you use this then you have only one input for the play. """ self._inputs = OrderedDict() default_inputs = self.engine.in_name if len(default_inputs) > 1: raise ValueError("Need more than one input, you sould use `add_input` for each of them") self.add_input(default_inputs[0], type_or_parse)
[ "def", "set_input_type", "(", "self", ",", "type_or_parse", ")", ":", "self", ".", "_inputs", "=", "OrderedDict", "(", ")", "default_inputs", "=", "self", ".", "engine", ".", "in_name", "if", "len", "(", "default_inputs", ")", ">", "1", ":", "raise", "ValueError", "(", "\"Need more than one input, you sould use `add_input` for each of them\"", ")", "self", ".", "add_input", "(", "default_inputs", "[", "0", "]", ",", "type_or_parse", ")" ]
Set an unique input type. If you use this then you have only one input for the play.
[ "Set", "an", "unique", "input", "type", "." ]
0450c7a9254c5c003162738458bbe0c49e777ba5
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/web.py#L74-L83
249,899
kodexlab/reliure
reliure/web.py
EngineView.add_input
def add_input(self, in_name, type_or_parse=None): """ Declare a possible input """ if type_or_parse is None: type_or_parse = GenericType() elif not isinstance(type_or_parse, GenericType) and callable(type_or_parse): type_or_parse = GenericType(parse=type_or_parse) elif not isinstance(type_or_parse, GenericType): raise ValueError("the given 'type_or_parse' is invalid") self._inputs[in_name] = type_or_parse
python
def add_input(self, in_name, type_or_parse=None): """ Declare a possible input """ if type_or_parse is None: type_or_parse = GenericType() elif not isinstance(type_or_parse, GenericType) and callable(type_or_parse): type_or_parse = GenericType(parse=type_or_parse) elif not isinstance(type_or_parse, GenericType): raise ValueError("the given 'type_or_parse' is invalid") self._inputs[in_name] = type_or_parse
[ "def", "add_input", "(", "self", ",", "in_name", ",", "type_or_parse", "=", "None", ")", ":", "if", "type_or_parse", "is", "None", ":", "type_or_parse", "=", "GenericType", "(", ")", "elif", "not", "isinstance", "(", "type_or_parse", ",", "GenericType", ")", "and", "callable", "(", "type_or_parse", ")", ":", "type_or_parse", "=", "GenericType", "(", "parse", "=", "type_or_parse", ")", "elif", "not", "isinstance", "(", "type_or_parse", ",", "GenericType", ")", ":", "raise", "ValueError", "(", "\"the given 'type_or_parse' is invalid\"", ")", "self", ".", "_inputs", "[", "in_name", "]", "=", "type_or_parse" ]
Declare a possible input
[ "Declare", "a", "possible", "input" ]
0450c7a9254c5c003162738458bbe0c49e777ba5
https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/web.py#L85-L94