repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
Gjum/agarnet | agarnet/utils.py | find_server | def find_server(region='EU-London', mode=None):
"""
Returns `(address, token)`, both strings.
`mode` is the game mode of the requested server. It can be
`'party'`, `'teams'`, `'experimental'`, or `None` for "Free for all".
The returned `address` is in `'IP:port'` format.
Makes a request to http://m.agar.io to get address and token.
"""
if mode:
region = '%s:%s' % (region, mode)
opener = urllib.request.build_opener()
opener.addheaders = default_headers
data = '%s\n%s' % (region, handshake_version)
return opener.open('http://m.agar.io/', data=data.encode()) \
.read().decode().split('\n')[0:2] | python | def find_server(region='EU-London', mode=None):
"""
Returns `(address, token)`, both strings.
`mode` is the game mode of the requested server. It can be
`'party'`, `'teams'`, `'experimental'`, or `None` for "Free for all".
The returned `address` is in `'IP:port'` format.
Makes a request to http://m.agar.io to get address and token.
"""
if mode:
region = '%s:%s' % (region, mode)
opener = urllib.request.build_opener()
opener.addheaders = default_headers
data = '%s\n%s' % (region, handshake_version)
return opener.open('http://m.agar.io/', data=data.encode()) \
.read().decode().split('\n')[0:2] | [
"def",
"find_server",
"(",
"region",
"=",
"'EU-London'",
",",
"mode",
"=",
"None",
")",
":",
"if",
"mode",
":",
"region",
"=",
"'%s:%s'",
"%",
"(",
"region",
",",
"mode",
")",
"opener",
"=",
"urllib",
".",
"request",
".",
"build_opener",
"(",
")",
"o... | Returns `(address, token)`, both strings.
`mode` is the game mode of the requested server. It can be
`'party'`, `'teams'`, `'experimental'`, or `None` for "Free for all".
The returned `address` is in `'IP:port'` format.
Makes a request to http://m.agar.io to get address and token. | [
"Returns",
"(",
"address",
"token",
")",
"both",
"strings",
"."
] | train | https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/utils.py#L20-L37 |
Gjum/agarnet | agarnet/utils.py | get_party_address | def get_party_address(party_token):
"""
Returns the address (`'IP:port'` string) of the party server.
To generate a `party_token`:
```
from agarnet.utils import find_server
_, token = find_server(mode='party')
```
Makes a request to http://m.agar.io/getToken to get the address.
"""
opener = urllib.request.build_opener()
opener.addheaders = default_headers
try:
data = party_token.encode()
return opener.open('http://m.agar.io/getToken', data=data) \
.read().decode().split('\n')[0]
except urllib.error.HTTPError:
raise ValueError('Invalid token "%s" (maybe timed out,'
' try creating a new one)' % party_token) | python | def get_party_address(party_token):
"""
Returns the address (`'IP:port'` string) of the party server.
To generate a `party_token`:
```
from agarnet.utils import find_server
_, token = find_server(mode='party')
```
Makes a request to http://m.agar.io/getToken to get the address.
"""
opener = urllib.request.build_opener()
opener.addheaders = default_headers
try:
data = party_token.encode()
return opener.open('http://m.agar.io/getToken', data=data) \
.read().decode().split('\n')[0]
except urllib.error.HTTPError:
raise ValueError('Invalid token "%s" (maybe timed out,'
' try creating a new one)' % party_token) | [
"def",
"get_party_address",
"(",
"party_token",
")",
":",
"opener",
"=",
"urllib",
".",
"request",
".",
"build_opener",
"(",
")",
"opener",
".",
"addheaders",
"=",
"default_headers",
"try",
":",
"data",
"=",
"party_token",
".",
"encode",
"(",
")",
"return",
... | Returns the address (`'IP:port'` string) of the party server.
To generate a `party_token`:
```
from agarnet.utils import find_server
_, token = find_server(mode='party')
```
Makes a request to http://m.agar.io/getToken to get the address. | [
"Returns",
"the",
"address",
"(",
"IP",
":",
"port",
"string",
")",
"of",
"the",
"party",
"server",
"."
] | train | https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/utils.py#L40-L60 |
honmaple/flask-maple | flask_maple/captcha.py | GenCaptcha.create_lines | def create_lines(self, draw, n_line, width, height):
'''绘制干扰线'''
line_num = randint(n_line[0], n_line[1]) # 干扰线条数
for i in range(line_num):
# 起始点
begin = (randint(0, width), randint(0, height))
# 结束点
end = (randint(0, width), randint(0, height))
draw.line([begin, end], fill=(0, 0, 0)) | python | def create_lines(self, draw, n_line, width, height):
'''绘制干扰线'''
line_num = randint(n_line[0], n_line[1]) # 干扰线条数
for i in range(line_num):
# 起始点
begin = (randint(0, width), randint(0, height))
# 结束点
end = (randint(0, width), randint(0, height))
draw.line([begin, end], fill=(0, 0, 0)) | [
"def",
"create_lines",
"(",
"self",
",",
"draw",
",",
"n_line",
",",
"width",
",",
"height",
")",
":",
"line_num",
"=",
"randint",
"(",
"n_line",
"[",
"0",
"]",
",",
"n_line",
"[",
"1",
"]",
")",
"# 干扰线条数",
"for",
"i",
"in",
"range",
"(",
"line_num... | 绘制干扰线 | [
"绘制干扰线"
] | train | https://github.com/honmaple/flask-maple/blob/8124de55e5e531a5cb43477944168f98608dc08f/flask_maple/captcha.py#L94-L102 |
honmaple/flask-maple | flask_maple/captcha.py | GenCaptcha.create_points | def create_points(self, draw, point_chance, width, height):
'''绘制干扰点'''
chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100]
for w in range(width):
for h in range(height):
tmp = randint(0, 100)
if tmp > 100 - chance:
draw.point((w, h), fill=(0, 0, 0)) | python | def create_points(self, draw, point_chance, width, height):
'''绘制干扰点'''
chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100]
for w in range(width):
for h in range(height):
tmp = randint(0, 100)
if tmp > 100 - chance:
draw.point((w, h), fill=(0, 0, 0)) | [
"def",
"create_points",
"(",
"self",
",",
"draw",
",",
"point_chance",
",",
"width",
",",
"height",
")",
":",
"chance",
"=",
"min",
"(",
"100",
",",
"max",
"(",
"0",
",",
"int",
"(",
"point_chance",
")",
")",
")",
"# 大小限制在[0, 100]",
"for",
"w",
"in",... | 绘制干扰点 | [
"绘制干扰点"
] | train | https://github.com/honmaple/flask-maple/blob/8124de55e5e531a5cb43477944168f98608dc08f/flask_maple/captcha.py#L104-L112 |
gwastro/pycbc-glue | misc/generate_vcs_info.py | call_out | def call_out(command):
"""
Run the given command (with shell=False) and return a tuple of
(int returncode, str output). Strip the output of enclosing whitespace.
"""
# start external command process
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# get outputs
out, _ = p.communicate()
return p.returncode, out.strip() | python | def call_out(command):
"""
Run the given command (with shell=False) and return a tuple of
(int returncode, str output). Strip the output of enclosing whitespace.
"""
# start external command process
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# get outputs
out, _ = p.communicate()
return p.returncode, out.strip() | [
"def",
"call_out",
"(",
"command",
")",
":",
"# start external command process",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"# get outputs",
"out",
... | Run the given command (with shell=False) and return a tuple of
(int returncode, str output). Strip the output of enclosing whitespace. | [
"Run",
"the",
"given",
"command",
"(",
"with",
"shell",
"=",
"False",
")",
"and",
"return",
"a",
"tuple",
"of",
"(",
"int",
"returncode",
"str",
"output",
")",
".",
"Strip",
"the",
"output",
"of",
"enclosing",
"whitespace",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/misc/generate_vcs_info.py#L96-L107 |
gwastro/pycbc-glue | misc/generate_vcs_info.py | check_call_out | def check_call_out(command):
"""
Run the given command (with shell=False) and return the output as a
string. Strip the output of enclosing whitespace.
If the return code is non-zero, throw GitInvocationError.
"""
# start external command process
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# get outputs
out, _ = p.communicate()
# throw exception if process failed
if p.returncode != 0:
raise GitInvocationError, 'failed to run "%s"' % " ".join(command)
return out.strip() | python | def check_call_out(command):
"""
Run the given command (with shell=False) and return the output as a
string. Strip the output of enclosing whitespace.
If the return code is non-zero, throw GitInvocationError.
"""
# start external command process
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# get outputs
out, _ = p.communicate()
# throw exception if process failed
if p.returncode != 0:
raise GitInvocationError, 'failed to run "%s"' % " ".join(command)
return out.strip() | [
"def",
"check_call_out",
"(",
"command",
")",
":",
"# start external command process",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"# get outputs",
"ou... | Run the given command (with shell=False) and return the output as a
string. Strip the output of enclosing whitespace.
If the return code is non-zero, throw GitInvocationError. | [
"Run",
"the",
"given",
"command",
"(",
"with",
"shell",
"=",
"False",
")",
"and",
"return",
"the",
"output",
"as",
"a",
"string",
".",
"Strip",
"the",
"output",
"of",
"enclosing",
"whitespace",
".",
"If",
"the",
"return",
"code",
"is",
"non",
"-",
"zer... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/misc/generate_vcs_info.py#L109-L125 |
humangeo/rawes | rawes/thrift_connection.py | ThriftConnection._dict_to_map_str_str | def _dict_to_map_str_str(self, d):
"""
Thrift requires the params and headers dict values to only contain str values.
"""
return dict(map(
lambda (k, v): (k, str(v).lower() if isinstance(v, bool) else str(v)),
d.iteritems()
)) | python | def _dict_to_map_str_str(self, d):
"""
Thrift requires the params and headers dict values to only contain str values.
"""
return dict(map(
lambda (k, v): (k, str(v).lower() if isinstance(v, bool) else str(v)),
d.iteritems()
)) | [
"def",
"_dict_to_map_str_str",
"(",
"self",
",",
"d",
")",
":",
"return",
"dict",
"(",
"map",
"(",
"lambda",
"(",
"k",
",",
"v",
")",
":",
"(",
"k",
",",
"str",
"(",
"v",
")",
".",
"lower",
"(",
")",
"if",
"isinstance",
"(",
"v",
",",
"bool",
... | Thrift requires the params and headers dict values to only contain str values. | [
"Thrift",
"requires",
"the",
"params",
"and",
"headers",
"dict",
"values",
"to",
"only",
"contain",
"str",
"values",
"."
] | train | https://github.com/humangeo/rawes/blob/b860100cbb4115a1c884133c83eae448ded6b2d3/rawes/thrift_connection.py#L94-L101 |
radzak/rtv-downloader | rtv/utils.py | suppress_stdout | def suppress_stdout():
"""
Context manager that suppresses stdout.
Examples:
>>> with suppress_stdout():
... print('Test print')
>>> print('test')
test
"""
save_stdout = sys.stdout
sys.stdout = DevNull()
yield
sys.stdout = save_stdout | python | def suppress_stdout():
"""
Context manager that suppresses stdout.
Examples:
>>> with suppress_stdout():
... print('Test print')
>>> print('test')
test
"""
save_stdout = sys.stdout
sys.stdout = DevNull()
yield
sys.stdout = save_stdout | [
"def",
"suppress_stdout",
"(",
")",
":",
"save_stdout",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stdout",
"=",
"DevNull",
"(",
")",
"yield",
"sys",
".",
"stdout",
"=",
"save_stdout"
] | Context manager that suppresses stdout.
Examples:
>>> with suppress_stdout():
... print('Test print')
>>> print('test')
test | [
"Context",
"manager",
"that",
"suppresses",
"stdout",
"."
] | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L25-L40 |
radzak/rtv-downloader | rtv/utils.py | get_domain_name | def get_domain_name(url):
"""
Extract a domain name from the url (without subdomain).
Args:
url (str): Url.
Returns:
str: Domain name.
Raises:
DomainNotMatchedError: If url is wrong.
Examples:
>>> get_domain_name('https://vod.tvp.pl/video/')
'tvp.pl'
>>> get_domain_name('https://vod')
Traceback (most recent call last):
...
rtv.exceptions.WrongUrlError: Couldn't match domain name of this url: https://vod
"""
if not validate_url(url):
raise WrongUrlError(f'Couldn\'t match domain name of this url: {url}')
ext = tldextract.extract(url)
return f'{ext.domain}.{ext.suffix}' | python | def get_domain_name(url):
"""
Extract a domain name from the url (without subdomain).
Args:
url (str): Url.
Returns:
str: Domain name.
Raises:
DomainNotMatchedError: If url is wrong.
Examples:
>>> get_domain_name('https://vod.tvp.pl/video/')
'tvp.pl'
>>> get_domain_name('https://vod')
Traceback (most recent call last):
...
rtv.exceptions.WrongUrlError: Couldn't match domain name of this url: https://vod
"""
if not validate_url(url):
raise WrongUrlError(f'Couldn\'t match domain name of this url: {url}')
ext = tldextract.extract(url)
return f'{ext.domain}.{ext.suffix}' | [
"def",
"get_domain_name",
"(",
"url",
")",
":",
"if",
"not",
"validate_url",
"(",
"url",
")",
":",
"raise",
"WrongUrlError",
"(",
"f'Couldn\\'t match domain name of this url: {url}'",
")",
"ext",
"=",
"tldextract",
".",
"extract",
"(",
"url",
")",
"return",
"f'{... | Extract a domain name from the url (without subdomain).
Args:
url (str): Url.
Returns:
str: Domain name.
Raises:
DomainNotMatchedError: If url is wrong.
Examples:
>>> get_domain_name('https://vod.tvp.pl/video/')
'tvp.pl'
>>> get_domain_name('https://vod')
Traceback (most recent call last):
...
rtv.exceptions.WrongUrlError: Couldn't match domain name of this url: https://vod | [
"Extract",
"a",
"domain",
"name",
"from",
"the",
"url",
"(",
"without",
"subdomain",
")",
"."
] | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L68-L95 |
radzak/rtv-downloader | rtv/utils.py | clean_video_data | def clean_video_data(_data):
"""
Clean video data:
-> cleans title
-> ...
Args:
_data (dict): Information about the video.
Returns:
dict: Refined video data.
"""
data = _data.copy()
# TODO: fix this ugliness
title = data.get('title')
if title:
data['title'] = clean_title(title)
return data | python | def clean_video_data(_data):
"""
Clean video data:
-> cleans title
-> ...
Args:
_data (dict): Information about the video.
Returns:
dict: Refined video data.
"""
data = _data.copy()
# TODO: fix this ugliness
title = data.get('title')
if title:
data['title'] = clean_title(title)
return data | [
"def",
"clean_video_data",
"(",
"_data",
")",
":",
"data",
"=",
"_data",
".",
"copy",
"(",
")",
"# TODO: fix this ugliness",
"title",
"=",
"data",
".",
"get",
"(",
"'title'",
")",
"if",
"title",
":",
"data",
"[",
"'title'",
"]",
"=",
"clean_title",
"(",
... | Clean video data:
-> cleans title
-> ...
Args:
_data (dict): Information about the video.
Returns:
dict: Refined video data. | [
"Clean",
"video",
"data",
":",
"-",
">",
"cleans",
"title",
"-",
">",
"..."
] | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L98-L119 |
radzak/rtv-downloader | rtv/utils.py | clean_title | def clean_title(title):
"""
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
"""
date_pattern = re.compile(r'\W*'
r'\d{1,2}'
r'[/\-.]'
r'\d{1,2}'
r'[/\-.]'
r'(?=\d*)(?:.{4}|.{2})'
r'\W*')
title = date_pattern.sub(' ', title)
title = re.sub(r'\s{2,}', ' ', title)
title = title.strip()
return title | python | def clean_title(title):
"""
Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces.
"""
date_pattern = re.compile(r'\W*'
r'\d{1,2}'
r'[/\-.]'
r'\d{1,2}'
r'[/\-.]'
r'(?=\d*)(?:.{4}|.{2})'
r'\W*')
title = date_pattern.sub(' ', title)
title = re.sub(r'\s{2,}', ' ', title)
title = title.strip()
return title | [
"def",
"clean_title",
"(",
"title",
")",
":",
"date_pattern",
"=",
"re",
".",
"compile",
"(",
"r'\\W*'",
"r'\\d{1,2}'",
"r'[/\\-.]'",
"r'\\d{1,2}'",
"r'[/\\-.]'",
"r'(?=\\d*)(?:.{4}|.{2})'",
"r'\\W*'",
")",
"title",
"=",
"date_pattern",
".",
"sub",
"(",
"' '",
"... | Clean title -> remove dates, remove duplicated spaces and strip title.
Args:
title (str): Title.
Returns:
str: Clean title without dates, duplicated, trailing and leading spaces. | [
"Clean",
"title",
"-",
">",
"remove",
"dates",
"remove",
"duplicated",
"spaces",
"and",
"strip",
"title",
"."
] | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L122-L143 |
radzak/rtv-downloader | rtv/utils.py | get_ext | def get_ext(url):
"""
Extract an extension from the url.
Args:
url (str): String representation of a url.
Returns:
str: Filename extension from a url (without a dot), '' if extension is not present.
"""
parsed = urllib.parse.urlparse(url)
root, ext = os.path.splitext(parsed.path)
return ext.lstrip('.') | python | def get_ext(url):
"""
Extract an extension from the url.
Args:
url (str): String representation of a url.
Returns:
str: Filename extension from a url (without a dot), '' if extension is not present.
"""
parsed = urllib.parse.urlparse(url)
root, ext = os.path.splitext(parsed.path)
return ext.lstrip('.') | [
"def",
"get_ext",
"(",
"url",
")",
":",
"parsed",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"root",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"parsed",
".",
"path",
")",
"return",
"ext",
".",
"lstrip",
"(",
"'... | Extract an extension from the url.
Args:
url (str): String representation of a url.
Returns:
str: Filename extension from a url (without a dot), '' if extension is not present. | [
"Extract",
"an",
"extension",
"from",
"the",
"url",
"."
] | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L176-L190 |
radzak/rtv-downloader | rtv/utils.py | delete_duplicates | def delete_duplicates(seq):
"""
Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects.
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | python | def delete_duplicates(seq):
"""
Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects.
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | [
"def",
"delete_duplicates",
"(",
"seq",
")",
":",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"return",
"[",
"x",
"for",
"x",
"in",
"seq",
"if",
"not",
"(",
"x",
"in",
"seen",
"or",
"seen_add",
"(",
"x",
")",
")",
"]"
] | Remove duplicates from an iterable, preserving the order.
Args:
seq: Iterable of various type.
Returns:
list: List of unique objects. | [
"Remove",
"duplicates",
"from",
"an",
"iterable",
"preserving",
"the",
"order",
"."
] | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/utils.py#L193-L206 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkCollection.py | RethinkCollection.joinOn | def joinOn(self, model, onIndex):
"""
Performs an eqJoin on with the given model. The resulting join will be
accessible through the models name.
"""
return self._joinOnAsPriv(model, onIndex, model.__name__) | python | def joinOn(self, model, onIndex):
"""
Performs an eqJoin on with the given model. The resulting join will be
accessible through the models name.
"""
return self._joinOnAsPriv(model, onIndex, model.__name__) | [
"def",
"joinOn",
"(",
"self",
",",
"model",
",",
"onIndex",
")",
":",
"return",
"self",
".",
"_joinOnAsPriv",
"(",
"model",
",",
"onIndex",
",",
"model",
".",
"__name__",
")"
] | Performs an eqJoin on with the given model. The resulting join will be
accessible through the models name. | [
"Performs",
"an",
"eqJoin",
"on",
"with",
"the",
"given",
"model",
".",
"The",
"resulting",
"join",
"will",
"be",
"accessible",
"through",
"the",
"models",
"name",
"."
] | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkCollection.py#L37-L42 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkCollection.py | RethinkCollection.joinOnAs | def joinOnAs(self, model, onIndex, whatAs):
"""
Like `joinOn` but allows setting the joined results name to access it
from.
Performs an eqJoin on with the given model. The resulting join will be
accessible through the given name.
"""
return self._joinOnAsPriv(model, onIndex, whatAs) | python | def joinOnAs(self, model, onIndex, whatAs):
"""
Like `joinOn` but allows setting the joined results name to access it
from.
Performs an eqJoin on with the given model. The resulting join will be
accessible through the given name.
"""
return self._joinOnAsPriv(model, onIndex, whatAs) | [
"def",
"joinOnAs",
"(",
"self",
",",
"model",
",",
"onIndex",
",",
"whatAs",
")",
":",
"return",
"self",
".",
"_joinOnAsPriv",
"(",
"model",
",",
"onIndex",
",",
"whatAs",
")"
] | Like `joinOn` but allows setting the joined results name to access it
from.
Performs an eqJoin on with the given model. The resulting join will be
accessible through the given name. | [
"Like",
"joinOn",
"but",
"allows",
"setting",
"the",
"joined",
"results",
"name",
"to",
"access",
"it",
"from",
"."
] | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkCollection.py#L44-L52 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkCollection.py | RethinkCollection._joinOnAsPriv | def _joinOnAsPriv(self, model, onIndex, whatAs):
"""
Private method for handling joins.
"""
if self._join:
raise Exception("Already joined with a table!")
self._join = model
self._joinedField = whatAs
table = model.table
self._query = self._query.eq_join(onIndex, r.table(table))
return self | python | def _joinOnAsPriv(self, model, onIndex, whatAs):
"""
Private method for handling joins.
"""
if self._join:
raise Exception("Already joined with a table!")
self._join = model
self._joinedField = whatAs
table = model.table
self._query = self._query.eq_join(onIndex, r.table(table))
return self | [
"def",
"_joinOnAsPriv",
"(",
"self",
",",
"model",
",",
"onIndex",
",",
"whatAs",
")",
":",
"if",
"self",
".",
"_join",
":",
"raise",
"Exception",
"(",
"\"Already joined with a table!\"",
")",
"self",
".",
"_join",
"=",
"model",
"self",
".",
"_joinedField",
... | Private method for handling joins. | [
"Private",
"method",
"for",
"handling",
"joins",
"."
] | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkCollection.py#L54-L65 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkCollection.py | RethinkCollection.orderBy | def orderBy(self, field, direct="desc"):
"""
Allows for the results to be ordered by a specific field. If given,
direction can be set with passing an additional argument in the form
of "asc" or "desc"
"""
if direct == "desc":
self._query = self._query.order_by(r.desc(field))
else:
self._query = self._query.order_by(r.asc(field))
return self | python | def orderBy(self, field, direct="desc"):
"""
Allows for the results to be ordered by a specific field. If given,
direction can be set with passing an additional argument in the form
of "asc" or "desc"
"""
if direct == "desc":
self._query = self._query.order_by(r.desc(field))
else:
self._query = self._query.order_by(r.asc(field))
return self | [
"def",
"orderBy",
"(",
"self",
",",
"field",
",",
"direct",
"=",
"\"desc\"",
")",
":",
"if",
"direct",
"==",
"\"desc\"",
":",
"self",
".",
"_query",
"=",
"self",
".",
"_query",
".",
"order_by",
"(",
"r",
".",
"desc",
"(",
"field",
")",
")",
"else",... | Allows for the results to be ordered by a specific field. If given,
direction can be set with passing an additional argument in the form
of "asc" or "desc" | [
"Allows",
"for",
"the",
"results",
"to",
"be",
"ordered",
"by",
"a",
"specific",
"field",
".",
"If",
"given",
"direction",
"can",
"be",
"set",
"with",
"passing",
"an",
"additional",
"argument",
"in",
"the",
"form",
"of",
"asc",
"or",
"desc"
] | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkCollection.py#L67-L78 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkCollection.py | RethinkCollection.offset | def offset(self, value):
"""
Allows for skipping a specified number of results in query. Useful
for pagination.
"""
self._query = self._query.skip(value)
return self | python | def offset(self, value):
"""
Allows for skipping a specified number of results in query. Useful
for pagination.
"""
self._query = self._query.skip(value)
return self | [
"def",
"offset",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_query",
"=",
"self",
".",
"_query",
".",
"skip",
"(",
"value",
")",
"return",
"self"
] | Allows for skipping a specified number of results in query. Useful
for pagination. | [
"Allows",
"for",
"skipping",
"a",
"specified",
"number",
"of",
"results",
"in",
"query",
".",
"Useful",
"for",
"pagination",
"."
] | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkCollection.py#L84-L92 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkCollection.py | RethinkCollection.limit | def limit(self, value):
"""
Allows for limiting number of results returned for query. Useful
for pagination.
"""
self._query = self._query.limit(value)
return self | python | def limit(self, value):
"""
Allows for limiting number of results returned for query. Useful
for pagination.
"""
self._query = self._query.limit(value)
return self | [
"def",
"limit",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_query",
"=",
"self",
".",
"_query",
".",
"limit",
"(",
"value",
")",
"return",
"self"
] | Allows for limiting number of results returned for query. Useful
for pagination. | [
"Allows",
"for",
"limiting",
"number",
"of",
"results",
"returned",
"for",
"query",
".",
"Useful",
"for",
"pagination",
"."
] | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkCollection.py#L94-L101 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkCollection.py | RethinkCollection.fetch | def fetch(self):
"""
Fetches the query and then tries to wrap the data in the model, joining
as needed, if applicable.
"""
returnResults = []
results = self._query.run()
for result in results:
if self._join:
# Because we can tell the models to ignore certian fields,
# through the protectedItems blacklist, we can nest models by
# name and have each one act normal and not accidentally store
# extra data from other models
item = self._model.fromRawEntry(**result["left"])
joined = self._join.fromRawEntry(**result["right"])
item.protectedItems = self._joinedField
item[self._joinedField] = joined
else:
item = self._model.fromRawEntry(**result)
returnResults.append(item)
self._documents = returnResults
return self._documents | python | def fetch(self):
"""
Fetches the query and then tries to wrap the data in the model, joining
as needed, if applicable.
"""
returnResults = []
results = self._query.run()
for result in results:
if self._join:
# Because we can tell the models to ignore certian fields,
# through the protectedItems blacklist, we can nest models by
# name and have each one act normal and not accidentally store
# extra data from other models
item = self._model.fromRawEntry(**result["left"])
joined = self._join.fromRawEntry(**result["right"])
item.protectedItems = self._joinedField
item[self._joinedField] = joined
else:
item = self._model.fromRawEntry(**result)
returnResults.append(item)
self._documents = returnResults
return self._documents | [
"def",
"fetch",
"(",
"self",
")",
":",
"returnResults",
"=",
"[",
"]",
"results",
"=",
"self",
".",
"_query",
".",
"run",
"(",
")",
"for",
"result",
"in",
"results",
":",
"if",
"self",
".",
"_join",
":",
"# Because we can tell the models to ignore certian fi... | Fetches the query and then tries to wrap the data in the model, joining
as needed, if applicable. | [
"Fetches",
"the",
"query",
"and",
"then",
"tries",
"to",
"wrap",
"the",
"data",
"in",
"the",
"model",
"joining",
"as",
"needed",
"if",
"applicable",
"."
] | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkCollection.py#L125-L150 |
mthornhill/django-postal | src/postal/utils.py | coerce_put_post | def coerce_put_post(request):
"""
Django doesn't particularly understand REST.
In case we send data over PUT, Django won't
actually look at the data and load it. We need
to twist its arm here.
The try/except abominiation here is due to a bug
in mod_python. This should fix it.
"""
if request.method == "PUT":
# Bug fix: if _load_post_and_files has already been called, for
# example by middleware accessing request.POST, the below code to
# pretend the request is a POST instead of a PUT will be too late
# to make a difference. Also calling _load_post_and_files will result
# in the following exception:
# AttributeError: You cannot set the upload handlers after the upload has been processed.
# The fix is to check for the presence of the _post field which is set
# the first time _load_post_and_files is called (both by wsgi.py and
# modpython.py). If it's set, the request has to be 'reset' to redo
# the query value parsing in POST mode.
if hasattr(request, '_post'):
del request._post
del request._files
try:
request.method = "POST"
request._load_post_and_files()
request.method = "PUT"
except AttributeError:
request.META['REQUEST_METHOD'] = 'POST'
request._load_post_and_files()
request.META['REQUEST_METHOD'] = 'PUT'
request.PUT = request.POST | python | def coerce_put_post(request):
"""
Django doesn't particularly understand REST.
In case we send data over PUT, Django won't
actually look at the data and load it. We need
to twist its arm here.
The try/except abominiation here is due to a bug
in mod_python. This should fix it.
"""
if request.method == "PUT":
# Bug fix: if _load_post_and_files has already been called, for
# example by middleware accessing request.POST, the below code to
# pretend the request is a POST instead of a PUT will be too late
# to make a difference. Also calling _load_post_and_files will result
# in the following exception:
# AttributeError: You cannot set the upload handlers after the upload has been processed.
# The fix is to check for the presence of the _post field which is set
# the first time _load_post_and_files is called (both by wsgi.py and
# modpython.py). If it's set, the request has to be 'reset' to redo
# the query value parsing in POST mode.
if hasattr(request, '_post'):
del request._post
del request._files
try:
request.method = "POST"
request._load_post_and_files()
request.method = "PUT"
except AttributeError:
request.META['REQUEST_METHOD'] = 'POST'
request._load_post_and_files()
request.META['REQUEST_METHOD'] = 'PUT'
request.PUT = request.POST | [
"def",
"coerce_put_post",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"PUT\"",
":",
"# Bug fix: if _load_post_and_files has already been called, for",
"# example by middleware accessing request.POST, the below code to",
"# pretend the request is a POST instead of ... | Django doesn't particularly understand REST.
In case we send data over PUT, Django won't
actually look at the data and load it. We need
to twist its arm here.
The try/except abominiation here is due to a bug
in mod_python. This should fix it. | [
"Django",
"doesn",
"t",
"particularly",
"understand",
"REST",
".",
"In",
"case",
"we",
"send",
"data",
"over",
"PUT",
"Django",
"won",
"t",
"actually",
"look",
"at",
"the",
"data",
"and",
"load",
"it",
".",
"We",
"need",
"to",
"twist",
"its",
"arm",
"h... | train | https://github.com/mthornhill/django-postal/blob/21d65e09b45f0515cde6166345f46c3f506dd08f/src/postal/utils.py#L78-L112 |
mthornhill/django-postal | src/postal/utils.py | Mimer.loader_for_type | def loader_for_type(self, ctype):
"""
Gets a function ref to deserialize content
for a certain mimetype.
"""
for loadee, mimes in Mimer.TYPES.iteritems():
for mime in mimes:
if ctype.startswith(mime):
return loadee | python | def loader_for_type(self, ctype):
"""
Gets a function ref to deserialize content
for a certain mimetype.
"""
for loadee, mimes in Mimer.TYPES.iteritems():
for mime in mimes:
if ctype.startswith(mime):
return loadee | [
"def",
"loader_for_type",
"(",
"self",
",",
"ctype",
")",
":",
"for",
"loadee",
",",
"mimes",
"in",
"Mimer",
".",
"TYPES",
".",
"iteritems",
"(",
")",
":",
"for",
"mime",
"in",
"mimes",
":",
"if",
"ctype",
".",
"startswith",
"(",
"mime",
")",
":",
... | Gets a function ref to deserialize content
for a certain mimetype. | [
"Gets",
"a",
"function",
"ref",
"to",
"deserialize",
"content",
"for",
"a",
"certain",
"mimetype",
"."
] | train | https://github.com/mthornhill/django-postal/blob/21d65e09b45f0515cde6166345f46c3f506dd08f/src/postal/utils.py#L136-L144 |
mthornhill/django-postal | src/postal/utils.py | Mimer.content_type | def content_type(self):
"""
Returns the content type of the request in all cases where it is
different than a submitted form - application/x-www-form-urlencoded
"""
type_formencoded = "application/x-www-form-urlencoded"
ctype = self.request.META.get('CONTENT_TYPE', type_formencoded)
if type_formencoded in ctype:
return None
return ctype | python | def content_type(self):
"""
Returns the content type of the request in all cases where it is
different than a submitted form - application/x-www-form-urlencoded
"""
type_formencoded = "application/x-www-form-urlencoded"
ctype = self.request.META.get('CONTENT_TYPE', type_formencoded)
if type_formencoded in ctype:
return None
return ctype | [
"def",
"content_type",
"(",
"self",
")",
":",
"type_formencoded",
"=",
"\"application/x-www-form-urlencoded\"",
"ctype",
"=",
"self",
".",
"request",
".",
"META",
".",
"get",
"(",
"'CONTENT_TYPE'",
",",
"type_formencoded",
")",
"if",
"type_formencoded",
"in",
"cty... | Returns the content type of the request in all cases where it is
different than a submitted form - application/x-www-form-urlencoded | [
"Returns",
"the",
"content",
"type",
"of",
"the",
"request",
"in",
"all",
"cases",
"where",
"it",
"is",
"different",
"than",
"a",
"submitted",
"form",
"-",
"application",
"/",
"x",
"-",
"www",
"-",
"form",
"-",
"urlencoded"
] | train | https://github.com/mthornhill/django-postal/blob/21d65e09b45f0515cde6166345f46c3f506dd08f/src/postal/utils.py#L146-L158 |
mthornhill/django-postal | src/postal/utils.py | Mimer.translate | def translate(self):
"""
Will look at the `Content-type` sent by the client, and maybe
deserialize the contents into the format they sent. This will
work for JSON, YAML, XML and Pickle. Since the data is not just
key-value (and maybe just a list), the data will be placed on
`request.data` instead, and the handler will have to read from
there.
It will also set `request.content_type` so the handler has an easy
way to tell what's going on. `request.content_type` will always be
None for form-encoded and/or multipart form data (what your browser sends.)
"""
ctype = self.content_type()
self.request.content_type = ctype
if not self.is_multipart() and ctype:
loadee = self.loader_for_type(ctype)
if loadee:
try:
self.request.data = loadee(self.request.raw_post_data)
# Reset both POST and PUT from request, as its
# misleading having their presence around.
self.request.POST = self.request.PUT = dict()
except (TypeError, ValueError):
# This also catches if loadee is None.
raise MimerDataException
else:
self.request.data = None
return self.request | python | def translate(self):
"""
Will look at the `Content-type` sent by the client, and maybe
deserialize the contents into the format they sent. This will
work for JSON, YAML, XML and Pickle. Since the data is not just
key-value (and maybe just a list), the data will be placed on
`request.data` instead, and the handler will have to read from
there.
It will also set `request.content_type` so the handler has an easy
way to tell what's going on. `request.content_type` will always be
None for form-encoded and/or multipart form data (what your browser sends.)
"""
ctype = self.content_type()
self.request.content_type = ctype
if not self.is_multipart() and ctype:
loadee = self.loader_for_type(ctype)
if loadee:
try:
self.request.data = loadee(self.request.raw_post_data)
# Reset both POST and PUT from request, as its
# misleading having their presence around.
self.request.POST = self.request.PUT = dict()
except (TypeError, ValueError):
# This also catches if loadee is None.
raise MimerDataException
else:
self.request.data = None
return self.request | [
"def",
"translate",
"(",
"self",
")",
":",
"ctype",
"=",
"self",
".",
"content_type",
"(",
")",
"self",
".",
"request",
".",
"content_type",
"=",
"ctype",
"if",
"not",
"self",
".",
"is_multipart",
"(",
")",
"and",
"ctype",
":",
"loadee",
"=",
"self",
... | Will look at the `Content-type` sent by the client, and maybe
deserialize the contents into the format they sent. This will
work for JSON, YAML, XML and Pickle. Since the data is not just
key-value (and maybe just a list), the data will be placed on
`request.data` instead, and the handler will have to read from
there.
It will also set `request.content_type` so the handler has an easy
way to tell what's going on. `request.content_type` will always be
None for form-encoded and/or multipart form data (what your browser sends.) | [
"Will",
"look",
"at",
"the",
"Content",
"-",
"type",
"sent",
"by",
"the",
"client",
"and",
"maybe",
"deserialize",
"the",
"contents",
"into",
"the",
"format",
"they",
"sent",
".",
"This",
"will",
"work",
"for",
"JSON",
"YAML",
"XML",
"and",
"Pickle",
"."... | train | https://github.com/mthornhill/django-postal/blob/21d65e09b45f0515cde6166345f46c3f506dd08f/src/postal/utils.py#L160-L192 |
mk-fg/feedjack | feedjack/fjcloud.py | getsteps | def getsteps(levels, tagmax):
""" Returns a list with the max number of posts per "tagcloud level"
"""
ntw = levels
if ntw < 2:
ntw = 2
steps = [(stp, 1 + (stp * int(math.ceil(tagmax * 1.0 / ntw - 1))))
for stp in range(ntw)]
# just to be sure~
steps[-1] = (steps[-1][0], tagmax+1)
return steps | python | def getsteps(levels, tagmax):
""" Returns a list with the max number of posts per "tagcloud level"
"""
ntw = levels
if ntw < 2:
ntw = 2
steps = [(stp, 1 + (stp * int(math.ceil(tagmax * 1.0 / ntw - 1))))
for stp in range(ntw)]
# just to be sure~
steps[-1] = (steps[-1][0], tagmax+1)
return steps | [
"def",
"getsteps",
"(",
"levels",
",",
"tagmax",
")",
":",
"ntw",
"=",
"levels",
"if",
"ntw",
"<",
"2",
":",
"ntw",
"=",
"2",
"steps",
"=",
"[",
"(",
"stp",
",",
"1",
"+",
"(",
"stp",
"*",
"int",
"(",
"math",
".",
"ceil",
"(",
"tagmax",
"*",
... | Returns a list with the max number of posts per "tagcloud level" | [
"Returns",
"a",
"list",
"with",
"the",
"max",
"number",
"of",
"posts",
"per",
"tagcloud",
"level"
] | train | https://github.com/mk-fg/feedjack/blob/3fe65c0f66dc2cfdf45834aaa7235ec9f81b3ca3/feedjack/fjcloud.py#L9-L20 |
mk-fg/feedjack | feedjack/fjcloud.py | build | def build(site, tagdata):
""" Returns the tag cloud for a list of tags.
"""
tagdata.sort()
# we get the most popular tag to calculate the tags' weigth
tagmax = 0
for tagname, tagcount in tagdata:
if tagcount > tagmax:
tagmax = tagcount
steps = getsteps(site.tagcloud_levels, tagmax)
tags = []
for tagname, tagcount in tagdata:
weight = [twt[0] \
for twt in steps if twt[1] >= tagcount and twt[1] > 0][0]+1
tags.append({'tagname':tagname, 'count':tagcount, 'weight':weight})
return tags | python | def build(site, tagdata):
""" Returns the tag cloud for a list of tags.
"""
tagdata.sort()
# we get the most popular tag to calculate the tags' weigth
tagmax = 0
for tagname, tagcount in tagdata:
if tagcount > tagmax:
tagmax = tagcount
steps = getsteps(site.tagcloud_levels, tagmax)
tags = []
for tagname, tagcount in tagdata:
weight = [twt[0] \
for twt in steps if twt[1] >= tagcount and twt[1] > 0][0]+1
tags.append({'tagname':tagname, 'count':tagcount, 'weight':weight})
return tags | [
"def",
"build",
"(",
"site",
",",
"tagdata",
")",
":",
"tagdata",
".",
"sort",
"(",
")",
"# we get the most popular tag to calculate the tags' weigth",
"tagmax",
"=",
"0",
"for",
"tagname",
",",
"tagcount",
"in",
"tagdata",
":",
"if",
"tagcount",
">",
"tagmax",
... | Returns the tag cloud for a list of tags. | [
"Returns",
"the",
"tag",
"cloud",
"for",
"a",
"list",
"of",
"tags",
"."
] | train | https://github.com/mk-fg/feedjack/blob/3fe65c0f66dc2cfdf45834aaa7235ec9f81b3ca3/feedjack/fjcloud.py#L22-L40 |
mk-fg/feedjack | feedjack/fjcloud.py | getquery | def getquery(query):
'Performs a query and get the results.'
try:
conn = connection.cursor()
conn.execute(query)
data = conn.fetchall()
conn.close()
except: data = list()
return data | python | def getquery(query):
'Performs a query and get the results.'
try:
conn = connection.cursor()
conn.execute(query)
data = conn.fetchall()
conn.close()
except: data = list()
return data | [
"def",
"getquery",
"(",
"query",
")",
":",
"try",
":",
"conn",
"=",
"connection",
".",
"cursor",
"(",
")",
"conn",
".",
"execute",
"(",
"query",
")",
"data",
"=",
"conn",
".",
"fetchall",
"(",
")",
"conn",
".",
"close",
"(",
")",
"except",
":",
"... | Performs a query and get the results. | [
"Performs",
"a",
"query",
"and",
"get",
"the",
"results",
"."
] | train | https://github.com/mk-fg/feedjack/blob/3fe65c0f66dc2cfdf45834aaa7235ec9f81b3ca3/feedjack/fjcloud.py#L42-L50 |
mk-fg/feedjack | feedjack/fjcloud.py | cloudata | def cloudata(site):
""" Returns a dictionary with all the tag clouds related to a site.
"""
# XXX: this looks like it can be done via ORM
tagdata = getquery("""
SELECT feedjack_post.feed_id, feedjack_tag.name, COUNT(*)
FROM feedjack_post, feedjack_subscriber, feedjack_tag,
feedjack_post_tags
WHERE feedjack_post.feed_id=feedjack_subscriber.feed_id AND
feedjack_post_tags.tag_id=feedjack_tag.id AND
feedjack_post_tags.post_id=feedjack_post.id AND
feedjack_subscriber.site_id=%d
GROUP BY feedjack_post.feed_id, feedjack_tag.name
ORDER BY feedjack_post.feed_id, feedjack_tag.name""" % site.id)
tagdict = {}
globaldict = {}
cloudict = {}
for feed_id, tagname, tagcount in tagdata:
if feed_id not in tagdict:
tagdict[feed_id] = []
tagdict[feed_id].append((tagname, tagcount))
try:
globaldict[tagname] += tagcount
except KeyError:
globaldict[tagname] = tagcount
tagdict[0] = globaldict.items()
for key, val in tagdict.items():
cloudict[key] = build(site, val)
return cloudict | python | def cloudata(site):
""" Returns a dictionary with all the tag clouds related to a site.
"""
# XXX: this looks like it can be done via ORM
tagdata = getquery("""
SELECT feedjack_post.feed_id, feedjack_tag.name, COUNT(*)
FROM feedjack_post, feedjack_subscriber, feedjack_tag,
feedjack_post_tags
WHERE feedjack_post.feed_id=feedjack_subscriber.feed_id AND
feedjack_post_tags.tag_id=feedjack_tag.id AND
feedjack_post_tags.post_id=feedjack_post.id AND
feedjack_subscriber.site_id=%d
GROUP BY feedjack_post.feed_id, feedjack_tag.name
ORDER BY feedjack_post.feed_id, feedjack_tag.name""" % site.id)
tagdict = {}
globaldict = {}
cloudict = {}
for feed_id, tagname, tagcount in tagdata:
if feed_id not in tagdict:
tagdict[feed_id] = []
tagdict[feed_id].append((tagname, tagcount))
try:
globaldict[tagname] += tagcount
except KeyError:
globaldict[tagname] = tagcount
tagdict[0] = globaldict.items()
for key, val in tagdict.items():
cloudict[key] = build(site, val)
return cloudict | [
"def",
"cloudata",
"(",
"site",
")",
":",
"# XXX: this looks like it can be done via ORM",
"tagdata",
"=",
"getquery",
"(",
"\"\"\"\n\t\tSELECT feedjack_post.feed_id, feedjack_tag.name, COUNT(*)\n\t\tFROM feedjack_post, feedjack_subscriber, feedjack_tag,\n\t\tfeedjack_post_tags\n\t\tWHERE feed... | Returns a dictionary with all the tag clouds related to a site. | [
"Returns",
"a",
"dictionary",
"with",
"all",
"the",
"tag",
"clouds",
"related",
"to",
"a",
"site",
"."
] | train | https://github.com/mk-fg/feedjack/blob/3fe65c0f66dc2cfdf45834aaa7235ec9f81b3ca3/feedjack/fjcloud.py#L52-L81 |
mk-fg/feedjack | feedjack/fjcloud.py | getcloud | def getcloud(site, feed_id=None):
""" Returns the tag cloud for a site or a site's subscriber.
"""
cloudict = fjcache.cache_get(site.id, 'tagclouds')
if not cloudict:
cloudict = cloudata(site)
fjcache.cache_set(site, 'tagclouds', cloudict)
# A subscriber's tag cloud has been requested.
if feed_id:
feed_id = int(feed_id)
if feed_id in cloudict:
return cloudict[feed_id]
return []
# The site tagcloud has been requested.
return cloudict[0] | python | def getcloud(site, feed_id=None):
""" Returns the tag cloud for a site or a site's subscriber.
"""
cloudict = fjcache.cache_get(site.id, 'tagclouds')
if not cloudict:
cloudict = cloudata(site)
fjcache.cache_set(site, 'tagclouds', cloudict)
# A subscriber's tag cloud has been requested.
if feed_id:
feed_id = int(feed_id)
if feed_id in cloudict:
return cloudict[feed_id]
return []
# The site tagcloud has been requested.
return cloudict[0] | [
"def",
"getcloud",
"(",
"site",
",",
"feed_id",
"=",
"None",
")",
":",
"cloudict",
"=",
"fjcache",
".",
"cache_get",
"(",
"site",
".",
"id",
",",
"'tagclouds'",
")",
"if",
"not",
"cloudict",
":",
"cloudict",
"=",
"cloudata",
"(",
"site",
")",
"fjcache"... | Returns the tag cloud for a site or a site's subscriber. | [
"Returns",
"the",
"tag",
"cloud",
"for",
"a",
"site",
"or",
"a",
"site",
"s",
"subscriber",
"."
] | train | https://github.com/mk-fg/feedjack/blob/3fe65c0f66dc2cfdf45834aaa7235ec9f81b3ca3/feedjack/fjcloud.py#L83-L99 |
bcho/gzbus | gzbus/extract.py | extract_stations | def extract_stations(page):
'''Extract bus stations from routine page.
:param page: crawled page.
'''
stations = [_(station.value) for station in page('.stateName')]
return {
'terminal': {
stations[0]: list(reversed(stations)),
stations[-1]: stations
},
'stations': stations
} | python | def extract_stations(page):
'''Extract bus stations from routine page.
:param page: crawled page.
'''
stations = [_(station.value) for station in page('.stateName')]
return {
'terminal': {
stations[0]: list(reversed(stations)),
stations[-1]: stations
},
'stations': stations
} | [
"def",
"extract_stations",
"(",
"page",
")",
":",
"stations",
"=",
"[",
"_",
"(",
"station",
".",
"value",
")",
"for",
"station",
"in",
"page",
"(",
"'.stateName'",
")",
"]",
"return",
"{",
"'terminal'",
":",
"{",
"stations",
"[",
"0",
"]",
":",
"lis... | Extract bus stations from routine page.
:param page: crawled page. | [
"Extract",
"bus",
"stations",
"from",
"routine",
"page",
"."
] | train | https://github.com/bcho/gzbus/blob/4dd2cc2e5068331d0f4bed885cf999a1d107b8b4/gzbus/extract.py#L31-L43 |
bcho/gzbus | gzbus/extract.py | extract_current_routine | def extract_current_routine(page, stations):
'''Extract current routine information from page.
:param page: crawled page.
:param stations: bus stations list. See `~extract_stations`.
'''
current_routines = CURRENT_ROUTINE_PATTERN.findall(page.text())
if not current_routines:
return
terminal_station = stations['stations'][-1]
for routine in current_routines:
if _(routine[0]) == terminal_station:
distance = int(routine[1])
stations_to_this_dir = stations['terminal'][terminal_station]
waiting_station = _(page('.now .stateName').val())
idx = stations_to_this_dir.index(waiting_station)
bus_station = stations_to_this_dir[idx - distance + 1]
return {
'destinate_station': terminal_station,
'bus_station': bus_station,
'waiting_station': waiting_station,
'distance': distance
} | python | def extract_current_routine(page, stations):
'''Extract current routine information from page.
:param page: crawled page.
:param stations: bus stations list. See `~extract_stations`.
'''
current_routines = CURRENT_ROUTINE_PATTERN.findall(page.text())
if not current_routines:
return
terminal_station = stations['stations'][-1]
for routine in current_routines:
if _(routine[0]) == terminal_station:
distance = int(routine[1])
stations_to_this_dir = stations['terminal'][terminal_station]
waiting_station = _(page('.now .stateName').val())
idx = stations_to_this_dir.index(waiting_station)
bus_station = stations_to_this_dir[idx - distance + 1]
return {
'destinate_station': terminal_station,
'bus_station': bus_station,
'waiting_station': waiting_station,
'distance': distance
} | [
"def",
"extract_current_routine",
"(",
"page",
",",
"stations",
")",
":",
"current_routines",
"=",
"CURRENT_ROUTINE_PATTERN",
".",
"findall",
"(",
"page",
".",
"text",
"(",
")",
")",
"if",
"not",
"current_routines",
":",
"return",
"terminal_station",
"=",
"stati... | Extract current routine information from page.
:param page: crawled page.
:param stations: bus stations list. See `~extract_stations`. | [
"Extract",
"current",
"routine",
"information",
"from",
"page",
"."
] | train | https://github.com/bcho/gzbus/blob/4dd2cc2e5068331d0f4bed885cf999a1d107b8b4/gzbus/extract.py#L46-L71 |
bcho/gzbus | gzbus/extract.py | extract_bus_routine | def extract_bus_routine(page):
'''Extract bus routine information from page.
:param page: crawled page.
'''
if not isinstance(page, pq):
page = pq(page)
stations = extract_stations(page)
return {
# Routine name.
'name': extract_routine_name(page),
# Bus stations.
'stations': stations,
# Current routine.
'current': extract_current_routine(page, stations)
} | python | def extract_bus_routine(page):
'''Extract bus routine information from page.
:param page: crawled page.
'''
if not isinstance(page, pq):
page = pq(page)
stations = extract_stations(page)
return {
# Routine name.
'name': extract_routine_name(page),
# Bus stations.
'stations': stations,
# Current routine.
'current': extract_current_routine(page, stations)
} | [
"def",
"extract_bus_routine",
"(",
"page",
")",
":",
"if",
"not",
"isinstance",
"(",
"page",
",",
"pq",
")",
":",
"page",
"=",
"pq",
"(",
"page",
")",
"stations",
"=",
"extract_stations",
"(",
"page",
")",
"return",
"{",
"# Routine name.",
"'name'",
":",... | Extract bus routine information from page.
:param page: crawled page. | [
"Extract",
"bus",
"routine",
"information",
"from",
"page",
"."
] | train | https://github.com/bcho/gzbus/blob/4dd2cc2e5068331d0f4bed885cf999a1d107b8b4/gzbus/extract.py#L74-L92 |
lobocv/pyperform | pyperform/comparisonbenchmark.py | ComparisonBenchmark.validate | def validate(self):
"""
Execute the code once to get it's results (to be used in function validation). Compare the result to the
first function in the group.
"""
validation_code = self.setup_src + '\nvalidation_result = ' + self.stmt
validation_scope = {}
exec(validation_code, validation_scope)
# Store the result in the first function in the group.
if len(self.groups[self.group]) == 1:
self.result = validation_scope['validation_result']
logging.info('PyPerform: Validating group "{b.group}" against function "{b.callable.__name__}"'
.format(b=self))
else:
compare_against_benchmark = self.groups[self.group][0]
test = [benchmark.result_validation for benchmark in self.groups[self.group]]
if not all(test):
raise ValueError('All functions within a group must have the same validation flag.')
compare_result = compare_against_benchmark.result
if self.validation_func:
results_are_valid = self.validation_func(compare_result, validation_scope['validation_result'])
else:
results_are_valid = compare_result == validation_scope['validation_result']
if results_are_valid:
logging.info('PyPerform: Validating {}......PASSED!'.format(self.callable.__name__))
else:
error = 'Results of functions {0} and {1} are not equivalent.\n{0}:\t {2}\n{1}:\t{3}'
raise ValidationError(error.format(compare_against_benchmark.callable.__name__, self.callable.__name__,
compare_result, validation_scope['validation_result'])) | python | def validate(self):
"""
Execute the code once to get it's results (to be used in function validation). Compare the result to the
first function in the group.
"""
validation_code = self.setup_src + '\nvalidation_result = ' + self.stmt
validation_scope = {}
exec(validation_code, validation_scope)
# Store the result in the first function in the group.
if len(self.groups[self.group]) == 1:
self.result = validation_scope['validation_result']
logging.info('PyPerform: Validating group "{b.group}" against function "{b.callable.__name__}"'
.format(b=self))
else:
compare_against_benchmark = self.groups[self.group][0]
test = [benchmark.result_validation for benchmark in self.groups[self.group]]
if not all(test):
raise ValueError('All functions within a group must have the same validation flag.')
compare_result = compare_against_benchmark.result
if self.validation_func:
results_are_valid = self.validation_func(compare_result, validation_scope['validation_result'])
else:
results_are_valid = compare_result == validation_scope['validation_result']
if results_are_valid:
logging.info('PyPerform: Validating {}......PASSED!'.format(self.callable.__name__))
else:
error = 'Results of functions {0} and {1} are not equivalent.\n{0}:\t {2}\n{1}:\t{3}'
raise ValidationError(error.format(compare_against_benchmark.callable.__name__, self.callable.__name__,
compare_result, validation_scope['validation_result'])) | [
"def",
"validate",
"(",
"self",
")",
":",
"validation_code",
"=",
"self",
".",
"setup_src",
"+",
"'\\nvalidation_result = '",
"+",
"self",
".",
"stmt",
"validation_scope",
"=",
"{",
"}",
"exec",
"(",
"validation_code",
",",
"validation_scope",
")",
"# Store the ... | Execute the code once to get it's results (to be used in function validation). Compare the result to the
first function in the group. | [
"Execute",
"the",
"code",
"once",
"to",
"get",
"it",
"s",
"results",
"(",
"to",
"be",
"used",
"in",
"function",
"validation",
")",
".",
"Compare",
"the",
"result",
"to",
"the",
"first",
"function",
"in",
"the",
"group",
"."
] | train | https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/comparisonbenchmark.py#L36-L64 |
lobocv/pyperform | pyperform/comparisonbenchmark.py | ComparisonBenchmark.summarize | def summarize(group, fs=None, include_source=True):
"""
Tabulate and write the results of ComparisonBenchmarks to a file or standard out.
:param str group: name of the comparison group.
:param fs: file-like object (Optional)
"""
_line_break = '{0:-<120}\n'.format('')
tests = sorted(ComparisonBenchmark.groups[group], key=lambda t: getattr(t, 'time_average_seconds'))
log = StringIO.StringIO()
log.write('Call statement:\n\n')
log.write('\t' + tests[0].stmt)
log.write('\n\n\n')
fmt = "{0: <8} {1: <35} {2: <12} {3: <15} {4: <15} {5: <14}\n"
log.write(fmt.format('Rank', 'Function Name', 'Time', '% of Slowest', 'timeit_repeat', 'timeit_number'))
log.write(_line_break)
log.write('\n')
for i, t in enumerate(tests):
func_name = "{}.{}".format(t.classname, t.callable.__name__) if t.classname else t.callable.__name__
if i == len(tests)-1:
time_percent = 'Slowest'
else:
time_percent = "{:.1f}".format(t.time_average_seconds / tests[-1].time_average_seconds * 100)
log.write(fmt.format(i+1,
func_name,
convert_time_units(t.time_average_seconds),
time_percent,
t.timeit_repeat,
t.timeit_number))
log.write(_line_break)
if include_source:
log.write('\n\n\nSource Code:\n')
log.write(_line_break)
for test in tests:
log.write(test.log.getvalue())
log.write(_line_break)
if isinstance(fs, str):
with open(fs, 'w') as f:
f.write(log.getvalue())
elif fs is None:
print(log.getvalue())
else:
try:
fs.write(log.getvalue())
except AttributeError as e:
print(e) | python | def summarize(group, fs=None, include_source=True):
"""
Tabulate and write the results of ComparisonBenchmarks to a file or standard out.
:param str group: name of the comparison group.
:param fs: file-like object (Optional)
"""
_line_break = '{0:-<120}\n'.format('')
tests = sorted(ComparisonBenchmark.groups[group], key=lambda t: getattr(t, 'time_average_seconds'))
log = StringIO.StringIO()
log.write('Call statement:\n\n')
log.write('\t' + tests[0].stmt)
log.write('\n\n\n')
fmt = "{0: <8} {1: <35} {2: <12} {3: <15} {4: <15} {5: <14}\n"
log.write(fmt.format('Rank', 'Function Name', 'Time', '% of Slowest', 'timeit_repeat', 'timeit_number'))
log.write(_line_break)
log.write('\n')
for i, t in enumerate(tests):
func_name = "{}.{}".format(t.classname, t.callable.__name__) if t.classname else t.callable.__name__
if i == len(tests)-1:
time_percent = 'Slowest'
else:
time_percent = "{:.1f}".format(t.time_average_seconds / tests[-1].time_average_seconds * 100)
log.write(fmt.format(i+1,
func_name,
convert_time_units(t.time_average_seconds),
time_percent,
t.timeit_repeat,
t.timeit_number))
log.write(_line_break)
if include_source:
log.write('\n\n\nSource Code:\n')
log.write(_line_break)
for test in tests:
log.write(test.log.getvalue())
log.write(_line_break)
if isinstance(fs, str):
with open(fs, 'w') as f:
f.write(log.getvalue())
elif fs is None:
print(log.getvalue())
else:
try:
fs.write(log.getvalue())
except AttributeError as e:
print(e) | [
"def",
"summarize",
"(",
"group",
",",
"fs",
"=",
"None",
",",
"include_source",
"=",
"True",
")",
":",
"_line_break",
"=",
"'{0:-<120}\\n'",
".",
"format",
"(",
"''",
")",
"tests",
"=",
"sorted",
"(",
"ComparisonBenchmark",
".",
"groups",
"[",
"group",
... | Tabulate and write the results of ComparisonBenchmarks to a file or standard out.
:param str group: name of the comparison group.
:param fs: file-like object (Optional) | [
"Tabulate",
"and",
"write",
"the",
"results",
"of",
"ComparisonBenchmarks",
"to",
"a",
"file",
"or",
"standard",
"out",
".",
":",
"param",
"str",
"group",
":",
"name",
"of",
"the",
"comparison",
"group",
".",
":",
"param",
"fs",
":",
"file",
"-",
"like",... | train | https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/comparisonbenchmark.py#L67-L115 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkModel.py | RethinkModel._grabData | def _grabData(self, key):
"""
Tries to find the existing document in the database, if it is found,
then the objects _data is set to that document, and this returns
`True`, otherwise this will return `False`
:param key: The primary key of the object we're looking for
:type key: Str
:return: True if a document was found, otherwise False
:rtype: Boolean
"""
rawCursor = r.table(self.table).get(key).run(self._conn)
if rawCursor:
self._data = rawCursor
self._new = False
return True
else:
return False | python | def _grabData(self, key):
"""
Tries to find the existing document in the database, if it is found,
then the objects _data is set to that document, and this returns
`True`, otherwise this will return `False`
:param key: The primary key of the object we're looking for
:type key: Str
:return: True if a document was found, otherwise False
:rtype: Boolean
"""
rawCursor = r.table(self.table).get(key).run(self._conn)
if rawCursor:
self._data = rawCursor
self._new = False
return True
else:
return False | [
"def",
"_grabData",
"(",
"self",
",",
"key",
")",
":",
"rawCursor",
"=",
"r",
".",
"table",
"(",
"self",
".",
"table",
")",
".",
"get",
"(",
"key",
")",
".",
"run",
"(",
"self",
".",
"_conn",
")",
"if",
"rawCursor",
":",
"self",
".",
"_data",
"... | Tries to find the existing document in the database, if it is found,
then the objects _data is set to that document, and this returns
`True`, otherwise this will return `False`
:param key: The primary key of the object we're looking for
:type key: Str
:return: True if a document was found, otherwise False
:rtype: Boolean | [
"Tries",
"to",
"find",
"the",
"existing",
"document",
"in",
"the",
"database",
"if",
"it",
"is",
"found",
"then",
"the",
"objects",
"_data",
"is",
"set",
"to",
"that",
"document",
"and",
"this",
"returns",
"True",
"otherwise",
"this",
"will",
"return",
"Fa... | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkModel.py#L95-L113 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkModel.py | RethinkModel._get | def _get(self, item):
"""
Helper function to keep the __getattr__ and __getitem__ calls
KISSish
"""
if item not in object.__getattribute__(self, "_protectedItems") \
and item[0] != "_":
data = object.__getattribute__(self, "_data")
if item in data:
return data[item]
return object.__getattribute__(self, item) | python | def _get(self, item):
"""
Helper function to keep the __getattr__ and __getitem__ calls
KISSish
"""
if item not in object.__getattribute__(self, "_protectedItems") \
and item[0] != "_":
data = object.__getattribute__(self, "_data")
if item in data:
return data[item]
return object.__getattribute__(self, item) | [
"def",
"_get",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
"not",
"in",
"object",
".",
"__getattribute__",
"(",
"self",
",",
"\"_protectedItems\"",
")",
"and",
"item",
"[",
"0",
"]",
"!=",
"\"_\"",
":",
"data",
"=",
"object",
".",
"__getattribute... | Helper function to keep the __getattr__ and __getitem__ calls
KISSish | [
"Helper",
"function",
"to",
"keep",
"the",
"__getattr__",
"and",
"__getitem__",
"calls",
"KISSish"
] | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkModel.py#L125-L135 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkModel.py | RethinkModel._set | def _set(self, item, value):
"""
Helper function to keep the __setattr__ and __setitem__ calls
KISSish
Will only set the objects _data if the given items name is not prefixed
with _ or if the item exists in the protected items List.
"""
if item not in object.__getattribute__(self, "_protectedItems") \
and item[0] != "_":
keys = object.__getattribute__(self, "_data")
if not hasattr(value, '__call__'):
keys[item] = value
return value
if hasattr(value, '__call__') and item in keys:
raise Exception("""Cannot set model data to a function, same \
name exists in data""")
return object.__setattr__(self, item, value) | python | def _set(self, item, value):
"""
Helper function to keep the __setattr__ and __setitem__ calls
KISSish
Will only set the objects _data if the given items name is not prefixed
with _ or if the item exists in the protected items List.
"""
if item not in object.__getattribute__(self, "_protectedItems") \
and item[0] != "_":
keys = object.__getattribute__(self, "_data")
if not hasattr(value, '__call__'):
keys[item] = value
return value
if hasattr(value, '__call__') and item in keys:
raise Exception("""Cannot set model data to a function, same \
name exists in data""")
return object.__setattr__(self, item, value) | [
"def",
"_set",
"(",
"self",
",",
"item",
",",
"value",
")",
":",
"if",
"item",
"not",
"in",
"object",
".",
"__getattribute__",
"(",
"self",
",",
"\"_protectedItems\"",
")",
"and",
"item",
"[",
"0",
"]",
"!=",
"\"_\"",
":",
"keys",
"=",
"object",
".",... | Helper function to keep the __setattr__ and __setitem__ calls
KISSish
Will only set the objects _data if the given items name is not prefixed
with _ or if the item exists in the protected items List. | [
"Helper",
"function",
"to",
"keep",
"the",
"__setattr__",
"and",
"__setitem__",
"calls",
"KISSish"
] | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkModel.py#L137-L154 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkModel.py | RethinkModel.fromRawEntry | def fromRawEntry(cls, **kwargs):
"""
Helper function to allow wrapping existing data/entries, such as
those returned by collections.
"""
id = kwargs["id"]
kwargs.pop("id")
what = cls(**kwargs)
what._new = False
what.id = id
return what | python | def fromRawEntry(cls, **kwargs):
"""
Helper function to allow wrapping existing data/entries, such as
those returned by collections.
"""
id = kwargs["id"]
kwargs.pop("id")
what = cls(**kwargs)
what._new = False
what.id = id
return what | [
"def",
"fromRawEntry",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"id",
"=",
"kwargs",
"[",
"\"id\"",
"]",
"kwargs",
".",
"pop",
"(",
"\"id\"",
")",
"what",
"=",
"cls",
"(",
"*",
"*",
"kwargs",
")",
"what",
".",
"_new",
"=",
"False",
"what",
... | Helper function to allow wrapping existing data/entries, such as
those returned by collections. | [
"Helper",
"function",
"to",
"allow",
"wrapping",
"existing",
"data",
"/",
"entries",
"such",
"as",
"those",
"returned",
"by",
"collections",
"."
] | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkModel.py#L194-L207 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkModel.py | RethinkModel.create | def create(cls, id=None, **kwargs):
"""
Similar to new() however this calls save() on the object before
returning it.
"""
what = cls(**kwargs)
if id:
setattr(what, cls.primaryKey, id)
what.save()
return what | python | def create(cls, id=None, **kwargs):
"""
Similar to new() however this calls save() on the object before
returning it.
"""
what = cls(**kwargs)
if id:
setattr(what, cls.primaryKey, id)
what.save()
return what | [
"def",
"create",
"(",
"cls",
",",
"id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"what",
"=",
"cls",
"(",
"*",
"*",
"kwargs",
")",
"if",
"id",
":",
"setattr",
"(",
"what",
",",
"cls",
".",
"primaryKey",
",",
"id",
")",
"what",
".",
"sa... | Similar to new() however this calls save() on the object before
returning it. | [
"Similar",
"to",
"new",
"()",
"however",
"this",
"calls",
"save",
"()",
"on",
"the",
"object",
"before",
"returning",
"it",
"."
] | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkModel.py#L219-L228 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkModel.py | RethinkModel.save | def save(self):
"""
If an id exists in the database, we assume we'll update it, and if not
then we'll insert it. This could be a problem with creating your own
id's on new objects, however luckily, we keep track of if this is a new
object through a private _new variable, and use that to determine if we
insert or update.
"""
if not self._new:
data = self._data.copy()
ID = data.pop(self.primaryKey)
reply = r.table(self.table).get(ID) \
.update(data,
durability=self.durability,
non_atomic=self.non_atomic) \
.run(self._conn)
else:
reply = r.table(self.table) \
.insert(self._data,
durability=self.durability,
upsert=self.upsert) \
.run(self._conn)
self._new = False
if "generated_keys" in reply and reply["generated_keys"]:
self._data[self.primaryKey] = reply["generated_keys"][0]
if "errors" in reply and reply["errors"] > 0:
raise Exception("Could not insert entry: %s"
% reply["first_error"])
return True | python | def save(self):
"""
If an id exists in the database, we assume we'll update it, and if not
then we'll insert it. This could be a problem with creating your own
id's on new objects, however luckily, we keep track of if this is a new
object through a private _new variable, and use that to determine if we
insert or update.
"""
if not self._new:
data = self._data.copy()
ID = data.pop(self.primaryKey)
reply = r.table(self.table).get(ID) \
.update(data,
durability=self.durability,
non_atomic=self.non_atomic) \
.run(self._conn)
else:
reply = r.table(self.table) \
.insert(self._data,
durability=self.durability,
upsert=self.upsert) \
.run(self._conn)
self._new = False
if "generated_keys" in reply and reply["generated_keys"]:
self._data[self.primaryKey] = reply["generated_keys"][0]
if "errors" in reply and reply["errors"] > 0:
raise Exception("Could not insert entry: %s"
% reply["first_error"])
return True | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_new",
":",
"data",
"=",
"self",
".",
"_data",
".",
"copy",
"(",
")",
"ID",
"=",
"data",
".",
"pop",
"(",
"self",
".",
"primaryKey",
")",
"reply",
"=",
"r",
".",
"table",
"(",
"... | If an id exists in the database, we assume we'll update it, and if not
then we'll insert it. This could be a problem with creating your own
id's on new objects, however luckily, we keep track of if this is a new
object through a private _new variable, and use that to determine if we
insert or update. | [
"If",
"an",
"id",
"exists",
"in",
"the",
"database",
"we",
"assume",
"we",
"ll",
"update",
"it",
"and",
"if",
"not",
"then",
"we",
"ll",
"insert",
"it",
".",
"This",
"could",
"be",
"a",
"problem",
"with",
"creating",
"your",
"own",
"id",
"s",
"on",
... | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkModel.py#L243-L275 |
JoshAshby/pyRethinkORM | rethinkORM/rethinkModel.py | RethinkModel.delete | def delete(self):
"""
Deletes the current instance. This assumes that we know what we're
doing, and have a primary key in our data already. If this is a new
instance, then we'll let the user know with an Exception
"""
if self._new:
raise Exception("This is a new object, %s not in data, \
indicating this entry isn't stored." % self.primaryKey)
r.table(self.table).get(self._data[self.primaryKey]) \
.delete(durability=self.durability).run(self._conn)
return True | python | def delete(self):
"""
Deletes the current instance. This assumes that we know what we're
doing, and have a primary key in our data already. If this is a new
instance, then we'll let the user know with an Exception
"""
if self._new:
raise Exception("This is a new object, %s not in data, \
indicating this entry isn't stored." % self.primaryKey)
r.table(self.table).get(self._data[self.primaryKey]) \
.delete(durability=self.durability).run(self._conn)
return True | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"self",
".",
"_new",
":",
"raise",
"Exception",
"(",
"\"This is a new object, %s not in data, \\\nindicating this entry isn't stored.\"",
"%",
"self",
".",
"primaryKey",
")",
"r",
".",
"table",
"(",
"self",
".",
"table... | Deletes the current instance. This assumes that we know what we're
doing, and have a primary key in our data already. If this is a new
instance, then we'll let the user know with an Exception | [
"Deletes",
"the",
"current",
"instance",
".",
"This",
"assumes",
"that",
"we",
"know",
"what",
"we",
"re",
"doing",
"and",
"have",
"a",
"primary",
"key",
"in",
"our",
"data",
"already",
".",
"If",
"this",
"is",
"a",
"new",
"instance",
"then",
"we",
"ll... | train | https://github.com/JoshAshby/pyRethinkORM/blob/92158d146dea6cfe9022d7de2537403f5f2c1e02/rethinkORM/rethinkModel.py#L277-L289 |
aganezov/bg | bg/tree.py | BGTree.add_edge | def add_edge(self, node1_name, node2_name, edge_length=DEFAULT_EDGE_LENGTH):
""" Adds a new edge to the current tree with specified characteristics
Forbids addition of an edge, if a parent node is not present
Forbids addition of an edge, if a child node already exists
:param node1_name: name of the parent node, to which an edge shall be added
:param node2_name: name of newly added child node
:param edge_length: a length of specified edge
:return: nothing, inplace changes
:raises: ValueError (if parent node IS NOT present in the tree, or child node IS already present in the tree)
"""
if not self.__has_node(name=node1_name):
raise ValueError("Can not add an edge to a non-existing node {name}".format(name=node1_name))
if self.__has_node(name=node2_name):
raise ValueError("Can not add an edge to already existing node {name}".format(name=node2_name))
self.multicolors_are_up_to_date = False
self.__get_node_by_name(name=node1_name).add_child(name=node2_name, dist=edge_length) | python | def add_edge(self, node1_name, node2_name, edge_length=DEFAULT_EDGE_LENGTH):
""" Adds a new edge to the current tree with specified characteristics
Forbids addition of an edge, if a parent node is not present
Forbids addition of an edge, if a child node already exists
:param node1_name: name of the parent node, to which an edge shall be added
:param node2_name: name of newly added child node
:param edge_length: a length of specified edge
:return: nothing, inplace changes
:raises: ValueError (if parent node IS NOT present in the tree, or child node IS already present in the tree)
"""
if not self.__has_node(name=node1_name):
raise ValueError("Can not add an edge to a non-existing node {name}".format(name=node1_name))
if self.__has_node(name=node2_name):
raise ValueError("Can not add an edge to already existing node {name}".format(name=node2_name))
self.multicolors_are_up_to_date = False
self.__get_node_by_name(name=node1_name).add_child(name=node2_name, dist=edge_length) | [
"def",
"add_edge",
"(",
"self",
",",
"node1_name",
",",
"node2_name",
",",
"edge_length",
"=",
"DEFAULT_EDGE_LENGTH",
")",
":",
"if",
"not",
"self",
".",
"__has_node",
"(",
"name",
"=",
"node1_name",
")",
":",
"raise",
"ValueError",
"(",
"\"Can not add an edge... | Adds a new edge to the current tree with specified characteristics
Forbids addition of an edge, if a parent node is not present
Forbids addition of an edge, if a child node already exists
:param node1_name: name of the parent node, to which an edge shall be added
:param node2_name: name of newly added child node
:param edge_length: a length of specified edge
:return: nothing, inplace changes
:raises: ValueError (if parent node IS NOT present in the tree, or child node IS already present in the tree) | [
"Adds",
"a",
"new",
"edge",
"to",
"the",
"current",
"tree",
"with",
"specified",
"characteristics"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/tree.py#L69-L86 |
aganezov/bg | bg/tree.py | BGTree.__get_node_by_name | def __get_node_by_name(self, name):
""" Returns a first TreeNode object, which name matches the specified argument
:raises: ValueError (if no node with specified name is present in the tree)
"""
try:
for entry in filter(lambda x: x.name == name, self.nodes()):
return entry
except StopIteration:
raise ValueError("Attempted to retrieve a non-existing tree node with name: {name}"
"".format(name=name)) | python | def __get_node_by_name(self, name):
""" Returns a first TreeNode object, which name matches the specified argument
:raises: ValueError (if no node with specified name is present in the tree)
"""
try:
for entry in filter(lambda x: x.name == name, self.nodes()):
return entry
except StopIteration:
raise ValueError("Attempted to retrieve a non-existing tree node with name: {name}"
"".format(name=name)) | [
"def",
"__get_node_by_name",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"for",
"entry",
"in",
"filter",
"(",
"lambda",
"x",
":",
"x",
".",
"name",
"==",
"name",
",",
"self",
".",
"nodes",
"(",
")",
")",
":",
"return",
"entry",
"except",
"StopI... | Returns a first TreeNode object, which name matches the specified argument
:raises: ValueError (if no node with specified name is present in the tree) | [
"Returns",
"a",
"first",
"TreeNode",
"object",
"which",
"name",
"matches",
"the",
"specified",
"argument"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/tree.py#L92-L102 |
aganezov/bg | bg/tree.py | BGTree.__has_edge | def __has_edge(self, node1_name, node2_name, account_for_direction=True):
""" Returns a boolean flag, telling if a tree has an edge with two nodes, specified by their names as arguments
If a account_for_direction is specified as True, the order of specified node names has to relate to parent - child relation,
otherwise both possibilities are checked
"""
try:
p1 = self.__get_node_by_name(name=node1_name)
wdir = node2_name in (node.name for node in p1.children)
if account_for_direction:
return wdir
else:
p2 = self.__get_node_by_name(name=node2_name)
return wdir or node1_name in (node.name for node in p2.children)
except ValueError:
return False | python | def __has_edge(self, node1_name, node2_name, account_for_direction=True):
""" Returns a boolean flag, telling if a tree has an edge with two nodes, specified by their names as arguments
If a account_for_direction is specified as True, the order of specified node names has to relate to parent - child relation,
otherwise both possibilities are checked
"""
try:
p1 = self.__get_node_by_name(name=node1_name)
wdir = node2_name in (node.name for node in p1.children)
if account_for_direction:
return wdir
else:
p2 = self.__get_node_by_name(name=node2_name)
return wdir or node1_name in (node.name for node in p2.children)
except ValueError:
return False | [
"def",
"__has_edge",
"(",
"self",
",",
"node1_name",
",",
"node2_name",
",",
"account_for_direction",
"=",
"True",
")",
":",
"try",
":",
"p1",
"=",
"self",
".",
"__get_node_by_name",
"(",
"name",
"=",
"node1_name",
")",
"wdir",
"=",
"node2_name",
"in",
"("... | Returns a boolean flag, telling if a tree has an edge with two nodes, specified by their names as arguments
If a account_for_direction is specified as True, the order of specified node names has to relate to parent - child relation,
otherwise both possibilities are checked | [
"Returns",
"a",
"boolean",
"flag",
"telling",
"if",
"a",
"tree",
"has",
"an",
"edge",
"with",
"two",
"nodes",
"specified",
"by",
"their",
"names",
"as",
"arguments"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/tree.py#L104-L119 |
aganezov/bg | bg/tree.py | BGTree.has_edge | def has_edge(self, node1_name, node2_name, account_for_direction=True):
""" Proxies a call to the __has_edge method """
return self.__has_edge(node1_name=node1_name, node2_name=node2_name, account_for_direction=account_for_direction) | python | def has_edge(self, node1_name, node2_name, account_for_direction=True):
""" Proxies a call to the __has_edge method """
return self.__has_edge(node1_name=node1_name, node2_name=node2_name, account_for_direction=account_for_direction) | [
"def",
"has_edge",
"(",
"self",
",",
"node1_name",
",",
"node2_name",
",",
"account_for_direction",
"=",
"True",
")",
":",
"return",
"self",
".",
"__has_edge",
"(",
"node1_name",
"=",
"node1_name",
",",
"node2_name",
"=",
"node2_name",
",",
"account_for_directio... | Proxies a call to the __has_edge method | [
"Proxies",
"a",
"call",
"to",
"the",
"__has_edge",
"method"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/tree.py#L121-L123 |
aganezov/bg | bg/tree.py | BGTree.get_distance | def get_distance(self, node1_name, node2_name):
""" Returns a length of an edge / path, if exists, from the current tree
:param node1_name: a first node name in current tree
:param node2_name: a second node name in current tree
:return: a length of specified by a pair of vertices edge / path
:rtype: `Number`
:raises: ValueError, if requested a length of an edge, that is not present in current tree
"""
return self.__root.get_distance(target=node1_name, target2=node2_name) | python | def get_distance(self, node1_name, node2_name):
""" Returns a length of an edge / path, if exists, from the current tree
:param node1_name: a first node name in current tree
:param node2_name: a second node name in current tree
:return: a length of specified by a pair of vertices edge / path
:rtype: `Number`
:raises: ValueError, if requested a length of an edge, that is not present in current tree
"""
return self.__root.get_distance(target=node1_name, target2=node2_name) | [
"def",
"get_distance",
"(",
"self",
",",
"node1_name",
",",
"node2_name",
")",
":",
"return",
"self",
".",
"__root",
".",
"get_distance",
"(",
"target",
"=",
"node1_name",
",",
"target2",
"=",
"node2_name",
")"
] | Returns a length of an edge / path, if exists, from the current tree
:param node1_name: a first node name in current tree
:param node2_name: a second node name in current tree
:return: a length of specified by a pair of vertices edge / path
:rtype: `Number`
:raises: ValueError, if requested a length of an edge, that is not present in current tree | [
"Returns",
"a",
"length",
"of",
"an",
"edge",
"/",
"path",
"if",
"exists",
"from",
"the",
"current",
"tree"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/tree.py#L139-L148 |
aganezov/bg | bg/tree.py | BGTree.__get_v_tree_consistent_leaf_based_hashable_multicolors | def __get_v_tree_consistent_leaf_based_hashable_multicolors(self):
""" Internally used method, that recalculates VTree-consistent sets of leaves in the current tree """
result = []
nodes = deque([self.__root])
while len(nodes) > 0:
current_node = nodes.popleft()
children = current_node.children
nodes.extend(children)
if not current_node.is_leaf():
leaves = filter(lambda node: node.is_leaf(), current_node.get_descendants())
result.append(Multicolor(*[self.__leaf_wrapper(leaf.name) for leaf in leaves]))
else:
result.append(Multicolor(self.__leaf_wrapper(current_node.name)))
result.append(Multicolor())
return result | python | def __get_v_tree_consistent_leaf_based_hashable_multicolors(self):
""" Internally used method, that recalculates VTree-consistent sets of leaves in the current tree """
result = []
nodes = deque([self.__root])
while len(nodes) > 0:
current_node = nodes.popleft()
children = current_node.children
nodes.extend(children)
if not current_node.is_leaf():
leaves = filter(lambda node: node.is_leaf(), current_node.get_descendants())
result.append(Multicolor(*[self.__leaf_wrapper(leaf.name) for leaf in leaves]))
else:
result.append(Multicolor(self.__leaf_wrapper(current_node.name)))
result.append(Multicolor())
return result | [
"def",
"__get_v_tree_consistent_leaf_based_hashable_multicolors",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"nodes",
"=",
"deque",
"(",
"[",
"self",
".",
"__root",
"]",
")",
"while",
"len",
"(",
"nodes",
")",
">",
"0",
":",
"current_node",
"=",
"node... | Internally used method, that recalculates VTree-consistent sets of leaves in the current tree | [
"Internally",
"used",
"method",
"that",
"recalculates",
"VTree",
"-",
"consistent",
"sets",
"of",
"leaves",
"in",
"the",
"current",
"tree"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/tree.py#L157-L171 |
aganezov/bg | bg/tree.py | BGTree.__update_consistent_multicolors | def __update_consistent_multicolors(self):
""" Internally used method, that recalculates T-consistent / VT-consistent multicolors for current tree topology
"""
v_t_consistent_multicolors = self.__get_v_tree_consistent_leaf_based_hashable_multicolors()
hashed_vtree_consistent_leaves_multicolors = {mc.hashable_representation for mc in v_t_consistent_multicolors}
self.vtree_consistent_multicolors_set = hashed_vtree_consistent_leaves_multicolors
self.vtree_consistent_multicolors = [Multicolor(*hashed_multicolor) for hashed_multicolor in
hashed_vtree_consistent_leaves_multicolors]
result = []
# T-consistent multicolors can be viewed as VT-consistent multicolors united with all of their complements
full_multicolor = v_t_consistent_multicolors[0]
for multicolor in v_t_consistent_multicolors:
result.append(multicolor)
result.append(full_multicolor - multicolor)
hashed_tree_consistent_leaves_multicolors = {mc.hashable_representation for mc in result}
self.tree_consistent_multicolors_set = hashed_tree_consistent_leaves_multicolors
self.tree_consistent_multicolors = [Multicolor(*hashed_multicolor) for hashed_multicolor in
hashed_tree_consistent_leaves_multicolors]
self.multicolors_are_up_to_date = True | python | def __update_consistent_multicolors(self):
""" Internally used method, that recalculates T-consistent / VT-consistent multicolors for current tree topology
"""
v_t_consistent_multicolors = self.__get_v_tree_consistent_leaf_based_hashable_multicolors()
hashed_vtree_consistent_leaves_multicolors = {mc.hashable_representation for mc in v_t_consistent_multicolors}
self.vtree_consistent_multicolors_set = hashed_vtree_consistent_leaves_multicolors
self.vtree_consistent_multicolors = [Multicolor(*hashed_multicolor) for hashed_multicolor in
hashed_vtree_consistent_leaves_multicolors]
result = []
# T-consistent multicolors can be viewed as VT-consistent multicolors united with all of their complements
full_multicolor = v_t_consistent_multicolors[0]
for multicolor in v_t_consistent_multicolors:
result.append(multicolor)
result.append(full_multicolor - multicolor)
hashed_tree_consistent_leaves_multicolors = {mc.hashable_representation for mc in result}
self.tree_consistent_multicolors_set = hashed_tree_consistent_leaves_multicolors
self.tree_consistent_multicolors = [Multicolor(*hashed_multicolor) for hashed_multicolor in
hashed_tree_consistent_leaves_multicolors]
self.multicolors_are_up_to_date = True | [
"def",
"__update_consistent_multicolors",
"(",
"self",
")",
":",
"v_t_consistent_multicolors",
"=",
"self",
".",
"__get_v_tree_consistent_leaf_based_hashable_multicolors",
"(",
")",
"hashed_vtree_consistent_leaves_multicolors",
"=",
"{",
"mc",
".",
"hashable_representation",
"f... | Internally used method, that recalculates T-consistent / VT-consistent multicolors for current tree topology | [
"Internally",
"used",
"method",
"that",
"recalculates",
"T",
"-",
"consistent",
"/",
"VT",
"-",
"consistent",
"multicolors",
"for",
"current",
"tree",
"topology"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/tree.py#L181-L201 |
aganezov/bg | bg/tree.py | BGTree.append | def append(self, node_name, tree, copy=False):
""" Append a specified tree (represented by a root TreeNode element) to the node, specified by its name
:param copy: a flag denoting if the appended tree has to be added as is, or is the deepcopy of it has to be used
:type copy: Boolean
:raises: ValueError (if no node with a specified name, to which the specified tree has to be appended, is present in the current tree)
"""
self.multicolors_are_up_to_date = False
tree_to_append = tree.__root if not copy else deepcopy(tree.__root)
self.__get_node_by_name(node_name).add_child(tree_to_append) | python | def append(self, node_name, tree, copy=False):
""" Append a specified tree (represented by a root TreeNode element) to the node, specified by its name
:param copy: a flag denoting if the appended tree has to be added as is, or is the deepcopy of it has to be used
:type copy: Boolean
:raises: ValueError (if no node with a specified name, to which the specified tree has to be appended, is present in the current tree)
"""
self.multicolors_are_up_to_date = False
tree_to_append = tree.__root if not copy else deepcopy(tree.__root)
self.__get_node_by_name(node_name).add_child(tree_to_append) | [
"def",
"append",
"(",
"self",
",",
"node_name",
",",
"tree",
",",
"copy",
"=",
"False",
")",
":",
"self",
".",
"multicolors_are_up_to_date",
"=",
"False",
"tree_to_append",
"=",
"tree",
".",
"__root",
"if",
"not",
"copy",
"else",
"deepcopy",
"(",
"tree",
... | Append a specified tree (represented by a root TreeNode element) to the node, specified by its name
:param copy: a flag denoting if the appended tree has to be added as is, or is the deepcopy of it has to be used
:type copy: Boolean
:raises: ValueError (if no node with a specified name, to which the specified tree has to be appended, is present in the current tree) | [
"Append",
"a",
"specified",
"tree",
"(",
"represented",
"by",
"a",
"root",
"TreeNode",
"element",
")",
"to",
"the",
"node",
"specified",
"by",
"its",
"name"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/tree.py#L278-L287 |
theiviaxx/Frog | frog/models.py | Image.export | def export(self, hashVal=None, hashPath=None, tags=None, galleries=None):
"""
The export function needs to:
- Move source image to asset folder
- Rename to guid.ext
- Save thumbnail, small, and image versions
"""
hashVal = hashVal or self.hash
hashPath = hashPath or self.parent / hashVal + self.ext
source = hashPath.replace('\\', '/').replace(ROOT, '')
galleries = galleries or []
tags = tags or []
imagefile = ROOT / source
if imagefile.ext == '.psd':
psd = psd_tools.PSDImage.load(imagefile)
workImage = psd.as_PIL()
else:
workImage = pilImage.open(imagefile)
self.source = source
if imagefile.ext in ('.tif', '.tiff', '.psd'):
png = imagefile.parent / '{}.png'.format(imagefile.namebase)
workImage.save(png)
workImage = pilImage.open(png)
imagefile.move(imagefile.replace(self.hash, self.title))
self.source = png.replace(ROOT, '')
formats = [
('image', FROG_IMAGE_SIZE_CAP),
('small', FROG_IMAGE_SMALL_SIZE),
]
for i, n in enumerate(formats):
if workImage.size[0] > n[1] or workImage.size[1] > n[1]:
workImage.thumbnail((n[1], n[1]), pilImage.ANTIALIAS)
setattr(self, n[0], self.source.name.replace(hashVal, '_' * i + hashVal))
workImage.save(ROOT + getattr(self, n[0]).name)
else:
setattr(self, n[0], self.source)
self.generateThumbnail()
for gal in galleries:
g = Gallery.objects.get(pk=int(gal))
g.images.add(self)
self.tagArtist()
for tagName in tags:
tag = Tag.objects.get_or_create(name=tagName)[0]
self.tags.add(tag)
if not self.guid:
self.guid = self.getGuid().guid
self.save() | python | def export(self, hashVal=None, hashPath=None, tags=None, galleries=None):
"""
The export function needs to:
- Move source image to asset folder
- Rename to guid.ext
- Save thumbnail, small, and image versions
"""
hashVal = hashVal or self.hash
hashPath = hashPath or self.parent / hashVal + self.ext
source = hashPath.replace('\\', '/').replace(ROOT, '')
galleries = galleries or []
tags = tags or []
imagefile = ROOT / source
if imagefile.ext == '.psd':
psd = psd_tools.PSDImage.load(imagefile)
workImage = psd.as_PIL()
else:
workImage = pilImage.open(imagefile)
self.source = source
if imagefile.ext in ('.tif', '.tiff', '.psd'):
png = imagefile.parent / '{}.png'.format(imagefile.namebase)
workImage.save(png)
workImage = pilImage.open(png)
imagefile.move(imagefile.replace(self.hash, self.title))
self.source = png.replace(ROOT, '')
formats = [
('image', FROG_IMAGE_SIZE_CAP),
('small', FROG_IMAGE_SMALL_SIZE),
]
for i, n in enumerate(formats):
if workImage.size[0] > n[1] or workImage.size[1] > n[1]:
workImage.thumbnail((n[1], n[1]), pilImage.ANTIALIAS)
setattr(self, n[0], self.source.name.replace(hashVal, '_' * i + hashVal))
workImage.save(ROOT + getattr(self, n[0]).name)
else:
setattr(self, n[0], self.source)
self.generateThumbnail()
for gal in galleries:
g = Gallery.objects.get(pk=int(gal))
g.images.add(self)
self.tagArtist()
for tagName in tags:
tag = Tag.objects.get_or_create(name=tagName)[0]
self.tags.add(tag)
if not self.guid:
self.guid = self.getGuid().guid
self.save() | [
"def",
"export",
"(",
"self",
",",
"hashVal",
"=",
"None",
",",
"hashPath",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"galleries",
"=",
"None",
")",
":",
"hashVal",
"=",
"hashVal",
"or",
"self",
".",
"hash",
"hashPath",
"=",
"hashPath",
"or",
"self... | The export function needs to:
- Move source image to asset folder
- Rename to guid.ext
- Save thumbnail, small, and image versions | [
"The",
"export",
"function",
"needs",
"to",
":",
"-",
"Move",
"source",
"image",
"to",
"asset",
"folder",
"-",
"Rename",
"to",
"guid",
".",
"ext",
"-",
"Save",
"thumbnail",
"small",
"and",
"image",
"versions"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/models.py#L292-L348 |
theiviaxx/Frog | frog/models.py | Image.generateThumbnail | def generateThumbnail(self):
"""Generates a square thumbnail"""
image = pilImage.open(ROOT / self.source.name)
box, width, height = cropBox(self.width, self.height)
# Resize
image.thumbnail((width, height), pilImage.ANTIALIAS)
# Crop from center
box = cropBox(*image.size)[0]
image = image.crop(box)
# save
self.thumbnail = self.source.name.replace(self.hash, '__{}'.format(self.hash))
image.save(ROOT / self.thumbnail.name) | python | def generateThumbnail(self):
"""Generates a square thumbnail"""
image = pilImage.open(ROOT / self.source.name)
box, width, height = cropBox(self.width, self.height)
# Resize
image.thumbnail((width, height), pilImage.ANTIALIAS)
# Crop from center
box = cropBox(*image.size)[0]
image = image.crop(box)
# save
self.thumbnail = self.source.name.replace(self.hash, '__{}'.format(self.hash))
image.save(ROOT / self.thumbnail.name) | [
"def",
"generateThumbnail",
"(",
"self",
")",
":",
"image",
"=",
"pilImage",
".",
"open",
"(",
"ROOT",
"/",
"self",
".",
"source",
".",
"name",
")",
"box",
",",
"width",
",",
"height",
"=",
"cropBox",
"(",
"self",
".",
"width",
",",
"self",
".",
"h... | Generates a square thumbnail | [
"Generates",
"a",
"square",
"thumbnail"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/models.py#L358-L370 |
theiviaxx/Frog | frog/models.py | Video.export | def export(self, hashVal, hashPath, tags=None, galleries=None):
"""
The export function needs to:
- Move source image to asset folder
- Rename to guid.ext
- Save thumbnail, video_thumbnail, and MP4 versions. If the source is already h264, then only transcode the thumbnails
"""
self.source = hashPath.replace('\\', '/').replace(ROOT, '')
galleries = galleries or []
tags = tags or []
# -- Get info
videodata = self.info()
self.width = videodata['width']
self.height = videodata['height']
self.framerate = videodata['framerate']
self.duration = videodata['duration']
self.generateThumbnail()
for gal in galleries:
g = Gallery.objects.get(pk=int(gal))
g.videos.add(self)
self.tagArtist()
for tagName in tags:
tag = Tag.objects.get_or_create(name=tagName)[0]
self.tags.add(tag)
if not self.guid:
self.guid = self.getGuid().guid
# -- Set the temp video while processing
queuedvideo = VideoQueue.objects.get_or_create(video=self)[0]
queuedvideo.save()
self.save()
try:
item = VideoQueue()
item.video = self
item.save()
except IntegrityError:
# -- Already queued
pass | python | def export(self, hashVal, hashPath, tags=None, galleries=None):
"""
The export function needs to:
- Move source image to asset folder
- Rename to guid.ext
- Save thumbnail, video_thumbnail, and MP4 versions. If the source is already h264, then only transcode the thumbnails
"""
self.source = hashPath.replace('\\', '/').replace(ROOT, '')
galleries = galleries or []
tags = tags or []
# -- Get info
videodata = self.info()
self.width = videodata['width']
self.height = videodata['height']
self.framerate = videodata['framerate']
self.duration = videodata['duration']
self.generateThumbnail()
for gal in galleries:
g = Gallery.objects.get(pk=int(gal))
g.videos.add(self)
self.tagArtist()
for tagName in tags:
tag = Tag.objects.get_or_create(name=tagName)[0]
self.tags.add(tag)
if not self.guid:
self.guid = self.getGuid().guid
# -- Set the temp video while processing
queuedvideo = VideoQueue.objects.get_or_create(video=self)[0]
queuedvideo.save()
self.save()
try:
item = VideoQueue()
item.video = self
item.save()
except IntegrityError:
# -- Already queued
pass | [
"def",
"export",
"(",
"self",
",",
"hashVal",
",",
"hashPath",
",",
"tags",
"=",
"None",
",",
"galleries",
"=",
"None",
")",
":",
"self",
".",
"source",
"=",
"hashPath",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
".",
"replace",
"(",
"ROOT",
"... | The export function needs to:
- Move source image to asset folder
- Rename to guid.ext
- Save thumbnail, video_thumbnail, and MP4 versions. If the source is already h264, then only transcode the thumbnails | [
"The",
"export",
"function",
"needs",
"to",
":",
"-",
"Move",
"source",
"image",
"to",
"asset",
"folder",
"-",
"Rename",
"to",
"guid",
".",
"ext",
"-",
"Save",
"thumbnail",
"video_thumbnail",
"and",
"MP4",
"versions",
".",
"If",
"the",
"source",
"is",
"a... | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/models.py#L382-L428 |
theiviaxx/Frog | frog/models.py | Video.generateThumbnail | def generateThumbnail(self):
"""Generates a square thumbnail"""
source = ROOT / self.source.name
thumbnail = source.parent / '_{}.jpg'.format(source.namebase)
# -- Save thumbnail and put into queue
poster = source.parent / '__{}.jpg'.format(source.namebase)
cmd = [FROG_FFMPEG, '-i', str(source), '-ss', '1', '-vframes', '1', str(thumbnail), '-y']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
proc.communicate()
image = pilImage.open(thumbnail)
image.save(poster)
self.poster = poster.replace(ROOT, '')
box, width, height = cropBox(self.width, self.height)
# Resize
image.thumbnail((width, height), pilImage.ANTIALIAS)
# Crop from center
box = cropBox(*image.size)[0]
image = image.crop(box)
# save
self.thumbnail = thumbnail.replace(ROOT, '')
image.save(thumbnail) | python | def generateThumbnail(self):
"""Generates a square thumbnail"""
source = ROOT / self.source.name
thumbnail = source.parent / '_{}.jpg'.format(source.namebase)
# -- Save thumbnail and put into queue
poster = source.parent / '__{}.jpg'.format(source.namebase)
cmd = [FROG_FFMPEG, '-i', str(source), '-ss', '1', '-vframes', '1', str(thumbnail), '-y']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
proc.communicate()
image = pilImage.open(thumbnail)
image.save(poster)
self.poster = poster.replace(ROOT, '')
box, width, height = cropBox(self.width, self.height)
# Resize
image.thumbnail((width, height), pilImage.ANTIALIAS)
# Crop from center
box = cropBox(*image.size)[0]
image = image.crop(box)
# save
self.thumbnail = thumbnail.replace(ROOT, '')
image.save(thumbnail) | [
"def",
"generateThumbnail",
"(",
"self",
")",
":",
"source",
"=",
"ROOT",
"/",
"self",
".",
"source",
".",
"name",
"thumbnail",
"=",
"source",
".",
"parent",
"/",
"'_{}.jpg'",
".",
"format",
"(",
"source",
".",
"namebase",
")",
"# -- Save thumbnail and put i... | Generates a square thumbnail | [
"Generates",
"a",
"square",
"thumbnail"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/models.py#L441-L464 |
loomchild/reload | reload.py | reload | def reload(*command, ignore_patterns=[]):
"""Reload given command"""
path = "."
sig = signal.SIGTERM
delay = 0.25
ignorefile = ".reloadignore"
ignore_patterns = ignore_patterns or load_ignore_patterns(ignorefile)
event_handler = ReloadEventHandler(ignore_patterns)
reloader = Reloader(command, signal)
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
reloader.start_command()
try:
while True:
time.sleep(delay)
sys.stdout.write(reloader.read())
sys.stdout.flush()
if event_handler.modified:
reloader.restart_command()
except KeyboardInterrupt:
observer.stop()
observer.join()
reloader.stop_command()
sys.stdout.write(reloader.read())
sys.stdout.flush() | python | def reload(*command, ignore_patterns=[]):
"""Reload given command"""
path = "."
sig = signal.SIGTERM
delay = 0.25
ignorefile = ".reloadignore"
ignore_patterns = ignore_patterns or load_ignore_patterns(ignorefile)
event_handler = ReloadEventHandler(ignore_patterns)
reloader = Reloader(command, signal)
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
reloader.start_command()
try:
while True:
time.sleep(delay)
sys.stdout.write(reloader.read())
sys.stdout.flush()
if event_handler.modified:
reloader.restart_command()
except KeyboardInterrupt:
observer.stop()
observer.join()
reloader.stop_command()
sys.stdout.write(reloader.read())
sys.stdout.flush() | [
"def",
"reload",
"(",
"*",
"command",
",",
"ignore_patterns",
"=",
"[",
"]",
")",
":",
"path",
"=",
"\".\"",
"sig",
"=",
"signal",
".",
"SIGTERM",
"delay",
"=",
"0.25",
"ignorefile",
"=",
"\".reloadignore\"",
"ignore_patterns",
"=",
"ignore_patterns",
"or",
... | Reload given command | [
"Reload",
"given",
"command"
] | train | https://github.com/loomchild/reload/blob/7900d831e76d6450cfd342ef414fbdc59d8ee5f7/reload.py#L92-L123 |
loomchild/reload | reload.py | reload_me | def reload_me(*args, ignore_patterns=[]):
"""Reload currently running command with given args"""
command = [sys.executable, sys.argv[0]]
command.extend(args)
reload(*command, ignore_patterns=ignore_patterns) | python | def reload_me(*args, ignore_patterns=[]):
"""Reload currently running command with given args"""
command = [sys.executable, sys.argv[0]]
command.extend(args)
reload(*command, ignore_patterns=ignore_patterns) | [
"def",
"reload_me",
"(",
"*",
"args",
",",
"ignore_patterns",
"=",
"[",
"]",
")",
":",
"command",
"=",
"[",
"sys",
".",
"executable",
",",
"sys",
".",
"argv",
"[",
"0",
"]",
"]",
"command",
".",
"extend",
"(",
"args",
")",
"reload",
"(",
"*",
"co... | Reload currently running command with given args | [
"Reload",
"currently",
"running",
"command",
"with",
"given",
"args"
] | train | https://github.com/loomchild/reload/blob/7900d831e76d6450cfd342ef414fbdc59d8ee5f7/reload.py#L126-L132 |
aganezov/bg | bg/grimm.py | GRIMMReader.parse_data_string | def parse_data_string(data_string):
""" Parses a string assumed to contain gene order data, retrieving information about fragment type, gene order, blocks names and their orientation
First checks if gene order termination signs are present.
Selects the earliest one.
Checks that information preceding is not empty and contains gene order.
Generates results structure by retrieving information about fragment type, blocks names and orientations.
**NOTE:** comment signs do not work in data strings. Rather use the fact that after first gene order termination sign everything is ignored for processing
:param data_string: a string to retrieve gene order information from
:type data_string: ``str``
:return: (``$`` | ``@``, [(``+`` | ``-``, block_name),...]) formatted structure corresponding to gene order in supplied data string and containing fragments type
:rtype: ``tuple(str, list((str, str), ...))``
"""
data_string = data_string.strip()
linear_terminator_index = data_string.index("$") if "$" in data_string else -1
circular_terminator_index = data_string.index("@") if "@" in data_string else -1
if linear_terminator_index < 0 and circular_terminator_index < 0:
raise ValueError("Invalid data string. No chromosome termination sign ($|@) found.")
if linear_terminator_index == 0 or circular_terminator_index == 0:
raise ValueError("Invalid data string. No data found before chromosome was terminated.")
if linear_terminator_index < 0 or 0 < circular_terminator_index < linear_terminator_index:
###############################################################################################
#
# we either encountered only a circular chromosome termination sign
# or we have encountered it before we've encountered the circular chromosome termination sign first
#
###############################################################################################
chr_type = "@"
terminator_index = circular_terminator_index
else:
chr_type = "$"
terminator_index = linear_terminator_index
###############################################################################################
#
# everything after first fragment termination sign is omitted
#
###############################################################################################
data = data_string[:terminator_index].strip()
###############################################################################################
#
# genomic blocks are separated between each other by the space character
#
###############################################################################################
split_data = data.split()
blocks = []
for block in split_data:
###############################################################################################
#
# since positively oriented blocks can be denoted both as "+block" as well as "block"
# we need to figure out where "block" name starts
#
###############################################################################################
cut_index = 1 if block.startswith("-") or block.startswith("+") else 0
if cut_index == 1 and len(block) == 1:
###############################################################################################
#
# block can not be empty
# from this one can derive the fact, that names "+" and "-" for blocks are forbidden
#
###############################################################################################
raise ValueError("Empty block name definition")
blocks.append(("-" if block.startswith("-") else "+", block[cut_index:]))
return chr_type, blocks | python | def parse_data_string(data_string):
""" Parses a string assumed to contain gene order data, retrieving information about fragment type, gene order, blocks names and their orientation
First checks if gene order termination signs are present.
Selects the earliest one.
Checks that information preceding is not empty and contains gene order.
Generates results structure by retrieving information about fragment type, blocks names and orientations.
**NOTE:** comment signs do not work in data strings. Rather use the fact that after first gene order termination sign everything is ignored for processing
:param data_string: a string to retrieve gene order information from
:type data_string: ``str``
:return: (``$`` | ``@``, [(``+`` | ``-``, block_name),...]) formatted structure corresponding to gene order in supplied data string and containing fragments type
:rtype: ``tuple(str, list((str, str), ...))``
"""
data_string = data_string.strip()
linear_terminator_index = data_string.index("$") if "$" in data_string else -1
circular_terminator_index = data_string.index("@") if "@" in data_string else -1
if linear_terminator_index < 0 and circular_terminator_index < 0:
raise ValueError("Invalid data string. No chromosome termination sign ($|@) found.")
if linear_terminator_index == 0 or circular_terminator_index == 0:
raise ValueError("Invalid data string. No data found before chromosome was terminated.")
if linear_terminator_index < 0 or 0 < circular_terminator_index < linear_terminator_index:
###############################################################################################
#
# we either encountered only a circular chromosome termination sign
# or we have encountered it before we've encountered the circular chromosome termination sign first
#
###############################################################################################
chr_type = "@"
terminator_index = circular_terminator_index
else:
chr_type = "$"
terminator_index = linear_terminator_index
###############################################################################################
#
# everything after first fragment termination sign is omitted
#
###############################################################################################
data = data_string[:terminator_index].strip()
###############################################################################################
#
# genomic blocks are separated between each other by the space character
#
###############################################################################################
split_data = data.split()
blocks = []
for block in split_data:
###############################################################################################
#
# since positively oriented blocks can be denoted both as "+block" as well as "block"
# we need to figure out where "block" name starts
#
###############################################################################################
cut_index = 1 if block.startswith("-") or block.startswith("+") else 0
if cut_index == 1 and len(block) == 1:
###############################################################################################
#
# block can not be empty
# from this one can derive the fact, that names "+" and "-" for blocks are forbidden
#
###############################################################################################
raise ValueError("Empty block name definition")
blocks.append(("-" if block.startswith("-") else "+", block[cut_index:]))
return chr_type, blocks | [
"def",
"parse_data_string",
"(",
"data_string",
")",
":",
"data_string",
"=",
"data_string",
".",
"strip",
"(",
")",
"linear_terminator_index",
"=",
"data_string",
".",
"index",
"(",
"\"$\"",
")",
"if",
"\"$\"",
"in",
"data_string",
"else",
"-",
"1",
"circular... | Parses a string assumed to contain gene order data, retrieving information about fragment type, gene order, blocks names and their orientation
First checks if gene order termination signs are present.
Selects the earliest one.
Checks that information preceding is not empty and contains gene order.
Generates results structure by retrieving information about fragment type, blocks names and orientations.
**NOTE:** comment signs do not work in data strings. Rather use the fact that after first gene order termination sign everything is ignored for processing
:param data_string: a string to retrieve gene order information from
:type data_string: ``str``
:return: (``$`` | ``@``, [(``+`` | ``-``, block_name),...]) formatted structure corresponding to gene order in supplied data string and containing fragments type
:rtype: ``tuple(str, list((str, str), ...))`` | [
"Parses",
"a",
"string",
"assumed",
"to",
"contain",
"gene",
"order",
"data",
"retrieving",
"information",
"about",
"fragment",
"type",
"gene",
"order",
"blocks",
"names",
"and",
"their",
"orientation"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/grimm.py#L95-L159 |
aganezov/bg | bg/grimm.py | GRIMMReader.__assign_vertex_pair | def __assign_vertex_pair(block):
""" Assigns usual BreakpointGraph type vertices to supplied block.
Vertices are labeled as "block_name" + "h" and "block_name" + "t" according to blocks orientation.
:param block: information about a genomic block to create a pair of vertices for in a format of ( ``+`` | ``-``, block_name)
:type block: ``(str, str)``
:return: a pair of vertices labeled according to supplied blocks name (respecting blocks orientation)
:rtype: ``(str, str)``
"""
sign, name = block
data = name.split(BlockVertex.NAME_SEPARATOR)
root_name, data = data[0], data[1:]
tags = [entry.split(TaggedVertex.TAG_SEPARATOR) for entry in data]
for tag_entry in tags:
if len(tag_entry) == 1:
tag_entry.append(None)
elif len(tag_entry) > 2:
tag_entry[1:] = [TaggedVertex.TAG_SEPARATOR.join(tag_entry[1:])]
tail, head = root_name + "t", root_name + "h"
tail, head = TaggedBlockVertex(tail), TaggedBlockVertex(head)
tail.mate_vertex = head
head.mate_vertex = tail
for tag, value in tags:
head.add_tag(tag, value)
tail.add_tag(tag, value)
return (tail, head) if sign == "+" else (head, tail) | python | def __assign_vertex_pair(block):
""" Assigns usual BreakpointGraph type vertices to supplied block.
Vertices are labeled as "block_name" + "h" and "block_name" + "t" according to blocks orientation.
:param block: information about a genomic block to create a pair of vertices for in a format of ( ``+`` | ``-``, block_name)
:type block: ``(str, str)``
:return: a pair of vertices labeled according to supplied blocks name (respecting blocks orientation)
:rtype: ``(str, str)``
"""
sign, name = block
data = name.split(BlockVertex.NAME_SEPARATOR)
root_name, data = data[0], data[1:]
tags = [entry.split(TaggedVertex.TAG_SEPARATOR) for entry in data]
for tag_entry in tags:
if len(tag_entry) == 1:
tag_entry.append(None)
elif len(tag_entry) > 2:
tag_entry[1:] = [TaggedVertex.TAG_SEPARATOR.join(tag_entry[1:])]
tail, head = root_name + "t", root_name + "h"
tail, head = TaggedBlockVertex(tail), TaggedBlockVertex(head)
tail.mate_vertex = head
head.mate_vertex = tail
for tag, value in tags:
head.add_tag(tag, value)
tail.add_tag(tag, value)
return (tail, head) if sign == "+" else (head, tail) | [
"def",
"__assign_vertex_pair",
"(",
"block",
")",
":",
"sign",
",",
"name",
"=",
"block",
"data",
"=",
"name",
".",
"split",
"(",
"BlockVertex",
".",
"NAME_SEPARATOR",
")",
"root_name",
",",
"data",
"=",
"data",
"[",
"0",
"]",
",",
"data",
"[",
"1",
... | Assigns usual BreakpointGraph type vertices to supplied block.
Vertices are labeled as "block_name" + "h" and "block_name" + "t" according to blocks orientation.
:param block: information about a genomic block to create a pair of vertices for in a format of ( ``+`` | ``-``, block_name)
:type block: ``(str, str)``
:return: a pair of vertices labeled according to supplied blocks name (respecting blocks orientation)
:rtype: ``(str, str)`` | [
"Assigns",
"usual",
"BreakpointGraph",
"type",
"vertices",
"to",
"supplied",
"block",
"."
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/grimm.py#L162-L188 |
aganezov/bg | bg/grimm.py | GRIMMReader.get_edges_from_parsed_data | def get_edges_from_parsed_data(parsed_data):
""" Taking into account fragment type (circular|linear) and retrieved gene order information translates adjacencies between blocks into edges for addition to the :class:`bg.breakpoint_graph.BreakpointGraph`
In case supplied fragment is linear (``$``) special artificial vertices (with ``__infinity`` suffix) are introduced to denote fragment extremities
:param parsed_data: (``$`` | ``@``, [(``+`` | ``-``, block_name),...]) formatted data about fragment type and ordered list of oriented blocks
:type parsed_data: ``tuple(str, list((str, str), ...))``
:return: a list of vertices pairs that would correspond to edges in :class:`bg.breakpoint_graph.BreakpointGraph`
:rtype: ``list((str, str), ...)``
"""
chr_type, blocks = parsed_data
vertices = []
for block in blocks:
###############################################################################################
#
# each block is represented as a pair of vertices (that correspond to block extremities)
#
###############################################################################################
v1, v2 = GRIMMReader.__assign_vertex_pair(block)
vertices.append(v1)
vertices.append(v2)
if chr_type == "@":
###############################################################################################
#
# if we parse a circular genomic fragment we must introduce an additional pair of vertices (edge)
# that would connect two outer most vertices in the vertex list, thus connecting fragment extremities
#
###############################################################################################
vertex = vertices.pop()
vertices.insert(0, vertex)
elif chr_type == "$":
###############################################################################################
#
# if we parse linear genomic fragment, we introduce two artificial (infinity) vertices
# that correspond to fragments ends, and introduce edges between them and respective outermost block vertices
#
# if outermost vertices at this moment are repeat vertices, the outermost pair shall be discarded and the innermost
# vertex info shall be utilized in the infinity vertex, that is introduced for the fragment extremity
#
###############################################################################################
if vertices[0].is_repeat_vertex:
left_iv_tags = sorted([(tag, value) if tag != "repeat" else (tag, BGVertex.get_vertex_name_root(vertices[1].name))
for tag, value in vertices[1].tags])
left_iv_root_name = BGVertex.get_vertex_name_root(vertices[2].name)
vertices = vertices[2:]
else:
left_iv_tags = []
left_iv_root_name = vertices[0].name
if vertices[-1].is_repeat_vertex:
right_iv_tags = sorted(
[(tag, value) if tag != "repeat" else (tag, BGVertex.get_vertex_name_root(vertices[-2].name))
for tag, value in vertices[-2].tags])
right_iv_root_name = BGVertex.get_vertex_name_root(vertices[-3].name)
vertices = vertices[:-2]
else:
right_iv_tags = []
right_iv_root_name = BGVertex.get_vertex_name_root(vertices[-1].name)
left_iv, right_iv = TaggedInfinityVertex(left_iv_root_name), TaggedInfinityVertex(right_iv_root_name)
left_iv.tags = left_iv_tags
right_iv.tags = right_iv_tags
vertices.insert(0, left_iv)
vertices.append(right_iv)
return [(v1, v2) for v1, v2 in zip(vertices[::2], vertices[1::2])] | python | def get_edges_from_parsed_data(parsed_data):
""" Taking into account fragment type (circular|linear) and retrieved gene order information translates adjacencies between blocks into edges for addition to the :class:`bg.breakpoint_graph.BreakpointGraph`
In case supplied fragment is linear (``$``) special artificial vertices (with ``__infinity`` suffix) are introduced to denote fragment extremities
:param parsed_data: (``$`` | ``@``, [(``+`` | ``-``, block_name),...]) formatted data about fragment type and ordered list of oriented blocks
:type parsed_data: ``tuple(str, list((str, str), ...))``
:return: a list of vertices pairs that would correspond to edges in :class:`bg.breakpoint_graph.BreakpointGraph`
:rtype: ``list((str, str), ...)``
"""
chr_type, blocks = parsed_data
vertices = []
for block in blocks:
###############################################################################################
#
# each block is represented as a pair of vertices (that correspond to block extremities)
#
###############################################################################################
v1, v2 = GRIMMReader.__assign_vertex_pair(block)
vertices.append(v1)
vertices.append(v2)
if chr_type == "@":
###############################################################################################
#
# if we parse a circular genomic fragment we must introduce an additional pair of vertices (edge)
# that would connect two outer most vertices in the vertex list, thus connecting fragment extremities
#
###############################################################################################
vertex = vertices.pop()
vertices.insert(0, vertex)
elif chr_type == "$":
###############################################################################################
#
# if we parse linear genomic fragment, we introduce two artificial (infinity) vertices
# that correspond to fragments ends, and introduce edges between them and respective outermost block vertices
#
# if outermost vertices at this moment are repeat vertices, the outermost pair shall be discarded and the innermost
# vertex info shall be utilized in the infinity vertex, that is introduced for the fragment extremity
#
###############################################################################################
if vertices[0].is_repeat_vertex:
left_iv_tags = sorted([(tag, value) if tag != "repeat" else (tag, BGVertex.get_vertex_name_root(vertices[1].name))
for tag, value in vertices[1].tags])
left_iv_root_name = BGVertex.get_vertex_name_root(vertices[2].name)
vertices = vertices[2:]
else:
left_iv_tags = []
left_iv_root_name = vertices[0].name
if vertices[-1].is_repeat_vertex:
right_iv_tags = sorted(
[(tag, value) if tag != "repeat" else (tag, BGVertex.get_vertex_name_root(vertices[-2].name))
for tag, value in vertices[-2].tags])
right_iv_root_name = BGVertex.get_vertex_name_root(vertices[-3].name)
vertices = vertices[:-2]
else:
right_iv_tags = []
right_iv_root_name = BGVertex.get_vertex_name_root(vertices[-1].name)
left_iv, right_iv = TaggedInfinityVertex(left_iv_root_name), TaggedInfinityVertex(right_iv_root_name)
left_iv.tags = left_iv_tags
right_iv.tags = right_iv_tags
vertices.insert(0, left_iv)
vertices.append(right_iv)
return [(v1, v2) for v1, v2 in zip(vertices[::2], vertices[1::2])] | [
"def",
"get_edges_from_parsed_data",
"(",
"parsed_data",
")",
":",
"chr_type",
",",
"blocks",
"=",
"parsed_data",
"vertices",
"=",
"[",
"]",
"for",
"block",
"in",
"blocks",
":",
"###############################################################################################",... | Taking into account fragment type (circular|linear) and retrieved gene order information translates adjacencies between blocks into edges for addition to the :class:`bg.breakpoint_graph.BreakpointGraph`
In case supplied fragment is linear (``$``) special artificial vertices (with ``__infinity`` suffix) are introduced to denote fragment extremities
:param parsed_data: (``$`` | ``@``, [(``+`` | ``-``, block_name),...]) formatted data about fragment type and ordered list of oriented blocks
:type parsed_data: ``tuple(str, list((str, str), ...))``
:return: a list of vertices pairs that would correspond to edges in :class:`bg.breakpoint_graph.BreakpointGraph`
:rtype: ``list((str, str), ...)`` | [
"Taking",
"into",
"account",
"fragment",
"type",
"(",
"circular|linear",
")",
"and",
"retrieved",
"gene",
"order",
"information",
"translates",
"adjacencies",
"between",
"blocks",
"into",
"edges",
"for",
"addition",
"to",
"the",
":",
"class",
":",
"bg",
".",
"... | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/grimm.py#L191-L253 |
aganezov/bg | bg/grimm.py | GRIMMReader.get_breakpoint_graph | def get_breakpoint_graph(stream, merge_edges=True):
""" Taking a file-like object transforms supplied gene order data into the language of
:param merge_edges: a flag that indicates if parallel edges in produced breakpoint graph shall be merged or not
:type merge_edges: ``bool``
:param stream: any iterable object where each iteration produces a ``str`` object
:type stream: ``iterable`` ver ``str``
:return: an instance of a BreakpointGraph that contains information about adjacencies in genome specified in GRIMM formatted input
:rtype: :class:`bg.breakpoint_graph.BreakpointGraph`
"""
result = BreakpointGraph()
current_genome = None
fragment_data = {}
for line in stream:
line = line.strip()
if len(line) == 0:
###############################################################################################
#
# empty lines are omitted
#
###############################################################################################
continue
if GRIMMReader.is_genome_declaration_string(data_string=line):
###############################################################################################
#
# is we have a genome declaration, we must update current genome
# all following gene order data (before EOF or next genome declaration) will be attributed to current genome
#
###############################################################################################
current_genome = GRIMMReader.parse_genome_declaration_string(data_string=line)
fragment_data = {}
elif GRIMMReader.is_comment_string(data_string=line):
if GRIMMReader.is_comment_data_string(string=line):
path, (key, value) = GRIMMReader.parse_comment_data_string(comment_data_string=line)
if len(path) > 0 and path[0] == "fragment":
add_to_dict_with_path(destination_dict=fragment_data, key=key, value=value, path=path)
else:
continue
elif current_genome is not None:
###############################################################################################
#
# gene order information that is specified before the first genome is specified can not be attributed to anything
# and thus omitted
#
###############################################################################################
parsed_data = GRIMMReader.parse_data_string(data_string=line)
edges = GRIMMReader.get_edges_from_parsed_data(parsed_data=parsed_data)
for v1, v2 in edges:
edge_specific_data = {
"fragment": {
"forward_orientation": (v1, v2)
}
}
edge = BGEdge(vertex1=v1, vertex2=v2, multicolor=Multicolor(current_genome), data=deepcopy(fragment_data))
edge.update_data(source=edge_specific_data)
result.add_bgedge(bgedge=edge,
merge=merge_edges)
return result | python | def get_breakpoint_graph(stream, merge_edges=True):
""" Taking a file-like object transforms supplied gene order data into the language of
:param merge_edges: a flag that indicates if parallel edges in produced breakpoint graph shall be merged or not
:type merge_edges: ``bool``
:param stream: any iterable object where each iteration produces a ``str`` object
:type stream: ``iterable`` ver ``str``
:return: an instance of a BreakpointGraph that contains information about adjacencies in genome specified in GRIMM formatted input
:rtype: :class:`bg.breakpoint_graph.BreakpointGraph`
"""
result = BreakpointGraph()
current_genome = None
fragment_data = {}
for line in stream:
line = line.strip()
if len(line) == 0:
###############################################################################################
#
# empty lines are omitted
#
###############################################################################################
continue
if GRIMMReader.is_genome_declaration_string(data_string=line):
###############################################################################################
#
# is we have a genome declaration, we must update current genome
# all following gene order data (before EOF or next genome declaration) will be attributed to current genome
#
###############################################################################################
current_genome = GRIMMReader.parse_genome_declaration_string(data_string=line)
fragment_data = {}
elif GRIMMReader.is_comment_string(data_string=line):
if GRIMMReader.is_comment_data_string(string=line):
path, (key, value) = GRIMMReader.parse_comment_data_string(comment_data_string=line)
if len(path) > 0 and path[0] == "fragment":
add_to_dict_with_path(destination_dict=fragment_data, key=key, value=value, path=path)
else:
continue
elif current_genome is not None:
###############################################################################################
#
# gene order information that is specified before the first genome is specified can not be attributed to anything
# and thus omitted
#
###############################################################################################
parsed_data = GRIMMReader.parse_data_string(data_string=line)
edges = GRIMMReader.get_edges_from_parsed_data(parsed_data=parsed_data)
for v1, v2 in edges:
edge_specific_data = {
"fragment": {
"forward_orientation": (v1, v2)
}
}
edge = BGEdge(vertex1=v1, vertex2=v2, multicolor=Multicolor(current_genome), data=deepcopy(fragment_data))
edge.update_data(source=edge_specific_data)
result.add_bgedge(bgedge=edge,
merge=merge_edges)
return result | [
"def",
"get_breakpoint_graph",
"(",
"stream",
",",
"merge_edges",
"=",
"True",
")",
":",
"result",
"=",
"BreakpointGraph",
"(",
")",
"current_genome",
"=",
"None",
"fragment_data",
"=",
"{",
"}",
"for",
"line",
"in",
"stream",
":",
"line",
"=",
"line",
"."... | Taking a file-like object transforms supplied gene order data into the language of
:param merge_edges: a flag that indicates if parallel edges in produced breakpoint graph shall be merged or not
:type merge_edges: ``bool``
:param stream: any iterable object where each iteration produces a ``str`` object
:type stream: ``iterable`` ver ``str``
:return: an instance of a BreakpointGraph that contains information about adjacencies in genome specified in GRIMM formatted input
:rtype: :class:`bg.breakpoint_graph.BreakpointGraph` | [
"Taking",
"a",
"file",
"-",
"like",
"object",
"transforms",
"supplied",
"gene",
"order",
"data",
"into",
"the",
"language",
"of"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/grimm.py#L256-L313 |
aganezov/bg | bg/grimm.py | GRIMMWriter.get_blocks_in_grimm_from_breakpoint_graph | def get_blocks_in_grimm_from_breakpoint_graph(bg):
"""
:param bg: a breakpoint graph, that contians all the information
:type bg: ``bg.breakpoint_graph.BreakpointGraph``
:return: list of strings, which represent genomes present in breakpoint graph as orders of blocks and is compatible with GRIMM format
"""
result = []
genomes = bg.get_overall_set_of_colors()
for genome in genomes:
genome_graph = bg.get_genome_graph(color=genome)
genome_blocks_orders = genome_graph.get_blocks_order()
blocks_orders = genome_blocks_orders[genome]
if len(blocks_orders) > 0:
result.append(">{genome_name}".format(genome_name=genome.name))
for chr_type, blocks_order in blocks_orders:
string = " ".join(value if sign == "+" else sign + value for sign, value in blocks_order)
string += " {chr_type}".format(chr_type=chr_type)
result.append(string)
return result | python | def get_blocks_in_grimm_from_breakpoint_graph(bg):
"""
:param bg: a breakpoint graph, that contians all the information
:type bg: ``bg.breakpoint_graph.BreakpointGraph``
:return: list of strings, which represent genomes present in breakpoint graph as orders of blocks and is compatible with GRIMM format
"""
result = []
genomes = bg.get_overall_set_of_colors()
for genome in genomes:
genome_graph = bg.get_genome_graph(color=genome)
genome_blocks_orders = genome_graph.get_blocks_order()
blocks_orders = genome_blocks_orders[genome]
if len(blocks_orders) > 0:
result.append(">{genome_name}".format(genome_name=genome.name))
for chr_type, blocks_order in blocks_orders:
string = " ".join(value if sign == "+" else sign + value for sign, value in blocks_order)
string += " {chr_type}".format(chr_type=chr_type)
result.append(string)
return result | [
"def",
"get_blocks_in_grimm_from_breakpoint_graph",
"(",
"bg",
")",
":",
"result",
"=",
"[",
"]",
"genomes",
"=",
"bg",
".",
"get_overall_set_of_colors",
"(",
")",
"for",
"genome",
"in",
"genomes",
":",
"genome_graph",
"=",
"bg",
".",
"get_genome_graph",
"(",
... | :param bg: a breakpoint graph, that contians all the information
:type bg: ``bg.breakpoint_graph.BreakpointGraph``
:return: list of strings, which represent genomes present in breakpoint graph as orders of blocks and is compatible with GRIMM format | [
":",
"param",
"bg",
":",
"a",
"breakpoint",
"graph",
"that",
"contians",
"all",
"the",
"information",
":",
"type",
"bg",
":",
"bg",
".",
"breakpoint_graph",
".",
"BreakpointGraph",
":",
"return",
":",
"list",
"of",
"strings",
"which",
"represent",
"genomes",... | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/grimm.py#L342-L360 |
aganezov/bg | bg/genome.py | BGGenome.from_json | def from_json(cls, data, json_schema_class=None):
""" JSON deserialization method that retrieves a genome instance from its json representation
If specific json schema is provided, it is utilized, and if not, a class specific is used
"""
schema = cls.json_schema if json_schema_class is None else json_schema_class()
return schema.load(data) | python | def from_json(cls, data, json_schema_class=None):
""" JSON deserialization method that retrieves a genome instance from its json representation
If specific json schema is provided, it is utilized, and if not, a class specific is used
"""
schema = cls.json_schema if json_schema_class is None else json_schema_class()
return schema.load(data) | [
"def",
"from_json",
"(",
"cls",
",",
"data",
",",
"json_schema_class",
"=",
"None",
")",
":",
"schema",
"=",
"cls",
".",
"json_schema",
"if",
"json_schema_class",
"is",
"None",
"else",
"json_schema_class",
"(",
")",
"return",
"schema",
".",
"load",
"(",
"d... | JSON deserialization method that retrieves a genome instance from its json representation
If specific json schema is provided, it is utilized, and if not, a class specific is used | [
"JSON",
"deserialization",
"method",
"that",
"retrieves",
"a",
"genome",
"instance",
"from",
"its",
"json",
"representation"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/genome.py#L73-L79 |
theiviaxx/Frog | frog/send_file.py | send_file | def send_file(request, filename, content_type='image/jpeg'):
"""
Send a file through Django without loading the whole file into
memory at once. The FileWrapper will turn the file object into an
iterator for chunks of 8KB.
"""
wrapper = FixedFileWrapper(file(filename, 'rb'))
response = HttpResponse(wrapper, content_type=content_type)
response['Content-Length'] = os.path.getsize(filename)
return response | python | def send_file(request, filename, content_type='image/jpeg'):
"""
Send a file through Django without loading the whole file into
memory at once. The FileWrapper will turn the file object into an
iterator for chunks of 8KB.
"""
wrapper = FixedFileWrapper(file(filename, 'rb'))
response = HttpResponse(wrapper, content_type=content_type)
response['Content-Length'] = os.path.getsize(filename)
return response | [
"def",
"send_file",
"(",
"request",
",",
"filename",
",",
"content_type",
"=",
"'image/jpeg'",
")",
":",
"wrapper",
"=",
"FixedFileWrapper",
"(",
"file",
"(",
"filename",
",",
"'rb'",
")",
")",
"response",
"=",
"HttpResponse",
"(",
"wrapper",
",",
"content_t... | Send a file through Django without loading the whole file into
memory at once. The FileWrapper will turn the file object into an
iterator for chunks of 8KB. | [
"Send",
"a",
"file",
"through",
"Django",
"without",
"loading",
"the",
"whole",
"file",
"into",
"memory",
"at",
"once",
".",
"The",
"FileWrapper",
"will",
"turn",
"the",
"file",
"object",
"into",
"an",
"iterator",
"for",
"chunks",
"of",
"8KB",
"."
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/send_file.py#L34-L43 |
theiviaxx/Frog | frog/send_file.py | send_zipfile | def send_zipfile(request, fileList):
"""
Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory. A similar approach can
be used for large dynamic PDF files.
"""
temp = tempfile.TemporaryFile()
archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
for artist,files in fileList.iteritems():
for f in files:
archive.write(f[0], '%s/%s' % (artist, f[1]))
archive.close()
wrapper = FixedFileWrapper(temp)
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=FrogSources.zip'
response['Content-Length'] = temp.tell()
temp.seek(0)
return response | python | def send_zipfile(request, fileList):
"""
Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory. A similar approach can
be used for large dynamic PDF files.
"""
temp = tempfile.TemporaryFile()
archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
for artist,files in fileList.iteritems():
for f in files:
archive.write(f[0], '%s/%s' % (artist, f[1]))
archive.close()
wrapper = FixedFileWrapper(temp)
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=FrogSources.zip'
response['Content-Length'] = temp.tell()
temp.seek(0)
return response | [
"def",
"send_zipfile",
"(",
"request",
",",
"fileList",
")",
":",
"temp",
"=",
"tempfile",
".",
"TemporaryFile",
"(",
")",
"archive",
"=",
"zipfile",
".",
"ZipFile",
"(",
"temp",
",",
"'w'",
",",
"zipfile",
".",
"ZIP_DEFLATED",
")",
"for",
"artist",
",",... | Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory. A similar approach can
be used for large dynamic PDF files. | [
"Create",
"a",
"ZIP",
"file",
"on",
"disk",
"and",
"transmit",
"it",
"in",
"chunks",
"of",
"8KB",
"without",
"loading",
"the",
"whole",
"file",
"into",
"memory",
".",
"A",
"similar",
"approach",
"can",
"be",
"used",
"for",
"large",
"dynamic",
"PDF",
"fil... | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/send_file.py#L46-L63 |
lobocv/pyperform | pyperform/__init__.py | enable | def enable():
"""
Enable all benchmarking.
"""
Benchmark.enable = True
ComparisonBenchmark.enable = True
BenchmarkedFunction.enable = True
BenchmarkedClass.enable = True | python | def enable():
"""
Enable all benchmarking.
"""
Benchmark.enable = True
ComparisonBenchmark.enable = True
BenchmarkedFunction.enable = True
BenchmarkedClass.enable = True | [
"def",
"enable",
"(",
")",
":",
"Benchmark",
".",
"enable",
"=",
"True",
"ComparisonBenchmark",
".",
"enable",
"=",
"True",
"BenchmarkedFunction",
".",
"enable",
"=",
"True",
"BenchmarkedClass",
".",
"enable",
"=",
"True"
] | Enable all benchmarking. | [
"Enable",
"all",
"benchmarking",
"."
] | train | https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/__init__.py#L23-L30 |
lobocv/pyperform | pyperform/__init__.py | disable | def disable():
"""
Disable all benchmarking.
"""
Benchmark.enable = False
ComparisonBenchmark.enable = False
BenchmarkedFunction.enable = False
BenchmarkedClass.enable = False | python | def disable():
"""
Disable all benchmarking.
"""
Benchmark.enable = False
ComparisonBenchmark.enable = False
BenchmarkedFunction.enable = False
BenchmarkedClass.enable = False | [
"def",
"disable",
"(",
")",
":",
"Benchmark",
".",
"enable",
"=",
"False",
"ComparisonBenchmark",
".",
"enable",
"=",
"False",
"BenchmarkedFunction",
".",
"enable",
"=",
"False",
"BenchmarkedClass",
".",
"enable",
"=",
"False"
] | Disable all benchmarking. | [
"Disable",
"all",
"benchmarking",
"."
] | train | https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/__init__.py#L33-L40 |
aganezov/bg | bg/vertices.py | BlockVertex.from_json | def from_json(cls, data, json_schema_class=None):
""" This class overwrites the from_json method thus, making sure, that if `from_json` is called from this class instance, it will provide its JSON schema as a default one """
json_schema = cls.json_schema if json_schema_class is None else json_schema_class()
return super(BlockVertex, cls).from_json(data=data, json_schema_class=json_schema.__class__) | python | def from_json(cls, data, json_schema_class=None):
""" This class overwrites the from_json method thus, making sure, that if `from_json` is called from this class instance, it will provide its JSON schema as a default one """
json_schema = cls.json_schema if json_schema_class is None else json_schema_class()
return super(BlockVertex, cls).from_json(data=data, json_schema_class=json_schema.__class__) | [
"def",
"from_json",
"(",
"cls",
",",
"data",
",",
"json_schema_class",
"=",
"None",
")",
":",
"json_schema",
"=",
"cls",
".",
"json_schema",
"if",
"json_schema_class",
"is",
"None",
"else",
"json_schema_class",
"(",
")",
"return",
"super",
"(",
"BlockVertex",
... | This class overwrites the from_json method thus, making sure, that if `from_json` is called from this class instance, it will provide its JSON schema as a default one | [
"This",
"class",
"overwrites",
"the",
"from_json",
"method",
"thus",
"making",
"sure",
"that",
"if",
"from_json",
"is",
"called",
"from",
"this",
"class",
"instance",
"it",
"will",
"provide",
"its",
"JSON",
"schema",
"as",
"a",
"default",
"one"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/vertices.py#L173-L176 |
aganezov/bg | bg/vertices.py | InfinityVertex.name | def name(self):
""" access to classic name attribute is hidden by this property """
return self.NAME_SEPARATOR.join([super(InfinityVertex, self).name, self.NAME_SUFFIX]) | python | def name(self):
""" access to classic name attribute is hidden by this property """
return self.NAME_SEPARATOR.join([super(InfinityVertex, self).name, self.NAME_SUFFIX]) | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"NAME_SEPARATOR",
".",
"join",
"(",
"[",
"super",
"(",
"InfinityVertex",
",",
"self",
")",
".",
"name",
",",
"self",
".",
"NAME_SUFFIX",
"]",
")"
] | access to classic name attribute is hidden by this property | [
"access",
"to",
"classic",
"name",
"attribute",
"is",
"hidden",
"by",
"this",
"property"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/vertices.py#L206-L208 |
aganezov/bg | bg/vertices.py | InfinityVertex.from_json | def from_json(cls, data, json_schema_class=None):
""" This class overwrites the from_json method, thus making sure that if `from_json` is called from this class instance, it will provide its JSON schema as a default one"""
schema = cls.json_schema if json_schema_class is None else json_schema_class()
return super(InfinityVertex, cls).from_json(data=data, json_schema_class=schema.__class__) | python | def from_json(cls, data, json_schema_class=None):
""" This class overwrites the from_json method, thus making sure that if `from_json` is called from this class instance, it will provide its JSON schema as a default one"""
schema = cls.json_schema if json_schema_class is None else json_schema_class()
return super(InfinityVertex, cls).from_json(data=data, json_schema_class=schema.__class__) | [
"def",
"from_json",
"(",
"cls",
",",
"data",
",",
"json_schema_class",
"=",
"None",
")",
":",
"schema",
"=",
"cls",
".",
"json_schema",
"if",
"json_schema_class",
"is",
"None",
"else",
"json_schema_class",
"(",
")",
"return",
"super",
"(",
"InfinityVertex",
... | This class overwrites the from_json method, thus making sure that if `from_json` is called from this class instance, it will provide its JSON schema as a default one | [
"This",
"class",
"overwrites",
"the",
"from_json",
"method",
"thus",
"making",
"sure",
"that",
"if",
"from_json",
"is",
"called",
"from",
"this",
"class",
"instance",
"it",
"will",
"provide",
"its",
"JSON",
"schema",
"as",
"a",
"default",
"one"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/vertices.py#L226-L229 |
aganezov/bg | bg/vertices.py | TaggedVertex.name | def name(self):
""" access to classic name attribute is hidden by this property """
return self.NAME_SEPARATOR.join([super(TaggedVertex, self).name] + self.get_tags_as_list_of_strings()) | python | def name(self):
""" access to classic name attribute is hidden by this property """
return self.NAME_SEPARATOR.join([super(TaggedVertex, self).name] + self.get_tags_as_list_of_strings()) | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"NAME_SEPARATOR",
".",
"join",
"(",
"[",
"super",
"(",
"TaggedVertex",
",",
"self",
")",
".",
"name",
"]",
"+",
"self",
".",
"get_tags_as_list_of_strings",
"(",
")",
")"
] | access to classic name attribute is hidden by this property | [
"access",
"to",
"classic",
"name",
"attribute",
"is",
"hidden",
"by",
"this",
"property"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/vertices.py#L264-L266 |
aganezov/bg | bg/vertices.py | TaggedVertex.add_tag | def add_tag(self, tag, value):
""" as tags are kept in a sorted order, a bisection is a fastest way to identify a correct position
of or a new tag to be added. An additional check is required to make sure w don't add duplicates
"""
index = bisect_left(self.tags, (tag, value))
contains = False
if index < len(self.tags):
contains = self.tags[index] == (tag, value)
if not contains:
self.tags.insert(index, (tag, value)) | python | def add_tag(self, tag, value):
""" as tags are kept in a sorted order, a bisection is a fastest way to identify a correct position
of or a new tag to be added. An additional check is required to make sure w don't add duplicates
"""
index = bisect_left(self.tags, (tag, value))
contains = False
if index < len(self.tags):
contains = self.tags[index] == (tag, value)
if not contains:
self.tags.insert(index, (tag, value)) | [
"def",
"add_tag",
"(",
"self",
",",
"tag",
",",
"value",
")",
":",
"index",
"=",
"bisect_left",
"(",
"self",
".",
"tags",
",",
"(",
"tag",
",",
"value",
")",
")",
"contains",
"=",
"False",
"if",
"index",
"<",
"len",
"(",
"self",
".",
"tags",
")",... | as tags are kept in a sorted order, a bisection is a fastest way to identify a correct position
of or a new tag to be added. An additional check is required to make sure w don't add duplicates | [
"as",
"tags",
"are",
"kept",
"in",
"a",
"sorted",
"order",
"a",
"bisection",
"is",
"a",
"fastest",
"way",
"to",
"identify",
"a",
"correct",
"position",
"of",
"or",
"a",
"new",
"tag",
"to",
"be",
"added",
".",
"An",
"additional",
"check",
"is",
"require... | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/vertices.py#L276-L285 |
aganezov/bg | bg/vertices.py | TaggedVertex.remove_tag | def remove_tag(self, tag, value, silent_fail=False):
""" we try to remove supplied pair tag -- value, and if does not exist outcome depends on the silent_fail flag """
try:
self.tags.remove((tag, value))
except ValueError as err:
if not silent_fail:
raise err | python | def remove_tag(self, tag, value, silent_fail=False):
""" we try to remove supplied pair tag -- value, and if does not exist outcome depends on the silent_fail flag """
try:
self.tags.remove((tag, value))
except ValueError as err:
if not silent_fail:
raise err | [
"def",
"remove_tag",
"(",
"self",
",",
"tag",
",",
"value",
",",
"silent_fail",
"=",
"False",
")",
":",
"try",
":",
"self",
".",
"tags",
".",
"remove",
"(",
"(",
"tag",
",",
"value",
")",
")",
"except",
"ValueError",
"as",
"err",
":",
"if",
"not",
... | we try to remove supplied pair tag -- value, and if does not exist outcome depends on the silent_fail flag | [
"we",
"try",
"to",
"remove",
"supplied",
"pair",
"tag",
"--",
"value",
"and",
"if",
"does",
"not",
"exist",
"outcome",
"depends",
"on",
"the",
"silent_fail",
"flag"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/vertices.py#L296-L302 |
aganezov/bg | bg/edge.py | BGEdge.merge | def merge(cls, edge1, edge2):
""" Merges multi-color information from two supplied :class:`BGEdge` instances into a new :class:`BGEdge`
Since :class:`BGEdge` represents an undirected edge, created edge's vertices are assign according to the order in first supplied edge.
Accounts for subclassing.
:param edge1: first out of two edge information from which is to be merged into a new one
:param edge2: second out of two edge information from which is to be merged into a new one
:return: a new undirected with multi-color information merged from two supplied :class:`BGEdge` objects
:raises: ``ValueError``
"""
if edge1.vertex1 != edge2.vertex1 and edge1.vertex1 != edge2.vertex2:
raise ValueError("Edges to be merged do not connect same vertices")
forward = edge1.vertex1 == edge2.vertex1
if forward and edge1.vertex2 != edge2.vertex2:
raise ValueError("Edges to be merged do not connect same vertices")
elif not forward and edge1.vertex2 != edge2.vertex1:
raise ValueError("Edges to be merged do not connect same vertices")
return cls(vertex1=edge1.vertex1, vertex2=edge1.vertex2, multicolor=edge1.multicolor + edge2.multicolor) | python | def merge(cls, edge1, edge2):
""" Merges multi-color information from two supplied :class:`BGEdge` instances into a new :class:`BGEdge`
Since :class:`BGEdge` represents an undirected edge, created edge's vertices are assign according to the order in first supplied edge.
Accounts for subclassing.
:param edge1: first out of two edge information from which is to be merged into a new one
:param edge2: second out of two edge information from which is to be merged into a new one
:return: a new undirected with multi-color information merged from two supplied :class:`BGEdge` objects
:raises: ``ValueError``
"""
if edge1.vertex1 != edge2.vertex1 and edge1.vertex1 != edge2.vertex2:
raise ValueError("Edges to be merged do not connect same vertices")
forward = edge1.vertex1 == edge2.vertex1
if forward and edge1.vertex2 != edge2.vertex2:
raise ValueError("Edges to be merged do not connect same vertices")
elif not forward and edge1.vertex2 != edge2.vertex1:
raise ValueError("Edges to be merged do not connect same vertices")
return cls(vertex1=edge1.vertex1, vertex2=edge1.vertex2, multicolor=edge1.multicolor + edge2.multicolor) | [
"def",
"merge",
"(",
"cls",
",",
"edge1",
",",
"edge2",
")",
":",
"if",
"edge1",
".",
"vertex1",
"!=",
"edge2",
".",
"vertex1",
"and",
"edge1",
".",
"vertex1",
"!=",
"edge2",
".",
"vertex2",
":",
"raise",
"ValueError",
"(",
"\"Edges to be merged do not con... | Merges multi-color information from two supplied :class:`BGEdge` instances into a new :class:`BGEdge`
Since :class:`BGEdge` represents an undirected edge, created edge's vertices are assign according to the order in first supplied edge.
Accounts for subclassing.
:param edge1: first out of two edge information from which is to be merged into a new one
:param edge2: second out of two edge information from which is to be merged into a new one
:return: a new undirected with multi-color information merged from two supplied :class:`BGEdge` objects
:raises: ``ValueError`` | [
"Merges",
"multi",
"-",
"color",
"information",
"from",
"two",
"supplied",
":",
"class",
":",
"BGEdge",
"instances",
"into",
"a",
"new",
":",
"class",
":",
"BGEdge"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/edge.py#L82-L101 |
aganezov/bg | bg/edge.py | BGEdge.colors_json_ids | def colors_json_ids(self):
""" A proxy property based access to vertices in current edge
When edge is serialized to JSON object, no explicit object for its multicolor is created, but rather all colors,
taking into account their multiplicity, are referenced by their json_ids.
"""
return [color.json_id if hasattr(color, "json_id") else hash(color) for color in self.multicolor.multicolors.elements()] | python | def colors_json_ids(self):
""" A proxy property based access to vertices in current edge
When edge is serialized to JSON object, no explicit object for its multicolor is created, but rather all colors,
taking into account their multiplicity, are referenced by their json_ids.
"""
return [color.json_id if hasattr(color, "json_id") else hash(color) for color in self.multicolor.multicolors.elements()] | [
"def",
"colors_json_ids",
"(",
"self",
")",
":",
"return",
"[",
"color",
".",
"json_id",
"if",
"hasattr",
"(",
"color",
",",
"\"json_id\"",
")",
"else",
"hash",
"(",
"color",
")",
"for",
"color",
"in",
"self",
".",
"multicolor",
".",
"multicolors",
".",
... | A proxy property based access to vertices in current edge
When edge is serialized to JSON object, no explicit object for its multicolor is created, but rather all colors,
taking into account their multiplicity, are referenced by their json_ids. | [
"A",
"proxy",
"property",
"based",
"access",
"to",
"vertices",
"in",
"current",
"edge"
] | train | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/edge.py#L163-L169 |
humangeo/rawes | rawes/elastic.py | Elastic._get_connection_from_url | def _get_connection_from_url(self, url, timeout, **kwargs):
"""Returns a connection object given a string url"""
url = self._decode_url(url, "")
if url.scheme == 'http' or url.scheme == 'https':
return HttpConnection(url.geturl(), timeout=timeout, **kwargs)
else:
if sys.version_info[0] > 2:
raise ValueError("Thrift transport is not available "
"for Python 3")
try:
from thrift_connection import ThriftConnection
except ImportError:
raise ImportError("The 'thrift' python package "
"does not seem to be installed.")
return ThriftConnection(url.hostname, url.port,
timeout=timeout, **kwargs) | python | def _get_connection_from_url(self, url, timeout, **kwargs):
"""Returns a connection object given a string url"""
url = self._decode_url(url, "")
if url.scheme == 'http' or url.scheme == 'https':
return HttpConnection(url.geturl(), timeout=timeout, **kwargs)
else:
if sys.version_info[0] > 2:
raise ValueError("Thrift transport is not available "
"for Python 3")
try:
from thrift_connection import ThriftConnection
except ImportError:
raise ImportError("The 'thrift' python package "
"does not seem to be installed.")
return ThriftConnection(url.hostname, url.port,
timeout=timeout, **kwargs) | [
"def",
"_get_connection_from_url",
"(",
"self",
",",
"url",
",",
"timeout",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"_decode_url",
"(",
"url",
",",
"\"\"",
")",
"if",
"url",
".",
"scheme",
"==",
"'http'",
"or",
"url",
".",
"scheme... | Returns a connection object given a string url | [
"Returns",
"a",
"connection",
"object",
"given",
"a",
"string",
"url"
] | train | https://github.com/humangeo/rawes/blob/b860100cbb4115a1c884133c83eae448ded6b2d3/rawes/elastic.py#L180-L198 |
lobocv/pyperform | pyperform/customlogger.py | new_log_level | def new_log_level(level, name, logger_name=None):
"""
Quick way to create a custom log level that behaves like the default levels in the logging module.
:param level: level number
:param name: level name
:param logger_name: optional logger name
"""
@CustomLogLevel(level, name, logger_name)
def _default_template(logger, msg, *args, **kwargs):
return msg, args, kwargs | python | def new_log_level(level, name, logger_name=None):
"""
Quick way to create a custom log level that behaves like the default levels in the logging module.
:param level: level number
:param name: level name
:param logger_name: optional logger name
"""
@CustomLogLevel(level, name, logger_name)
def _default_template(logger, msg, *args, **kwargs):
return msg, args, kwargs | [
"def",
"new_log_level",
"(",
"level",
",",
"name",
",",
"logger_name",
"=",
"None",
")",
":",
"@",
"CustomLogLevel",
"(",
"level",
",",
"name",
",",
"logger_name",
")",
"def",
"_default_template",
"(",
"logger",
",",
"msg",
",",
"*",
"args",
",",
"*",
... | Quick way to create a custom log level that behaves like the default levels in the logging module.
:param level: level number
:param name: level name
:param logger_name: optional logger name | [
"Quick",
"way",
"to",
"create",
"a",
"custom",
"log",
"level",
"that",
"behaves",
"like",
"the",
"default",
"levels",
"in",
"the",
"logging",
"module",
".",
":",
"param",
"level",
":",
"level",
"number",
":",
"param",
"name",
":",
"level",
"name",
":",
... | train | https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/customlogger.py#L40-L49 |
theiviaxx/Frog | frog/common.py | userToJson | def userToJson(user):
"""Returns a serializable User dict
:param user: User to get info for
:type user: User
:returns: dict
"""
obj = {
'id': user.id,
'username': user.username,
'name': user.get_full_name(),
'email': user.email,
}
return obj | python | def userToJson(user):
"""Returns a serializable User dict
:param user: User to get info for
:type user: User
:returns: dict
"""
obj = {
'id': user.id,
'username': user.username,
'name': user.get_full_name(),
'email': user.email,
}
return obj | [
"def",
"userToJson",
"(",
"user",
")",
":",
"obj",
"=",
"{",
"'id'",
":",
"user",
".",
"id",
",",
"'username'",
":",
"user",
".",
"username",
",",
"'name'",
":",
"user",
".",
"get_full_name",
"(",
")",
",",
"'email'",
":",
"user",
".",
"email",
","... | Returns a serializable User dict
:param user: User to get info for
:type user: User
:returns: dict | [
"Returns",
"a",
"serializable",
"User",
"dict"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/common.py#L84-L98 |
theiviaxx/Frog | frog/common.py | commentToJson | def commentToJson(comment):
"""Returns a serializable Comment dict
:param comment: Comment to get info for
:type comment: Comment
:returns: dict
"""
obj = {
'id': comment.id,
'comment': comment.comment,
'user': userToJson(comment.user),
'date': comment.submit_date.isoformat(),
}
return obj | python | def commentToJson(comment):
"""Returns a serializable Comment dict
:param comment: Comment to get info for
:type comment: Comment
:returns: dict
"""
obj = {
'id': comment.id,
'comment': comment.comment,
'user': userToJson(comment.user),
'date': comment.submit_date.isoformat(),
}
return obj | [
"def",
"commentToJson",
"(",
"comment",
")",
":",
"obj",
"=",
"{",
"'id'",
":",
"comment",
".",
"id",
",",
"'comment'",
":",
"comment",
".",
"comment",
",",
"'user'",
":",
"userToJson",
"(",
"comment",
".",
"user",
")",
",",
"'date'",
":",
"comment",
... | Returns a serializable Comment dict
:param comment: Comment to get info for
:type comment: Comment
:returns: dict | [
"Returns",
"a",
"serializable",
"Comment",
"dict"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/common.py#L101-L115 |
theiviaxx/Frog | frog/common.py | getPutData | def getPutData(request):
"""Adds raw post to the PUT and DELETE querydicts on the request so they behave like post
:param request: Request object to add PUT/DELETE to
:type request: Request
"""
dataDict = {}
data = request.body
for n in urlparse.parse_qsl(data):
dataDict[n[0]] = n[1]
setattr(request, 'PUT', dataDict)
setattr(request, 'DELETE', dataDict) | python | def getPutData(request):
"""Adds raw post to the PUT and DELETE querydicts on the request so they behave like post
:param request: Request object to add PUT/DELETE to
:type request: Request
"""
dataDict = {}
data = request.body
for n in urlparse.parse_qsl(data):
dataDict[n[0]] = n[1]
setattr(request, 'PUT', dataDict)
setattr(request, 'DELETE', dataDict) | [
"def",
"getPutData",
"(",
"request",
")",
":",
"dataDict",
"=",
"{",
"}",
"data",
"=",
"request",
".",
"body",
"for",
"n",
"in",
"urlparse",
".",
"parse_qsl",
"(",
"data",
")",
":",
"dataDict",
"[",
"n",
"[",
"0",
"]",
"]",
"=",
"n",
"[",
"1",
... | Adds raw post to the PUT and DELETE querydicts on the request so they behave like post
:param request: Request object to add PUT/DELETE to
:type request: Request | [
"Adds",
"raw",
"post",
"to",
"the",
"PUT",
"and",
"DELETE",
"querydicts",
"on",
"the",
"request",
"so",
"they",
"behave",
"like",
"post"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/common.py#L118-L131 |
theiviaxx/Frog | frog/common.py | getHashForFile | def getHashForFile(f):
"""Returns a hash value for a file
:param f: File to hash
:type f: str
:returns: str
"""
hashVal = hashlib.sha1()
while True:
r = f.read(1024)
if not r:
break
hashVal.update(r)
f.seek(0)
return hashVal.hexdigest() | python | def getHashForFile(f):
"""Returns a hash value for a file
:param f: File to hash
:type f: str
:returns: str
"""
hashVal = hashlib.sha1()
while True:
r = f.read(1024)
if not r:
break
hashVal.update(r)
f.seek(0)
return hashVal.hexdigest() | [
"def",
"getHashForFile",
"(",
"f",
")",
":",
"hashVal",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"while",
"True",
":",
"r",
"=",
"f",
".",
"read",
"(",
"1024",
")",
"if",
"not",
"r",
":",
"break",
"hashVal",
".",
"update",
"(",
"r",
")",
"f",
"."... | Returns a hash value for a file
:param f: File to hash
:type f: str
:returns: str | [
"Returns",
"a",
"hash",
"value",
"for",
"a",
"file"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/common.py#L134-L149 |
theiviaxx/Frog | frog/common.py | uniqueID | def uniqueID(size=6, chars=string.ascii_uppercase + string.digits):
"""A quick and dirty way to get a unique string"""
return ''.join(random.choice(chars) for x in xrange(size)) | python | def uniqueID(size=6, chars=string.ascii_uppercase + string.digits):
"""A quick and dirty way to get a unique string"""
return ''.join(random.choice(chars) for x in xrange(size)) | [
"def",
"uniqueID",
"(",
"size",
"=",
"6",
",",
"chars",
"=",
"string",
".",
"ascii_uppercase",
"+",
"string",
".",
"digits",
")",
":",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"chars",
")",
"for",
"x",
"in",
"xrange",
"(",
"s... | A quick and dirty way to get a unique string | [
"A",
"quick",
"and",
"dirty",
"way",
"to",
"get",
"a",
"unique",
"string"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/common.py#L157-L159 |
theiviaxx/Frog | frog/common.py | getObjectsFromGuids | def getObjectsFromGuids(guids):
"""Gets the model objects based on a guid list
:param guids: Guids to get objects for
:type guids: list
:returns: list
"""
guids = guids[:]
img = list(Image.objects.filter(guid__in=guids))
vid = list(Video.objects.filter(guid__in=guids))
objects = img + vid
sortedobjects = []
if objects:
while guids:
for obj in iter(objects):
if obj.guid == guids[0]:
sortedobjects.append(obj)
guids.pop(0)
break
return sortedobjects | python | def getObjectsFromGuids(guids):
"""Gets the model objects based on a guid list
:param guids: Guids to get objects for
:type guids: list
:returns: list
"""
guids = guids[:]
img = list(Image.objects.filter(guid__in=guids))
vid = list(Video.objects.filter(guid__in=guids))
objects = img + vid
sortedobjects = []
if objects:
while guids:
for obj in iter(objects):
if obj.guid == guids[0]:
sortedobjects.append(obj)
guids.pop(0)
break
return sortedobjects | [
"def",
"getObjectsFromGuids",
"(",
"guids",
")",
":",
"guids",
"=",
"guids",
"[",
":",
"]",
"img",
"=",
"list",
"(",
"Image",
".",
"objects",
".",
"filter",
"(",
"guid__in",
"=",
"guids",
")",
")",
"vid",
"=",
"list",
"(",
"Video",
".",
"objects",
... | Gets the model objects based on a guid list
:param guids: Guids to get objects for
:type guids: list
:returns: list | [
"Gets",
"the",
"model",
"objects",
"based",
"on",
"a",
"guid",
"list"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/common.py#L162-L183 |
theiviaxx/Frog | frog/common.py | getClientIP | def getClientIP(request):
"""Returns the best IP address found from the request"""
forwardedfor = request.META.get('HTTP_X_FORWARDED_FOR')
if forwardedfor:
ip = forwardedfor.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip | python | def getClientIP(request):
"""Returns the best IP address found from the request"""
forwardedfor = request.META.get('HTTP_X_FORWARDED_FOR')
if forwardedfor:
ip = forwardedfor.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip | [
"def",
"getClientIP",
"(",
"request",
")",
":",
"forwardedfor",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_X_FORWARDED_FOR'",
")",
"if",
"forwardedfor",
":",
"ip",
"=",
"forwardedfor",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
"else",
":",
... | Returns the best IP address found from the request | [
"Returns",
"the",
"best",
"IP",
"address",
"found",
"from",
"the",
"request"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/common.py#L186-L194 |
theiviaxx/Frog | frog/common.py | __discoverPlugins | def __discoverPlugins():
""" Discover the plugin classes contained in Python files, given a
list of directory names to scan. Return a list of plugin classes.
"""
for app in settings.INSTALLED_APPS:
if not app.startswith('django'):
module = __import__(app)
moduledir = path.Path(module.__file__).parent
plugin = moduledir / 'frog_plugin.py'
if plugin.exists():
file_, fpath, desc = imp.find_module('frog_plugin', [moduledir])
if file_:
imp.load_module('frog_plugin', file_, fpath, desc)
return FrogPluginRegistry.plugins | python | def __discoverPlugins():
""" Discover the plugin classes contained in Python files, given a
list of directory names to scan. Return a list of plugin classes.
"""
for app in settings.INSTALLED_APPS:
if not app.startswith('django'):
module = __import__(app)
moduledir = path.Path(module.__file__).parent
plugin = moduledir / 'frog_plugin.py'
if plugin.exists():
file_, fpath, desc = imp.find_module('frog_plugin', [moduledir])
if file_:
imp.load_module('frog_plugin', file_, fpath, desc)
return FrogPluginRegistry.plugins | [
"def",
"__discoverPlugins",
"(",
")",
":",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"if",
"not",
"app",
".",
"startswith",
"(",
"'django'",
")",
":",
"module",
"=",
"__import__",
"(",
"app",
")",
"moduledir",
"=",
"path",
".",
"Path",
... | Discover the plugin classes contained in Python files, given a
list of directory names to scan. Return a list of plugin classes. | [
"Discover",
"the",
"plugin",
"classes",
"contained",
"in",
"Python",
"files",
"given",
"a",
"list",
"of",
"directory",
"names",
"to",
"scan",
".",
"Return",
"a",
"list",
"of",
"plugin",
"classes",
"."
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/common.py#L238-L252 |
theiviaxx/Frog | frog/common.py | Result.append | def append(self, val):
"""Appends the object to the end of the values list. Will also set the value to the first
item in the values list
:param val: Object to append
:type val: primitive
"""
self.values.append(val)
self.value = self.values[0] | python | def append(self, val):
"""Appends the object to the end of the values list. Will also set the value to the first
item in the values list
:param val: Object to append
:type val: primitive
"""
self.values.append(val)
self.value = self.values[0] | [
"def",
"append",
"(",
"self",
",",
"val",
")",
":",
"self",
".",
"values",
".",
"append",
"(",
"val",
")",
"self",
".",
"value",
"=",
"self",
".",
"values",
"[",
"0",
"]"
] | Appends the object to the end of the values list. Will also set the value to the first
item in the values list
:param val: Object to append
:type val: primitive | [
"Appends",
"the",
"object",
"to",
"the",
"end",
"of",
"the",
"values",
"list",
".",
"Will",
"also",
"set",
"the",
"value",
"to",
"the",
"first",
"item",
"in",
"the",
"values",
"list"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/common.py#L57-L65 |
theiviaxx/Frog | frog/common.py | Result.asDict | def asDict(self):
"""Returns a serializable object"""
return {
'isError': self.isError,
'message': self.message,
'values': self.values,
'value': self.value,
} | python | def asDict(self):
"""Returns a serializable object"""
return {
'isError': self.isError,
'message': self.message,
'values': self.values,
'value': self.value,
} | [
"def",
"asDict",
"(",
"self",
")",
":",
"return",
"{",
"'isError'",
":",
"self",
".",
"isError",
",",
"'message'",
":",
"self",
".",
"message",
",",
"'values'",
":",
"self",
".",
"values",
",",
"'value'",
":",
"self",
".",
"value",
",",
"}"
] | Returns a serializable object | [
"Returns",
"a",
"serializable",
"object"
] | train | https://github.com/theiviaxx/Frog/blob/a9475463a8eed1323fe3ef5d51f9751fb1dc9edd/frog/common.py#L67-L74 |
gmr/tredis | tredis/server.py | ServerMixin.auth | def auth(self, password):
"""Request for authentication in a password-protected Redis server.
Redis can be instructed to require a password before allowing clients
to execute commands. This is done using the ``requirepass`` directive
in the configuration file.
If the password does not match, an
:exc:`~tredis.exceptions.AuthError` exception
will be raised.
:param password: The password to authenticate with
:type password: :class:`str`, :class:`bytes`
:rtype: bool
:raises: :exc:`~tredis.exceptions.AuthError`,
:exc:`~tredis.exceptions.RedisError`
"""
future = concurrent.TracebackFuture()
def on_response(response):
"""Process the redis response
:param response: The future with the response
:type response: tornado.concurrent.Future
"""
exc = response.exception()
if exc:
if exc.args[0] == b'invalid password':
future.set_exception(exceptions.AuthError(exc))
else:
future.set_exception(exc)
else:
future.set_result(response.result())
execute_future = self._execute([b'AUTH', password], b'OK')
self.io_loop.add_future(execute_future, on_response)
return future | python | def auth(self, password):
"""Request for authentication in a password-protected Redis server.
Redis can be instructed to require a password before allowing clients
to execute commands. This is done using the ``requirepass`` directive
in the configuration file.
If the password does not match, an
:exc:`~tredis.exceptions.AuthError` exception
will be raised.
:param password: The password to authenticate with
:type password: :class:`str`, :class:`bytes`
:rtype: bool
:raises: :exc:`~tredis.exceptions.AuthError`,
:exc:`~tredis.exceptions.RedisError`
"""
future = concurrent.TracebackFuture()
def on_response(response):
"""Process the redis response
:param response: The future with the response
:type response: tornado.concurrent.Future
"""
exc = response.exception()
if exc:
if exc.args[0] == b'invalid password':
future.set_exception(exceptions.AuthError(exc))
else:
future.set_exception(exc)
else:
future.set_result(response.result())
execute_future = self._execute([b'AUTH', password], b'OK')
self.io_loop.add_future(execute_future, on_response)
return future | [
"def",
"auth",
"(",
"self",
",",
"password",
")",
":",
"future",
"=",
"concurrent",
".",
"TracebackFuture",
"(",
")",
"def",
"on_response",
"(",
"response",
")",
":",
"\"\"\"Process the redis response\n\n :param response: The future with the response\n ... | Request for authentication in a password-protected Redis server.
Redis can be instructed to require a password before allowing clients
to execute commands. This is done using the ``requirepass`` directive
in the configuration file.
If the password does not match, an
:exc:`~tredis.exceptions.AuthError` exception
will be raised.
:param password: The password to authenticate with
:type password: :class:`str`, :class:`bytes`
:rtype: bool
:raises: :exc:`~tredis.exceptions.AuthError`,
:exc:`~tredis.exceptions.RedisError` | [
"Request",
"for",
"authentication",
"in",
"a",
"password",
"-",
"protected",
"Redis",
"server",
".",
"Redis",
"can",
"be",
"instructed",
"to",
"require",
"a",
"password",
"before",
"allowing",
"clients",
"to",
"execute",
"commands",
".",
"This",
"is",
"done",
... | train | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/server.py#L14-L51 |
gmr/tredis | tredis/server.py | ServerMixin.info | def info(self, section=None):
"""The INFO command returns information and statistics about the server
in a format that is simple to parse by computers and easy to read by
humans.
The optional parameter can be used to select a specific section of
information:
- server: General information about the Redis server
- clients: Client connections section
- memory: Memory consumption related information
- persistence: RDB and AOF related information
- stats: General statistics
- replication: Master/slave replication information
- cpu: CPU consumption statistics
- commandstats: Redis command statistics
- cluster: Redis Cluster section
- keyspace: Database related statistics
It can also take the following values:
- all: Return all sections
- default: Return only the default set of sections
When no parameter is provided, the default option is assumed.
:param str section: Optional
:return: dict
"""
cmd = [b'INFO']
if section:
cmd.append(section)
return self._execute(cmd, format_callback=common.format_info_response) | python | def info(self, section=None):
"""The INFO command returns information and statistics about the server
in a format that is simple to parse by computers and easy to read by
humans.
The optional parameter can be used to select a specific section of
information:
- server: General information about the Redis server
- clients: Client connections section
- memory: Memory consumption related information
- persistence: RDB and AOF related information
- stats: General statistics
- replication: Master/slave replication information
- cpu: CPU consumption statistics
- commandstats: Redis command statistics
- cluster: Redis Cluster section
- keyspace: Database related statistics
It can also take the following values:
- all: Return all sections
- default: Return only the default set of sections
When no parameter is provided, the default option is assumed.
:param str section: Optional
:return: dict
"""
cmd = [b'INFO']
if section:
cmd.append(section)
return self._execute(cmd, format_callback=common.format_info_response) | [
"def",
"info",
"(",
"self",
",",
"section",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"b'INFO'",
"]",
"if",
"section",
":",
"cmd",
".",
"append",
"(",
"section",
")",
"return",
"self",
".",
"_execute",
"(",
"cmd",
",",
"format_callback",
"=",
"common",... | The INFO command returns information and statistics about the server
in a format that is simple to parse by computers and easy to read by
humans.
The optional parameter can be used to select a specific section of
information:
- server: General information about the Redis server
- clients: Client connections section
- memory: Memory consumption related information
- persistence: RDB and AOF related information
- stats: General statistics
- replication: Master/slave replication information
- cpu: CPU consumption statistics
- commandstats: Redis command statistics
- cluster: Redis Cluster section
- keyspace: Database related statistics
It can also take the following values:
- all: Return all sections
- default: Return only the default set of sections
When no parameter is provided, the default option is assumed.
:param str section: Optional
:return: dict | [
"The",
"INFO",
"command",
"returns",
"information",
"and",
"statistics",
"about",
"the",
"server",
"in",
"a",
"format",
"that",
"is",
"simple",
"to",
"parse",
"by",
"computers",
"and",
"easy",
"to",
"read",
"by",
"humans",
"."
] | train | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/server.py#L64-L97 |
gmr/tredis | tredis/server.py | ServerMixin.select | def select(self, index=0):
"""Select the DB with having the specified zero-based numeric index.
New connections always use DB ``0``.
:param int index: The database to select
:rtype: bool
:raises: :exc:`~tredis.exceptions.RedisError`
:raises: :exc:`~tredis.exceptions.InvalidClusterCommand`
"""
if self._clustering:
raise exceptions.InvalidClusterCommand
future = self._execute(
[b'SELECT', ascii(index).encode('ascii')], b'OK')
def on_selected(f):
self._connection.database = index
self.io_loop.add_future(future, on_selected)
return future | python | def select(self, index=0):
"""Select the DB with having the specified zero-based numeric index.
New connections always use DB ``0``.
:param int index: The database to select
:rtype: bool
:raises: :exc:`~tredis.exceptions.RedisError`
:raises: :exc:`~tredis.exceptions.InvalidClusterCommand`
"""
if self._clustering:
raise exceptions.InvalidClusterCommand
future = self._execute(
[b'SELECT', ascii(index).encode('ascii')], b'OK')
def on_selected(f):
self._connection.database = index
self.io_loop.add_future(future, on_selected)
return future | [
"def",
"select",
"(",
"self",
",",
"index",
"=",
"0",
")",
":",
"if",
"self",
".",
"_clustering",
":",
"raise",
"exceptions",
".",
"InvalidClusterCommand",
"future",
"=",
"self",
".",
"_execute",
"(",
"[",
"b'SELECT'",
",",
"ascii",
"(",
"index",
")",
... | Select the DB with having the specified zero-based numeric index.
New connections always use DB ``0``.
:param int index: The database to select
:rtype: bool
:raises: :exc:`~tredis.exceptions.RedisError`
:raises: :exc:`~tredis.exceptions.InvalidClusterCommand` | [
"Select",
"the",
"DB",
"with",
"having",
"the",
"specified",
"zero",
"-",
"based",
"numeric",
"index",
".",
"New",
"connections",
"always",
"use",
"DB",
"0",
"."
] | train | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/server.py#L126-L145 |
gmr/tredis | tredis/server.py | ServerMixin.time | def time(self):
"""Retrieve the current time from the redis server.
:rtype: float
:raises: :exc:`~tredis.exceptions.RedisError`
"""
def format_response(value):
"""Format a TIME response into a datetime.datetime
:param list value: TIME response is a list of the number
of seconds since the epoch and the number of micros
as two byte strings
:rtype: float
"""
seconds, micros = value
return float(seconds) + (float(micros) / 1000000.0)
return self._execute([b'TIME'], format_callback=format_response) | python | def time(self):
"""Retrieve the current time from the redis server.
:rtype: float
:raises: :exc:`~tredis.exceptions.RedisError`
"""
def format_response(value):
"""Format a TIME response into a datetime.datetime
:param list value: TIME response is a list of the number
of seconds since the epoch and the number of micros
as two byte strings
:rtype: float
"""
seconds, micros = value
return float(seconds) + (float(micros) / 1000000.0)
return self._execute([b'TIME'], format_callback=format_response) | [
"def",
"time",
"(",
"self",
")",
":",
"def",
"format_response",
"(",
"value",
")",
":",
"\"\"\"Format a TIME response into a datetime.datetime\n\n :param list value: TIME response is a list of the number\n of seconds since the epoch and the number of micros\n ... | Retrieve the current time from the redis server.
:rtype: float
:raises: :exc:`~tredis.exceptions.RedisError` | [
"Retrieve",
"the",
"current",
"time",
"from",
"the",
"redis",
"server",
"."
] | train | https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/server.py#L147-L167 |
radzak/rtv-downloader | rtv/extractors/vodtvp.py | VodTVP.get_show_name | def get_show_name(self):
"""
Get video show name from the website. It's located in the div with 'data-hover'
attribute under the 'title' key.
Returns:
str: Video show name.
"""
div = self.soup.find('div', attrs={'data-hover': True})
data = json.loads(div['data-hover'])
show_name = data.get('title')
return show_name | python | def get_show_name(self):
"""
Get video show name from the website. It's located in the div with 'data-hover'
attribute under the 'title' key.
Returns:
str: Video show name.
"""
div = self.soup.find('div', attrs={'data-hover': True})
data = json.loads(div['data-hover'])
show_name = data.get('title')
return show_name | [
"def",
"get_show_name",
"(",
"self",
")",
":",
"div",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'div'",
",",
"attrs",
"=",
"{",
"'data-hover'",
":",
"True",
"}",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"div",
"[",
"'data-hover'",
"]",
")",
... | Get video show name from the website. It's located in the div with 'data-hover'
attribute under the 'title' key.
Returns:
str: Video show name. | [
"Get",
"video",
"show",
"name",
"from",
"the",
"website",
".",
"It",
"s",
"located",
"in",
"the",
"div",
"with",
"data",
"-",
"hover",
"attribute",
"under",
"the",
"title",
"key",
"."
] | train | https://github.com/radzak/rtv-downloader/blob/b9114b7f4c35fabe6ec9ad1764a65858667a866e/rtv/extractors/vodtvp.py#L43-L56 |
hodgesds/elasticsearch_tornado | elasticsearch_tornado/client.py | BaseClient.mk_req | def mk_req(self, url, **kwargs):
"""
Helper function to create a tornado HTTPRequest object, kwargs get passed in to
create the HTTPRequest object. See:
http://tornado.readthedocs.org/en/latest/httpclient.html#request-objects
"""
req_url = self.base_url + url
req_kwargs = kwargs
req_kwargs['ca_certs'] = req_kwargs.get('ca_certs', self.certs)
# have to do this because tornado's HTTP client doesn't
# play nice with elasticsearch
req_kwargs['allow_nonstandard_methods'] = req_kwargs.get(
'allow_nonstandard_methods',
True
)
return HTTPRequest(req_url, **req_kwargs) | python | def mk_req(self, url, **kwargs):
"""
Helper function to create a tornado HTTPRequest object, kwargs get passed in to
create the HTTPRequest object. See:
http://tornado.readthedocs.org/en/latest/httpclient.html#request-objects
"""
req_url = self.base_url + url
req_kwargs = kwargs
req_kwargs['ca_certs'] = req_kwargs.get('ca_certs', self.certs)
# have to do this because tornado's HTTP client doesn't
# play nice with elasticsearch
req_kwargs['allow_nonstandard_methods'] = req_kwargs.get(
'allow_nonstandard_methods',
True
)
return HTTPRequest(req_url, **req_kwargs) | [
"def",
"mk_req",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"req_url",
"=",
"self",
".",
"base_url",
"+",
"url",
"req_kwargs",
"=",
"kwargs",
"req_kwargs",
"[",
"'ca_certs'",
"]",
"=",
"req_kwargs",
".",
"get",
"(",
"'ca_certs'",
",",
... | Helper function to create a tornado HTTPRequest object, kwargs get passed in to
create the HTTPRequest object. See:
http://tornado.readthedocs.org/en/latest/httpclient.html#request-objects | [
"Helper",
"function",
"to",
"create",
"a",
"tornado",
"HTTPRequest",
"object",
"kwargs",
"get",
"passed",
"in",
"to",
"create",
"the",
"HTTPRequest",
"object",
".",
"See",
":",
"http",
":",
"//",
"tornado",
".",
"readthedocs",
".",
"org",
"/",
"en",
"/",
... | train | https://github.com/hodgesds/elasticsearch_tornado/blob/5acc1385589c92ffe3587ad05b7921c2cd1a30da/elasticsearch_tornado/client.py#L37-L52 |
hodgesds/elasticsearch_tornado | elasticsearch_tornado/client.py | BaseClient.mk_url | def mk_url(self, *args, **kwargs):
"""
Args get parameterized into base url:
*(foo, bar, baz) -> /foo/bar/baz
Kwargs get encoded and appended to base url:
**{'hello':'world'} -> /foo/bar/baz?hello=world
"""
params = urlencode(kwargs)
url = '/' + '/'.join([x for x in args if x])
if params:
url += '?' + params
return url | python | def mk_url(self, *args, **kwargs):
"""
Args get parameterized into base url:
*(foo, bar, baz) -> /foo/bar/baz
Kwargs get encoded and appended to base url:
**{'hello':'world'} -> /foo/bar/baz?hello=world
"""
params = urlencode(kwargs)
url = '/' + '/'.join([x for x in args if x])
if params:
url += '?' + params
return url | [
"def",
"mk_url",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"urlencode",
"(",
"kwargs",
")",
"url",
"=",
"'/'",
"+",
"'/'",
".",
"join",
"(",
"[",
"x",
"for",
"x",
"in",
"args",
"if",
"x",
"]",
")",
"if",... | Args get parameterized into base url:
*(foo, bar, baz) -> /foo/bar/baz
Kwargs get encoded and appended to base url:
**{'hello':'world'} -> /foo/bar/baz?hello=world | [
"Args",
"get",
"parameterized",
"into",
"base",
"url",
":",
"*",
"(",
"foo",
"bar",
"baz",
")",
"-",
">",
"/",
"foo",
"/",
"bar",
"/",
"baz",
"Kwargs",
"get",
"encoded",
"and",
"appended",
"to",
"base",
"url",
":",
"**",
"{",
"hello",
":",
"world",... | train | https://github.com/hodgesds/elasticsearch_tornado/blob/5acc1385589c92ffe3587ad05b7921c2cd1a30da/elasticsearch_tornado/client.py#L54-L65 |
hodgesds/elasticsearch_tornado | elasticsearch_tornado/client.py | BaseClient.ping | def ping(self, callback=None, **kwargs):
"""
Ping request to check status of elasticsearch host
"""
self.client.fetch(
self.mk_req('', method='HEAD', **kwargs),
callback = callback
) | python | def ping(self, callback=None, **kwargs):
"""
Ping request to check status of elasticsearch host
"""
self.client.fetch(
self.mk_req('', method='HEAD', **kwargs),
callback = callback
) | [
"def",
"ping",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"client",
".",
"fetch",
"(",
"self",
".",
"mk_req",
"(",
"''",
",",
"method",
"=",
"'HEAD'",
",",
"*",
"*",
"kwargs",
")",
",",
"callback",
... | Ping request to check status of elasticsearch host | [
"Ping",
"request",
"to",
"check",
"status",
"of",
"elasticsearch",
"host"
] | train | https://github.com/hodgesds/elasticsearch_tornado/blob/5acc1385589c92ffe3587ad05b7921c2cd1a30da/elasticsearch_tornado/client.py#L73-L80 |
hodgesds/elasticsearch_tornado | elasticsearch_tornado/client.py | BaseClient.info | def info(self, callback=None, **kwargs):
"""
Get the basic info from the current cluster.
"""
self.client.fetch(
self.mk_req('', method='GET', **kwargs),
callback = callback
) | python | def info(self, callback=None, **kwargs):
"""
Get the basic info from the current cluster.
"""
self.client.fetch(
self.mk_req('', method='GET', **kwargs),
callback = callback
) | [
"def",
"info",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"client",
".",
"fetch",
"(",
"self",
".",
"mk_req",
"(",
"''",
",",
"method",
"=",
"'GET'",
",",
"*",
"*",
"kwargs",
")",
",",
"callback",
... | Get the basic info from the current cluster. | [
"Get",
"the",
"basic",
"info",
"from",
"the",
"current",
"cluster",
"."
] | train | https://github.com/hodgesds/elasticsearch_tornado/blob/5acc1385589c92ffe3587ad05b7921c2cd1a30da/elasticsearch_tornado/client.py#L82-L89 |
hodgesds/elasticsearch_tornado | elasticsearch_tornado/client.py | BaseClient.create_doc | def create_doc(self,
index,
doc_type,
body,
doc_id = None,
params = {},
callback = None,
**kwargs
):
"""
Adds a typed JSON document in a specific index, making it searchable.
Behind the scenes this method calls index(..., op_type='create')
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-index_.html>`_
:arg index: The name of the index
:arg doc_type: The type of the document
:arg doc_id: Document ID
:arg body: The document
:arg consistency: Explicit write consistency setting for the operation
:arg id: Specific document ID (when the POST method is used)
:arg parent: ID of the parent document
:arg percolate: Percolator queries to execute while indexing the document
:arg refresh: Refresh the index after performing the operation
:arg replication: Specific replication type (default: sync)
:arg routing: Specific routing value
:arg timeout: Explicit operation timeout
:arg timestamp: Explicit timestamp for the document
:arg ttl: Expiration time for the document
:arg version: Explicit version number for concurrency control
:arg version_type: Specific version type
"""
method = 'PUT' if doc_id else 'POST'
query_params = ('consistency', 'op_type', 'parent', 'refresh',
'replication', 'routing', 'timeout', 'timestamp', 'ttl', 'version',
'version_type',
)
params = self._filter_params(query_params, params)
url = self.mk_url(*[index, doc_type, doc_id], **params)
self.client.fetch(
self.mk_req(url, method=method, body=body, **kwargs),
callback = callback
) | python | def create_doc(self,
index,
doc_type,
body,
doc_id = None,
params = {},
callback = None,
**kwargs
):
"""
Adds a typed JSON document in a specific index, making it searchable.
Behind the scenes this method calls index(..., op_type='create')
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-index_.html>`_
:arg index: The name of the index
:arg doc_type: The type of the document
:arg doc_id: Document ID
:arg body: The document
:arg consistency: Explicit write consistency setting for the operation
:arg id: Specific document ID (when the POST method is used)
:arg parent: ID of the parent document
:arg percolate: Percolator queries to execute while indexing the document
:arg refresh: Refresh the index after performing the operation
:arg replication: Specific replication type (default: sync)
:arg routing: Specific routing value
:arg timeout: Explicit operation timeout
:arg timestamp: Explicit timestamp for the document
:arg ttl: Expiration time for the document
:arg version: Explicit version number for concurrency control
:arg version_type: Specific version type
"""
method = 'PUT' if doc_id else 'POST'
query_params = ('consistency', 'op_type', 'parent', 'refresh',
'replication', 'routing', 'timeout', 'timestamp', 'ttl', 'version',
'version_type',
)
params = self._filter_params(query_params, params)
url = self.mk_url(*[index, doc_type, doc_id], **params)
self.client.fetch(
self.mk_req(url, method=method, body=body, **kwargs),
callback = callback
) | [
"def",
"create_doc",
"(",
"self",
",",
"index",
",",
"doc_type",
",",
"body",
",",
"doc_id",
"=",
"None",
",",
"params",
"=",
"{",
"}",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"method",
"=",
"'PUT'",
"if",
"doc_id",
"else",... | Adds a typed JSON document in a specific index, making it searchable.
Behind the scenes this method calls index(..., op_type='create')
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-index_.html>`_
:arg index: The name of the index
:arg doc_type: The type of the document
:arg doc_id: Document ID
:arg body: The document
:arg consistency: Explicit write consistency setting for the operation
:arg id: Specific document ID (when the POST method is used)
:arg parent: ID of the parent document
:arg percolate: Percolator queries to execute while indexing the document
:arg refresh: Refresh the index after performing the operation
:arg replication: Specific replication type (default: sync)
:arg routing: Specific routing value
:arg timeout: Explicit operation timeout
:arg timestamp: Explicit timestamp for the document
:arg ttl: Expiration time for the document
:arg version: Explicit version number for concurrency control
:arg version_type: Specific version type | [
"Adds",
"a",
"typed",
"JSON",
"document",
"in",
"a",
"specific",
"index",
"making",
"it",
"searchable",
".",
"Behind",
"the",
"scenes",
"this",
"method",
"calls",
"index",
"(",
"...",
"op_type",
"=",
"create",
")",
"<http",
":",
"//",
"www",
".",
"elasti... | train | https://github.com/hodgesds/elasticsearch_tornado/blob/5acc1385589c92ffe3587ad05b7921c2cd1a30da/elasticsearch_tornado/client.py#L91-L136 |
hodgesds/elasticsearch_tornado | elasticsearch_tornado/client.py | BaseClient.scroll | def scroll(self, scroll_id, params={}, callback=None, **kwargs):
"""
Scroll a search request created by specifying the scroll parameter.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_
:arg scroll_id: The scroll ID
:arg scroll: Specify how long a consistent view of the index should be
maintained for scrolled search
"""
query_params = ('scroll',)
params = self._filter_params(query_params, params)
url = self.mk_url(*['/_search/scroll'], **params)
self.client.fetch(
self.mk_req(url, method='GET', body=scroll_id, **kwargs),
callback = callback
) | python | def scroll(self, scroll_id, params={}, callback=None, **kwargs):
"""
Scroll a search request created by specifying the scroll parameter.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_
:arg scroll_id: The scroll ID
:arg scroll: Specify how long a consistent view of the index should be
maintained for scrolled search
"""
query_params = ('scroll',)
params = self._filter_params(query_params, params)
url = self.mk_url(*['/_search/scroll'], **params)
self.client.fetch(
self.mk_req(url, method='GET', body=scroll_id, **kwargs),
callback = callback
) | [
"def",
"scroll",
"(",
"self",
",",
"scroll_id",
",",
"params",
"=",
"{",
"}",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"query_params",
"=",
"(",
"'scroll'",
",",
")",
"params",
"=",
"self",
".",
"_filter_params",
"(",
"query_p... | Scroll a search request created by specifying the scroll parameter.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_
:arg scroll_id: The scroll ID
:arg scroll: Specify how long a consistent view of the index should be
maintained for scrolled search | [
"Scroll",
"a",
"search",
"request",
"created",
"by",
"specifying",
"the",
"scroll",
"parameter",
".",
"<http",
":",
"//",
"www",
".",
"elasticsearch",
".",
"org",
"/",
"guide",
"/",
"en",
"/",
"elasticsearch",
"/",
"reference",
"/",
"current",
"/",
"search... | train | https://github.com/hodgesds/elasticsearch_tornado/blob/5acc1385589c92ffe3587ad05b7921c2cd1a30da/elasticsearch_tornado/client.py#L630-L648 |
hodgesds/elasticsearch_tornado | elasticsearch_tornado/client.py | BaseClient.clear_scroll | def clear_scroll(self,
scroll_id = None,
body = '',
params = {},
callback = None,
**kwargs
):
"""
Clear the scroll request created by specifying the scroll parameter to
search.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_
:arg scroll_id: The scroll ID or a list of scroll IDs
:arg body: A comma-separated list of scroll IDs to clear if none was
specified via the scroll_id parameter
"""
url = self.mk_url(*['_search', 'scroll', scroll_id])
self.client.fetch(
self.mk_req(url, method='DELETE', body=body, **kwargs),
callback = callback
) | python | def clear_scroll(self,
scroll_id = None,
body = '',
params = {},
callback = None,
**kwargs
):
"""
Clear the scroll request created by specifying the scroll parameter to
search.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_
:arg scroll_id: The scroll ID or a list of scroll IDs
:arg body: A comma-separated list of scroll IDs to clear if none was
specified via the scroll_id parameter
"""
url = self.mk_url(*['_search', 'scroll', scroll_id])
self.client.fetch(
self.mk_req(url, method='DELETE', body=body, **kwargs),
callback = callback
) | [
"def",
"clear_scroll",
"(",
"self",
",",
"scroll_id",
"=",
"None",
",",
"body",
"=",
"''",
",",
"params",
"=",
"{",
"}",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"mk_url",
"(",
"*",
"[",
"'_search'... | Clear the scroll request created by specifying the scroll parameter to
search.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-scroll.html>`_
:arg scroll_id: The scroll ID or a list of scroll IDs
:arg body: A comma-separated list of scroll IDs to clear if none was
specified via the scroll_id parameter | [
"Clear",
"the",
"scroll",
"request",
"created",
"by",
"specifying",
"the",
"scroll",
"parameter",
"to",
"search",
".",
"<http",
":",
"//",
"www",
".",
"elasticsearch",
".",
"org",
"/",
"guide",
"/",
"en",
"/",
"elasticsearch",
"/",
"reference",
"/",
"curre... | train | https://github.com/hodgesds/elasticsearch_tornado/blob/5acc1385589c92ffe3587ad05b7921c2cd1a30da/elasticsearch_tornado/client.py#L650-L671 |
hodgesds/elasticsearch_tornado | elasticsearch_tornado/client.py | BaseClient.abort_benchmark | def abort_benchmark(self, name=None, params={}, body='', callback=None, **kwargs):
"""
Aborts a running benchmark.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html>`_
:arg name: A benchmark name
"""
url = self.mk_url(*['_bench', 'abort', name])
self.client.fetch(
self.mk_req(url, method='POST', body=body, **kwargs),
callback = callback
) | python | def abort_benchmark(self, name=None, params={}, body='', callback=None, **kwargs):
"""
Aborts a running benchmark.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html>`_
:arg name: A benchmark name
"""
url = self.mk_url(*['_bench', 'abort', name])
self.client.fetch(
self.mk_req(url, method='POST', body=body, **kwargs),
callback = callback
) | [
"def",
"abort_benchmark",
"(",
"self",
",",
"name",
"=",
"None",
",",
"params",
"=",
"{",
"}",
",",
"body",
"=",
"''",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"mk_url",
"(",
"*",
"[",
"'_bench'",
... | Aborts a running benchmark.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html>`_
:arg name: A benchmark name | [
"Aborts",
"a",
"running",
"benchmark",
".",
"<http",
":",
"//",
"www",
".",
"elasticsearch",
".",
"org",
"/",
"guide",
"/",
"en",
"/",
"elasticsearch",
"/",
"reference",
"/",
"master",
"/",
"search",
"-",
"benchmark",
".",
"html",
">",
"_",
":",
"arg",... | train | https://github.com/hodgesds/elasticsearch_tornado/blob/5acc1385589c92ffe3587ad05b7921c2cd1a30da/elasticsearch_tornado/client.py#L1260-L1272 |
hodgesds/elasticsearch_tornado | elasticsearch_tornado/client.py | BaseClient.list_benchmarks | def list_benchmarks(self,
index = None,
doc_type = None,
params = {},
cb = None,
**kwargs
):
"""
View the progress of long-running benchmarks.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html>`_
:arg index: A comma-separated list of index names; use `_all` or empty
string to perform the operation on all indices
:arg doc_type: The name of the document type
"""
url = self.mk_url(*[index, doc_type, '_bench'], **params)
self.client.fetch(
self.mk_req(url, method='GET', **kwargs),
callback = callback
) | python | def list_benchmarks(self,
index = None,
doc_type = None,
params = {},
cb = None,
**kwargs
):
"""
View the progress of long-running benchmarks.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html>`_
:arg index: A comma-separated list of index names; use `_all` or empty
string to perform the operation on all indices
:arg doc_type: The name of the document type
"""
url = self.mk_url(*[index, doc_type, '_bench'], **params)
self.client.fetch(
self.mk_req(url, method='GET', **kwargs),
callback = callback
) | [
"def",
"list_benchmarks",
"(",
"self",
",",
"index",
"=",
"None",
",",
"doc_type",
"=",
"None",
",",
"params",
"=",
"{",
"}",
",",
"cb",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"mk_url",
"(",
"*",
"[",
"index",
... | View the progress of long-running benchmarks.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html>`_
:arg index: A comma-separated list of index names; use `_all` or empty
string to perform the operation on all indices
:arg doc_type: The name of the document type | [
"View",
"the",
"progress",
"of",
"long",
"-",
"running",
"benchmarks",
".",
"<http",
":",
"//",
"www",
".",
"elasticsearch",
".",
"org",
"/",
"guide",
"/",
"en",
"/",
"elasticsearch",
"/",
"reference",
"/",
"master",
"/",
"search",
"-",
"benchmark",
".",... | train | https://github.com/hodgesds/elasticsearch_tornado/blob/5acc1385589c92ffe3587ad05b7921c2cd1a30da/elasticsearch_tornado/client.py#L1274-L1294 |
hodgesds/elasticsearch_tornado | elasticsearch_tornado/client.py | BaseClient.put_script | def put_script(self, lang, script_id, body, params={}, callback=None, **kwargs):
"""
Create a script in given language with specified ID.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-scripting.html>`_
:arg lang: Script language
:arg script_id: Script ID
:arg body: The document
:arg op_type: Explicit operation type, default u'index'
:arg version: Explicit version number for concurrency control
:arg version_type: Specific version type
"""
query_params = ('op_type', 'version', 'version_type',)
params = self._filter_params(query_params, params)
url = self.mk_url(*['_scripts', lang, script_id], **params)
self.client.fetch(
self.mk_req(url, method='PUT', body=body, **kwargs),
callback = callback
) | python | def put_script(self, lang, script_id, body, params={}, callback=None, **kwargs):
"""
Create a script in given language with specified ID.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-scripting.html>`_
:arg lang: Script language
:arg script_id: Script ID
:arg body: The document
:arg op_type: Explicit operation type, default u'index'
:arg version: Explicit version number for concurrency control
:arg version_type: Specific version type
"""
query_params = ('op_type', 'version', 'version_type',)
params = self._filter_params(query_params, params)
url = self.mk_url(*['_scripts', lang, script_id], **params)
self.client.fetch(
self.mk_req(url, method='PUT', body=body, **kwargs),
callback = callback
) | [
"def",
"put_script",
"(",
"self",
",",
"lang",
",",
"script_id",
",",
"body",
",",
"params",
"=",
"{",
"}",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"query_params",
"=",
"(",
"'op_type'",
",",
"'version'",
",",
"'version_type'",... | Create a script in given language with specified ID.
`<http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-scripting.html>`_
:arg lang: Script language
:arg script_id: Script ID
:arg body: The document
:arg op_type: Explicit operation type, default u'index'
:arg version: Explicit version number for concurrency control
:arg version_type: Specific version type | [
"Create",
"a",
"script",
"in",
"given",
"language",
"with",
"specified",
"ID",
".",
"<http",
":",
"//",
"www",
".",
"elasticsearch",
".",
"org",
"/",
"guide",
"/",
"en",
"/",
"elasticsearch",
"/",
"reference",
"/",
"current",
"/",
"modules",
"-",
"script... | train | https://github.com/hodgesds/elasticsearch_tornado/blob/5acc1385589c92ffe3587ad05b7921c2cd1a30da/elasticsearch_tornado/client.py#L1296-L1316 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.