repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServerRequestHandler.handle_special | def handle_special(self, send_body, method_str):
"""Handles a dynamic request. If this method returns False the request
is interpreted as static file request. Methods can be registered
using the `add_TYPE_METHOD_mask` methods of QuickServer.
Parameters
----------
s... | python | def handle_special(self, send_body, method_str):
"""Handles a dynamic request. If this method returns False the request
is interpreted as static file request. Methods can be registered
using the `add_TYPE_METHOD_mask` methods of QuickServer.
Parameters
----------
s... | [
"def",
"handle_special",
"(",
"self",
",",
"send_body",
",",
"method_str",
")",
":",
"ongoing",
"=",
"True",
"if",
"self",
".",
"server",
".",
"report_slow_requests",
":",
"path",
"=",
"self",
".",
"path",
"def",
"do_report",
"(",
")",
":",
"if",
"not",
... | Handles a dynamic request. If this method returns False the request
is interpreted as static file request. Methods can be registered
using the `add_TYPE_METHOD_mask` methods of QuickServer.
Parameters
----------
send_body : bool
Whether to actually send the res... | [
"Handles",
"a",
"dynamic",
"request",
".",
"If",
"this",
"method",
"returns",
"False",
"the",
"request",
"is",
"interpreted",
"as",
"static",
"file",
"request",
".",
"Methods",
"can",
"be",
"registered",
"using",
"the",
"add_TYPE_METHOD_mask",
"methods",
"of",
... | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L635-L673 | train | Handles a special request. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServerRequestHandler.translate_path | def translate_path(self, orig_path):
"""Translates a path for a static file request. The server base path
could be different from our cwd.
Parameters
----------
path : string
The path.
Returns
-------
The absolute file path denoted by the ... | python | def translate_path(self, orig_path):
"""Translates a path for a static file request. The server base path
could be different from our cwd.
Parameters
----------
path : string
The path.
Returns
-------
The absolute file path denoted by the ... | [
"def",
"translate_path",
"(",
"self",
",",
"orig_path",
")",
":",
"init_path",
"=",
"orig_path",
"orig_path",
"=",
"urlparse",
".",
"urlparse",
"(",
"orig_path",
")",
"[",
"2",
"]",
"needs_redirect",
"=",
"False",
"is_folder",
"=",
"len",
"(",
"orig_path",
... | Translates a path for a static file request. The server base path
could be different from our cwd.
Parameters
----------
path : string
The path.
Returns
-------
The absolute file path denoted by the original path. | [
"Translates",
"a",
"path",
"for",
"a",
"static",
"file",
"request",
".",
"The",
"server",
"base",
"path",
"could",
"be",
"different",
"from",
"our",
"cwd",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L747-L876 | train | Translates a path for a static file request. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServerRequestHandler.check_cache | def check_cache(self, e_tag, match):
"""Checks the ETag and sends a cache match response if it matches."""
if e_tag != match:
return False
self.send_response(304)
self.send_header("ETag", e_tag)
self.send_header("Cache-Control",
"max-age={0}".... | python | def check_cache(self, e_tag, match):
"""Checks the ETag and sends a cache match response if it matches."""
if e_tag != match:
return False
self.send_response(304)
self.send_header("ETag", e_tag)
self.send_header("Cache-Control",
"max-age={0}".... | [
"def",
"check_cache",
"(",
"self",
",",
"e_tag",
",",
"match",
")",
":",
"if",
"e_tag",
"!=",
"match",
":",
"return",
"False",
"self",
".",
"send_response",
"(",
"304",
")",
"self",
".",
"send_header",
"(",
"\"ETag\"",
",",
"e_tag",
")",
"self",
".",
... | Checks the ETag and sends a cache match response if it matches. | [
"Checks",
"the",
"ETag",
"and",
"sends",
"a",
"cache",
"match",
"response",
"if",
"it",
"matches",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L878-L888 | train | Checks the ETag and sends a cache match response if it matches. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServerRequestHandler.handle_error | def handle_error(self):
"""Tries to send an 500 error after encountering an exception."""
if self.server.can_ignore_error(self):
return
if thread_local.status_code is None:
msg("ERROR: Cannot send error status code! " +
"Header already sent!\n{0}", traceba... | python | def handle_error(self):
"""Tries to send an 500 error after encountering an exception."""
if self.server.can_ignore_error(self):
return
if thread_local.status_code is None:
msg("ERROR: Cannot send error status code! " +
"Header already sent!\n{0}", traceba... | [
"def",
"handle_error",
"(",
"self",
")",
":",
"if",
"self",
".",
"server",
".",
"can_ignore_error",
"(",
"self",
")",
":",
"return",
"if",
"thread_local",
".",
"status_code",
"is",
"None",
":",
"msg",
"(",
"\"ERROR: Cannot send error status code! \"",
"+",
"\"... | Tries to send an 500 error after encountering an exception. | [
"Tries",
"to",
"send",
"an",
"500",
"error",
"after",
"encountering",
"an",
"exception",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L925-L941 | train | Tries to send an 500 error after encountering an exception. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServerRequestHandler.cross_origin_headers | def cross_origin_headers(self):
"""Sends cross origin headers."""
if not self.is_cross_origin():
return False
# we allow everything
self.send_header("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, HEAD")
allow_headers = _getheader(sel... | python | def cross_origin_headers(self):
"""Sends cross origin headers."""
if not self.is_cross_origin():
return False
# we allow everything
self.send_header("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, HEAD")
allow_headers = _getheader(sel... | [
"def",
"cross_origin_headers",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_cross_origin",
"(",
")",
":",
"return",
"False",
"# we allow everything",
"self",
".",
"send_header",
"(",
"\"Access-Control-Allow-Methods\"",
",",
"\"GET, POST, PUT, DELETE, HEAD\"",
... | Sends cross origin headers. | [
"Sends",
"cross",
"origin",
"headers",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L946-L959 | train | Sends cross origin headers. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServerRequestHandler.do_OPTIONS | def do_OPTIONS(self):
"""Handles an OPTIONS request."""
thread_local.clock_start = get_time()
thread_local.status_code = 200
thread_local.message = None
thread_local.headers = []
thread_local.end_headers = []
thread_local.size = -1
thread_local.method = 'O... | python | def do_OPTIONS(self):
"""Handles an OPTIONS request."""
thread_local.clock_start = get_time()
thread_local.status_code = 200
thread_local.message = None
thread_local.headers = []
thread_local.end_headers = []
thread_local.size = -1
thread_local.method = 'O... | [
"def",
"do_OPTIONS",
"(",
"self",
")",
":",
"thread_local",
".",
"clock_start",
"=",
"get_time",
"(",
")",
"thread_local",
".",
"status_code",
"=",
"200",
"thread_local",
".",
"message",
"=",
"None",
"thread_local",
".",
"headers",
"=",
"[",
"]",
"thread_loc... | Handles an OPTIONS request. | [
"Handles",
"an",
"OPTIONS",
"request",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L961-L978 | train | Handles an OPTIONS request. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServerRequestHandler.do_GET | def do_GET(self):
"""Handles a GET request."""
thread_local.clock_start = get_time()
thread_local.status_code = 200
thread_local.message = None
thread_local.headers = []
thread_local.end_headers = []
thread_local.size = -1
thread_local.method = 'GET'
... | python | def do_GET(self):
"""Handles a GET request."""
thread_local.clock_start = get_time()
thread_local.status_code = 200
thread_local.message = None
thread_local.headers = []
thread_local.end_headers = []
thread_local.size = -1
thread_local.method = 'GET'
... | [
"def",
"do_GET",
"(",
"self",
")",
":",
"thread_local",
".",
"clock_start",
"=",
"get_time",
"(",
")",
"thread_local",
".",
"status_code",
"=",
"200",
"thread_local",
".",
"message",
"=",
"None",
"thread_local",
".",
"headers",
"=",
"[",
"]",
"thread_local",... | Handles a GET request. | [
"Handles",
"a",
"GET",
"request",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1040-L1060 | train | Handles a GET request. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServerRequestHandler.log_message | def log_message(self, format, *args):
"""Logs a message. All messages get prefixed with '[SERVER]'
and the arguments act like `format`.
"""
clock_start = getattr(thread_local, 'clock_start', None)
thread_local.clock_start = None
timing = self.log_elapsed_time_string(
... | python | def log_message(self, format, *args):
"""Logs a message. All messages get prefixed with '[SERVER]'
and the arguments act like `format`.
"""
clock_start = getattr(thread_local, 'clock_start', None)
thread_local.clock_start = None
timing = self.log_elapsed_time_string(
... | [
"def",
"log_message",
"(",
"self",
",",
"format",
",",
"*",
"args",
")",
":",
"clock_start",
"=",
"getattr",
"(",
"thread_local",
",",
"'clock_start'",
",",
"None",
")",
"thread_local",
".",
"clock_start",
"=",
"None",
"timing",
"=",
"self",
".",
"log_elap... | Logs a message. All messages get prefixed with '[SERVER]'
and the arguments act like `format`. | [
"Logs",
"a",
"message",
".",
"All",
"messages",
"get",
"prefixed",
"with",
"[",
"SERVER",
"]",
"and",
"the",
"arguments",
"act",
"like",
"format",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1177-L1187 | train | Logs a message. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServerRequestHandler.log_request | def log_request(self, code='-', size='-'):
"""Logs the current request."""
print_size = getattr(thread_local, 'size', -1)
if size != '-':
size_str = ' (%s)' % size
elif print_size >= 0:
size_str = self.log_size_string(print_size) + ' '
else:
si... | python | def log_request(self, code='-', size='-'):
"""Logs the current request."""
print_size = getattr(thread_local, 'size', -1)
if size != '-':
size_str = ' (%s)' % size
elif print_size >= 0:
size_str = self.log_size_string(print_size) + ' '
else:
si... | [
"def",
"log_request",
"(",
"self",
",",
"code",
"=",
"'-'",
",",
"size",
"=",
"'-'",
")",
":",
"print_size",
"=",
"getattr",
"(",
"thread_local",
",",
"'size'",
",",
"-",
"1",
")",
"if",
"size",
"!=",
"'-'",
":",
"size_str",
"=",
"' (%s)'",
"%",
"s... | Logs the current request. | [
"Logs",
"the",
"current",
"request",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1189-L1202 | train | Logs the current request. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer._process_request | def _process_request(self, request, client_address):
"""Actually processes the request."""
try:
self.finish_request(request, client_address)
except Exception:
self.handle_error(request, client_address)
finally:
self.shutdown_request(request) | python | def _process_request(self, request, client_address):
"""Actually processes the request."""
try:
self.finish_request(request, client_address)
except Exception:
self.handle_error(request, client_address)
finally:
self.shutdown_request(request) | [
"def",
"_process_request",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"try",
":",
"self",
".",
"finish_request",
"(",
"request",
",",
"client_address",
")",
"except",
"Exception",
":",
"self",
".",
"handle_error",
"(",
"request",
",",
"cli... | Actually processes the request. | [
"Actually",
"processes",
"the",
"request",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1355-L1362 | train | Actually processes the request. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.process_request | def process_request(self, request, client_address):
"""Processes the request by delegating to `_process_request`."""
if not self._parallel:
self._process_request(request, client_address)
return
t = self._thread_factory(
target=self._process_request, args=(requ... | python | def process_request(self, request, client_address):
"""Processes the request by delegating to `_process_request`."""
if not self._parallel:
self._process_request(request, client_address)
return
t = self._thread_factory(
target=self._process_request, args=(requ... | [
"def",
"process_request",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"if",
"not",
"self",
".",
"_parallel",
":",
"self",
".",
"_process_request",
"(",
"request",
",",
"client_address",
")",
"return",
"t",
"=",
"self",
".",
"_thread_factory... | Processes the request by delegating to `_process_request`. | [
"Processes",
"the",
"request",
"by",
"delegating",
"to",
"_process_request",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1364-L1372 | train | Processes the request by delegating to _process_request. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.add_file_patterns | def add_file_patterns(self, patterns, blacklist):
"""Adds a list of file patterns to either the black- or white-list.
Note that this pattern is applied to the absolute path of the file
that will be delivered. For including or excluding folders use
`add_folder_mask` or `add_folde... | python | def add_file_patterns(self, patterns, blacklist):
"""Adds a list of file patterns to either the black- or white-list.
Note that this pattern is applied to the absolute path of the file
that will be delivered. For including or excluding folders use
`add_folder_mask` or `add_folde... | [
"def",
"add_file_patterns",
"(",
"self",
",",
"patterns",
",",
"blacklist",
")",
":",
"bl",
"=",
"self",
".",
"_pattern_black",
"if",
"blacklist",
"else",
"self",
".",
"_pattern_white",
"for",
"pattern",
"in",
"patterns",
":",
"bl",
".",
"append",
"(",
"pa... | Adds a list of file patterns to either the black- or white-list.
Note that this pattern is applied to the absolute path of the file
that will be delivered. For including or excluding folders use
`add_folder_mask` or `add_folder_fallback`. | [
"Adds",
"a",
"list",
"of",
"file",
"patterns",
"to",
"either",
"the",
"black",
"-",
"or",
"white",
"-",
"list",
".",
"Note",
"that",
"this",
"pattern",
"is",
"applied",
"to",
"the",
"absolute",
"path",
"of",
"the",
"file",
"that",
"will",
"be",
"delive... | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1376-L1384 | train | Adds a list of file patterns to either the black - list or white - list. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.bind_path | def bind_path(self, name, folder):
"""Adds a mask that maps to a given folder relative to `base_path`."""
if not len(name) or name[0] != '/' or name[-1] != '/':
raise ValueError(
"name must start and end with '/': {0}".format(name))
self._folder_masks.insert(0, (name,... | python | def bind_path(self, name, folder):
"""Adds a mask that maps to a given folder relative to `base_path`."""
if not len(name) or name[0] != '/' or name[-1] != '/':
raise ValueError(
"name must start and end with '/': {0}".format(name))
self._folder_masks.insert(0, (name,... | [
"def",
"bind_path",
"(",
"self",
",",
"name",
",",
"folder",
")",
":",
"if",
"not",
"len",
"(",
"name",
")",
"or",
"name",
"[",
"0",
"]",
"!=",
"'/'",
"or",
"name",
"[",
"-",
"1",
"]",
"!=",
"'/'",
":",
"raise",
"ValueError",
"(",
"\"name must st... | Adds a mask that maps to a given folder relative to `base_path`. | [
"Adds",
"a",
"mask",
"that",
"maps",
"to",
"a",
"given",
"folder",
"relative",
"to",
"base_path",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1412-L1417 | train | Adds a mask that maps to a given folder relative to base_path. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.bind_path_fallback | def bind_path_fallback(self, name, folder):
"""Adds a fallback for a given folder relative to `base_path`."""
if not len(name) or name[0] != '/' or name[-1] != '/':
raise ValueError(
"name must start and end with '/': {0}".format(name))
self._folder_masks.append((name... | python | def bind_path_fallback(self, name, folder):
"""Adds a fallback for a given folder relative to `base_path`."""
if not len(name) or name[0] != '/' or name[-1] != '/':
raise ValueError(
"name must start and end with '/': {0}".format(name))
self._folder_masks.append((name... | [
"def",
"bind_path_fallback",
"(",
"self",
",",
"name",
",",
"folder",
")",
":",
"if",
"not",
"len",
"(",
"name",
")",
"or",
"name",
"[",
"0",
"]",
"!=",
"'/'",
"or",
"name",
"[",
"-",
"1",
"]",
"!=",
"'/'",
":",
"raise",
"ValueError",
"(",
"\"nam... | Adds a fallback for a given folder relative to `base_path`. | [
"Adds",
"a",
"fallback",
"for",
"a",
"given",
"folder",
"relative",
"to",
"base_path",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1419-L1424 | train | Adds a fallback for a given folder relative to base_path. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.bind_proxy | def bind_proxy(self, name, proxy):
"""Adds a mask that maps to a given proxy."""
if not len(name) or name[0] != '/' or name[-1] != '/':
raise ValueError(
"name must start and end with '/': {0}".format(name))
self._folder_proxys.insert(0, (name, proxy)) | python | def bind_proxy(self, name, proxy):
"""Adds a mask that maps to a given proxy."""
if not len(name) or name[0] != '/' or name[-1] != '/':
raise ValueError(
"name must start and end with '/': {0}".format(name))
self._folder_proxys.insert(0, (name, proxy)) | [
"def",
"bind_proxy",
"(",
"self",
",",
"name",
",",
"proxy",
")",
":",
"if",
"not",
"len",
"(",
"name",
")",
"or",
"name",
"[",
"0",
"]",
"!=",
"'/'",
"or",
"name",
"[",
"-",
"1",
"]",
"!=",
"'/'",
":",
"raise",
"ValueError",
"(",
"\"name must st... | Adds a mask that maps to a given proxy. | [
"Adds",
"a",
"mask",
"that",
"maps",
"to",
"a",
"given",
"proxy",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1426-L1431 | train | Adds a mask that maps to a given proxy. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.add_cmd_method | def add_cmd_method(self, name, method, argc=None, complete=None):
"""Adds a command to the command line interface loop.
Parameters
----------
name : string
The command.
method : function(args)
The function to execute when this command is issued. The argu... | python | def add_cmd_method(self, name, method, argc=None, complete=None):
"""Adds a command to the command line interface loop.
Parameters
----------
name : string
The command.
method : function(args)
The function to execute when this command is issued. The argu... | [
"def",
"add_cmd_method",
"(",
"self",
",",
"name",
",",
"method",
",",
"argc",
"=",
"None",
",",
"complete",
"=",
"None",
")",
":",
"if",
"' '",
"in",
"name",
":",
"raise",
"ValueError",
"(",
"\"' ' cannot be in command name {0}\"",
".",
"format",
"(",
"na... | Adds a command to the command line interface loop.
Parameters
----------
name : string
The command.
method : function(args)
The function to execute when this command is issued. The argument
of the function is a list of space separated arguments to th... | [
"Adds",
"a",
"command",
"to",
"the",
"command",
"line",
"interface",
"loop",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1433-L1461 | train | Adds a command to the command line interface loop. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer._add_file_mask | def _add_file_mask(self, start, method_str, method):
"""Adds a raw file mask for dynamic requests.
Parameters
----------
start : string
The URL prefix that must be matched to perform this request.
method_str : string
The HTTP method for which to trigger ... | python | def _add_file_mask(self, start, method_str, method):
"""Adds a raw file mask for dynamic requests.
Parameters
----------
start : string
The URL prefix that must be matched to perform this request.
method_str : string
The HTTP method for which to trigger ... | [
"def",
"_add_file_mask",
"(",
"self",
",",
"start",
",",
"method_str",
",",
"method",
")",
":",
"fm",
"=",
"self",
".",
"_f_mask",
".",
"get",
"(",
"method_str",
",",
"[",
"]",
")",
"fm",
".",
"append",
"(",
"(",
"start",
",",
"method",
")",
")",
... | Adds a raw file mask for dynamic requests.
Parameters
----------
start : string
The URL prefix that must be matched to perform this request.
method_str : string
The HTTP method for which to trigger the request.
method : function(esrh, args)
... | [
"Adds",
"a",
"raw",
"file",
"mask",
"for",
"dynamic",
"requests",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1477-L1504 | train | Adds a raw file mask for dynamic requests. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.add_json_mask | def add_json_mask(self, start, method_str, json_producer):
"""Adds a handler that produces a JSON response.
Parameters
----------
start : string
The URL prefix that must be matched to perform this request.
method_str : string
The HTTP method for which to... | python | def add_json_mask(self, start, method_str, json_producer):
"""Adds a handler that produces a JSON response.
Parameters
----------
start : string
The URL prefix that must be matched to perform this request.
method_str : string
The HTTP method for which to... | [
"def",
"add_json_mask",
"(",
"self",
",",
"start",
",",
"method_str",
",",
"json_producer",
")",
":",
"def",
"send_json",
"(",
"drh",
",",
"rem_path",
")",
":",
"obj",
"=",
"json_producer",
"(",
"drh",
",",
"rem_path",
")",
"if",
"not",
"isinstance",
"("... | Adds a handler that produces a JSON response.
Parameters
----------
start : string
The URL prefix that must be matched to perform this request.
method_str : string
The HTTP method for which to trigger the request.
json_producer : function(esrh, args)
... | [
"Adds",
"a",
"handler",
"that",
"produces",
"a",
"JSON",
"response",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1506-L1566 | train | Adds a handler that produces a JSON response. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.add_text_mask | def add_text_mask(self, start, method_str, text_producer):
"""Adds a handler that produces a plain text response.
Parameters
----------
start : string
The URL prefix that must be matched to perform this request.
method_str : string
The HTTP method for wh... | python | def add_text_mask(self, start, method_str, text_producer):
"""Adds a handler that produces a plain text response.
Parameters
----------
start : string
The URL prefix that must be matched to perform this request.
method_str : string
The HTTP method for wh... | [
"def",
"add_text_mask",
"(",
"self",
",",
"start",
",",
"method_str",
",",
"text_producer",
")",
":",
"def",
"send_text",
"(",
"drh",
",",
"rem_path",
")",
":",
"text",
"=",
"text_producer",
"(",
"drh",
",",
"rem_path",
")",
"if",
"not",
"isinstance",
"(... | Adds a handler that produces a plain text response.
Parameters
----------
start : string
The URL prefix that must be matched to perform this request.
method_str : string
The HTTP method for which to trigger the request.
text_producer : function(esrh, ar... | [
"Adds",
"a",
"handler",
"that",
"produces",
"a",
"plain",
"text",
"response",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1644-L1703 | train | Adds a handler that produces a plain text response. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.add_special_file | def add_special_file(self, mask, path, from_quick_server, ctype=None):
"""Adds a special file that might have a different actual path than
its address.
Parameters
----------
mask : string
The URL that must be matched to perform this request.
path : string... | python | def add_special_file(self, mask, path, from_quick_server, ctype=None):
"""Adds a special file that might have a different actual path than
its address.
Parameters
----------
mask : string
The URL that must be matched to perform this request.
path : string... | [
"def",
"add_special_file",
"(",
"self",
",",
"mask",
",",
"path",
",",
"from_quick_server",
",",
"ctype",
"=",
"None",
")",
":",
"full_path",
"=",
"path",
"if",
"not",
"from_quick_server",
"else",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
... | Adds a special file that might have a different actual path than
its address.
Parameters
----------
mask : string
The URL that must be matched to perform this request.
path : string
The actual file path.
from_quick_server : bool
I... | [
"Adds",
"a",
"special",
"file",
"that",
"might",
"have",
"a",
"different",
"actual",
"path",
"than",
"its",
"address",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1846-L1873 | train | Adds a special file that might have a different actual path than the original path than the original path. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.mirror_file | def mirror_file(self, path_to, path_from, from_quick_server=True):
"""Mirrors a file to a different location. Each time the file changes
while the process is running it will be copied to 'path_to',
overwriting the destination.
Parameters
----------
path_to : string... | python | def mirror_file(self, path_to, path_from, from_quick_server=True):
"""Mirrors a file to a different location. Each time the file changes
while the process is running it will be copied to 'path_to',
overwriting the destination.
Parameters
----------
path_to : string... | [
"def",
"mirror_file",
"(",
"self",
",",
"path_to",
",",
"path_from",
",",
"from_quick_server",
"=",
"True",
")",
":",
"full_path",
"=",
"path_from",
"if",
"not",
"from_quick_server",
"else",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"d... | Mirrors a file to a different location. Each time the file changes
while the process is running it will be copied to 'path_to',
overwriting the destination.
Parameters
----------
path_to : string
The mirror destination.
path_from : string
T... | [
"Mirrors",
"a",
"file",
"to",
"a",
"different",
"location",
".",
"Each",
"time",
"the",
"file",
"changes",
"while",
"the",
"process",
"is",
"running",
"it",
"will",
"be",
"copied",
"to",
"path_to",
"overwriting",
"the",
"destination",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1875-L1904 | train | Mirrors a file to a different location. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.link_empty_favicon_fallback | def link_empty_favicon_fallback(self):
"""Links the empty favicon as default favicon."""
self.favicon_fallback = os.path.join(
os.path.dirname(__file__), 'favicon.ico') | python | def link_empty_favicon_fallback(self):
"""Links the empty favicon as default favicon."""
self.favicon_fallback = os.path.join(
os.path.dirname(__file__), 'favicon.ico') | [
"def",
"link_empty_favicon_fallback",
"(",
"self",
")",
":",
"self",
".",
"favicon_fallback",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'favicon.ico'",
")"
] | Links the empty favicon as default favicon. | [
"Links",
"the",
"empty",
"favicon",
"as",
"default",
"favicon",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L1980-L1983 | train | Links the empty favicon as default favicon. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.json_worker | def json_worker(self, mask, cache_id=None, cache_method="string",
cache_section="www"):
"""A function annotation that adds a worker request. A worker request
is a POST request that is computed asynchronously. That is, the
actual task is performed in a different thread a... | python | def json_worker(self, mask, cache_id=None, cache_method="string",
cache_section="www"):
"""A function annotation that adds a worker request. A worker request
is a POST request that is computed asynchronously. That is, the
actual task is performed in a different thread a... | [
"def",
"json_worker",
"(",
"self",
",",
"mask",
",",
"cache_id",
"=",
"None",
",",
"cache_method",
"=",
"\"string\"",
",",
"cache_section",
"=",
"\"www\"",
")",
":",
"use_cache",
"=",
"cache_id",
"is",
"not",
"None",
"def",
"wrapper",
"(",
"fun",
")",
":... | A function annotation that adds a worker request. A worker request
is a POST request that is computed asynchronously. That is, the
actual task is performed in a different thread and the network
request returns immediately. The client side uses polling to fetch
the result and ... | [
"A",
"function",
"annotation",
"that",
"adds",
"a",
"worker",
"request",
".",
"A",
"worker",
"request",
"is",
"a",
"POST",
"request",
"that",
"is",
"computed",
"asynchronously",
".",
"That",
"is",
"the",
"actual",
"task",
"is",
"performed",
"in",
"a",
"dif... | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L2033-L2343 | train | A worker function that adds a request to the network and returns the result. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.get_token_obj | def get_token_obj(self, token, expire=_token_default):
"""Returns or creates the object associaten with the given token.
Parameters
----------
token : string
The token for the object as returned by `create_token`.
expire : number or None
The number of se... | python | def get_token_obj(self, token, expire=_token_default):
"""Returns or creates the object associaten with the given token.
Parameters
----------
token : string
The token for the object as returned by `create_token`.
expire : number or None
The number of se... | [
"def",
"get_token_obj",
"(",
"self",
",",
"token",
",",
"expire",
"=",
"_token_default",
")",
":",
"if",
"expire",
"==",
"_token_default",
":",
"expire",
"=",
"self",
".",
"get_default_token_expiration",
"(",
")",
"now",
"=",
"get_time",
"(",
")",
"until",
... | Returns or creates the object associaten with the given token.
Parameters
----------
token : string
The token for the object as returned by `create_token`.
expire : number or None
The number of seconds until the object associated with the token
expir... | [
"Returns",
"or",
"creates",
"the",
"object",
"associaten",
"with",
"the",
"given",
"token",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L2356-L2409 | train | Returns or creates the object associated with the given token. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.handle_cmd | def handle_cmd(self, cmd):
"""Handles a single server command."""
cmd = cmd.strip()
segments = []
for s in cmd.split():
# remove bash-like comments
if s.startswith('#'):
break
# TODO implement escape sequences (also for \#)
... | python | def handle_cmd(self, cmd):
"""Handles a single server command."""
cmd = cmd.strip()
segments = []
for s in cmd.split():
# remove bash-like comments
if s.startswith('#'):
break
# TODO implement escape sequences (also for \#)
... | [
"def",
"handle_cmd",
"(",
"self",
",",
"cmd",
")",
":",
"cmd",
"=",
"cmd",
".",
"strip",
"(",
")",
"segments",
"=",
"[",
"]",
"for",
"s",
"in",
"cmd",
".",
"split",
"(",
")",
":",
"# remove bash-like comments",
"if",
"s",
".",
"startswith",
"(",
"'... | Handles a single server command. | [
"Handles",
"a",
"single",
"server",
"command",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L2514-L2558 | train | Handles a single server command. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.start_cmd_loop | def start_cmd_loop(self):
"""Starts the command line loop. This method is called automatically by
the serve_forever method. The function call is idempotent so you can
call the method before or after that without worrying or extra
side-effect. An EOF terminates the loop but does ... | python | def start_cmd_loop(self):
"""Starts the command line loop. This method is called automatically by
the serve_forever method. The function call is idempotent so you can
call the method before or after that without worrying or extra
side-effect. An EOF terminates the loop but does ... | [
"def",
"start_cmd_loop",
"(",
"self",
")",
":",
"# thread-safe check if the loop is already running",
"with",
"self",
".",
"_cmd_lock",
":",
"cmd_start",
"=",
"self",
".",
"_cmd_start",
"self",
".",
"_cmd_start",
"=",
"True",
"if",
"cmd_start",
":",
"return",
"cmd... | Starts the command line loop. This method is called automatically by
the serve_forever method. The function call is idempotent so you can
call the method before or after that without worrying or extra
side-effect. An EOF terminates the loop but does not close the
server. A `K... | [
"Starts",
"the",
"command",
"line",
"loop",
".",
"This",
"method",
"is",
"called",
"automatically",
"by",
"the",
"serve_forever",
"method",
".",
"The",
"function",
"call",
"is",
"idempotent",
"so",
"you",
"can",
"call",
"the",
"method",
"before",
"or",
"afte... | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L2560-L2714 | train | Starts the command line loop. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.handle_request | def handle_request(self):
"""Handles an HTTP request.The actual HTTP request is handled using a
different thread.
"""
timeout = self.socket.gettimeout()
if timeout is None:
timeout = self.timeout
elif self.timeout is not None:
timeout = min(time... | python | def handle_request(self):
"""Handles an HTTP request.The actual HTTP request is handled using a
different thread.
"""
timeout = self.socket.gettimeout()
if timeout is None:
timeout = self.timeout
elif self.timeout is not None:
timeout = min(time... | [
"def",
"handle_request",
"(",
"self",
")",
":",
"timeout",
"=",
"self",
".",
"socket",
".",
"gettimeout",
"(",
")",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"self",
".",
"timeout",
"elif",
"self",
".",
"timeout",
"is",
"not",
"None",
":",
... | Handles an HTTP request.The actual HTTP request is handled using a
different thread. | [
"Handles",
"an",
"HTTP",
"request",
".",
"The",
"actual",
"HTTP",
"request",
"is",
"handled",
"using",
"a",
"different",
"thread",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L2716-L2748 | train | Handles an HTTP request. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.serve_forever | def serve_forever(self):
"""Starts the server handling commands and HTTP requests.
The server will loop until done is True or a KeyboardInterrupt is
received.
"""
self.start_cmd_loop()
try:
while not self.done:
self.handle_request()
... | python | def serve_forever(self):
"""Starts the server handling commands and HTTP requests.
The server will loop until done is True or a KeyboardInterrupt is
received.
"""
self.start_cmd_loop()
try:
while not self.done:
self.handle_request()
... | [
"def",
"serve_forever",
"(",
"self",
")",
":",
"self",
".",
"start_cmd_loop",
"(",
")",
"try",
":",
"while",
"not",
"self",
".",
"done",
":",
"self",
".",
"handle_request",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"# clean error output if log file is STD_ER... | Starts the server handling commands and HTTP requests.
The server will loop until done is True or a KeyboardInterrupt is
received. | [
"Starts",
"the",
"server",
"handling",
"commands",
"and",
"HTTP",
"requests",
".",
"The",
"server",
"will",
"loop",
"until",
"done",
"is",
"True",
"or",
"a",
"KeyboardInterrupt",
"is",
"received",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L2750-L2766 | train | Starts the server handling commands and HTTP requests. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.can_ignore_error | def can_ignore_error(self, reqhnd=None):
"""Tests if the error is worth reporting.
"""
value = sys.exc_info()[1]
try:
if isinstance(value, BrokenPipeError) or \
isinstance(value, ConnectionResetError):
return True
except NameError:
... | python | def can_ignore_error(self, reqhnd=None):
"""Tests if the error is worth reporting.
"""
value = sys.exc_info()[1]
try:
if isinstance(value, BrokenPipeError) or \
isinstance(value, ConnectionResetError):
return True
except NameError:
... | [
"def",
"can_ignore_error",
"(",
"self",
",",
"reqhnd",
"=",
"None",
")",
":",
"value",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"try",
":",
"if",
"isinstance",
"(",
"value",
",",
"BrokenPipeError",
")",
"or",
"isinstance",
"(",
"value",
... | Tests if the error is worth reporting. | [
"Tests",
"if",
"the",
"error",
"is",
"worth",
"reporting",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L2768-L2785 | train | Tests if the error is worth reporting. |
JosuaKrause/quick_server | quick_server/quick_server.py | QuickServer.handle_error | def handle_error(self, request, client_address):
"""Handle an error gracefully.
"""
if self.can_ignore_error():
return
thread = threading.current_thread()
msg("Error in request ({0}): {1} in {2}\n{3}",
client_address, repr(request), thread.name, traceback.... | python | def handle_error(self, request, client_address):
"""Handle an error gracefully.
"""
if self.can_ignore_error():
return
thread = threading.current_thread()
msg("Error in request ({0}): {1} in {2}\n{3}",
client_address, repr(request), thread.name, traceback.... | [
"def",
"handle_error",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"if",
"self",
".",
"can_ignore_error",
"(",
")",
":",
"return",
"thread",
"=",
"threading",
".",
"current_thread",
"(",
")",
"msg",
"(",
"\"Error in request ({0}): {1} in {2}\\n... | Handle an error gracefully. | [
"Handle",
"an",
"error",
"gracefully",
"."
] | 55dc7c5fe726a341f8476f749fe0f9da156fc1cb | https://github.com/JosuaKrause/quick_server/blob/55dc7c5fe726a341f8476f749fe0f9da156fc1cb/quick_server/quick_server.py#L2787-L2794 | train | Handle an error gracefully. |
mgoral/subconvert | src/subconvert/gui/tools/Synchronizer.py | _findRow | def _findRow(subNo, model):
"""Finds a row in a given model which has a column with a given
number."""
items = model.findItems(str(subNo))
if len(items) == 0:
return None
if len(items) > 1:
raise IndexError("Too many items with sub number %s" % subNo)
return items[0].row() | python | def _findRow(subNo, model):
"""Finds a row in a given model which has a column with a given
number."""
items = model.findItems(str(subNo))
if len(items) == 0:
return None
if len(items) > 1:
raise IndexError("Too many items with sub number %s" % subNo)
return items[0].row() | [
"def",
"_findRow",
"(",
"subNo",
",",
"model",
")",
":",
"items",
"=",
"model",
".",
"findItems",
"(",
"str",
"(",
"subNo",
")",
")",
"if",
"len",
"(",
"items",
")",
"==",
"0",
":",
"return",
"None",
"if",
"len",
"(",
"items",
")",
">",
"1",
":... | Finds a row in a given model which has a column with a given
number. | [
"Finds",
"a",
"row",
"in",
"a",
"given",
"model",
"which",
"has",
"a",
"column",
"with",
"a",
"given",
"number",
"."
] | 59701e5e69ef1ca26ce7d1d766c936664aa2cb32 | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/gui/tools/Synchronizer.py#L317-L325 | train | Finds a row in a given model which has a column with a given
number. |
mgoral/subconvert | src/subconvert/gui/tools/Synchronizer.py | Synchronizer._subtitlesAdded | def _subtitlesAdded(self, path, subNos):
"""When subtitle is added, all syncPoints greater or equal than a new
subtitle are incremented."""
def action(current, count, model, row):
_setSubNo(current + count, model, row)
def count(current, nos):
ret = 0
... | python | def _subtitlesAdded(self, path, subNos):
"""When subtitle is added, all syncPoints greater or equal than a new
subtitle are incremented."""
def action(current, count, model, row):
_setSubNo(current + count, model, row)
def count(current, nos):
ret = 0
... | [
"def",
"_subtitlesAdded",
"(",
"self",
",",
"path",
",",
"subNos",
")",
":",
"def",
"action",
"(",
"current",
",",
"count",
",",
"model",
",",
"row",
")",
":",
"_setSubNo",
"(",
"current",
"+",
"count",
",",
"model",
",",
"row",
")",
"def",
"count",
... | When subtitle is added, all syncPoints greater or equal than a new
subtitle are incremented. | [
"When",
"subtitle",
"is",
"added",
"all",
"syncPoints",
"greater",
"or",
"equal",
"than",
"a",
"new",
"subtitle",
"are",
"incremented",
"."
] | 59701e5e69ef1ca26ce7d1d766c936664aa2cb32 | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/gui/tools/Synchronizer.py#L222-L238 | train | When subtitle is added all syncPoints greater than a new
are incremented. |
mgoral/subconvert | src/subconvert/gui/tools/Synchronizer.py | Synchronizer._subtitlesRemoved | def _subtitlesRemoved(self, path, subNos):
"""When subtitle is removed, all syncPoints greater than removed
subtitle are decremented. SyncPoint equal to removed subtitle is also
removed."""
def action(current, count, model, row):
if count.equal > 0:
model.remo... | python | def _subtitlesRemoved(self, path, subNos):
"""When subtitle is removed, all syncPoints greater than removed
subtitle are decremented. SyncPoint equal to removed subtitle is also
removed."""
def action(current, count, model, row):
if count.equal > 0:
model.remo... | [
"def",
"_subtitlesRemoved",
"(",
"self",
",",
"path",
",",
"subNos",
")",
":",
"def",
"action",
"(",
"current",
",",
"count",
",",
"model",
",",
"row",
")",
":",
"if",
"count",
".",
"equal",
">",
"0",
":",
"model",
".",
"removeRow",
"(",
"row",
")"... | When subtitle is removed, all syncPoints greater than removed
subtitle are decremented. SyncPoint equal to removed subtitle is also
removed. | [
"When",
"subtitle",
"is",
"removed",
"all",
"syncPoints",
"greater",
"than",
"removed",
"subtitle",
"are",
"decremented",
".",
"SyncPoint",
"equal",
"to",
"removed",
"subtitle",
"is",
"also",
"removed",
"."
] | 59701e5e69ef1ca26ce7d1d766c936664aa2cb32 | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/gui/tools/Synchronizer.py#L240-L253 | train | When subtitle is removed all syncPoints greater than removed
subtitle are decremented. SyncPoint equal to removed
subtitle is also removed. |
mgoral/subconvert | src/subconvert/gui/tools/Synchronizer.py | Synchronizer._changeSubNos | def _changeSubNos(self, path, subNos, count, action, reverse=False):
"""Implementation of subs add/removal handling.
Args:
path: file path associated with model on which work is done
subNos: list of added/removed subtitle numbers
count: function which accepts current... | python | def _changeSubNos(self, path, subNos, count, action, reverse=False):
"""Implementation of subs add/removal handling.
Args:
path: file path associated with model on which work is done
subNos: list of added/removed subtitle numbers
count: function which accepts current... | [
"def",
"_changeSubNos",
"(",
"self",
",",
"path",
",",
"subNos",
",",
"count",
",",
"action",
",",
"reverse",
"=",
"False",
")",
":",
"model",
"=",
"self",
".",
"_models",
".",
"get",
"(",
"path",
")",
"if",
"model",
"is",
"None",
":",
"return",
"s... | Implementation of subs add/removal handling.
Args:
path: file path associated with model on which work is done
subNos: list of added/removed subtitle numbers
count: function which accepts current sync point's subtitle number
and subNos and returns anything... | [
"Implementation",
"of",
"subs",
"add",
"/",
"removal",
"handling",
"."
] | 59701e5e69ef1ca26ce7d1d766c936664aa2cb32 | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/gui/tools/Synchronizer.py#L255-L281 | train | Implementation of subs add removal handling. |
mkoura/dump2polarion | dump2polarion/results/csvtools.py | _get_csv_fieldnames | def _get_csv_fieldnames(csv_reader):
"""Finds fieldnames in Polarion exported csv file."""
fieldnames = []
for row in csv_reader:
for col in row:
field = (
col.strip()
.replace('"', "")
.replace(" ", "")
.replace("(", "")
... | python | def _get_csv_fieldnames(csv_reader):
"""Finds fieldnames in Polarion exported csv file."""
fieldnames = []
for row in csv_reader:
for col in row:
field = (
col.strip()
.replace('"', "")
.replace(" ", "")
.replace("(", "")
... | [
"def",
"_get_csv_fieldnames",
"(",
"csv_reader",
")",
":",
"fieldnames",
"=",
"[",
"]",
"for",
"row",
"in",
"csv_reader",
":",
"for",
"col",
"in",
"row",
":",
"field",
"=",
"(",
"col",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"'\"'",
",",
"\"\"",... | Finds fieldnames in Polarion exported csv file. | [
"Finds",
"fieldnames",
"in",
"Polarion",
"exported",
"csv",
"file",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/results/csvtools.py#L18-L52 | train | Finds fieldnames in Polarion exported csv file. |
mkoura/dump2polarion | dump2polarion/results/csvtools.py | _get_results | def _get_results(csv_reader, fieldnames):
"""Maps data to fieldnames.
The reader needs to be at position after fieldnames, before the results data.
"""
fieldnames_count = len(fieldnames)
results = []
for row in csv_reader:
for col in row:
if col:
break
... | python | def _get_results(csv_reader, fieldnames):
"""Maps data to fieldnames.
The reader needs to be at position after fieldnames, before the results data.
"""
fieldnames_count = len(fieldnames)
results = []
for row in csv_reader:
for col in row:
if col:
break
... | [
"def",
"_get_results",
"(",
"csv_reader",
",",
"fieldnames",
")",
":",
"fieldnames_count",
"=",
"len",
"(",
"fieldnames",
")",
"results",
"=",
"[",
"]",
"for",
"row",
"in",
"csv_reader",
":",
"for",
"col",
"in",
"row",
":",
"if",
"col",
":",
"break",
"... | Maps data to fieldnames.
The reader needs to be at position after fieldnames, before the results data. | [
"Maps",
"data",
"to",
"fieldnames",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/results/csvtools.py#L83-L107 | train | Maps data to fieldnames.
|
mkoura/dump2polarion | dump2polarion/results/csvtools.py | _get_csv_reader | def _get_csv_reader(input_file):
"""Returns csv reader."""
dialect = csv.Sniffer().sniff(input_file.read(2048))
input_file.seek(0)
return csv_unicode.get_csv_reader(input_file, dialect) | python | def _get_csv_reader(input_file):
"""Returns csv reader."""
dialect = csv.Sniffer().sniff(input_file.read(2048))
input_file.seek(0)
return csv_unicode.get_csv_reader(input_file, dialect) | [
"def",
"_get_csv_reader",
"(",
"input_file",
")",
":",
"dialect",
"=",
"csv",
".",
"Sniffer",
"(",
")",
".",
"sniff",
"(",
"input_file",
".",
"read",
"(",
"2048",
")",
")",
"input_file",
".",
"seek",
"(",
"0",
")",
"return",
"csv_unicode",
".",
"get_cs... | Returns csv reader. | [
"Returns",
"csv",
"reader",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/results/csvtools.py#L110-L114 | train | Returns csv reader. |
mkoura/dump2polarion | dump2polarion/results/csvtools.py | get_imported_data | def get_imported_data(csv_file, **kwargs):
"""Reads the content of the Polarion exported csv file and returns imported data."""
open_args = []
open_kwargs = {}
try:
# pylint: disable=pointless-statement
unicode
open_args.append("rb")
except NameError:
open_kwargs["enc... | python | def get_imported_data(csv_file, **kwargs):
"""Reads the content of the Polarion exported csv file and returns imported data."""
open_args = []
open_kwargs = {}
try:
# pylint: disable=pointless-statement
unicode
open_args.append("rb")
except NameError:
open_kwargs["enc... | [
"def",
"get_imported_data",
"(",
"csv_file",
",",
"*",
"*",
"kwargs",
")",
":",
"open_args",
"=",
"[",
"]",
"open_kwargs",
"=",
"{",
"}",
"try",
":",
"# pylint: disable=pointless-statement",
"unicode",
"open_args",
".",
"append",
"(",
"\"rb\"",
")",
"except",
... | Reads the content of the Polarion exported csv file and returns imported data. | [
"Reads",
"the",
"content",
"of",
"the",
"Polarion",
"exported",
"csv",
"file",
"and",
"returns",
"imported",
"data",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/results/csvtools.py#L118-L143 | train | Reads the content of the Polarion exported csv file and returns imported data. |
mkoura/dump2polarion | dump2polarion/results/csvtools.py | import_csv | def import_csv(csv_file, **kwargs):
"""Imports data and checks that all required columns are there."""
records = get_imported_data(csv_file, **kwargs)
_check_required_columns(csv_file, records.results)
return records | python | def import_csv(csv_file, **kwargs):
"""Imports data and checks that all required columns are there."""
records = get_imported_data(csv_file, **kwargs)
_check_required_columns(csv_file, records.results)
return records | [
"def",
"import_csv",
"(",
"csv_file",
",",
"*",
"*",
"kwargs",
")",
":",
"records",
"=",
"get_imported_data",
"(",
"csv_file",
",",
"*",
"*",
"kwargs",
")",
"_check_required_columns",
"(",
"csv_file",
",",
"records",
".",
"results",
")",
"return",
"records"
... | Imports data and checks that all required columns are there. | [
"Imports",
"data",
"and",
"checks",
"that",
"all",
"required",
"columns",
"are",
"there",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/results/csvtools.py#L157-L161 | train | Imports data and checks that all required columns are there. |
noahbenson/pimms | pimms/__init__.py | reload_pimms | def reload_pimms():
'''
reload_pimms() reloads the entire pimms module and returns it.
'''
import sys, six
try: from importlib import reload
except: from imp import reload
reload(sys.modules['pimms.util'])
reload(sys.modules['pimms.table'])
reload(sys.modules['pimms.immutabl... | python | def reload_pimms():
'''
reload_pimms() reloads the entire pimms module and returns it.
'''
import sys, six
try: from importlib import reload
except: from imp import reload
reload(sys.modules['pimms.util'])
reload(sys.modules['pimms.table'])
reload(sys.modules['pimms.immutabl... | [
"def",
"reload_pimms",
"(",
")",
":",
"import",
"sys",
",",
"six",
"try",
":",
"from",
"importlib",
"import",
"reload",
"except",
":",
"from",
"imp",
"import",
"reload",
"reload",
"(",
"sys",
".",
"modules",
"[",
"'pimms.util'",
"]",
")",
"reload",
"(",
... | reload_pimms() reloads the entire pimms module and returns it. | [
"reload_pimms",
"()",
"reloads",
"the",
"entire",
"pimms",
"module",
"and",
"returns",
"it",
"."
] | 9051b86d6b858a7a13511b72c48dc21bc903dab2 | https://github.com/noahbenson/pimms/blob/9051b86d6b858a7a13511b72c48dc21bc903dab2/pimms/__init__.py#L144-L157 | train | reload_pimms reloads the entire pimms module and returns it. |
oemof/oemof.db | oemof/db/config.py | load_config | def load_config(filename):
"""
Load data from config file to `cfg` that can be accessed by get, set
afterwards.
Specify absolute or relative path to your config file.
:param filename: Relative or absolute path
:type filename: str
"""
if filename is None:
filename = ''
abs... | python | def load_config(filename):
"""
Load data from config file to `cfg` that can be accessed by get, set
afterwards.
Specify absolute or relative path to your config file.
:param filename: Relative or absolute path
:type filename: str
"""
if filename is None:
filename = ''
abs... | [
"def",
"load_config",
"(",
"filename",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"''",
"abs_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"filename",
")",
"global",
"FILE",
"# find the co... | Load data from config file to `cfg` that can be accessed by get, set
afterwards.
Specify absolute or relative path to your config file.
:param filename: Relative or absolute path
:type filename: str | [
"Load",
"data",
"from",
"config",
"file",
"to",
"cfg",
"that",
"can",
"be",
"accessed",
"by",
"get",
"set",
"afterwards",
"."
] | d51ac50187f03a875bd7ce5991ed4772e8b77b93 | https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/config.py#L48-L81 | train | Load data from config file to cfg that can be accessed by get set
afterwards. |
oemof/oemof.db | oemof/db/config.py | init | def init(FILE):
"""
Read config file
:param FILE: Absolute path to config file (incl. filename)
:type FILE: str
"""
try:
cfg.read(FILE)
global _loaded
_loaded = True
except:
file_not_found_message(FILE) | python | def init(FILE):
"""
Read config file
:param FILE: Absolute path to config file (incl. filename)
:type FILE: str
"""
try:
cfg.read(FILE)
global _loaded
_loaded = True
except:
file_not_found_message(FILE) | [
"def",
"init",
"(",
"FILE",
")",
":",
"try",
":",
"cfg",
".",
"read",
"(",
"FILE",
")",
"global",
"_loaded",
"_loaded",
"=",
"True",
"except",
":",
"file_not_found_message",
"(",
"FILE",
")"
] | Read config file
:param FILE: Absolute path to config file (incl. filename)
:type FILE: str | [
"Read",
"config",
"file"
] | d51ac50187f03a875bd7ce5991ed4772e8b77b93 | https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/config.py#L113-L125 | train | Read config file and initialize the object |
oemof/oemof.db | oemof/db/config.py | get | def get(section, key):
"""
returns the value of a given key of a given section of the main
config file.
:param section: the section.
:type section: str.
:param key: the key.
:type key: str.
:returns: the value which will be casted to float, int or boolean.
if no cast is successfull... | python | def get(section, key):
"""
returns the value of a given key of a given section of the main
config file.
:param section: the section.
:type section: str.
:param key: the key.
:type key: str.
:returns: the value which will be casted to float, int or boolean.
if no cast is successfull... | [
"def",
"get",
"(",
"section",
",",
"key",
")",
":",
"# FILE = 'config_misc'",
"if",
"not",
"_loaded",
":",
"init",
"(",
"FILE",
")",
"try",
":",
"return",
"cfg",
".",
"getfloat",
"(",
"section",
",",
"key",
")",
"except",
"Exception",
":",
"try",
":",
... | returns the value of a given key of a given section of the main
config file.
:param section: the section.
:type section: str.
:param key: the key.
:type key: str.
:returns: the value which will be casted to float, int or boolean.
if no cast is successfull, the raw string will be returned. | [
"returns",
"the",
"value",
"of",
"a",
"given",
"key",
"of",
"a",
"given",
"section",
"of",
"the",
"main",
"config",
"file",
"."
] | d51ac50187f03a875bd7ce5991ed4772e8b77b93 | https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/config.py#L128-L154 | train | returns the value of a given key of a given section of the main
config file. |
rehandalal/flask-funnel | flask_funnel/manager.py | bundle_assets | def bundle_assets():
"""Compress and minify assets"""
YUI_COMPRESSOR_BIN = current_app.config.get('YUI_COMPRESSOR_BIN')
path_to_jar = YUI_COMPRESSOR_BIN
tmp_files = []
def get_path(item):
"""Get the static path of an item"""
return os.path.join(current_app.static_folder, item)
... | python | def bundle_assets():
"""Compress and minify assets"""
YUI_COMPRESSOR_BIN = current_app.config.get('YUI_COMPRESSOR_BIN')
path_to_jar = YUI_COMPRESSOR_BIN
tmp_files = []
def get_path(item):
"""Get the static path of an item"""
return os.path.join(current_app.static_folder, item)
... | [
"def",
"bundle_assets",
"(",
")",
":",
"YUI_COMPRESSOR_BIN",
"=",
"current_app",
".",
"config",
".",
"get",
"(",
"'YUI_COMPRESSOR_BIN'",
")",
"path_to_jar",
"=",
"YUI_COMPRESSOR_BIN",
"tmp_files",
"=",
"[",
"]",
"def",
"get_path",
"(",
"item",
")",
":",
"\"\"\... | Compress and minify assets | [
"Compress",
"and",
"minify",
"assets"
] | b635cf52d1c9133c748aab7465edd7caef48e433 | https://github.com/rehandalal/flask-funnel/blob/b635cf52d1c9133c748aab7465edd7caef48e433/flask_funnel/manager.py#L19-L194 | train | Compress and minify assets for a single item |
praekeltfoundation/seed-message-sender | message_sender/serializers.py | InboundSerializer.to_internal_value | def to_internal_value(self, data):
"""
Adds extra data to the helper_metadata field.
"""
if "session_event" in data:
data["helper_metadata"]["session_event"] = data["session_event"]
return super(InboundSerializer, self).to_internal_value(data) | python | def to_internal_value(self, data):
"""
Adds extra data to the helper_metadata field.
"""
if "session_event" in data:
data["helper_metadata"]["session_event"] = data["session_event"]
return super(InboundSerializer, self).to_internal_value(data) | [
"def",
"to_internal_value",
"(",
"self",
",",
"data",
")",
":",
"if",
"\"session_event\"",
"in",
"data",
":",
"data",
"[",
"\"helper_metadata\"",
"]",
"[",
"\"session_event\"",
"]",
"=",
"data",
"[",
"\"session_event\"",
"]",
"return",
"super",
"(",
"InboundSe... | Adds extra data to the helper_metadata field. | [
"Adds",
"extra",
"data",
"to",
"the",
"helper_metadata",
"field",
"."
] | 257b01635171b9dbe1f5f13baa810c971bb2620e | https://github.com/praekeltfoundation/seed-message-sender/blob/257b01635171b9dbe1f5f13baa810c971bb2620e/message_sender/serializers.py#L97-L104 | train | Adds extra data to the helper_metadata field. |
mgoral/subconvert | src/subconvert/utils/Alias.py | acceptAlias | def acceptAlias(decoratedFunction):
"""This function should be used as a decorator. Each class method that is decorated will be able
to accept alias or original names as a first function positional parameter."""
def wrapper(self, *args, **kwargs):
SubAssert(isinstance(self, AliasBase))
if l... | python | def acceptAlias(decoratedFunction):
"""This function should be used as a decorator. Each class method that is decorated will be able
to accept alias or original names as a first function positional parameter."""
def wrapper(self, *args, **kwargs):
SubAssert(isinstance(self, AliasBase))
if l... | [
"def",
"acceptAlias",
"(",
"decoratedFunction",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"SubAssert",
"(",
"isinstance",
"(",
"self",
",",
"AliasBase",
")",
")",
"if",
"len",
"(",
"args",
")",
">",... | This function should be used as a decorator. Each class method that is decorated will be able
to accept alias or original names as a first function positional parameter. | [
"This",
"function",
"should",
"be",
"used",
"as",
"a",
"decorator",
".",
"Each",
"class",
"method",
"that",
"is",
"decorated",
"will",
"be",
"able",
"to",
"accept",
"alias",
"or",
"original",
"names",
"as",
"a",
"first",
"function",
"positional",
"parameter"... | 59701e5e69ef1ca26ce7d1d766c936664aa2cb32 | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/utils/Alias.py#L24-L36 | train | This is a decorator that can be used as a decorator. Each class method that is decorated will be able
to accept alias or original names as first function positional parameter. |
romanorac/discomll | discomll/ensemble/core/measures.py | nominal_splits | def nominal_splits(x, y, x_vals, y_dist, separate_max):
"""
Function uses heuristic to find best binary split of nominal values. Heuristic is described in (1) and it is
originally defined for binary classes. We extend it to work with multiple classes by comparing label with least
samples to others.
... | python | def nominal_splits(x, y, x_vals, y_dist, separate_max):
"""
Function uses heuristic to find best binary split of nominal values. Heuristic is described in (1) and it is
originally defined for binary classes. We extend it to work with multiple classes by comparing label with least
samples to others.
... | [
"def",
"nominal_splits",
"(",
"x",
",",
"y",
",",
"x_vals",
",",
"y_dist",
",",
"separate_max",
")",
":",
"# select a label with least samples",
"y_val",
"=",
"max",
"(",
"y_dist",
",",
"key",
"=",
"y_dist",
".",
"get",
")",
"if",
"separate_max",
"else",
"... | Function uses heuristic to find best binary split of nominal values. Heuristic is described in (1) and it is
originally defined for binary classes. We extend it to work with multiple classes by comparing label with least
samples to others.
x: numpy array - nominal feature
y: numpy array - label
x_v... | [
"Function",
"uses",
"heuristic",
"to",
"find",
"best",
"binary",
"split",
"of",
"nominal",
"values",
".",
"Heuristic",
"is",
"described",
"in",
"(",
"1",
")",
"and",
"it",
"is",
"originally",
"defined",
"for",
"binary",
"classes",
".",
"We",
"extend",
"it"... | a4703daffb2ba3c9f614bc3dbe45ae55884aea00 | https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/ensemble/core/measures.py#L24-L53 | train | Function uses heuristic to find best binary split of nominal values. |
romanorac/discomll | discomll/ensemble/core/measures.py | h | def h(values):
"""
Function calculates entropy.
values: list of integers
"""
ent = np.true_divide(values, np.sum(values))
return -np.sum(np.multiply(ent, np.log2(ent))) | python | def h(values):
"""
Function calculates entropy.
values: list of integers
"""
ent = np.true_divide(values, np.sum(values))
return -np.sum(np.multiply(ent, np.log2(ent))) | [
"def",
"h",
"(",
"values",
")",
":",
"ent",
"=",
"np",
".",
"true_divide",
"(",
"values",
",",
"np",
".",
"sum",
"(",
"values",
")",
")",
"return",
"-",
"np",
".",
"sum",
"(",
"np",
".",
"multiply",
"(",
"ent",
",",
"np",
".",
"log2",
"(",
"e... | Function calculates entropy.
values: list of integers | [
"Function",
"calculates",
"entropy",
"."
] | a4703daffb2ba3c9f614bc3dbe45ae55884aea00 | https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/ensemble/core/measures.py#L56-L63 | train | Function calculates entropy. |
romanorac/discomll | discomll/ensemble/core/measures.py | info_gain_nominal | def info_gain_nominal(x, y, separate_max):
"""
Function calculates information gain for discrete features. If feature is continuous it is firstly discretized.
x: numpy array - numerical or discrete feature
y: numpy array - labels
ft: string - feature type ("c" - continuous, "d" - discrete)
spli... | python | def info_gain_nominal(x, y, separate_max):
"""
Function calculates information gain for discrete features. If feature is continuous it is firstly discretized.
x: numpy array - numerical or discrete feature
y: numpy array - labels
ft: string - feature type ("c" - continuous, "d" - discrete)
spli... | [
"def",
"info_gain_nominal",
"(",
"x",
",",
"y",
",",
"separate_max",
")",
":",
"x_vals",
"=",
"np",
".",
"unique",
"(",
"x",
")",
"# unique values",
"if",
"len",
"(",
"x_vals",
")",
"<",
"3",
":",
"# if there is just one unique value",
"return",
"None",
"y... | Function calculates information gain for discrete features. If feature is continuous it is firstly discretized.
x: numpy array - numerical or discrete feature
y: numpy array - labels
ft: string - feature type ("c" - continuous, "d" - discrete)
split_fun: function - function for discretization of numeri... | [
"Function",
"calculates",
"information",
"gain",
"for",
"discrete",
"features",
".",
"If",
"feature",
"is",
"continuous",
"it",
"is",
"firstly",
"discretized",
"."
] | a4703daffb2ba3c9f614bc3dbe45ae55884aea00 | https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/ensemble/core/measures.py#L66-L109 | train | Function calculates information gain for discrete features. |
romanorac/discomll | discomll/ensemble/core/measures.py | multinomLog2 | def multinomLog2(selectors):
"""
Function calculates logarithm 2 of a kind of multinom.
selectors: list of integers
"""
ln2 = 0.69314718055994528622
noAll = sum(selectors)
lgNf = math.lgamma(noAll + 1.0) / ln2 # log2(N!)
lgnFac = []
for selector in selectors:
if selector ... | python | def multinomLog2(selectors):
"""
Function calculates logarithm 2 of a kind of multinom.
selectors: list of integers
"""
ln2 = 0.69314718055994528622
noAll = sum(selectors)
lgNf = math.lgamma(noAll + 1.0) / ln2 # log2(N!)
lgnFac = []
for selector in selectors:
if selector ... | [
"def",
"multinomLog2",
"(",
"selectors",
")",
":",
"ln2",
"=",
"0.69314718055994528622",
"noAll",
"=",
"sum",
"(",
"selectors",
")",
"lgNf",
"=",
"math",
".",
"lgamma",
"(",
"noAll",
"+",
"1.0",
")",
"/",
"ln2",
"# log2(N!)",
"lgnFac",
"=",
"[",
"]",
"... | Function calculates logarithm 2 of a kind of multinom.
selectors: list of integers | [
"Function",
"calculates",
"logarithm",
"2",
"of",
"a",
"kind",
"of",
"multinom",
"."
] | a4703daffb2ba3c9f614bc3dbe45ae55884aea00 | https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/ensemble/core/measures.py#L154-L175 | train | Function calculates logarithm 2 of a kind of multinom. |
romanorac/discomll | discomll/ensemble/core/measures.py | calc_mdl | def calc_mdl(yx_dist, y_dist):
"""
Function calculates mdl with given label distributions.
yx_dist: list of dictionaries - for every split it contains a dictionary with label distributions
y_dist: dictionary - all label distributions
Reference:
Igor Kononenko. On biases in estimating mult... | python | def calc_mdl(yx_dist, y_dist):
"""
Function calculates mdl with given label distributions.
yx_dist: list of dictionaries - for every split it contains a dictionary with label distributions
y_dist: dictionary - all label distributions
Reference:
Igor Kononenko. On biases in estimating mult... | [
"def",
"calc_mdl",
"(",
"yx_dist",
",",
"y_dist",
")",
":",
"prior",
"=",
"multinomLog2",
"(",
"y_dist",
".",
"values",
"(",
")",
")",
"prior",
"+=",
"multinomLog2",
"(",
"[",
"len",
"(",
"y_dist",
".",
"keys",
"(",
")",
")",
"-",
"1",
",",
"sum",
... | Function calculates mdl with given label distributions.
yx_dist: list of dictionaries - for every split it contains a dictionary with label distributions
y_dist: dictionary - all label distributions
Reference:
Igor Kononenko. On biases in estimating multi-valued attributes. In IJCAI, volume 95, p... | [
"Function",
"calculates",
"mdl",
"with",
"given",
"label",
"distributions",
"."
] | a4703daffb2ba3c9f614bc3dbe45ae55884aea00 | https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/ensemble/core/measures.py#L178-L195 | train | Function calculates mdl with given label distributions. |
romanorac/discomll | discomll/ensemble/core/measures.py | mdl_nominal | def mdl_nominal(x, y, separate_max):
"""
Function calculates minimum description length for discrete features. If feature is continuous it is firstly discretized.
x: numpy array - numerical or discrete feature
y: numpy array - labels
"""
x_vals = np.unique(x) # unique values
if len(x_vals)... | python | def mdl_nominal(x, y, separate_max):
"""
Function calculates minimum description length for discrete features. If feature is continuous it is firstly discretized.
x: numpy array - numerical or discrete feature
y: numpy array - labels
"""
x_vals = np.unique(x) # unique values
if len(x_vals)... | [
"def",
"mdl_nominal",
"(",
"x",
",",
"y",
",",
"separate_max",
")",
":",
"x_vals",
"=",
"np",
".",
"unique",
"(",
"x",
")",
"# unique values",
"if",
"len",
"(",
"x_vals",
")",
"==",
"1",
":",
"# if there is just one unique value",
"return",
"None",
"y_dist... | Function calculates minimum description length for discrete features. If feature is continuous it is firstly discretized.
x: numpy array - numerical or discrete feature
y: numpy array - labels | [
"Function",
"calculates",
"minimum",
"description",
"length",
"for",
"discrete",
"features",
".",
"If",
"feature",
"is",
"continuous",
"it",
"is",
"firstly",
"discretized",
"."
] | a4703daffb2ba3c9f614bc3dbe45ae55884aea00 | https://github.com/romanorac/discomll/blob/a4703daffb2ba3c9f614bc3dbe45ae55884aea00/discomll/ensemble/core/measures.py#L198-L233 | train | Function calculates minimum description length for discrete features. |
oemof/oemof.db | oemof/db/__init__.py | url | def url(section="postGIS", config_file=None):
""" Retrieve the URL used to connect to the database.
Use this if you have your own means of accessing the database and do not
want to use :func:`engine` or :func:`connection`.
Parameters
----------
section : str, optional
The `config.ini` ... | python | def url(section="postGIS", config_file=None):
""" Retrieve the URL used to connect to the database.
Use this if you have your own means of accessing the database and do not
want to use :func:`engine` or :func:`connection`.
Parameters
----------
section : str, optional
The `config.ini` ... | [
"def",
"url",
"(",
"section",
"=",
"\"postGIS\"",
",",
"config_file",
"=",
"None",
")",
":",
"cfg",
".",
"load_config",
"(",
"config_file",
")",
"try",
":",
"pw",
"=",
"keyring",
".",
"get_password",
"(",
"cfg",
".",
"get",
"(",
"section",
",",
"\"data... | Retrieve the URL used to connect to the database.
Use this if you have your own means of accessing the database and do not
want to use :func:`engine` or :func:`connection`.
Parameters
----------
section : str, optional
The `config.ini` section corresponding to the targeted database.
... | [
"Retrieve",
"the",
"URL",
"used",
"to",
"connect",
"to",
"the",
"database",
"."
] | d51ac50187f03a875bd7ce5991ed4772e8b77b93 | https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/__init__.py#L11-L73 | train | Retrieve the URL used to connect to the database. |
ResidentMario/pysocrata | pysocrata/pysocrata.py | get_endpoints_using_raw_json_emission | def get_endpoints_using_raw_json_emission(domain):
"""
Implements a raw HTTP GET against the entire Socrata portal for the domain in question. This method uses the
first of the two ways of getting this information, the raw JSON endpoint.
Parameters
----------
domain: str
A Socrata data ... | python | def get_endpoints_using_raw_json_emission(domain):
"""
Implements a raw HTTP GET against the entire Socrata portal for the domain in question. This method uses the
first of the two ways of getting this information, the raw JSON endpoint.
Parameters
----------
domain: str
A Socrata data ... | [
"def",
"get_endpoints_using_raw_json_emission",
"(",
"domain",
")",
":",
"uri",
"=",
"\"http://{0}/data.json\"",
".",
"format",
"(",
"domain",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"uri",
")",
"r",
".",
"raise_for_status",
"(",
")",
"return",
"r",
".",... | Implements a raw HTTP GET against the entire Socrata portal for the domain in question. This method uses the
first of the two ways of getting this information, the raw JSON endpoint.
Parameters
----------
domain: str
A Socrata data portal domain. "data.seattle.gov" or "data.cityofnewyork.us" fo... | [
"Implements",
"a",
"raw",
"HTTP",
"GET",
"against",
"the",
"entire",
"Socrata",
"portal",
"for",
"the",
"domain",
"in",
"question",
".",
"This",
"method",
"uses",
"the",
"first",
"of",
"the",
"two",
"ways",
"of",
"getting",
"this",
"information",
"the",
"r... | 78d31ed24f9966284043eee45acebd62aa67e5b1 | https://github.com/ResidentMario/pysocrata/blob/78d31ed24f9966284043eee45acebd62aa67e5b1/pysocrata/pysocrata.py#L31-L48 | train | This method uses a raw HTTP GET against the entire Socrata portal for the domain in question. |
ResidentMario/pysocrata | pysocrata/pysocrata.py | get_endpoints_using_catalog_api | def get_endpoints_using_catalog_api(domain, token):
"""
Implements a raw HTTP GET against the entire Socrata portal for the domain in question. This method uses the
second of the two ways of getting this information, the catalog API.
Parameters
----------
domain: str
A Socrata data port... | python | def get_endpoints_using_catalog_api(domain, token):
"""
Implements a raw HTTP GET against the entire Socrata portal for the domain in question. This method uses the
second of the two ways of getting this information, the catalog API.
Parameters
----------
domain: str
A Socrata data port... | [
"def",
"get_endpoints_using_catalog_api",
"(",
"domain",
",",
"token",
")",
":",
"# Token required for all requests. Providing login info instead is also possible but I didn't implement it.",
"headers",
"=",
"{",
"\"X-App-Token\"",
":",
"token",
"}",
"# The API will return only 100 r... | Implements a raw HTTP GET against the entire Socrata portal for the domain in question. This method uses the
second of the two ways of getting this information, the catalog API.
Parameters
----------
domain: str
A Socrata data portal domain. "data.seattle.gov" or "data.cityofnewyork.us" for exa... | [
"Implements",
"a",
"raw",
"HTTP",
"GET",
"against",
"the",
"entire",
"Socrata",
"portal",
"for",
"the",
"domain",
"in",
"question",
".",
"This",
"method",
"uses",
"the",
"second",
"of",
"the",
"two",
"ways",
"of",
"getting",
"this",
"information",
"the",
"... | 78d31ed24f9966284043eee45acebd62aa67e5b1 | https://github.com/ResidentMario/pysocrata/blob/78d31ed24f9966284043eee45acebd62aa67e5b1/pysocrata/pysocrata.py#L51-L108 | train | This method uses the HTTP GET against the entire Socrata portal for the domain in question and token. It uses the HTTP GET against the entire Socrata portal for the domain in question and token. |
ResidentMario/pysocrata | pysocrata/pysocrata.py | get_resources | def get_resources(domain, token):
"""
Returns a list of resources (data endpoints) on a Socrata domain.
The catalog API and JSON endpoint both return useful information, but the information that they return is useful
in slightly different ways. The JSON endpoint provides less information about the reso... | python | def get_resources(domain, token):
"""
Returns a list of resources (data endpoints) on a Socrata domain.
The catalog API and JSON endpoint both return useful information, but the information that they return is useful
in slightly different ways. The JSON endpoint provides less information about the reso... | [
"def",
"get_resources",
"(",
"domain",
",",
"token",
")",
":",
"json_endpoints",
"=",
"get_endpoints_using_raw_json_emission",
"(",
"domain",
")",
"catalog_api_output",
"=",
"get_endpoints_using_catalog_api",
"(",
"domain",
",",
"token",
")",
"catalog_endpoints",
"=",
... | Returns a list of resources (data endpoints) on a Socrata domain.
The catalog API and JSON endpoint both return useful information, but the information that they return is useful
in slightly different ways. The JSON endpoint provides less information about the resource in question,
including lacking a fiel... | [
"Returns",
"a",
"list",
"of",
"resources",
"(",
"data",
"endpoints",
")",
"on",
"a",
"Socrata",
"domain",
"."
] | 78d31ed24f9966284043eee45acebd62aa67e5b1 | https://github.com/ResidentMario/pysocrata/blob/78d31ed24f9966284043eee45acebd62aa67e5b1/pysocrata/pysocrata.py#L111-L159 | train | Returns a list of resources on a Socrata domain. |
ResidentMario/pysocrata | pysocrata/pysocrata.py | count_resources | def count_resources(domain, token):
"""
Given the domain in question, generates counts for that domain of each of the different data types.
Parameters
----------
domain: str
A Socrata data portal domain. "data.seattle.gov" or "data.cityofnewyork.us" for example.
token: str
A Soc... | python | def count_resources(domain, token):
"""
Given the domain in question, generates counts for that domain of each of the different data types.
Parameters
----------
domain: str
A Socrata data portal domain. "data.seattle.gov" or "data.cityofnewyork.us" for example.
token: str
A Soc... | [
"def",
"count_resources",
"(",
"domain",
",",
"token",
")",
":",
"resources",
"=",
"get_resources",
"(",
"domain",
",",
"token",
")",
"return",
"dict",
"(",
"Counter",
"(",
"[",
"r",
"[",
"'resource'",
"]",
"[",
"'type'",
"]",
"for",
"r",
"in",
"resour... | Given the domain in question, generates counts for that domain of each of the different data types.
Parameters
----------
domain: str
A Socrata data portal domain. "data.seattle.gov" or "data.cityofnewyork.us" for example.
token: str
A Socrata application token. Application tokens can b... | [
"Given",
"the",
"domain",
"in",
"question",
"generates",
"counts",
"for",
"that",
"domain",
"of",
"each",
"of",
"the",
"different",
"data",
"types",
"."
] | 78d31ed24f9966284043eee45acebd62aa67e5b1 | https://github.com/ResidentMario/pysocrata/blob/78d31ed24f9966284043eee45acebd62aa67e5b1/pysocrata/pysocrata.py#L162-L179 | train | Given a domain in question generates counts for each of the different endpoint types classifiable as published public datasets. |
ngmarchant/oasis | oasis/sawade.py | ImportanceSampler._sample_item | def _sample_item(self, **kwargs):
"""Sample an item from the pool according to the instrumental
distribution
"""
loc = np.random.choice(self._n_items, p = self._inst_pmf)
weight = (1/self._n_items)/self._inst_pmf[loc]
return loc, weight, {} | python | def _sample_item(self, **kwargs):
"""Sample an item from the pool according to the instrumental
distribution
"""
loc = np.random.choice(self._n_items, p = self._inst_pmf)
weight = (1/self._n_items)/self._inst_pmf[loc]
return loc, weight, {} | [
"def",
"_sample_item",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"loc",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"self",
".",
"_n_items",
",",
"p",
"=",
"self",
".",
"_inst_pmf",
")",
"weight",
"=",
"(",
"1",
"/",
"self",
".",
"_n_item... | Sample an item from the pool according to the instrumental
distribution | [
"Sample",
"an",
"item",
"from",
"the",
"pool",
"according",
"to",
"the",
"instrumental",
"distribution"
] | 28a037a8924b85ae97db8a93960a910a219d6a4a | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/sawade.py#L145-L151 | train | Sample an item from the pool according to the instrumental
distribution
|
ngmarchant/oasis | oasis/sawade.py | ImportanceSampler._calc_F_guess | def _calc_F_guess(self, alpha, predictions, probabilities):
"""Calculate an estimate of the F-measure based on the scores"""
num = np.sum(predictions.T * probabilities, axis=1)
den = np.sum((1 - alpha) * probabilities + \
alpha * predictions.T, axis=1)
F_guess = num/... | python | def _calc_F_guess(self, alpha, predictions, probabilities):
"""Calculate an estimate of the F-measure based on the scores"""
num = np.sum(predictions.T * probabilities, axis=1)
den = np.sum((1 - alpha) * probabilities + \
alpha * predictions.T, axis=1)
F_guess = num/... | [
"def",
"_calc_F_guess",
"(",
"self",
",",
"alpha",
",",
"predictions",
",",
"probabilities",
")",
":",
"num",
"=",
"np",
".",
"sum",
"(",
"predictions",
".",
"T",
"*",
"probabilities",
",",
"axis",
"=",
"1",
")",
"den",
"=",
"np",
".",
"sum",
"(",
... | Calculate an estimate of the F-measure based on the scores | [
"Calculate",
"an",
"estimate",
"of",
"the",
"F",
"-",
"measure",
"based",
"on",
"the",
"scores"
] | 28a037a8924b85ae97db8a93960a910a219d6a4a | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/sawade.py#L153-L161 | train | Calculate an estimate of the F - measure based on the scores |
ngmarchant/oasis | oasis/sawade.py | ImportanceSampler._initialise_pmf | def _initialise_pmf(self):
"""Calculate the epsilon-greedy instrumental distribution"""
# Easy vars
epsilon = self.epsilon
alpha = self.alpha
preds = self.predictions
p1 = self._probs_avg_opt_class
p0 = 1 - p1
n_items = self._n_items
F = self._F_gu... | python | def _initialise_pmf(self):
"""Calculate the epsilon-greedy instrumental distribution"""
# Easy vars
epsilon = self.epsilon
alpha = self.alpha
preds = self.predictions
p1 = self._probs_avg_opt_class
p0 = 1 - p1
n_items = self._n_items
F = self._F_gu... | [
"def",
"_initialise_pmf",
"(",
"self",
")",
":",
"# Easy vars",
"epsilon",
"=",
"self",
".",
"epsilon",
"alpha",
"=",
"self",
".",
"alpha",
"preds",
"=",
"self",
".",
"predictions",
"p1",
"=",
"self",
".",
"_probs_avg_opt_class",
"p0",
"=",
"1",
"-",
"p1... | Calculate the epsilon-greedy instrumental distribution | [
"Calculate",
"the",
"epsilon",
"-",
"greedy",
"instrumental",
"distribution"
] | 28a037a8924b85ae97db8a93960a910a219d6a4a | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/sawade.py#L163-L183 | train | Initialise the optimal instrumental distribution for the current class entry. |
iLampard/x-utils | xutils/date_utils/calendar.py | is_tradetime_now | def is_tradetime_now():
"""
判断目前是不是交易时间, 同时考虑节假日
:return: bool
"""
cal = Calendar('china.sse')
now_time = time.localtime()
today = Date(now_time[0], now_time[1], now_time[2])
if not cal.isBizDay(today):
return False
now = (now_time.tm_hour, now_time.tm_min, now_time.tm_sec)
... | python | def is_tradetime_now():
"""
判断目前是不是交易时间, 同时考虑节假日
:return: bool
"""
cal = Calendar('china.sse')
now_time = time.localtime()
today = Date(now_time[0], now_time[1], now_time[2])
if not cal.isBizDay(today):
return False
now = (now_time.tm_hour, now_time.tm_min, now_time.tm_sec)
... | [
"def",
"is_tradetime_now",
"(",
")",
":",
"cal",
"=",
"Calendar",
"(",
"'china.sse'",
")",
"now_time",
"=",
"time",
".",
"localtime",
"(",
")",
"today",
"=",
"Date",
"(",
"now_time",
"[",
"0",
"]",
",",
"now_time",
"[",
"1",
"]",
",",
"now_time",
"["... | 判断目前是不是交易时间, 同时考虑节假日
:return: bool | [
"判断目前是不是交易时间",
"同时考虑节假日",
":",
"return",
":",
"bool"
] | 291d92832ee0e0c89bc22e10ecf2f44445e0d300 | https://github.com/iLampard/x-utils/blob/291d92832ee0e0c89bc22e10ecf2f44445e0d300/xutils/date_utils/calendar.py#L683-L696 | train | Check if the current time is a tradetime. |
ngmarchant/oasis | oasis/stratification.py | stratify_by_features | def stratify_by_features(features, n_strata, **kwargs):
"""Stratify by clustering the items in feature space
Parameters
----------
features : array-like, shape=(n_items,n_features)
feature matrix for the pool, where rows correspond to items and columns
correspond to features.
n_str... | python | def stratify_by_features(features, n_strata, **kwargs):
"""Stratify by clustering the items in feature space
Parameters
----------
features : array-like, shape=(n_items,n_features)
feature matrix for the pool, where rows correspond to items and columns
correspond to features.
n_str... | [
"def",
"stratify_by_features",
"(",
"features",
",",
"n_strata",
",",
"*",
"*",
"kwargs",
")",
":",
"n_items",
"=",
"features",
".",
"shape",
"[",
"0",
"]",
"km",
"=",
"KMeans",
"(",
"n_clusters",
"=",
"n_strata",
",",
"*",
"*",
"kwargs",
")",
"allocat... | Stratify by clustering the items in feature space
Parameters
----------
features : array-like, shape=(n_items,n_features)
feature matrix for the pool, where rows correspond to items and columns
correspond to features.
n_strata : int
number of strata to create.
**kwargs :
... | [
"Stratify",
"by",
"clustering",
"the",
"items",
"in",
"feature",
"space"
] | 28a037a8924b85ae97db8a93960a910a219d6a4a | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/stratification.py#L7-L29 | train | Stratify by clustering the items in feature space. |
ngmarchant/oasis | oasis/stratification.py | _heuristic_bin_width | def _heuristic_bin_width(obs):
"""Optimal histogram bin width based on the Freedman-Diaconis rule"""
IQR = sp.percentile(obs, 75) - sp.percentile(obs, 25)
N = len(obs)
return 2*IQR*N**(-1/3) | python | def _heuristic_bin_width(obs):
"""Optimal histogram bin width based on the Freedman-Diaconis rule"""
IQR = sp.percentile(obs, 75) - sp.percentile(obs, 25)
N = len(obs)
return 2*IQR*N**(-1/3) | [
"def",
"_heuristic_bin_width",
"(",
"obs",
")",
":",
"IQR",
"=",
"sp",
".",
"percentile",
"(",
"obs",
",",
"75",
")",
"-",
"sp",
".",
"percentile",
"(",
"obs",
",",
"25",
")",
"N",
"=",
"len",
"(",
"obs",
")",
"return",
"2",
"*",
"IQR",
"*",
"N... | Optimal histogram bin width based on the Freedman-Diaconis rule | [
"Optimal",
"histogram",
"bin",
"width",
"based",
"on",
"the",
"Freedman",
"-",
"Diaconis",
"rule"
] | 28a037a8924b85ae97db8a93960a910a219d6a4a | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/stratification.py#L31-L35 | train | Optimal histogram bin width based on the Freedman - Diaconis rule |
ngmarchant/oasis | oasis/stratification.py | stratify_by_scores | def stratify_by_scores(scores, goal_n_strata='auto', method='cum_sqrt_F',
n_bins = 'auto'):
"""Stratify by binning the items based on their scores
Parameters
----------
scores : array-like, shape=(n_items,)
ordered array of scores which quantify the classifier confidence ... | python | def stratify_by_scores(scores, goal_n_strata='auto', method='cum_sqrt_F',
n_bins = 'auto'):
"""Stratify by binning the items based on their scores
Parameters
----------
scores : array-like, shape=(n_items,)
ordered array of scores which quantify the classifier confidence ... | [
"def",
"stratify_by_scores",
"(",
"scores",
",",
"goal_n_strata",
"=",
"'auto'",
",",
"method",
"=",
"'cum_sqrt_F'",
",",
"n_bins",
"=",
"'auto'",
")",
":",
"available_methods",
"=",
"[",
"'equal_size'",
",",
"'cum_sqrt_F'",
"]",
"if",
"method",
"not",
"in",
... | Stratify by binning the items based on their scores
Parameters
----------
scores : array-like, shape=(n_items,)
ordered array of scores which quantify the classifier confidence for
the items in the pool. High scores indicate a high confidence that
the true label is a "1" (and vice v... | [
"Stratify",
"by",
"binning",
"the",
"items",
"based",
"on",
"their",
"scores"
] | 28a037a8924b85ae97db8a93960a910a219d6a4a | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/stratification.py#L37-L150 | train | Stratify the items in the hierarchy based on their scores. |
ngmarchant/oasis | oasis/stratification.py | auto_stratify | def auto_stratify(scores, **kwargs):
"""Generate Strata instance automatically
Parameters
----------
scores : array-like, shape=(n_items,)
ordered array of scores which quantify the classifier confidence for
the items in the pool. High scores indicate a high confidence that
the ... | python | def auto_stratify(scores, **kwargs):
"""Generate Strata instance automatically
Parameters
----------
scores : array-like, shape=(n_items,)
ordered array of scores which quantify the classifier confidence for
the items in the pool. High scores indicate a high confidence that
the ... | [
"def",
"auto_stratify",
"(",
"scores",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'stratification_method'",
"in",
"kwargs",
":",
"method",
"=",
"kwargs",
"[",
"'stratification_method'",
"]",
"else",
":",
"method",
"=",
"'cum_sqrt_F'",
"if",
"'stratification_n_str... | Generate Strata instance automatically
Parameters
----------
scores : array-like, shape=(n_items,)
ordered array of scores which quantify the classifier confidence for
the items in the pool. High scores indicate a high confidence that
the true label is a "1" (and vice versa for labe... | [
"Generate",
"Strata",
"instance",
"automatically"
] | 28a037a8924b85ae97db8a93960a910a219d6a4a | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/stratification.py#L152-L184 | train | Generate a Strata instance automatically based on scores. |
ngmarchant/oasis | oasis/stratification.py | Strata._sample_stratum | def _sample_stratum(self, pmf=None, replace=True):
"""Sample a stratum
Parameters
----------
pmf : array-like, shape=(n_strata,), optional, default None
probability distribution to use when sampling from the strata. If
not given, use the stratum weights.
... | python | def _sample_stratum(self, pmf=None, replace=True):
"""Sample a stratum
Parameters
----------
pmf : array-like, shape=(n_strata,), optional, default None
probability distribution to use when sampling from the strata. If
not given, use the stratum weights.
... | [
"def",
"_sample_stratum",
"(",
"self",
",",
"pmf",
"=",
"None",
",",
"replace",
"=",
"True",
")",
":",
"if",
"pmf",
"is",
"None",
":",
"# Use weights",
"pmf",
"=",
"self",
".",
"weights_",
"if",
"not",
"replace",
":",
"# Find strata which have been fully sam... | Sample a stratum
Parameters
----------
pmf : array-like, shape=(n_strata,), optional, default None
probability distribution to use when sampling from the strata. If
not given, use the stratum weights.
replace : bool, optional, default True
whether to... | [
"Sample",
"a",
"stratum"
] | 28a037a8924b85ae97db8a93960a910a219d6a4a | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/stratification.py#L258-L289 | train | Sample a stratum from the strata. |
ngmarchant/oasis | oasis/stratification.py | Strata._sample_in_stratum | def _sample_in_stratum(self, stratum_idx, replace = True):
"""Sample an item uniformly from a stratum
Parameters
----------
stratum_idx : int
stratum index to sample from
replace : bool, optional, default True
whether to sample with replacement
... | python | def _sample_in_stratum(self, stratum_idx, replace = True):
"""Sample an item uniformly from a stratum
Parameters
----------
stratum_idx : int
stratum index to sample from
replace : bool, optional, default True
whether to sample with replacement
... | [
"def",
"_sample_in_stratum",
"(",
"self",
",",
"stratum_idx",
",",
"replace",
"=",
"True",
")",
":",
"if",
"replace",
":",
"stratum_loc",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"self",
".",
"sizes_",
"[",
"stratum_idx",
"]",
")",
"else",
":",
"#... | Sample an item uniformly from a stratum
Parameters
----------
stratum_idx : int
stratum index to sample from
replace : bool, optional, default True
whether to sample with replacement
Returns
-------
int
location of the random... | [
"Sample",
"an",
"item",
"uniformly",
"from",
"a",
"stratum"
] | 28a037a8924b85ae97db8a93960a910a219d6a4a | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/stratification.py#L291-L319 | train | Sample an item uniformly from a stratum. |
ngmarchant/oasis | oasis/stratification.py | Strata.sample | def sample(self, pmf=None, replace=True):
"""Sample an item from the strata
Parameters
----------
pmf : array-like, shape=(n_strata,), optional, default None
probability distribution to use when sampling from the strata. If
not given, use the stratum weights.
... | python | def sample(self, pmf=None, replace=True):
"""Sample an item from the strata
Parameters
----------
pmf : array-like, shape=(n_strata,), optional, default None
probability distribution to use when sampling from the strata. If
not given, use the stratum weights.
... | [
"def",
"sample",
"(",
"self",
",",
"pmf",
"=",
"None",
",",
"replace",
"=",
"True",
")",
":",
"stratum_idx",
"=",
"self",
".",
"_sample_stratum",
"(",
"pmf",
",",
"replace",
"=",
"replace",
")",
"loc",
"=",
"self",
".",
"_sample_in_stratum",
"(",
"stra... | Sample an item from the strata
Parameters
----------
pmf : array-like, shape=(n_strata,), optional, default None
probability distribution to use when sampling from the strata. If
not given, use the stratum weights.
replace : bool, optional, default True
... | [
"Sample",
"an",
"item",
"from",
"the",
"strata"
] | 28a037a8924b85ae97db8a93960a910a219d6a4a | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/stratification.py#L321-L343 | train | Sample an item from the strata and return the location and index of the sample in the stratum. |
ngmarchant/oasis | oasis/stratification.py | Strata.intra_mean | def intra_mean(self, values):
"""Calculate the mean of a quantity within strata
Parameters
----------
values : array-like, shape=(n_items,n_class)
array containing the values of the quantity for each item in the
pool
Returns
-------
numpy... | python | def intra_mean(self, values):
"""Calculate the mean of a quantity within strata
Parameters
----------
values : array-like, shape=(n_items,n_class)
array containing the values of the quantity for each item in the
pool
Returns
-------
numpy... | [
"def",
"intra_mean",
"(",
"self",
",",
"values",
")",
":",
"# TODO Check that quantity is valid",
"if",
"values",
".",
"ndim",
">",
"1",
":",
"return",
"np",
".",
"array",
"(",
"[",
"np",
".",
"mean",
"(",
"values",
"[",
"x",
",",
":",
"]",
",",
"axi... | Calculate the mean of a quantity within strata
Parameters
----------
values : array-like, shape=(n_items,n_class)
array containing the values of the quantity for each item in the
pool
Returns
-------
numpy.ndarray, shape=(n_strata,n_class)
... | [
"Calculate",
"the",
"mean",
"of",
"a",
"quantity",
"within",
"strata"
] | 28a037a8924b85ae97db8a93960a910a219d6a4a | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/stratification.py#L345-L363 | train | Calculate the mean of a quantity within a strata |
ngmarchant/oasis | oasis/stratification.py | Strata.reset | def reset(self):
"""Reset the instance to begin sampling from scratch"""
self._sampled = [np.repeat(False, x) for x in self.sizes_]
self._n_sampled = np.zeros(self.n_strata_, dtype=int) | python | def reset(self):
"""Reset the instance to begin sampling from scratch"""
self._sampled = [np.repeat(False, x) for x in self.sizes_]
self._n_sampled = np.zeros(self.n_strata_, dtype=int) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_sampled",
"=",
"[",
"np",
".",
"repeat",
"(",
"False",
",",
"x",
")",
"for",
"x",
"in",
"self",
".",
"sizes_",
"]",
"self",
".",
"_n_sampled",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"n_s... | Reset the instance to begin sampling from scratch | [
"Reset",
"the",
"instance",
"to",
"begin",
"sampling",
"from",
"scratch"
] | 28a037a8924b85ae97db8a93960a910a219d6a4a | https://github.com/ngmarchant/oasis/blob/28a037a8924b85ae97db8a93960a910a219d6a4a/oasis/stratification.py#L365-L368 | train | Reset the instance to begin sampling from scratch |
davidfokkema/artist | artist/simple_smooth.py | smooth | def smooth(x, y, degree=3):
"""Smooth y-values and return new x, y pair."""
if degree == 1:
return x, y
elif not isodd(degree):
raise ValueError("Degree must be an odd number")
else:
window_width = int(degree / 2)
data_size = len(y) - degree + 1
smoothed_y = np.... | python | def smooth(x, y, degree=3):
"""Smooth y-values and return new x, y pair."""
if degree == 1:
return x, y
elif not isodd(degree):
raise ValueError("Degree must be an odd number")
else:
window_width = int(degree / 2)
data_size = len(y) - degree + 1
smoothed_y = np.... | [
"def",
"smooth",
"(",
"x",
",",
"y",
",",
"degree",
"=",
"3",
")",
":",
"if",
"degree",
"==",
"1",
":",
"return",
"x",
",",
"y",
"elif",
"not",
"isodd",
"(",
"degree",
")",
":",
"raise",
"ValueError",
"(",
"\"Degree must be an odd number\"",
")",
"el... | Smooth y-values and return new x, y pair. | [
"Smooth",
"y",
"-",
"values",
"and",
"return",
"new",
"x",
"y",
"pair",
"."
] | 26ae7987522622710f2910980770c50012fda47d | https://github.com/davidfokkema/artist/blob/26ae7987522622710f2910980770c50012fda47d/artist/simple_smooth.py#L6-L24 | train | Smooth y - values and return new x y pair. |
ludeeus/GHLocalApi | examples/bluetooth_scan_network.py | bluetooth_scan | async def bluetooth_scan():
"""
Get devices from all GH units on the network.
This will scan the IPRANGE defined above for GH units.
Then do a multirun scan on each unit.
Compiling all devices from all units so you can see which unit has
the stronges signal to the device.
"""
devices = ... | python | async def bluetooth_scan():
"""
Get devices from all GH units on the network.
This will scan the IPRANGE defined above for GH units.
Then do a multirun scan on each unit.
Compiling all devices from all units so you can see which unit has
the stronges signal to the device.
"""
devices = ... | [
"async",
"def",
"bluetooth_scan",
"(",
")",
":",
"devices",
"=",
"{",
"}",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"ghlocalapi",
"=",
"NetworkScan",
"(",
"LOOP",
",",
"session",
")",
"result",
"=",
"await",
"ghlo... | Get devices from all GH units on the network.
This will scan the IPRANGE defined above for GH units.
Then do a multirun scan on each unit.
Compiling all devices from all units so you can see which unit has
the stronges signal to the device. | [
"Get",
"devices",
"from",
"all",
"GH",
"units",
"on",
"the",
"network",
"."
] | 93abdee299c4a4b65aa9dd03c77ec34e174e3c56 | https://github.com/ludeeus/GHLocalApi/blob/93abdee299c4a4b65aa9dd03c77ec34e174e3c56/examples/bluetooth_scan_network.py#L11-L45 | train | Scan for GH units on the network and return a list of all devices that have been added to the network. |
mkoura/dump2polarion | dump2polarion/verify.py | get_queue_obj | def get_queue_obj(session, queue_url, log_url):
"""Checks that all the data that is needed for submit verification is available."""
skip = False
if not queue_url:
logger.error("The queue url is not configured, skipping submit verification")
skip = True
if not session:
logger.err... | python | def get_queue_obj(session, queue_url, log_url):
"""Checks that all the data that is needed for submit verification is available."""
skip = False
if not queue_url:
logger.error("The queue url is not configured, skipping submit verification")
skip = True
if not session:
logger.err... | [
"def",
"get_queue_obj",
"(",
"session",
",",
"queue_url",
",",
"log_url",
")",
":",
"skip",
"=",
"False",
"if",
"not",
"queue_url",
":",
"logger",
".",
"error",
"(",
"\"The queue url is not configured, skipping submit verification\"",
")",
"skip",
"=",
"True",
"if... | Checks that all the data that is needed for submit verification is available. | [
"Checks",
"that",
"all",
"the",
"data",
"that",
"is",
"needed",
"for",
"submit",
"verification",
"is",
"available",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/verify.py#L176-L188 | train | Checks that all the data that is needed for submit verification is available. |
mkoura/dump2polarion | dump2polarion/verify.py | verify_submit | def verify_submit(
session, queue_url, log_url, job_ids, timeout=_DEFAULT_TIMEOUT, delay=_DEFAULT_DELAY, **kwargs
):
"""Verifies that the results were successfully submitted."""
verification_queue = get_queue_obj(session=session, queue_url=queue_url, log_url=log_url)
return verification_queue.verify_sub... | python | def verify_submit(
session, queue_url, log_url, job_ids, timeout=_DEFAULT_TIMEOUT, delay=_DEFAULT_DELAY, **kwargs
):
"""Verifies that the results were successfully submitted."""
verification_queue = get_queue_obj(session=session, queue_url=queue_url, log_url=log_url)
return verification_queue.verify_sub... | [
"def",
"verify_submit",
"(",
"session",
",",
"queue_url",
",",
"log_url",
",",
"job_ids",
",",
"timeout",
"=",
"_DEFAULT_TIMEOUT",
",",
"delay",
"=",
"_DEFAULT_DELAY",
",",
"*",
"*",
"kwargs",
")",
":",
"verification_queue",
"=",
"get_queue_obj",
"(",
"session... | Verifies that the results were successfully submitted. | [
"Verifies",
"that",
"the",
"results",
"were",
"successfully",
"submitted",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/verify.py#L192-L197 | train | Verifies that the results were successfully submitted. |
mkoura/dump2polarion | dump2polarion/verify.py | QueueSearch.download_queue | def download_queue(self, job_ids):
"""Downloads data of completed jobs."""
if self.skip:
return None
url = "{}?jobtype=completed&jobIds={}".format(
self.queue_url, ",".join(str(x) for x in job_ids)
)
try:
response = self.session.get(url, heade... | python | def download_queue(self, job_ids):
"""Downloads data of completed jobs."""
if self.skip:
return None
url = "{}?jobtype=completed&jobIds={}".format(
self.queue_url, ",".join(str(x) for x in job_ids)
)
try:
response = self.session.get(url, heade... | [
"def",
"download_queue",
"(",
"self",
",",
"job_ids",
")",
":",
"if",
"self",
".",
"skip",
":",
"return",
"None",
"url",
"=",
"\"{}?jobtype=completed&jobIds={}\"",
".",
"format",
"(",
"self",
".",
"queue_url",
",",
"\",\"",
".",
"join",
"(",
"str",
"(",
... | Downloads data of completed jobs. | [
"Downloads",
"data",
"of",
"completed",
"jobs",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/verify.py#L31-L50 | train | Downloads data of completed jobs. |
mkoura/dump2polarion | dump2polarion/verify.py | QueueSearch.find_jobs | def find_jobs(self, job_ids):
"""Finds the jobs in the completed job queue."""
matched_jobs = []
if self.skip:
return matched_jobs
json_data = self.download_queue(job_ids)
if not json_data:
return matched_jobs
jobs = json_data["jobs"]
for... | python | def find_jobs(self, job_ids):
"""Finds the jobs in the completed job queue."""
matched_jobs = []
if self.skip:
return matched_jobs
json_data = self.download_queue(job_ids)
if not json_data:
return matched_jobs
jobs = json_data["jobs"]
for... | [
"def",
"find_jobs",
"(",
"self",
",",
"job_ids",
")",
":",
"matched_jobs",
"=",
"[",
"]",
"if",
"self",
".",
"skip",
":",
"return",
"matched_jobs",
"json_data",
"=",
"self",
".",
"download_queue",
"(",
"job_ids",
")",
"if",
"not",
"json_data",
":",
"retu... | Finds the jobs in the completed job queue. | [
"Finds",
"the",
"jobs",
"in",
"the",
"completed",
"job",
"queue",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/verify.py#L52-L70 | train | Finds the jobs in the completed job queue. |
mkoura/dump2polarion | dump2polarion/verify.py | QueueSearch.wait_for_jobs | def wait_for_jobs(self, job_ids, timeout, delay):
"""Waits until the jobs appears in the completed job queue."""
if self.skip:
return
logger.debug("Waiting up to %d sec for completion of the job IDs %s", timeout, job_ids)
remaining_job_ids = set(job_ids)
found_jobs ... | python | def wait_for_jobs(self, job_ids, timeout, delay):
"""Waits until the jobs appears in the completed job queue."""
if self.skip:
return
logger.debug("Waiting up to %d sec for completion of the job IDs %s", timeout, job_ids)
remaining_job_ids = set(job_ids)
found_jobs ... | [
"def",
"wait_for_jobs",
"(",
"self",
",",
"job_ids",
",",
"timeout",
",",
"delay",
")",
":",
"if",
"self",
".",
"skip",
":",
"return",
"logger",
".",
"debug",
"(",
"\"Waiting up to %d sec for completion of the job IDs %s\"",
",",
"timeout",
",",
"job_ids",
")",
... | Waits until the jobs appears in the completed job queue. | [
"Waits",
"until",
"the",
"jobs",
"appears",
"in",
"the",
"completed",
"job",
"queue",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/verify.py#L73-L97 | train | Waits up to delay seconds for the jobs in the completed job queue. |
mkoura/dump2polarion | dump2polarion/verify.py | QueueSearch._check_outcome | def _check_outcome(self, jobs):
"""Parses returned messages and checks submit outcome."""
if self.skip:
return False
if not jobs:
logger.error("Import failed!")
return False
failed_jobs = []
for job in jobs:
status = job.get("stat... | python | def _check_outcome(self, jobs):
"""Parses returned messages and checks submit outcome."""
if self.skip:
return False
if not jobs:
logger.error("Import failed!")
return False
failed_jobs = []
for job in jobs:
status = job.get("stat... | [
"def",
"_check_outcome",
"(",
"self",
",",
"jobs",
")",
":",
"if",
"self",
".",
"skip",
":",
"return",
"False",
"if",
"not",
"jobs",
":",
"logger",
".",
"error",
"(",
"\"Import failed!\"",
")",
"return",
"False",
"failed_jobs",
"=",
"[",
"]",
"for",
"j... | Parses returned messages and checks submit outcome. | [
"Parses",
"returned",
"messages",
"and",
"checks",
"submit",
"outcome",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/verify.py#L99-L127 | train | Parses returned messages and checks submit outcome. |
mkoura/dump2polarion | dump2polarion/verify.py | QueueSearch._download_log | def _download_log(self, url, output_file):
"""Saves log returned by the message bus."""
logger.info("Saving log %s to %s", url, output_file)
def _do_log_download():
try:
return self.session.get(url)
# pylint: disable=broad-except
except Except... | python | def _download_log(self, url, output_file):
"""Saves log returned by the message bus."""
logger.info("Saving log %s to %s", url, output_file)
def _do_log_download():
try:
return self.session.get(url)
# pylint: disable=broad-except
except Except... | [
"def",
"_download_log",
"(",
"self",
",",
"url",
",",
"output_file",
")",
":",
"logger",
".",
"info",
"(",
"\"Saving log %s to %s\"",
",",
"url",
",",
"output_file",
")",
"def",
"_do_log_download",
"(",
")",
":",
"try",
":",
"return",
"self",
".",
"session... | Saves log returned by the message bus. | [
"Saves",
"log",
"returned",
"by",
"the",
"message",
"bus",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/verify.py#L129-L151 | train | Downloads log from the specified url and saves it to the specified file. |
mkoura/dump2polarion | dump2polarion/verify.py | QueueSearch.get_logs | def get_logs(self, jobs, log_file=None):
"""Get log or log url of the jobs."""
if not (jobs and self.log_url):
return
for job in jobs:
url = "{}?jobId={}".format(self.log_url, job.get("id"))
if log_file:
self._download_log("{}&download".format... | python | def get_logs(self, jobs, log_file=None):
"""Get log or log url of the jobs."""
if not (jobs and self.log_url):
return
for job in jobs:
url = "{}?jobId={}".format(self.log_url, job.get("id"))
if log_file:
self._download_log("{}&download".format... | [
"def",
"get_logs",
"(",
"self",
",",
"jobs",
",",
"log_file",
"=",
"None",
")",
":",
"if",
"not",
"(",
"jobs",
"and",
"self",
".",
"log_url",
")",
":",
"return",
"for",
"job",
"in",
"jobs",
":",
"url",
"=",
"\"{}?jobId={}\"",
".",
"format",
"(",
"s... | Get log or log url of the jobs. | [
"Get",
"log",
"or",
"log",
"url",
"of",
"the",
"jobs",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/verify.py#L153-L163 | train | Get log url of the jobs. |
mkoura/dump2polarion | dump2polarion/verify.py | QueueSearch.verify_submit | def verify_submit(self, job_ids, timeout, delay, **kwargs):
"""Verifies that the results were successfully submitted."""
if self.skip:
return False
jobs = self.wait_for_jobs(job_ids, timeout, delay)
self.get_logs(jobs, log_file=kwargs.get("log_file"))
return self._c... | python | def verify_submit(self, job_ids, timeout, delay, **kwargs):
"""Verifies that the results were successfully submitted."""
if self.skip:
return False
jobs = self.wait_for_jobs(job_ids, timeout, delay)
self.get_logs(jobs, log_file=kwargs.get("log_file"))
return self._c... | [
"def",
"verify_submit",
"(",
"self",
",",
"job_ids",
",",
"timeout",
",",
"delay",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"skip",
":",
"return",
"False",
"jobs",
"=",
"self",
".",
"wait_for_jobs",
"(",
"job_ids",
",",
"timeout",
",",
"... | Verifies that the results were successfully submitted. | [
"Verifies",
"that",
"the",
"results",
"were",
"successfully",
"submitted",
"."
] | f4bd24e9d5070e282aad15f1e8bb514c0525cd37 | https://github.com/mkoura/dump2polarion/blob/f4bd24e9d5070e282aad15f1e8bb514c0525cd37/dump2polarion/verify.py#L165-L173 | train | Verifies that the results were successfully submitted. |
Genida/dependenpy | src/dependenpy/node.py | RootNode.submodules | def submodules(self):
"""
Property to return all sub-modules of the node, recursively.
Returns:
list of Module: the sub-modules.
"""
submodules = []
submodules.extend(self.modules)
for p in self.packages:
submodules.extend(p.submodules)
... | python | def submodules(self):
"""
Property to return all sub-modules of the node, recursively.
Returns:
list of Module: the sub-modules.
"""
submodules = []
submodules.extend(self.modules)
for p in self.packages:
submodules.extend(p.submodules)
... | [
"def",
"submodules",
"(",
"self",
")",
":",
"submodules",
"=",
"[",
"]",
"submodules",
".",
"extend",
"(",
"self",
".",
"modules",
")",
"for",
"p",
"in",
"self",
".",
"packages",
":",
"submodules",
".",
"extend",
"(",
"p",
".",
"submodules",
")",
"re... | Property to return all sub-modules of the node, recursively.
Returns:
list of Module: the sub-modules. | [
"Property",
"to",
"return",
"all",
"sub",
"-",
"modules",
"of",
"the",
"node",
"recursively",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L112-L123 | train | Property to return all sub - modules of the node recursively. |
Genida/dependenpy | src/dependenpy/node.py | RootNode._contains | def _contains(self, item):
"""
Whether given item is contained inside the node modules/packages.
Args:
item (Package/Module): a package or module.
Returns:
bool: True if self is item or item in self's packages/modules.
"""
if self is item:
... | python | def _contains(self, item):
"""
Whether given item is contained inside the node modules/packages.
Args:
item (Package/Module): a package or module.
Returns:
bool: True if self is item or item in self's packages/modules.
"""
if self is item:
... | [
"def",
"_contains",
"(",
"self",
",",
"item",
")",
":",
"if",
"self",
"is",
"item",
":",
"return",
"True",
"for",
"m",
"in",
"self",
".",
"modules",
":",
"if",
"item",
"in",
"m",
":",
"return",
"True",
"for",
"p",
"in",
"self",
".",
"packages",
"... | Whether given item is contained inside the node modules/packages.
Args:
item (Package/Module): a package or module.
Returns:
bool: True if self is item or item in self's packages/modules. | [
"Whether",
"given",
"item",
"is",
"contained",
"inside",
"the",
"node",
"modules",
"/",
"packages",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L129-L147 | train | Returns True if given item is contained inside the node modules or packages. |
Genida/dependenpy | src/dependenpy/node.py | RootNode.get | def get(self, item):
"""
Get item through ``__getitem__`` and cache the result.
Args:
item (str): name of package or module.
Returns:
Package/Module: the corresponding object.
"""
if item not in self._item_cache:
try:
... | python | def get(self, item):
"""
Get item through ``__getitem__`` and cache the result.
Args:
item (str): name of package or module.
Returns:
Package/Module: the corresponding object.
"""
if item not in self._item_cache:
try:
... | [
"def",
"get",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
"not",
"in",
"self",
".",
"_item_cache",
":",
"try",
":",
"item",
"=",
"self",
".",
"__getitem__",
"(",
"item",
")",
"except",
"KeyError",
":",
"item",
"=",
"None",
"self",
".",
"_item... | Get item through ``__getitem__`` and cache the result.
Args:
item (str): name of package or module.
Returns:
Package/Module: the corresponding object. | [
"Get",
"item",
"through",
"__getitem__",
"and",
"cache",
"the",
"result",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L149-L165 | train | Get item through the __getitem__ and cache the result. |
Genida/dependenpy | src/dependenpy/node.py | RootNode.get_target | def get_target(self, target):
"""
Get the result of _get_target, cache it and return it.
Args:
target (str): target to find.
Returns:
Package/Module: package containing target or corresponding module.
"""
if target not in self._target_cache:
... | python | def get_target(self, target):
"""
Get the result of _get_target, cache it and return it.
Args:
target (str): target to find.
Returns:
Package/Module: package containing target or corresponding module.
"""
if target not in self._target_cache:
... | [
"def",
"get_target",
"(",
"self",
",",
"target",
")",
":",
"if",
"target",
"not",
"in",
"self",
".",
"_target_cache",
":",
"self",
".",
"_target_cache",
"[",
"target",
"]",
"=",
"self",
".",
"_get_target",
"(",
"target",
")",
"return",
"self",
".",
"_t... | Get the result of _get_target, cache it and return it.
Args:
target (str): target to find.
Returns:
Package/Module: package containing target or corresponding module. | [
"Get",
"the",
"result",
"of",
"_get_target",
"cache",
"it",
"and",
"return",
"it",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L167-L179 | train | Get the result of _get_target cache it and return it. |
Genida/dependenpy | src/dependenpy/node.py | RootNode._get_target | def _get_target(self, target):
"""
Get the Package or Module related to given target.
Args:
target (str): target to find.
Returns:
Package/Module: package containing target or corresponding module.
"""
depth = target.count('.') + 1
parts ... | python | def _get_target(self, target):
"""
Get the Package or Module related to given target.
Args:
target (str): target to find.
Returns:
Package/Module: package containing target or corresponding module.
"""
depth = target.count('.') + 1
parts ... | [
"def",
"_get_target",
"(",
"self",
",",
"target",
")",
":",
"depth",
"=",
"target",
".",
"count",
"(",
"'.'",
")",
"+",
"1",
"parts",
"=",
"target",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"for",
"m",
"in",
"self",
".",
"modules",
":",
"if",
"... | Get the Package or Module related to given target.
Args:
target (str): target to find.
Returns:
Package/Module: package containing target or corresponding module. | [
"Get",
"the",
"Package",
"or",
"Module",
"related",
"to",
"given",
"target",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L181-L213 | train | Get the Package or Module related to a given target. |
Genida/dependenpy | src/dependenpy/node.py | RootNode.build_dependencies | def build_dependencies(self):
"""
Recursively build the dependencies for sub-modules and sub-packages.
Iterate on node's modules then packages and call their
build_dependencies methods.
"""
for m in self.modules:
m.build_dependencies()
for p in self.p... | python | def build_dependencies(self):
"""
Recursively build the dependencies for sub-modules and sub-packages.
Iterate on node's modules then packages and call their
build_dependencies methods.
"""
for m in self.modules:
m.build_dependencies()
for p in self.p... | [
"def",
"build_dependencies",
"(",
"self",
")",
":",
"for",
"m",
"in",
"self",
".",
"modules",
":",
"m",
".",
"build_dependencies",
"(",
")",
"for",
"p",
"in",
"self",
".",
"packages",
":",
"p",
".",
"build_dependencies",
"(",
")"
] | Recursively build the dependencies for sub-modules and sub-packages.
Iterate on node's modules then packages and call their
build_dependencies methods. | [
"Recursively",
"build",
"the",
"dependencies",
"for",
"sub",
"-",
"modules",
"and",
"sub",
"-",
"packages",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L215-L225 | train | Recursively build the dependencies for modules and packages. |
Genida/dependenpy | src/dependenpy/node.py | RootNode.print_graph | def print_graph(self, format=None, output=sys.stdout, depth=0, **kwargs):
"""
Print the graph for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
depth (int): depth of the graph.
"... | python | def print_graph(self, format=None, output=sys.stdout, depth=0, **kwargs):
"""
Print the graph for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
depth (int): depth of the graph.
"... | [
"def",
"print_graph",
"(",
"self",
",",
"format",
"=",
"None",
",",
"output",
"=",
"sys",
".",
"stdout",
",",
"depth",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"graph",
"=",
"self",
".",
"as_graph",
"(",
"depth",
"=",
"depth",
")",
"graph",
"... | Print the graph for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
depth (int): depth of the graph. | [
"Print",
"the",
"graph",
"for",
"self",
"s",
"nodes",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L227-L237 | train | Print the graph of the node s nodes. |
Genida/dependenpy | src/dependenpy/node.py | RootNode.print_matrix | def print_matrix(self, format=None, output=sys.stdout, depth=0, **kwargs):
"""
Print the matrix for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
depth (int): depth of the matrix.
... | python | def print_matrix(self, format=None, output=sys.stdout, depth=0, **kwargs):
"""
Print the matrix for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
depth (int): depth of the matrix.
... | [
"def",
"print_matrix",
"(",
"self",
",",
"format",
"=",
"None",
",",
"output",
"=",
"sys",
".",
"stdout",
",",
"depth",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"matrix",
"=",
"self",
".",
"as_matrix",
"(",
"depth",
"=",
"depth",
")",
"matrix",... | Print the matrix for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
depth (int): depth of the matrix. | [
"Print",
"the",
"matrix",
"for",
"self",
"s",
"nodes",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L239-L249 | train | Print the matrix for this node. |
Genida/dependenpy | src/dependenpy/node.py | RootNode.print_treemap | def print_treemap(self, format=None, output=sys.stdout, **kwargs):
"""
Print the matrix for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
"""
treemap = self.as_treemap()
tree... | python | def print_treemap(self, format=None, output=sys.stdout, **kwargs):
"""
Print the matrix for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write.
"""
treemap = self.as_treemap()
tree... | [
"def",
"print_treemap",
"(",
"self",
",",
"format",
"=",
"None",
",",
"output",
"=",
"sys",
".",
"stdout",
",",
"*",
"*",
"kwargs",
")",
":",
"treemap",
"=",
"self",
".",
"as_treemap",
"(",
")",
"treemap",
".",
"print",
"(",
"format",
"=",
"format",
... | Print the matrix for self's nodes.
Args:
format (str): output format (csv, json or text).
output (file): file descriptor on which to write. | [
"Print",
"the",
"matrix",
"for",
"self",
"s",
"nodes",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L251-L260 | train | Print the matrix for this node. |
Genida/dependenpy | src/dependenpy/node.py | RootNode.as_dict | def as_dict(self):
"""
Return the dependencies as a dictionary.
Returns:
dict: dictionary of dependencies.
"""
return {
'name': str(self),
'modules': [m.as_dict() for m in self.modules],
'packages': [p.as_dict() for p in self.packa... | python | def as_dict(self):
"""
Return the dependencies as a dictionary.
Returns:
dict: dictionary of dependencies.
"""
return {
'name': str(self),
'modules': [m.as_dict() for m in self.modules],
'packages': [p.as_dict() for p in self.packa... | [
"def",
"as_dict",
"(",
"self",
")",
":",
"return",
"{",
"'name'",
":",
"str",
"(",
"self",
")",
",",
"'modules'",
":",
"[",
"m",
".",
"as_dict",
"(",
")",
"for",
"m",
"in",
"self",
".",
"modules",
"]",
",",
"'packages'",
":",
"[",
"p",
".",
"as... | Return the dependencies as a dictionary.
Returns:
dict: dictionary of dependencies. | [
"Return",
"the",
"dependencies",
"as",
"a",
"dictionary",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L287-L298 | train | Return the dependencies as a dictionary. |
Genida/dependenpy | src/dependenpy/node.py | RootNode.as_graph | def as_graph(self, depth=0):
"""
Create a graph with self as node, cache it, return it.
Args:
depth (int): depth of the graph.
Returns:
Graph: an instance of Graph.
"""
if depth in self._graph_cache:
return self._graph_cache[depth]
... | python | def as_graph(self, depth=0):
"""
Create a graph with self as node, cache it, return it.
Args:
depth (int): depth of the graph.
Returns:
Graph: an instance of Graph.
"""
if depth in self._graph_cache:
return self._graph_cache[depth]
... | [
"def",
"as_graph",
"(",
"self",
",",
"depth",
"=",
"0",
")",
":",
"if",
"depth",
"in",
"self",
".",
"_graph_cache",
":",
"return",
"self",
".",
"_graph_cache",
"[",
"depth",
"]",
"self",
".",
"_graph_cache",
"[",
"depth",
"]",
"=",
"graph",
"=",
"Gra... | Create a graph with self as node, cache it, return it.
Args:
depth (int): depth of the graph.
Returns:
Graph: an instance of Graph. | [
"Create",
"a",
"graph",
"with",
"self",
"as",
"node",
"cache",
"it",
"return",
"it",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L300-L313 | train | Create a graph with self as node cache it and return it. |
Genida/dependenpy | src/dependenpy/node.py | RootNode.as_matrix | def as_matrix(self, depth=0):
"""
Create a matrix with self as node, cache it, return it.
Args:
depth (int): depth of the matrix.
Returns:
Matrix: an instance of Matrix.
"""
if depth in self._matrix_cache:
return self._matrix_cache[de... | python | def as_matrix(self, depth=0):
"""
Create a matrix with self as node, cache it, return it.
Args:
depth (int): depth of the matrix.
Returns:
Matrix: an instance of Matrix.
"""
if depth in self._matrix_cache:
return self._matrix_cache[de... | [
"def",
"as_matrix",
"(",
"self",
",",
"depth",
"=",
"0",
")",
":",
"if",
"depth",
"in",
"self",
".",
"_matrix_cache",
":",
"return",
"self",
".",
"_matrix_cache",
"[",
"depth",
"]",
"self",
".",
"_matrix_cache",
"[",
"depth",
"]",
"=",
"matrix",
"=",
... | Create a matrix with self as node, cache it, return it.
Args:
depth (int): depth of the matrix.
Returns:
Matrix: an instance of Matrix. | [
"Create",
"a",
"matrix",
"with",
"self",
"as",
"node",
"cache",
"it",
"return",
"it",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L315-L328 | train | Create a matrix with self as node cache it return it. |
Genida/dependenpy | src/dependenpy/node.py | RootNode.as_treemap | def as_treemap(self):
"""
Return the dependencies as a TreeMap.
Returns:
TreeMap: instance of TreeMap.
"""
if self._treemap_cache:
return self._treemap_cache
self._treemap_cache = treemap = TreeMap(self)
return treemap | python | def as_treemap(self):
"""
Return the dependencies as a TreeMap.
Returns:
TreeMap: instance of TreeMap.
"""
if self._treemap_cache:
return self._treemap_cache
self._treemap_cache = treemap = TreeMap(self)
return treemap | [
"def",
"as_treemap",
"(",
"self",
")",
":",
"if",
"self",
".",
"_treemap_cache",
":",
"return",
"self",
".",
"_treemap_cache",
"self",
".",
"_treemap_cache",
"=",
"treemap",
"=",
"TreeMap",
"(",
"self",
")",
"return",
"treemap"
] | Return the dependencies as a TreeMap.
Returns:
TreeMap: instance of TreeMap. | [
"Return",
"the",
"dependencies",
"as",
"a",
"TreeMap",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L330-L340 | train | Return the dependencies as a TreeMap. |
Genida/dependenpy | src/dependenpy/node.py | LeafNode.root | def root(self):
"""
Property to return the root of this node.
Returns:
Package: this node's root package.
"""
node = self
while node.package is not None:
node = node.package
return node | python | def root(self):
"""
Property to return the root of this node.
Returns:
Package: this node's root package.
"""
node = self
while node.package is not None:
node = node.package
return node | [
"def",
"root",
"(",
"self",
")",
":",
"node",
"=",
"self",
"while",
"node",
".",
"package",
"is",
"not",
"None",
":",
"node",
"=",
"node",
".",
"package",
"return",
"node"
] | Property to return the root of this node.
Returns:
Package: this node's root package. | [
"Property",
"to",
"return",
"the",
"root",
"of",
"this",
"node",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L355-L365 | train | Returns the root node of the hierarchy. |
Genida/dependenpy | src/dependenpy/node.py | LeafNode.depth | def depth(self):
"""
Property to tell the depth of the node in the tree.
Returns:
int: the node's depth in the tree.
"""
if self._depth_cache is not None:
return self._depth_cache
depth, node = 1, self
while node.package is not None:
... | python | def depth(self):
"""
Property to tell the depth of the node in the tree.
Returns:
int: the node's depth in the tree.
"""
if self._depth_cache is not None:
return self._depth_cache
depth, node = 1, self
while node.package is not None:
... | [
"def",
"depth",
"(",
"self",
")",
":",
"if",
"self",
".",
"_depth_cache",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_depth_cache",
"depth",
",",
"node",
"=",
"1",
",",
"self",
"while",
"node",
".",
"package",
"is",
"not",
"None",
":",
"depth"... | Property to tell the depth of the node in the tree.
Returns:
int: the node's depth in the tree. | [
"Property",
"to",
"tell",
"the",
"depth",
"of",
"the",
"node",
"in",
"the",
"tree",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L368-L382 | train | Return the depth of the node in the tree. |
Genida/dependenpy | src/dependenpy/node.py | LeafNode.absolute_name | def absolute_name(self, depth=0):
"""
Return the absolute name of the node.
Concatenate names from root to self within depth.
Args:
depth (int): maximum depth to go to.
Returns:
str: absolute name of the node (until given depth is reached).
"""
... | python | def absolute_name(self, depth=0):
"""
Return the absolute name of the node.
Concatenate names from root to self within depth.
Args:
depth (int): maximum depth to go to.
Returns:
str: absolute name of the node (until given depth is reached).
"""
... | [
"def",
"absolute_name",
"(",
"self",
",",
"depth",
"=",
"0",
")",
":",
"node",
",",
"node_depth",
"=",
"self",
",",
"self",
".",
"depth",
"if",
"depth",
"<",
"1",
":",
"depth",
"=",
"node_depth",
"while",
"node_depth",
">",
"depth",
"and",
"node",
".... | Return the absolute name of the node.
Concatenate names from root to self within depth.
Args:
depth (int): maximum depth to go to.
Returns:
str: absolute name of the node (until given depth is reached). | [
"Return",
"the",
"absolute",
"name",
"of",
"the",
"node",
"."
] | df099c17cbe735c990eca9197e39cfc5eb8a4c8e | https://github.com/Genida/dependenpy/blob/df099c17cbe735c990eca9197e39cfc5eb8a4c8e/src/dependenpy/node.py#L384-L406 | train | Return the absolute name of the node. |
klen/zeta-library | zetalibrary/utils.py | color_msg | def color_msg(msg, color):
" Return colored message "
return ''.join((COLORS.get(color, COLORS['endc']), msg, COLORS['endc'])) | python | def color_msg(msg, color):
" Return colored message "
return ''.join((COLORS.get(color, COLORS['endc']), msg, COLORS['endc'])) | [
"def",
"color_msg",
"(",
"msg",
",",
"color",
")",
":",
"return",
"''",
".",
"join",
"(",
"(",
"COLORS",
".",
"get",
"(",
"color",
",",
"COLORS",
"[",
"'endc'",
"]",
")",
",",
"msg",
",",
"COLORS",
"[",
"'endc'",
"]",
")",
")"
] | Return colored message | [
"Return",
"colored",
"message"
] | b76f89000f467e10ddcc94aded3f6c6bf4a0e5bd | https://github.com/klen/zeta-library/blob/b76f89000f467e10ddcc94aded3f6c6bf4a0e5bd/zetalibrary/utils.py#L9-L11 | train | Return colored message |
klen/zeta-library | zetalibrary/utils.py | gen_files | def gen_files(path, prefix="_"):
" Return file generator "
if op.isdir(path):
for name in listdir(path):
fpath = op.join(path, name)
if is_parsed_file(fpath):
yield op.abspath(fpath)
elif is_parsed_file(path):
yield op.abspath(path) | python | def gen_files(path, prefix="_"):
" Return file generator "
if op.isdir(path):
for name in listdir(path):
fpath = op.join(path, name)
if is_parsed_file(fpath):
yield op.abspath(fpath)
elif is_parsed_file(path):
yield op.abspath(path) | [
"def",
"gen_files",
"(",
"path",
",",
"prefix",
"=",
"\"_\"",
")",
":",
"if",
"op",
".",
"isdir",
"(",
"path",
")",
":",
"for",
"name",
"in",
"listdir",
"(",
"path",
")",
":",
"fpath",
"=",
"op",
".",
"join",
"(",
"path",
",",
"name",
")",
"if"... | Return file generator | [
"Return",
"file",
"generator"
] | b76f89000f467e10ddcc94aded3f6c6bf4a0e5bd | https://github.com/klen/zeta-library/blob/b76f89000f467e10ddcc94aded3f6c6bf4a0e5bd/zetalibrary/utils.py#L19-L29 | train | Return file generator |
klen/zeta-library | zetalibrary/utils.py | pack | def pack(args):
" Pack files. "
from zetalibrary.packer import Packer
args = parse_config(args)
for path in gen_files(args.source, prefix=args.prefix):
Packer(path, args).pack() | python | def pack(args):
" Pack files. "
from zetalibrary.packer import Packer
args = parse_config(args)
for path in gen_files(args.source, prefix=args.prefix):
Packer(path, args).pack() | [
"def",
"pack",
"(",
"args",
")",
":",
"from",
"zetalibrary",
".",
"packer",
"import",
"Packer",
"args",
"=",
"parse_config",
"(",
"args",
")",
"for",
"path",
"in",
"gen_files",
"(",
"args",
".",
"source",
",",
"prefix",
"=",
"args",
".",
"prefix",
")",... | Pack files. | [
"Pack",
"files",
"."
] | b76f89000f467e10ddcc94aded3f6c6bf4a0e5bd | https://github.com/klen/zeta-library/blob/b76f89000f467e10ddcc94aded3f6c6bf4a0e5bd/zetalibrary/utils.py#L41-L47 | train | Pack files. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.