prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>check.py<|end_file_name|><|fim▁begin|>#-*- coding:utf-8 -*-
from findbilibili import *
#funtion name [checkinfo]
#判断要输出的回答
#param array 抓取的文字
#return string 回答
def checkinfo2(content):
conte<|fim_middle|>ntent[1].decode('gbk')
key = content[1].encode('utf-8')
if key == '节操':
return '这种东西早就没有了'
result = animation(key) #搜动漫
return result
#funtion name [animation]
#搜索动漫
#param array 动漫名字
#return string 最后更新网址
def animation(name):
url = bilibili(name)
try:
result = 'bilibili最后更新:第'+url[-1][0]+'集'+url[-1][1]
return result
except IndexError:
return '什么都找不到!'<|fim▁end|> | nt[1] = co |
<|file_name|>check.py<|end_file_name|><|fim▁begin|>#-*- coding:utf-8 -*-
from findbilibili import *
#funtion name [checkinfo]
#判断要输出的回答
#param array 抓取的文字
#return string 回答
def checkinfo2(content):
content[1] = content[1].decode('gbk')
key = content[1].encode('utf-8')
if key == '节操':
return '这种东西早就没有了'
result = animation(key) #搜动漫
return result
#funtion name [animation]
#搜索动漫
#param array 动漫名字
#return string 最后更新网址
def animation(name):
url = bilibili(name)
try:
result = 'bilibili最后更新:第'+u<|fim_middle|>+'集'+url[-1][1]
return result
except IndexError:
return '什么都找不到!'<|fim▁end|> | rl[-1][0] |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return<|fim▁hole|> If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])<|fim▁end|> | a url that includes the parameters as a properly formatted
query string.
|
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
<|fim_middle|>
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
<|fim_middle|>
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
<|fim_middle|>
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | """Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment]) |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
<|fim_middle|>
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | """ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8') |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
<|fim_middle|>
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)] |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
<|fim_middle|>
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | """use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False) |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
<|fim_middle|>
<|fim▁end|> | """Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment]) |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
<|fim_middle|>
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | path += new_path |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
<|fim_middle|>
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | path += '/' + new_path |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
<|fim_middle|>
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | pass |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
<|fim_middle|>
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | value = value.decode('utf-8') |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
<|fim_middle|>
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | value = unicode(value) |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
<|fim_middle|>
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | return [_query_param(*param) for param in params.items()] |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
<|fim_middle|>
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | return [_query_param(*params)] |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
<|fim_middle|>
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params)) |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
<|fim_middle|>
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | query_bits.extend(_make_query_tuples(params)) |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def <|fim_middle|>(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | get_path |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def <|fim_middle|>(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | get_host |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def <|fim_middle|>(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | add_path |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def <|fim_middle|>(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | _query_param |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def <|fim_middle|>(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | _make_query_tuples |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def <|fim_middle|>(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def update_query_params(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | add_query_params |
<|file_name|>url_operations.py<|end_file_name|><|fim▁begin|>import urllib
import urlparse
def get_path(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return path
def get_host(url):
scheme, host, path, query, fragment = urlparse.urlsplit(url)
return host
def add_path(url, new_path):
"""Given a url and path, return a new url that combines
the two.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
new_path = new_path.lstrip('/')
if path.endswith('/'):
path += new_path
else:
path += '/' + new_path
return urlparse.urlunsplit([scheme, host, path, query, fragment])
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf-8')
def _make_query_tuples(params):
if hasattr(params, 'items'):
return [_query_param(*param) for param in params.items()]
else:
return [_query_param(*params)]
def add_query_params(url, params):
"""use the _update_query_params function to set a new query
string for the url based on params.
"""
return update_query_params(url, params, update=False)
def <|fim_middle|>(url, params, update=True):
"""Given a url and a tuple or dict of parameters, return
a url that includes the parameters as a properly formatted
query string.
If update is True, change any existing values to new values
given in params.
"""
scheme, host, path, query, fragment = urlparse.urlsplit(url)
# urlparse.parse_qsl gives back url-decoded byte strings. Leave these as
# they are: they will be re-urlencoded below
query_bits = [(k, v) for k, v in urlparse.parse_qsl(query)]
if update:
query_bits = dict(query_bits)
query_bits.update(_make_query_tuples(params))
else:
query_bits.extend(_make_query_tuples(params))
query = urllib.urlencode(query_bits)
return urlparse.urlunsplit([scheme, host, path, query, fragment])
<|fim▁end|> | update_query_params |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue<|fim▁hole|> if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())<|fim▁end|> | testname = path.join(root, fn)[:-4] |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
<|fim_middle|>
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False) |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
<|fim_middle|>
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
<|fim_middle|>
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1 |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
<|fim_middle|>
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read() |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
<|fim_middle|>
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex] |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
<|fim_middle|>
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | errindex = real_stdout.find('error: Process didn\'t exit successfully') |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
<|fim_middle|>
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | real_stdout = real_stdout[:errindex] |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
<|fim_middle|>
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
<|fim_middle|>
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False) |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
<|fim_middle|>
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode) |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
<|fim_middle|>
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | print('*** ERROR: compilation failed')
raise RuntimeError |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
<|fim_middle|>
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | return 2 |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
<|fim_middle|>
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | continue |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
<|fim_middle|>
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | continue |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
<|fim_middle|>
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | continue |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
<|fim_middle|>
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | testcode = path.join(root, 'fft.i') |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
<|fim_middle|>
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | testcode = path.join(root, 'life2.i') |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
<|fim_middle|>
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
<|fim_middle|>
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | print('Failed:')
for testname in failed:
print(' ' + testname) |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | sys.exit(main()) |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def <|fim_middle|>(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | run_test |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def <|fim_middle|>(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def main():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | check |
<|file_name|>test.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------------
# Rick, a Rust intercal compiler. Save your souls!
#
# Copyright (c) 2015-2021 Georg Brandl
#
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program;
# if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# -------------------------------------------------------------------------------------------------
import os
import sys
import time
import difflib
from os import path
from subprocess import Popen, PIPE, STDOUT
already_compiled = set()
def run_test(testname, testcode, compiled):
stdin = b''
if path.isfile(testname + '.tst'):
with open(testname + '.tst', 'rb') as stdinfile:
stdin = stdinfile.read()
with open(testname + '.chk', 'r') as stdoutfile:
stdout = stdoutfile.read()
def check(proc, remove_cargo):
real_stdout, _ = proc.communicate(stdin)
real_stdout = real_stdout.decode()
# remove cargo's "Running" line
if remove_cargo:
errindex = real_stdout.find('An unknown error occurred')
if errindex == -1:
errindex = real_stdout.find('error: Process didn\'t exit successfully')
if errindex > -1:
real_stdout = real_stdout[:errindex]
if real_stdout != stdout:
print('*** ERROR: standard output does not match check file')
print(''.join(difflib.unified_diff(stdout.splitlines(True),
real_stdout.splitlines(True))))
raise RuntimeError
print('')
print('>>> Test: ' + testname)
print(' > Step 1: interpreted')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbi', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
print(' > Step 2: interpreted + optimized')
check(Popen(['cargo', 'run', '--release', '-q', '--', '-Rbio', testcode],
stdin=PIPE, stdout=PIPE, stderr=STDOUT), True)
if compiled:
print(' > Step 3: compiled + optimized')
if testcode not in already_compiled:
if os.system('cargo run --release -q -- -RFbo %s > /dev/null' % testcode) != 0:
print('*** ERROR: compilation failed')
raise RuntimeError
already_compiled.add(testcode)
check(Popen([testcode[:-2]], stdin=PIPE, stdout=PIPE, stderr=STDOUT),
False)
def <|fim_middle|>():
start = time.time()
compile_flag = '--nocompile' not in sys.argv
skip_flag = '--all' not in sys.argv
tests = [path.splitext(test.replace('/', os.sep))[0]
for test in sys.argv[1:] if not test.startswith('-')]
print('Building...')
if os.system('cargo build --release') != 0:
return 2
print('Running tests, please wait...')
passed = 0
total = 0
failed = []
for root, dirs, files in os.walk('code'):
dirs.sort()
for fn in sorted(files):
if not fn.endswith('.chk'):
continue
if skip_flag and fn.startswith(('fft-', 'flonck', 'unlambda')):
continue
testname = path.join(root, fn)[:-4]
if tests and testname not in tests:
continue
testcode = testname + '.i'
# special case
if fn.startswith('fft-'):
testcode = path.join(root, 'fft.i')
elif fn.startswith('life-'):
testcode = path.join(root, 'life2.i')
if not path.isfile(testcode):
print('')
print('*** WARNING: found %s.chk, but not %s' % (testname, testcode))
continue
total += 1
try:
t1 = time.time()
run_test(testname, testcode, compile_flag)
t2 = time.time()
passed += 1
print('--- passed (%5.2f sec)' % (t2 - t1))
except RuntimeError:
failed.append(testname)
end = time.time()
print('')
print('RESULT: %d/%d tests passed (%6.2f sec)' % (passed, total, end - start))
if failed:
print('Failed:')
for testname in failed:
print(' ' + testname)
return 0 if passed == total else 1
if __name__ == '__main__':
sys.exit(main())
<|fim▁end|> | main |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'<|fim▁hole|>paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)<|fim▁end|> | elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1)) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
<|fim_middle|>
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return '' |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
<|fim_middle|>
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site') |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
<|fim_middle|>
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | """
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1})) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
<|fim_middle|>
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | """
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1)) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
<|fim_middle|>
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | """
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
} |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
<|fim_middle|>
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | """
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
<|fim_middle|>
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | self.nodelist = nodelist
self.delimiter = delimiter |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
<|fim_middle|>
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
<|fim_middle|>
<|fim▁end|> | try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
<|fim_middle|>
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site')) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
<|fim_middle|>
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | return '' |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
<|fim_middle|>
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | return Site.objects.get_current().name |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
<|fim_middle|>
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | return _('Django site') |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
<|fim_middle|>
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | return u'<li><a href="#">...</a></li>' |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
<|fim_middle|>
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1)) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
<|fim_middle|>
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1)) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
<|fim_middle|>
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | page_range = [] |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
<|fim_middle|>
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages)) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
<|fim_middle|>
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | page_range = range(paginator.num_pages) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
<|fim_middle|>
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages)) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
<|fim_middle|>
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1)) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
<|fim_middle|>
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | page_range.extend(range(0, page_num + 1)) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
<|fim_middle|>
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages)) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
<|fim_middle|>
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | page_range.extend(range(page_num + 1, paginator.num_pages)) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
<|fim_middle|>
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | return '' |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
<|fim_middle|>
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]] |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
<|fim_middle|>
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | active = ' class="active"'
d[0] = d[0][1:] |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
<|fim_middle|>
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | active = '' |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
<|fim_middle|>
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | divider = '' |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
<|fim_middle|>
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | divider = '<span class="divider">/</span>' |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
<|fim_middle|>
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
<|fim_middle|>
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | out += '<li%s>%s%s</li>' % (active, d[0], divider) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
<|fim_middle|>
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d)) |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def <|fim_middle|>():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | atb_site_link |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def <|fim_middle|>():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | atb_site_name |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def <|fim_middle|>(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | bootstrap_page_url |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def <|fim_middle|>(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | bootstrap_paginator_number |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def <|fim_middle|>(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | bootstrap_pagination |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def <|fim_middle|>(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | __init__ |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def <|fim_middle|>(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def do_breadcrumbs(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | render |
<|file_name|>admintools_bootstrap.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.contrib.admin.views.main import PAGE_VAR, ALL_VAR
from django.conf import settings
from django.contrib.sites.models import Site
from BeautifulSoup import BeautifulSoup
register = template.Library()
@register.simple_tag
def atb_site_link():
if settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK:
return '''
<li><a href="%s" class="top-icon" title="%s" rel="popover" data-placement="below"><i
class="icon-home icon-white"></i></a></li>
<li class="divider-vertical"></li>
''' % (settings.ADMINTOOLS_BOOTSTRAP_SITE_LINK, _('Open site'))
else:
return ''
@register.simple_tag
def atb_site_name():
if 'django.contrib.sites' in settings.INSTALLED_APPS:
return Site.objects.get_current().name
else:
return _('Django site')
@register.simple_tag
def bootstrap_page_url(cl, page_num):
"""
generates page URL for given page_num, uses for prev and next links
django numerates pages from 0
"""
return escape(cl.get_query_string({PAGE_VAR: page_num-1}))
DOT = '.'
def bootstrap_paginator_number(cl,i, li_class=None):
"""
Generates an individual page index link in a paginated list.
"""
if i == DOT:
return u'<li><a href="#">...</a></li>'
elif i == cl.page_num:
return mark_safe(u'<li class="active"><a href="#">%d</a></li> ' % (i+1))
else:
return mark_safe(u'<li><a href="%s">%d</a></li>' % (escape(cl.get_query_string({PAGE_VAR: i})), i+1))
paginator_number = register.simple_tag(bootstrap_paginator_number)
def bootstrap_pagination(cl):
"""
Generates the series of links to the pages in a paginated list.
"""
paginator, page_num = cl.paginator, cl.page_num
pagination_required = (not cl.show_all or not cl.can_show_all) and cl.multi_page
if not pagination_required:
page_range = []
else:
ON_EACH_SIDE = 3
ON_ENDS = 2
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
# ON_EACH_SIDE links at either end of the "current page" link.
page_range = []
if page_num > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(0, ON_EACH_SIDE - 1))
page_range.append(DOT)
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {
'cl': cl,
'pagination_required': pagination_required,
'show_all_url': need_show_all_link and cl.get_query_string({ALL_VAR: ''}),
'page_range': page_range,
'ALL_VAR': ALL_VAR,
'1': 1,
'curr_page': cl.paginator.page(cl.page_num+1),
}
bootstrap_pagination = register.inclusion_tag('admin/pagination.html')(bootstrap_pagination)
# breadcrumbs tag
class BreadcrumbsNode(template.Node):
"""
renders bootstrap breadcrumbs list.
usage::
{% breadcrumbs %}
url1|text1
url2|text2
text3
{% endbreadcrumbs %}
| is delimiter by default, you can use {% breadcrumbs delimiter_char %} to change it.
lines without delimiters are interpreted as active breadcrumbs
"""
def __init__(self, nodelist, delimiter):
self.nodelist = nodelist
self.delimiter = delimiter
def render(self, context):
data = self.nodelist.render(context).strip()
if not data:
return ''
try:
data.index('<div class="breadcrumbs">')
except ValueError:
lines = [ l.strip().split(self.delimiter) for l in data.split("\n") if l.strip() ]
else:
# data is django-style breadcrumbs, parsing
try:
soup = BeautifulSoup(data)
lines = [ (a.get('href'), a.text) for a in soup.findAll('a')]
lines.append([soup.find('div').text.split('›')[-1].strip()])
except Exception, e:
lines = [["Cannot parse breadcrumbs: %s" % unicode(e)]]
out = '<ul class="breadcrumb">'
curr = 0
for d in lines:
if d[0][0] == '*':
active = ' class="active"'
d[0] = d[0][1:]
else:
active = ''
curr += 1
if (len(lines) == curr):
# last
divider = ''
else:
divider = '<span class="divider">/</span>'
if len(d) == 2:
out += '<li%s><a href="%s">%s</a>%s</li>' % (active, d[0], d[1], divider)
elif len(d) == 1:
out += '<li%s>%s%s</li>' % (active, d[0], divider)
else:
raise ValueError('Invalid breadcrumb line: %s' % self.delimiter.join(d))
out += '</ul>'
return out
@register.tag(name='breadcrumbs')
def <|fim_middle|>(parser, token):
try:
tag_name, delimiter = token.contents.split(None, 1)
except ValueError:
delimiter = '|'
nodelist = parser.parse(('endbreadcrumbs',))
parser.delete_first_token()
return BreadcrumbsNode(nodelist, delimiter)
<|fim▁end|> | do_breadcrumbs |
<|file_name|>0c431867c679_pets_now_have_a_description.py<|end_file_name|><|fim▁begin|><|fim▁hole|>
Revision ID: 0c431867c679
Revises: 5b1bdc1f3125
Create Date: 2016-11-07 18:36:25.912155
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0c431867c679'
down_revision = '5b1bdc1f3125'
branch_labels = None
depends_on = None
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('pet', sa.Column('description', sa.Text(), nullable=False))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('pet', 'description')
### end Alembic commands ###<|fim▁end|> | """Pets now have a description |
<|file_name|>0c431867c679_pets_now_have_a_description.py<|end_file_name|><|fim▁begin|>"""Pets now have a description
Revision ID: 0c431867c679
Revises: 5b1bdc1f3125
Create Date: 2016-11-07 18:36:25.912155
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0c431867c679'
down_revision = '5b1bdc1f3125'
branch_labels = None
depends_on = None
def upgrade():
### commands auto generated by Alembic - please adjust! ###
<|fim_middle|>
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('pet', 'description')
### end Alembic commands ###
<|fim▁end|> | op.add_column('pet', sa.Column('description', sa.Text(), nullable=False))
### end Alembic commands ### |
<|file_name|>0c431867c679_pets_now_have_a_description.py<|end_file_name|><|fim▁begin|>"""Pets now have a description
Revision ID: 0c431867c679
Revises: 5b1bdc1f3125
Create Date: 2016-11-07 18:36:25.912155
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0c431867c679'
down_revision = '5b1bdc1f3125'
branch_labels = None
depends_on = None
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('pet', sa.Column('description', sa.Text(), nullable=False))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
<|fim_middle|>
<|fim▁end|> | op.drop_column('pet', 'description')
### end Alembic commands ### |
<|file_name|>0c431867c679_pets_now_have_a_description.py<|end_file_name|><|fim▁begin|>"""Pets now have a description
Revision ID: 0c431867c679
Revises: 5b1bdc1f3125
Create Date: 2016-11-07 18:36:25.912155
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0c431867c679'
down_revision = '5b1bdc1f3125'
branch_labels = None
depends_on = None
def <|fim_middle|>():
### commands auto generated by Alembic - please adjust! ###
op.add_column('pet', sa.Column('description', sa.Text(), nullable=False))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('pet', 'description')
### end Alembic commands ###
<|fim▁end|> | upgrade |
<|file_name|>0c431867c679_pets_now_have_a_description.py<|end_file_name|><|fim▁begin|>"""Pets now have a description
Revision ID: 0c431867c679
Revises: 5b1bdc1f3125
Create Date: 2016-11-07 18:36:25.912155
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0c431867c679'
down_revision = '5b1bdc1f3125'
branch_labels = None
depends_on = None
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('pet', sa.Column('description', sa.Text(), nullable=False))
### end Alembic commands ###
def <|fim_middle|>():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('pet', 'description')
### end Alembic commands ###
<|fim▁end|> | downgrade |
<|file_name|>test_view_list_all_medications.py<|end_file_name|><|fim▁begin|>from django.test import TestCase
from medicine.models import Medicine
from medicine.views import ListAllMedicines
from user.models import HealthProfessional
class TestListAllMedicines(TestCase):
def setUp(self):
# Making a HealthProfessional<|fim▁hole|>
# Making medicati
self.medicine = Medicine()
self.medicine.name = "Medicamento Teste"
self.medicine.active_ingredient = "Teste Lab"
self.medicine.save()
self.listing = Medicine.objects.all()
def test_medicine_is_show(self):
instance = self.view()
self.assertEqual(instance.get_queryset()[0], self.listing[0])<|fim▁end|> |
self.view = ListAllMedicines |
<|file_name|>test_view_list_all_medications.py<|end_file_name|><|fim▁begin|>from django.test import TestCase
from medicine.models import Medicine
from medicine.views import ListAllMedicines
from user.models import HealthProfessional
class TestListAllMedicines(TestCase):
<|fim_middle|>
<|fim▁end|> | def setUp(self):
# Making a HealthProfessional
self.view = ListAllMedicines
# Making medicati
self.medicine = Medicine()
self.medicine.name = "Medicamento Teste"
self.medicine.active_ingredient = "Teste Lab"
self.medicine.save()
self.listing = Medicine.objects.all()
def test_medicine_is_show(self):
instance = self.view()
self.assertEqual(instance.get_queryset()[0], self.listing[0]) |
<|file_name|>test_view_list_all_medications.py<|end_file_name|><|fim▁begin|>from django.test import TestCase
from medicine.models import Medicine
from medicine.views import ListAllMedicines
from user.models import HealthProfessional
class TestListAllMedicines(TestCase):
def setUp(self):
# Making a HealthProfessional
<|fim_middle|>
def test_medicine_is_show(self):
instance = self.view()
self.assertEqual(instance.get_queryset()[0], self.listing[0])
<|fim▁end|> | self.view = ListAllMedicines
# Making medicati
self.medicine = Medicine()
self.medicine.name = "Medicamento Teste"
self.medicine.active_ingredient = "Teste Lab"
self.medicine.save()
self.listing = Medicine.objects.all() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.