repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript._dump | def _dump(self):
"""For debugging, dump the entire data structure."""
pp = pprint.PrettyPrinter(indent=4)
print("=== Variables ===")
print("-- Globals --")
pp.pprint(self._global)
print("-- Bot vars --")
pp.pprint(self._var)
print("-- Substitutions --")
pp.pprint(self._sub)
print("-- Person Substitutions --")
pp.pprint(self._person)
print("-- Arrays --")
pp.pprint(self._array)
print("=== Topic Structure ===")
pp.pprint(self._topics)
print("=== %Previous Structure ===")
pp.pprint(self._thats)
print("=== Includes ===")
pp.pprint(self._includes)
print("=== Inherits ===")
pp.pprint(self._lineage)
print("=== Sort Buffer ===")
pp.pprint(self._sorted)
print("=== Syntax Tree ===")
pp.pprint(self._syntax) | python | def _dump(self):
"""For debugging, dump the entire data structure."""
pp = pprint.PrettyPrinter(indent=4)
print("=== Variables ===")
print("-- Globals --")
pp.pprint(self._global)
print("-- Bot vars --")
pp.pprint(self._var)
print("-- Substitutions --")
pp.pprint(self._sub)
print("-- Person Substitutions --")
pp.pprint(self._person)
print("-- Arrays --")
pp.pprint(self._array)
print("=== Topic Structure ===")
pp.pprint(self._topics)
print("=== %Previous Structure ===")
pp.pprint(self._thats)
print("=== Includes ===")
pp.pprint(self._includes)
print("=== Inherits ===")
pp.pprint(self._lineage)
print("=== Sort Buffer ===")
pp.pprint(self._sorted)
print("=== Syntax Tree ===")
pp.pprint(self._syntax) | For debugging, dump the entire data structure. | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L992-L1023 |
aichaos/rivescript-python | rivescript/parser.py | Parser.parse | def parse(self, filename, code):
"""Read and parse a RiveScript document.
Returns a data structure that represents all of the useful contents of
the document, in this format::
{
"begin": { # "begin" data
"global": {}, # map of !global vars
"var": {}, # bot !var's
"sub": {}, # !sub substitutions
"person": {}, # !person substitutions
"array": {}, # !array lists
},
"topics": { # main reply data
"random": { # (topic name)
"includes": {}, # map of included topics (values=1)
"inherits": {}, # map of inherited topics
"triggers": [ # array of triggers
{
"trigger": "hello bot",
"reply": [], # array of replies
"condition": [], # array of conditions
"redirect": None, # redirect command
"previous": None, # 'previous' reply
},
# ...
]
}
}
"objects": [ # parsed object macros
{
"name": "", # object name
"language": "", # programming language
"code": [], # array of lines of code
}
]
}
Args:
filename (str): The name of the file that the code came from, for
syntax error reporting purposes.
code (str[]): The source code to parse.
Returns:
dict: The aforementioned data structure.
"""
# Eventual returned structure ("abstract syntax tree" but not really)
ast = {
"begin": {
"global": {},
"var": {},
"sub": {},
"person": {},
"array": {},
},
"topics": {},
"objects": [],
}
# Track temporary variables.
topic = 'random' # Default topic=random
lineno = 0 # Line numbers for syntax tracking
comment = False # In a multi-line comment
inobj = False # In an object
objname = '' # The name of the object we're in
objlang = '' # The programming language of the object
objbuf = [] # Object contents buffer
curtrig = None # Pointer to the current trigger in ast.topics
isThat = None # Is a %Previous trigger
# Local (file scoped) parser options.
local_options = dict(
concat="none", # Concat mode for ^Continue command
)
# Read each line.
for lp, line in enumerate(code):
lineno += 1
self.say("Line: " + line + " (topic: " + topic + ") incomment: " + str(inobj))
if len(line.strip()) == 0: # Skip blank lines
continue
# In an object?
if inobj:
if re.match(RE.objend, line):
# End the object.
if len(objname):
ast["objects"].append({
"name": objname,
"language": objlang,
"code": objbuf,
})
objname = ''
objlang = ''
objbuf = []
inobj = False
else:
objbuf.append(line)
continue
line = line.strip() # Trim excess space. We do it down here so we
# don't mess up python objects!
line = RE.ws.sub(" ", line) # Replace the multiple whitespaces by single whitespace
# Look for comments.
if line[:2] == '//': # A single-line comment.
continue
elif line[0] == '#':
self.warn("Using the # symbol for comments is deprecated", filename, lineno)
elif line[:2] == '/*': # Start of a multi-line comment.
if '*/' not in line: # Cancel if the end is here too.
comment = True
continue
elif '*/' in line:
comment = False
continue
if comment:
continue
# Separate the command from the data.
if len(line) < 2:
self.warn("Weird single-character line '" + line + "' found.", filename, lineno)
continue
cmd = line[0]
line = line[1:].strip()
# Ignore inline comments if there's a space before the // symbols.
if " //" in line:
line = line.split(" //")[0].strip()
# Run a syntax check on this line.
syntax_error = self.check_syntax(cmd, line)
if syntax_error:
# There was a syntax error! Are we enforcing strict mode?
syntax_error = "Syntax error in " + filename + " line " + str(lineno) + ": " \
+ syntax_error + " (near: " + cmd + " " + line + ")"
if self.strict:
raise Exception(syntax_error)
else:
self.warn(syntax_error)
return # Don't try to continue
# Reset the %Previous state if this is a new +Trigger.
if cmd == '+':
isThat = None
# Do a lookahead for ^Continue and %Previous commands.
for i in range(lp + 1, len(code)):
lookahead = code[i].strip()
if len(lookahead) < 2:
continue
lookCmd = lookahead[0]
lookahead = lookahead[1:].strip()
lookahead = re.sub(RE.space, ' ', lookahead) # Replace the `\s` in the message
# Only continue if the lookahead line has any data.
if len(lookahead) != 0:
# The lookahead command has to be either a % or a ^.
if lookCmd != '^' and lookCmd != '%':
break
# If the current command is a +, see if the following is
# a %.
if cmd == '+':
if lookCmd == '%':
isThat = lookahead
break
else:
isThat = None
# If the current command is a ! and the next command(s) are
# ^, we'll tack each extension on as a line break (which is
# useful information for arrays).
if cmd == '!':
if lookCmd == '^':
line += "<crlf>" + lookahead
continue
# If the current command is not a ^ and the line after is
# not a %, but the line after IS a ^, then tack it on to the
# end of the current line.
if cmd != '^' and lookCmd != '%':
if lookCmd == '^':
line += self.concat_modes.get(
local_options["concat"], ""
) + lookahead
else:
break
self.say("Command: " + cmd + "; line: " + line)
# Handle the types of RiveScript commands.
if cmd == '!':
# ! DEFINE
halves = re.split(RE.equals, line, 2)
left = re.split(RE.ws, halves[0].strip(), 2)
value, type, var = '', '', ''
if len(halves) == 2:
value = halves[1].strip()
if len(left) >= 1:
type = left[0].strip()
if len(left) >= 2:
var = ' '.join(left[1:]).strip()
# Remove 'fake' line breaks unless this is an array.
if type != 'array':
value = re.sub(RE.crlf, '', value)
# Handle version numbers.
if type == 'version':
# Verify we support it.
try:
if float(value) > rs_version:
self.warn("Unsupported RiveScript version. We only support " + rs_version, filename, lineno)
return
except:
self.warn("Error parsing RiveScript version number: not a number", filename, lineno)
continue
# All other types of defines require a variable and value name.
if len(var) == 0:
self.warn("Undefined variable name", filename, lineno)
continue
elif len(value) == 0:
self.warn("Undefined variable value", filename, lineno)
continue
# Handle the rest of the types.
if type == 'local':
# Local file-scoped parser options.
self.say("\tSet parser option " + var + " = " + value)
local_options[var] = value
elif type == 'global':
# 'Global' variables
self.say("\tSet global " + var + " = " + value)
if value == '<undef>':
try:
del(ast["begin"]["global"][var])
except:
self.warn("Failed to delete missing global variable", filename, lineno)
else:
ast["begin"]["global"][var] = value
# Handle flipping debug and depth vars.
if var == 'debug':
if value.lower() == 'true':
value = True
else:
value = False
elif var == 'depth':
try:
value = int(value)
except:
self.warn("Failed to set 'depth' because the value isn't a number!", filename, lineno)
elif var == 'strict':
if value.lower() == 'true':
value = True
else:
value = False
elif type == 'var':
# Bot variables
self.say("\tSet bot variable " + var + " = " + value)
if value == '<undef>':
try:
del(ast["begin"]["var"][var])
except:
self.warn("Failed to delete missing bot variable", filename, lineno)
else:
ast["begin"]["var"][var] = value
elif type == 'array':
# Arrays
self.say("\tArray " + var + " = " + value)
if value == '<undef>':
try:
del(ast["begin"]["array"][var])
except:
self.warn("Failed to delete missing array", filename, lineno)
continue
# Did this have multiple parts?
parts = value.split("<crlf>")
# Process each line of array data.
fields = []
for val in parts:
if '|' in val:
fields.extend(val.split('|'))
else:
fields.extend(re.split(RE.ws, val))
# Convert any remaining '\s' escape codes into spaces.
for f in fields:
f = f.replace('\s', ' ')
ast["begin"]["array"][var] = fields
elif type == 'sub':
# Substitutions
self.say("\tSubstitution " + var + " => " + value)
if value == '<undef>':
try:
del(ast["begin"]["sub"][var])
except:
self.warn("Failed to delete missing substitution", filename, lineno)
else:
ast["begin"]["sub"][var] = value
elif type == 'person':
# Person Substitutions
self.say("\tPerson Substitution " + var + " => " + value)
if value == '<undef>':
try:
del(ast["begin"]["person"][var])
except:
self.warn("Failed to delete missing person substitution", filename, lineno)
else:
ast["begin"]["person"][var] = value
else:
self.warn("Unknown definition type '" + type + "'", filename, lineno)
elif cmd == '>':
# > LABEL
temp = re.split(RE.ws, line)
type = temp[0]
name = ''
fields = []
if len(temp) >= 2:
name = temp[1]
if len(temp) >= 3:
fields = temp[2:]
# Handle the label types.
if type == 'begin':
# The BEGIN block.
self.say("\tFound the BEGIN block.")
type = 'topic'
name = '__begin__'
if type == 'topic':
# Starting a new topic.
self.say("\tSet topic to " + name)
curtrig = None
topic = name
# Initialize the topic tree.
self._init_topic(ast["topics"], topic)
# Does this topic include or inherit another one?
mode = '' # or 'inherits' or 'includes'
if len(fields) >= 2:
for field in fields:
if field == 'includes':
mode = 'includes'
elif field == 'inherits':
mode = 'inherits'
elif mode != '':
# This topic is either inherited or included.
if mode == 'includes':
ast["topics"][name]["includes"][field] = 1
else:
ast["topics"][name]["inherits"][field] = 1
elif type == 'object':
# If a field was provided, it should be the programming
# language.
lang = None
if len(fields) > 0:
lang = fields[0].lower()
# Only try to parse a language we support.
curtrig = None
if lang is None:
self.warn("Trying to parse unknown programming language", filename, lineno)
lang = 'python' # Assume it's Python.
# We have a handler, so start loading the code.
objname = name
objlang = lang
objbuf = []
inobj = True
else:
self.warn("Unknown label type '" + type + "'", filename, lineno)
elif cmd == '<':
# < LABEL
type = line
if type == 'begin' or type == 'topic':
self.say("\tEnd topic label.")
topic = 'random'
elif type == 'object':
self.say("\tEnd object label.")
inobj = False
elif cmd == '+':
# + TRIGGER
self.say("\tTrigger pattern: " + line)
# Initialize the topic tree.
self._init_topic(ast["topics"], topic)
curtrig = {
"trigger": line,
"reply": [],
"condition": [],
"redirect": None,
"previous": isThat,
}
ast["topics"][topic]["triggers"].append(curtrig)
elif cmd == '-':
# - REPLY
if curtrig is None:
self.warn("Response found before trigger", filename, lineno)
continue
self.say("\tResponse: " + line)
curtrig["reply"].append(line.strip())
elif cmd == '%':
# % PREVIOUS
pass # This was handled above.
elif cmd == '^':
# ^ CONTINUE
pass # This was handled above.
elif cmd == '@':
# @ REDIRECT
if curtrig is None:
self.warn("Redirect found before trigger", filename, lineno)
continue
self.say("\tRedirect: " + line)
curtrig["redirect"] = line.strip()
elif cmd == '*':
# * CONDITION
if curtrig is None:
self.warn("Condition found before trigger", filename, lineno)
continue
self.say("\tAdding condition: " + line)
curtrig["condition"].append(line.strip())
else:
self.warn("Unrecognized command \"" + cmd + "\"", filename, lineno)
continue
return ast | python | def parse(self, filename, code):
"""Read and parse a RiveScript document.
Returns a data structure that represents all of the useful contents of
the document, in this format::
{
"begin": { # "begin" data
"global": {}, # map of !global vars
"var": {}, # bot !var's
"sub": {}, # !sub substitutions
"person": {}, # !person substitutions
"array": {}, # !array lists
},
"topics": { # main reply data
"random": { # (topic name)
"includes": {}, # map of included topics (values=1)
"inherits": {}, # map of inherited topics
"triggers": [ # array of triggers
{
"trigger": "hello bot",
"reply": [], # array of replies
"condition": [], # array of conditions
"redirect": None, # redirect command
"previous": None, # 'previous' reply
},
# ...
]
}
}
"objects": [ # parsed object macros
{
"name": "", # object name
"language": "", # programming language
"code": [], # array of lines of code
}
]
}
Args:
filename (str): The name of the file that the code came from, for
syntax error reporting purposes.
code (str[]): The source code to parse.
Returns:
dict: The aforementioned data structure.
"""
# Eventual returned structure ("abstract syntax tree" but not really)
ast = {
"begin": {
"global": {},
"var": {},
"sub": {},
"person": {},
"array": {},
},
"topics": {},
"objects": [],
}
# Track temporary variables.
topic = 'random' # Default topic=random
lineno = 0 # Line numbers for syntax tracking
comment = False # In a multi-line comment
inobj = False # In an object
objname = '' # The name of the object we're in
objlang = '' # The programming language of the object
objbuf = [] # Object contents buffer
curtrig = None # Pointer to the current trigger in ast.topics
isThat = None # Is a %Previous trigger
# Local (file scoped) parser options.
local_options = dict(
concat="none", # Concat mode for ^Continue command
)
# Read each line.
for lp, line in enumerate(code):
lineno += 1
self.say("Line: " + line + " (topic: " + topic + ") incomment: " + str(inobj))
if len(line.strip()) == 0: # Skip blank lines
continue
# In an object?
if inobj:
if re.match(RE.objend, line):
# End the object.
if len(objname):
ast["objects"].append({
"name": objname,
"language": objlang,
"code": objbuf,
})
objname = ''
objlang = ''
objbuf = []
inobj = False
else:
objbuf.append(line)
continue
line = line.strip() # Trim excess space. We do it down here so we
# don't mess up python objects!
line = RE.ws.sub(" ", line) # Replace the multiple whitespaces by single whitespace
# Look for comments.
if line[:2] == '//': # A single-line comment.
continue
elif line[0] == '#':
self.warn("Using the # symbol for comments is deprecated", filename, lineno)
elif line[:2] == '/*': # Start of a multi-line comment.
if '*/' not in line: # Cancel if the end is here too.
comment = True
continue
elif '*/' in line:
comment = False
continue
if comment:
continue
# Separate the command from the data.
if len(line) < 2:
self.warn("Weird single-character line '" + line + "' found.", filename, lineno)
continue
cmd = line[0]
line = line[1:].strip()
# Ignore inline comments if there's a space before the // symbols.
if " //" in line:
line = line.split(" //")[0].strip()
# Run a syntax check on this line.
syntax_error = self.check_syntax(cmd, line)
if syntax_error:
# There was a syntax error! Are we enforcing strict mode?
syntax_error = "Syntax error in " + filename + " line " + str(lineno) + ": " \
+ syntax_error + " (near: " + cmd + " " + line + ")"
if self.strict:
raise Exception(syntax_error)
else:
self.warn(syntax_error)
return # Don't try to continue
# Reset the %Previous state if this is a new +Trigger.
if cmd == '+':
isThat = None
# Do a lookahead for ^Continue and %Previous commands.
for i in range(lp + 1, len(code)):
lookahead = code[i].strip()
if len(lookahead) < 2:
continue
lookCmd = lookahead[0]
lookahead = lookahead[1:].strip()
lookahead = re.sub(RE.space, ' ', lookahead) # Replace the `\s` in the message
# Only continue if the lookahead line has any data.
if len(lookahead) != 0:
# The lookahead command has to be either a % or a ^.
if lookCmd != '^' and lookCmd != '%':
break
# If the current command is a +, see if the following is
# a %.
if cmd == '+':
if lookCmd == '%':
isThat = lookahead
break
else:
isThat = None
# If the current command is a ! and the next command(s) are
# ^, we'll tack each extension on as a line break (which is
# useful information for arrays).
if cmd == '!':
if lookCmd == '^':
line += "<crlf>" + lookahead
continue
# If the current command is not a ^ and the line after is
# not a %, but the line after IS a ^, then tack it on to the
# end of the current line.
if cmd != '^' and lookCmd != '%':
if lookCmd == '^':
line += self.concat_modes.get(
local_options["concat"], ""
) + lookahead
else:
break
self.say("Command: " + cmd + "; line: " + line)
# Handle the types of RiveScript commands.
if cmd == '!':
# ! DEFINE
halves = re.split(RE.equals, line, 2)
left = re.split(RE.ws, halves[0].strip(), 2)
value, type, var = '', '', ''
if len(halves) == 2:
value = halves[1].strip()
if len(left) >= 1:
type = left[0].strip()
if len(left) >= 2:
var = ' '.join(left[1:]).strip()
# Remove 'fake' line breaks unless this is an array.
if type != 'array':
value = re.sub(RE.crlf, '', value)
# Handle version numbers.
if type == 'version':
# Verify we support it.
try:
if float(value) > rs_version:
self.warn("Unsupported RiveScript version. We only support " + rs_version, filename, lineno)
return
except:
self.warn("Error parsing RiveScript version number: not a number", filename, lineno)
continue
# All other types of defines require a variable and value name.
if len(var) == 0:
self.warn("Undefined variable name", filename, lineno)
continue
elif len(value) == 0:
self.warn("Undefined variable value", filename, lineno)
continue
# Handle the rest of the types.
if type == 'local':
# Local file-scoped parser options.
self.say("\tSet parser option " + var + " = " + value)
local_options[var] = value
elif type == 'global':
# 'Global' variables
self.say("\tSet global " + var + " = " + value)
if value == '<undef>':
try:
del(ast["begin"]["global"][var])
except:
self.warn("Failed to delete missing global variable", filename, lineno)
else:
ast["begin"]["global"][var] = value
# Handle flipping debug and depth vars.
if var == 'debug':
if value.lower() == 'true':
value = True
else:
value = False
elif var == 'depth':
try:
value = int(value)
except:
self.warn("Failed to set 'depth' because the value isn't a number!", filename, lineno)
elif var == 'strict':
if value.lower() == 'true':
value = True
else:
value = False
elif type == 'var':
# Bot variables
self.say("\tSet bot variable " + var + " = " + value)
if value == '<undef>':
try:
del(ast["begin"]["var"][var])
except:
self.warn("Failed to delete missing bot variable", filename, lineno)
else:
ast["begin"]["var"][var] = value
elif type == 'array':
# Arrays
self.say("\tArray " + var + " = " + value)
if value == '<undef>':
try:
del(ast["begin"]["array"][var])
except:
self.warn("Failed to delete missing array", filename, lineno)
continue
# Did this have multiple parts?
parts = value.split("<crlf>")
# Process each line of array data.
fields = []
for val in parts:
if '|' in val:
fields.extend(val.split('|'))
else:
fields.extend(re.split(RE.ws, val))
# Convert any remaining '\s' escape codes into spaces.
for f in fields:
f = f.replace('\s', ' ')
ast["begin"]["array"][var] = fields
elif type == 'sub':
# Substitutions
self.say("\tSubstitution " + var + " => " + value)
if value == '<undef>':
try:
del(ast["begin"]["sub"][var])
except:
self.warn("Failed to delete missing substitution", filename, lineno)
else:
ast["begin"]["sub"][var] = value
elif type == 'person':
# Person Substitutions
self.say("\tPerson Substitution " + var + " => " + value)
if value == '<undef>':
try:
del(ast["begin"]["person"][var])
except:
self.warn("Failed to delete missing person substitution", filename, lineno)
else:
ast["begin"]["person"][var] = value
else:
self.warn("Unknown definition type '" + type + "'", filename, lineno)
elif cmd == '>':
# > LABEL
temp = re.split(RE.ws, line)
type = temp[0]
name = ''
fields = []
if len(temp) >= 2:
name = temp[1]
if len(temp) >= 3:
fields = temp[2:]
# Handle the label types.
if type == 'begin':
# The BEGIN block.
self.say("\tFound the BEGIN block.")
type = 'topic'
name = '__begin__'
if type == 'topic':
# Starting a new topic.
self.say("\tSet topic to " + name)
curtrig = None
topic = name
# Initialize the topic tree.
self._init_topic(ast["topics"], topic)
# Does this topic include or inherit another one?
mode = '' # or 'inherits' or 'includes'
if len(fields) >= 2:
for field in fields:
if field == 'includes':
mode = 'includes'
elif field == 'inherits':
mode = 'inherits'
elif mode != '':
# This topic is either inherited or included.
if mode == 'includes':
ast["topics"][name]["includes"][field] = 1
else:
ast["topics"][name]["inherits"][field] = 1
elif type == 'object':
# If a field was provided, it should be the programming
# language.
lang = None
if len(fields) > 0:
lang = fields[0].lower()
# Only try to parse a language we support.
curtrig = None
if lang is None:
self.warn("Trying to parse unknown programming language", filename, lineno)
lang = 'python' # Assume it's Python.
# We have a handler, so start loading the code.
objname = name
objlang = lang
objbuf = []
inobj = True
else:
self.warn("Unknown label type '" + type + "'", filename, lineno)
elif cmd == '<':
# < LABEL
type = line
if type == 'begin' or type == 'topic':
self.say("\tEnd topic label.")
topic = 'random'
elif type == 'object':
self.say("\tEnd object label.")
inobj = False
elif cmd == '+':
# + TRIGGER
self.say("\tTrigger pattern: " + line)
# Initialize the topic tree.
self._init_topic(ast["topics"], topic)
curtrig = {
"trigger": line,
"reply": [],
"condition": [],
"redirect": None,
"previous": isThat,
}
ast["topics"][topic]["triggers"].append(curtrig)
elif cmd == '-':
# - REPLY
if curtrig is None:
self.warn("Response found before trigger", filename, lineno)
continue
self.say("\tResponse: " + line)
curtrig["reply"].append(line.strip())
elif cmd == '%':
# % PREVIOUS
pass # This was handled above.
elif cmd == '^':
# ^ CONTINUE
pass # This was handled above.
elif cmd == '@':
# @ REDIRECT
if curtrig is None:
self.warn("Redirect found before trigger", filename, lineno)
continue
self.say("\tRedirect: " + line)
curtrig["redirect"] = line.strip()
elif cmd == '*':
# * CONDITION
if curtrig is None:
self.warn("Condition found before trigger", filename, lineno)
continue
self.say("\tAdding condition: " + line)
curtrig["condition"].append(line.strip())
else:
self.warn("Unrecognized command \"" + cmd + "\"", filename, lineno)
continue
return ast | Read and parse a RiveScript document.
Returns a data structure that represents all of the useful contents of
the document, in this format::
{
"begin": { # "begin" data
"global": {}, # map of !global vars
"var": {}, # bot !var's
"sub": {}, # !sub substitutions
"person": {}, # !person substitutions
"array": {}, # !array lists
},
"topics": { # main reply data
"random": { # (topic name)
"includes": {}, # map of included topics (values=1)
"inherits": {}, # map of inherited topics
"triggers": [ # array of triggers
{
"trigger": "hello bot",
"reply": [], # array of replies
"condition": [], # array of conditions
"redirect": None, # redirect command
"previous": None, # 'previous' reply
},
# ...
]
}
}
"objects": [ # parsed object macros
{
"name": "", # object name
"language": "", # programming language
"code": [], # array of lines of code
}
]
}
Args:
filename (str): The name of the file that the code came from, for
syntax error reporting purposes.
code (str[]): The source code to parse.
Returns:
dict: The aforementioned data structure. | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/parser.py#L62-L505 |
aichaos/rivescript-python | rivescript/parser.py | Parser.check_syntax | def check_syntax(self, cmd, line):
"""Syntax check a line of RiveScript code.
Args:
str cmd: The command symbol for the line of code, such as one
of ``+``, ``-``, ``*``, ``>``, etc.
str line: The remainder of the line of code, such as the text of
a trigger or reply.
Return:
str: A string syntax error message or ``None`` if no errors.
"""
# Run syntax checks based on the type of command.
if cmd == '!':
# ! Definition
# - Must be formatted like this:
# ! type name = value
# OR
# ! type = value
match = re.match(RE.def_syntax, line)
if not match:
return "Invalid format for !Definition line: must be '! type name = value' OR '! type = value'"
elif cmd == '>':
# > Label
# - The "begin" label must have only one argument ("begin")
# - "topic" labels must be lowercased but can inherit other topics (a-z0-9_\s)
# - "object" labels must follow the same rules as "topic", but don't need to be lowercase
parts = re.split(" ", line, 2)
if parts[0] == "begin" and len(parts) > 1:
return "The 'begin' label takes no additional arguments, should be verbatim '> begin'"
elif parts[0] == "topic":
search = re.search(RE.name_syntax, line)
if search:
return "Topics should be lowercased and contain only numbers and letters"
elif parts[0] == "object":
search = re.search(RE.obj_syntax, line) # Upper case is allowed
if search:
return "Objects can only contain numbers and letters"
elif cmd == '+' or cmd == '%' or cmd == '@':
# + Trigger, % Previous, @ Redirect
# This one is strict. The triggers are to be run through the regexp engine,
# therefore it should be acceptable for the regexp engine.
# - Entirely lowercase
# - No symbols except: ( | ) [ ] * _ # @ { } < > =
# - All brackets should be matched
# - No empty option with pipe such as ||, [|, |], (|, |) and whitespace between
parens = 0 # Open parenthesis
square = 0 # Open square brackets
curly = 0 # Open curly brackets
angle = 0 # Open angled brackets
# Count brackets.
for char in line:
if char == '(':
parens += 1
elif char == ')':
parens -= 1
elif char == '[':
square += 1
elif char == ']':
square -= 1
elif char == '{':
curly += 1
elif char == '}':
curly -= 1
elif char == '<':
angle += 1
elif char == '>':
angle -= 1
elif char == '|':
if parens == 0 and square == 0: # Pipe outside the alternative and option
return "Pipe | must be within parenthesis brackets or square brackets"
if (angle != 0) and (char in {"(", ")", "[", "]", "{", "}"}):
return "Angle bracket must be closed before closing or opening other type of brackets"
total = parens + square + curly # At each character, not more than 1 bracket opens, except <>
for special_char_count in [parens, square, curly, angle, total]:
if special_char_count not in (0, 1):
return "Unbalanced brackets"
# Any mismatches?
if parens != 0:
return "Unmatched parenthesis brackets"
elif square != 0:
return "Unmatched square brackets"
elif curly != 0:
return "Unmatched curly brackets"
elif angle != 0:
return "Unmatched angle brackets"
# Check for empty pipe
search = re.search(RE.empty_pipe, line)
if search:
return "Piped arrays can't include blank entries"
# In UTF-8 mode, most symbols are allowed.
if self.utf8:
search = re.search(RE.utf8_trig, line)
if search:
return "Triggers can't contain uppercase letters, backslashes or dots in UTF-8 mode."
else:
search = re.search(RE.trig_syntax, line)
if search:
return "Triggers may only contain lowercase letters, numbers, and these symbols: ( | ) [ ] * _ # @ { } < > ="
elif cmd == '-' or cmd == '^' or cmd == '/':
# - Trigger, ^ Continue, / Comment
# These commands take verbatim arguments, so their syntax is loose.
pass
elif cmd == '*':
# * Condition
# Syntax for a conditional is as follows:
# * value symbol value => response
match = re.match(RE.cond_syntax, line)
if not match:
return "Invalid format for !Condition: should be like '* value symbol value => response'"
return None | python | def check_syntax(self, cmd, line):
"""Syntax check a line of RiveScript code.
Args:
str cmd: The command symbol for the line of code, such as one
of ``+``, ``-``, ``*``, ``>``, etc.
str line: The remainder of the line of code, such as the text of
a trigger or reply.
Return:
str: A string syntax error message or ``None`` if no errors.
"""
# Run syntax checks based on the type of command.
if cmd == '!':
# ! Definition
# - Must be formatted like this:
# ! type name = value
# OR
# ! type = value
match = re.match(RE.def_syntax, line)
if not match:
return "Invalid format for !Definition line: must be '! type name = value' OR '! type = value'"
elif cmd == '>':
# > Label
# - The "begin" label must have only one argument ("begin")
# - "topic" labels must be lowercased but can inherit other topics (a-z0-9_\s)
# - "object" labels must follow the same rules as "topic", but don't need to be lowercase
parts = re.split(" ", line, 2)
if parts[0] == "begin" and len(parts) > 1:
return "The 'begin' label takes no additional arguments, should be verbatim '> begin'"
elif parts[0] == "topic":
search = re.search(RE.name_syntax, line)
if search:
return "Topics should be lowercased and contain only numbers and letters"
elif parts[0] == "object":
search = re.search(RE.obj_syntax, line) # Upper case is allowed
if search:
return "Objects can only contain numbers and letters"
elif cmd == '+' or cmd == '%' or cmd == '@':
# + Trigger, % Previous, @ Redirect
# This one is strict. The triggers are to be run through the regexp engine,
# therefore it should be acceptable for the regexp engine.
# - Entirely lowercase
# - No symbols except: ( | ) [ ] * _ # @ { } < > =
# - All brackets should be matched
# - No empty option with pipe such as ||, [|, |], (|, |) and whitespace between
parens = 0 # Open parenthesis
square = 0 # Open square brackets
curly = 0 # Open curly brackets
angle = 0 # Open angled brackets
# Count brackets.
for char in line:
if char == '(':
parens += 1
elif char == ')':
parens -= 1
elif char == '[':
square += 1
elif char == ']':
square -= 1
elif char == '{':
curly += 1
elif char == '}':
curly -= 1
elif char == '<':
angle += 1
elif char == '>':
angle -= 1
elif char == '|':
if parens == 0 and square == 0: # Pipe outside the alternative and option
return "Pipe | must be within parenthesis brackets or square brackets"
if (angle != 0) and (char in {"(", ")", "[", "]", "{", "}"}):
return "Angle bracket must be closed before closing or opening other type of brackets"
total = parens + square + curly # At each character, not more than 1 bracket opens, except <>
for special_char_count in [parens, square, curly, angle, total]:
if special_char_count not in (0, 1):
return "Unbalanced brackets"
# Any mismatches?
if parens != 0:
return "Unmatched parenthesis brackets"
elif square != 0:
return "Unmatched square brackets"
elif curly != 0:
return "Unmatched curly brackets"
elif angle != 0:
return "Unmatched angle brackets"
# Check for empty pipe
search = re.search(RE.empty_pipe, line)
if search:
return "Piped arrays can't include blank entries"
# In UTF-8 mode, most symbols are allowed.
if self.utf8:
search = re.search(RE.utf8_trig, line)
if search:
return "Triggers can't contain uppercase letters, backslashes or dots in UTF-8 mode."
else:
search = re.search(RE.trig_syntax, line)
if search:
return "Triggers may only contain lowercase letters, numbers, and these symbols: ( | ) [ ] * _ # @ { } < > ="
elif cmd == '-' or cmd == '^' or cmd == '/':
# - Trigger, ^ Continue, / Comment
# These commands take verbatim arguments, so their syntax is loose.
pass
elif cmd == '*':
# * Condition
# Syntax for a conditional is as follows:
# * value symbol value => response
match = re.match(RE.cond_syntax, line)
if not match:
return "Invalid format for !Condition: should be like '* value symbol value => response'"
return None | Syntax check a line of RiveScript code.
Args:
str cmd: The command symbol for the line of code, such as one
of ``+``, ``-``, ``*``, ``>``, etc.
str line: The remainder of the line of code, such as the text of
a trigger or reply.
Return:
str: A string syntax error message or ``None`` if no errors. | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/parser.py#L507-L625 |
semente/django-smuggler | smuggler/views.py | dump_to_response | def dump_to_response(request, app_label=None, exclude=None,
filename_prefix=None):
"""Utility function that dumps the given app/model to an HttpResponse.
"""
app_label = app_label or []
exclude = exclude
try:
filename = '%s.%s' % (datetime.now().isoformat(),
settings.SMUGGLER_FORMAT)
if filename_prefix:
filename = '%s_%s' % (filename_prefix, filename)
if not isinstance(app_label, list):
app_label = [app_label]
response = serialize_to_response(app_label, exclude)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
except CommandError as e:
messages.error(
request,
_('An exception occurred while dumping data: %s') % force_text(e))
return HttpResponseRedirect(request.build_absolute_uri().split('dump')[0]) | python | def dump_to_response(request, app_label=None, exclude=None,
filename_prefix=None):
"""Utility function that dumps the given app/model to an HttpResponse.
"""
app_label = app_label or []
exclude = exclude
try:
filename = '%s.%s' % (datetime.now().isoformat(),
settings.SMUGGLER_FORMAT)
if filename_prefix:
filename = '%s_%s' % (filename_prefix, filename)
if not isinstance(app_label, list):
app_label = [app_label]
response = serialize_to_response(app_label, exclude)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
except CommandError as e:
messages.error(
request,
_('An exception occurred while dumping data: %s') % force_text(e))
return HttpResponseRedirect(request.build_absolute_uri().split('dump')[0]) | Utility function that dumps the given app/model to an HttpResponse. | https://github.com/semente/django-smuggler/blob/3be76f4e94e50e927a55a60741fac1a793df83de/smuggler/views.py#L31-L51 |
semente/django-smuggler | smuggler/views.py | dump_data | def dump_data(request):
"""Exports data from whole project.
"""
# Try to grab app_label data
app_label = request.GET.get('app_label', [])
if app_label:
app_label = app_label.split(',')
return dump_to_response(request, app_label=app_label,
exclude=settings.SMUGGLER_EXCLUDE_LIST) | python | def dump_data(request):
"""Exports data from whole project.
"""
# Try to grab app_label data
app_label = request.GET.get('app_label', [])
if app_label:
app_label = app_label.split(',')
return dump_to_response(request, app_label=app_label,
exclude=settings.SMUGGLER_EXCLUDE_LIST) | Exports data from whole project. | https://github.com/semente/django-smuggler/blob/3be76f4e94e50e927a55a60741fac1a793df83de/smuggler/views.py#L63-L71 |
semente/django-smuggler | smuggler/views.py | dump_model_data | def dump_model_data(request, app_label, model_label):
"""Exports data from a model.
"""
return dump_to_response(request, '%s.%s' % (app_label, model_label),
[], '-'.join((app_label, model_label))) | python | def dump_model_data(request, app_label, model_label):
"""Exports data from a model.
"""
return dump_to_response(request, '%s.%s' % (app_label, model_label),
[], '-'.join((app_label, model_label))) | Exports data from a model. | https://github.com/semente/django-smuggler/blob/3be76f4e94e50e927a55a60741fac1a793df83de/smuggler/views.py#L83-L87 |
mozilla/crontabber | crontabber/base.py | toposort | def toposort(data):
"""Dependencies are expressed as a dictionary whose keys are items
and whose values are a set of dependent items. Output is a list of
sets in topological order. The first set consists of items with no
dependences, each subsequent set consists of items that depend upon
items in the preceeding sets.
"""
# Special case empty input.
if len(data) == 0:
return
# Copy the input so as to leave it unmodified.
data = data.copy()
# Ignore self dependencies.
for k, v in data.items():
v.discard(k)
# Find all items that don't depend on anything.
extra_items_in_deps = functools.reduce(
set.union, data.values()
) - set(data.keys())
# Add empty dependences where needed.
data.update(dict((item, set()) for item in extra_items_in_deps))
while True:
ordered = set(item for item, dep in data.items() if len(dep) == 0)
if not ordered:
break
yield ordered
data = dict(
(item, (dep - ordered))
for item, dep in data.items()
if item not in ordered
)
if len(data) != 0:
raise ValueError(
'Cyclic dependencies exist among these items: {}'
.format(', '.join(repr(x) for x in data.items()))
) | python | def toposort(data):
"""Dependencies are expressed as a dictionary whose keys are items
and whose values are a set of dependent items. Output is a list of
sets in topological order. The first set consists of items with no
dependences, each subsequent set consists of items that depend upon
items in the preceeding sets.
"""
# Special case empty input.
if len(data) == 0:
return
# Copy the input so as to leave it unmodified.
data = data.copy()
# Ignore self dependencies.
for k, v in data.items():
v.discard(k)
# Find all items that don't depend on anything.
extra_items_in_deps = functools.reduce(
set.union, data.values()
) - set(data.keys())
# Add empty dependences where needed.
data.update(dict((item, set()) for item in extra_items_in_deps))
while True:
ordered = set(item for item, dep in data.items() if len(dep) == 0)
if not ordered:
break
yield ordered
data = dict(
(item, (dep - ordered))
for item, dep in data.items()
if item not in ordered
)
if len(data) != 0:
raise ValueError(
'Cyclic dependencies exist among these items: {}'
.format(', '.join(repr(x) for x in data.items()))
) | Dependencies are expressed as a dictionary whose keys are items
and whose values are a set of dependent items. Output is a list of
sets in topological order. The first set consists of items with no
dependences, each subsequent set consists of items that depend upon
items in the preceeding sets. | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/base.py#L30-L69 |
mozilla/crontabber | crontabber/base.py | reorder_dag | def reorder_dag(sequence,
depends_getter=lambda x: x.depends_on,
name_getter=lambda x: x.app_name,
impatience_max=100):
"""
DAG = Directed Acyclic Graph
If we have something like:
C depends on B
B depends on A
A doesn't depend on any
Given the order of [C, B, A] expect it to return [A, B, C]
parameters:
:sequence: some sort of iterable list
:depends_getter: a callable that extracts the depends on sub-list
:name_getter: a callable that extracts the name
:impatience_max: a max count that is reached before we end up in
an infinite loop.
"""
jobs = collections.defaultdict(list)
map_ = {}
_count_roots = 0
for each in sequence:
name = name_getter(each)
depends_on = depends_getter(each)
if depends_on is None:
depends_on = []
elif isinstance(depends_on, tuple):
depends_on = list(depends_on)
elif not isinstance(depends_on, list):
depends_on = [depends_on]
if not depends_on:
_count_roots += 1
jobs[name] += depends_on
map_[name] = each
if not _count_roots:
raise CircularDAGError("No job is at the root")
try:
jobs = dict(zip(jobs.keys(), map(set, jobs.values())))
ordered_jobs = list(toposort_flatten(jobs))
except ValueError, e:
raise CircularDAGError(e)
return [map_[x] for x in ordered_jobs if x in map_] | python | def reorder_dag(sequence,
depends_getter=lambda x: x.depends_on,
name_getter=lambda x: x.app_name,
impatience_max=100):
"""
DAG = Directed Acyclic Graph
If we have something like:
C depends on B
B depends on A
A doesn't depend on any
Given the order of [C, B, A] expect it to return [A, B, C]
parameters:
:sequence: some sort of iterable list
:depends_getter: a callable that extracts the depends on sub-list
:name_getter: a callable that extracts the name
:impatience_max: a max count that is reached before we end up in
an infinite loop.
"""
jobs = collections.defaultdict(list)
map_ = {}
_count_roots = 0
for each in sequence:
name = name_getter(each)
depends_on = depends_getter(each)
if depends_on is None:
depends_on = []
elif isinstance(depends_on, tuple):
depends_on = list(depends_on)
elif not isinstance(depends_on, list):
depends_on = [depends_on]
if not depends_on:
_count_roots += 1
jobs[name] += depends_on
map_[name] = each
if not _count_roots:
raise CircularDAGError("No job is at the root")
try:
jobs = dict(zip(jobs.keys(), map(set, jobs.values())))
ordered_jobs = list(toposort_flatten(jobs))
except ValueError, e:
raise CircularDAGError(e)
return [map_[x] for x in ordered_jobs if x in map_] | DAG = Directed Acyclic Graph
If we have something like:
C depends on B
B depends on A
A doesn't depend on any
Given the order of [C, B, A] expect it to return [A, B, C]
parameters:
:sequence: some sort of iterable list
:depends_getter: a callable that extracts the depends on sub-list
:name_getter: a callable that extracts the name
:impatience_max: a max count that is reached before we end up in
an infinite loop. | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/base.py#L84-L135 |
mozilla/crontabber | crontabber/base.py | convert_frequency | def convert_frequency(frequency):
"""return the number of seconds that a certain frequency string represents.
For example: `1d` means 1 day which means 60 * 60 * 24 seconds.
The recognized formats are:
10d : 10 days
3m : 3 minutes
12h : 12 hours
"""
number = int(re.findall('\d+', frequency)[0])
unit = re.findall('[^\d]+', frequency)[0]
if unit == 'h':
number *= 60 * 60
elif unit == 'm':
number *= 60
elif unit == 'd':
number *= 60 * 60 * 24
elif unit:
raise FrequencyDefinitionError(unit)
return number | python | def convert_frequency(frequency):
"""return the number of seconds that a certain frequency string represents.
For example: `1d` means 1 day which means 60 * 60 * 24 seconds.
The recognized formats are:
10d : 10 days
3m : 3 minutes
12h : 12 hours
"""
number = int(re.findall('\d+', frequency)[0])
unit = re.findall('[^\d]+', frequency)[0]
if unit == 'h':
number *= 60 * 60
elif unit == 'm':
number *= 60
elif unit == 'd':
number *= 60 * 60 * 24
elif unit:
raise FrequencyDefinitionError(unit)
return number | return the number of seconds that a certain frequency string represents.
For example: `1d` means 1 day which means 60 * 60 * 24 seconds.
The recognized formats are:
10d : 10 days
3m : 3 minutes
12h : 12 hours | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/base.py#L139-L157 |
mozilla/crontabber | crontabber/datetimeutil.py | timesince | def timesince(d, now):
"""
Taken from django.utils.timesince and modified to simpler requirements.
Takes two datetime objects and returns the time between d and now
as a nicely formatted string, e.g. "10 minutes". If d occurs after now,
then "0 minutes" is returned.
Units used are years, months, weeks, days, hours, and minutes.
Seconds and microseconds are ignored. Up to two adjacent units will be
displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are
possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.
Adapted from
http://web.archive.org/web/20060617175230/\
http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
"""
def pluralize(a, b):
def inner(n):
if n == 1:
return a % n
return b % n
return inner
def ugettext(s):
return s
chunks = (
(60 * 60 * 24 * 365, pluralize('%d year', '%d years')),
(60 * 60 * 24 * 30, pluralize('%d month', '%d months')),
(60 * 60 * 24 * 7, pluralize('%d week', '%d weeks')),
(60 * 60 * 24, pluralize('%d day', '%d days')),
(60 * 60, pluralize('%d hour', '%d hours')),
(60, pluralize('%d minute', '%d minutes')),
(0, pluralize('%d second', '%d seconds'))
)
# Convert datetime.date to datetime.datetime for comparison.
if not isinstance(d, datetime.datetime):
d = datetime.datetime(d.year, d.month, d.day)
if now and not isinstance(now, datetime.datetime):
now = datetime.datetime(now.year, now.month, now.day)
delta = now - d
# ignore microseconds
since = delta.days * 24 * 60 * 60 + delta.seconds
if since <= 0:
# d is in the future compared to now, stop processing.
# We'll use the last chunk (highest granularity)
_, name = chunks[-1]
return name(0)
for i, (seconds, name) in enumerate(chunks):
if seconds > 0:
count = since // seconds
if count != 0:
break
else:
count = since
result = name(count)
if i + 1 < len(chunks):
# Now get the second item
seconds2, name2 = chunks[i + 1]
if seconds2 > 0:
count2 = (since - (seconds * count)) // seconds2
else:
count2 = since - (seconds * count)
if count2 != 0:
result += ugettext(', ') + name2(count2)
return result | python | def timesince(d, now):
"""
Taken from django.utils.timesince and modified to simpler requirements.
Takes two datetime objects and returns the time between d and now
as a nicely formatted string, e.g. "10 minutes". If d occurs after now,
then "0 minutes" is returned.
Units used are years, months, weeks, days, hours, and minutes.
Seconds and microseconds are ignored. Up to two adjacent units will be
displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are
possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.
Adapted from
http://web.archive.org/web/20060617175230/\
http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
"""
def pluralize(a, b):
def inner(n):
if n == 1:
return a % n
return b % n
return inner
def ugettext(s):
return s
chunks = (
(60 * 60 * 24 * 365, pluralize('%d year', '%d years')),
(60 * 60 * 24 * 30, pluralize('%d month', '%d months')),
(60 * 60 * 24 * 7, pluralize('%d week', '%d weeks')),
(60 * 60 * 24, pluralize('%d day', '%d days')),
(60 * 60, pluralize('%d hour', '%d hours')),
(60, pluralize('%d minute', '%d minutes')),
(0, pluralize('%d second', '%d seconds'))
)
# Convert datetime.date to datetime.datetime for comparison.
if not isinstance(d, datetime.datetime):
d = datetime.datetime(d.year, d.month, d.day)
if now and not isinstance(now, datetime.datetime):
now = datetime.datetime(now.year, now.month, now.day)
delta = now - d
# ignore microseconds
since = delta.days * 24 * 60 * 60 + delta.seconds
if since <= 0:
# d is in the future compared to now, stop processing.
# We'll use the last chunk (highest granularity)
_, name = chunks[-1]
return name(0)
for i, (seconds, name) in enumerate(chunks):
if seconds > 0:
count = since // seconds
if count != 0:
break
else:
count = since
result = name(count)
if i + 1 < len(chunks):
# Now get the second item
seconds2, name2 = chunks[i + 1]
if seconds2 > 0:
count2 = (since - (seconds * count)) // seconds2
else:
count2 = since - (seconds * count)
if count2 != 0:
result += ugettext(', ') + name2(count2)
return result | Taken from django.utils.timesince and modified to simpler requirements.
Takes two datetime objects and returns the time between d and now
as a nicely formatted string, e.g. "10 minutes". If d occurs after now,
then "0 minutes" is returned.
Units used are years, months, weeks, days, hours, and minutes.
Seconds and microseconds are ignored. Up to two adjacent units will be
displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are
possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.
Adapted from
http://web.archive.org/web/20060617175230/\
http://blog.natbat.co.uk/archive/2003/Jun/14/time_since | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/datetimeutil.py#L48-L117 |
mozilla/crontabber | crontabber/connection_factory.py | ConnectionFactory.connection | def connection(self, name=None):
"""return a named connection.
This function will return a named connection by either finding one
in its pool by the name or creating a new one. If no name is given,
it will use the name of the current executing thread as the name of
the connection.
parameters:
name - a name as a string
"""
if not name:
name = self._get_default_connection_name()
if name in self.pool:
return self.pool[name]
self.pool[name] = psycopg2.connect(self.dsn)
return self.pool[name] | python | def connection(self, name=None):
"""return a named connection.
This function will return a named connection by either finding one
in its pool by the name or creating a new one. If no name is given,
it will use the name of the current executing thread as the name of
the connection.
parameters:
name - a name as a string
"""
if not name:
name = self._get_default_connection_name()
if name in self.pool:
return self.pool[name]
self.pool[name] = psycopg2.connect(self.dsn)
return self.pool[name] | return a named connection.
This function will return a named connection by either finding one
in its pool by the name or creating a new one. If no name is given,
it will use the name of the current executing thread as the name of
the connection.
parameters:
name - a name as a string | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/connection_factory.py#L94-L110 |
mozilla/crontabber | crontabber/connection_factory.py | ConnectionFactory.close_connection | def close_connection(self, connection, force=False):
"""overriding the baseclass function, this routine will decline to
close a connection at the end of a transaction context. This allows
for reuse of connections."""
if force:
try:
connection.close()
except self.operational_exceptions:
self.config.logger.error('ConnectionFactory - failed closing')
for name, conn in self.pool.iteritems():
if conn is connection:
break
del self.pool[name]
else:
pass | python | def close_connection(self, connection, force=False):
"""overriding the baseclass function, this routine will decline to
close a connection at the end of a transaction context. This allows
for reuse of connections."""
if force:
try:
connection.close()
except self.operational_exceptions:
self.config.logger.error('ConnectionFactory - failed closing')
for name, conn in self.pool.iteritems():
if conn is connection:
break
del self.pool[name]
else:
pass | overriding the baseclass function, this routine will decline to
close a connection at the end of a transaction context. This allows
for reuse of connections. | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/connection_factory.py#L129-L143 |
mozilla/crontabber | crontabber/generic_app.py | respond_to_SIGHUP | def respond_to_SIGHUP(signal_number, frame, logger=None):
"""raise the KeyboardInterrupt which will cause the app to effectively
shutdown, closing all it resources. Then, because it sets 'restart' to
True, the app will reread all the configuration information, rebuild all
of its structures and resources and start running again"""
global restart
restart = True
if logger:
logger.info('detected SIGHUP')
raise KeyboardInterrupt | python | def respond_to_SIGHUP(signal_number, frame, logger=None):
"""raise the KeyboardInterrupt which will cause the app to effectively
shutdown, closing all it resources. Then, because it sets 'restart' to
True, the app will reread all the configuration information, rebuild all
of its structures and resources and start running again"""
global restart
restart = True
if logger:
logger.info('detected SIGHUP')
raise KeyboardInterrupt | raise the KeyboardInterrupt which will cause the app to effectively
shutdown, closing all it resources. Then, because it sets 'restart' to
True, the app will reread all the configuration information, rebuild all
of its structures and resources and start running again | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/generic_app.py#L195-L204 |
mozilla/crontabber | crontabber/transaction_executor.py | TransactionExecutorWithInfiniteBackoff.backoff_generator | def backoff_generator(self):
"""Generate a series of integers used for the length of the sleep
between retries. It produces after exhausting the list, it repeats
the last value from the list forever. This generator will never raise
the StopIteration exception."""
for x in self.config.backoff_delays:
yield x
while True:
yield self.config.backoff_delays[-1] | python | def backoff_generator(self):
"""Generate a series of integers used for the length of the sleep
between retries. It produces after exhausting the list, it repeats
the last value from the list forever. This generator will never raise
the StopIteration exception."""
for x in self.config.backoff_delays:
yield x
while True:
yield self.config.backoff_delays[-1] | Generate a series of integers used for the length of the sleep
between retries. It produces after exhausting the list, it repeats
the last value from the list forever. This generator will never raise
the StopIteration exception. | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/transaction_executor.py#L76-L84 |
mozilla/crontabber | crontabber/transaction_executor.py | TransactionExecutorWithInfiniteBackoff.responsive_sleep | def responsive_sleep(self, seconds, wait_reason=''):
"""Sleep for the specified number of seconds, logging every
'wait_log_interval' seconds with progress info."""
for x in xrange(int(seconds)):
if (self.config.wait_log_interval and
not x % self.config.wait_log_interval):
self.config.logger.debug(
'%s: %dsec of %dsec' % (wait_reason, x, seconds)
)
self.quit_check()
time.sleep(1.0) | python | def responsive_sleep(self, seconds, wait_reason=''):
"""Sleep for the specified number of seconds, logging every
'wait_log_interval' seconds with progress info."""
for x in xrange(int(seconds)):
if (self.config.wait_log_interval and
not x % self.config.wait_log_interval):
self.config.logger.debug(
'%s: %dsec of %dsec' % (wait_reason, x, seconds)
)
self.quit_check()
time.sleep(1.0) | Sleep for the specified number of seconds, logging every
'wait_log_interval' seconds with progress info. | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/transaction_executor.py#L87-L97 |
mozilla/crontabber | crontabber/mixins.py | as_backfill_cron_app | def as_backfill_cron_app(cls):
"""a class decorator for Crontabber Apps. This decorator embues a CronApp
with the parts necessary to be a backfill CronApp. It adds a main method
that forces the base class to use a value of False for 'once'. That means
it will do the work of a backfilling app.
"""
#----------------------------------------------------------------------
def main(self, function=None):
return super(cls, self).main(
function=function,
once=False,
)
cls.main = main
cls._is_backfill_app = True
return cls | python | def as_backfill_cron_app(cls):
"""a class decorator for Crontabber Apps. This decorator embues a CronApp
with the parts necessary to be a backfill CronApp. It adds a main method
that forces the base class to use a value of False for 'once'. That means
it will do the work of a backfilling app.
"""
#----------------------------------------------------------------------
def main(self, function=None):
return super(cls, self).main(
function=function,
once=False,
)
cls.main = main
cls._is_backfill_app = True
return cls | a class decorator for Crontabber Apps. This decorator embues a CronApp
with the parts necessary to be a backfill CronApp. It adds a main method
that forces the base class to use a value of False for 'once'. That means
it will do the work of a backfilling app. | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/mixins.py#L14-L28 |
mozilla/crontabber | crontabber/mixins.py | with_transactional_resource | def with_transactional_resource(
transactional_resource_class,
resource_name,
reference_value_from=None
):
"""a class decorator for Crontabber Apps. This decorator will give access
to a resource connection source. Configuration will be automatically set
up and the cron app can expect to have attributes:
self.{resource_name}_connection_factory
self.{resource_name}_transaction_executor
available to use.
Within the setup, the RequiredConfig structure gets set up like this:
config.{resource_name}.{resource_name}_class = \
transactional_resource_class
config.{resource_name}.{resource_name}_transaction_executor_class = \
'crontabber.transaction_executor.TransactionExecutor'
parameters:
transactional_resource_class - a string representing the full path of
the class that represents a connection to the resource. An example
is "crontabber.connection_factory.ConnectionFactory".
resource_name - a string that will serve as an identifier for this
resource within the mixin. For example, if the resource is
'database' we'll see configman namespace in the cron job section
of "...class-SomeCronJob.database.database_connection_class" and
"...class-SomeCronJob.database.transaction_executor_class"
"""
def class_decorator(cls):
if not issubclass(cls, RequiredConfig):
raise Exception(
'%s must have RequiredConfig as a base class' % cls
)
new_req = cls.get_required_config()
new_req.namespace(resource_name)
new_req[resource_name].add_option(
'%s_class' % resource_name,
default=transactional_resource_class,
from_string_converter=class_converter,
reference_value_from=reference_value_from,
)
new_req[resource_name].add_option(
'%s_transaction_executor_class' % resource_name,
default='crontabber.transaction_executor.TransactionExecutor',
doc='a class that will execute transactions',
from_string_converter=class_converter,
reference_value_from=reference_value_from
)
cls.required_config = new_req
#------------------------------------------------------------------
def new__init__(self, *args, **kwargs):
# instantiate the connection class for the resource
super(cls, self).__init__(*args, **kwargs)
setattr(
self,
"%s_connection_factory" % resource_name,
self.config[resource_name]['%s_class' % resource_name](
self.config[resource_name]
)
)
# instantiate a transaction executor bound to the
# resource connection
setattr(
self,
"%s_transaction_executor" % resource_name,
self.config[resource_name][
'%s_transaction_executor_class' % resource_name
](
self.config[resource_name],
getattr(self, "%s_connection_factory" % resource_name)
)
)
if hasattr(cls, '__init__'):
original_init = cls.__init__
def both_inits(self, *args, **kwargs):
new__init__(self, *args, **kwargs)
return original_init(self, *args, **kwargs)
cls.__init__ = both_inits
else:
cls.__init__ = new__init__
return cls
return class_decorator | python | def with_transactional_resource(
transactional_resource_class,
resource_name,
reference_value_from=None
):
"""a class decorator for Crontabber Apps. This decorator will give access
to a resource connection source. Configuration will be automatically set
up and the cron app can expect to have attributes:
self.{resource_name}_connection_factory
self.{resource_name}_transaction_executor
available to use.
Within the setup, the RequiredConfig structure gets set up like this:
config.{resource_name}.{resource_name}_class = \
transactional_resource_class
config.{resource_name}.{resource_name}_transaction_executor_class = \
'crontabber.transaction_executor.TransactionExecutor'
parameters:
transactional_resource_class - a string representing the full path of
the class that represents a connection to the resource. An example
is "crontabber.connection_factory.ConnectionFactory".
resource_name - a string that will serve as an identifier for this
resource within the mixin. For example, if the resource is
'database' we'll see configman namespace in the cron job section
of "...class-SomeCronJob.database.database_connection_class" and
"...class-SomeCronJob.database.transaction_executor_class"
"""
def class_decorator(cls):
if not issubclass(cls, RequiredConfig):
raise Exception(
'%s must have RequiredConfig as a base class' % cls
)
new_req = cls.get_required_config()
new_req.namespace(resource_name)
new_req[resource_name].add_option(
'%s_class' % resource_name,
default=transactional_resource_class,
from_string_converter=class_converter,
reference_value_from=reference_value_from,
)
new_req[resource_name].add_option(
'%s_transaction_executor_class' % resource_name,
default='crontabber.transaction_executor.TransactionExecutor',
doc='a class that will execute transactions',
from_string_converter=class_converter,
reference_value_from=reference_value_from
)
cls.required_config = new_req
#------------------------------------------------------------------
def new__init__(self, *args, **kwargs):
# instantiate the connection class for the resource
super(cls, self).__init__(*args, **kwargs)
setattr(
self,
"%s_connection_factory" % resource_name,
self.config[resource_name]['%s_class' % resource_name](
self.config[resource_name]
)
)
# instantiate a transaction executor bound to the
# resource connection
setattr(
self,
"%s_transaction_executor" % resource_name,
self.config[resource_name][
'%s_transaction_executor_class' % resource_name
](
self.config[resource_name],
getattr(self, "%s_connection_factory" % resource_name)
)
)
if hasattr(cls, '__init__'):
original_init = cls.__init__
def both_inits(self, *args, **kwargs):
new__init__(self, *args, **kwargs)
return original_init(self, *args, **kwargs)
cls.__init__ = both_inits
else:
cls.__init__ = new__init__
return cls
return class_decorator | a class decorator for Crontabber Apps. This decorator will give access
to a resource connection source. Configuration will be automatically set
up and the cron app can expect to have attributes:
self.{resource_name}_connection_factory
self.{resource_name}_transaction_executor
available to use.
Within the setup, the RequiredConfig structure gets set up like this:
config.{resource_name}.{resource_name}_class = \
transactional_resource_class
config.{resource_name}.{resource_name}_transaction_executor_class = \
'crontabber.transaction_executor.TransactionExecutor'
parameters:
transactional_resource_class - a string representing the full path of
the class that represents a connection to the resource. An example
is "crontabber.connection_factory.ConnectionFactory".
resource_name - a string that will serve as an identifier for this
resource within the mixin. For example, if the resource is
'database' we'll see configman namespace in the cron job section
of "...class-SomeCronJob.database.database_connection_class" and
"...class-SomeCronJob.database.transaction_executor_class" | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/mixins.py#L32-L114 |
mozilla/crontabber | crontabber/mixins.py | with_resource_connection_as_argument | def with_resource_connection_as_argument(resource_name):
"""a class decorator for Crontabber Apps. This decorator will a class a
_run_proxy method that passes a databsase connection as a context manager
into the CronApp's run method. The connection will automatically be closed
when the ConApp's run method ends.
In order for this dectorator to function properly, it must be used in
conjunction with previous dectorator, "with_transactional_resource" or
equivalent. This decorator depends on the mechanims added by that
decorator.
"""
connection_factory_attr_name = '%s_connection_factory' % resource_name
def class_decorator(cls):
def _run_proxy(self, *args, **kwargs):
factory = getattr(self, connection_factory_attr_name)
with factory() as connection:
try:
self.run(connection, *args, **kwargs)
finally:
factory.close_connection(connection, force=True)
cls._run_proxy = _run_proxy
return cls
return class_decorator | python | def with_resource_connection_as_argument(resource_name):
"""a class decorator for Crontabber Apps. This decorator will a class a
_run_proxy method that passes a databsase connection as a context manager
into the CronApp's run method. The connection will automatically be closed
when the ConApp's run method ends.
In order for this dectorator to function properly, it must be used in
conjunction with previous dectorator, "with_transactional_resource" or
equivalent. This decorator depends on the mechanims added by that
decorator.
"""
connection_factory_attr_name = '%s_connection_factory' % resource_name
def class_decorator(cls):
def _run_proxy(self, *args, **kwargs):
factory = getattr(self, connection_factory_attr_name)
with factory() as connection:
try:
self.run(connection, *args, **kwargs)
finally:
factory.close_connection(connection, force=True)
cls._run_proxy = _run_proxy
return cls
return class_decorator | a class decorator for Crontabber Apps. This decorator will a class a
_run_proxy method that passes a databsase connection as a context manager
into the CronApp's run method. The connection will automatically be closed
when the ConApp's run method ends.
In order for this dectorator to function properly, it must be used in
conjunction with previous dectorator, "with_transactional_resource" or
equivalent. This decorator depends on the mechanims added by that
decorator. | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/mixins.py#L118-L141 |
mozilla/crontabber | crontabber/mixins.py | with_single_transaction | def with_single_transaction(resource_name):
"""a class decorator for Crontabber Apps. This decorator will give a class
a _run_proxy method that passes a databsase connection as a context manager
into the CronApp's 'run' method. The run method may then use the
connection at will knowing that after if 'run' exits normally, the
connection will automatically be commited. Any abnormal exit from 'run'
will result in the connnection being rolledback.
In order for this dectorator to function properly, it must be used in
conjunction with previous dectorator, "with_transactional_resource" or
equivalent. This decorator depends on the mechanims added by that
decorator.
"""
transaction_executor_attr_name = "%s_transaction_executor" % resource_name
def class_decorator(cls):
def _run_proxy(self, *args, **kwargs):
getattr(self, transaction_executor_attr_name)(
self.run,
*args,
**kwargs
)
cls._run_proxy = _run_proxy
return cls
return class_decorator | python | def with_single_transaction(resource_name):
"""a class decorator for Crontabber Apps. This decorator will give a class
a _run_proxy method that passes a databsase connection as a context manager
into the CronApp's 'run' method. The run method may then use the
connection at will knowing that after if 'run' exits normally, the
connection will automatically be commited. Any abnormal exit from 'run'
will result in the connnection being rolledback.
In order for this dectorator to function properly, it must be used in
conjunction with previous dectorator, "with_transactional_resource" or
equivalent. This decorator depends on the mechanims added by that
decorator.
"""
transaction_executor_attr_name = "%s_transaction_executor" % resource_name
def class_decorator(cls):
def _run_proxy(self, *args, **kwargs):
getattr(self, transaction_executor_attr_name)(
self.run,
*args,
**kwargs
)
cls._run_proxy = _run_proxy
return cls
return class_decorator | a class decorator for Crontabber Apps. This decorator will give a class
a _run_proxy method that passes a databsase connection as a context manager
into the CronApp's 'run' method. The run method may then use the
connection at will knowing that after if 'run' exits normally, the
connection will automatically be commited. Any abnormal exit from 'run'
will result in the connnection being rolledback.
In order for this dectorator to function properly, it must be used in
conjunction with previous dectorator, "with_transactional_resource" or
equivalent. This decorator depends on the mechanims added by that
decorator. | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/mixins.py#L145-L169 |
mozilla/crontabber | crontabber/mixins.py | with_subprocess | def with_subprocess(cls):
"""a class decorator for Crontabber Apps. This decorator gives the CronApp
a _run_proxy method that will execute the cron app as a single PG
transaction. Commit and Rollback are automatic. The cron app should do
no transaction management of its own. The cron app should be short so that
the transaction is not held open too long.
"""
def run_process(self, command, input=None):
"""
Run the command and return a tuple of three things.
1. exit code - an integer number
2. stdout - all output that was sent to stdout
2. stderr - all output that was sent to stderr
"""
if isinstance(command, (tuple, list)):
command = ' '.join('"%s"' % x for x in command)
proc = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = proc.communicate(input=input)
return proc.returncode, out.strip(), err.strip()
cls.run_process = run_process
return cls | python | def with_subprocess(cls):
"""a class decorator for Crontabber Apps. This decorator gives the CronApp
a _run_proxy method that will execute the cron app as a single PG
transaction. Commit and Rollback are automatic. The cron app should do
no transaction management of its own. The cron app should be short so that
the transaction is not held open too long.
"""
def run_process(self, command, input=None):
"""
Run the command and return a tuple of three things.
1. exit code - an integer number
2. stdout - all output that was sent to stdout
2. stderr - all output that was sent to stderr
"""
if isinstance(command, (tuple, list)):
command = ' '.join('"%s"' % x for x in command)
proc = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = proc.communicate(input=input)
return proc.returncode, out.strip(), err.strip()
cls.run_process = run_process
return cls | a class decorator for Crontabber Apps. This decorator gives the CronApp
a _run_proxy method that will execute the cron app as a single PG
transaction. Commit and Rollback are automatic. The cron app should do
no transaction management of its own. The cron app should be short so that
the transaction is not held open too long. | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/mixins.py#L173-L201 |
mozilla/crontabber | crontabber/app.py | classes_in_namespaces_converter_with_compression | def classes_in_namespaces_converter_with_compression(
reference_namespace={},
template_for_namespace="class-%(name)s",
list_splitter_fn=_default_list_splitter,
class_extractor=_default_class_extractor,
extra_extractor=_default_extra_extractor):
"""
parameters:
template_for_namespace - a template for the names of the namespaces
that will contain the classes and their
associated required config options. There are
two template variables available: %(name)s -
the name of the class to be contained in the
namespace; %(index)d - the sequential index
number of the namespace.
list_converter - a function that will take the string list of classes
and break it up into a sequence if individual elements
class_extractor - a function that will return the string version of
a classname from the result of the list_converter
extra_extractor - a function that will return a Namespace of options
created from any extra information associated with
the classes returned by the list_converter function
"""
# -------------------------------------------------------------------------
def class_list_converter(class_list_str):
"""This function becomes the actual converter used by configman to
take a string and convert it into the nested sequence of Namespaces,
one for each class in the list. It does this by creating a proxy
class stuffed with its own 'required_config' that's dynamically
generated."""
if isinstance(class_list_str, basestring):
class_str_list = list_splitter_fn(class_list_str)
else:
raise TypeError('must be derivative of a basestring')
# =====================================================================
class InnerClassList(RequiredConfig):
"""This nested class is a proxy list for the classes. It collects
all the config requirements for the listed classes and places them
each into their own Namespace.
"""
# we're dynamically creating a class here. The following block of
# code is actually adding class level attributes to this new class
# 1st requirement for configman
required_config = Namespace()
# to help the programmer know what Namespaces we added
subordinate_namespace_names = []
# save the template for future reference
namespace_template = template_for_namespace
# for display
original_input = class_list_str.replace('\n', '\\n')
# for each class in the class list
class_list = []
for namespace_index, class_list_element in enumerate(
class_str_list
):
try:
a_class = class_converter(
class_extractor(class_list_element)
)
except CannotConvertError:
raise JobNotFoundError(class_list_element)
class_list.append((a_class.__name__, a_class))
# figure out the Namespace name
namespace_name_dict = {
'name': a_class.__name__,
'index': namespace_index
}
namespace_name = template_for_namespace % namespace_name_dict
subordinate_namespace_names.append(namespace_name)
# create the new Namespace
required_config.namespace(namespace_name)
a_class_namespace = required_config[namespace_name]
# add options for the 'extra data'
try:
extra_options = extra_extractor(class_list_element)
a_class_namespace.update(extra_options)
except NotImplementedError:
pass
# add options frr the classes required config
try:
for k, v in a_class.get_required_config().iteritems():
if k not in reference_namespace:
a_class_namespace[k] = v
except AttributeError: # a_class has no get_required_config
pass
@classmethod
def to_str(cls):
"""this method takes this inner class object and turns it back
into the original string of classnames. This is used
primarily as for the output of the 'help' option"""
return cls.original_input
return InnerClassList # result of class_list_converter
return class_list_converter | python | def classes_in_namespaces_converter_with_compression(
reference_namespace={},
template_for_namespace="class-%(name)s",
list_splitter_fn=_default_list_splitter,
class_extractor=_default_class_extractor,
extra_extractor=_default_extra_extractor):
"""
parameters:
template_for_namespace - a template for the names of the namespaces
that will contain the classes and their
associated required config options. There are
two template variables available: %(name)s -
the name of the class to be contained in the
namespace; %(index)d - the sequential index
number of the namespace.
list_converter - a function that will take the string list of classes
and break it up into a sequence if individual elements
class_extractor - a function that will return the string version of
a classname from the result of the list_converter
extra_extractor - a function that will return a Namespace of options
created from any extra information associated with
the classes returned by the list_converter function
"""
# -------------------------------------------------------------------------
def class_list_converter(class_list_str):
"""This function becomes the actual converter used by configman to
take a string and convert it into the nested sequence of Namespaces,
one for each class in the list. It does this by creating a proxy
class stuffed with its own 'required_config' that's dynamically
generated."""
if isinstance(class_list_str, basestring):
class_str_list = list_splitter_fn(class_list_str)
else:
raise TypeError('must be derivative of a basestring')
# =====================================================================
class InnerClassList(RequiredConfig):
"""This nested class is a proxy list for the classes. It collects
all the config requirements for the listed classes and places them
each into their own Namespace.
"""
# we're dynamically creating a class here. The following block of
# code is actually adding class level attributes to this new class
# 1st requirement for configman
required_config = Namespace()
# to help the programmer know what Namespaces we added
subordinate_namespace_names = []
# save the template for future reference
namespace_template = template_for_namespace
# for display
original_input = class_list_str.replace('\n', '\\n')
# for each class in the class list
class_list = []
for namespace_index, class_list_element in enumerate(
class_str_list
):
try:
a_class = class_converter(
class_extractor(class_list_element)
)
except CannotConvertError:
raise JobNotFoundError(class_list_element)
class_list.append((a_class.__name__, a_class))
# figure out the Namespace name
namespace_name_dict = {
'name': a_class.__name__,
'index': namespace_index
}
namespace_name = template_for_namespace % namespace_name_dict
subordinate_namespace_names.append(namespace_name)
# create the new Namespace
required_config.namespace(namespace_name)
a_class_namespace = required_config[namespace_name]
# add options for the 'extra data'
try:
extra_options = extra_extractor(class_list_element)
a_class_namespace.update(extra_options)
except NotImplementedError:
pass
# add options frr the classes required config
try:
for k, v in a_class.get_required_config().iteritems():
if k not in reference_namespace:
a_class_namespace[k] = v
except AttributeError: # a_class has no get_required_config
pass
@classmethod
def to_str(cls):
"""this method takes this inner class object and turns it back
into the original string of classnames. This is used
primarily as for the output of the 'help' option"""
return cls.original_input
return InnerClassList # result of class_list_converter
return class_list_converter | parameters:
template_for_namespace - a template for the names of the namespaces
that will contain the classes and their
associated required config options. There are
two template variables available: %(name)s -
the name of the class to be contained in the
namespace; %(index)d - the sequential index
number of the namespace.
list_converter - a function that will take the string list of classes
and break it up into a sequence if individual elements
class_extractor - a function that will return the string version of
a classname from the result of the list_converter
extra_extractor - a function that will return a Namespace of options
created from any extra information associated with
the classes returned by the list_converter function | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L503-L605 |
mozilla/crontabber | crontabber/app.py | check_time | def check_time(value):
"""check that it's a value like 03:45 or 1:1"""
try:
h, m = value.split(':')
h = int(h)
m = int(m)
if h >= 24 or h < 0:
raise ValueError
if m >= 60 or m < 0:
raise ValueError
except ValueError:
raise TimeDefinitionError("Invalid definition of time %r" % value) | python | def check_time(value):
"""check that it's a value like 03:45 or 1:1"""
try:
h, m = value.split(':')
h = int(h)
m = int(m)
if h >= 24 or h < 0:
raise ValueError
if m >= 60 or m < 0:
raise ValueError
except ValueError:
raise TimeDefinitionError("Invalid definition of time %r" % value) | check that it's a value like 03:45 or 1:1 | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L640-L651 |
mozilla/crontabber | crontabber/app.py | JobStateDatabase.keys | def keys(self):
"""return a list of all app_names"""
keys = []
for app_name, __ in self.items():
keys.append(app_name)
return keys | python | def keys(self):
"""return a list of all app_names"""
keys = []
for app_name, __ in self.items():
keys.append(app_name)
return keys | return a list of all app_names | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L257-L262 |
mozilla/crontabber | crontabber/app.py | JobStateDatabase.items | def items(self):
"""return all the app_names and their values as tuples"""
sql = """
SELECT
app_name,
next_run,
first_run,
last_run,
last_success,
depends_on,
error_count,
last_error
FROM crontabber"""
columns = (
'app_name',
'next_run', 'first_run', 'last_run', 'last_success',
'depends_on', 'error_count', 'last_error'
)
items = []
for record in self.transaction_executor(execute_query_fetchall, sql):
row = dict(zip(columns, record))
items.append((row.pop('app_name'), row))
return items | python | def items(self):
"""return all the app_names and their values as tuples"""
sql = """
SELECT
app_name,
next_run,
first_run,
last_run,
last_success,
depends_on,
error_count,
last_error
FROM crontabber"""
columns = (
'app_name',
'next_run', 'first_run', 'last_run', 'last_success',
'depends_on', 'error_count', 'last_error'
)
items = []
for record in self.transaction_executor(execute_query_fetchall, sql):
row = dict(zip(columns, record))
items.append((row.pop('app_name'), row))
return items | return all the app_names and their values as tuples | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L264-L286 |
mozilla/crontabber | crontabber/app.py | JobStateDatabase.values | def values(self):
"""return a list of all state values"""
values = []
for __, data in self.items():
values.append(data)
return values | python | def values(self):
"""return a list of all state values"""
values = []
for __, data in self.items():
values.append(data)
return values | return a list of all state values | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L288-L293 |
mozilla/crontabber | crontabber/app.py | JobStateDatabase.pop | def pop(self, key, default=_marker):
"""remove the item by key
If not default is specified, raise KeyError if nothing
could be removed.
Return 'default' if specified and nothing could be removed
"""
try:
popped = self[key]
del self[key]
return popped
except KeyError:
if default == _marker:
raise
return default | python | def pop(self, key, default=_marker):
"""remove the item by key
If not default is specified, raise KeyError if nothing
could be removed.
Return 'default' if specified and nothing could be removed
"""
try:
popped = self[key]
del self[key]
return popped
except KeyError:
if default == _marker:
raise
return default | remove the item by key
If not default is specified, raise KeyError if nothing
could be removed.
Return 'default' if specified and nothing could be removed | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L451-L464 |
mozilla/crontabber | crontabber/app.py | CronTabberBase.nagios | def nagios(self, stream=sys.stdout):
"""
return 0 (OK) if there are no errors in the state.
return 1 (WARNING) if a backfill app only has 1 error.
return 2 (CRITICAL) if a backfill app has > 1 error.
return 2 (CRITICAL) if a non-backfill app has 1 error.
"""
warnings = []
criticals = []
for class_name, job_class in self.config.crontabber.jobs.class_list:
if job_class.app_name in self.job_state_database:
info = self.job_state_database.get(job_class.app_name)
if not info.get('error_count', 0):
continue
error_count = info['error_count']
# trouble!
serialized = (
'%s (%s) | %s | %s' %
(job_class.app_name,
class_name,
info['last_error']['type'],
info['last_error']['value'])
)
if (
error_count == 1 and
hasattr(job_class, "_is_backfill_app")
):
# just a warning for now
warnings.append(serialized)
else:
# anything worse than that is critical
criticals.append(serialized)
if criticals:
stream.write('CRITICAL - ')
stream.write('; '.join(criticals))
stream.write('\n')
return 2
elif warnings:
stream.write('WARNING - ')
stream.write('; '.join(warnings))
stream.write('\n')
return 1
stream.write('OK - All systems nominal')
stream.write('\n')
return 0 | python | def nagios(self, stream=sys.stdout):
"""
return 0 (OK) if there are no errors in the state.
return 1 (WARNING) if a backfill app only has 1 error.
return 2 (CRITICAL) if a backfill app has > 1 error.
return 2 (CRITICAL) if a non-backfill app has 1 error.
"""
warnings = []
criticals = []
for class_name, job_class in self.config.crontabber.jobs.class_list:
if job_class.app_name in self.job_state_database:
info = self.job_state_database.get(job_class.app_name)
if not info.get('error_count', 0):
continue
error_count = info['error_count']
# trouble!
serialized = (
'%s (%s) | %s | %s' %
(job_class.app_name,
class_name,
info['last_error']['type'],
info['last_error']['value'])
)
if (
error_count == 1 and
hasattr(job_class, "_is_backfill_app")
):
# just a warning for now
warnings.append(serialized)
else:
# anything worse than that is critical
criticals.append(serialized)
if criticals:
stream.write('CRITICAL - ')
stream.write('; '.join(criticals))
stream.write('\n')
return 2
elif warnings:
stream.write('WARNING - ')
stream.write('; '.join(warnings))
stream.write('\n')
return 1
stream.write('OK - All systems nominal')
stream.write('\n')
return 0 | return 0 (OK) if there are no errors in the state.
return 1 (WARNING) if a backfill app only has 1 error.
return 2 (CRITICAL) if a backfill app has > 1 error.
return 2 (CRITICAL) if a non-backfill app has 1 error. | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L876-L921 |
mozilla/crontabber | crontabber/app.py | CronTabberBase.reset_job | def reset_job(self, description):
"""remove the job from the state.
if means that next time we run, this job will start over from scratch.
"""
class_list = self.config.crontabber.jobs.class_list
class_list = self._reorder_class_list(class_list)
for class_name, job_class in class_list:
if (
job_class.app_name == description or
description == job_class.__module__ + '.' + job_class.__name__
):
if job_class.app_name in self.job_state_database:
self.config.logger.info('App reset')
self.job_state_database.pop(job_class.app_name)
else:
self.config.logger.warning('App already reset')
return
raise JobNotFoundError(description) | python | def reset_job(self, description):
"""remove the job from the state.
if means that next time we run, this job will start over from scratch.
"""
class_list = self.config.crontabber.jobs.class_list
class_list = self._reorder_class_list(class_list)
for class_name, job_class in class_list:
if (
job_class.app_name == description or
description == job_class.__module__ + '.' + job_class.__name__
):
if job_class.app_name in self.job_state_database:
self.config.logger.info('App reset')
self.job_state_database.pop(job_class.app_name)
else:
self.config.logger.warning('App already reset')
return
raise JobNotFoundError(description) | remove the job from the state.
if means that next time we run, this job will start over from scratch. | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L987-L1004 |
mozilla/crontabber | crontabber/app.py | CronTabberBase.time_to_run | def time_to_run(self, class_, time_):
"""return true if it's time to run the job.
This is true if there is no previous information about its last run
or if the last time it ran and set its next_run to a date that is now
past.
"""
app_name = class_.app_name
try:
info = self.job_state_database[app_name]
except KeyError:
if time_:
h, m = [int(x) for x in time_.split(':')]
# only run if this hour and minute is < now
now = utc_now()
if now.hour > h:
return True
elif now.hour == h and now.minute >= m:
return True
return False
else:
# no past information, run now
return True
next_run = info['next_run']
if not next_run:
# It has never run before.
# If it has an active ongoing status it means two
# independent threads tried to start it. The second one
# (by a tiny time margin) will have a job_class whose
# `ongoing` value has already been set.
# If that's the case, let it through because it will
# commence and break due to RowLevelLockError in the
# state's __setitem__ method.
return bool(info['ongoing'])
if next_run < utc_now():
return True
return False | python | def time_to_run(self, class_, time_):
"""return true if it's time to run the job.
This is true if there is no previous information about its last run
or if the last time it ran and set its next_run to a date that is now
past.
"""
app_name = class_.app_name
try:
info = self.job_state_database[app_name]
except KeyError:
if time_:
h, m = [int(x) for x in time_.split(':')]
# only run if this hour and minute is < now
now = utc_now()
if now.hour > h:
return True
elif now.hour == h and now.minute >= m:
return True
return False
else:
# no past information, run now
return True
next_run = info['next_run']
if not next_run:
# It has never run before.
# If it has an active ongoing status it means two
# independent threads tried to start it. The second one
# (by a tiny time margin) will have a job_class whose
# `ongoing` value has already been set.
# If that's the case, let it through because it will
# commence and break due to RowLevelLockError in the
# state's __setitem__ method.
return bool(info['ongoing'])
if next_run < utc_now():
return True
return False | return true if it's time to run the job.
This is true if there is no previous information about its last run
or if the last time it ran and set its next_run to a date that is now
past. | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L1195-L1232 |
mozilla/crontabber | crontabber/app.py | CronTabberBase.audit_ghosts | def audit_ghosts(self):
"""compare the list of configured jobs with the jobs in the state"""
print_header = True
for app_name in self._get_ghosts():
if print_header:
print_header = False
print (
"Found the following in the state database but not "
"available as a configured job:"
)
print "\t%s" % (app_name,) | python | def audit_ghosts(self):
"""compare the list of configured jobs with the jobs in the state"""
print_header = True
for app_name in self._get_ghosts():
if print_header:
print_header = False
print (
"Found the following in the state database but not "
"available as a configured job:"
)
print "\t%s" % (app_name,) | compare the list of configured jobs with the jobs in the state | https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L1385-L1395 |
transceptor-technology/pyleri | pyleri/grammar.py | Grammar.export_js | def export_js(
self,
js_module_name=JS_MODULE_NAME,
js_template=JS_ES6_IMPORT_EXPORT_TEMPLATE,
js_indent=JS_INDENTATION):
'''Export the grammar to a JavaScript file which can be
used with the js-lrparsing module.
Two templates are available:
Grammar.JS_WINDOW_TEMPLATE
Grammar.JS_ES6_IMPORT_EXPORT_TEMPLATE (default)
'''
language = []
refs = []
classes = {'Grammar'}
indent = 0
cname = self.__class__.__name__ if 'import ' in js_template else None
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_js'):
continue
language.append('{indent}{var} {name} = {value};'.format(
indent=js_indent,
name=name,
var='static' if cname else 'var',
value=elem._export_js(js_indent, indent, classes, cname)))
for name, ref in self._refs.items():
refs.append(
'{pre}{name}.set({value});'
.format(
pre='{}.'.format(cname) if cname else js_indent,
name=name,
value=ref._element._export_js(
js_indent,
-1 if cname else indent,
classes,
cname)))
if 'Rule' in classes:
classes.remove('Rule')
return js_template.format(
name=self.__class__.__name__,
indent=js_indent,
js_module=js_module_name,
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
refs='\n{}'.format('\n'.join(refs)),
arguments=',\n'.join(map(lambda s:
js_indent * 3 + s, classes)),
re_keywords=self.RE_KEYWORDS.pattern.replace('\\', '\\\\'),
classes=', '.join(classes),
constructors=',\n'.join(
map(lambda s: js_indent + s,
['.'.join([
'window',
js_module_name, n]) for n in classes]))) | python | def export_js(
self,
js_module_name=JS_MODULE_NAME,
js_template=JS_ES6_IMPORT_EXPORT_TEMPLATE,
js_indent=JS_INDENTATION):
'''Export the grammar to a JavaScript file which can be
used with the js-lrparsing module.
Two templates are available:
Grammar.JS_WINDOW_TEMPLATE
Grammar.JS_ES6_IMPORT_EXPORT_TEMPLATE (default)
'''
language = []
refs = []
classes = {'Grammar'}
indent = 0
cname = self.__class__.__name__ if 'import ' in js_template else None
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_js'):
continue
language.append('{indent}{var} {name} = {value};'.format(
indent=js_indent,
name=name,
var='static' if cname else 'var',
value=elem._export_js(js_indent, indent, classes, cname)))
for name, ref in self._refs.items():
refs.append(
'{pre}{name}.set({value});'
.format(
pre='{}.'.format(cname) if cname else js_indent,
name=name,
value=ref._element._export_js(
js_indent,
-1 if cname else indent,
classes,
cname)))
if 'Rule' in classes:
classes.remove('Rule')
return js_template.format(
name=self.__class__.__name__,
indent=js_indent,
js_module=js_module_name,
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
refs='\n{}'.format('\n'.join(refs)),
arguments=',\n'.join(map(lambda s:
js_indent * 3 + s, classes)),
re_keywords=self.RE_KEYWORDS.pattern.replace('\\', '\\\\'),
classes=', '.join(classes),
constructors=',\n'.join(
map(lambda s: js_indent + s,
['.'.join([
'window',
js_module_name, n]) for n in classes]))) | Export the grammar to a JavaScript file which can be
used with the js-lrparsing module.
Two templates are available:
Grammar.JS_WINDOW_TEMPLATE
Grammar.JS_ES6_IMPORT_EXPORT_TEMPLATE (default) | https://github.com/transceptor-technology/pyleri/blob/af754300d42a5a79bcdfc7852ee4cc75ce245f39/pyleri/grammar.py#L341-L402 |
transceptor-technology/pyleri | pyleri/grammar.py | Grammar.export_py | def export_py(
self,
py_module_name=PY_MODULE_NAME,
py_template=PY_TEMPLATE,
py_indent=PY_INDENTATION):
'''Export the grammar to a python file which can be
used with the pyleri module. This can be useful when python code
if used to auto-create a grammar and an export of the final result is
required.'''
language = []
classes = {'Grammar'}
indent = 0
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_py'):
continue
language.append('{indent}{name} = {value}'.format(
indent=py_indent,
name=name,
value=elem._export_py(py_indent, indent, classes)))
for name, ref in self._refs.items():
language.append(
'{indent}{name} = {value}'
.format(
indent=py_indent,
name=name,
value=ref._element._export_py(
py_indent,
indent,
classes)))
return py_template.format(
name=self.__class__.__name__,
indent=py_indent,
py_module=py_module_name,
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
re_keywords=self.RE_KEYWORDS.pattern.replace('\\', '\\\\'),
imports='\n'.join(
map(lambda s: s, [
' '.join(['from', py_module_name, 'import', n])
for n in classes if n != 'Rule']))) | python | def export_py(
self,
py_module_name=PY_MODULE_NAME,
py_template=PY_TEMPLATE,
py_indent=PY_INDENTATION):
'''Export the grammar to a python file which can be
used with the pyleri module. This can be useful when python code
if used to auto-create a grammar and an export of the final result is
required.'''
language = []
classes = {'Grammar'}
indent = 0
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_py'):
continue
language.append('{indent}{name} = {value}'.format(
indent=py_indent,
name=name,
value=elem._export_py(py_indent, indent, classes)))
for name, ref in self._refs.items():
language.append(
'{indent}{name} = {value}'
.format(
indent=py_indent,
name=name,
value=ref._element._export_py(
py_indent,
indent,
classes)))
return py_template.format(
name=self.__class__.__name__,
indent=py_indent,
py_module=py_module_name,
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
re_keywords=self.RE_KEYWORDS.pattern.replace('\\', '\\\\'),
imports='\n'.join(
map(lambda s: s, [
' '.join(['from', py_module_name, 'import', n])
for n in classes if n != 'Rule']))) | Export the grammar to a python file which can be
used with the pyleri module. This can be useful when python code
if used to auto-create a grammar and an export of the final result is
required. | https://github.com/transceptor-technology/pyleri/blob/af754300d42a5a79bcdfc7852ee4cc75ce245f39/pyleri/grammar.py#L404-L450 |
transceptor-technology/pyleri | pyleri/grammar.py | Grammar.export_c | def export_c(self, target=C_TARGET, c_indent=C_INDENTATION, headerf=None):
'''Export the grammar to a c (source and header) file which can be
used with the libcleri module.'''
language = []
indent = 0
enums = set()
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_c'):
continue
language.append(
'{indent}cleri_t * {name} = {value};'.format(
indent=c_indent,
name=name,
value=elem._export_c(c_indent, indent, enums)))
for name, ref in self._refs.items():
language.append(
'{indent}cleri_ref_set({name}, {value});'
.format(
indent=c_indent,
name=name,
value=ref._element._export_c(
c_indent,
indent,
enums,
ref)))
pattern = self.RE_KEYWORDS.pattern.replace('\\', '\\\\')
if not pattern.startswith('^'):
pattern = '^' + pattern
enums = ',\n'.join([
'{}{}'.format(c_indent, gid)
for gid in sorted(enums)]) + ','
header_file = '"{}.h"'.format(target) if headerf is None else headerf
fun = target.strip('/').replace('/', '_')
return (self.__class__.C_TEMPLATE_C.format(
name=self.__class__.__name__,
target=target,
header_file=header_file,
fun=fun,
indent=c_indent,
datetime=time.strftime(
'%Y-%m-%d %H:%M:%S',
time.localtime()),
language='\n'.join(language),
re_keywords=pattern),
self.__class__.C_TEMPLATE_H.format(
name=self.__class__.__name__,
target=target,
fun=fun,
guard=target.upper().replace('/', '_').replace('\\', '_'),
datetime=time.strftime(
'%Y-%m-%d %H:%M:%S',
time.localtime()),
language='\n'.join(language),
enums=enums)) | python | def export_c(self, target=C_TARGET, c_indent=C_INDENTATION, headerf=None):
'''Export the grammar to a c (source and header) file which can be
used with the libcleri module.'''
language = []
indent = 0
enums = set()
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_c'):
continue
language.append(
'{indent}cleri_t * {name} = {value};'.format(
indent=c_indent,
name=name,
value=elem._export_c(c_indent, indent, enums)))
for name, ref in self._refs.items():
language.append(
'{indent}cleri_ref_set({name}, {value});'
.format(
indent=c_indent,
name=name,
value=ref._element._export_c(
c_indent,
indent,
enums,
ref)))
pattern = self.RE_KEYWORDS.pattern.replace('\\', '\\\\')
if not pattern.startswith('^'):
pattern = '^' + pattern
enums = ',\n'.join([
'{}{}'.format(c_indent, gid)
for gid in sorted(enums)]) + ','
header_file = '"{}.h"'.format(target) if headerf is None else headerf
fun = target.strip('/').replace('/', '_')
return (self.__class__.C_TEMPLATE_C.format(
name=self.__class__.__name__,
target=target,
header_file=header_file,
fun=fun,
indent=c_indent,
datetime=time.strftime(
'%Y-%m-%d %H:%M:%S',
time.localtime()),
language='\n'.join(language),
re_keywords=pattern),
self.__class__.C_TEMPLATE_H.format(
name=self.__class__.__name__,
target=target,
fun=fun,
guard=target.upper().replace('/', '_').replace('\\', '_'),
datetime=time.strftime(
'%Y-%m-%d %H:%M:%S',
time.localtime()),
language='\n'.join(language),
enums=enums)) | Export the grammar to a c (source and header) file which can be
used with the libcleri module. | https://github.com/transceptor-technology/pyleri/blob/af754300d42a5a79bcdfc7852ee4cc75ce245f39/pyleri/grammar.py#L452-L514 |
transceptor-technology/pyleri | pyleri/grammar.py | Grammar.export_go | def export_go(
self,
go_template=GO_TEMPLATE,
go_indent=GO_INDENTATION,
go_package=GO_PACKAGE):
'''Export the grammar to a Go file which can be
used with the goleri module.'''
language = []
enums = set()
indent = 0
pattern = self.RE_KEYWORDS.pattern.replace('`', '` + "`" + `')
if not pattern.startswith('^'):
pattern = '^' + pattern
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_go'):
continue
language.append('{indent}{name} := {value}'.format(
indent=go_indent,
name=camel_case(name),
value=elem._export_go(go_indent, indent, enums)))
for name, ref in self._refs.items():
language.append(
'{indent}{name}.Set({value})'
.format(
indent=go_indent,
name=camel_case(name),
value=ref._element._export_go(
go_indent,
indent,
enums)))
enums = ' = iota\n'.join([
'{}{}'.format(go_indent, gid)
for gid in sorted(enums)]) + ' = iota'
return go_template.format(
name=self.__class__.__name__,
indent=go_indent,
package=go_package,
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
re_keywords=pattern,
enums=enums) | python | def export_go(
self,
go_template=GO_TEMPLATE,
go_indent=GO_INDENTATION,
go_package=GO_PACKAGE):
'''Export the grammar to a Go file which can be
used with the goleri module.'''
language = []
enums = set()
indent = 0
pattern = self.RE_KEYWORDS.pattern.replace('`', '` + "`" + `')
if not pattern.startswith('^'):
pattern = '^' + pattern
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_go'):
continue
language.append('{indent}{name} := {value}'.format(
indent=go_indent,
name=camel_case(name),
value=elem._export_go(go_indent, indent, enums)))
for name, ref in self._refs.items():
language.append(
'{indent}{name}.Set({value})'
.format(
indent=go_indent,
name=camel_case(name),
value=ref._element._export_go(
go_indent,
indent,
enums)))
enums = ' = iota\n'.join([
'{}{}'.format(go_indent, gid)
for gid in sorted(enums)]) + ' = iota'
return go_template.format(
name=self.__class__.__name__,
indent=go_indent,
package=go_package,
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
re_keywords=pattern,
enums=enums) | Export the grammar to a Go file which can be
used with the goleri module. | https://github.com/transceptor-technology/pyleri/blob/af754300d42a5a79bcdfc7852ee4cc75ce245f39/pyleri/grammar.py#L516-L564 |
transceptor-technology/pyleri | pyleri/grammar.py | Grammar.export_java | def export_java(
self,
java_template=JAVA_TEMPLATE,
java_indent=JAVA_INDENTATION,
java_package=JAVA_PACKAGE,
is_public=True):
'''Export the grammar to a Java file which can be
used with the jleri module.'''
language = []
enums = set()
classes = {'jleri.Grammar', 'jleri.Element'}
refs = []
indent = 0
pattern = self.RE_KEYWORDS.pattern.replace('\\', '\\\\')
if not pattern.startswith('^'):
pattern = '^' + pattern
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_java'):
continue
language.append(
'{indent}private static final Element {name} = {value};'
.format(
indent=java_indent,
name=name.upper(),
value=elem._export_java(
java_indent, indent, enums, classes)))
enum_str = ',\n'.join([
'{indent}{indent}{gid}'.format(
indent=java_indent,
gid=gid)
for gid in sorted(enums)])
for name, ref in self._refs.items():
refs.append(
'{indent}{indent}((Ref) {name}).set({value});'
.format(
indent=java_indent,
name=name.upper(),
value=ref._element._export_java(
java_indent,
-2,
enums,
classes)))
return java_template.format(
name=self.__class__.__name__,
imports='\n'.join(
map(lambda s: s, [
'import {};'.format(c)
for c in sorted(classes) if c != 'Rule'])),
indent=java_indent,
package='' if java_package is None
else 'package {};\n'.format(java_package),
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
re_keywords=pattern,
refs='' if not refs else '{}\n'.format('\n'.join(refs)),
enums=enum_str,
public='public ' if is_public else '') | python | def export_java(
self,
java_template=JAVA_TEMPLATE,
java_indent=JAVA_INDENTATION,
java_package=JAVA_PACKAGE,
is_public=True):
'''Export the grammar to a Java file which can be
used with the jleri module.'''
language = []
enums = set()
classes = {'jleri.Grammar', 'jleri.Element'}
refs = []
indent = 0
pattern = self.RE_KEYWORDS.pattern.replace('\\', '\\\\')
if not pattern.startswith('^'):
pattern = '^' + pattern
for name in self._order:
elem = getattr(self, name, None)
if not isinstance(elem, Element):
continue
if not hasattr(elem, '_export_java'):
continue
language.append(
'{indent}private static final Element {name} = {value};'
.format(
indent=java_indent,
name=name.upper(),
value=elem._export_java(
java_indent, indent, enums, classes)))
enum_str = ',\n'.join([
'{indent}{indent}{gid}'.format(
indent=java_indent,
gid=gid)
for gid in sorted(enums)])
for name, ref in self._refs.items():
refs.append(
'{indent}{indent}((Ref) {name}).set({value});'
.format(
indent=java_indent,
name=name.upper(),
value=ref._element._export_java(
java_indent,
-2,
enums,
classes)))
return java_template.format(
name=self.__class__.__name__,
imports='\n'.join(
map(lambda s: s, [
'import {};'.format(c)
for c in sorted(classes) if c != 'Rule'])),
indent=java_indent,
package='' if java_package is None
else 'package {};\n'.format(java_package),
datetime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
language='\n'.join(language),
re_keywords=pattern,
refs='' if not refs else '{}\n'.format('\n'.join(refs)),
enums=enum_str,
public='public ' if is_public else '') | Export the grammar to a Java file which can be
used with the jleri module. | https://github.com/transceptor-technology/pyleri/blob/af754300d42a5a79bcdfc7852ee4cc75ce245f39/pyleri/grammar.py#L566-L630 |
transceptor-technology/pyleri | pyleri/grammar.py | Grammar.parse | def parse(self, string):
'''Parse some string to the Grammar.
Returns a nodeResult with the following attributes:
- is_valid: True when the string is successfully parsed
by the Grammar.
- pos: position in the string where parsing ended.
(this is the end of the string when is_valid is True)
- expecting: a list containing possible elements at position
'pos' in the string.
- tree: the parse_tree containing a structured
result for the given string.
'''
self._string = string
self._expecting = Expecting()
self._cached_kw_match.clear()
self._len_string = len(string)
self._pos = None
tree = Node(self._element, string, 0, self._len_string)
node_res = Result(*self._walk(
self._element,
0,
tree.children,
self._element,
True))
# get rest if anything
rest = self._string[node_res.pos:].lstrip()
# set is_valid to False if we have 'rest' left.
if node_res.is_valid and rest:
node_res.is_valid = False
# add end_of_statement to expecting if this is possible
if not self._expecting.required and rest:
self._expecting.set_mode_required(node_res.pos, True)
self._expecting.update(end_of_statement, node_res.pos)
node_res.expecting = self._expecting.get_expecting()
# add expecting and correct pos to node_res if node_res is not valid
if not node_res.is_valid:
node_res.pos = self._expecting.pos
node_res.tree = tree
return node_res | python | def parse(self, string):
'''Parse some string to the Grammar.
Returns a nodeResult with the following attributes:
- is_valid: True when the string is successfully parsed
by the Grammar.
- pos: position in the string where parsing ended.
(this is the end of the string when is_valid is True)
- expecting: a list containing possible elements at position
'pos' in the string.
- tree: the parse_tree containing a structured
result for the given string.
'''
self._string = string
self._expecting = Expecting()
self._cached_kw_match.clear()
self._len_string = len(string)
self._pos = None
tree = Node(self._element, string, 0, self._len_string)
node_res = Result(*self._walk(
self._element,
0,
tree.children,
self._element,
True))
# get rest if anything
rest = self._string[node_res.pos:].lstrip()
# set is_valid to False if we have 'rest' left.
if node_res.is_valid and rest:
node_res.is_valid = False
# add end_of_statement to expecting if this is possible
if not self._expecting.required and rest:
self._expecting.set_mode_required(node_res.pos, True)
self._expecting.update(end_of_statement, node_res.pos)
node_res.expecting = self._expecting.get_expecting()
# add expecting and correct pos to node_res if node_res is not valid
if not node_res.is_valid:
node_res.pos = self._expecting.pos
node_res.tree = tree
return node_res | Parse some string to the Grammar.
Returns a nodeResult with the following attributes:
- is_valid: True when the string is successfully parsed
by the Grammar.
- pos: position in the string where parsing ended.
(this is the end of the string when is_valid is True)
- expecting: a list containing possible elements at position
'pos' in the string.
- tree: the parse_tree containing a structured
result for the given string. | https://github.com/transceptor-technology/pyleri/blob/af754300d42a5a79bcdfc7852ee4cc75ce245f39/pyleri/grammar.py#L632-L678 |
cheind/tf-matplotlib | tfmpl/figure.py | figure_buffer | def figure_buffer(figs):
'''Extract raw image buffer from matplotlib figure shaped as 1xHxWx3.'''
assert len(figs) > 0, 'No figure buffers given. Forgot to return from draw call?'
buffers = []
w, h = figs[0].canvas.get_width_height()
for f in figs:
wf, hf = f.canvas.get_width_height()
assert wf == w and hf == h, 'All canvas objects need to have same size'
buffers.append(np.fromstring(f.canvas.tostring_rgb(), dtype=np.uint8).reshape(h, w, 3))
return np.stack(buffers) | python | def figure_buffer(figs):
'''Extract raw image buffer from matplotlib figure shaped as 1xHxWx3.'''
assert len(figs) > 0, 'No figure buffers given. Forgot to return from draw call?'
buffers = []
w, h = figs[0].canvas.get_width_height()
for f in figs:
wf, hf = f.canvas.get_width_height()
assert wf == w and hf == h, 'All canvas objects need to have same size'
buffers.append(np.fromstring(f.canvas.tostring_rgb(), dtype=np.uint8).reshape(h, w, 3))
return np.stack(buffers) | Extract raw image buffer from matplotlib figure shaped as 1xHxWx3. | https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/figure.py#L14-L24 |
cheind/tf-matplotlib | tfmpl/figure.py | figure_tensor | def figure_tensor(func, **tf_pyfunc_kwargs):
'''Decorate matplotlib drawing routines.
This dectorator is meant to decorate functions that return matplotlib
figures. The decorated function has to have the following signature
def decorated(*args, **kwargs) -> figure or iterable of figures
where `*args` can be any positional argument and `**kwargs` are any
keyword arguments. The decorated function returns a tensor of shape
`[NumFigures, Height, Width, 3]` of type `tf.uint8`.
The drawing code is invoked during running of TensorFlow sessions,
at a time when all positional tensor arguments have been evaluated
by the session. The decorated function is then passed the tensor values.
All non tensor arguments remain unchanged.
'''
name = tf_pyfunc_kwargs.pop('name', func.__name__)
@wraps(func)
def wrapper(*func_args, **func_kwargs):
tf_args = PositionalTensorArgs(func_args)
def pyfnc_callee(*tensor_values, **unused):
try:
figs = as_list(func(*tf_args.mix_args(tensor_values), **func_kwargs))
for f in figs:
f.canvas.draw()
return figure_buffer(figs)
except Exception:
print('-'*5 + 'tfmpl catched exception' + '-'*5)
print(traceback.format_exc())
print('-'*20)
raise
return tf.py_func(pyfnc_callee, tf_args.tensor_args, tf.uint8, name=name, **tf_pyfunc_kwargs)
return wrapper | python | def figure_tensor(func, **tf_pyfunc_kwargs):
'''Decorate matplotlib drawing routines.
This dectorator is meant to decorate functions that return matplotlib
figures. The decorated function has to have the following signature
def decorated(*args, **kwargs) -> figure or iterable of figures
where `*args` can be any positional argument and `**kwargs` are any
keyword arguments. The decorated function returns a tensor of shape
`[NumFigures, Height, Width, 3]` of type `tf.uint8`.
The drawing code is invoked during running of TensorFlow sessions,
at a time when all positional tensor arguments have been evaluated
by the session. The decorated function is then passed the tensor values.
All non tensor arguments remain unchanged.
'''
name = tf_pyfunc_kwargs.pop('name', func.__name__)
@wraps(func)
def wrapper(*func_args, **func_kwargs):
tf_args = PositionalTensorArgs(func_args)
def pyfnc_callee(*tensor_values, **unused):
try:
figs = as_list(func(*tf_args.mix_args(tensor_values), **func_kwargs))
for f in figs:
f.canvas.draw()
return figure_buffer(figs)
except Exception:
print('-'*5 + 'tfmpl catched exception' + '-'*5)
print(traceback.format_exc())
print('-'*20)
raise
return tf.py_func(pyfnc_callee, tf_args.tensor_args, tf.uint8, name=name, **tf_pyfunc_kwargs)
return wrapper | Decorate matplotlib drawing routines.
This dectorator is meant to decorate functions that return matplotlib
figures. The decorated function has to have the following signature
def decorated(*args, **kwargs) -> figure or iterable of figures
where `*args` can be any positional argument and `**kwargs` are any
keyword arguments. The decorated function returns a tensor of shape
`[NumFigures, Height, Width, 3]` of type `tf.uint8`.
The drawing code is invoked during running of TensorFlow sessions,
at a time when all positional tensor arguments have been evaluated
by the session. The decorated function is then passed the tensor values.
All non tensor arguments remain unchanged. | https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/figure.py#L27-L64 |
cheind/tf-matplotlib | tfmpl/figure.py | blittable_figure_tensor | def blittable_figure_tensor(func, init_func, **tf_pyfunc_kwargs):
'''Decorate matplotlib drawing routines with blitting support.
This dectorator is meant to decorate functions that return matplotlib
figures. The decorated function has to have the following signature
def decorated(*args, **kwargs) -> iterable of artists
where `*args` can be any positional argument and `**kwargs` are any
keyword arguments. The decorated function returns a tensor of shape
`[NumFigures, Height, Width, 3]` of type `tf.uint8`.
Besides the actual drawing function, `blittable_figure_tensor` requires
a `init_func` argument with the following signature
def init(*args, **kwargs) -> iterable of figures, iterable of artists
The init function is meant to create and initialize figures, as well as to
perform drawing that is meant to be done only once. Any set of artits to be
updated in later drawing calls should also be allocated in init. The
initialize function must have the same positional and keyword arguments
as the decorated function. It is called once before the decorated function
is called.
The drawing code / init function is invoked during running of TensorFlow
sessions, at a time when all positional tensor arguments have been
evaluated by the session. The decorated / init function is then passed the
tensor values. All non tensor arguments remain unchanged.
'''
name = tf_pyfunc_kwargs.pop('name', func.__name__)
assert callable(init_func), 'Init function not callable'
@wraps(func)
def wrapper(*func_args, **func_kwargs):
figs = None
bgs = None
tf_args = PositionalTensorArgs(func_args)
def pyfnc_callee(*tensor_values, **unused):
try:
nonlocal figs, bgs
pos_args = tf_args.mix_args(tensor_values)
if figs is None:
figs, artists = init_func(*pos_args, **func_kwargs)
figs = as_list(figs)
artists = as_list(artists)
for f in figs:
f.canvas.draw()
for a in artists:
a.set_animated(True)
bgs = [f.canvas.copy_from_bbox(f.bbox) for f in figs]
artists = as_list(func(*pos_args, **func_kwargs))
for f, bg in zip(figs, bgs):
f.canvas.restore_region(bg)
for a in artists:
a.axes.draw_artist(a)
for f in figs:
f.canvas.blit(f.bbox)
return figure_buffer(figs)
except Exception:
print('-'*5 + 'tfmpl catched exception' + '-'*5)
print(traceback.format_exc())
print('-'*20)
raise
return tf.py_func(pyfnc_callee, tf_args.tensor_args, tf.uint8, name=name, **tf_pyfunc_kwargs)
return wrapper | python | def blittable_figure_tensor(func, init_func, **tf_pyfunc_kwargs):
'''Decorate matplotlib drawing routines with blitting support.
This dectorator is meant to decorate functions that return matplotlib
figures. The decorated function has to have the following signature
def decorated(*args, **kwargs) -> iterable of artists
where `*args` can be any positional argument and `**kwargs` are any
keyword arguments. The decorated function returns a tensor of shape
`[NumFigures, Height, Width, 3]` of type `tf.uint8`.
Besides the actual drawing function, `blittable_figure_tensor` requires
a `init_func` argument with the following signature
def init(*args, **kwargs) -> iterable of figures, iterable of artists
The init function is meant to create and initialize figures, as well as to
perform drawing that is meant to be done only once. Any set of artits to be
updated in later drawing calls should also be allocated in init. The
initialize function must have the same positional and keyword arguments
as the decorated function. It is called once before the decorated function
is called.
The drawing code / init function is invoked during running of TensorFlow
sessions, at a time when all positional tensor arguments have been
evaluated by the session. The decorated / init function is then passed the
tensor values. All non tensor arguments remain unchanged.
'''
name = tf_pyfunc_kwargs.pop('name', func.__name__)
assert callable(init_func), 'Init function not callable'
@wraps(func)
def wrapper(*func_args, **func_kwargs):
figs = None
bgs = None
tf_args = PositionalTensorArgs(func_args)
def pyfnc_callee(*tensor_values, **unused):
try:
nonlocal figs, bgs
pos_args = tf_args.mix_args(tensor_values)
if figs is None:
figs, artists = init_func(*pos_args, **func_kwargs)
figs = as_list(figs)
artists = as_list(artists)
for f in figs:
f.canvas.draw()
for a in artists:
a.set_animated(True)
bgs = [f.canvas.copy_from_bbox(f.bbox) for f in figs]
artists = as_list(func(*pos_args, **func_kwargs))
for f, bg in zip(figs, bgs):
f.canvas.restore_region(bg)
for a in artists:
a.axes.draw_artist(a)
for f in figs:
f.canvas.blit(f.bbox)
return figure_buffer(figs)
except Exception:
print('-'*5 + 'tfmpl catched exception' + '-'*5)
print(traceback.format_exc())
print('-'*20)
raise
return tf.py_func(pyfnc_callee, tf_args.tensor_args, tf.uint8, name=name, **tf_pyfunc_kwargs)
return wrapper | Decorate matplotlib drawing routines with blitting support.
This dectorator is meant to decorate functions that return matplotlib
figures. The decorated function has to have the following signature
def decorated(*args, **kwargs) -> iterable of artists
where `*args` can be any positional argument and `**kwargs` are any
keyword arguments. The decorated function returns a tensor of shape
`[NumFigures, Height, Width, 3]` of type `tf.uint8`.
Besides the actual drawing function, `blittable_figure_tensor` requires
a `init_func` argument with the following signature
def init(*args, **kwargs) -> iterable of figures, iterable of artists
The init function is meant to create and initialize figures, as well as to
perform drawing that is meant to be done only once. Any set of artits to be
updated in later drawing calls should also be allocated in init. The
initialize function must have the same positional and keyword arguments
as the decorated function. It is called once before the decorated function
is called.
The drawing code / init function is invoked during running of TensorFlow
sessions, at a time when all positional tensor arguments have been
evaluated by the session. The decorated / init function is then passed the
tensor values. All non tensor arguments remain unchanged. | https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/figure.py#L67-L139 |
cheind/tf-matplotlib | tfmpl/samples/mnist.py | draw_confusion_matrix | def draw_confusion_matrix(matrix):
'''Draw confusion matrix for MNIST.'''
fig = tfmpl.create_figure(figsize=(7,7))
ax = fig.add_subplot(111)
ax.set_title('Confusion matrix for MNIST classification')
tfmpl.plots.confusion_matrix.draw(
ax, matrix,
axis_labels=['Digit ' + str(x) for x in range(10)],
normalize=True
)
return fig | python | def draw_confusion_matrix(matrix):
'''Draw confusion matrix for MNIST.'''
fig = tfmpl.create_figure(figsize=(7,7))
ax = fig.add_subplot(111)
ax.set_title('Confusion matrix for MNIST classification')
tfmpl.plots.confusion_matrix.draw(
ax, matrix,
axis_labels=['Digit ' + str(x) for x in range(10)],
normalize=True
)
return fig | Draw confusion matrix for MNIST. | https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/samples/mnist.py#L24-L36 |
cheind/tf-matplotlib | tfmpl/plots/confusion_matrix.py | from_labels_and_predictions | def from_labels_and_predictions(labels, predictions, num_classes):
'''Compute a confusion matrix from labels and predictions.
A drop-in replacement for tf.confusion_matrix that works on CPU data
and not tensors.
Params
------
labels : array-like
1-D array of real labels for classification
predicitions: array-like
1-D array of predicted label classes
num_classes: scalar
Total number of classes
Returns
-------
matrix : NxN array
Array of shape [num_classes, num_classes] containing the confusion values.
'''
assert len(labels) == len(predictions)
cm = np.zeros((num_classes, num_classes), dtype=np.int32)
for i in range(len(labels)):
cm[labels[i], predictions[i]] += 1
return cm | python | def from_labels_and_predictions(labels, predictions, num_classes):
'''Compute a confusion matrix from labels and predictions.
A drop-in replacement for tf.confusion_matrix that works on CPU data
and not tensors.
Params
------
labels : array-like
1-D array of real labels for classification
predicitions: array-like
1-D array of predicted label classes
num_classes: scalar
Total number of classes
Returns
-------
matrix : NxN array
Array of shape [num_classes, num_classes] containing the confusion values.
'''
assert len(labels) == len(predictions)
cm = np.zeros((num_classes, num_classes), dtype=np.int32)
for i in range(len(labels)):
cm[labels[i], predictions[i]] += 1
return cm | Compute a confusion matrix from labels and predictions.
A drop-in replacement for tf.confusion_matrix that works on CPU data
and not tensors.
Params
------
labels : array-like
1-D array of real labels for classification
predicitions: array-like
1-D array of predicted label classes
num_classes: scalar
Total number of classes
Returns
-------
matrix : NxN array
Array of shape [num_classes, num_classes] containing the confusion values. | https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/plots/confusion_matrix.py#L11-L35 |
cheind/tf-matplotlib | tfmpl/plots/confusion_matrix.py | draw | def draw(ax, cm, axis_labels=None, normalize=False):
'''Plot a confusion matrix.
Inspired by
https://stackoverflow.com/questions/41617463/tensorflow-confusion-matrix-in-tensorboard
Params
------
ax : axis
Axis to plot on
cm : NxN array
Confusion matrix
Kwargs
------
axis_labels : array-like
Array of size N containing axis labels
normalize : bool
Whether to plot counts or ratios.
'''
cm = np.asarray(cm)
num_classes = cm.shape[0]
if normalize:
with np.errstate(invalid='ignore', divide='ignore'):
cm = cm / cm.sum(1, keepdims=True)
cm = np.nan_to_num(cm, copy=True)
po = np.get_printoptions()
np.set_printoptions(precision=2)
ax.imshow(cm, cmap='Oranges')
ticks = np.arange(num_classes)
ax.set_xlabel('Predicted')
ax.set_xticks(ticks)
ax.xaxis.set_label_position('bottom')
ax.xaxis.tick_bottom()
ax.set_ylabel('Actual')
ax.set_yticks(ticks)
ax.yaxis.set_label_position('left')
ax.yaxis.tick_left()
if axis_labels is not None:
ticklabels = [re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', x) for x in axis_labels]
ticklabels = ['\n'.join(wrap(l, 20)) for l in ticklabels]
ax.set_xticklabels(ticklabels, rotation=-90, ha='center')
ax.set_yticklabels(ticklabels, va ='center')
for i, j in product(range(num_classes), range(num_classes)):
if cm[i,j] == 0:
txt = '.'
elif normalize:
txt = '{:.2f}'.format(cm[i,j])
else:
txt = '{}'.format(cm[i,j])
ax.text(j, i, txt, horizontalalignment="center", verticalalignment='center', color= "black", fontsize=7)
np.set_printoptions(**po) | python | def draw(ax, cm, axis_labels=None, normalize=False):
'''Plot a confusion matrix.
Inspired by
https://stackoverflow.com/questions/41617463/tensorflow-confusion-matrix-in-tensorboard
Params
------
ax : axis
Axis to plot on
cm : NxN array
Confusion matrix
Kwargs
------
axis_labels : array-like
Array of size N containing axis labels
normalize : bool
Whether to plot counts or ratios.
'''
cm = np.asarray(cm)
num_classes = cm.shape[0]
if normalize:
with np.errstate(invalid='ignore', divide='ignore'):
cm = cm / cm.sum(1, keepdims=True)
cm = np.nan_to_num(cm, copy=True)
po = np.get_printoptions()
np.set_printoptions(precision=2)
ax.imshow(cm, cmap='Oranges')
ticks = np.arange(num_classes)
ax.set_xlabel('Predicted')
ax.set_xticks(ticks)
ax.xaxis.set_label_position('bottom')
ax.xaxis.tick_bottom()
ax.set_ylabel('Actual')
ax.set_yticks(ticks)
ax.yaxis.set_label_position('left')
ax.yaxis.tick_left()
if axis_labels is not None:
ticklabels = [re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', x) for x in axis_labels]
ticklabels = ['\n'.join(wrap(l, 20)) for l in ticklabels]
ax.set_xticklabels(ticklabels, rotation=-90, ha='center')
ax.set_yticklabels(ticklabels, va ='center')
for i, j in product(range(num_classes), range(num_classes)):
if cm[i,j] == 0:
txt = '.'
elif normalize:
txt = '{:.2f}'.format(cm[i,j])
else:
txt = '{}'.format(cm[i,j])
ax.text(j, i, txt, horizontalalignment="center", verticalalignment='center', color= "black", fontsize=7)
np.set_printoptions(**po) | Plot a confusion matrix.
Inspired by
https://stackoverflow.com/questions/41617463/tensorflow-confusion-matrix-in-tensorboard
Params
------
ax : axis
Axis to plot on
cm : NxN array
Confusion matrix
Kwargs
------
axis_labels : array-like
Array of size N containing axis labels
normalize : bool
Whether to plot counts or ratios. | https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/plots/confusion_matrix.py#L37-L98 |
cheind/tf-matplotlib | tfmpl/create.py | create_figure | def create_figure(*fig_args, **fig_kwargs):
'''Create a single figure.
Args and Kwargs are passed to `matplotlib.figure.Figure`.
This routine is provided in order to avoid usage of pyplot which
is stateful and not thread safe. As drawing routines in tf-matplotlib
are called from py-funcs in their respective thread, avoid usage
of pyplot where possible.
'''
fig = Figure(*fig_args, **fig_kwargs)
# Attach canvas
FigureCanvas(fig)
return fig | python | def create_figure(*fig_args, **fig_kwargs):
'''Create a single figure.
Args and Kwargs are passed to `matplotlib.figure.Figure`.
This routine is provided in order to avoid usage of pyplot which
is stateful and not thread safe. As drawing routines in tf-matplotlib
are called from py-funcs in their respective thread, avoid usage
of pyplot where possible.
'''
fig = Figure(*fig_args, **fig_kwargs)
# Attach canvas
FigureCanvas(fig)
return fig | Create a single figure.
Args and Kwargs are passed to `matplotlib.figure.Figure`.
This routine is provided in order to avoid usage of pyplot which
is stateful and not thread safe. As drawing routines in tf-matplotlib
are called from py-funcs in their respective thread, avoid usage
of pyplot where possible. | https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/create.py#L9-L23 |
cheind/tf-matplotlib | tfmpl/create.py | create_figures | def create_figures(n, *fig_args, **fig_kwargs):
'''Create multiple figures.
Args and Kwargs are passed to `matplotlib.figure.Figure`.
This routine is provided in order to avoid usage of pyplot which
is stateful and not thread safe. As drawing routines in tf-matplotlib
are called from py-funcs in their respective thread, avoid usage
of pyplot where possible.
'''
return [create_figure(*fig_args, **fig_kwargs) for _ in range(n)] | python | def create_figures(n, *fig_args, **fig_kwargs):
'''Create multiple figures.
Args and Kwargs are passed to `matplotlib.figure.Figure`.
This routine is provided in order to avoid usage of pyplot which
is stateful and not thread safe. As drawing routines in tf-matplotlib
are called from py-funcs in their respective thread, avoid usage
of pyplot where possible.
'''
return [create_figure(*fig_args, **fig_kwargs) for _ in range(n)] | Create multiple figures.
Args and Kwargs are passed to `matplotlib.figure.Figure`.
This routine is provided in order to avoid usage of pyplot which
is stateful and not thread safe. As drawing routines in tf-matplotlib
are called from py-funcs in their respective thread, avoid usage
of pyplot where possible. | https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/create.py#L25-L35 |
cheind/tf-matplotlib | tfmpl/meta.py | vararg_decorator | def vararg_decorator(f):
'''Decorator to handle variable argument decorators.'''
@wraps(f)
def decorator(*args, **kwargs):
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
return f(args[0])
else:
return lambda realf: f(realf, *args, **kwargs)
return decorator | python | def vararg_decorator(f):
'''Decorator to handle variable argument decorators.'''
@wraps(f)
def decorator(*args, **kwargs):
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
return f(args[0])
else:
return lambda realf: f(realf, *args, **kwargs)
return decorator | Decorator to handle variable argument decorators. | https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/meta.py#L11-L21 |
cheind/tf-matplotlib | tfmpl/meta.py | as_list | def as_list(x):
'''Ensure `x` is of list type.'''
if x is None:
x = []
elif not isinstance(x, Sequence):
x = [x]
return list(x) | python | def as_list(x):
'''Ensure `x` is of list type.'''
if x is None:
x = []
elif not isinstance(x, Sequence):
x = [x]
return list(x) | Ensure `x` is of list type. | https://github.com/cheind/tf-matplotlib/blob/c6904d3d2d306d9a479c24fbcb1f674a57dafd0e/tfmpl/meta.py#L40-L47 |
yakupadakli/python-unsplash | unsplash/photo.py | Photo.all | def all(self, page=1, per_page=10, order_by="latest"):
"""
Get a single page from the list of all photos.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:param order_by [string]: How to sort the photos. Optional.
(Valid values: latest, oldest, popular; default: latest)
:return: [Array]: A single page of the Photo list.
"""
return self._all("/photos", page=page, per_page=per_page, order_by=order_by) | python | def all(self, page=1, per_page=10, order_by="latest"):
"""
Get a single page from the list of all photos.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:param order_by [string]: How to sort the photos. Optional.
(Valid values: latest, oldest, popular; default: latest)
:return: [Array]: A single page of the Photo list.
"""
return self._all("/photos", page=page, per_page=per_page, order_by=order_by) | Get a single page from the list of all photos.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:param order_by [string]: How to sort the photos. Optional.
(Valid values: latest, oldest, popular; default: latest)
:return: [Array]: A single page of the Photo list. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/photo.py#L34-L44 |
yakupadakli/python-unsplash | unsplash/photo.py | Photo.curated | def curated(self, page=1, per_page=10, order_by="latest"):
"""
Get a single page from the list of the curated photos (front-page’s photos).
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:param order_by [string]: How to sort the photos. Optional.
(Valid values: latest, oldest, popular; default: latest)
:return: [Array]: A single page of the curated Photo list.
"""
return self._all("/photos/curated", page=page, per_page=per_page, order_by=order_by) | python | def curated(self, page=1, per_page=10, order_by="latest"):
"""
Get a single page from the list of the curated photos (front-page’s photos).
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:param order_by [string]: How to sort the photos. Optional.
(Valid values: latest, oldest, popular; default: latest)
:return: [Array]: A single page of the curated Photo list.
"""
return self._all("/photos/curated", page=page, per_page=per_page, order_by=order_by) | Get a single page from the list of the curated photos (front-page’s photos).
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:param order_by [string]: How to sort the photos. Optional.
(Valid values: latest, oldest, popular; default: latest)
:return: [Array]: A single page of the curated Photo list. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/photo.py#L46-L56 |
yakupadakli/python-unsplash | unsplash/photo.py | Photo.get | def get(self, photo_id, width=None, height=None, rect=None):
"""
Retrieve a single photo.
Note: Supplying the optional w or h parameters will result
in the custom photo URL being added to the 'urls' object:
:param photo_id [string]: The photo’s ID. Required.
:param width [integer]: Image width in pixels.
:param height [integer]: Image height in pixels.
:param rect [string]: 4 comma-separated integers representing x, y, width, height of the cropped rectangle.
:return: [Photo]: The Unsplash Photo.
"""
url = "/photos/%s" % photo_id
params = {
"w": width,
"h": height,
"rect": rect
}
result = self._get(url, params=params)
return PhotoModel.parse(result) | python | def get(self, photo_id, width=None, height=None, rect=None):
"""
Retrieve a single photo.
Note: Supplying the optional w or h parameters will result
in the custom photo URL being added to the 'urls' object:
:param photo_id [string]: The photo’s ID. Required.
:param width [integer]: Image width in pixels.
:param height [integer]: Image height in pixels.
:param rect [string]: 4 comma-separated integers representing x, y, width, height of the cropped rectangle.
:return: [Photo]: The Unsplash Photo.
"""
url = "/photos/%s" % photo_id
params = {
"w": width,
"h": height,
"rect": rect
}
result = self._get(url, params=params)
return PhotoModel.parse(result) | Retrieve a single photo.
Note: Supplying the optional w or h parameters will result
in the custom photo URL being added to the 'urls' object:
:param photo_id [string]: The photo’s ID. Required.
:param width [integer]: Image width in pixels.
:param height [integer]: Image height in pixels.
:param rect [string]: 4 comma-separated integers representing x, y, width, height of the cropped rectangle.
:return: [Photo]: The Unsplash Photo. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/photo.py#L58-L78 |
yakupadakli/python-unsplash | unsplash/photo.py | Photo.search | def search(self, query, category=None, orientation=None, page=1, per_page=10):
"""
Get a single page from a photo search.
Optionally limit your search to a set of categories by supplying the category ID’s.
Note: If supplying multiple category ID’s,
the resulting photos will be those that match all of the given categories,
not ones that match any category.
:param query [string]: Search terms.
:param category [string]: Category ID(‘s) to filter search. If multiple, comma-separated. (deprecated)
:param orientation [string]: Filter search results by photo orientation.
Valid values are landscape, portrait, and squarish.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [Array]: A single page of the curated Photo list.
:raise UnsplashError: If the given orientation is not in the default orientation values.
"""
if orientation and orientation not in self.orientation_values:
raise Exception()
params = {
"query": query,
"category": category,
"orientation": orientation,
"page": page,
"per_page": per_page
}
url = "/photos/search"
result = self._get(url, params=params)
return PhotoModel.parse_list(result) | python | def search(self, query, category=None, orientation=None, page=1, per_page=10):
"""
Get a single page from a photo search.
Optionally limit your search to a set of categories by supplying the category ID’s.
Note: If supplying multiple category ID’s,
the resulting photos will be those that match all of the given categories,
not ones that match any category.
:param query [string]: Search terms.
:param category [string]: Category ID(‘s) to filter search. If multiple, comma-separated. (deprecated)
:param orientation [string]: Filter search results by photo orientation.
Valid values are landscape, portrait, and squarish.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [Array]: A single page of the curated Photo list.
:raise UnsplashError: If the given orientation is not in the default orientation values.
"""
if orientation and orientation not in self.orientation_values:
raise Exception()
params = {
"query": query,
"category": category,
"orientation": orientation,
"page": page,
"per_page": per_page
}
url = "/photos/search"
result = self._get(url, params=params)
return PhotoModel.parse_list(result) | Get a single page from a photo search.
Optionally limit your search to a set of categories by supplying the category ID’s.
Note: If supplying multiple category ID’s,
the resulting photos will be those that match all of the given categories,
not ones that match any category.
:param query [string]: Search terms.
:param category [string]: Category ID(‘s) to filter search. If multiple, comma-separated. (deprecated)
:param orientation [string]: Filter search results by photo orientation.
Valid values are landscape, portrait, and squarish.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [Array]: A single page of the curated Photo list.
:raise UnsplashError: If the given orientation is not in the default orientation values. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/photo.py#L80-L109 |
yakupadakli/python-unsplash | unsplash/photo.py | Photo.random | def random(self, count=1, **kwargs):
"""
Retrieve a single random photo, given optional filters.
Note: If supplying multiple category ID’s,
the resulting photos will be those that
match all of the given categories, not ones that match any category.
Note: You can’t use the collections and query parameters in the same request
Note: When supplying a count parameter
- and only then - the response will be an array of photos,
even if the value of count is 1.
All parameters are optional, and can be combined to narrow
the pool of photos from which a random one will be chosen.
:param count [integer]: The number of photos to return. (Default: 1; max: 30)
:param category: Category ID(‘s) to filter selection. If multiple, comma-separated. (deprecated)
:param collections: Public collection ID(‘s) to filter selection. If multiple, comma-separated
:param featured: Limit selection to featured photos.
:param username: Limit selection to a single user.
:param query: Limit selection to photos matching a search term.
:param w: Image width in pixels.
:param h: Image height in pixels.
:param orientation: Filter search results by photo orientation.
Valid values are landscape, portrait, and squarish.
:return: [Array] or [Photo]: A single page of the curated Photo list or The Unsplash Photo. .
:raise UnsplashError: If the given orientation is not in the default orientation values.
"""
kwargs.update({"count": count})
orientation = kwargs.get("orientation", None)
if orientation and orientation not in self.orientation_values:
raise Exception()
url = "/photos/random"
result = self._get(url, params=kwargs)
return PhotoModel.parse_list(result) | python | def random(self, count=1, **kwargs):
"""
Retrieve a single random photo, given optional filters.
Note: If supplying multiple category ID’s,
the resulting photos will be those that
match all of the given categories, not ones that match any category.
Note: You can’t use the collections and query parameters in the same request
Note: When supplying a count parameter
- and only then - the response will be an array of photos,
even if the value of count is 1.
All parameters are optional, and can be combined to narrow
the pool of photos from which a random one will be chosen.
:param count [integer]: The number of photos to return. (Default: 1; max: 30)
:param category: Category ID(‘s) to filter selection. If multiple, comma-separated. (deprecated)
:param collections: Public collection ID(‘s) to filter selection. If multiple, comma-separated
:param featured: Limit selection to featured photos.
:param username: Limit selection to a single user.
:param query: Limit selection to photos matching a search term.
:param w: Image width in pixels.
:param h: Image height in pixels.
:param orientation: Filter search results by photo orientation.
Valid values are landscape, portrait, and squarish.
:return: [Array] or [Photo]: A single page of the curated Photo list or The Unsplash Photo. .
:raise UnsplashError: If the given orientation is not in the default orientation values.
"""
kwargs.update({"count": count})
orientation = kwargs.get("orientation", None)
if orientation and orientation not in self.orientation_values:
raise Exception()
url = "/photos/random"
result = self._get(url, params=kwargs)
return PhotoModel.parse_list(result) | Retrieve a single random photo, given optional filters.
Note: If supplying multiple category ID’s,
the resulting photos will be those that
match all of the given categories, not ones that match any category.
Note: You can’t use the collections and query parameters in the same request
Note: When supplying a count parameter
- and only then - the response will be an array of photos,
even if the value of count is 1.
All parameters are optional, and can be combined to narrow
the pool of photos from which a random one will be chosen.
:param count [integer]: The number of photos to return. (Default: 1; max: 30)
:param category: Category ID(‘s) to filter selection. If multiple, comma-separated. (deprecated)
:param collections: Public collection ID(‘s) to filter selection. If multiple, comma-separated
:param featured: Limit selection to featured photos.
:param username: Limit selection to a single user.
:param query: Limit selection to photos matching a search term.
:param w: Image width in pixels.
:param h: Image height in pixels.
:param orientation: Filter search results by photo orientation.
Valid values are landscape, portrait, and squarish.
:return: [Array] or [Photo]: A single page of the curated Photo list or The Unsplash Photo. .
:raise UnsplashError: If the given orientation is not in the default orientation values. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/photo.py#L111-L147 |
yakupadakli/python-unsplash | unsplash/photo.py | Photo.stats | def stats(self, photo_id):
"""
Retrieve a single photo’s stats.
:param photo_id [string]: The photo’s ID. Required.
:return: [Stat]: The Unsplash Stat.
"""
url = "/photos/%s/stats" % photo_id
result = self._get(url)
return StatModel.parse(result) | python | def stats(self, photo_id):
"""
Retrieve a single photo’s stats.
:param photo_id [string]: The photo’s ID. Required.
:return: [Stat]: The Unsplash Stat.
"""
url = "/photos/%s/stats" % photo_id
result = self._get(url)
return StatModel.parse(result) | Retrieve a single photo’s stats.
:param photo_id [string]: The photo’s ID. Required.
:return: [Stat]: The Unsplash Stat. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/photo.py#L149-L158 |
yakupadakli/python-unsplash | unsplash/photo.py | Photo.like | def like(self, photo_id):
"""
Like a photo on behalf of the logged-in user.
This requires the 'write_likes' scope.
Note: This action is idempotent; sending the POST request
to a single photo multiple times has no additional effect.
:param photo_id [string]: The photo’s ID. Required.
:return: [Photo]: The Unsplash Photo.
"""
url = "/photos/%s/like" % photo_id
result = self._post(url)
return PhotoModel.parse(result) | python | def like(self, photo_id):
"""
Like a photo on behalf of the logged-in user.
This requires the 'write_likes' scope.
Note: This action is idempotent; sending the POST request
to a single photo multiple times has no additional effect.
:param photo_id [string]: The photo’s ID. Required.
:return: [Photo]: The Unsplash Photo.
"""
url = "/photos/%s/like" % photo_id
result = self._post(url)
return PhotoModel.parse(result) | Like a photo on behalf of the logged-in user.
This requires the 'write_likes' scope.
Note: This action is idempotent; sending the POST request
to a single photo multiple times has no additional effect.
:param photo_id [string]: The photo’s ID. Required.
:return: [Photo]: The Unsplash Photo. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/photo.py#L179-L192 |
yakupadakli/python-unsplash | unsplash/photo.py | Photo.unlike | def unlike(self, photo_id):
"""
Remove a user’s like of a photo.
Note: This action is idempotent; sending the DELETE request
to a single photo multiple times has no additional effect.
:param photo_id [string]: The photo’s ID. Required.
:return: [Photo]: The Unsplash Photo.
"""
url = "/photos/%s/like" % photo_id
result = self._delete(url)
return PhotoModel.parse(result) | python | def unlike(self, photo_id):
"""
Remove a user’s like of a photo.
Note: This action is idempotent; sending the DELETE request
to a single photo multiple times has no additional effect.
:param photo_id [string]: The photo’s ID. Required.
:return: [Photo]: The Unsplash Photo.
"""
url = "/photos/%s/like" % photo_id
result = self._delete(url)
return PhotoModel.parse(result) | Remove a user’s like of a photo.
Note: This action is idempotent; sending the DELETE request
to a single photo multiple times has no additional effect.
:param photo_id [string]: The photo’s ID. Required.
:return: [Photo]: The Unsplash Photo. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/photo.py#L194-L206 |
yakupadakli/python-unsplash | unsplash/search.py | Search.photos | def photos(self, query, page=1, per_page=10):
"""
Get a single page of photo results for a query.
:param query [string]: Search terms.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [Photo]}
"""
url = "/search/photos"
data = self._search(url, query, page=page, per_page=per_page)
data["results"] = PhotoModel.parse_list(data.get("results"))
return data | python | def photos(self, query, page=1, per_page=10):
"""
Get a single page of photo results for a query.
:param query [string]: Search terms.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [Photo]}
"""
url = "/search/photos"
data = self._search(url, query, page=page, per_page=per_page)
data["results"] = PhotoModel.parse_list(data.get("results"))
return data | Get a single page of photo results for a query.
:param query [string]: Search terms.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [Photo]} | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/search.py#L19-L31 |
yakupadakli/python-unsplash | unsplash/search.py | Search.collections | def collections(self, query, page=1, per_page=10):
"""
Get a single page of collection results for a query.
:param query [string]: Search terms.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [Collection]}
"""
url = "/search/collections"
data = self._search(url, query, page=page, per_page=per_page)
data["results"] = CollectionModel.parse_list(data.get("results"))
return data | python | def collections(self, query, page=1, per_page=10):
"""
Get a single page of collection results for a query.
:param query [string]: Search terms.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [Collection]}
"""
url = "/search/collections"
data = self._search(url, query, page=page, per_page=per_page)
data["results"] = CollectionModel.parse_list(data.get("results"))
return data | Get a single page of collection results for a query.
:param query [string]: Search terms.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [Collection]} | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/search.py#L33-L45 |
yakupadakli/python-unsplash | unsplash/search.py | Search.users | def users(self, query, page=1, per_page=10):
"""
Get a single page of user results for a query.
:param query [string]: Search terms.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [User]}
"""
url = "/search/users"
data = self._search(url, query, page=page, per_page=per_page)
data["results"] = UserModel.parse_list(data.get("results"))
return data | python | def users(self, query, page=1, per_page=10):
"""
Get a single page of user results for a query.
:param query [string]: Search terms.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [User]}
"""
url = "/search/users"
data = self._search(url, query, page=page, per_page=per_page)
data["results"] = UserModel.parse_list(data.get("results"))
return data | Get a single page of user results for a query.
:param query [string]: Search terms.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [dict]: {u'total': 0, u'total_pages': 0, u'results': [User]} | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/search.py#L47-L59 |
yakupadakli/python-unsplash | unsplash/collection.py | Collection.all | def all(self, page=1, per_page=10):
"""
Get a single page from the list of all collections.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [Array]: A single page of the Collection list.
"""
url = "/collections"
result = self._all(url, page=page, per_page=per_page)
return CollectionModel.parse_list(result) | python | def all(self, page=1, per_page=10):
"""
Get a single page from the list of all collections.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [Array]: A single page of the Collection list.
"""
url = "/collections"
result = self._all(url, page=page, per_page=per_page)
return CollectionModel.parse_list(result) | Get a single page from the list of all collections.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [Array]: A single page of the Collection list. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L29-L39 |
yakupadakli/python-unsplash | unsplash/collection.py | Collection.get | def get(self, collection_id):
"""
Retrieve a single collection.
To view a user’s private collections, the 'read_collections' scope is required.
:param collection_id [string]: The collections’s ID. Required.
:return: [Collection]: The Unsplash Collection.
"""
url = "/collections/%s" % collection_id
result = self._get(url)
return CollectionModel.parse(result) | python | def get(self, collection_id):
"""
Retrieve a single collection.
To view a user’s private collections, the 'read_collections' scope is required.
:param collection_id [string]: The collections’s ID. Required.
:return: [Collection]: The Unsplash Collection.
"""
url = "/collections/%s" % collection_id
result = self._get(url)
return CollectionModel.parse(result) | Retrieve a single collection.
To view a user’s private collections, the 'read_collections' scope is required.
:param collection_id [string]: The collections’s ID. Required.
:return: [Collection]: The Unsplash Collection. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L65-L75 |
yakupadakli/python-unsplash | unsplash/collection.py | Collection.get_curated | def get_curated(self, collection_id):
"""
Retrieve a single curated collection.
To view a user’s private collections, the 'read_collections' scope is required.
:param collection_id [string]: The collections’s ID. Required.
:return: [Collection]: The Unsplash Collection.
"""
url = "/collections/curated/%s" % collection_id
result = self._get(url)
return CollectionModel.parse(result) | python | def get_curated(self, collection_id):
"""
Retrieve a single curated collection.
To view a user’s private collections, the 'read_collections' scope is required.
:param collection_id [string]: The collections’s ID. Required.
:return: [Collection]: The Unsplash Collection.
"""
url = "/collections/curated/%s" % collection_id
result = self._get(url)
return CollectionModel.parse(result) | Retrieve a single curated collection.
To view a user’s private collections, the 'read_collections' scope is required.
:param collection_id [string]: The collections’s ID. Required.
:return: [Collection]: The Unsplash Collection. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L77-L87 |
yakupadakli/python-unsplash | unsplash/collection.py | Collection.photos | def photos(self, collection_id, page=1, per_page=10):
"""
Retrieve a collection’s photos.
:param collection_id [string]: The collection’s ID. Required.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [Array]: A single page of the Photo list.
"""
url = "/collections/%s/photos" % collection_id
result = self._all(url, page=page, per_page=per_page)
return PhotoModel.parse_list(result) | python | def photos(self, collection_id, page=1, per_page=10):
"""
Retrieve a collection’s photos.
:param collection_id [string]: The collection’s ID. Required.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [Array]: A single page of the Photo list.
"""
url = "/collections/%s/photos" % collection_id
result = self._all(url, page=page, per_page=per_page)
return PhotoModel.parse_list(result) | Retrieve a collection’s photos.
:param collection_id [string]: The collection’s ID. Required.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [Array]: A single page of the Photo list. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L89-L100 |
yakupadakli/python-unsplash | unsplash/collection.py | Collection.related | def related(self, collection_id):
"""
Retrieve a list of collections related to this one.
:param collection_id [string]: The collection’s ID. Required.
:return: [Array]: A single page of the Collection list.
"""
url = "/collections/%s/related" % collection_id
result = self._get(url)
return CollectionModel.parse_list(result) | python | def related(self, collection_id):
"""
Retrieve a list of collections related to this one.
:param collection_id [string]: The collection’s ID. Required.
:return: [Array]: A single page of the Collection list.
"""
url = "/collections/%s/related" % collection_id
result = self._get(url)
return CollectionModel.parse_list(result) | Retrieve a list of collections related to this one.
:param collection_id [string]: The collection’s ID. Required.
:return: [Array]: A single page of the Collection list. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L115-L124 |
yakupadakli/python-unsplash | unsplash/collection.py | Collection.create | def create(self, title, description=None, private=False):
"""
Create a new collection.
This requires the 'write_collections' scope.
:param title [string]: The title of the collection. (Required.)
:param description [string]: The collection’s description. (Optional.)
:param private [boolean]: Whether to make this collection private. (Optional; default false).
:return: [Collection]: The Unsplash Collection.
"""
url = "/collections"
data = {
"title": title,
"description": description,
"private": private
}
result = self._post(url, data=data)
return CollectionModel.parse(result) | python | def create(self, title, description=None, private=False):
"""
Create a new collection.
This requires the 'write_collections' scope.
:param title [string]: The title of the collection. (Required.)
:param description [string]: The collection’s description. (Optional.)
:param private [boolean]: Whether to make this collection private. (Optional; default false).
:return: [Collection]: The Unsplash Collection.
"""
url = "/collections"
data = {
"title": title,
"description": description,
"private": private
}
result = self._post(url, data=data)
return CollectionModel.parse(result) | Create a new collection.
This requires the 'write_collections' scope.
:param title [string]: The title of the collection. (Required.)
:param description [string]: The collection’s description. (Optional.)
:param private [boolean]: Whether to make this collection private. (Optional; default false).
:return: [Collection]: The Unsplash Collection. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L126-L143 |
yakupadakli/python-unsplash | unsplash/collection.py | Collection.update | def update(self, collection_id, title=None, description=None, private=False):
"""
Update an existing collection belonging to the logged-in user.
This requires the 'write_collections' scope.
:param collection_id [string]: The collection’s ID. Required.
:param title [string]: The title of the collection. (Required.)
:param description [string]: The collection’s description. (Optional.)
:param private [boolean]: Whether to make this collection private. (Optional; default false).
:return: [Collection]: The Unsplash Collection.
"""
url = "/collections/%s" % collection_id
data = {
"title": title,
"description": description,
"private": private
}
result = self._put(url, data=data)
return CollectionModel.parse(result) | python | def update(self, collection_id, title=None, description=None, private=False):
"""
Update an existing collection belonging to the logged-in user.
This requires the 'write_collections' scope.
:param collection_id [string]: The collection’s ID. Required.
:param title [string]: The title of the collection. (Required.)
:param description [string]: The collection’s description. (Optional.)
:param private [boolean]: Whether to make this collection private. (Optional; default false).
:return: [Collection]: The Unsplash Collection.
"""
url = "/collections/%s" % collection_id
data = {
"title": title,
"description": description,
"private": private
}
result = self._put(url, data=data)
return CollectionModel.parse(result) | Update an existing collection belonging to the logged-in user.
This requires the 'write_collections' scope.
:param collection_id [string]: The collection’s ID. Required.
:param title [string]: The title of the collection. (Required.)
:param description [string]: The collection’s description. (Optional.)
:param private [boolean]: Whether to make this collection private. (Optional; default false).
:return: [Collection]: The Unsplash Collection. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L145-L163 |
yakupadakli/python-unsplash | unsplash/collection.py | Collection.add_photo | def add_photo(self, collection_id, photo_id):
"""
Add a photo to one of the logged-in user’s collections.
Requires the 'write_collections' scope.
Note: If the photo is already in the collection, this acion has no effect.
:param collection_id [string]: The collection’s ID. Required.
:param photo_id [string]: The photo’s ID. Required.
:return: [Tuple]: The Unsplash Collection and Photo
"""
url = "/collections/%s/add" % collection_id
data = {
"collection_id": collection_id,
"photo_id": photo_id
}
result = self._post(url, data=data) or {}
return CollectionModel.parse(result.get("collection")), PhotoModel.parse(result.get("photo")) | python | def add_photo(self, collection_id, photo_id):
"""
Add a photo to one of the logged-in user’s collections.
Requires the 'write_collections' scope.
Note: If the photo is already in the collection, this acion has no effect.
:param collection_id [string]: The collection’s ID. Required.
:param photo_id [string]: The photo’s ID. Required.
:return: [Tuple]: The Unsplash Collection and Photo
"""
url = "/collections/%s/add" % collection_id
data = {
"collection_id": collection_id,
"photo_id": photo_id
}
result = self._post(url, data=data) or {}
return CollectionModel.parse(result.get("collection")), PhotoModel.parse(result.get("photo")) | Add a photo to one of the logged-in user’s collections.
Requires the 'write_collections' scope.
Note: If the photo is already in the collection, this acion has no effect.
:param collection_id [string]: The collection’s ID. Required.
:param photo_id [string]: The photo’s ID. Required.
:return: [Tuple]: The Unsplash Collection and Photo | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L176-L193 |
yakupadakli/python-unsplash | unsplash/collection.py | Collection.remove_photo | def remove_photo(self, collection_id, photo_id):
"""
Remove a photo from one of the logged-in user’s collections.
Requires the 'write_collections' scope.
:param collection_id [string]: The collection’s ID. Required.
:param photo_id [string]: The photo’s ID. Required.
:return: [Tuple]: The Unsplash Collection and Photo
"""
url = "/collections/%s/remove" % collection_id
data = {
"collection_id": collection_id,
"photo_id": photo_id
}
result = self._delete(url, data=data) or {}
return CollectionModel.parse(result.get("collection")), PhotoModel.parse(result.get("photo")) | python | def remove_photo(self, collection_id, photo_id):
"""
Remove a photo from one of the logged-in user’s collections.
Requires the 'write_collections' scope.
:param collection_id [string]: The collection’s ID. Required.
:param photo_id [string]: The photo’s ID. Required.
:return: [Tuple]: The Unsplash Collection and Photo
"""
url = "/collections/%s/remove" % collection_id
data = {
"collection_id": collection_id,
"photo_id": photo_id
}
result = self._delete(url, data=data) or {}
return CollectionModel.parse(result.get("collection")), PhotoModel.parse(result.get("photo")) | Remove a photo from one of the logged-in user’s collections.
Requires the 'write_collections' scope.
:param collection_id [string]: The collection’s ID. Required.
:param photo_id [string]: The photo’s ID. Required.
:return: [Tuple]: The Unsplash Collection and Photo | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L195-L210 |
yakupadakli/python-unsplash | unsplash/stat.py | Stat.total | def total(self):
"""
Get a list of counts for all of Unsplash
:return [Stat]: The Unsplash Stat.
"""
url = "/stats/total"
result = self._get(url)
return StatModel.parse(result) | python | def total(self):
"""
Get a list of counts for all of Unsplash
:return [Stat]: The Unsplash Stat.
"""
url = "/stats/total"
result = self._get(url)
return StatModel.parse(result) | Get a list of counts for all of Unsplash
:return [Stat]: The Unsplash Stat. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/stat.py#L11-L19 |
yakupadakli/python-unsplash | unsplash/stat.py | Stat.month | def month(self):
"""
Get the overall Unsplash stats for the past 30 days.
:return [Stat]: The Unsplash Stat.
"""
url = "/stats/month"
result = self._get(url)
return StatModel.parse(result) | python | def month(self):
"""
Get the overall Unsplash stats for the past 30 days.
:return [Stat]: The Unsplash Stat.
"""
url = "/stats/month"
result = self._get(url)
return StatModel.parse(result) | Get the overall Unsplash stats for the past 30 days.
:return [Stat]: The Unsplash Stat. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/stat.py#L21-L29 |
yakupadakli/python-unsplash | unsplash/auth.py | Auth.get_access_token | def get_access_token(self, code):
"""
Getting access token
:param code [string]: The authorization code supplied to the callback by Unsplash.
:return [string]: access token
"""
self.token = self.oauth.fetch_token(
token_url=self.access_token_url,
client_id=self.client_id,
client_secret=self.client_secret,
scope=self.scope,
code=code
)
return self.token.get("access_token") | python | def get_access_token(self, code):
"""
Getting access token
:param code [string]: The authorization code supplied to the callback by Unsplash.
:return [string]: access token
"""
self.token = self.oauth.fetch_token(
token_url=self.access_token_url,
client_id=self.client_id,
client_secret=self.client_secret,
scope=self.scope,
code=code
)
return self.token.get("access_token") | Getting access token
:param code [string]: The authorization code supplied to the callback by Unsplash.
:return [string]: access token | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/auth.py#L61-L74 |
yakupadakli/python-unsplash | unsplash/auth.py | Auth.refresh_token | def refresh_token(self):
"""
Refreshing the current expired access token
"""
self.token = self.oauth.refresh_token(self.access_token_url, refresh_token=self.get_refresh_token())
self.access_token = self.token.get("access_token") | python | def refresh_token(self):
"""
Refreshing the current expired access token
"""
self.token = self.oauth.refresh_token(self.access_token_url, refresh_token=self.get_refresh_token())
self.access_token = self.token.get("access_token") | Refreshing the current expired access token | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/auth.py#L83-L88 |
yakupadakli/python-unsplash | unsplash/models.py | Model.parse_list | def parse_list(cls, data):
"""Parse a list of JSON objects into a result set of model instances."""
results = ResultSet()
data = data or []
for obj in data:
if obj:
results.append(cls.parse(obj))
return results | python | def parse_list(cls, data):
"""Parse a list of JSON objects into a result set of model instances."""
results = ResultSet()
data = data or []
for obj in data:
if obj:
results.append(cls.parse(obj))
return results | Parse a list of JSON objects into a result set of model instances. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/models.py#L18-L25 |
yakupadakli/python-unsplash | unsplash/client.py | Client.get_auth_header | def get_auth_header(self):
"""
Getting the authorization header according to the authentication procedure
:return [dict]: Authorization header
"""
if self.api.is_authenticated:
return {"Authorization": "Bearer %s" % self.api.access_token}
return {"Authorization": "Client-ID %s" % self.api.client_id} | python | def get_auth_header(self):
"""
Getting the authorization header according to the authentication procedure
:return [dict]: Authorization header
"""
if self.api.is_authenticated:
return {"Authorization": "Bearer %s" % self.api.access_token}
return {"Authorization": "Client-ID %s" % self.api.client_id} | Getting the authorization header according to the authentication procedure
:return [dict]: Authorization header | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/client.py#L52-L60 |
yakupadakli/python-unsplash | unsplash/user.py | User.me | def me(self):
"""
Get the currently-logged in user.
Note: To access a user’s private data,
the user is required to authorize the 'read_user' scope.
Without it, this request will return a '403 Forbidden' response.
Note: Without a Bearer token (i.e. using a Client-ID token)
this request will return a '401 Unauthorized' response.
:return: [User]: The Unsplash User.
"""
url = "/me"
result = self._get(url)
return UserModel.parse(result) | python | def me(self):
"""
Get the currently-logged in user.
Note: To access a user’s private data,
the user is required to authorize the 'read_user' scope.
Without it, this request will return a '403 Forbidden' response.
Note: Without a Bearer token (i.e. using a Client-ID token)
this request will return a '401 Unauthorized' response.
:return: [User]: The Unsplash User.
"""
url = "/me"
result = self._get(url)
return UserModel.parse(result) | Get the currently-logged in user.
Note: To access a user’s private data,
the user is required to authorize the 'read_user' scope.
Without it, this request will return a '403 Forbidden' response.
Note: Without a Bearer token (i.e. using a Client-ID token)
this request will return a '401 Unauthorized' response.
:return: [User]: The Unsplash User. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/user.py#L25-L40 |
yakupadakli/python-unsplash | unsplash/user.py | User.update | def update(self, **kwargs):
"""
Update the currently-logged in user.
Note: This action requires the write_user scope.
Without it, it will return a 403 Forbidden response.
All parameters are optional.
:param username [string]: Username.
:param first_name [string]: First name.
:param last_name [string]: Last name.
:param email [string]: Email.
:param url [string]: Portfolio/personal URL.
:param location [string]: Location.
:param bio [string]: About/bio.
:param instagram_username [string]: Instagram username.
:return: [User]: The Unsplash User.
"""
url = "/me"
result = self._put(url, data=kwargs)
return UserModel.parse(result) | python | def update(self, **kwargs):
"""
Update the currently-logged in user.
Note: This action requires the write_user scope.
Without it, it will return a 403 Forbidden response.
All parameters are optional.
:param username [string]: Username.
:param first_name [string]: First name.
:param last_name [string]: Last name.
:param email [string]: Email.
:param url [string]: Portfolio/personal URL.
:param location [string]: Location.
:param bio [string]: About/bio.
:param instagram_username [string]: Instagram username.
:return: [User]: The Unsplash User.
"""
url = "/me"
result = self._put(url, data=kwargs)
return UserModel.parse(result) | Update the currently-logged in user.
Note: This action requires the write_user scope.
Without it, it will return a 403 Forbidden response.
All parameters are optional.
:param username [string]: Username.
:param first_name [string]: First name.
:param last_name [string]: Last name.
:param email [string]: Email.
:param url [string]: Portfolio/personal URL.
:param location [string]: Location.
:param bio [string]: About/bio.
:param instagram_username [string]: Instagram username.
:return: [User]: The Unsplash User. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/user.py#L42-L62 |
yakupadakli/python-unsplash | unsplash/user.py | User.get | def get(self, username, width=None, height=None):
"""
Retrieve public details on a given user.
Note: Supplying the optional w or h parameters will result
in the 'custom' photo URL being added to the 'profile_image' object:
:param username [string]: The user’s username. Required.
:param width [integer]: Profile image width in pixels.
:param height [integer]: Profile image height in pixels.
:return: [User]: The Unsplash User.
"""
url = "/users/{username}".format(username=username)
params = {
"w": width,
"h": height
}
result = self._get(url, params=params)
return UserModel.parse(result) | python | def get(self, username, width=None, height=None):
"""
Retrieve public details on a given user.
Note: Supplying the optional w or h parameters will result
in the 'custom' photo URL being added to the 'profile_image' object:
:param username [string]: The user’s username. Required.
:param width [integer]: Profile image width in pixels.
:param height [integer]: Profile image height in pixels.
:return: [User]: The Unsplash User.
"""
url = "/users/{username}".format(username=username)
params = {
"w": width,
"h": height
}
result = self._get(url, params=params)
return UserModel.parse(result) | Retrieve public details on a given user.
Note: Supplying the optional w or h parameters will result
in the 'custom' photo URL being added to the 'profile_image' object:
:param username [string]: The user’s username. Required.
:param width [integer]: Profile image width in pixels.
:param height [integer]: Profile image height in pixels.
:return: [User]: The Unsplash User. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/user.py#L64-L82 |
yakupadakli/python-unsplash | unsplash/user.py | User.portfolio | def portfolio(self, username):
"""
Retrieve a single user’s portfolio link.
:param username [string]: The user’s username. Required.
:return: [Link]: The Unsplash Link.
"""
url = "/users/{username}/portfolio".format(username=username)
result = self._get(url)
return LinkModel.parse(result) | python | def portfolio(self, username):
"""
Retrieve a single user’s portfolio link.
:param username [string]: The user’s username. Required.
:return: [Link]: The Unsplash Link.
"""
url = "/users/{username}/portfolio".format(username=username)
result = self._get(url)
return LinkModel.parse(result) | Retrieve a single user’s portfolio link.
:param username [string]: The user’s username. Required.
:return: [Link]: The Unsplash Link. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/user.py#L84-L93 |
yakupadakli/python-unsplash | unsplash/user.py | User.photos | def photos(self, username, page=1, per_page=10, order_by="latest"):
"""
Get a list of photos uploaded by a user.
:param username [string]: The user’s username. Required.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:param order_by [string]: How to sort the photos. Optional.
(Valid values: latest, oldest, popular; default: latest)
:return: [Array]: A single page of the Photo list.
"""
url = "/users/{username}/photos".format(username=username)
result = self._photos(url, username, page=page, per_page=per_page, order_by=order_by)
return PhotoModel.parse_list(result) | python | def photos(self, username, page=1, per_page=10, order_by="latest"):
"""
Get a list of photos uploaded by a user.
:param username [string]: The user’s username. Required.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:param order_by [string]: How to sort the photos. Optional.
(Valid values: latest, oldest, popular; default: latest)
:return: [Array]: A single page of the Photo list.
"""
url = "/users/{username}/photos".format(username=username)
result = self._photos(url, username, page=page, per_page=per_page, order_by=order_by)
return PhotoModel.parse_list(result) | Get a list of photos uploaded by a user.
:param username [string]: The user’s username. Required.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:param order_by [string]: How to sort the photos. Optional.
(Valid values: latest, oldest, popular; default: latest)
:return: [Array]: A single page of the Photo list. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/user.py#L105-L118 |
yakupadakli/python-unsplash | unsplash/user.py | User.collections | def collections(self, username, page=1, per_page=10):
"""
Get a list of collections created by the user.
:param username [string]: The user’s username. Required.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [Array]: A single page of the Collection list.
"""
url = "/users/{username}/collections".format(username=username)
params = {
"page": page,
"per_page": per_page
}
result = self._get(url, params=params)
return CollectionModel.parse_list(result) | python | def collections(self, username, page=1, per_page=10):
"""
Get a list of collections created by the user.
:param username [string]: The user’s username. Required.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [Array]: A single page of the Collection list.
"""
url = "/users/{username}/collections".format(username=username)
params = {
"page": page,
"per_page": per_page
}
result = self._get(url, params=params)
return CollectionModel.parse_list(result) | Get a list of collections created by the user.
:param username [string]: The user’s username. Required.
:param page [integer]: Page number to retrieve. (Optional; default: 1)
:param per_page [integer]: Number of items per page. (Optional; default: 10)
:return: [Array]: A single page of the Collection list. | https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/user.py#L135-L150 |
pri22296/beautifultable | beautifultable/ansi.py | ANSIMultiByteString.wrap | def wrap(self, width):
"""Returns a partition of the string based on `width`"""
res = []
prev_state = set()
part = []
cwidth = 0
for char, _width, state in zip(self._string, self._width, self._state):
if cwidth + _width > width:
if prev_state:
part.append(self.ANSI_RESET)
res.append("".join(part))
prev_state = set()
part = []
cwidth = 0
cwidth += _width
if prev_state == state:
pass
elif prev_state <= state:
part.extend(state - prev_state)
else:
part.append(self.ANSI_RESET)
part.extend(state)
prev_state = state
part.append(char)
if prev_state:
part.append(self.ANSI_RESET)
if part:
res.append("".join(part))
return res | python | def wrap(self, width):
"""Returns a partition of the string based on `width`"""
res = []
prev_state = set()
part = []
cwidth = 0
for char, _width, state in zip(self._string, self._width, self._state):
if cwidth + _width > width:
if prev_state:
part.append(self.ANSI_RESET)
res.append("".join(part))
prev_state = set()
part = []
cwidth = 0
cwidth += _width
if prev_state == state:
pass
elif prev_state <= state:
part.extend(state - prev_state)
else:
part.append(self.ANSI_RESET)
part.extend(state)
prev_state = state
part.append(char)
if prev_state:
part.append(self.ANSI_RESET)
if part:
res.append("".join(part))
return res | Returns a partition of the string based on `width` | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/ansi.py#L87-L115 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable.max_table_width | def max_table_width(self):
"""get/set the maximum width of the table.
The width of the table is guaranteed to not exceed this value. If it
is not possible to print a given table with the width provided, this
value will automatically adjust.
"""
offset = ((self._column_count - 1)
* termwidth(self.column_separator_char))
offset += termwidth(self.left_border_char)
offset += termwidth(self.right_border_char)
self._max_table_width = max(self._max_table_width,
offset + self._column_count)
return self._max_table_width | python | def max_table_width(self):
"""get/set the maximum width of the table.
The width of the table is guaranteed to not exceed this value. If it
is not possible to print a given table with the width provided, this
value will automatically adjust.
"""
offset = ((self._column_count - 1)
* termwidth(self.column_separator_char))
offset += termwidth(self.left_border_char)
offset += termwidth(self.right_border_char)
self._max_table_width = max(self._max_table_width,
offset + self._column_count)
return self._max_table_width | get/set the maximum width of the table.
The width of the table is guaranteed to not exceed this value. If it
is not possible to print a given table with the width provided, this
value will automatically adjust. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L401-L414 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable._initialize_table | def _initialize_table(self, column_count):
"""Sets the column count of the table.
This method is called to set the number of columns for the first time.
Parameters
----------
column_count : int
number of columns in the table
"""
header = [''] * column_count
alignment = [self.default_alignment] * column_count
width = [0] * column_count
padding = [self.default_padding] * column_count
self._column_count = column_count
self._column_headers = HeaderData(self, header)
self._column_alignments = AlignmentMetaData(self, alignment)
self._column_widths = PositiveIntegerMetaData(self, width)
self._left_padding_widths = PositiveIntegerMetaData(self, padding)
self._right_padding_widths = PositiveIntegerMetaData(self, padding) | python | def _initialize_table(self, column_count):
"""Sets the column count of the table.
This method is called to set the number of columns for the first time.
Parameters
----------
column_count : int
number of columns in the table
"""
header = [''] * column_count
alignment = [self.default_alignment] * column_count
width = [0] * column_count
padding = [self.default_padding] * column_count
self._column_count = column_count
self._column_headers = HeaderData(self, header)
self._column_alignments = AlignmentMetaData(self, alignment)
self._column_widths = PositiveIntegerMetaData(self, width)
self._left_padding_widths = PositiveIntegerMetaData(self, padding)
self._right_padding_widths = PositiveIntegerMetaData(self, padding) | Sets the column count of the table.
This method is called to set the number of columns for the first time.
Parameters
----------
column_count : int
number of columns in the table | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L422-L442 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable.set_style | def set_style(self, style):
"""Set the style of the table from a predefined set of styles.
Parameters
----------
style: Style
It can be one of the following:
* beautifulTable.STYLE_DEFAULT
* beautifultable.STYLE_NONE
* beautifulTable.STYLE_DOTTED
* beautifulTable.STYLE_MYSQL
* beautifulTable.STYLE_SEPARATED
* beautifulTable.STYLE_COMPACT
* beautifulTable.STYLE_MARKDOWN
* beautifulTable.STYLE_RESTRUCTURED_TEXT
* beautifultable.STYLE_BOX
* beautifultable.STYLE_BOX_DOUBLED
* beautifultable.STYLE_BOX_ROUNDED
* beautifultable.STYLE_GRID
"""
if not isinstance(style, enums.Style):
allowed = ("{}.{}".format(type(self).__name__, i.name)
for i in enums.Style)
error_msg = ("allowed values for style are: "
+ ', '.join(allowed))
raise ValueError(error_msg)
style_template = style.value
self.left_border_char = style_template.left_border_char
self.right_border_char = style_template.right_border_char
self.top_border_char = style_template.top_border_char
self.bottom_border_char = style_template.bottom_border_char
self.header_separator_char = style_template.header_separator_char
self.column_separator_char = style_template.column_separator_char
self.row_separator_char = style_template.row_separator_char
self.intersect_top_left = style_template.intersect_top_left
self.intersect_top_mid = style_template.intersect_top_mid
self.intersect_top_right = style_template.intersect_top_right
self.intersect_header_left = style_template.intersect_header_left
self.intersect_header_mid = style_template.intersect_header_mid
self.intersect_header_right = style_template.intersect_header_right
self.intersect_row_left = style_template.intersect_row_left
self.intersect_row_mid = style_template.intersect_row_mid
self.intersect_row_right = style_template.intersect_row_right
self.intersect_bottom_left = style_template.intersect_bottom_left
self.intersect_bottom_mid = style_template.intersect_bottom_mid
self.intersect_bottom_right = style_template.intersect_bottom_right | python | def set_style(self, style):
"""Set the style of the table from a predefined set of styles.
Parameters
----------
style: Style
It can be one of the following:
* beautifulTable.STYLE_DEFAULT
* beautifultable.STYLE_NONE
* beautifulTable.STYLE_DOTTED
* beautifulTable.STYLE_MYSQL
* beautifulTable.STYLE_SEPARATED
* beautifulTable.STYLE_COMPACT
* beautifulTable.STYLE_MARKDOWN
* beautifulTable.STYLE_RESTRUCTURED_TEXT
* beautifultable.STYLE_BOX
* beautifultable.STYLE_BOX_DOUBLED
* beautifultable.STYLE_BOX_ROUNDED
* beautifultable.STYLE_GRID
"""
if not isinstance(style, enums.Style):
allowed = ("{}.{}".format(type(self).__name__, i.name)
for i in enums.Style)
error_msg = ("allowed values for style are: "
+ ', '.join(allowed))
raise ValueError(error_msg)
style_template = style.value
self.left_border_char = style_template.left_border_char
self.right_border_char = style_template.right_border_char
self.top_border_char = style_template.top_border_char
self.bottom_border_char = style_template.bottom_border_char
self.header_separator_char = style_template.header_separator_char
self.column_separator_char = style_template.column_separator_char
self.row_separator_char = style_template.row_separator_char
self.intersect_top_left = style_template.intersect_top_left
self.intersect_top_mid = style_template.intersect_top_mid
self.intersect_top_right = style_template.intersect_top_right
self.intersect_header_left = style_template.intersect_header_left
self.intersect_header_mid = style_template.intersect_header_mid
self.intersect_header_right = style_template.intersect_header_right
self.intersect_row_left = style_template.intersect_row_left
self.intersect_row_mid = style_template.intersect_row_mid
self.intersect_row_right = style_template.intersect_row_right
self.intersect_bottom_left = style_template.intersect_bottom_left
self.intersect_bottom_mid = style_template.intersect_bottom_mid
self.intersect_bottom_right = style_template.intersect_bottom_right | Set the style of the table from a predefined set of styles.
Parameters
----------
style: Style
It can be one of the following:
* beautifulTable.STYLE_DEFAULT
* beautifultable.STYLE_NONE
* beautifulTable.STYLE_DOTTED
* beautifulTable.STYLE_MYSQL
* beautifulTable.STYLE_SEPARATED
* beautifulTable.STYLE_COMPACT
* beautifulTable.STYLE_MARKDOWN
* beautifulTable.STYLE_RESTRUCTURED_TEXT
* beautifultable.STYLE_BOX
* beautifultable.STYLE_BOX_DOUBLED
* beautifultable.STYLE_BOX_ROUNDED
* beautifultable.STYLE_GRID | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L580-L627 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable._calculate_column_widths | def _calculate_column_widths(self):
"""Calculate width of column automatically based on data."""
table_width = self.get_table_width()
lpw, rpw = self._left_padding_widths, self._right_padding_widths
pad_widths = [(lpw[i] + rpw[i]) for i in range(self._column_count)]
max_widths = [0 for index in range(self._column_count)]
offset = table_width - sum(self._column_widths) + sum(pad_widths)
self._max_table_width = max(self._max_table_width,
offset + self._column_count)
for index, column in enumerate(zip(*self._table)):
max_length = 0
for i in column:
for j in to_unicode(i).split('\n'):
output_str = get_output_str(j, self.detect_numerics,
self.numeric_precision,
self.sign_mode.value)
max_length = max(max_length, termwidth(output_str))
for i in to_unicode(self._column_headers[index]).split('\n'):
output_str = get_output_str(i, self.detect_numerics,
self.numeric_precision,
self.sign_mode.value)
max_length = max(max_length, termwidth(output_str))
max_widths[index] += max_length
sum_ = sum(max_widths)
desired_sum = self._max_table_width - offset
# Set flag for columns who are within their fair share
temp_sum = 0
flag = [0] * len(max_widths)
for i, width in enumerate(max_widths):
if width <= int(desired_sum / self._column_count):
temp_sum += width
flag[i] = 1
else:
# Allocate atleast 1 character width to the column
temp_sum += 1
avail_space = desired_sum - temp_sum
actual_space = sum_ - temp_sum
shrinked_columns = {}
# Columns which exceed their fair share should be shrinked based on
# how much space is left for the table
for i, width in enumerate(max_widths):
self.column_widths[i] = width
if not flag[i]:
new_width = 1 + int((width-1) * avail_space / actual_space)
if new_width < width:
self.column_widths[i] = new_width
shrinked_columns[new_width] = i
# Divide any remaining space among shrinked columns
if shrinked_columns:
extra = (self._max_table_width
- offset
- sum(self.column_widths))
actual_space = sum(shrinked_columns)
if extra > 0:
for i, width in enumerate(sorted(shrinked_columns)):
index = shrinked_columns[width]
extra_width = int(width * extra / actual_space)
self.column_widths[i] += extra_width
if i == (len(shrinked_columns) - 1):
extra = (self._max_table_width
- offset
- sum(self.column_widths))
self.column_widths[index] += extra
for i in range(self.column_count):
self.column_widths[i] += pad_widths[i] | python | def _calculate_column_widths(self):
"""Calculate width of column automatically based on data."""
table_width = self.get_table_width()
lpw, rpw = self._left_padding_widths, self._right_padding_widths
pad_widths = [(lpw[i] + rpw[i]) for i in range(self._column_count)]
max_widths = [0 for index in range(self._column_count)]
offset = table_width - sum(self._column_widths) + sum(pad_widths)
self._max_table_width = max(self._max_table_width,
offset + self._column_count)
for index, column in enumerate(zip(*self._table)):
max_length = 0
for i in column:
for j in to_unicode(i).split('\n'):
output_str = get_output_str(j, self.detect_numerics,
self.numeric_precision,
self.sign_mode.value)
max_length = max(max_length, termwidth(output_str))
for i in to_unicode(self._column_headers[index]).split('\n'):
output_str = get_output_str(i, self.detect_numerics,
self.numeric_precision,
self.sign_mode.value)
max_length = max(max_length, termwidth(output_str))
max_widths[index] += max_length
sum_ = sum(max_widths)
desired_sum = self._max_table_width - offset
# Set flag for columns who are within their fair share
temp_sum = 0
flag = [0] * len(max_widths)
for i, width in enumerate(max_widths):
if width <= int(desired_sum / self._column_count):
temp_sum += width
flag[i] = 1
else:
# Allocate atleast 1 character width to the column
temp_sum += 1
avail_space = desired_sum - temp_sum
actual_space = sum_ - temp_sum
shrinked_columns = {}
# Columns which exceed their fair share should be shrinked based on
# how much space is left for the table
for i, width in enumerate(max_widths):
self.column_widths[i] = width
if not flag[i]:
new_width = 1 + int((width-1) * avail_space / actual_space)
if new_width < width:
self.column_widths[i] = new_width
shrinked_columns[new_width] = i
# Divide any remaining space among shrinked columns
if shrinked_columns:
extra = (self._max_table_width
- offset
- sum(self.column_widths))
actual_space = sum(shrinked_columns)
if extra > 0:
for i, width in enumerate(sorted(shrinked_columns)):
index = shrinked_columns[width]
extra_width = int(width * extra / actual_space)
self.column_widths[i] += extra_width
if i == (len(shrinked_columns) - 1):
extra = (self._max_table_width
- offset
- sum(self.column_widths))
self.column_widths[index] += extra
for i in range(self.column_count):
self.column_widths[i] += pad_widths[i] | Calculate width of column automatically based on data. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L629-L701 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable.sort | def sort(self, key, reverse=False):
"""Stable sort of the table *IN-PLACE* with respect to a column.
Parameters
----------
key: int, str
index or header of the column. Normal list rules apply.
reverse : bool
If `True` then table is sorted as if each comparison was reversed.
"""
if isinstance(key, int):
index = key
elif isinstance(key, basestring):
index = self.get_column_index(key)
else:
raise TypeError("'key' must either be 'int' or 'str'")
self._table.sort(key=operator.itemgetter(index), reverse=reverse) | python | def sort(self, key, reverse=False):
"""Stable sort of the table *IN-PLACE* with respect to a column.
Parameters
----------
key: int, str
index or header of the column. Normal list rules apply.
reverse : bool
If `True` then table is sorted as if each comparison was reversed.
"""
if isinstance(key, int):
index = key
elif isinstance(key, basestring):
index = self.get_column_index(key)
else:
raise TypeError("'key' must either be 'int' or 'str'")
self._table.sort(key=operator.itemgetter(index), reverse=reverse) | Stable sort of the table *IN-PLACE* with respect to a column.
Parameters
----------
key: int, str
index or header of the column. Normal list rules apply.
reverse : bool
If `True` then table is sorted as if each comparison was reversed. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L718-L734 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable.get_column_index | def get_column_index(self, header):
"""Get index of a column from it's header.
Parameters
----------
header: str
header of the column.
Raises
------
ValueError:
If no column could be found corresponding to `header`.
"""
try:
index = self._column_headers.index(header)
return index
except ValueError:
raise_suppressed(KeyError(("'{}' is not a header for any "
"column").format(header))) | python | def get_column_index(self, header):
"""Get index of a column from it's header.
Parameters
----------
header: str
header of the column.
Raises
------
ValueError:
If no column could be found corresponding to `header`.
"""
try:
index = self._column_headers.index(header)
return index
except ValueError:
raise_suppressed(KeyError(("'{}' is not a header for any "
"column").format(header))) | Get index of a column from it's header.
Parameters
----------
header: str
header of the column.
Raises
------
ValueError:
If no column could be found corresponding to `header`. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L756-L774 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable.get_column | def get_column(self, key):
"""Return an iterator to a column.
Parameters
----------
key : int, str
index of the column, or the header of the column.
If index is specified, then normal list rules apply.
Raises
------
TypeError:
If key is not of type `int`, or `str`.
Returns
-------
iter:
Iterator to the specified column.
"""
if isinstance(key, int):
index = key
elif isinstance(key, basestring):
index = self.get_column_index(key)
else:
raise TypeError(("key must be an int or str, "
"not {}").format(type(key).__name__))
return iter(map(operator.itemgetter(index), self._table)) | python | def get_column(self, key):
"""Return an iterator to a column.
Parameters
----------
key : int, str
index of the column, or the header of the column.
If index is specified, then normal list rules apply.
Raises
------
TypeError:
If key is not of type `int`, or `str`.
Returns
-------
iter:
Iterator to the specified column.
"""
if isinstance(key, int):
index = key
elif isinstance(key, basestring):
index = self.get_column_index(key)
else:
raise TypeError(("key must be an int or str, "
"not {}").format(type(key).__name__))
return iter(map(operator.itemgetter(index), self._table)) | Return an iterator to a column.
Parameters
----------
key : int, str
index of the column, or the header of the column.
If index is specified, then normal list rules apply.
Raises
------
TypeError:
If key is not of type `int`, or `str`.
Returns
-------
iter:
Iterator to the specified column. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L776-L802 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable.pop_column | def pop_column(self, index=-1):
"""Remove and return row at index (default last).
Parameters
----------
index : int, str
index of the column, or the header of the column.
If index is specified, then normal list rules apply.
Raises
------
TypeError:
If index is not an instance of `int`, or `str`.
IndexError:
If Table is empty.
"""
if isinstance(index, int):
pass
elif isinstance(index, basestring):
index = self.get_column_index(index)
else:
raise TypeError(("column index must be an integer or a string, "
"not {}").format(type(index).__name__))
if self._column_count == 0:
raise IndexError("pop from empty table")
if self._column_count == 1:
# This is the last column. So we should clear the table to avoid
# empty rows
self.clear(clear_metadata=True)
else:
# Not the last column. safe to pop from row
self._column_count -= 1
self._column_alignments._pop(index)
self._column_widths._pop(index)
self._left_padding_widths._pop(index)
self._right_padding_widths._pop(index)
self._column_headers._pop(index)
for row in self._table:
row._pop(index) | python | def pop_column(self, index=-1):
"""Remove and return row at index (default last).
Parameters
----------
index : int, str
index of the column, or the header of the column.
If index is specified, then normal list rules apply.
Raises
------
TypeError:
If index is not an instance of `int`, or `str`.
IndexError:
If Table is empty.
"""
if isinstance(index, int):
pass
elif isinstance(index, basestring):
index = self.get_column_index(index)
else:
raise TypeError(("column index must be an integer or a string, "
"not {}").format(type(index).__name__))
if self._column_count == 0:
raise IndexError("pop from empty table")
if self._column_count == 1:
# This is the last column. So we should clear the table to avoid
# empty rows
self.clear(clear_metadata=True)
else:
# Not the last column. safe to pop from row
self._column_count -= 1
self._column_alignments._pop(index)
self._column_widths._pop(index)
self._left_padding_widths._pop(index)
self._right_padding_widths._pop(index)
self._column_headers._pop(index)
for row in self._table:
row._pop(index) | Remove and return row at index (default last).
Parameters
----------
index : int, str
index of the column, or the header of the column.
If index is specified, then normal list rules apply.
Raises
------
TypeError:
If index is not an instance of `int`, or `str`.
IndexError:
If Table is empty. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L819-L858 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable.insert_row | def insert_row(self, index, row):
"""Insert a row before index in the table.
Parameters
----------
index : int
List index rules apply
row : iterable
Any iterable of appropriate length.
Raises
------
TypeError:
If `row` is not an iterable.
ValueError:
If size of `row` is inconsistent with the current number
of columns.
"""
row = self._validate_row(row)
row_obj = RowData(self, row)
self._table.insert(index, row_obj) | python | def insert_row(self, index, row):
"""Insert a row before index in the table.
Parameters
----------
index : int
List index rules apply
row : iterable
Any iterable of appropriate length.
Raises
------
TypeError:
If `row` is not an iterable.
ValueError:
If size of `row` is inconsistent with the current number
of columns.
"""
row = self._validate_row(row)
row_obj = RowData(self, row)
self._table.insert(index, row_obj) | Insert a row before index in the table.
Parameters
----------
index : int
List index rules apply
row : iterable
Any iterable of appropriate length.
Raises
------
TypeError:
If `row` is not an iterable.
ValueError:
If size of `row` is inconsistent with the current number
of columns. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L860-L882 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable.update_row | def update_row(self, key, value):
"""Update a column named `header` in the table.
If length of column is smaller than number of rows, lets say
`k`, only the first `k` values in the column is updated.
Parameters
----------
key : int or slice
index of the row, or a slice object.
value : iterable
If an index is specified, `value` should be an iterable
of appropriate length. Instead if a slice object is
passed as key, value should be an iterable of rows.
Raises
------
IndexError:
If index specified is out of range.
TypeError:
If `value` is of incorrect type.
ValueError:
If length of row does not matches number of columns.
"""
if isinstance(key, int):
row = self._validate_row(value, init_table_if_required=False)
row_obj = RowData(self, row)
self._table[key] = row_obj
elif isinstance(key, slice):
row_obj_list = []
for row in value:
row_ = self._validate_row(row, init_table_if_required=True)
row_obj_list.append(RowData(self, row_))
self._table[key] = row_obj_list
else:
raise TypeError("key must be an integer or a slice object") | python | def update_row(self, key, value):
"""Update a column named `header` in the table.
If length of column is smaller than number of rows, lets say
`k`, only the first `k` values in the column is updated.
Parameters
----------
key : int or slice
index of the row, or a slice object.
value : iterable
If an index is specified, `value` should be an iterable
of appropriate length. Instead if a slice object is
passed as key, value should be an iterable of rows.
Raises
------
IndexError:
If index specified is out of range.
TypeError:
If `value` is of incorrect type.
ValueError:
If length of row does not matches number of columns.
"""
if isinstance(key, int):
row = self._validate_row(value, init_table_if_required=False)
row_obj = RowData(self, row)
self._table[key] = row_obj
elif isinstance(key, slice):
row_obj_list = []
for row in value:
row_ = self._validate_row(row, init_table_if_required=True)
row_obj_list.append(RowData(self, row_))
self._table[key] = row_obj_list
else:
raise TypeError("key must be an integer or a slice object") | Update a column named `header` in the table.
If length of column is smaller than number of rows, lets say
`k`, only the first `k` values in the column is updated.
Parameters
----------
key : int or slice
index of the row, or a slice object.
value : iterable
If an index is specified, `value` should be an iterable
of appropriate length. Instead if a slice object is
passed as key, value should be an iterable of rows.
Raises
------
IndexError:
If index specified is out of range.
TypeError:
If `value` is of incorrect type.
ValueError:
If length of row does not matches number of columns. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L895-L933 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable.update_column | def update_column(self, header, column):
"""Update a column named `header` in the table.
If length of column is smaller than number of rows, lets say
`k`, only the first `k` values in the column is updated.
Parameters
----------
header : str
Header of the column
column : iterable
Any iterable of appropriate length.
Raises
------
TypeError:
If length of `column` is shorter than number of rows.
ValueError:
If no column exists with title `header`.
"""
index = self.get_column_index(header)
if not isinstance(header, basestring):
raise TypeError("header must be of type str")
for row, new_item in zip(self._table, column):
row[index] = new_item | python | def update_column(self, header, column):
"""Update a column named `header` in the table.
If length of column is smaller than number of rows, lets say
`k`, only the first `k` values in the column is updated.
Parameters
----------
header : str
Header of the column
column : iterable
Any iterable of appropriate length.
Raises
------
TypeError:
If length of `column` is shorter than number of rows.
ValueError:
If no column exists with title `header`.
"""
index = self.get_column_index(header)
if not isinstance(header, basestring):
raise TypeError("header must be of type str")
for row, new_item in zip(self._table, column):
row[index] = new_item | Update a column named `header` in the table.
If length of column is smaller than number of rows, lets say
`k`, only the first `k` values in the column is updated.
Parameters
----------
header : str
Header of the column
column : iterable
Any iterable of appropriate length.
Raises
------
TypeError:
If length of `column` is shorter than number of rows.
ValueError:
If no column exists with title `header`. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L935-L961 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable.insert_column | def insert_column(self, index, header, column):
"""Insert a column before `index` in the table.
If length of column is bigger than number of rows, lets say
`k`, only the first `k` values of `column` is considered.
If column is shorter than 'k', ValueError is raised.
Note that Table remains in consistent state even if column
is too short. Any changes made by this method is rolled back
before raising the exception.
Parameters
----------
index : int
List index rules apply.
header : str
Title of the column.
column : iterable
Any iterable of appropriate length.
Raises
------
TypeError:
If `header` is not of type `str`.
ValueError:
If length of `column` is shorter than number of rows.
"""
if self._column_count == 0:
self.column_headers = HeaderData(self, [header])
self._table = [RowData(self, [i]) for i in column]
else:
if not isinstance(header, basestring):
raise TypeError("header must be of type str")
column_length = 0
for i, (row, new_item) in enumerate(zip(self._table, column)):
row._insert(index, new_item)
column_length = i
if column_length == len(self._table) - 1:
self._column_count += 1
self._column_headers._insert(index, header)
self._column_alignments._insert(index, self.default_alignment)
self._column_widths._insert(index, 0)
self._left_padding_widths._insert(index, self.default_padding)
self._right_padding_widths._insert(index, self.default_padding)
else:
# Roll back changes so that table remains in consistent state
for j in range(column_length, -1, -1):
self._table[j]._pop(index)
raise ValueError(("length of 'column' should be atleast {}, "
"got {}").format(len(self._table),
column_length + 1)) | python | def insert_column(self, index, header, column):
"""Insert a column before `index` in the table.
If length of column is bigger than number of rows, lets say
`k`, only the first `k` values of `column` is considered.
If column is shorter than 'k', ValueError is raised.
Note that Table remains in consistent state even if column
is too short. Any changes made by this method is rolled back
before raising the exception.
Parameters
----------
index : int
List index rules apply.
header : str
Title of the column.
column : iterable
Any iterable of appropriate length.
Raises
------
TypeError:
If `header` is not of type `str`.
ValueError:
If length of `column` is shorter than number of rows.
"""
if self._column_count == 0:
self.column_headers = HeaderData(self, [header])
self._table = [RowData(self, [i]) for i in column]
else:
if not isinstance(header, basestring):
raise TypeError("header must be of type str")
column_length = 0
for i, (row, new_item) in enumerate(zip(self._table, column)):
row._insert(index, new_item)
column_length = i
if column_length == len(self._table) - 1:
self._column_count += 1
self._column_headers._insert(index, header)
self._column_alignments._insert(index, self.default_alignment)
self._column_widths._insert(index, 0)
self._left_padding_widths._insert(index, self.default_padding)
self._right_padding_widths._insert(index, self.default_padding)
else:
# Roll back changes so that table remains in consistent state
for j in range(column_length, -1, -1):
self._table[j]._pop(index)
raise ValueError(("length of 'column' should be atleast {}, "
"got {}").format(len(self._table),
column_length + 1)) | Insert a column before `index` in the table.
If length of column is bigger than number of rows, lets say
`k`, only the first `k` values of `column` is considered.
If column is shorter than 'k', ValueError is raised.
Note that Table remains in consistent state even if column
is too short. Any changes made by this method is rolled back
before raising the exception.
Parameters
----------
index : int
List index rules apply.
header : str
Title of the column.
column : iterable
Any iterable of appropriate length.
Raises
------
TypeError:
If `header` is not of type `str`.
ValueError:
If length of `column` is shorter than number of rows. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L963-L1016 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable.append_column | def append_column(self, header, column):
"""Append a column to end of the table.
Parameters
----------
header : str
Title of the column
column : iterable
Any iterable of appropriate length.
"""
self.insert_column(self._column_count, header, column) | python | def append_column(self, header, column):
"""Append a column to end of the table.
Parameters
----------
header : str
Title of the column
column : iterable
Any iterable of appropriate length.
"""
self.insert_column(self._column_count, header, column) | Append a column to end of the table.
Parameters
----------
header : str
Title of the column
column : iterable
Any iterable of appropriate length. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L1018-L1029 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable._get_horizontal_line | def _get_horizontal_line(self, char, intersect_left,
intersect_mid, intersect_right):
"""Get a horizontal line for the table.
Internal method used to actually get all horizontal lines in the table.
Column width should be set prior to calling this method. This method
detects intersection and handles it according to the values of
`intersect_*_*` attributes.
Parameters
----------
char : str
Character used to draw the line.
Returns
-------
str
String which will be printed as the Top border of the table.
"""
width = self.get_table_width()
try:
line = list(char * (int(width/termwidth(char)) + 1))[:width]
except ZeroDivisionError:
line = [' '] * width
if len(line) == 0:
return ''
# Only if Special Intersection is enabled and horizontal line is
# visible
if not char.isspace():
# If left border is enabled and it is visible
visible_junc = not intersect_left.isspace()
if termwidth(self.left_border_char) > 0:
if not (self.left_border_char.isspace() and visible_junc):
length = min(termwidth(self.left_border_char),
termwidth(intersect_left))
for i in range(length):
line[i] = intersect_left[i]
visible_junc = not intersect_right.isspace()
# If right border is enabled and it is visible
if termwidth(self.right_border_char) > 0:
if not (self.right_border_char.isspace() and visible_junc):
length = min(termwidth(self.right_border_char),
termwidth(intersect_right))
for i in range(length):
line[-i-1] = intersect_right[-i-1]
visible_junc = not intersect_mid.isspace()
# If column separator is enabled and it is visible
if termwidth(self.column_separator_char):
if not (self.column_separator_char.isspace() and visible_junc):
index = termwidth(self.left_border_char)
for i in range(self._column_count-1):
index += (self._column_widths[i])
length = min(termwidth(self.column_separator_char),
termwidth(intersect_mid))
for i in range(length):
line[index+i] = intersect_mid[i]
index += termwidth(self.column_separator_char)
return ''.join(line) | python | def _get_horizontal_line(self, char, intersect_left,
intersect_mid, intersect_right):
"""Get a horizontal line for the table.
Internal method used to actually get all horizontal lines in the table.
Column width should be set prior to calling this method. This method
detects intersection and handles it according to the values of
`intersect_*_*` attributes.
Parameters
----------
char : str
Character used to draw the line.
Returns
-------
str
String which will be printed as the Top border of the table.
"""
width = self.get_table_width()
try:
line = list(char * (int(width/termwidth(char)) + 1))[:width]
except ZeroDivisionError:
line = [' '] * width
if len(line) == 0:
return ''
# Only if Special Intersection is enabled and horizontal line is
# visible
if not char.isspace():
# If left border is enabled and it is visible
visible_junc = not intersect_left.isspace()
if termwidth(self.left_border_char) > 0:
if not (self.left_border_char.isspace() and visible_junc):
length = min(termwidth(self.left_border_char),
termwidth(intersect_left))
for i in range(length):
line[i] = intersect_left[i]
visible_junc = not intersect_right.isspace()
# If right border is enabled and it is visible
if termwidth(self.right_border_char) > 0:
if not (self.right_border_char.isspace() and visible_junc):
length = min(termwidth(self.right_border_char),
termwidth(intersect_right))
for i in range(length):
line[-i-1] = intersect_right[-i-1]
visible_junc = not intersect_mid.isspace()
# If column separator is enabled and it is visible
if termwidth(self.column_separator_char):
if not (self.column_separator_char.isspace() and visible_junc):
index = termwidth(self.left_border_char)
for i in range(self._column_count-1):
index += (self._column_widths[i])
length = min(termwidth(self.column_separator_char),
termwidth(intersect_mid))
for i in range(length):
line[index+i] = intersect_mid[i]
index += termwidth(self.column_separator_char)
return ''.join(line) | Get a horizontal line for the table.
Internal method used to actually get all horizontal lines in the table.
Column width should be set prior to calling this method. This method
detects intersection and handles it according to the values of
`intersect_*_*` attributes.
Parameters
----------
char : str
Character used to draw the line.
Returns
-------
str
String which will be printed as the Top border of the table. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L1049-L1110 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable.get_table_width | def get_table_width(self):
"""Get the width of the table as number of characters.
Column width should be set prior to calling this method.
Returns
-------
int
Width of the table as number of characters.
"""
if self.column_count == 0:
return 0
width = sum(self._column_widths)
width += ((self._column_count - 1)
* termwidth(self.column_separator_char))
width += termwidth(self.left_border_char)
width += termwidth(self.right_border_char)
return width | python | def get_table_width(self):
"""Get the width of the table as number of characters.
Column width should be set prior to calling this method.
Returns
-------
int
Width of the table as number of characters.
"""
if self.column_count == 0:
return 0
width = sum(self._column_widths)
width += ((self._column_count - 1)
* termwidth(self.column_separator_char))
width += termwidth(self.left_border_char)
width += termwidth(self.right_border_char)
return width | Get the width of the table as number of characters.
Column width should be set prior to calling this method.
Returns
-------
int
Width of the table as number of characters. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L1188-L1205 |
pri22296/beautifultable | beautifultable/beautifultable.py | BeautifulTable.get_string | def get_string(self, recalculate_width=True):
"""Get the table as a String.
Parameters
----------
recalculate_width : bool, optional
If width for each column should be recalculated(default True).
Note that width is always calculated if it wasn't set
explicitly when this method is called for the first time ,
regardless of the value of `recalculate_width`.
Returns
-------
str:
Table as a string.
"""
# Empty table. returning empty string.
if len(self._table) == 0:
return ''
if self.serialno and self.column_count > 0:
self.insert_column(0, self.serialno_header,
range(1, len(self) + 1))
# Should widths of column be recalculated
if recalculate_width or sum(self._column_widths) == 0:
self._calculate_column_widths()
string_ = []
# Drawing the top border
if self.top_border_char:
string_.append(
self._get_top_border())
# Print headers if not empty or only spaces
if ''.join(self._column_headers).strip():
headers = to_unicode(self._column_headers)
string_.append(headers)
if self.header_separator_char:
string_.append(
self._get_header_separator())
# Printing rows
first_row_encountered = False
for row in self._table:
if first_row_encountered and self.row_separator_char:
string_.append(
self._get_row_separator())
first_row_encountered = True
content = to_unicode(row)
string_.append(content)
# Drawing the bottom border
if self.bottom_border_char:
string_.append(
self._get_bottom_border())
if self.serialno and self.column_count > 0:
self.pop_column(0)
return '\n'.join(string_) | python | def get_string(self, recalculate_width=True):
"""Get the table as a String.
Parameters
----------
recalculate_width : bool, optional
If width for each column should be recalculated(default True).
Note that width is always calculated if it wasn't set
explicitly when this method is called for the first time ,
regardless of the value of `recalculate_width`.
Returns
-------
str:
Table as a string.
"""
# Empty table. returning empty string.
if len(self._table) == 0:
return ''
if self.serialno and self.column_count > 0:
self.insert_column(0, self.serialno_header,
range(1, len(self) + 1))
# Should widths of column be recalculated
if recalculate_width or sum(self._column_widths) == 0:
self._calculate_column_widths()
string_ = []
# Drawing the top border
if self.top_border_char:
string_.append(
self._get_top_border())
# Print headers if not empty or only spaces
if ''.join(self._column_headers).strip():
headers = to_unicode(self._column_headers)
string_.append(headers)
if self.header_separator_char:
string_.append(
self._get_header_separator())
# Printing rows
first_row_encountered = False
for row in self._table:
if first_row_encountered and self.row_separator_char:
string_.append(
self._get_row_separator())
first_row_encountered = True
content = to_unicode(row)
string_.append(content)
# Drawing the bottom border
if self.bottom_border_char:
string_.append(
self._get_bottom_border())
if self.serialno and self.column_count > 0:
self.pop_column(0)
return '\n'.join(string_) | Get the table as a String.
Parameters
----------
recalculate_width : bool, optional
If width for each column should be recalculated(default True).
Note that width is always calculated if it wasn't set
explicitly when this method is called for the first time ,
regardless of the value of `recalculate_width`.
Returns
-------
str:
Table as a string. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/beautifultable.py#L1207-L1269 |
pri22296/beautifultable | beautifultable/utils.py | _convert_to_numeric | def _convert_to_numeric(item):
"""
Helper method to convert a string to float or int if possible.
If the conversion is not possible, it simply returns the string.
"""
if PY3:
num_types = (int, float)
else: # pragma: no cover
num_types = (int, long, float) # noqa: F821
# We don't wan't to perform any conversions if item is already a number
if isinstance(item, num_types):
return item
# First try for an int conversion so that strings like "5" are converted
# to 5 instead of 5.0 . This is safe as a direct int cast for a non integer
# string raises a ValueError.
try:
num = int(to_unicode(item))
except ValueError:
try:
num = float(to_unicode(item))
except ValueError:
return item
else:
return num
except TypeError:
return item
else:
return num | python | def _convert_to_numeric(item):
"""
Helper method to convert a string to float or int if possible.
If the conversion is not possible, it simply returns the string.
"""
if PY3:
num_types = (int, float)
else: # pragma: no cover
num_types = (int, long, float) # noqa: F821
# We don't wan't to perform any conversions if item is already a number
if isinstance(item, num_types):
return item
# First try for an int conversion so that strings like "5" are converted
# to 5 instead of 5.0 . This is safe as a direct int cast for a non integer
# string raises a ValueError.
try:
num = int(to_unicode(item))
except ValueError:
try:
num = float(to_unicode(item))
except ValueError:
return item
else:
return num
except TypeError:
return item
else:
return num | Helper method to convert a string to float or int if possible.
If the conversion is not possible, it simply returns the string. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/utils.py#L11-L40 |
pri22296/beautifultable | beautifultable/utils.py | get_output_str | def get_output_str(item, detect_numerics, precision, sign_value):
"""Returns the final string which should be displayed"""
if detect_numerics:
item = _convert_to_numeric(item)
if isinstance(item, float):
item = round(item, precision)
try:
item = '{:{sign}}'.format(item, sign=sign_value)
except (ValueError, TypeError):
pass
return to_unicode(item) | python | def get_output_str(item, detect_numerics, precision, sign_value):
"""Returns the final string which should be displayed"""
if detect_numerics:
item = _convert_to_numeric(item)
if isinstance(item, float):
item = round(item, precision)
try:
item = '{:{sign}}'.format(item, sign=sign_value)
except (ValueError, TypeError):
pass
return to_unicode(item) | Returns the final string which should be displayed | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/utils.py#L43-L53 |
pri22296/beautifultable | beautifultable/rows.py | RowData._get_row_within_width | def _get_row_within_width(self, row):
"""Process a row so that it is clamped by column_width.
Parameters
----------
row : array_like
A single row.
Returns
-------
list of list:
List representation of the `row` after it has been processed
according to width exceed policy.
"""
table = self._table
lpw, rpw = table.left_padding_widths, table.right_padding_widths
wep = table.width_exceed_policy
list_of_rows = []
if (wep is WidthExceedPolicy.WEP_STRIP or
wep is WidthExceedPolicy.WEP_ELLIPSIS):
# Let's strip the row
delimiter = '' if wep is WidthExceedPolicy.WEP_STRIP else '...'
row_item_list = []
for index, row_item in enumerate(row):
left_pad = table._column_pad * lpw[index]
right_pad = table._column_pad * rpw[index]
clmp_str = (left_pad
+ self._clamp_string(row_item, index, delimiter)
+ right_pad)
row_item_list.append(clmp_str)
list_of_rows.append(row_item_list)
elif wep is WidthExceedPolicy.WEP_WRAP:
# Let's wrap the row
string_partition = []
for index, row_item in enumerate(row):
width = table.column_widths[index] - lpw[index] - rpw[index]
string_partition.append(textwrap(row_item, width))
for row_items in zip_longest(*string_partition, fillvalue=''):
row_item_list = []
for index, row_item in enumerate(row_items):
left_pad = table._column_pad * lpw[index]
right_pad = table._column_pad * rpw[index]
row_item_list.append(left_pad + row_item + right_pad)
list_of_rows.append(row_item_list)
if len(list_of_rows) == 0:
return [[''] * table.column_count]
else:
return list_of_rows | python | def _get_row_within_width(self, row):
"""Process a row so that it is clamped by column_width.
Parameters
----------
row : array_like
A single row.
Returns
-------
list of list:
List representation of the `row` after it has been processed
according to width exceed policy.
"""
table = self._table
lpw, rpw = table.left_padding_widths, table.right_padding_widths
wep = table.width_exceed_policy
list_of_rows = []
if (wep is WidthExceedPolicy.WEP_STRIP or
wep is WidthExceedPolicy.WEP_ELLIPSIS):
# Let's strip the row
delimiter = '' if wep is WidthExceedPolicy.WEP_STRIP else '...'
row_item_list = []
for index, row_item in enumerate(row):
left_pad = table._column_pad * lpw[index]
right_pad = table._column_pad * rpw[index]
clmp_str = (left_pad
+ self._clamp_string(row_item, index, delimiter)
+ right_pad)
row_item_list.append(clmp_str)
list_of_rows.append(row_item_list)
elif wep is WidthExceedPolicy.WEP_WRAP:
# Let's wrap the row
string_partition = []
for index, row_item in enumerate(row):
width = table.column_widths[index] - lpw[index] - rpw[index]
string_partition.append(textwrap(row_item, width))
for row_items in zip_longest(*string_partition, fillvalue=''):
row_item_list = []
for index, row_item in enumerate(row_items):
left_pad = table._column_pad * lpw[index]
right_pad = table._column_pad * rpw[index]
row_item_list.append(left_pad + row_item + right_pad)
list_of_rows.append(row_item_list)
if len(list_of_rows) == 0:
return [[''] * table.column_count]
else:
return list_of_rows | Process a row so that it is clamped by column_width.
Parameters
----------
row : array_like
A single row.
Returns
-------
list of list:
List representation of the `row` after it has been processed
according to width exceed policy. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/rows.py#L9-L63 |
pri22296/beautifultable | beautifultable/rows.py | RowData._clamp_string | def _clamp_string(self, row_item, column_index, delimiter=''):
"""Clamp `row_item` to fit in column referred by column_index.
This method considers padding and appends the delimiter if `row_item`
needs to be truncated.
Parameters
----------
row_item: str
String which should be clamped.
column_index: int
Index of the column `row_item` belongs to.
delimiter: str
String which is to be appended to the clamped string.
Returns
-------
str
The modified string which fits in it's column.
"""
width = (self._table.column_widths[column_index]
- self._table.left_padding_widths[column_index]
- self._table.right_padding_widths[column_index])
if termwidth(row_item) <= width:
return row_item
else:
if width - len(delimiter) >= 0:
clamped_string = (textwrap(row_item, width-len(delimiter))[0]
+ delimiter)
else:
clamped_string = delimiter[:width]
return clamped_string | python | def _clamp_string(self, row_item, column_index, delimiter=''):
"""Clamp `row_item` to fit in column referred by column_index.
This method considers padding and appends the delimiter if `row_item`
needs to be truncated.
Parameters
----------
row_item: str
String which should be clamped.
column_index: int
Index of the column `row_item` belongs to.
delimiter: str
String which is to be appended to the clamped string.
Returns
-------
str
The modified string which fits in it's column.
"""
width = (self._table.column_widths[column_index]
- self._table.left_padding_widths[column_index]
- self._table.right_padding_widths[column_index])
if termwidth(row_item) <= width:
return row_item
else:
if width - len(delimiter) >= 0:
clamped_string = (textwrap(row_item, width-len(delimiter))[0]
+ delimiter)
else:
clamped_string = delimiter[:width]
return clamped_string | Clamp `row_item` to fit in column referred by column_index.
This method considers padding and appends the delimiter if `row_item`
needs to be truncated.
Parameters
----------
row_item: str
String which should be clamped.
column_index: int
Index of the column `row_item` belongs to.
delimiter: str
String which is to be appended to the clamped string.
Returns
-------
str
The modified string which fits in it's column. | https://github.com/pri22296/beautifultable/blob/c9638f73dff4bb1f341c9ee783e4e47f26efba0b/beautifultable/rows.py#L65-L99 |
icq-bot/python-icq-bot | icq/bot.py | ICQBot.send_im | def send_im(self, target, message, mentions=None, parse=None, update_msg_id=None, wrap_length=5000):
"""
Send text message.
:param target: Target user UIN or chat ID.
:param message: Message text.
:param mentions: Iterable with UINs to mention in message.
:param parse: Iterable with several values from :class:`icq.constant.MessageParseType` specifying which message
items should be parsed by target client (making preview, snippets, etc.). Specify empty iterable to avoid
parsing message at target client. By default all types are included.
:param update_msg_id: Message ID to update.
:param wrap_length: Maximum length of symbols in one message. Text exceeding this length will be sent in several
messages.
:return: Tuple of HTTP responses.
"""
try:
responses = set()
for text in wrap(string=str(message), length=wrap_length):
response = self.http_session.post(
url="{}/im/sendIM".format(self.api_base_url),
data={
"r": uuid.uuid4(),
"aimsid": self.token,
"t": target,
"message": text,
"mentions": (
mentions if isinstance(mentions, six.string_types) or not hasattr(mentions, "__iter__")
else ",".join(mentions)
),
"parse": json.dumps([p.value for p in parse]) if parse is not None else None,
"updateMsgId": update_msg_id
},
timeout=self.timeout_s
)
try:
self.__sent_im_cache[response.json()["response"]["data"]["msgId"]] = text
except (LookupError, TypeError):
self.log.exception("Error while getting 'msgId'!")
responses.add(response)
return tuple(responses)
except ReadTimeout:
self.log.exception("Timeout while sending request!") | python | def send_im(self, target, message, mentions=None, parse=None, update_msg_id=None, wrap_length=5000):
"""
Send text message.
:param target: Target user UIN or chat ID.
:param message: Message text.
:param mentions: Iterable with UINs to mention in message.
:param parse: Iterable with several values from :class:`icq.constant.MessageParseType` specifying which message
items should be parsed by target client (making preview, snippets, etc.). Specify empty iterable to avoid
parsing message at target client. By default all types are included.
:param update_msg_id: Message ID to update.
:param wrap_length: Maximum length of symbols in one message. Text exceeding this length will be sent in several
messages.
:return: Tuple of HTTP responses.
"""
try:
responses = set()
for text in wrap(string=str(message), length=wrap_length):
response = self.http_session.post(
url="{}/im/sendIM".format(self.api_base_url),
data={
"r": uuid.uuid4(),
"aimsid": self.token,
"t": target,
"message": text,
"mentions": (
mentions if isinstance(mentions, six.string_types) or not hasattr(mentions, "__iter__")
else ",".join(mentions)
),
"parse": json.dumps([p.value for p in parse]) if parse is not None else None,
"updateMsgId": update_msg_id
},
timeout=self.timeout_s
)
try:
self.__sent_im_cache[response.json()["response"]["data"]["msgId"]] = text
except (LookupError, TypeError):
self.log.exception("Error while getting 'msgId'!")
responses.add(response)
return tuple(responses)
except ReadTimeout:
self.log.exception("Timeout while sending request!") | Send text message.
:param target: Target user UIN or chat ID.
:param message: Message text.
:param mentions: Iterable with UINs to mention in message.
:param parse: Iterable with several values from :class:`icq.constant.MessageParseType` specifying which message
items should be parsed by target client (making preview, snippets, etc.). Specify empty iterable to avoid
parsing message at target client. By default all types are included.
:param update_msg_id: Message ID to update.
:param wrap_length: Maximum length of symbols in one message. Text exceeding this length will be sent in several
messages.
:return: Tuple of HTTP responses. | https://github.com/icq-bot/python-icq-bot/blob/1d278cc91f8eba5481bb8d70f80fc74160a40c8b/icq/bot.py#L459-L503 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.