docstring
stringlengths 52
499
| function
stringlengths 67
35.2k
| __index_level_0__
int64 52.6k
1.16M
|
|---|---|---|
Find root of identifier, from scope
args:
scope (Scope): current scope
names (list): identifier name list (, separated identifiers)
returns:
list
|
def root(self, scope, names):
parent = scope.scopename
if parent:
parent = parent[-1]
if parent.parsed:
parsed_names = []
for name in names:
ampersand_count = name.count('&')
if ampersand_count:
filtered_parts = []
for part in parent.parsed:
if part and part[0] not in self._subp:
filtered_parts.append(part)
permutations = list(
utility.permutations_with_replacement(
filtered_parts, ampersand_count))
for permutation in permutations:
parsed = []
for name_part in name:
if name_part == "&":
parent_part = permutation.pop(0)
if parsed and parsed[-1].endswith(']'):
parsed.extend(' ')
if parent_part[-1] == ' ':
parent_part.pop()
parsed.extend(parent_part)
else:
parsed.append(name_part)
parsed_names.append(parsed)
else:
# NOTE(saschpe): Maybe this code can be expressed with permutations too?
for part in parent.parsed:
if part and part[0] not in self._subp:
parsed = []
if name[0] == "@media":
parsed.extend(name)
else:
parsed.extend(part)
if part[-1] != ' ':
parsed.append(' ')
parsed.extend(name)
parsed_names.append(parsed)
else:
parsed_names.append(name)
return parsed_names
return names
| 726,905
|
Raw identifier.
args:
clean (bool): clean name
returns:
str
|
def raw(self, clean=False):
if clean:
return ''.join(''.join(p) for p in self.parsed).replace('?', ' ')
return '%'.join('%'.join(p) for p in self.parsed).strip().strip('%')
| 726,906
|
Format identifier
args:
fills (dict): replacements
returns:
str (CSS)
|
def fmt(self, fills):
name = ',$$'.join(''.join(p).strip() for p in self.parsed)
name = re.sub('\?(.)\?', '%(ws)s\\1%(ws)s', name) % fills
return name.replace('$$', fills['nl']).replace(' ', ' ')
| 726,908
|
Scope
Args:
init (bool): Initiate scope
|
def __init__(self, init=False):
super(Scope, self).__init__()
self._mixins = {}
if init:
self.push()
self.deferred = False
self.real = []
| 726,909
|
Add block element to scope
Args:
block (Block): Block object
|
def add_block(self, block):
self[-1]['__blocks__'].append(block)
self[-1]['__names__'].append(block.raw())
| 726,910
|
Remove block element from scope
Args:
block (Block): Block object
|
def remove_block(self, block, index="-1"):
self[index]["__blocks__"].remove(block)
self[index]["__names__"].remove(block.raw())
| 726,911
|
Add mixin to scope
Args:
mixin (Mixin): Mixin object
|
def add_mixin(self, mixin):
raw = mixin.tokens[0][0].raw()
if raw in self._mixins:
self._mixins[raw].append(mixin)
else:
self._mixins[raw] = [mixin]
| 726,912
|
Search for variable by name. Searches scope top down
Args:
name (string): Search term
Returns:
Variable object OR False
|
def variables(self, name):
if isinstance(name, tuple):
name = name[0]
if name.startswith('@{'):
name = '@' + name[2:-1]
i = len(self)
while i >= 0:
i -= 1
if name in self[i]['__variables__']:
return self[i]['__variables__'][name]
return False
| 726,913
|
Search mixins for name.
Allow '>' to be ignored. '.a .b()' == '.a > .b()'
Args:
name (string): Search term
Returns:
Mixin object list OR False
|
def mixins(self, name):
m = self._smixins(name)
if m:
return m
return self._smixins(name.replace('?>?', ' '))
| 726,914
|
Search for defined blocks recursively.
Allow '>' to be ignored. '.a .b' == '.a > .b'
Args:
name (string): Search term
Returns:
Block object OR False
|
def blocks(self, name):
b = self._blocks(name)
if b:
return b
return self._blocks(name.replace('?>?', ' '))
| 726,916
|
Update scope. Add another scope to this one.
Args:
scope (Scope): Scope object
Kwargs:
at (int): Level to update
|
def update(self, scope, at=0):
if hasattr(scope, '_mixins') and not at:
self._mixins.update(scope._mixins)
self[at]['__variables__'].update(scope[at]['__variables__'])
self[at]['__blocks__'].extend(scope[at]['__blocks__'])
self[at]['__names__'].extend(scope[at]['__names__'])
| 726,918
|
Swap variable name for variable value
Args:
name (str): Variable name
Returns:
Variable value (Mixed)
|
def swap(self, name):
if name.startswith('@@'):
var = self.variables(name[1:])
if var is False:
raise SyntaxError('Unknown variable %s' % name)
name = '@' + utility.destring(var.value[0])
var = self.variables(name)
if var is False:
raise SyntaxError('Unknown variable %s' % name)
elif name.startswith('@{'):
var = self.variables('@' + name[2:-1])
if var is False:
raise SyntaxError('Unknown escaped variable %s' % name)
if isinstance(var.value[0], string_types):
var.value[0] = utility.destring(var.value[0])
else:
var = self.variables(name)
if var is False:
raise SyntaxError('Unknown variable %s' % name)
return var.value
| 726,919
|
Base Node
args:
tokens (list): tokenlist
lineno (int): Line number of node
|
def __init__(self, tokens, lineno=0):
self.tokens = tokens
self.lineno = lineno
self.parsed = False
| 726,920
|
Process tokenslist, flattening and parsing it
args:
tokens (list): tokenlist
scope (Scope): Current scope
returns:
list
|
def process(self, tokens, scope):
while True:
tokens = list(utility.flatten(tokens))
done = True
if any(t for t in tokens if hasattr(t, 'parse')):
tokens = [
t.parse(scope) if hasattr(t, 'parse') else t
for t in tokens
]
done = False
if any(
t for t in tokens
if (utility.is_variable(t)) or str(type(t)) ==
"<class 'lesscpy.plib.variable.Variable'>"):
tokens = self.replace_variables(tokens, scope)
done = False
if done:
break
return tokens
| 726,921
|
Replace variables in tokenlist
args:
tokens (list): tokenlist
scope (Scope): Current scope
returns:
list
|
def replace_variables(self, tokens, scope):
list = []
for t in tokens:
if utility.is_variable(t):
list.append(scope.swap(t))
elif str(type(t)) == "<class 'lesscpy.plib.variable.Variable'>":
list.append(scope.swap(t.name))
else:
list.append(t)
return list
| 726,922
|
Parse node
args:
scope (Scope): current scope
raises:
SyntaxError
returns:
self
|
def parse(self, scope):
if not self.parsed:
if len(self.tokens) > 2:
property, style, _ = self.tokens
self.important = True
else:
property, style = self.tokens
self.important = False
self.property = ''.join(property)
self.parsed = []
if style:
style = self.preprocess(style)
self.parsed = self.process(style, scope)
return self
| 726,923
|
Hackish preprocessing from font shorthand tags.
Skips expression parse on certain tags.
args:
style (list): .
returns:
list
|
def preprocess(self, style):
if self.property == 'font':
style = [
''.join(u.expression()) if hasattr(u, 'expression') else u
for u in style
]
else:
style = [(u, ' ') if hasattr(u, 'expression') else u
for u in style]
return style
| 726,924
|
Format node
args:
fills (dict): replacements
returns:
str
|
def fmt(self, fills):
f = "%(tab)s%(property)s:%(ws)s%(style)s%(important)s;%(nl)s"
imp = ' !important' if self.important else ''
if fills['nl']:
self.parsed = [
',%s' % fills['ws'] if p == ',' else p for p in self.parsed
]
style = ''.join([
p.fmt(fills) if hasattr(p, 'fmt') else str(p) for p in self.parsed
])
# IE cannot handle no space after url()
style = re.sub("(url\([^\)]*\))([^\s,])", "\\1 \\2", style)
fills.update({
'property': self.property,
'style': style.strip(),
'important': imp
})
return f % fills
| 726,925
|
Parse node
args:
scope (Scope): current scope
raises:
SyntaxError
returns:
self
|
def parse(self, scope):
self.name, args, self.guards = self.tokens[0]
self.args = [a for a in utility.flatten(args) if a]
self.body = Block([None, self.tokens[1]], 0)
self.vars = list(
utility.flatten([
list(v.values()) for v in [s['__variables__'] for s in scope]
]))
return self
| 726,926
|
Parse arguments to mixin. Add them to scope
as variables. Sets upp special variable @arguments
as well.
args:
args (list): arguments
scope (Scope): current scope
raises:
SyntaxError
|
def parse_args(self, args, scope):
arguments = list(zip(args,
[' '] * len(args))) if args and args[0] else None
zl = itertools.zip_longest if sys.version_info[
0] == 3 else itertools.izip_longest
if self.args:
parsed = [
v if hasattr(v, 'parse') else v for v in copy.copy(self.args)
]
args = args if isinstance(args, list) else [args]
vars = [
self._parse_arg(var, arg, scope)
for arg, var in zl([a for a in args], parsed)
]
for var in vars:
if var:
var.parse(scope)
if not arguments:
arguments = [v.value for v in vars if v]
if not arguments:
arguments = ''
Variable(['@arguments', None, arguments]).parse(scope)
| 726,927
|
Parse a single argument to mixin.
args:
var (Variable object): variable
arg (mixed): argument
scope (Scope object): current scope
returns:
Variable object or None
|
def _parse_arg(self, var, arg, scope):
if isinstance(var, Variable):
# kwarg
if arg:
if utility.is_variable(arg[0]):
tmp = scope.variables(arg[0])
if not tmp:
return None
val = tmp.value
else:
val = arg
var = Variable(var.tokens[:-1] + [val])
else:
# arg
if utility.is_variable(var):
if arg is None:
raise SyntaxError('Missing argument to mixin')
elif utility.is_variable(arg[0]):
tmp = scope.variables(arg[0])
if not tmp:
return None
val = tmp.value
else:
val = arg
var = Variable([var, None, val])
else:
return None
return var
| 726,928
|
Parse guards on mixin.
args:
scope (Scope): current scope
raises:
SyntaxError
returns:
bool (passes guards)
|
def parse_guards(self, scope):
if self.guards:
cor = True if ',' in self.guards else False
for g in self.guards:
if isinstance(g, list):
res = (g[0].parse(scope)
if len(g) == 1 else Expression(g).parse(scope))
if cor:
if res:
return True
elif not res:
return False
return True
| 726,929
|
Call mixin. Parses a copy of the mixins body
in the current scope and returns it.
args:
scope (Scope): current scope
args (list): arguments
raises:
SyntaxError
returns:
list or False
|
def call(self, scope, args=[]):
ret = False
if args:
args = [[
a.parse(scope) if isinstance(a, Expression) else a for a in arg
] if arg else arg for arg in args]
try:
self.parse_args(args, scope)
except SyntaxError:
pass
else:
if self.parse_guards(scope):
body = self.body.copy()
ret = body.tokens[1]
if ret:
utility.rename(ret, scope, Block)
return ret
| 726,930
|
Parse function
args:
scope (Scope): Scope object
returns:
self
|
def parse(self, scope):
self.name, _, self.value = self.tokens
if isinstance(self.name, tuple):
if len(self.name) > 1:
self.name, pad = self.name
self.value.append(pad)
else:
self.name = self.name[0]
scope.add_variable(self)
return self
| 726,931
|
Parse Node within scope.
the functions ~( and e( map to self.escape
and %( maps to self.sformat
args:
scope (Scope): Current scope
|
def parse(self, scope):
name = ''.join(self.tokens[0])
parsed = self.process(self.tokens[1:], scope)
if name == '%(':
name = 'sformat'
elif name in ('~', 'e'):
name = 'escape'
color = Color.Color()
args = [
t for t in parsed
if not isinstance(t, string_types) or t not in '(),'
]
if hasattr(self, name):
try:
return getattr(self, name)(*args)
except ValueError:
pass
if hasattr(color, name):
try:
result = getattr(color, name)(*args)
try:
return result + ' '
except TypeError:
return result
except ValueError:
pass
return name + ''.join([p for p in parsed])
| 726,932
|
String format.
args:
string (str): string to format
args (list): format options
returns:
str
|
def sformat(self, string, *args):
format = string
items = []
m = re.findall('(%[asdA])', format)
if m and not args:
raise SyntaxError('Not enough arguments...')
i = 0
for n in m:
v = {
'%A': urlquote,
'%s': utility.destring,
}.get(n, str)(args[i])
items.append(v)
i += 1
format = format.replace('%A', '%s')
format = format.replace('%d', '%s')
return format % tuple(items)
| 726,933
|
Is number
args:
string (str): match
returns:
bool
|
def isnumber(self, string, *args):
try:
n, u = utility.analyze_number(string)
except SyntaxError:
return False
return True
| 726,934
|
Is url
args:
string (str): match
returns:
bool
|
def isurl(self, string, *args):
arg = utility.destring(string)
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
# localhost...
r'localhost|'
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
# optional port
r'(?::\d+)?'
r'(?:/?|[/?]\S+)$',
re.IGNORECASE)
return regex.match(arg)
| 726,935
|
Is string
args:
string (str): match
returns:
bool
|
def isstring(self, string, *args):
regex = re.compile(r'\'[^\']*\'|"[^"]*"')
return regex.match(string)
| 726,936
|
Increment function
args:
value (str): target
returns:
str
|
def increment(self, value, *args):
n, u = utility.analyze_number(value)
return utility.with_unit(n + 1, u)
| 726,937
|
Add integers
args:
args (list): target
returns:
str
|
def add(self, *args):
if (len(args) <= 1):
return 0
return sum([int(v) for v in args])
| 726,938
|
Round number
args:
value (str): target
returns:
str
|
def round(self, value, *args):
n, u = utility.analyze_number(value)
return utility.with_unit(
int(utility.away_from_zero_round(float(n))), u)
| 726,939
|
Ceil number
args:
value (str): target
returns:
str
|
def ceil(self, value, *args):
n, u = utility.analyze_number(value)
return utility.with_unit(int(math.ceil(n)), u)
| 726,940
|
Return percentage value
args:
value (str): target
returns:
str
|
def percentage(self, value, *args):
n, u = utility.analyze_number(value)
n = int(n * 100.0)
u = '%'
return utility.with_unit(n, u)
| 726,941
|
Process color expression
args:
expression (tuple): color expression
returns:
str
|
def process(self, expression):
a, o, b = expression
c1 = self._hextorgb(a)
c2 = self._hextorgb(b)
r = ['#']
for i in range(3):
v = self.operate(c1[i], c2[i], o)
if v > 0xff:
v = 0xff
if v < 0:
v = 0
r.append("%02x" % int(v))
return ''.join(r)
| 726,942
|
Do operation on colors
args:
left (str): left side
right (str): right side
operation (str): Operation
returns:
str
|
def operate(self, left, right, operation):
operation = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv
}.get(operation)
return operation(left, right)
| 726,943
|
Return the hue value of a color
args:
color (str): color
raises:
ValueError
returns:
float
|
def hue(self, color, *args):
if color:
h, l, s = self._hextohls(color)
return utility.convergent_round(h * 360.0, 3)
raise ValueError('Illegal color values')
| 726,949
|
Return the saturation value of a color
args:
color (str): color
raises:
ValueError
returns:
float
|
def saturation(self, color, *args):
if color:
h, l, s = self._hextohls(color)
return s * 100.0
raise ValueError('Illegal color values')
| 726,950
|
Lighten a color
args:
color (str): color
diff (str): percentage
returns:
str
|
def lighten(self, color, diff, *args):
if color and diff:
return self._ophsl(color, diff, 1, operator.add)
raise ValueError('Illegal color values')
| 726,951
|
Darken a color
args:
color (str): color
diff (str): percentage
returns:
str
|
def darken(self, color, diff, *args):
if color and diff:
return self._ophsl(color, diff, 1, operator.sub)
raise ValueError('Illegal color values')
| 726,952
|
Spin color by degree. (Increase / decrease hue)
args:
color (str): color
degree (str): percentage
raises:
ValueError
returns:
str
|
def spin(self, color, degree, *args):
if color and degree:
if isinstance(degree, string_types):
degree = float(degree.strip('%'))
h, l, s = self._hextohls(color)
h = ((h * 360.0) + degree) % 360.0
h = 360.0 + h if h < 0 else h
rgb = colorsys.hls_to_rgb(h / 360.0, l, s)
color = (utility.convergent_round(c * 255) for c in rgb)
return self._rgbatohex(color)
raise ValueError('Illegal color values')
| 726,953
|
Format CSS Hex color code.
uppercase becomes lowercase, 3 digit codes expand to 6 digit.
args:
color (str): color
raises:
ValueError
returns:
str
|
def fmt(self, color):
if utility.is_color(color):
color = color.lower().strip('#')
if len(color) in [3, 4]:
color = ''.join([c * 2 for c in color])
return '#%s' % color
raise ValueError('Cannot format non-color')
| 726,955
|
Flatten list.
Args:
lst (list): List to flatten
Returns:
generator
|
def flatten(lst):
for elm in lst:
if isinstance(elm, collections.Iterable) and not isinstance(
elm, string_types):
for sub in flatten(elm):
yield sub
else:
yield elm
| 726,961
|
yield item i and item i+1 in lst. e.g.
(lst[0], lst[1]), (lst[1], lst[2]), ..., (lst[-1], None)
Args:
lst (list): List to process
Returns:
list
|
def pairwise(lst):
if not lst:
return
length = len(lst)
for i in range(length - 1):
yield lst[i], lst[i + 1]
yield lst[-1], None
| 726,962
|
Rename all sub-blocks moved under another
block. (mixins)
Args:
lst (list): block list
scope (object): Scope object
|
def rename(blocks, scope, stype):
for p in blocks:
if isinstance(p, stype):
p.tokens[0].parse(scope)
if p.tokens[1]:
scope.push()
scope.current = p.tokens[0]
rename(p.tokens[1], scope, stype)
scope.pop()
| 726,963
|
Recursive search for name in block (inner blocks)
Args:
name (str): search term
Returns:
Block OR False
|
def blocksearch(block, name):
if hasattr(block, 'tokens'):
for b in block.tokens[1]:
b = (b if hasattr(b, 'raw') and b.raw() == name else blocksearch(
b, name))
if b:
return b
return False
| 726,964
|
Reverse guard expression. not
(@a > 5) -> (@a =< 5)
Args:
lst (list): Expression
returns:
list
|
def reverse_guard(lst):
rev = {'<': '>=', '>': '=<', '>=': '<', '=<': '>'}
return [rev[l] if l in rev else l for l in lst]
| 726,965
|
Print scope tree
args:
lst (list): parse result
lvl (int): current nesting level
|
def debug_print(lst, lvl=0):
pad = ''.join(['\t.'] * lvl)
t = type(lst)
if t is list:
for p in lst:
debug_print(p, lvl)
elif hasattr(lst, 'tokens'):
print(pad, t)
debug_print(list(flatten(lst.tokens)), lvl + 1)
| 726,966
|
Analyse number for type and split from unit
1px -> (q, 'px')
args:
var (str): number string
kwargs:
err (str): Error message
raises:
SyntaxError
returns:
tuple
|
def analyze_number(var, err=''):
n, u = split_unit(var)
if not isinstance(var, string_types):
return (var, u)
if is_color(var):
return (var, 'color')
if is_int(n):
n = int(n)
elif is_float(n):
n = float(n)
else:
raise SyntaxError('%s ´%s´' % (err, var))
return (n, u)
| 726,967
|
Return number with unit
args:
number (mixed): Number
unit (str): Unit
returns:
str
|
def with_unit(number, unit=None):
if isinstance(number, tuple):
number, unit = number
if number == 0:
return '0'
if unit:
number = str(number)
if number.startswith('.'):
number = '0' + number
return "%s%s" % (number, unit)
return number if isinstance(number, string_types) else str(number)
| 726,968
|
Is string CSS color
args:
value (str): string
returns:
bool
|
def is_color(value):
if not value or not isinstance(value, string_types):
return False
if value[0] == '#' and len(value) in [4, 5, 7, 9]:
try:
int(value[1:], 16)
return True
except ValueError:
pass
return False
| 726,969
|
Check if string is LESS variable
args:
value (str): string
returns:
bool
|
def is_variable(value):
if isinstance(value, string_types):
return (value.startswith('@') or value.startswith('-@'))
elif isinstance(value, tuple):
value = ''.join(value)
return (value.startswith('@') or value.startswith('-@'))
return False
| 726,970
|
Is value float
args:
value (str): string
returns:
bool
|
def is_float(value):
if not is_int(value):
try:
float(str(value))
return True
except (ValueError, TypeError):
pass
return False
| 726,971
|
Split a number from its unit
1px -> (q, 'px')
Args:
value (str): input
returns:
tuple
|
def split_unit(value):
r = re.search('^(\-?[\d\.]+)(.*)$', str(value))
return r.groups() if r else ('', '')
| 726,972
|
Utility function to process strings that contain either percentiles or floats
args:
str: s
returns:
float
|
def pc_or_float(s):
if isinstance(s, string_types) and '%' in s:
return float(s.strip('%')) / 100.0
return float(s)
| 726,975
|
Parse Node
args:
scope (Scope): Scope object
raises:
SyntaxError
returns:
str
|
def parse(self, scope):
assert (len(self.tokens) == 3)
expr = self.process(self.tokens, scope)
A, O, B = [
e[0] if isinstance(e, tuple) else e for e in expr
if str(e).strip()
]
try:
a, ua = utility.analyze_number(A, 'Illegal element in expression')
b, ub = utility.analyze_number(B, 'Illegal element in expression')
except SyntaxError:
return ' '.join([str(A), str(O), str(B)])
if (a is False or b is False):
return ' '.join([str(A), str(O), str(B)])
if ua == 'color' or ub == 'color':
return color.Color().process((A, O, B))
if a == 0 and O == '/':
# NOTE(saschpe): The ugliest but valid CSS since sliced bread: 'font: 0/1 a;'
return ''.join([str(A), str(O), str(B), ' '])
out = self.operate(a, b, O)
if isinstance(out, bool):
return out
return self.with_units(out, ua, ub)
| 726,977
|
Return value with unit.
args:
val (mixed): result
ua (str): 1st unit
ub (str): 2nd unit
raises:
SyntaxError
returns:
str
|
def with_units(self, val, ua, ub):
if not val:
return str(val)
if ua or ub:
if ua and ub:
if ua == ub:
return str(val) + ua
else:
# Nodejs version does not seem to mind mismatched
# units within expressions. So we choose the first
# as they do
# raise SyntaxError("Error in expression %s != %s" % (ua, ub))
return str(val) + ua
elif ua:
return str(val) + ua
elif ub:
return str(val) + ub
return repr(val)
| 726,978
|
Perform operation
args:
vala (mixed): 1st value
valb (mixed): 2nd value
oper (str): operation
returns:
mixed
|
def operate(self, vala, valb, oper):
operation = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
'=': operator.eq,
'>': operator.gt,
'<': operator.lt,
'>=': operator.ge,
'=<': operator.le,
}.get(oper)
if operation is None:
raise SyntaxError("Unknown operation %s" % oper)
ret = operation(vala, valb)
if oper in '+-*/' and int(ret) == ret:
ret = int(ret)
return ret
| 726,979
|
Internal error handler
args:
t (Lex token): Error token
|
def p_error(self, t):
if t:
error_msg = "E: %s line: %d, Syntax Error, token: `%s`, `%s`" % \
(self.target, t.lineno, t.type, t.value)
self.register.register(error_msg)
while True:
t = self.lex.token()
if not t or t.value == '}':
if len(self.scope) > 1:
self.scope.pop()
break
self.parser.restart()
return t
| 727,005
|
Custom error handler
args:
e (Mixed): Exception or str
line (int): line number
t(str): Error type
|
def handle_error(self, e, line, t='E'):
self.register.register("%s: line: %d: %s\n" % (t, line, e))
| 727,006
|
Parse node
args:
scope (Scope): current scope
raises:
SyntaxError
returns:
parsed
|
def parse(self, scope):
if not self.parsed:
self.parsed = ''.join(self.process(self.tokens, scope))
return self.parsed
| 727,007
|
Initialise client.
Args:
base_url (str): The base URL to the service being used.
username (str): The username to authenticate with.
api_key (str): The API key to authenticate with.
timeout (int): Maximum time before timing out.
|
def __init__(
self,
base_url,
username=None,
api_key=None,
status_endpoint=None,
timeout=60
):
self.base_url = base_url
self.username = username
self.api_key = api_key
self.status_endpoint = urljoin(self.base_url, status_endpoint)
self.timeout = timeout
| 727,039
|
Add request content data to request body, set Content-type header.
Should be overridden by subclasses if not using JSON encoding.
Args:
request (HTTPRequest): The request object.
data (dict, None): Data to be encoded.
Returns:
HTTPRequest: The request object.
|
def encode(request, data):
if data is None:
return request
request.add_header('Content-Type', 'application/json')
request.data = json.dumps(data)
return request
| 727,040
|
Call the API with a GET request.
Args:
url (str): Resource location relative to the base URL.
params (dict or None): Query-string parameters.
Returns:
ResultParser or ErrorParser.
|
def get(self, url, params=None, **kwargs):
return self.call_api(
"GET",
url,
params=params,
**kwargs
)
| 727,042
|
Call the API with a DELETE request.
Args:
url (str): Resource location relative to the base URL.
params (dict or None): Query-string parameters.
Returns:
ResultParser or ErrorParser.
|
def delete(self, url, params=None, **kwargs):
return self.call_api(
"DELETE",
url,
params=params,
**kwargs
)
| 727,043
|
Call the API with a PUT request.
Args:
url (str): Resource location relative to the base URL.
params (dict or None): Query-string parameters.
data (dict or None): Request body contents.
files (dict or None: Files to be passed to the request.
Returns:
An instance of ResultParser or ErrorParser.
|
def put(self, url, params=None, data=None, files=None, **kwargs):
return self.call_api(
"PUT",
url,
params=params,
data=data,
files=files,
**kwargs
)
| 727,044
|
Call the API with a POST request.
Args:
url (str): Resource location relative to the base URL.
params (dict or None): Query-string parameters.
data (dict or None): Request body contents.
files (dict or None: Files to be passed to the request.
Returns:
An instance of ResultParser or ErrorParser.
|
def post(self, url, params=None, data=None, files=None, **kwargs):
return self.call_api(
"POST",
url,
params=params,
data=data,
files=files,
**kwargs
)
| 727,045
|
Process query recursively, if the text is too long,
it is split and processed bit a bit.
Args:
query (sdict): Text to be processed.
prepared (bool): True when the query is ready to be submitted via
POST request.
Returns:
str: Body ready to be submitted to the API.
|
def _process_query(self, query, prepared=False):
# Exit condition and POST
if prepared is True:
files = {'query': str(query)}
logger.debug('About to submit the following query {}'.format(query))
res, status = self.post(
self.disambiguate_service,
files=files,
headers={'Accept': 'application/json'},
)
if status == 200:
return self.decode(res), status
else:
logger.debug('Disambiguation failed.')
return None, status
text = query['text']
sentence_coordinates = [
{
"offsetStart": 0,
"offsetEnd": len(text)
}
]
total_nb_sentences = len(sentence_coordinates) # Sentences from text.
sentences_groups = []
if len(text) > self.max_text_length:
res, status_code = self.segment(text)
if status_code == 200:
sentence_coordinates = res['sentences']
total_nb_sentences = len(sentence_coordinates)
else:
logger.error('Error during the segmentation of the text.')
logger.debug(
'Text too long, split in {} sentences; building groups of {} '
'sentences.'.format(
total_nb_sentences, self.sentences_per_group
)
)
sentences_groups = self._group_sentences(
total_nb_sentences,
self.sentences_per_group
)
else:
query['sentence'] = "true"
if total_nb_sentences > 1:
query['sentences'] = sentence_coordinates
if len(sentences_groups) > 0:
for group in sentences_groups:
query['processSentence'] = group
res, status_code = self._process_query(query, prepared=True)
if status_code == 200:
if 'entities' in res:
query['entities'] = res[u'entities']
query['language'] = res[u'language']
else:
logger.error(
"Error when processing the query {}".format(query)
)
return None, status_code
else:
res, status_code = self._process_query(query, prepared=True)
if status_code == 200:
query['language'] = res[u'language']
if 'entities' in res:
query['entities'] = res[u'entities']
else:
logger.error("Error when processing the query {}".format(query))
return None, status_code
return query, status_code
| 727,062
|
Split sentences in groups, given a specific group length.
Args:
total_nb_sentences (int): Total available sentences.
group_length (int): Limit of length for each group.
Returns:
list: Contains groups (lists) of sentences.
|
def _group_sentences(total_nb_sentences, group_length):
sentences_groups = []
current_sentence_group = []
for i in range(0, total_nb_sentences):
if i % group_length == 0:
if len(current_sentence_group) > 0:
sentences_groups.append(current_sentence_group)
current_sentence_group = [i]
else:
current_sentence_group.append(i)
if len(current_sentence_group) > 0:
sentences_groups.append(current_sentence_group)
return sentences_groups
| 727,063
|
Call the disambiguation service in order to process a pdf file .
Args:
pdf (file): PDF file to be disambiguated.
language (str): language of text (if known)
Returns:
dict, int: API response and API status.
|
def disambiguate_pdf(self, file, language=None, entities=None):
body = {
"customisation": "generic"
}
if language:
body['language'] = {"lang": language}
if entities:
body['entities'] = entities
files = {
'query': str(body),
'file': (
file,
open(file, 'rb'),
'application/pdf',
{'Expires': '0'}
)
}
res, status = self.post(
self.disambiguate_service,
files=files,
headers={'Accept': 'application/json'},
)
if status != 200:
logger.debug('Disambiguation failed with error ' + str(status))
return self.decode(res), status
| 727,064
|
Call the disambiguation service in order to get meanings.
Args:
terms (obj): list of objects of term, weight
language (str): language of text, english if not specified
entities (list): list of entities or mentions to be supplied by
the user.
Returns:
dict, int: API response and API status.
|
def disambiguate_terms(self, terms, language="en", entities=None):
body = {
"termVector": terms,
"entities": [],
"onlyNER": "false",
"customisation": "generic"
}
body['language'] = {"lang": language}
if entities:
body['entities'] = entities
files = {'query': str(body)}
logger.debug('About to submit the following query {}'.format(body))
res, status = self.post(
self.disambiguate_service,
files=files,
headers={'Accept': 'application/json'},
)
if status == 200:
return self.decode(res), status
else:
logger.debug('Disambiguation failed.')
return None, status
| 727,065
|
Call the disambiguation service in order to get meanings.
Args:
text (str): Text to be disambiguated.
language (str): language of text (if known)
entities (list): list of entities or mentions to be supplied by
the user.
Returns:
dict, int: API response and API status.
|
def disambiguate_text(self, text, language=None, entities=None):
body = {
"text": text,
"entities": [],
"onlyNER": "false",
"customisation": "generic"
}
if language:
body['language'] = {"lang": language}
if entities:
body['entities'] = entities
result, status_code = self._process_query(body)
if status_code != 200:
logger.debug('Disambiguation failed.')
return result, status_code
| 727,066
|
Call the disambiguation service in order to disambiguate a search query.
Args:
text (str): Query to be disambiguated.
language (str): language of text (if known)
entities (list): list of entities or mentions to be supplied by
the user.
Returns:
dict, int: API response and API status.
|
def disambiguate_query(self, query, language=None, entities=None):
body = {
"shortText": query,
"entities": [],
"onlyNER": "false",
"customisation": "generic"
}
if language:
body['language'] = {"lang": language}
if entities:
body['entities'] = entities
files = {'query': str(body)}
logger.debug('About to submit the following query {}'.format(body))
res, status = self.post(
self.disambiguate_service,
files=files,
headers={'Accept': 'application/json'},
)
if status == 200:
return self.decode(res), status
else:
logger.debug('Disambiguation failed.')
return None, status
| 727,067
|
Call the segmenter in order to split text in sentences.
Args:
text (str): Text to be segmented.
Returns:
dict, int: A dict containing a list of dicts with the offsets of
each sentence; an integer representing the response code.
|
def segment(self, text):
files = {'text': text}
res, status_code = self.post(self.segmentation_service, files=files)
if status_code != 200:
logger.debug('Segmentation failed.')
return self.decode(res), status_code
| 727,068
|
Recognise the language of the text in input
Args:
id (str): The text whose the language needs to be recognised
Returns:
dict, int: A dict containing the recognised language and the
confidence score.
|
def get_language(self, text):
files = {'text': text}
res, status_code = self.post(self.language_service, files=files)
if status_code != 200:
logger.debug('Language recognition failed.')
return self.decode(res), status_code
| 727,069
|
Fetch the concept from the Knowledge base
Args:
id (str): The concept id to be fetched, it can be Wikipedia
page id or Wikiedata id.
Returns:
dict, int: A dict containing the concept information; an integer
representing the response code.
|
def get_concept(self, conceptId, lang='en'):
url = urljoin(self.concept_service + '/', conceptId)
res, status_code = self.get(url, params={'lang': lang})
if status_code != 200:
logger.debug('Fetch concept failed.')
return self.decode(res), status_code
| 727,070
|
Performs /register with type: m.login.application_service
Args:
username(str): Username to register.
|
def register(self, username=""):
if not username:
username = utils.mxid2localpart(self.identity)
content = {
"type": "m.login.application_service",
"username": username,
}
return self._send("POST", "/register", content,
api_path=MATRIX_V2_API_PATH)
| 727,670
|
Returns a constant `value` TensorFluent with given `dtype`.
Args:
value: The constant value.
dtype: The output's data type.
Returns:
A constant TensorFluent.
|
def constant(cls,
value: Value,
dtype: tf.DType = tf.float32) -> 'TensorFluent':
t = tf.constant(value, dtype=dtype)
scope = [] # type: List
batch = False
return TensorFluent(t, scope, batch=batch)
| 727,750
|
Returns a TensorFluent for the Bernoulli sampling op with given mean parameter.
Args:
mean: The mean parameter of the Bernoulli distribution.
batch_size: The size of the batch (optional).
Returns:
The Bernoulli distribution and a TensorFluent sample drawn from the distribution.
|
def Bernoulli(cls,
mean: 'TensorFluent',
batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']:
probs = mean.tensor
dist = tf.distributions.Bernoulli(probs=probs, dtype=tf.bool)
batch = mean.batch
if not batch and batch_size is not None:
t = dist.sample(batch_size)
batch = True
else:
t = dist.sample()
scope = mean.scope.as_list()
return (dist, TensorFluent(t, scope, batch=batch))
| 727,751
|
Returns a TensorFluent for the Uniform sampling op with given low and high parameters.
Args:
low: The low parameter of the Uniform distribution.
high: The high parameter of the Uniform distribution.
batch_size: The size of the batch (optional).
Returns:
The Uniform distribution and a TensorFluent sample drawn from the distribution.
Raises:
ValueError: If parameters do not have the same scope.
|
def Uniform(cls,
low: 'TensorFluent', high: 'TensorFluent',
batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']:
if low.scope != high.scope:
raise ValueError('Uniform distribution: parameters must have same scope!')
dist = tf.distributions.Uniform(low.tensor, high.tensor)
batch = low.batch or high.batch
if not batch and batch_size is not None:
t = dist.sample(batch_size)
batch = True
else:
t = dist.sample()
scope = low.scope.as_list()
return (dist, TensorFluent(t, scope, batch=batch))
| 727,752
|
Returns a TensorFluent for the Normal sampling op with given mean and variance.
Args:
mean: The mean parameter of the Normal distribution.
variance: The variance parameter of the Normal distribution.
batch_size: The size of the batch (optional).
Returns:
The Normal distribution and a TensorFluent sample drawn from the distribution.
Raises:
ValueError: If parameters do not have the same scope.
|
def Normal(cls,
mean: 'TensorFluent', variance: 'TensorFluent',
batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']:
if mean.scope != variance.scope:
raise ValueError('Normal distribution: parameters must have same scope!')
loc = mean.tensor
scale = tf.sqrt(variance.tensor)
dist = tf.distributions.Normal(loc, scale)
batch = mean.batch or variance.batch
if not batch and batch_size is not None:
t = dist.sample(batch_size)
batch = True
else:
t = dist.sample()
scope = mean.scope.as_list()
return (dist, TensorFluent(t, scope, batch=batch))
| 727,753
|
Returns a TensorFluent for the Gamma sampling op with given shape and scale parameters.
Args:
shape: The shape parameter of the Gamma distribution.
scale: The scale parameter of the Gamma distribution.
batch_size: The size of the batch (optional).
Returns:
The Gamma distribution and a TensorFluent sample drawn from the distribution.
Raises:
ValueError: If parameters do not have the same scope.
|
def Gamma(cls,
shape: 'TensorFluent',
scale: 'TensorFluent',
batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']:
if shape.scope != scale.scope:
raise ValueError('Gamma distribution: parameters must have same scope!')
concentration = shape.tensor
rate = 1 / scale.tensor
dist = tf.distributions.Gamma(concentration, rate)
batch = shape.batch or scale.batch
if not batch and batch_size is not None:
t = dist.sample(batch_size)
batch = True
else:
t = dist.sample()
scope = shape.scope.as_list()
return (dist, TensorFluent(t, scope, batch=batch))
| 727,754
|
Returns a TensorFluent for the Exponential sampling op with given mean parameter.
Args:
mean: The mean parameter of the Exponential distribution.
batch_size: The size of the batch (optional).
Returns:
The Exponential distribution and a TensorFluent sample drawn from the distribution.
|
def Exponential(cls,
mean: 'TensorFluent',
batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']:
rate = 1 / mean.tensor
dist = tf.distributions.Exponential(rate)
batch = mean.batch
if not batch and batch_size is not None:
t = dist.sample(batch_size)
batch = True
else:
t = dist.sample()
scope = mean.scope.as_list()
return (dist, TensorFluent(t, scope, batch=batch))
| 727,755
|
Returns a copy of the input fluent with stop_gradient at tensor level.
Args:
x: The input fluent.
Returns:
A TensorFluent that stops backpropagation of gradient computations.
|
def stop_gradient(cls, x: 'TensorFluent') -> 'TensorFluent':
scope = x.scope.as_list()
batch = x.batch
return TensorFluent(tf.stop_gradient(x.tensor), scope, batch)
| 727,756
|
Returns a copy of the inputs fluent with stop_gradient applied at batch level.
Args:
x: The input fluent.
stop_batch: A boolean tf.Tensor with shape=(batch_size, ...)
Returns:
A TensorFluent that conditionally stops backpropagation of gradient computations.
|
def stop_batch_gradient(cls, x: 'TensorFluent', stop_batch: tf.Tensor) -> 'TensorFluent':
scope = x.scope.as_list()
batch = x.batch
tensor = tf.where(stop_batch, tf.stop_gradient(x.tensor), x.tensor)
return TensorFluent(tensor, scope, batch)
| 727,757
|
Returns a TensorFluent for the abs function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the abs function.
|
def abs(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.abs, tf.float32)
| 727,758
|
Returns a TensorFluent for the exp function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the exp function.
|
def exp(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.exp, tf.float32)
| 727,759
|
Returns a TensorFluent for the log function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the log function.
|
def log(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.log, tf.float32)
| 727,760
|
Returns a TensorFluent for the sqrt function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the sqrt function.
|
def sqrt(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.sqrt, tf.float32)
| 727,761
|
Returns a TensorFluent for the cos function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the cos function.
|
def cos(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.cos, tf.float32)
| 727,762
|
Returns a TensorFluent for the sin function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the sin function.
|
def sin(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.sin, tf.float32)
| 727,763
|
Returns a TensorFluent for the tan function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the tan function.
|
def tan(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.tan, tf.float32)
| 727,764
|
Returns a TensorFluent for the arccos function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the arccos function.
|
def acos(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.acos, tf.float32)
| 727,765
|
Returns a TensorFluent for the arcsin function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the arcsin function.
|
def asin(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.asin, tf.float32)
| 727,766
|
Returns a TensorFluent for the arctan function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the arctan function.
|
def atan(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.atan2, tf.float32)
| 727,767
|
Returns a TensorFluent for the round function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the round function.
|
def round(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.round, tf.float32)
| 727,768
|
Returns a TensorFluent for the ceil function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the ceil function.
|
def ceil(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.ceil, tf.float32)
| 727,769
|
Returns a TensorFluent for the floor function.
Args:
x: The input fluent.
Returns:
A TensorFluent wrapping the floor function.
|
def floor(cls, x: 'TensorFluent') -> 'TensorFluent':
return cls._unary_op(x, tf.floor, tf.float32)
| 727,770
|
Returns a TensorFluent for the pow function.TensorFluent
Args:
x: The first operand.
y: The second operand.
Returns:
A TensorFluent wrapping the pow function.
|
def pow(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent':
return cls._binary_op(x, y, tf.pow, tf.float32)
| 727,771
|
Returns a TensorFluent for the maximum function.TensorFluent
Args:
x: The first operand.
y: The second operand.
Returns:
A TensorFluent wrapping the maximum function.
|
def max(cls, x: 'TensorFluent', y: 'TensorFluent') -> 'TensorFluent':
return cls._binary_op(x, y, tf.maximum, tf.float32)
| 727,772
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.