hexsha stringlengths 40 40 | repo stringlengths 7 114 | path stringlengths 4 124 | license listlengths 1 9 | language stringclasses 1
value | identifier stringlengths 1 71 | return_type stringlengths 1 749 ⌀ | original_string stringlengths 76 22.7k | original_docstring stringlengths 16 7.61k | docstring stringlengths 16 2.47k | docstring_tokens listlengths 6 477 | code stringlengths 14 10.2k | code_tokens listlengths 6 996 | short_docstring stringlengths 2 644 | short_docstring_tokens listlengths 1 116 | comment listlengths 1 89 | parameters listlengths 0 64 | docstring_params dict |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2494465cc1475d846863f4177c222f5e50d85692 | williampaciaroni/IPIN-System | nlls.py | [
"MIT"
] | Python | nlls | <not_specific> | def nlls(P, R, N=100, start=lls):
"""Non-linear least squares algorithm"""
if len(R) < 3: return None
S = start(P, R)
iterations = 0
e1, e2 = None, residual(P, R, S)
while iterations < N:
if not all([ distance(S, p) >= 1e-5 for p in P]):
return S
A = np.array([[(S[0]... | Non-linear least squares algorithm | Non-linear least squares algorithm | [
"Non",
"-",
"linear",
"least",
"squares",
"algorithm"
] | def nlls(P, R, N=100, start=lls):
if len(R) < 3: return None
S = start(P, R)
iterations = 0
e1, e2 = None, residual(P, R, S)
while iterations < N:
if not all([ distance(S, p) >= 1e-5 for p in P]):
return S
A = np.array([[(S[0] - p[0]) / distance(S, p),(S[1] - p[1]) / dist... | [
"def",
"nlls",
"(",
"P",
",",
"R",
",",
"N",
"=",
"100",
",",
"start",
"=",
"lls",
")",
":",
"if",
"len",
"(",
"R",
")",
"<",
"3",
":",
"return",
"None",
"S",
"=",
"start",
"(",
"P",
",",
"R",
")",
"iterations",
"=",
"0",
"e1",
",",
"e2",... | Non-linear least squares algorithm | [
"Non",
"-",
"linear",
"least",
"squares",
"algorithm"
] | [
"\"\"\"Non-linear least squares algorithm\"\"\"",
"# Solve using the closed form solution $(A^TA)^{-1}(A^Tb)$"
] | [
{
"param": "P",
"type": null
},
{
"param": "R",
"type": null
},
{
"param": "N",
"type": null
},
{
"param": "start",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "P",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "R",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
c00b9cbdf3db979a9bcb48eda828f07530b5ee88 | williampaciaroni/IPIN-System | clustering.py | [
"MIT"
] | Python | approximate | <not_specific> | def approximate(p1, r1, p2, r2):
"""Approximate a circle intersection point."""
d = np.linalg.norm(p1-p2)
if abs(d)<exp(1e-5):
return None
dr1, dr2 = r1 / d, r2 / d
p = p2-p1
dp1, dp2 = dr1*p, dr2*p
p11, p12, p21, p22 = p1 + dp1, p1-dp1, p2 + dp2, p2-dp2 # Find nearest pair of inter... | Approximate a circle intersection point. | Approximate a circle intersection point. | [
"Approximate",
"a",
"circle",
"intersection",
"point",
"."
] | def approximate(p1, r1, p2, r2):
d = np.linalg.norm(p1-p2)
if abs(d)<exp(1e-5):
return None
dr1, dr2 = r1 / d, r2 / d
p = p2-p1
dp1, dp2 = dr1*p, dr2*p
p11, p12, p21, p22 = p1 + dp1, p1-dp1, p2 + dp2, p2-dp2
n1, n2 = p11, p21
d1, dt = np.linalg.norm(p11-p21), np.linalg.norm(p11... | [
"def",
"approximate",
"(",
"p1",
",",
"r1",
",",
"p2",
",",
"r2",
")",
":",
"d",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"p1",
"-",
"p2",
")",
"if",
"abs",
"(",
"d",
")",
"<",
"exp",
"(",
"1e-5",
")",
":",
"return",
"None",
"dr1",
",",
... | Approximate a circle intersection point. | [
"Approximate",
"a",
"circle",
"intersection",
"point",
"."
] | [
"\"\"\"Approximate a circle intersection point.\"\"\"",
"# Find nearest pair of intersection point belonging to different # circles.",
"# return middle of line between two nearest points as result "
] | [
{
"param": "p1",
"type": null
},
{
"param": "r1",
"type": null
},
{
"param": "p2",
"type": null
},
{
"param": "r2",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "p1",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "r1",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
a096277a432f20b83ad98d094a58a36db91056b6 | williampaciaroni/IPIN-System | lls.py | [
"MIT"
] | Python | lls | <not_specific> | def lls(P, R):
"""P is a 2xN matrix of landmark positions. R is a vector of
distances measured from each landmark N."""
if len(R) < 3: return None
A = np.array([[P[i, 0] - P[-1, 0], P[i, 1] - P[-1, 1]]
for i in range(P.shape[0] - 1)])
b = np.array([(P[i, 0] ** 2 - P[-1, 0] ** 2 + \... | P is a 2xN matrix of landmark positions. R is a vector of
distances measured from each landmark N. | P is a 2xN matrix of landmark positions. R is a vector of
distances measured from each landmark N. | [
"P",
"is",
"a",
"2xN",
"matrix",
"of",
"landmark",
"positions",
".",
"R",
"is",
"a",
"vector",
"of",
"distances",
"measured",
"from",
"each",
"landmark",
"N",
"."
] | def lls(P, R):
if len(R) < 3: return None
A = np.array([[P[i, 0] - P[-1, 0], P[i, 1] - P[-1, 1]]
for i in range(P.shape[0] - 1)])
b = np.array([(P[i, 0] ** 2 - P[-1, 0] ** 2 + \
P[i, 1] ** 2 - P[-1, 1] ** 2 + \
R[-1] ** 2 - R[i] ** 2) * 0.5 \
... | [
"def",
"lls",
"(",
"P",
",",
"R",
")",
":",
"if",
"len",
"(",
"R",
")",
"<",
"3",
":",
"return",
"None",
"A",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"P",
"[",
"i",
",",
"0",
"]",
"-",
"P",
"[",
"-",
"1",
",",
"0",
"]",
",",
"P",
"[... | P is a 2xN matrix of landmark positions. | [
"P",
"is",
"a",
"2xN",
"matrix",
"of",
"landmark",
"positions",
"."
] | [
"\"\"\"P is a 2xN matrix of landmark positions. R is a vector of\n distances measured from each landmark N.\"\"\""
] | [
{
"param": "P",
"type": null
},
{
"param": "R",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "P",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "R",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
767d5931a420fcf84a698ebbd0d4d699485e3847 | strayge/hstt | hstt/main.py | [
"MIT"
] | Python | worker_loop | None | async def worker_loop(
args: argparse.Namespace, tasks: Queue, results: Queue, start_event: Event, worker_number: int,
) -> None:
"""Make actual requests in loop."""
try:
# trace for tracking time different times inside requests
async def trace_call(name: str, session: ClientSession, context... | Make actual requests in loop. | Make actual requests in loop. | [
"Make",
"actual",
"requests",
"in",
"loop",
"."
] | async def worker_loop(
args: argparse.Namespace, tasks: Queue, results: Queue, start_event: Event, worker_number: int,
) -> None:
try:
async def trace_call(name: str, session: ClientSession, context: SimpleNamespace, params: Any) -> None:
if name not in context.trace_request_ctx:
... | [
"async",
"def",
"worker_loop",
"(",
"args",
":",
"argparse",
".",
"Namespace",
",",
"tasks",
":",
"Queue",
",",
"results",
":",
"Queue",
",",
"start_event",
":",
"Event",
",",
"worker_number",
":",
"int",
",",
")",
"->",
"None",
":",
"try",
":",
"async... | Make actual requests in loop. | [
"Make",
"actual",
"requests",
"in",
"loop",
"."
] | [
"\"\"\"Make actual requests in loop.\"\"\"",
"# trace for tracking time different times inside requests",
"# noqa",
"# noqa",
"# noqa",
"# noqa",
"# noqa",
"# noqa",
"# wait until all threads will be initialized",
"# common session for all requests",
"# throttle requests",
"# new session for e... | [
{
"param": "args",
"type": "argparse.Namespace"
},
{
"param": "tasks",
"type": "Queue"
},
{
"param": "results",
"type": "Queue"
},
{
"param": "start_event",
"type": "Event"
},
{
"param": "worker_number",
"type": "int"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "args",
"type": "argparse.Namespace",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "tasks",
"type": "Queue",
"docstring": null,
"... |
767d5931a420fcf84a698ebbd0d4d699485e3847 | strayge/hstt | hstt/main.py | [
"MIT"
] | Python | timing_stats | List[str] | def timing_stats(results: List[Result]) -> List[str]:
"""Calculate and format lines with timings across completed results."""
def percentile(data: List[float], percent: int) -> Union[float, str]:
if not data:
return '-'
data_sorted = sorted(data)
pos = max(int(round(percent /... | Calculate and format lines with timings across completed results. | Calculate and format lines with timings across completed results. | [
"Calculate",
"and",
"format",
"lines",
"with",
"timings",
"across",
"completed",
"results",
"."
] | def timing_stats(results: List[Result]) -> List[str]:
def percentile(data: List[float], percent: int) -> Union[float, str]:
if not data:
return '-'
data_sorted = sorted(data)
pos = max(int(round(percent / 100 * len(data) + 0.5)), 2)
return data_sorted[pos - 2]
def for... | [
"def",
"timing_stats",
"(",
"results",
":",
"List",
"[",
"Result",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"def",
"percentile",
"(",
"data",
":",
"List",
"[",
"float",
"]",
",",
"percent",
":",
"int",
")",
"->",
"Union",
"[",
"float",
",",
... | Calculate and format lines with timings across completed results. | [
"Calculate",
"and",
"format",
"lines",
"with",
"timings",
"across",
"completed",
"results",
"."
] | [
"\"\"\"Calculate and format lines with timings across completed results.\"\"\""
] | [
{
"param": "results",
"type": "List[Result]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "results",
"type": "List[Result]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
767d5931a420fcf84a698ebbd0d4d699485e3847 | strayge/hstt | hstt/main.py | [
"MIT"
] | Python | codes_stats | List[str] | def codes_stats(results: List[Result]) -> List[str]:
"""Calculate and format lines return codes / errors across results."""
lines = []
with_codes = Counter([r.status for r in results if r.status])
with_errors = Counter([r.error for r in results if r.error])
for code, count in with_codes.items():
... | Calculate and format lines return codes / errors across results. | Calculate and format lines return codes / errors across results. | [
"Calculate",
"and",
"format",
"lines",
"return",
"codes",
"/",
"errors",
"across",
"results",
"."
] | def codes_stats(results: List[Result]) -> List[str]:
lines = []
with_codes = Counter([r.status for r in results if r.status])
with_errors = Counter([r.error for r in results if r.error])
for code, count in with_codes.items():
lines.append(f'{code:<10}: {count:>6} ({count * 100 / len(results):6.2... | [
"def",
"codes_stats",
"(",
"results",
":",
"List",
"[",
"Result",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"lines",
"=",
"[",
"]",
"with_codes",
"=",
"Counter",
"(",
"[",
"r",
".",
"status",
"for",
"r",
"in",
"results",
"if",
"r",
".",
"stat... | Calculate and format lines return codes / errors across results. | [
"Calculate",
"and",
"format",
"lines",
"return",
"codes",
"/",
"errors",
"across",
"results",
"."
] | [
"\"\"\"Calculate and format lines return codes / errors across results.\"\"\""
] | [
{
"param": "results",
"type": "List[Result]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "results",
"type": "List[Result]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
767d5931a420fcf84a698ebbd0d4d699485e3847 | strayge/hstt | hstt/main.py | [
"MIT"
] | Python | detect_window_resize | None | def detect_window_resize(screen) -> None:
"""Detect terminal resize & ^C pressing."""
# required for getting resize signal
keycode = None
while keycode != -1:
keycode = screen.getch()
if keycode == 3:
# curses eat ^C, so we need raise it manually
raise KeyboardInt... | Detect terminal resize & ^C pressing. | Detect terminal resize & ^C pressing. | [
"Detect",
"terminal",
"resize",
"&",
"^C",
"pressing",
"."
] | def detect_window_resize(screen) -> None:
keycode = None
while keycode != -1:
keycode = screen.getch()
if keycode == 3:
raise KeyboardInterrupt()
if curses.is_term_resized(*screen.getmaxyx()):
curses.resize_term(0, 0)
screen.erase() | [
"def",
"detect_window_resize",
"(",
"screen",
")",
"->",
"None",
":",
"keycode",
"=",
"None",
"while",
"keycode",
"!=",
"-",
"1",
":",
"keycode",
"=",
"screen",
".",
"getch",
"(",
")",
"if",
"keycode",
"==",
"3",
":",
"raise",
"KeyboardInterrupt",
"(",
... | Detect terminal resize & ^C pressing. | [
"Detect",
"terminal",
"resize",
"&",
"^C",
"pressing",
"."
] | [
"\"\"\"Detect terminal resize & ^C pressing.\"\"\"",
"# required for getting resize signal",
"# curses eat ^C, so we need raise it manually",
"# detect different size changed by signal"
] | [
{
"param": "screen",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "screen",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
767d5931a420fcf84a698ebbd0d4d699485e3847 | strayge/hstt | hstt/main.py | [
"MIT"
] | Python | draw_text | None | def draw_text(self, y: int, x: int, text: str) -> None:
"""Draw text at specific coords from SubArea start (excluding border)."""
y_start = self.top + y
if self.border_top:
y_start += 1
x_start = self.left + x
if self.border_left:
x_start += 1
try:... | Draw text at specific coords from SubArea start (excluding border). | Draw text at specific coords from SubArea start (excluding border). | [
"Draw",
"text",
"at",
"specific",
"coords",
"from",
"SubArea",
"start",
"(",
"excluding",
"border",
")",
"."
] | def draw_text(self, y: int, x: int, text: str) -> None:
y_start = self.top + y
if self.border_top:
y_start += 1
x_start = self.left + x
if self.border_left:
x_start += 1
try:
self.window.addstr(y_start, x_start, text)
except curses.erro... | [
"def",
"draw_text",
"(",
"self",
",",
"y",
":",
"int",
",",
"x",
":",
"int",
",",
"text",
":",
"str",
")",
"->",
"None",
":",
"y_start",
"=",
"self",
".",
"top",
"+",
"y",
"if",
"self",
".",
"border_top",
":",
"y_start",
"+=",
"1",
"x_start",
"... | Draw text at specific coords from SubArea start (excluding border). | [
"Draw",
"text",
"at",
"specific",
"coords",
"from",
"SubArea",
"start",
"(",
"excluding",
"border",
")",
"."
] | [
"\"\"\"Draw text at specific coords from SubArea start (excluding border).\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "y",
"type": "int"
},
{
"param": "x",
"type": "int"
},
{
"param": "text",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "y",
"type": "int",
"docstring": null,
"docstring_tokens": [],... |
767d5931a420fcf84a698ebbd0d4d699485e3847 | strayge/hstt | hstt/main.py | [
"MIT"
] | Python | draw_hline | None | def draw_hline(self, y: int, x: int, length: int) -> None:
"""Draw horizontal line at specific coords from SubArea start (excluding border)."""
if not length:
return
y_start = self.top + y
if self.border_top:
y_start += 1
x_start = self.left + x
if... | Draw horizontal line at specific coords from SubArea start (excluding border). | Draw horizontal line at specific coords from SubArea start (excluding border). | [
"Draw",
"horizontal",
"line",
"at",
"specific",
"coords",
"from",
"SubArea",
"start",
"(",
"excluding",
"border",
")",
"."
] | def draw_hline(self, y: int, x: int, length: int) -> None:
if not length:
return
y_start = self.top + y
if self.border_top:
y_start += 1
x_start = self.left + x
if self.border_left:
x_start += 1
try:
self.window.hline(y_star... | [
"def",
"draw_hline",
"(",
"self",
",",
"y",
":",
"int",
",",
"x",
":",
"int",
",",
"length",
":",
"int",
")",
"->",
"None",
":",
"if",
"not",
"length",
":",
"return",
"y_start",
"=",
"self",
".",
"top",
"+",
"y",
"if",
"self",
".",
"border_top",
... | Draw horizontal line at specific coords from SubArea start (excluding border). | [
"Draw",
"horizontal",
"line",
"at",
"specific",
"coords",
"from",
"SubArea",
"start",
"(",
"excluding",
"border",
")",
"."
] | [
"\"\"\"Draw horizontal line at specific coords from SubArea start (excluding border).\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "y",
"type": "int"
},
{
"param": "x",
"type": "int"
},
{
"param": "length",
"type": "int"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "y",
"type": "int",
"docstring": null,
"docstring_tokens": [],... |
767d5931a420fcf84a698ebbd0d4d699485e3847 | strayge/hstt | hstt/main.py | [
"MIT"
] | Python | draw_vline | None | def draw_vline(self, y: int, x: int, length: int) -> None:
"""Draw vertical line at specific coords from SubArea start (excluding border)."""
if not length:
return
y_start = self.top + y
if self.border_top:
y_start += 1
x_start = self.left + x
if s... | Draw vertical line at specific coords from SubArea start (excluding border). | Draw vertical line at specific coords from SubArea start (excluding border). | [
"Draw",
"vertical",
"line",
"at",
"specific",
"coords",
"from",
"SubArea",
"start",
"(",
"excluding",
"border",
")",
"."
] | def draw_vline(self, y: int, x: int, length: int) -> None:
if not length:
return
y_start = self.top + y
if self.border_top:
y_start += 1
x_start = self.left + x
if self.border_left:
x_start += 1
try:
self.window.vline(y_star... | [
"def",
"draw_vline",
"(",
"self",
",",
"y",
":",
"int",
",",
"x",
":",
"int",
",",
"length",
":",
"int",
")",
"->",
"None",
":",
"if",
"not",
"length",
":",
"return",
"y_start",
"=",
"self",
".",
"top",
"+",
"y",
"if",
"self",
".",
"border_top",
... | Draw vertical line at specific coords from SubArea start (excluding border). | [
"Draw",
"vertical",
"line",
"at",
"specific",
"coords",
"from",
"SubArea",
"start",
"(",
"excluding",
"border",
")",
"."
] | [
"\"\"\"Draw vertical line at specific coords from SubArea start (excluding border).\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "y",
"type": "int"
},
{
"param": "x",
"type": "int"
},
{
"param": "length",
"type": "int"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "y",
"type": "int",
"docstring": null,
"docstring_tokens": [],... |
8febfc96ef318352994c3d7d38a4c7f3f8e5b4b6 | RankoHata/PrefectDecorator | PrefectDecorator/save_to_file.py | [
"MIT"
] | Python | save_to_file | <not_specific> | def save_to_file(filepath, save=True, override=False, filetype='text', encoding='utf-8', end='\n', headers=None, process_func=None):
"""A decorator that save the data to file.
Note:
The arguments of the wrapped function can dynamically affect the function of the decorator.
The arguments of ... | A decorator that save the data to file.
Note:
The arguments of the wrapped function can dynamically affect the function of the decorator.
The arguments of the wrapped function have a higher priority.
Args:
filepath: The absolute path of the target file where the data is saved.
... | A decorator that save the data to file.
Note:
The arguments of the wrapped function can dynamically affect the function of the decorator.
The arguments of the wrapped function have a higher priority. | [
"A",
"decorator",
"that",
"save",
"the",
"data",
"to",
"file",
".",
"Note",
":",
"The",
"arguments",
"of",
"the",
"wrapped",
"function",
"can",
"dynamically",
"affect",
"the",
"function",
"of",
"the",
"decorator",
".",
"The",
"arguments",
"of",
"the",
"wra... | def save_to_file(filepath, save=True, override=False, filetype='text', encoding='utf-8', end='\n', headers=None, process_func=None):
def decorate(func):
@wraps(func)
def wrapper(*args, **kwargs):
nonlocal save, override, headers
try:
save = kwargs.pop('save')
... | [
"def",
"save_to_file",
"(",
"filepath",
",",
"save",
"=",
"True",
",",
"override",
"=",
"False",
",",
"filetype",
"=",
"'text'",
",",
"encoding",
"=",
"'utf-8'",
",",
"end",
"=",
"'\\n'",
",",
"headers",
"=",
"None",
",",
"process_func",
"=",
"None",
"... | A decorator that save the data to file. | [
"A",
"decorator",
"that",
"save",
"the",
"data",
"to",
"file",
"."
] | [
"\"\"\"A decorator that save the data to file.\n \n Note:\n The arguments of the wrapped function can dynamically affect the function of the decorator.\n The arguments of the wrapped function have a higher priority.\n\n Args:\n filepath: The absolute path of the target file where the d... | [
{
"param": "filepath",
"type": null
},
{
"param": "save",
"type": null
},
{
"param": "override",
"type": null
},
{
"param": "filetype",
"type": null
},
{
"param": "encoding",
"type": null
},
{
"param": "end",
"type": null
},
{
"param": "hea... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "filepath",
"type": null,
"docstring": "The absolute path of the target file where the data is saved.",
"docstring_tokens": [
"The",
"absolute",
"path",
"of",
"the",
"target",
... |
f27cd42d1c2393ad54aead2a2713e716912c64b0 | Trion/pySoundToolbox | pySoundToolbox.py | [
"MIT"
] | Python | genSine | <not_specific> | def genSine(frequency=1.0, amplitude=1.0, phaseShift=0.0):
"""
Generates complex signal.
@param frequency frequency of the wave in Hz
@param amplitude amplitude of the sine
@param phaseShift phase shift of the wave
@return A function with a parameter t. t is the time which needs to be a float
... |
Generates complex signal.
@param frequency frequency of the wave in Hz
@param amplitude amplitude of the sine
@param phaseShift phase shift of the wave
@return A function with a parameter t. t is the time which needs to be a float
or an numpy array of floats. The function returns a float, ... | Generates complex signal.
@param frequency frequency of the wave in Hz
@param amplitude amplitude of the sine
@param phaseShift phase shift of the wave
@return A function with a parameter t. t is the time which needs to be a float
or an numpy array of floats. The function returns a float, which is the value of the wave... | [
"Generates",
"complex",
"signal",
".",
"@param",
"frequency",
"frequency",
"of",
"the",
"wave",
"in",
"Hz",
"@param",
"amplitude",
"amplitude",
"of",
"the",
"sine",
"@param",
"phaseShift",
"phase",
"shift",
"of",
"the",
"wave",
"@return",
"A",
"function",
"wit... | def genSine(frequency=1.0, amplitude=1.0, phaseShift=0.0):
return lambda t: amplitude * np.exp(-1j * 2 * np.pi * frequency * t + phaseShift) | [
"def",
"genSine",
"(",
"frequency",
"=",
"1.0",
",",
"amplitude",
"=",
"1.0",
",",
"phaseShift",
"=",
"0.0",
")",
":",
"return",
"lambda",
"t",
":",
"amplitude",
"*",
"np",
".",
"exp",
"(",
"-",
"1j",
"*",
"2",
"*",
"np",
".",
"pi",
"*",
"frequen... | Generates complex signal. | [
"Generates",
"complex",
"signal",
"."
] | [
"\"\"\"\n Generates complex signal.\n\n @param frequency frequency of the wave in Hz\n @param amplitude amplitude of the sine\n @param phaseShift phase shift of the wave\n @return A function with a parameter t. t is the time which needs to be a float\n or an numpy array of floats. The function... | [
{
"param": "frequency",
"type": null
},
{
"param": "amplitude",
"type": null
},
{
"param": "phaseShift",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "frequency",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "amplitude",
"type": null,
"docstring": null,
"docstring_... |
f27cd42d1c2393ad54aead2a2713e716912c64b0 | Trion/pySoundToolbox | pySoundToolbox.py | [
"MIT"
] | Python | genArrayResponseFunc | <not_specific> | def genArrayResponseFunc(angles, antennaPositions=np.array([[0.113, -0.036, -0.076, -0.113], [0.0, 0.0, 0.0, 0.0]]), frequencies=1, amplitudes=1, phaseShifts=0, noiseStd=0):
"""
Generates an array response function.
@param angles 1-D numpy array with angles of the sources in rad
@param antennaPositions... |
Generates an array response function.
@param angles 1-D numpy array with angles of the sources in rad
@param antennaPositions positions of the antennas to an abitrary origin as numpy array
@param frequenies numpy array or float with the frequencies of the sound sources in Hz
@param amplitudes nump... | Generates an array response function. | [
"Generates",
"an",
"array",
"response",
"function",
"."
] | def genArrayResponseFunc(angles, antennaPositions=np.array([[0.113, -0.036, -0.076, -0.113], [0.0, 0.0, 0.0, 0.0]]), frequencies=1, amplitudes=1, phaseShifts=0, noiseStd=0):
antennaNum = antennaPositions.shape[1]
if np.isscalar(angles):
angles = np.array([angles], dtype=np.float128)
sourcesNum = ang... | [
"def",
"genArrayResponseFunc",
"(",
"angles",
",",
"antennaPositions",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0.113",
",",
"-",
"0.036",
",",
"-",
"0.076",
",",
"-",
"0.113",
"]",
",",
"[",
"0.0",
",",
"0.0",
",",
"0.0",
",",
"0.0",
"]",
"]",
"... | Generates an array response function. | [
"Generates",
"an",
"array",
"response",
"function",
"."
] | [
"\"\"\"\n Generates an array response function.\n\n @param angles 1-D numpy array with angles of the sources in rad\n @param antennaPositions positions of the antennas to an abitrary origin as numpy array\n @param frequenies numpy array or float with the frequencies of the sound sources in Hz\n @para... | [
{
"param": "angles",
"type": null
},
{
"param": "antennaPositions",
"type": null
},
{
"param": "frequencies",
"type": null
},
{
"param": "amplitudes",
"type": null
},
{
"param": "phaseShifts",
"type": null
},
{
"param": "noiseStd",
"type": null
}... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "angles",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "antennaPositions",
"type": null,
"docstring": null,
"docstr... |
f27cd42d1c2393ad54aead2a2713e716912c64b0 | Trion/pySoundToolbox | pySoundToolbox.py | [
"MIT"
] | Python | func | <not_specific> | def func(t):
"""
Array response function.
@param t time, which needs to be a float or a numpy array with times
@return a numpy array with the elongation of the wave at times t.
A row represents one microphone within the array.
"""
if type(t) != np.ndarray:
... |
Array response function.
@param t time, which needs to be a float or a numpy array with times
@return a numpy array with the elongation of the wave at times t.
A row represents one microphone within the array.
| Array response function.
@param t time, which needs to be a float or a numpy array with times
@return a numpy array with the elongation of the wave at times t.
A row represents one microphone within the array. | [
"Array",
"response",
"function",
".",
"@param",
"t",
"time",
"which",
"needs",
"to",
"be",
"a",
"float",
"or",
"a",
"numpy",
"array",
"with",
"times",
"@return",
"a",
"numpy",
"array",
"with",
"the",
"elongation",
"of",
"the",
"wave",
"at",
"times",
"t",... | def func(t):
if type(t) != np.ndarray:
t = np.array([t])
data = np.matrix(np.empty((antennaNum, t.shape[0]), dtype=np.complex))
for i in range(t.shape[0]):
sourceData = np.matrix([[sourceSignals[k](t[i])] for k in range(sourcesNum)], dtype=np.complex256)
noise... | [
"def",
"func",
"(",
"t",
")",
":",
"if",
"type",
"(",
"t",
")",
"!=",
"np",
".",
"ndarray",
":",
"t",
"=",
"np",
".",
"array",
"(",
"[",
"t",
"]",
")",
"data",
"=",
"np",
".",
"matrix",
"(",
"np",
".",
"empty",
"(",
"(",
"antennaNum",
",",
... | Array response function. | [
"Array",
"response",
"function",
"."
] | [
"\"\"\"\n Array response function.\n\n @param t time, which needs to be a float or a numpy array with times\n @return a numpy array with the elongation of the wave at times t.\n A row represents one microphone within the array.\n \"\"\""
] | [
{
"param": "t",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "t",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
f27cd42d1c2393ad54aead2a2713e716912c64b0 | Trion/pySoundToolbox | pySoundToolbox.py | [
"MIT"
] | Python | save24PCM | null | def save24PCM(fileName, data, samplingRate=16000):
"""
Saves a 24 PCM wav file.
@param fileName name of the file
@param data already sampled data as numpy uint32 array. The cols represent the time and the rows
are the channels.
@param samplingRate sampling rate in Hz
"""
# Determin... |
Saves a 24 PCM wav file.
@param fileName name of the file
@param data already sampled data as numpy uint32 array. The cols represent the time and the rows
are the channels.
@param samplingRate sampling rate in Hz
| Saves a 24 PCM wav file.
@param fileName name of the file
@param data already sampled data as numpy uint32 array. The cols represent the time and the rows
are the channels.
@param samplingRate sampling rate in Hz | [
"Saves",
"a",
"24",
"PCM",
"wav",
"file",
".",
"@param",
"fileName",
"name",
"of",
"the",
"file",
"@param",
"data",
"already",
"sampled",
"data",
"as",
"numpy",
"uint32",
"array",
".",
"The",
"cols",
"represent",
"the",
"time",
"and",
"the",
"rows",
"are... | def save24PCM(fileName, data, samplingRate=16000):
if len(data.shape) == 1:
data = np.matrix(data)
with wave.open(fileName, 'w') as wav:
wav.setframerate(samplingRate)
wav.setsampwidth(3)
wav.setnchannels(data.shape[0])
for i in range(data.shape[1]):
for k in ... | [
"def",
"save24PCM",
"(",
"fileName",
",",
"data",
",",
"samplingRate",
"=",
"16000",
")",
":",
"if",
"len",
"(",
"data",
".",
"shape",
")",
"==",
"1",
":",
"data",
"=",
"np",
".",
"matrix",
"(",
"data",
")",
"with",
"wave",
".",
"open",
"(",
"fil... | Saves a 24 PCM wav file. | [
"Saves",
"a",
"24",
"PCM",
"wav",
"file",
"."
] | [
"\"\"\"\n Saves a 24 PCM wav file.\n\n @param fileName name of the file\n @param data already sampled data as numpy uint32 array. The cols represent the time and the rows\n are the channels.\n @param samplingRate sampling rate in Hz\n \"\"\"",
"# Determine number of channels",
"# Revert by... | [
{
"param": "fileName",
"type": null
},
{
"param": "data",
"type": null
},
{
"param": "samplingRate",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "fileName",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens... |
f27cd42d1c2393ad54aead2a2713e716912c64b0 | Trion/pySoundToolbox | pySoundToolbox.py | [
"MIT"
] | Python | read24PCM | <not_specific> | def read24PCM(fileName):
"""
Reads a 24 PCM wav file.
@param fileName name of the file
@return tupel (data, samplingRate):
data is a numpy int32 array with the read data. A row represents one channel.
samplingRate is the provided sampling rate.
"""
with wave.open(fileName, 'r')... |
Reads a 24 PCM wav file.
@param fileName name of the file
@return tupel (data, samplingRate):
data is a numpy int32 array with the read data. A row represents one channel.
samplingRate is the provided sampling rate.
| Reads a 24 PCM wav file.
@param fileName name of the file
@return tupel (data, samplingRate):
data is a numpy int32 array with the read data. A row represents one channel.
samplingRate is the provided sampling rate. | [
"Reads",
"a",
"24",
"PCM",
"wav",
"file",
".",
"@param",
"fileName",
"name",
"of",
"the",
"file",
"@return",
"tupel",
"(",
"data",
"samplingRate",
")",
":",
"data",
"is",
"a",
"numpy",
"int32",
"array",
"with",
"the",
"read",
"data",
".",
"A",
"row",
... | def read24PCM(fileName):
with wave.open(fileName, 'r') as wav:
samplingRate = wav.getframerate()
data = np.zeros((wav.getnchannels(), wav.getnframes()), dtype=np.int32)
for i in range(data.shape[1]):
frame = wav.readframes(1)
for k in range(data.shape[0]):
... | [
"def",
"read24PCM",
"(",
"fileName",
")",
":",
"with",
"wave",
".",
"open",
"(",
"fileName",
",",
"'r'",
")",
"as",
"wav",
":",
"samplingRate",
"=",
"wav",
".",
"getframerate",
"(",
")",
"data",
"=",
"np",
".",
"zeros",
"(",
"(",
"wav",
".",
"getnc... | Reads a 24 PCM wav file. | [
"Reads",
"a",
"24",
"PCM",
"wav",
"file",
"."
] | [
"\"\"\"\n Reads a 24 PCM wav file.\n\n @param fileName name of the file\n @return tupel (data, samplingRate):\n data is a numpy int32 array with the read data. A row represents one channel.\n samplingRate is the provided sampling rate.\n \"\"\"",
"# Seems pretty ugly and only works in py... | [
{
"param": "fileName",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "fileName",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
f27cd42d1c2393ad54aead2a2713e716912c64b0 | Trion/pySoundToolbox | pySoundToolbox.py | [
"MIT"
] | Python | genAnalyticSignal | <not_specific> | def genAnalyticSignal(data):
"""
Generates an analytic signal to given real data (converts real signal into a complex one).
I'm using "Computing the discrete-time analytic signal via fft" by S. Lawrence Marple.
@param data real data as 24 PCM numpy array. A row represents the response of one microphone... |
Generates an analytic signal to given real data (converts real signal into a complex one).
I'm using "Computing the discrete-time analytic signal via fft" by S. Lawrence Marple.
@param data real data as 24 PCM numpy array. A row represents the response of one microphone.
@return the complex response o... | Generates an analytic signal to given real data (converts real signal into a complex one).
I'm using "Computing the discrete-time analytic signal via fft" by S. Lawrence Marple.
@param data real data as 24 PCM numpy array. A row represents the response of one microphone.
@return the complex response of the microphone ... | [
"Generates",
"an",
"analytic",
"signal",
"to",
"given",
"real",
"data",
"(",
"converts",
"real",
"signal",
"into",
"a",
"complex",
"one",
")",
".",
"I",
"'",
"m",
"using",
"\"",
"Computing",
"the",
"discrete",
"-",
"time",
"analytic",
"signal",
"via",
"f... | def genAnalyticSignal(data):
spectrum = np.fft.fft(data.flat)
n = spectrum.shape[0]
h = np.empty(n, dtype=np.complex256)
h[0] = spectrum[0]
h[n / 2] = spectrum[n / 2]
h[1:n / 2] = 2 * spectrum[1:n / 2]
h[n / 2 + 1:] = 0
analyticSignal = np.fft.ifft(h).conjugate()
return analyticSign... | [
"def",
"genAnalyticSignal",
"(",
"data",
")",
":",
"spectrum",
"=",
"np",
".",
"fft",
".",
"fft",
"(",
"data",
".",
"flat",
")",
"n",
"=",
"spectrum",
".",
"shape",
"[",
"0",
"]",
"h",
"=",
"np",
".",
"empty",
"(",
"n",
",",
"dtype",
"=",
"np",... | Generates an analytic signal to given real data (converts real signal into a complex one). | [
"Generates",
"an",
"analytic",
"signal",
"to",
"given",
"real",
"data",
"(",
"converts",
"real",
"signal",
"into",
"a",
"complex",
"one",
")",
"."
] | [
"\"\"\"\n Generates an analytic signal to given real data (converts real signal into a complex one).\n I'm using \"Computing the discrete-time analytic signal via fft\" by S. Lawrence Marple.\n\n @param data real data as 24 PCM numpy array. A row represents the response of one microphone.\n @return the ... | [
{
"param": "data",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "data",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
f27cd42d1c2393ad54aead2a2713e716912c64b0 | Trion/pySoundToolbox | pySoundToolbox.py | [
"MIT"
] | Python | onAdd | null | def onAdd(self, array):
"""
Event handler that will be executed when this source is attached to an array.
@param array MicrophoneArray object
"""
self.samplingRate = array.samplingRate |
Event handler that will be executed when this source is attached to an array.
@param array MicrophoneArray object
| Event handler that will be executed when this source is attached to an array.
@param array MicrophoneArray object | [
"Event",
"handler",
"that",
"will",
"be",
"executed",
"when",
"this",
"source",
"is",
"attached",
"to",
"an",
"array",
".",
"@param",
"array",
"MicrophoneArray",
"object"
] | def onAdd(self, array):
self.samplingRate = array.samplingRate | [
"def",
"onAdd",
"(",
"self",
",",
"array",
")",
":",
"self",
".",
"samplingRate",
"=",
"array",
".",
"samplingRate"
] | Event handler that will be executed when this source is attached to an array. | [
"Event",
"handler",
"that",
"will",
"be",
"executed",
"when",
"this",
"source",
"is",
"attached",
"to",
"an",
"array",
"."
] | [
"\"\"\"\n Event handler that will be executed when this source is attached to an array.\n\n @param array MicrophoneArray object\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "array",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "array",
"type": null,
"docstring": null,
"docstring_tokens": ... |
f27cd42d1c2393ad54aead2a2713e716912c64b0 | Trion/pySoundToolbox | pySoundToolbox.py | [
"MIT"
] | Python | onAdd | null | def onAdd(self, array):
"""
Event handler that will be executed when this source is attached to an array.
@param array MicrophoneArray object
"""
pass |
Event handler that will be executed when this source is attached to an array.
@param array MicrophoneArray object
| Event handler that will be executed when this source is attached to an array.
@param array MicrophoneArray object | [
"Event",
"handler",
"that",
"will",
"be",
"executed",
"when",
"this",
"source",
"is",
"attached",
"to",
"an",
"array",
".",
"@param",
"array",
"MicrophoneArray",
"object"
] | def onAdd(self, array):
pass | [
"def",
"onAdd",
"(",
"self",
",",
"array",
")",
":",
"pass"
] | Event handler that will be executed when this source is attached to an array. | [
"Event",
"handler",
"that",
"will",
"be",
"executed",
"when",
"this",
"source",
"is",
"attached",
"to",
"an",
"array",
"."
] | [
"\"\"\"\n Event handler that will be executed when this source is attached to an array.\n\n @param array MicrophoneArray object\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "array",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "array",
"type": null,
"docstring": null,
"docstring_tokens": ... |
f27cd42d1c2393ad54aead2a2713e716912c64b0 | Trion/pySoundToolbox | pySoundToolbox.py | [
"MIT"
] | Python | onAdd | null | def onAdd(self, array):
"""
Event handler that will be executed when this source is attached to an array.
@param array MicrophoneArray object
"""
if array.samplingRate != self.fileSamplingRate:
raise ValueError("Array sampling rate and file sampling rate must be the... |
Event handler that will be executed when this source is attached to an array.
@param array MicrophoneArray object
| Event handler that will be executed when this source is attached to an array.
@param array MicrophoneArray object | [
"Event",
"handler",
"that",
"will",
"be",
"executed",
"when",
"this",
"source",
"is",
"attached",
"to",
"an",
"array",
".",
"@param",
"array",
"MicrophoneArray",
"object"
] | def onAdd(self, array):
if array.samplingRate != self.fileSamplingRate:
raise ValueError("Array sampling rate and file sampling rate must be the same!") | [
"def",
"onAdd",
"(",
"self",
",",
"array",
")",
":",
"if",
"array",
".",
"samplingRate",
"!=",
"self",
".",
"fileSamplingRate",
":",
"raise",
"ValueError",
"(",
"\"Array sampling rate and file sampling rate must be the same!\"",
")"
] | Event handler that will be executed when this source is attached to an array. | [
"Event",
"handler",
"that",
"will",
"be",
"executed",
"when",
"this",
"source",
"is",
"attached",
"to",
"an",
"array",
"."
] | [
"\"\"\"\n Event handler that will be executed when this source is attached to an array.\n\n @param array MicrophoneArray object\n \"\"\"",
"# TODO maybe interpolate samples if sampling rates are not compatible"
] | [
{
"param": "self",
"type": null
},
{
"param": "array",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "array",
"type": null,
"docstring": null,
"docstring_tokens": ... |
f27cd42d1c2393ad54aead2a2713e716912c64b0 | Trion/pySoundToolbox | pySoundToolbox.py | [
"MIT"
] | Python | addSource | null | def addSource(self, angle, source):
"""
Adds a source that will be "recorded" by the microphone array.
@param angle angle of arrival in rad of the sound emitted by the source. The angle is relative to the x-axis of
the coordinate plane.
@param source a source object that has... |
Adds a source that will be "recorded" by the microphone array.
@param angle angle of arrival in rad of the sound emitted by the source. The angle is relative to the x-axis of
the coordinate plane.
@param source a source object that has a get and an onAdd method
| Adds a source that will be "recorded" by the microphone array.
@param angle angle of arrival in rad of the sound emitted by the source. The angle is relative to the x-axis of
the coordinate plane.
@param source a source object that has a get and an onAdd method | [
"Adds",
"a",
"source",
"that",
"will",
"be",
"\"",
"recorded",
"\"",
"by",
"the",
"microphone",
"array",
".",
"@param",
"angle",
"angle",
"of",
"arrival",
"in",
"rad",
"of",
"the",
"sound",
"emitted",
"by",
"the",
"source",
".",
"The",
"angle",
"is",
"... | def addSource(self, angle, source):
if not np.isscalar(angle):
raise ValueError('Only scalar types are allowed for angle!')
if not np.isreal(angle):
raise ValueError('angle must be a real value!')
doa = np.array([np.cos(angle), np.sin(angle)])
source.onAdd(self)
... | [
"def",
"addSource",
"(",
"self",
",",
"angle",
",",
"source",
")",
":",
"if",
"not",
"np",
".",
"isscalar",
"(",
"angle",
")",
":",
"raise",
"ValueError",
"(",
"'Only scalar types are allowed for angle!'",
")",
"if",
"not",
"np",
".",
"isreal",
"(",
"angle... | Adds a source that will be "recorded" by the microphone array. | [
"Adds",
"a",
"source",
"that",
"will",
"be",
"\"",
"recorded",
"\"",
"by",
"the",
"microphone",
"array",
"."
] | [
"\"\"\"\n Adds a source that will be \"recorded\" by the microphone array.\n\n @param angle angle of arrival in rad of the sound emitted by the source. The angle is relative to the x-axis of\n the coordinate plane.\n @param source a source object that has a get and an onAdd method\n ... | [
{
"param": "self",
"type": null
},
{
"param": "angle",
"type": null
},
{
"param": "source",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "angle",
"type": null,
"docstring": null,
"docstring_tokens": ... |
da68c4d5936377b9c6b9bf98a35fd9c60eee54e7 | wernherd/KiBoM | bomlib/units.py | [
"MIT"
] | Python | compMatch | <not_specific> | def compMatch(component):
"""
Return a normalized value and units for a given component value string
e.g. compMatch("10R2") returns (10, R)
e.g. compMatch("3.3mOhm") returns (0.0033, R)
"""
# Remove any commas
component = component.strip().replace(",", "").lower()
match = matchString()... |
Return a normalized value and units for a given component value string
e.g. compMatch("10R2") returns (10, R)
e.g. compMatch("3.3mOhm") returns (0.0033, R)
| Return a normalized value and units for a given component value string
e.g. | [
"Return",
"a",
"normalized",
"value",
"and",
"units",
"for",
"a",
"given",
"component",
"value",
"string",
"e",
".",
"g",
"."
] | def compMatch(component):
component = component.strip().replace(",", "").lower()
match = matchString()
result = re.search(match, component)
if not result:
return None
if not len(result.groups()) == 4:
return None
value, prefix, units, post = result.groups()
if post and "." no... | [
"def",
"compMatch",
"(",
"component",
")",
":",
"component",
"=",
"component",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"\",\"",
",",
"\"\"",
")",
".",
"lower",
"(",
")",
"match",
"=",
"matchString",
"(",
")",
"result",
"=",
"re",
".",
"search",
... | Return a normalized value and units for a given component value string
e.g. | [
"Return",
"a",
"normalized",
"value",
"and",
"units",
"for",
"a",
"given",
"component",
"value",
"string",
"e",
".",
"g",
"."
] | [
"\"\"\"\n Return a normalized value and units for a given component value string\n e.g. compMatch(\"10R2\") returns (10, R)\n e.g. compMatch(\"3.3mOhm\") returns (0.0033, R)\n \"\"\"",
"# Remove any commas",
"# Special case where units is in the middle of the string",
"# e.g. \"0R05\" for 0.05Ohm"... | [
{
"param": "component",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "component",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
2625452dc000acc69f96400fbb7b7ad29dde9b67 | mikejarrett/vulnerability-db | vdb/lib/nvd.py | [
"MIT"
] | Python | download_recent | <not_specific> | def download_recent(self, local_store=True):
"""Method which downloads the recent CVE gzip from NVD"""
data = self.fetch("recent")
if local_store:
self.store(data)
return data | Method which downloads the recent CVE gzip from NVD | Method which downloads the recent CVE gzip from NVD | [
"Method",
"which",
"downloads",
"the",
"recent",
"CVE",
"gzip",
"from",
"NVD"
] | def download_recent(self, local_store=True):
data = self.fetch("recent")
if local_store:
self.store(data)
return data | [
"def",
"download_recent",
"(",
"self",
",",
"local_store",
"=",
"True",
")",
":",
"data",
"=",
"self",
".",
"fetch",
"(",
"\"recent\"",
")",
"if",
"local_store",
":",
"self",
".",
"store",
"(",
"data",
")",
"return",
"data"
] | Method which downloads the recent CVE gzip from NVD | [
"Method",
"which",
"downloads",
"the",
"recent",
"CVE",
"gzip",
"from",
"NVD"
] | [
"\"\"\"Method which downloads the recent CVE gzip from NVD\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "local_store",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "local_store",
"type": null,
"docstring": null,
"docstring_tok... |
2625452dc000acc69f96400fbb7b7ad29dde9b67 | mikejarrett/vulnerability-db | vdb/lib/nvd.py | [
"MIT"
] | Python | fetch | <not_specific> | def fetch(self, year):
"""Private Method which downloads the given CVE gzip from NVD"""
url = config.nvd_url % dict(year=year)
LOG.debug("Download NVD CVE from {}".format(url))
with tempfile.NamedTemporaryFile() as tf:
try:
r = requests.get(url, stream=True)
... | Private Method which downloads the given CVE gzip from NVD | Private Method which downloads the given CVE gzip from NVD | [
"Private",
"Method",
"which",
"downloads",
"the",
"given",
"CVE",
"gzip",
"from",
"NVD"
] | def fetch(self, year):
url = config.nvd_url % dict(year=year)
LOG.debug("Download NVD CVE from {}".format(url))
with tempfile.NamedTemporaryFile() as tf:
try:
r = requests.get(url, stream=True)
except Exception:
logging.warning(f"Exception ... | [
"def",
"fetch",
"(",
"self",
",",
"year",
")",
":",
"url",
"=",
"config",
".",
"nvd_url",
"%",
"dict",
"(",
"year",
"=",
"year",
")",
"LOG",
".",
"debug",
"(",
"\"Download NVD CVE from {}\"",
".",
"format",
"(",
"url",
")",
")",
"with",
"tempfile",
"... | Private Method which downloads the given CVE gzip from NVD | [
"Private",
"Method",
"which",
"downloads",
"the",
"given",
"CVE",
"gzip",
"from",
"NVD"
] | [
"\"\"\"Private Method which downloads the given CVE gzip from NVD\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "year",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "year",
"type": null,
"docstring": null,
"docstring_tokens": [... |
2625452dc000acc69f96400fbb7b7ad29dde9b67 | mikejarrett/vulnerability-db | vdb/lib/nvd.py | [
"MIT"
] | Python | bulk_search | null | def bulk_search():
"""
Bulk search the resource instead of downloading the information
:return: Vulnerability result
"""
raise NotImplementedError |
Bulk search the resource instead of downloading the information
:return: Vulnerability result
| Bulk search the resource instead of downloading the information | [
"Bulk",
"search",
"the",
"resource",
"instead",
"of",
"downloading",
"the",
"information"
] | def bulk_search():
raise NotImplementedError | [
"def",
"bulk_search",
"(",
")",
":",
"raise",
"NotImplementedError"
] | Bulk search the resource instead of downloading the information | [
"Bulk",
"search",
"the",
"resource",
"instead",
"of",
"downloading",
"the",
"information"
] | [
"\"\"\"\n Bulk search the resource instead of downloading the information\n :return: Vulnerability result\n \"\"\""
] | [] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
112849dddd32f17fe9dde8ebab09bc86be122afd | mikejarrett/vulnerability-db | vdb/lib/gha.py | [
"MIT"
] | Python | download_recent | <not_specific> | def download_recent(self, local_store=True):
"""Method which downloads the recent CVE"""
data, page_info = self.fetch("recent")
if data and local_store:
self.store(data)
return data | Method which downloads the recent CVE | Method which downloads the recent CVE | [
"Method",
"which",
"downloads",
"the",
"recent",
"CVE"
] | def download_recent(self, local_store=True):
data, page_info = self.fetch("recent")
if data and local_store:
self.store(data)
return data | [
"def",
"download_recent",
"(",
"self",
",",
"local_store",
"=",
"True",
")",
":",
"data",
",",
"page_info",
"=",
"self",
".",
"fetch",
"(",
"\"recent\"",
")",
"if",
"data",
"and",
"local_store",
":",
"self",
".",
"store",
"(",
"data",
")",
"return",
"d... | Method which downloads the recent CVE | [
"Method",
"which",
"downloads",
"the",
"recent",
"CVE"
] | [
"\"\"\"Method which downloads the recent CVE\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "local_store",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "local_store",
"type": null,
"docstring": null,
"docstring_tok... |
112849dddd32f17fe9dde8ebab09bc86be122afd | mikejarrett/vulnerability-db | vdb/lib/gha.py | [
"MIT"
] | Python | fetch | <not_specific> | def fetch(self, type):
"""Private method to fetch the advisory data via GraphQL api"""
LOG.debug(
"Download GitHub advisory from {} with cursor {}".format(
config.gha_url, type
)
)
r = requests.post(
url=config.gha_url, json=get_query(t... | Private method to fetch the advisory data via GraphQL api | Private method to fetch the advisory data via GraphQL api | [
"Private",
"method",
"to",
"fetch",
"the",
"advisory",
"data",
"via",
"GraphQL",
"api"
] | def fetch(self, type):
LOG.debug(
"Download GitHub advisory from {} with cursor {}".format(
config.gha_url, type
)
)
r = requests.post(
url=config.gha_url, json=get_query(type=type), headers=headers
)
json_data = r.json()
... | [
"def",
"fetch",
"(",
"self",
",",
"type",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Download GitHub advisory from {} with cursor {}\"",
".",
"format",
"(",
"config",
".",
"gha_url",
",",
"type",
")",
")",
"r",
"=",
"requests",
".",
"post",
"(",
"url",
"=",
... | Private method to fetch the advisory data via GraphQL api | [
"Private",
"method",
"to",
"fetch",
"the",
"advisory",
"data",
"via",
"GraphQL",
"api"
] | [
"\"\"\"Private method to fetch the advisory data via GraphQL api\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "type",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "type",
"type": null,
"docstring": null,
"docstring_tokens": [... |
112849dddd32f17fe9dde8ebab09bc86be122afd | mikejarrett/vulnerability-db | vdb/lib/gha.py | [
"MIT"
] | Python | convert | <not_specific> | def convert(self, cve_data):
"""Convert the GitHub advisory data into Vulnerability objects"""
ret_data = []
if cve_data.get("errors"):
return ret_data, None
if cve_data.get("message") and cve_data.get("message") == "Bad credentials":
LOG.warning("GITHUB_TOKEN env... | Convert the GitHub advisory data into Vulnerability objects | Convert the GitHub advisory data into Vulnerability objects | [
"Convert",
"the",
"GitHub",
"advisory",
"data",
"into",
"Vulnerability",
"objects"
] | def convert(self, cve_data):
ret_data = []
if cve_data.get("errors"):
return ret_data, None
if cve_data.get("message") and cve_data.get("message") == "Bad credentials":
LOG.warning("GITHUB_TOKEN environment variable is invalid!")
return ret_data, None
... | [
"def",
"convert",
"(",
"self",
",",
"cve_data",
")",
":",
"ret_data",
"=",
"[",
"]",
"if",
"cve_data",
".",
"get",
"(",
"\"errors\"",
")",
":",
"return",
"ret_data",
",",
"None",
"if",
"cve_data",
".",
"get",
"(",
"\"message\"",
")",
"and",
"cve_data",... | Convert the GitHub advisory data into Vulnerability objects | [
"Convert",
"the",
"GitHub",
"advisory",
"data",
"into",
"Vulnerability",
"objects"
] | [
"\"\"\"Convert the GitHub advisory data into Vulnerability objects\"\"\"",
"# If this CVE is withdrawn continue",
"# This extract's the correct vendor based on the namespace",
"# Eg: org.springframework:spring-webflux would result in",
"# vendor: org.springframework",
"# product: spring-webflux"
] | [
{
"param": "self",
"type": null
},
{
"param": "cve_data",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "cve_data",
"type": null,
"docstring": null,
"docstring_tokens... |
01c5836eb9479a290fdac16b960410fa94df750f | mikejarrett/vulnerability-db | vdb/cli.py | [
"MIT"
] | Python | build_args | <not_specific> | def build_args():
"""
Constructs command line arguments for the vulnerability-db tool
"""
parser = argparse.ArgumentParser(
description="AppThreat's vulnerability database and package search library with a built-in file based storage"
)
parser.add_argument(
"--clean",
act... |
Constructs command line arguments for the vulnerability-db tool
| Constructs command line arguments for the vulnerability-db tool | [
"Constructs",
"command",
"line",
"arguments",
"for",
"the",
"vulnerability",
"-",
"db",
"tool"
] | def build_args():
parser = argparse.ArgumentParser(
description="AppThreat's vulnerability database and package search library with a built-in file based storage"
)
parser.add_argument(
"--clean",
action="store_true",
default=False,
dest="clean",
help="Clear t... | [
"def",
"build_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"AppThreat's vulnerability database and package search library with a built-in file based storage\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--clean\"",
",",
... | Constructs command line arguments for the vulnerability-db tool | [
"Constructs",
"command",
"line",
"arguments",
"for",
"the",
"vulnerability",
"-",
"db",
"tool"
] | [
"\"\"\"\n Constructs command line arguments for the vulnerability-db tool\n \"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
73d289a21a30fc4ae6bd763c25ec5a6502506e87 | mikejarrett/vulnerability-db | vdb/lib/db.py | [
"MIT"
] | Python | build_index | <not_specific> | def build_index(index_list):
"""This function builds two index. One with just name and version the other
including vendor (aka group) string
:param index_list:
:return: Normal index and vendor index
"""
idx = {}
vendor_idx = {}
for d in index_list:
min_version = d.get(
... | This function builds two index. One with just name and version the other
including vendor (aka group) string
:param index_list:
:return: Normal index and vendor index
| This function builds two index. One with just name and version the other
including vendor (aka group) string | [
"This",
"function",
"builds",
"two",
"index",
".",
"One",
"with",
"just",
"name",
"and",
"version",
"the",
"other",
"including",
"vendor",
"(",
"aka",
"group",
")",
"string"
] | def build_index(index_list):
idx = {}
vendor_idx = {}
for d in index_list:
min_version = d.get(
"min_affected_version_excluding", d.get("min_affected_version_including")
)
max_version = d.get(
"max_affected_version_excluding", d.get("max_affected_version_inclu... | [
"def",
"build_index",
"(",
"index_list",
")",
":",
"idx",
"=",
"{",
"}",
"vendor_idx",
"=",
"{",
"}",
"for",
"d",
"in",
"index_list",
":",
"min_version",
"=",
"d",
".",
"get",
"(",
"\"min_affected_version_excluding\"",
",",
"d",
".",
"get",
"(",
"\"min_a... | This function builds two index. | [
"This",
"function",
"builds",
"two",
"index",
"."
] | [
"\"\"\"This function builds two index. One with just name and version the other\n including vendor (aka group) string\n\n :param index_list:\n :return: Normal index and vendor index\n \"\"\""
] | [
{
"param": "index_list",
"type": null
}
] | {
"returns": [
{
"docstring": "Normal index and vendor index",
"docstring_tokens": [
"Normal",
"index",
"and",
"vendor",
"index"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "index_list",
"type": null,
... |
73d289a21a30fc4ae6bd763c25ec5a6502506e87 | mikejarrett/vulnerability-db | vdb/lib/db.py | [
"MIT"
] | Python | index_count | <not_specific> | def index_count(index_file=config.vdb_bin_index):
"""
Method to return the number of indexed items
:param index_file: Index DB file
:return: Count of the index
"""
return len(storage.stream_read(index_file)) |
Method to return the number of indexed items
:param index_file: Index DB file
:return: Count of the index
| Method to return the number of indexed items | [
"Method",
"to",
"return",
"the",
"number",
"of",
"indexed",
"items"
] | def index_count(index_file=config.vdb_bin_index):
return len(storage.stream_read(index_file)) | [
"def",
"index_count",
"(",
"index_file",
"=",
"config",
".",
"vdb_bin_index",
")",
":",
"return",
"len",
"(",
"storage",
".",
"stream_read",
"(",
"index_file",
")",
")"
] | Method to return the number of indexed items | [
"Method",
"to",
"return",
"the",
"number",
"of",
"indexed",
"items"
] | [
"\"\"\"\n Method to return the number of indexed items\n :param index_file: Index DB file\n :return: Count of the index\n \"\"\""
] | [
{
"param": "index_file",
"type": null
}
] | {
"returns": [
{
"docstring": "Count of the index",
"docstring_tokens": [
"Count",
"of",
"the",
"index"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "index_file",
"type": null,
"docstring": "Index DB file",
... |
73d289a21a30fc4ae6bd763c25ec5a6502506e87 | mikejarrett/vulnerability-db | vdb/lib/db.py | [
"MIT"
] | Python | index_search | <not_specific> | def index_search(name, version):
"""Search the index for the given package name and version
:param name: Name of the package
:param version: Package version
:return boolean True if the package should be found on the main database. False otherwise.
"""
try:
datas = bulk_index_search([{"... | Search the index for the given package name and version
:param name: Name of the package
:param version: Package version
:return boolean True if the package should be found on the main database. False otherwise.
| Search the index for the given package name and version
:param name: Name of the package
:param version: Package version
:return boolean True if the package should be found on the main database. False otherwise. | [
"Search",
"the",
"index",
"for",
"the",
"given",
"package",
"name",
"and",
"version",
":",
"param",
"name",
":",
"Name",
"of",
"the",
"package",
":",
"param",
"version",
":",
"Package",
"version",
":",
"return",
"boolean",
"True",
"if",
"the",
"package",
... | def index_search(name, version):
try:
datas = bulk_index_search([{"name": name.lower(), "version": version}])
return len(datas) > 0
except IndexError:
return False | [
"def",
"index_search",
"(",
"name",
",",
"version",
")",
":",
"try",
":",
"datas",
"=",
"bulk_index_search",
"(",
"[",
"{",
"\"name\"",
":",
"name",
".",
"lower",
"(",
")",
",",
"\"version\"",
":",
"version",
"}",
"]",
")",
"return",
"len",
"(",
"dat... | Search the index for the given package name and version
:param name: Name of the package
:param version: Package version | [
"Search",
"the",
"index",
"for",
"the",
"given",
"package",
"name",
"and",
"version",
":",
"param",
"name",
":",
"Name",
"of",
"the",
"package",
":",
"param",
"version",
":",
"Package",
"version"
] | [
"\"\"\"Search the index for the given package name and version\n\n :param name: Name of the package\n :param version: Package version\n\n :return boolean True if the package should be found on the main database. False otherwise.\n \"\"\""
] | [
{
"param": "name",
"type": null
},
{
"param": "version",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "name",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "version",
"type": null,
"docstring": null,
"docstring_tokens"... |
73d289a21a30fc4ae6bd763c25ec5a6502506e87 | mikejarrett/vulnerability-db | vdb/lib/db.py | [
"MIT"
] | Python | pkg_search | <not_specific> | def pkg_search(db, name, version):
"""Search for a given package and convert into Vulnerability Occurence
:param db: db instance
:param name: Name of the package
:param version: Package version
:return List of vulnerability occurrence or none
"""
datas = storage.stream_bulk_search(
... | Search for a given package and convert into Vulnerability Occurence
:param db: db instance
:param name: Name of the package
:param version: Package version
:return List of vulnerability occurrence or none
|
:return List of vulnerability occurrence or none | [
":",
"return",
"List",
"of",
"vulnerability",
"occurrence",
"or",
"none"
] | def pkg_search(db, name, version):
datas = storage.stream_bulk_search(
[name.lower() + "|" + version], _key_func, db_file=db["db_file"]
)
return convert_to_occurrence(datas) | [
"def",
"pkg_search",
"(",
"db",
",",
"name",
",",
"version",
")",
":",
"datas",
"=",
"storage",
".",
"stream_bulk_search",
"(",
"[",
"name",
".",
"lower",
"(",
")",
"+",
"\"|\"",
"+",
"version",
"]",
",",
"_key_func",
",",
"db_file",
"=",
"db",
"[",
... | Search for a given package and convert into Vulnerability Occurence
:param db: db instance
:param name: Name of the package
:param version: Package version | [
"Search",
"for",
"a",
"given",
"package",
"and",
"convert",
"into",
"Vulnerability",
"Occurence",
":",
"param",
"db",
":",
"db",
"instance",
":",
"param",
"name",
":",
"Name",
"of",
"the",
"package",
":",
"param",
"version",
":",
"Package",
"version"
] | [
"\"\"\"Search for a given package and convert into Vulnerability Occurence\n\n :param db: db instance\n :param name: Name of the package\n :param version: Package version\n\n :return List of vulnerability occurrence or none\n \"\"\""
] | [
{
"param": "db",
"type": null
},
{
"param": "name",
"type": null
},
{
"param": "version",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "db",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "name",
"type": null,
"docstring": null,
"docstring_tokens": [],... |
73d289a21a30fc4ae6bd763c25ec5a6502506e87 | mikejarrett/vulnerability-db | vdb/lib/db.py | [
"MIT"
] | Python | vendor_pkg_search | <not_specific> | def vendor_pkg_search(db, vendor, name, version):
"""Search for a given package and convert into Vulnerability Occurence
:param db: db instance
:param vendor: Vendor name
:param name: Name of the package
:param version: Package version
:return List of vulnerability occurrence or none
"""
... | Search for a given package and convert into Vulnerability Occurence
:param db: db instance
:param vendor: Vendor name
:param name: Name of the package
:param version: Package version
:return List of vulnerability occurrence or none
|
:return List of vulnerability occurrence or none | [
":",
"return",
"List",
"of",
"vulnerability",
"occurrence",
"or",
"none"
] | def vendor_pkg_search(db, vendor, name, version):
datas = storage.stream_bulk_search(
[vendor.lower() + "|" + name.lower() + "|" + version],
_key_func,
db_file=db["db_file"],
)
return convert_to_occurrence(datas) | [
"def",
"vendor_pkg_search",
"(",
"db",
",",
"vendor",
",",
"name",
",",
"version",
")",
":",
"datas",
"=",
"storage",
".",
"stream_bulk_search",
"(",
"[",
"vendor",
".",
"lower",
"(",
")",
"+",
"\"|\"",
"+",
"name",
".",
"lower",
"(",
")",
"+",
"\"|\... | Search for a given package and convert into Vulnerability Occurence
:param db: db instance
:param vendor: Vendor name
:param name: Name of the package
:param version: Package version | [
"Search",
"for",
"a",
"given",
"package",
"and",
"convert",
"into",
"Vulnerability",
"Occurence",
":",
"param",
"db",
":",
"db",
"instance",
":",
"param",
"vendor",
":",
"Vendor",
"name",
":",
"param",
"name",
":",
"Name",
"of",
"the",
"package",
":",
"p... | [
"\"\"\"Search for a given package and convert into Vulnerability Occurence\n\n :param db: db instance\n :param vendor: Vendor name\n :param name: Name of the package\n :param version: Package version\n\n :return List of vulnerability occurrence or none\n \"\"\""
] | [
{
"param": "db",
"type": null
},
{
"param": "vendor",
"type": null
},
{
"param": "name",
"type": null
},
{
"param": "version",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "db",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "vendor",
"type": null,
"docstring": null,
"docstring_tokens": [... |
73d289a21a30fc4ae6bd763c25ec5a6502506e87 | mikejarrett/vulnerability-db | vdb/lib/db.py | [
"MIT"
] | Python | pkg_bulk_search | <not_specific> | def pkg_bulk_search(db, pkg_key_list):
"""Bulk search for a given package and convert into Vulnerability Occurence
:param db: db instance
:param pkg_key_list: List of package name|version keys
:return List of vulnerability occurence or none
"""
datas = storage.stream_bulk_search(pkg_key_list, ... | Bulk search for a given package and convert into Vulnerability Occurence
:param db: db instance
:param pkg_key_list: List of package name|version keys
:return List of vulnerability occurence or none
| Bulk search for a given package and convert into Vulnerability Occurence
:param db: db instance
:param pkg_key_list: List of package name|version keys
:return List of vulnerability occurence or none | [
"Bulk",
"search",
"for",
"a",
"given",
"package",
"and",
"convert",
"into",
"Vulnerability",
"Occurence",
":",
"param",
"db",
":",
"db",
"instance",
":",
"param",
"pkg_key_list",
":",
"List",
"of",
"package",
"name|version",
"keys",
":",
"return",
"List",
"o... | def pkg_bulk_search(db, pkg_key_list):
datas = storage.stream_bulk_search(pkg_key_list, _key_func, db_file=db["db_file"])
return convert_to_occurrence(datas) | [
"def",
"pkg_bulk_search",
"(",
"db",
",",
"pkg_key_list",
")",
":",
"datas",
"=",
"storage",
".",
"stream_bulk_search",
"(",
"pkg_key_list",
",",
"_key_func",
",",
"db_file",
"=",
"db",
"[",
"\"db_file\"",
"]",
")",
"return",
"convert_to_occurrence",
"(",
"dat... | Bulk search for a given package and convert into Vulnerability Occurence
:param db: db instance
:param pkg_key_list: List of package name|version keys | [
"Bulk",
"search",
"for",
"a",
"given",
"package",
"and",
"convert",
"into",
"Vulnerability",
"Occurence",
":",
"param",
"db",
":",
"db",
"instance",
":",
"param",
"pkg_key_list",
":",
"List",
"of",
"package",
"name|version",
"keys"
] | [
"\"\"\"Bulk search for a given package and convert into Vulnerability Occurence\n\n :param db: db instance\n :param pkg_key_list: List of package name|version keys\n\n :return List of vulnerability occurence or none\n \"\"\""
] | [
{
"param": "db",
"type": null
},
{
"param": "pkg_key_list",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "db",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pkg_key_list",
"type": null,
"docstring": null,
"docstring_toke... |
47aa4848bde8189b61f1739cfa4105bf0b97a725 | mikejarrett/vulnerability-db | vdb/lib/__init__.py | [
"MIT"
] | Python | convert_time | <not_specific> | def convert_time(time_str):
"""Convert iso string to date time object
:param time_str: String time to convert
"""
try:
dt = datetime.strptime(time_str, "%Y-%m-%dT%H:%Mz")
return dt
except Exception:
return time_str | Convert iso string to date time object
:param time_str: String time to convert
| Convert iso string to date time object | [
"Convert",
"iso",
"string",
"to",
"date",
"time",
"object"
] | def convert_time(time_str):
try:
dt = datetime.strptime(time_str, "%Y-%m-%dT%H:%Mz")
return dt
except Exception:
return time_str | [
"def",
"convert_time",
"(",
"time_str",
")",
":",
"try",
":",
"dt",
"=",
"datetime",
".",
"strptime",
"(",
"time_str",
",",
"\"%Y-%m-%dT%H:%Mz\"",
")",
"return",
"dt",
"except",
"Exception",
":",
"return",
"time_str"
] | Convert iso string to date time object | [
"Convert",
"iso",
"string",
"to",
"date",
"time",
"object"
] | [
"\"\"\"Convert iso string to date time object\n\n :param time_str: String time to convert\n \"\"\""
] | [
{
"param": "time_str",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "time_str",
"type": null,
"docstring": "String time to convert",
"docstring_tokens": [
"String",
"time",
"to",
"convert"
],
"default": null,
"is_optional": null
}
],
"ou... |
e4d083b0ff21ad042f1e525c4beaff7f559add36 | mikejarrett/vulnerability-db | vdb/lib/utils.py | [
"MIT"
] | Python | load | <not_specific> | def load(d):
"""Parses a python object from a JSON string. Every Object which should be loaded needs a constuctor that doesn't need any Arguments.
Arguments: Dict object; the module which contains the class, the parsed object is instance of."""
def _load(d):
if isinstance(d, list):
li =... | Parses a python object from a JSON string. Every Object which should be loaded needs a constuctor that doesn't need any Arguments.
Arguments: Dict object; the module which contains the class, the parsed object is instance of. | Parses a python object from a JSON string. Every Object which should be loaded needs a constuctor that doesn't need any Arguments.
Arguments: Dict object; the module which contains the class, the parsed object is instance of. | [
"Parses",
"a",
"python",
"object",
"from",
"a",
"JSON",
"string",
".",
"Every",
"Object",
"which",
"should",
"be",
"loaded",
"needs",
"a",
"constuctor",
"that",
"doesn",
"'",
"t",
"need",
"any",
"Arguments",
".",
"Arguments",
":",
"Dict",
"object",
";",
... | def load(d):
def _load(d):
if isinstance(d, list):
li = []
for item in d:
li.append(_load(item))
return li
elif isinstance(d, dict) and "type" in d:
t = d["type"]
if t == "datetime":
if hasattr(datetime, "f... | [
"def",
"load",
"(",
"d",
")",
":",
"def",
"_load",
"(",
"d",
")",
":",
"if",
"isinstance",
"(",
"d",
",",
"list",
")",
":",
"li",
"=",
"[",
"]",
"for",
"item",
"in",
"d",
":",
"li",
".",
"append",
"(",
"_load",
"(",
"item",
")",
")",
"retur... | Parses a python object from a JSON string. | [
"Parses",
"a",
"python",
"object",
"from",
"a",
"JSON",
"string",
"."
] | [
"\"\"\"Parses a python object from a JSON string. Every Object which should be loaded needs a constuctor that doesn't need any Arguments.\n Arguments: Dict object; the module which contains the class, the parsed object is instance of.\"\"\"",
"# object",
"# dict"
] | [
{
"param": "d",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "d",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
e4d083b0ff21ad042f1e525c4beaff7f559add36 | mikejarrett/vulnerability-db | vdb/lib/utils.py | [
"MIT"
] | Python | dump | <not_specific> | def dump(obj):
"""Dumps a python object to a JSON string. Argument: Python object"""
def _dump(obj, path):
if isinstance(obj, list):
li = []
i = 0
for item in obj:
li.append(_dump(item, path + "/[" + str(i) + "]"))
i += 1
r... | Dumps a python object to a JSON string. Argument: Python object | Dumps a python object to a JSON string. Argument: Python object | [
"Dumps",
"a",
"python",
"object",
"to",
"a",
"JSON",
"string",
".",
"Argument",
":",
"Python",
"object"
] | def dump(obj):
def _dump(obj, path):
if isinstance(obj, list):
li = []
i = 0
for item in obj:
li.append(_dump(item, path + "/[" + str(i) + "]"))
i += 1
return li
elif isinstance(obj, Enum):
d = {}
... | [
"def",
"dump",
"(",
"obj",
")",
":",
"def",
"_dump",
"(",
"obj",
",",
"path",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"li",
"=",
"[",
"]",
"i",
"=",
"0",
"for",
"item",
"in",
"obj",
":",
"li",
".",
"append",
"(",
"_... | Dumps a python object to a JSON string. | [
"Dumps",
"a",
"python",
"object",
"to",
"a",
"JSON",
"string",
"."
] | [
"\"\"\"Dumps a python object to a JSON string. Argument: Python object\"\"\"",
"# Enum",
"# dict",
"# datetime"
] | [
{
"param": "obj",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "obj",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
e4d083b0ff21ad042f1e525c4beaff7f559add36 | mikejarrett/vulnerability-db | vdb/lib/utils.py | [
"MIT"
] | Python | serialize_vuln_list | <not_specific> | def serialize_vuln_list(datas):
"""Serialize vulnerability data list to help with storage
:param datas: Data list to store
:return List of serialized data
"""
data_list = []
for data in datas:
ddata = data
details = None
if type(data) != "dict":
ddata = vars(... | Serialize vulnerability data list to help with storage
:param datas: Data list to store
:return List of serialized data
| Serialize vulnerability data list to help with storage
:param datas: Data list to store
:return List of serialized data | [
"Serialize",
"vulnerability",
"data",
"list",
"to",
"help",
"with",
"storage",
":",
"param",
"datas",
":",
"Data",
"list",
"to",
"store",
":",
"return",
"List",
"of",
"serialized",
"data"
] | def serialize_vuln_list(datas):
data_list = []
for data in datas:
ddata = data
details = None
if type(data) != "dict":
ddata = vars(data)
details = data.details
else:
details = data["details"]
for vuln_detail in details:
dat... | [
"def",
"serialize_vuln_list",
"(",
"datas",
")",
":",
"data_list",
"=",
"[",
"]",
"for",
"data",
"in",
"datas",
":",
"ddata",
"=",
"data",
"details",
"=",
"None",
"if",
"type",
"(",
"data",
")",
"!=",
"\"dict\"",
":",
"ddata",
"=",
"vars",
"(",
"data... | Serialize vulnerability data list to help with storage
:param datas: Data list to store
:return List of serialized data | [
"Serialize",
"vulnerability",
"data",
"list",
"to",
"help",
"with",
"storage",
":",
"param",
"datas",
":",
"Data",
"list",
"to",
"store",
":",
"return",
"List",
"of",
"serialized",
"data"
] | [
"\"\"\"Serialize vulnerability data list to help with storage\n\n :param datas: Data list to store\n :return List of serialized data\n \"\"\""
] | [
{
"param": "datas",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "datas",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
e4d083b0ff21ad042f1e525c4beaff7f559add36 | mikejarrett/vulnerability-db | vdb/lib/utils.py | [
"MIT"
] | Python | semver_compatible | <not_specific> | def semver_compatible(compare_ver, min_version, max_version):
"""Method to check if all version numbers are semver compatible"""
return (
VersionInfo.isvalid(compare_ver)
and VersionInfo.isvalid(min_version)
and VersionInfo.isvalid(max_version)
) | Method to check if all version numbers are semver compatible | Method to check if all version numbers are semver compatible | [
"Method",
"to",
"check",
"if",
"all",
"version",
"numbers",
"are",
"semver",
"compatible"
] | def semver_compatible(compare_ver, min_version, max_version):
return (
VersionInfo.isvalid(compare_ver)
and VersionInfo.isvalid(min_version)
and VersionInfo.isvalid(max_version)
) | [
"def",
"semver_compatible",
"(",
"compare_ver",
",",
"min_version",
",",
"max_version",
")",
":",
"return",
"(",
"VersionInfo",
".",
"isvalid",
"(",
"compare_ver",
")",
"and",
"VersionInfo",
".",
"isvalid",
"(",
"min_version",
")",
"and",
"VersionInfo",
".",
"... | Method to check if all version numbers are semver compatible | [
"Method",
"to",
"check",
"if",
"all",
"version",
"numbers",
"are",
"semver",
"compatible"
] | [
"\"\"\"Method to check if all version numbers are semver compatible\"\"\""
] | [
{
"param": "compare_ver",
"type": null
},
{
"param": "min_version",
"type": null
},
{
"param": "max_version",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "compare_ver",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "min_version",
"type": null,
"docstring": null,
"docstr... |
e4d083b0ff21ad042f1e525c4beaff7f559add36 | mikejarrett/vulnerability-db | vdb/lib/utils.py | [
"MIT"
] | Python | convert_to_semver | <not_specific> | def convert_to_semver(version):
"""
Convert an incomplete version string into a semver-compatible VersionInfo
object
* Tries to detect a "basic" version string (``major.minor.patch``).
* If not enough components can be found, missing components are
set to zero to obtain a valid semver versi... |
Convert an incomplete version string into a semver-compatible VersionInfo
object
* Tries to detect a "basic" version string (``major.minor.patch``).
* If not enough components can be found, missing components are
set to zero to obtain a valid semver version.
:param str version: the versio... | Convert an incomplete version string into a semver-compatible VersionInfo
object
Tries to detect a "basic" version string (``major.minor.patch``).
If not enough components can be found, missing components are
set to zero to obtain a valid semver version. | [
"Convert",
"an",
"incomplete",
"version",
"string",
"into",
"a",
"semver",
"-",
"compatible",
"VersionInfo",
"object",
"Tries",
"to",
"detect",
"a",
"\"",
"basic",
"\"",
"version",
"string",
"(",
"`",
"`",
"major",
".",
"minor",
".",
"patch",
"`",
"`",
"... | def convert_to_semver(version):
match = BASEVERSION.search(version)
if not match:
return (None, version)
ver = {
key: 0 if value is None else value for key, value in match.groupdict().items()
}
if ver.get("prerelease"):
try:
prefloat = float(ver.get("prerelease"))... | [
"def",
"convert_to_semver",
"(",
"version",
")",
":",
"match",
"=",
"BASEVERSION",
".",
"search",
"(",
"version",
")",
"if",
"not",
"match",
":",
"return",
"(",
"None",
",",
"version",
")",
"ver",
"=",
"{",
"key",
":",
"0",
"if",
"value",
"is",
"None... | Convert an incomplete version string into a semver-compatible VersionInfo
object | [
"Convert",
"an",
"incomplete",
"version",
"string",
"into",
"a",
"semver",
"-",
"compatible",
"VersionInfo",
"object"
] | [
"\"\"\"\n Convert an incomplete version string into a semver-compatible VersionInfo\n object\n\n * Tries to detect a \"basic\" version string (``major.minor.patch``).\n * If not enough components can be found, missing components are\n set to zero to obtain a valid semver version.\n\n :param st... | [
{
"param": "version",
"type": null
}
] | {
"returns": [
{
"docstring": "a tuple with a :class:`VersionInfo` instance (or ``None``\nif it's not a version) and the rest of the string which doesn't\nbelong to a basic version.",
"docstring_tokens": [
"a",
"tuple",
"with",
"a",
":",
"class",
... |
e4d083b0ff21ad042f1e525c4beaff7f559add36 | mikejarrett/vulnerability-db | vdb/lib/utils.py | [
"MIT"
] | Python | parse_cpe | <not_specific> | def parse_cpe(cpe_uri):
"""
Parse cpe uri to return the parts
:param cpe_uri: CPE to parse
:return: Individual parts
"""
parts = CPE_FULL_REGEX.match(cpe_uri)
if parts:
return (
parts.group("vendor"),
parts.group("package"),
parts.group("version"),... |
Parse cpe uri to return the parts
:param cpe_uri: CPE to parse
:return: Individual parts
| Parse cpe uri to return the parts | [
"Parse",
"cpe",
"uri",
"to",
"return",
"the",
"parts"
] | def parse_cpe(cpe_uri):
parts = CPE_FULL_REGEX.match(cpe_uri)
if parts:
return (
parts.group("vendor"),
parts.group("package"),
parts.group("version"),
parts.group("cve_type"),
)
else:
return "", None, None, None | [
"def",
"parse_cpe",
"(",
"cpe_uri",
")",
":",
"parts",
"=",
"CPE_FULL_REGEX",
".",
"match",
"(",
"cpe_uri",
")",
"if",
"parts",
":",
"return",
"(",
"parts",
".",
"group",
"(",
"\"vendor\"",
")",
",",
"parts",
".",
"group",
"(",
"\"package\"",
")",
",",... | Parse cpe uri to return the parts | [
"Parse",
"cpe",
"uri",
"to",
"return",
"the",
"parts"
] | [
"\"\"\"\n Parse cpe uri to return the parts\n :param cpe_uri: CPE to parse\n :return: Individual parts\n \"\"\""
] | [
{
"param": "cpe_uri",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "cpe_uri",
"type": null,
"docstring": "CPE to parse",
"docstring_tokens": [
"CPE",
"to",
"pa... |
e4d083b0ff21ad042f1e525c4beaff7f559add36 | mikejarrett/vulnerability-db | vdb/lib/utils.py | [
"MIT"
] | Python | convert_to_occurrence | <not_specific> | def convert_to_occurrence(datas):
"""Method to parse raw search result and convert to Vulnerability occurence
:param datas: Search results from database
:return List of vulnerability occurence
"""
data_list = []
id_list = []
for d in datas:
vobj = load(d)
vdetails = vobj["de... | Method to parse raw search result and convert to Vulnerability occurence
:param datas: Search results from database
:return List of vulnerability occurence
| Method to parse raw search result and convert to Vulnerability occurence
:param datas: Search results from database
:return List of vulnerability occurence | [
"Method",
"to",
"parse",
"raw",
"search",
"result",
"and",
"convert",
"to",
"Vulnerability",
"occurence",
":",
"param",
"datas",
":",
"Search",
"results",
"from",
"database",
":",
"return",
"List",
"of",
"vulnerability",
"occurence"
] | def convert_to_occurrence(datas):
data_list = []
id_list = []
for d in datas:
vobj = load(d)
vdetails = vobj["details"]
package_type = ""
package = ""
cpe_uri = ""
if isinstance(vdetails, dict):
package_type = vdetails["package_type"]
p... | [
"def",
"convert_to_occurrence",
"(",
"datas",
")",
":",
"data_list",
"=",
"[",
"]",
"id_list",
"=",
"[",
"]",
"for",
"d",
"in",
"datas",
":",
"vobj",
"=",
"load",
"(",
"d",
")",
"vdetails",
"=",
"vobj",
"[",
"\"details\"",
"]",
"package_type",
"=",
"... | Method to parse raw search result and convert to Vulnerability occurence
:param datas: Search results from database
:return List of vulnerability occurence | [
"Method",
"to",
"parse",
"raw",
"search",
"result",
"and",
"convert",
"to",
"Vulnerability",
"occurence",
":",
"param",
"datas",
":",
"Search",
"results",
"from",
"database",
":",
"return",
"List",
"of",
"vulnerability",
"occurence"
] | [
"\"\"\"Method to parse raw search result and convert to Vulnerability occurence\n\n :param datas: Search results from database\n :return List of vulnerability occurence\n \"\"\"",
"# Filter duplicates for the same package with the same id"
] | [
{
"param": "datas",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "datas",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
e4d083b0ff21ad042f1e525c4beaff7f559add36 | mikejarrett/vulnerability-db | vdb/lib/utils.py | [
"MIT"
] | Python | fix_text | <not_specific> | def fix_text(text):
"""
Method to fix up bad text from feeds
:param text: Text to cleanup
:return: Fixed text
"""
if text is None:
text = ""
text = re.sub(r"[]^\\-]", " ", text)
return text |
Method to fix up bad text from feeds
:param text: Text to cleanup
:return: Fixed text
| Method to fix up bad text from feeds | [
"Method",
"to",
"fix",
"up",
"bad",
"text",
"from",
"feeds"
] | def fix_text(text):
if text is None:
text = ""
text = re.sub(r"[]^\\-]", " ", text)
return text | [
"def",
"fix_text",
"(",
"text",
")",
":",
"if",
"text",
"is",
"None",
":",
"text",
"=",
"\"\"",
"text",
"=",
"re",
".",
"sub",
"(",
"r\"[]^\\\\-]\"",
",",
"\" \"",
",",
"text",
")",
"return",
"text"
] | Method to fix up bad text from feeds | [
"Method",
"to",
"fix",
"up",
"bad",
"text",
"from",
"feeds"
] | [
"\"\"\"\n Method to fix up bad text from feeds\n :param text: Text to cleanup\n :return: Fixed text\n \"\"\""
] | [
{
"param": "text",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "text",
"type": null,
"docstring": "Text to cleanup",
"docstring_tokens": [
"Text",
"to",
"c... |
e4d083b0ff21ad042f1e525c4beaff7f559add36 | mikejarrett/vulnerability-db | vdb/lib/utils.py | [
"MIT"
] | Python | convert_md_references | <not_specific> | def convert_md_references(md_text):
"""Method to convert markdown list to references url format"""
if not md_text:
return []
ref_list = []
md_text = md_text.replace("\n", "").strip()
for ref in md_text.split("- "):
if not ref:
continue
parts = ref.split("](")
... | Method to convert markdown list to references url format | Method to convert markdown list to references url format | [
"Method",
"to",
"convert",
"markdown",
"list",
"to",
"references",
"url",
"format"
] | def convert_md_references(md_text):
if not md_text:
return []
ref_list = []
md_text = md_text.replace("\n", "").strip()
for ref in md_text.split("- "):
if not ref:
continue
parts = ref.split("](")
if len(parts) == 2:
ref_list.append(
... | [
"def",
"convert_md_references",
"(",
"md_text",
")",
":",
"if",
"not",
"md_text",
":",
"return",
"[",
"]",
"ref_list",
"=",
"[",
"]",
"md_text",
"=",
"md_text",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",
".",
"strip",
"(",
")",
"for",
"ref",
"... | Method to convert markdown list to references url format | [
"Method",
"to",
"convert",
"markdown",
"list",
"to",
"references",
"url",
"format"
] | [
"\"\"\"Method to convert markdown list to references url format\"\"\""
] | [
{
"param": "md_text",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "md_text",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
b7f9c6e414b1a9e17558f72e9211fad878b9e0b1 | filelib/filelib-python | filelib/client.py | [
"MIT"
] | Python | is_access_token | <not_specific> | def is_access_token(self):
"""
Check if an ACTIVE Access Token is present
:return: Boolean True|False
"""
# TODO: Verify Expiration
try:
assert self.__ACCESS_TOKEN is not None, "NO_ACCESS_TOKEN_PRESENT"
assert self.__ACCESS_TOKEN_EXPIRATION and dat... |
Check if an ACTIVE Access Token is present
:return: Boolean True|False
| Check if an ACTIVE Access Token is present | [
"Check",
"if",
"an",
"ACTIVE",
"Access",
"Token",
"is",
"present"
] | def is_access_token(self):
try:
assert self.__ACCESS_TOKEN is not None, "NO_ACCESS_TOKEN_PRESENT"
assert self.__ACCESS_TOKEN_EXPIRATION and datetime.now(
tz=pytz.UTC) < self.__ACCESS_TOKEN_EXPIRATION, "Expired"
except AssertionError as e:
return False
... | [
"def",
"is_access_token",
"(",
"self",
")",
":",
"try",
":",
"assert",
"self",
".",
"__ACCESS_TOKEN",
"is",
"not",
"None",
",",
"\"NO_ACCESS_TOKEN_PRESENT\"",
"assert",
"self",
".",
"__ACCESS_TOKEN_EXPIRATION",
"and",
"datetime",
".",
"now",
"(",
"tz",
"=",
"p... | Check if an ACTIVE Access Token is present | [
"Check",
"if",
"an",
"ACTIVE",
"Access",
"Token",
"is",
"present"
] | [
"\"\"\"\n Check if an ACTIVE Access Token is present\n :return: Boolean True|False\n \"\"\"",
"# TODO: Verify Expiration"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
b7f9c6e414b1a9e17558f72e9211fad878b9e0b1 | filelib/filelib-python | filelib/client.py | [
"MIT"
] | Python | acquire_access_token | null | def acquire_access_token(self):
"""
Acquire an ACCESS TOKEN by utilizing JWT(pyJwt)
make a POST request to AUTHENTICATION_URL to acquire an access_token
:return: None
"""
# Make a pseudo request temporarily to acquire access_token
jwt_headers = {}
jwt_pa... |
Acquire an ACCESS TOKEN by utilizing JWT(pyJwt)
make a POST request to AUTHENTICATION_URL to acquire an access_token
:return: None
| Acquire an ACCESS TOKEN by utilizing JWT(pyJwt)
make a POST request to AUTHENTICATION_URL to acquire an access_token | [
"Acquire",
"an",
"ACCESS",
"TOKEN",
"by",
"utilizing",
"JWT",
"(",
"pyJwt",
")",
"make",
"a",
"POST",
"request",
"to",
"AUTHENTICATION_URL",
"to",
"acquire",
"an",
"access_token"
] | def acquire_access_token(self):
jwt_headers = {}
jwt_payload = {
"filelib_api_key": self.__FILELIB_API_KEY,
'request_client_source': REQUEST_CLIENT_SOURCE
}
jwt_encoded = jwt.encode(
payload=jwt_payload,
key=self.__FILELIB_API_SECRET,
... | [
"def",
"acquire_access_token",
"(",
"self",
")",
":",
"jwt_headers",
"=",
"{",
"}",
"jwt_payload",
"=",
"{",
"\"filelib_api_key\"",
":",
"self",
".",
"__FILELIB_API_KEY",
",",
"'request_client_source'",
":",
"REQUEST_CLIENT_SOURCE",
"}",
"jwt_encoded",
"=",
"jwt",
... | Acquire an ACCESS TOKEN by utilizing JWT(pyJwt)
make a POST request to AUTHENTICATION_URL to acquire an access_token | [
"Acquire",
"an",
"ACCESS",
"TOKEN",
"by",
"utilizing",
"JWT",
"(",
"pyJwt",
")",
"make",
"a",
"POST",
"request",
"to",
"AUTHENTICATION_URL",
"to",
"acquire",
"an",
"access_token"
] | [
"\"\"\"\n Acquire an ACCESS TOKEN by utilizing JWT(pyJwt)\n make a POST request to AUTHENTICATION_URL to acquire an access_token\n :return: None\n \"\"\"",
"# Make a pseudo request temporarily to acquire access_token"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
b7f9c6e414b1a9e17558f72e9211fad878b9e0b1 | filelib/filelib-python | filelib/client.py | [
"MIT"
] | Python | __set_pool_config | null | def __set_pool_config(self, config):
"""
this is to be used internally by the Client class
:param config:
:return:
"""
self.__config.update(config) |
this is to be used internally by the Client class
:param config:
:return:
| this is to be used internally by the Client class | [
"this",
"is",
"to",
"be",
"used",
"internally",
"by",
"the",
"Client",
"class"
] | def __set_pool_config(self, config):
self.__config.update(config) | [
"def",
"__set_pool_config",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"__config",
".",
"update",
"(",
"config",
")"
] | this is to be used internally by the Client class | [
"this",
"is",
"to",
"be",
"used",
"internally",
"by",
"the",
"Client",
"class"
] | [
"\"\"\"\n this is to be used internally by the Client class\n :param config:\n :return:\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "config",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
b7f9c6e414b1a9e17558f72e9211fad878b9e0b1 | filelib/filelib-python | filelib/client.py | [
"MIT"
] | Python | __prep_file_to_upload | <not_specific> | def __prep_file_to_upload(self, file):
"""
Read file, if parm is string into memory for upload
Or read the file-like object from memory for upload.
https://2.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
:param file: str -> Path to the file that wil... |
Read file, if parm is string into memory for upload
Or read the file-like object from memory for upload.
https://2.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
:param file: str -> Path to the file that will be uploaded.
:return:[
... | Read file, if parm is string into memory for upload
Or read the file-like object from memory for upload. | [
"Read",
"file",
"if",
"parm",
"is",
"string",
"into",
"memory",
"for",
"upload",
"Or",
"read",
"the",
"file",
"-",
"like",
"object",
"from",
"memory",
"for",
"upload",
"."
] | def __prep_file_to_upload(self, file):
if type(file) is str:
content = open(file, 'rb')
file_name = content.name
else:
content = file.read()
file_name = file.name
file_name = os.path.basename(file_name)
if not file_name:
file_na... | [
"def",
"__prep_file_to_upload",
"(",
"self",
",",
"file",
")",
":",
"if",
"type",
"(",
"file",
")",
"is",
"str",
":",
"content",
"=",
"open",
"(",
"file",
",",
"'rb'",
")",
"file_name",
"=",
"content",
".",
"name",
"else",
":",
"content",
"=",
"file"... | Read file, if parm is string into memory for upload
Or read the file-like object from memory for upload. | [
"Read",
"file",
"if",
"parm",
"is",
"string",
"into",
"memory",
"for",
"upload",
"Or",
"read",
"the",
"file",
"-",
"like",
"object",
"from",
"memory",
"for",
"upload",
"."
] | [
"\"\"\"\n Read file, if parm is string into memory for upload\n Or read the file-like object from memory for upload.\n https://2.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file\n :param file: str -> Path to the file that will be uploaded.\n\n :return:[... | [
{
"param": "self",
"type": null
},
{
"param": "file",
"type": null
}
] | {
"returns": [
{
"docstring": "[\n(FORM_FIELD_FILE_NAME, open('path_to_file/pyfile-1.pdf', 'rb')),\n(FORM_FIELD_FILE_NAME, open('path_to_file/test', 'rb')),\n(FORM_FIELD_FILE_NAME, open('path_to_file/10mb.jpg', 'rb')),\n(FORM_FIELD_FILE_NAME, open('path_to_file/nasa2.jpg', 'rb')),\n(FORM_FIELD_FILE_NAME, op... |
b7f9c6e414b1a9e17558f72e9211fad878b9e0b1 | filelib/filelib-python | filelib/client.py | [
"MIT"
] | Python | __upload | <not_specific> | def __upload(self):
"""
Process files queued for uploading.
Also read one file at a time into memory
Send(POST|PUT) one file at a time
:return: Dict(JSON) response
"""
# files = self.__pre_files_to_upload()
out = []
for file in self.get_files():
... |
Process files queued for uploading.
Also read one file at a time into memory
Send(POST|PUT) one file at a time
:return: Dict(JSON) response
| Process files queued for uploading.
Also read one file at a time into memory
Send(POST|PUT) one file at a time | [
"Process",
"files",
"queued",
"for",
"uploading",
".",
"Also",
"read",
"one",
"file",
"at",
"a",
"time",
"into",
"memory",
"Send",
"(",
"POST|PUT",
")",
"one",
"file",
"at",
"a",
"time"
] | def __upload(self):
out = []
for file in self.get_files():
out.append(self.__upload_file(file))
return out | [
"def",
"__upload",
"(",
"self",
")",
":",
"out",
"=",
"[",
"]",
"for",
"file",
"in",
"self",
".",
"get_files",
"(",
")",
":",
"out",
".",
"append",
"(",
"self",
".",
"__upload_file",
"(",
"file",
")",
")",
"return",
"out"
] | Process files queued for uploading. | [
"Process",
"files",
"queued",
"for",
"uploading",
"."
] | [
"\"\"\"\n Process files queued for uploading.\n Also read one file at a time into memory\n Send(POST|PUT) one file at a time\n\n :return: Dict(JSON) response\n \"\"\"",
"# files = self.__pre_files_to_upload()"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
b7f9c6e414b1a9e17558f72e9211fad878b9e0b1 | filelib/filelib-python | filelib/client.py | [
"MIT"
] | Python | upload | <not_specific> | def upload(self, files, config=None):
"""
Upload given files to Filelib API
:param config: a dict that contains configuration options for the upload process
:param files: a list object of file paths to upload
:return:
"""
# Ensure the client is authenticated
... |
Upload given files to Filelib API
:param config: a dict that contains configuration options for the upload process
:param files: a list object of file paths to upload
:return:
| Upload given files to Filelib API | [
"Upload",
"given",
"files",
"to",
"Filelib",
"API"
] | def upload(self, files, config=None):
if not self.is_access_token():
self.acquire_access_token()
self.__set_pool_config(config)
self.set_files(files)
return self.__upload() | [
"def",
"upload",
"(",
"self",
",",
"files",
",",
"config",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_access_token",
"(",
")",
":",
"self",
".",
"acquire_access_token",
"(",
")",
"self",
".",
"__set_pool_config",
"(",
"config",
")",
"self",
"... | Upload given files to Filelib API | [
"Upload",
"given",
"files",
"to",
"Filelib",
"API"
] | [
"\"\"\"\n Upload given files to Filelib API\n\n :param config: a dict that contains configuration options for the upload process\n :param files: a list object of file paths to upload\n :return:\n \"\"\"",
"# Ensure the client is authenticated",
"# If not, authenticate with giv... | [
{
"param": "self",
"type": null
},
{
"param": "files",
"type": null
},
{
"param": "config",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
b7f9c6e414b1a9e17558f72e9211fad878b9e0b1 | filelib/filelib-python | filelib/client.py | [
"MIT"
] | Python | upload_file_objects | <not_specific> | def upload_file_objects(self, files, config=None):
"""
Upload file-like objects.
This method allows client to upload a file that is already in memory
:param files: Type list object with file-like object items
:param config: a dict that contains configuration options for the uploa... |
Upload file-like objects.
This method allows client to upload a file that is already in memory
:param files: Type list object with file-like object items
:param config: a dict that contains configuration options for the upload process
:return: self.__upload()
| Upload file-like objects.
This method allows client to upload a file that is already in memory | [
"Upload",
"file",
"-",
"like",
"objects",
".",
"This",
"method",
"allows",
"client",
"to",
"upload",
"a",
"file",
"that",
"is",
"already",
"in",
"memory"
] | def upload_file_objects(self, files, config=None):
for file in files:
self.__add_file_like_object(file)
for key, value in config.items():
self.set_config(key, value)
return self.__upload() | [
"def",
"upload_file_objects",
"(",
"self",
",",
"files",
",",
"config",
"=",
"None",
")",
":",
"for",
"file",
"in",
"files",
":",
"self",
".",
"__add_file_like_object",
"(",
"file",
")",
"for",
"key",
",",
"value",
"in",
"config",
".",
"items",
"(",
")... | Upload file-like objects. | [
"Upload",
"file",
"-",
"like",
"objects",
"."
] | [
"\"\"\"\n Upload file-like objects.\n This method allows client to upload a file that is already in memory\n :param files: Type list object with file-like object items\n :param config: a dict that contains configuration options for the upload process\n :return: self.__upload()\n ... | [
{
"param": "self",
"type": null
},
{
"param": "files",
"type": null
},
{
"param": "config",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | weight_variable | <not_specific> | def weight_variable(self, shape, stddev = 0.01):
"""
Initialize weight with slight amount of noise to
break symmetry and prevent zero gradients
"""
initial = tf.truncated_normal(shape, stddev = stddev)
return tf.Variable(initial) |
Initialize weight with slight amount of noise to
break symmetry and prevent zero gradients
| Initialize weight with slight amount of noise to
break symmetry and prevent zero gradients | [
"Initialize",
"weight",
"with",
"slight",
"amount",
"of",
"noise",
"to",
"break",
"symmetry",
"and",
"prevent",
"zero",
"gradients"
] | def weight_variable(self, shape, stddev = 0.01):
initial = tf.truncated_normal(shape, stddev = stddev)
return tf.Variable(initial) | [
"def",
"weight_variable",
"(",
"self",
",",
"shape",
",",
"stddev",
"=",
"0.01",
")",
":",
"initial",
"=",
"tf",
".",
"truncated_normal",
"(",
"shape",
",",
"stddev",
"=",
"stddev",
")",
"return",
"tf",
".",
"Variable",
"(",
"initial",
")"
] | Initialize weight with slight amount of noise to
break symmetry and prevent zero gradients | [
"Initialize",
"weight",
"with",
"slight",
"amount",
"of",
"noise",
"to",
"break",
"symmetry",
"and",
"prevent",
"zero",
"gradients"
] | [
"\"\"\"\n Initialize weight with slight amount of noise to\n break symmetry and prevent zero gradients\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "shape",
"type": null
},
{
"param": "stddev",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "shape",
"type": null,
"docstring": null,
"docstring_tokens": ... |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | bias_variable | <not_specific> | def bias_variable(self, shape, value = 0.01):
"""
Initialize ReLU neurons with slight positive initial
bias to avoid dead neurons
"""
initial = tf.constant(value, shape=shape)
return tf.Variable(initial) |
Initialize ReLU neurons with slight positive initial
bias to avoid dead neurons
| Initialize ReLU neurons with slight positive initial
bias to avoid dead neurons | [
"Initialize",
"ReLU",
"neurons",
"with",
"slight",
"positive",
"initial",
"bias",
"to",
"avoid",
"dead",
"neurons"
] | def bias_variable(self, shape, value = 0.01):
initial = tf.constant(value, shape=shape)
return tf.Variable(initial) | [
"def",
"bias_variable",
"(",
"self",
",",
"shape",
",",
"value",
"=",
"0.01",
")",
":",
"initial",
"=",
"tf",
".",
"constant",
"(",
"value",
",",
"shape",
"=",
"shape",
")",
"return",
"tf",
".",
"Variable",
"(",
"initial",
")"
] | Initialize ReLU neurons with slight positive initial
bias to avoid dead neurons | [
"Initialize",
"ReLU",
"neurons",
"with",
"slight",
"positive",
"initial",
"bias",
"to",
"avoid",
"dead",
"neurons"
] | [
"\"\"\"\n Initialize ReLU neurons with slight positive initial\n bias to avoid dead neurons\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "shape",
"type": null
},
{
"param": "value",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "shape",
"type": null,
"docstring": null,
"docstring_tokens": ... |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | conv2d | <not_specific> | def conv2d(self, x, W, stride = 1):
"""
We use a stride size of 1 and zero padded convolutions
to ensure we get the same output size as it was our input
"""
return tf.nn.conv2d(x, W, strides = [1, stride, stride, 1], padding = "SAME") |
We use a stride size of 1 and zero padded convolutions
to ensure we get the same output size as it was our input
| We use a stride size of 1 and zero padded convolutions
to ensure we get the same output size as it was our input | [
"We",
"use",
"a",
"stride",
"size",
"of",
"1",
"and",
"zero",
"padded",
"convolutions",
"to",
"ensure",
"we",
"get",
"the",
"same",
"output",
"size",
"as",
"it",
"was",
"our",
"input"
] | def conv2d(self, x, W, stride = 1):
return tf.nn.conv2d(x, W, strides = [1, stride, stride, 1], padding = "SAME") | [
"def",
"conv2d",
"(",
"self",
",",
"x",
",",
"W",
",",
"stride",
"=",
"1",
")",
":",
"return",
"tf",
".",
"nn",
".",
"conv2d",
"(",
"x",
",",
"W",
",",
"strides",
"=",
"[",
"1",
",",
"stride",
",",
"stride",
",",
"1",
"]",
",",
"padding",
"... | We use a stride size of 1 and zero padded convolutions
to ensure we get the same output size as it was our input | [
"We",
"use",
"a",
"stride",
"size",
"of",
"1",
"and",
"zero",
"padded",
"convolutions",
"to",
"ensure",
"we",
"get",
"the",
"same",
"output",
"size",
"as",
"it",
"was",
"our",
"input"
] | [
"\"\"\"\n We use a stride size of 1 and zero padded convolutions\n to ensure we get the same output size as it was our input\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "x",
"type": null
},
{
"param": "W",
"type": null
},
{
"param": "stride",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | max_pool_2x2 | <not_specific> | def max_pool_2x2(self, x):
"""
Our pooling is plain old max pooling over 2x2 blocks
"""
return tf.nn.max_pool(x, ksize = [1, 2, 2, 1],
strides = [1, 2, 2, 1], padding = "SAME") |
Our pooling is plain old max pooling over 2x2 blocks
| Our pooling is plain old max pooling over 2x2 blocks | [
"Our",
"pooling",
"is",
"plain",
"old",
"max",
"pooling",
"over",
"2x2",
"blocks"
] | def max_pool_2x2(self, x):
return tf.nn.max_pool(x, ksize = [1, 2, 2, 1],
strides = [1, 2, 2, 1], padding = "SAME") | [
"def",
"max_pool_2x2",
"(",
"self",
",",
"x",
")",
":",
"return",
"tf",
".",
"nn",
".",
"max_pool",
"(",
"x",
",",
"ksize",
"=",
"[",
"1",
",",
"2",
",",
"2",
",",
"1",
"]",
",",
"strides",
"=",
"[",
"1",
",",
"2",
",",
"2",
",",
"1",
"]"... | Our pooling is plain old max pooling over 2x2 blocks | [
"Our",
"pooling",
"is",
"plain",
"old",
"max",
"pooling",
"over",
"2x2",
"blocks"
] | [
"\"\"\"\n Our pooling is plain old max pooling over 2x2 blocks\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "x",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | build_weights_biases | <not_specific> | def build_weights_biases(self, weights_shape):
"""
Build the weights and bias of a convolutional layer
"""
return self.weight_variable(weights_shape), \
self.bias_variable(weights_shape[-1:]) |
Build the weights and bias of a convolutional layer
| Build the weights and bias of a convolutional layer | [
"Build",
"the",
"weights",
"and",
"bias",
"of",
"a",
"convolutional",
"layer"
] | def build_weights_biases(self, weights_shape):
return self.weight_variable(weights_shape), \
self.bias_variable(weights_shape[-1:]) | [
"def",
"build_weights_biases",
"(",
"self",
",",
"weights_shape",
")",
":",
"return",
"self",
".",
"weight_variable",
"(",
"weights_shape",
")",
",",
"self",
".",
"bias_variable",
"(",
"weights_shape",
"[",
"-",
"1",
":",
"]",
")"
] | Build the weights and bias of a convolutional layer | [
"Build",
"the",
"weights",
"and",
"bias",
"of",
"a",
"convolutional",
"layer"
] | [
"\"\"\"\n Build the weights and bias of a convolutional layer\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "weights_shape",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "weights_shape",
"type": null,
"docstring": null,
"docstring_t... |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | convolve_relu_pool | <not_specific> | def convolve_relu_pool(self, nn_input, weights_shape, stride = 4, pool = True):
"""
Convolve the input to the network with the weight tensor,
add the bias, apply the ReLU function and finally max pool
"""
W_conv, b_conv = self.build_weights_biases(weights_shape)
h_conv = ... |
Convolve the input to the network with the weight tensor,
add the bias, apply the ReLU function and finally max pool
| Convolve the input to the network with the weight tensor,
add the bias, apply the ReLU function and finally max pool | [
"Convolve",
"the",
"input",
"to",
"the",
"network",
"with",
"the",
"weight",
"tensor",
"add",
"the",
"bias",
"apply",
"the",
"ReLU",
"function",
"and",
"finally",
"max",
"pool"
] | def convolve_relu_pool(self, nn_input, weights_shape, stride = 4, pool = True):
W_conv, b_conv = self.build_weights_biases(weights_shape)
h_conv = tf.nn.relu(self.conv2d(nn_input, W_conv, stride) + b_conv)
if not pool:
return h_conv
return self.max_pool_2x2(h_conv) | [
"def",
"convolve_relu_pool",
"(",
"self",
",",
"nn_input",
",",
"weights_shape",
",",
"stride",
"=",
"4",
",",
"pool",
"=",
"True",
")",
":",
"W_conv",
",",
"b_conv",
"=",
"self",
".",
"build_weights_biases",
"(",
"weights_shape",
")",
"h_conv",
"=",
"tf",... | Convolve the input to the network with the weight tensor,
add the bias, apply the ReLU function and finally max pool | [
"Convolve",
"the",
"input",
"to",
"the",
"network",
"with",
"the",
"weight",
"tensor",
"add",
"the",
"bias",
"apply",
"the",
"ReLU",
"function",
"and",
"finally",
"max",
"pool"
] | [
"\"\"\"\n Convolve the input to the network with the weight tensor,\n add the bias, apply the ReLU function and finally max pool\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "nn_input",
"type": null
},
{
"param": "weights_shape",
"type": null
},
{
"param": "stride",
"type": null
},
{
"param": "pool",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "nn_input",
"type": null,
"docstring": null,
"docstring_tokens... |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | build_network | <not_specific> | def build_network(self):
"""
Sets up the deep neural network
"""
# the input is going to be reshaped to a
# 80x80 color image (4 channels)
input_image = tf.placeholder("float", [None, self.input_width,
self.input_height, self.nimages... |
Sets up the deep neural network
| Sets up the deep neural network | [
"Sets",
"up",
"the",
"deep",
"neural",
"network"
] | def build_network(self):
input_image = tf.placeholder("float", [None, self.input_width,
self.input_height, self.nimages])
h_pool1 = self.convolve_relu_pool(input_image, [8, 8, self.nimages, 32])
h_conv2 = self.convolve_relu_pool(h_pool1, [4, 4, 32, 64], 2, F... | [
"def",
"build_network",
"(",
"self",
")",
":",
"input_image",
"=",
"tf",
".",
"placeholder",
"(",
"\"float\"",
",",
"[",
"None",
",",
"self",
".",
"input_width",
",",
"self",
".",
"input_height",
",",
"self",
".",
"nimages",
"]",
")",
"h_pool1",
"=",
"... | Sets up the deep neural network | [
"Sets",
"up",
"the",
"deep",
"neural",
"network"
] | [
"\"\"\"\n Sets up the deep neural network\n \"\"\"",
"# the input is going to be reshaped to a",
"# 80x80 color image (4 channels)",
"# create the first convolutional layers",
"# create the densely connected layers",
"# finally add the readout layer"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | save_variables | null | def save_variables(self, a_file, h_file, stack):
"""
Saves neural network weight variables for
debugging purposes
"""
readout_t = self.readout_act(stack)
a_file.write(",".join([str(x) for x in readout_t]) + '\n')
h_file.write(",".join([str(x) for x in self.h_fc1.e... |
Saves neural network weight variables for
debugging purposes
| Saves neural network weight variables for
debugging purposes | [
"Saves",
"neural",
"network",
"weight",
"variables",
"for",
"debugging",
"purposes"
] | def save_variables(self, a_file, h_file, stack):
readout_t = self.readout_act(stack)
a_file.write(",".join([str(x) for x in readout_t]) + '\n')
h_file.write(",".join([str(x) for x in self.h_fc1.eval(
feed_dict={self.input_image:[stack]})[0]]) + '\n') | [
"def",
"save_variables",
"(",
"self",
",",
"a_file",
",",
"h_file",
",",
"stack",
")",
":",
"readout_t",
"=",
"self",
".",
"readout_act",
"(",
"stack",
")",
"a_file",
".",
"write",
"(",
"\",\"",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"... | Saves neural network weight variables for
debugging purposes | [
"Saves",
"neural",
"network",
"weight",
"variables",
"for",
"debugging",
"purposes"
] | [
"\"\"\"\n Saves neural network weight variables for\n debugging purposes\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "a_file",
"type": null
},
{
"param": "h_file",
"type": null
},
{
"param": "stack",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "a_file",
"type": null,
"docstring": null,
"docstring_tokens":... |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | save_percepts | null | def save_percepts(self, path, x_t1):
"""
Saves an image array to visualize
how the image is compressed before saving
"""
cv2.imwrite(path, np.rot90(x_t1)) |
Saves an image array to visualize
how the image is compressed before saving
| Saves an image array to visualize
how the image is compressed before saving | [
"Saves",
"an",
"image",
"array",
"to",
"visualize",
"how",
"the",
"image",
"is",
"compressed",
"before",
"saving"
] | def save_percepts(self, path, x_t1):
cv2.imwrite(path, np.rot90(x_t1)) | [
"def",
"save_percepts",
"(",
"self",
",",
"path",
",",
"x_t1",
")",
":",
"cv2",
".",
"imwrite",
"(",
"path",
",",
"np",
".",
"rot90",
"(",
"x_t1",
")",
")"
] | Saves an image array to visualize
how the image is compressed before saving | [
"Saves",
"an",
"image",
"array",
"to",
"visualize",
"how",
"the",
"image",
"is",
"compressed",
"before",
"saving"
] | [
"\"\"\"\n Saves an image array to visualize\n how the image is compressed before saving\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "path",
"type": null
},
{
"param": "x_t1",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "path",
"type": null,
"docstring": null,
"docstring_tokens": [... |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | save_network | null | def save_network(self, directory, iteration):
"""
Saves the progress of the agent
for further use later on
"""
self.saver.save(self.session, directory + '/network', global_step = iteration) |
Saves the progress of the agent
for further use later on
| Saves the progress of the agent
for further use later on | [
"Saves",
"the",
"progress",
"of",
"the",
"agent",
"for",
"further",
"use",
"later",
"on"
] | def save_network(self, directory, iteration):
self.saver.save(self.session, directory + '/network', global_step = iteration) | [
"def",
"save_network",
"(",
"self",
",",
"directory",
",",
"iteration",
")",
":",
"self",
".",
"saver",
".",
"save",
"(",
"self",
".",
"session",
",",
"directory",
"+",
"'/network'",
",",
"global_step",
"=",
"iteration",
")"
] | Saves the progress of the agent
for further use later on | [
"Saves",
"the",
"progress",
"of",
"the",
"agent",
"for",
"further",
"use",
"later",
"on"
] | [
"\"\"\"\n Saves the progress of the agent\n for further use later on\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "directory",
"type": null
},
{
"param": "iteration",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "directory",
"type": null,
"docstring": null,
"docstring_token... |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | attempt_restore | <not_specific> | def attempt_restore(self, directory):
"""
Restors the latest file saved if
available
"""
checkpoint = tf.train.get_checkpoint_state(directory)
if checkpoint and checkpoint.model_checkpoint_path:
self.saver.restore(self.session, checkpoint.model_checkpoint_path... |
Restors the latest file saved if
available
| Restors the latest file saved if
available | [
"Restors",
"the",
"latest",
"file",
"saved",
"if",
"available"
] | def attempt_restore(self, directory):
checkpoint = tf.train.get_checkpoint_state(directory)
if checkpoint and checkpoint.model_checkpoint_path:
self.saver.restore(self.session, checkpoint.model_checkpoint_path)
return checkpoint.model_checkpoint_path | [
"def",
"attempt_restore",
"(",
"self",
",",
"directory",
")",
":",
"checkpoint",
"=",
"tf",
".",
"train",
".",
"get_checkpoint_state",
"(",
"directory",
")",
"if",
"checkpoint",
"and",
"checkpoint",
".",
"model_checkpoint_path",
":",
"self",
".",
"saver",
".",... | Restors the latest file saved if
available | [
"Restors",
"the",
"latest",
"file",
"saved",
"if",
"available"
] | [
"\"\"\"\n Restors the latest file saved if\n available\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "directory",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "directory",
"type": null,
"docstring": null,
"docstring_token... |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | preprocess_percepts | <not_specific> | def preprocess_percepts(self, x_t1_colored, reshape = True):
"""
The raw image arrays get shrunk down and
remove any color whatsoever. Also gets it in
3 dimensions if needed
"""
x_t1_resized = cv2.resize(x_t1_colored, (self.input_width, self.input_height))
x_t1_gr... |
The raw image arrays get shrunk down and
remove any color whatsoever. Also gets it in
3 dimensions if needed
| The raw image arrays get shrunk down and
remove any color whatsoever. Also gets it in
3 dimensions if needed | [
"The",
"raw",
"image",
"arrays",
"get",
"shrunk",
"down",
"and",
"remove",
"any",
"color",
"whatsoever",
".",
"Also",
"gets",
"it",
"in",
"3",
"dimensions",
"if",
"needed"
] | def preprocess_percepts(self, x_t1_colored, reshape = True):
x_t1_resized = cv2.resize(x_t1_colored, (self.input_width, self.input_height))
x_t1_greyscale = cv2.cvtColor(x_t1_resized, cv2.COLOR_BGR2GRAY)
ret, x_t1 = cv2.threshold(x_t1_greyscale, 1, 255, cv2.THRESH_BINARY)
if not reshape:... | [
"def",
"preprocess_percepts",
"(",
"self",
",",
"x_t1_colored",
",",
"reshape",
"=",
"True",
")",
":",
"x_t1_resized",
"=",
"cv2",
".",
"resize",
"(",
"x_t1_colored",
",",
"(",
"self",
".",
"input_width",
",",
"self",
".",
"input_height",
")",
")",
"x_t1_g... | The raw image arrays get shrunk down and
remove any color whatsoever. | [
"The",
"raw",
"image",
"arrays",
"get",
"shrunk",
"down",
"and",
"remove",
"any",
"color",
"whatsoever",
"."
] | [
"\"\"\"\n The raw image arrays get shrunk down and\n remove any color whatsoever. Also gets it in\n 3 dimensions if needed\n \"\"\"",
"\"\"\"\n import time\n timestamp = int(time.time())\n cv2.imwrite(\"percepts/%d-color.png\" % timestamp,\n np.r... | [
{
"param": "self",
"type": null
},
{
"param": "x_t1_colored",
"type": null
},
{
"param": "reshape",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x_t1_colored",
"type": null,
"docstring": null,
"docstring_to... |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | readout_act | <not_specific> | def readout_act(self, stack):
"""
Gets the best action
for a given stack of images
"""
stack = [stack] if hasattr(stack, 'shape') and len(stack.shape) == 3 else stack
return self.y_conv.eval(feed_dict = {self.input_image: stack}) |
Gets the best action
for a given stack of images
| Gets the best action
for a given stack of images | [
"Gets",
"the",
"best",
"action",
"for",
"a",
"given",
"stack",
"of",
"images"
] | def readout_act(self, stack):
stack = [stack] if hasattr(stack, 'shape') and len(stack.shape) == 3 else stack
return self.y_conv.eval(feed_dict = {self.input_image: stack}) | [
"def",
"readout_act",
"(",
"self",
",",
"stack",
")",
":",
"stack",
"=",
"[",
"stack",
"]",
"if",
"hasattr",
"(",
"stack",
",",
"'shape'",
")",
"and",
"len",
"(",
"stack",
".",
"shape",
")",
"==",
"3",
"else",
"stack",
"return",
"self",
".",
"y_con... | Gets the best action
for a given stack of images | [
"Gets",
"the",
"best",
"action",
"for",
"a",
"given",
"stack",
"of",
"images"
] | [
"\"\"\"\n Gets the best action\n for a given stack of images\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "stack",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "stack",
"type": null,
"docstring": null,
"docstring_tokens": ... |
bc2a152002e92e8d55e206713a851690baa13195 | mimoralea/king-pong | multicnet.py | [
"MIT"
] | Python | select_best_action | <not_specific> | def select_best_action(self, stack):
"""
Selects the action with the
highest value
"""
return np.argmax(self.readout_act(stack)) |
Selects the action with the
highest value
| Selects the action with the
highest value | [
"Selects",
"the",
"action",
"with",
"the",
"highest",
"value"
] | def select_best_action(self, stack):
return np.argmax(self.readout_act(stack)) | [
"def",
"select_best_action",
"(",
"self",
",",
"stack",
")",
":",
"return",
"np",
".",
"argmax",
"(",
"self",
".",
"readout_act",
"(",
"stack",
")",
")"
] | Selects the action with the
highest value | [
"Selects",
"the",
"action",
"with",
"the",
"highest",
"value"
] | [
"\"\"\"\n Selects the action with the\n highest value\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "stack",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "stack",
"type": null,
"docstring": null,
"docstring_tokens": ... |
75bc8317bbac87601e8fbccc0bed5e02605ac6e6 | mimoralea/king-pong | king_pong.py | [
"MIT"
] | Python | score_last_changed | <not_specific> | def score_last_changed(self):
"""
Checks if the scores has changed since
the last time this function was accessed
"""
current = self.score_changed
self.score_changed = False
return current |
Checks if the scores has changed since
the last time this function was accessed
| Checks if the scores has changed since
the last time this function was accessed | [
"Checks",
"if",
"the",
"scores",
"has",
"changed",
"since",
"the",
"last",
"time",
"this",
"function",
"was",
"accessed"
] | def score_last_changed(self):
current = self.score_changed
self.score_changed = False
return current | [
"def",
"score_last_changed",
"(",
"self",
")",
":",
"current",
"=",
"self",
".",
"score_changed",
"self",
".",
"score_changed",
"=",
"False",
"return",
"current"
] | Checks if the scores has changed since
the last time this function was accessed | [
"Checks",
"if",
"the",
"scores",
"has",
"changed",
"since",
"the",
"last",
"time",
"this",
"function",
"was",
"accessed"
] | [
"\"\"\"\n Checks if the scores has changed since\n the last time this function was accessed\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
75bc8317bbac87601e8fbccc0bed5e02605ac6e6 | mimoralea/king-pong | king_pong.py | [
"MIT"
] | Python | game_over | <not_specific> | def game_over(self):
"""
The game is over when any player reaches
the number of games playing to
"""
return self.games[0] == self.first_to[0] or \
self.games[1] == self.first_to[0] |
The game is over when any player reaches
the number of games playing to
| The game is over when any player reaches
the number of games playing to | [
"The",
"game",
"is",
"over",
"when",
"any",
"player",
"reaches",
"the",
"number",
"of",
"games",
"playing",
"to"
] | def game_over(self):
return self.games[0] == self.first_to[0] or \
self.games[1] == self.first_to[0] | [
"def",
"game_over",
"(",
"self",
")",
":",
"return",
"self",
".",
"games",
"[",
"0",
"]",
"==",
"self",
".",
"first_to",
"[",
"0",
"]",
"or",
"self",
".",
"games",
"[",
"1",
"]",
"==",
"self",
".",
"first_to",
"[",
"0",
"]"
] | The game is over when any player reaches
the number of games playing to | [
"The",
"game",
"is",
"over",
"when",
"any",
"player",
"reaches",
"the",
"number",
"of",
"games",
"playing",
"to"
] | [
"\"\"\"\n The game is over when any player reaches\n the number of games playing to\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
75bc8317bbac87601e8fbccc0bed5e02605ac6e6 | mimoralea/king-pong | king_pong.py | [
"MIT"
] | Python | reset_positions | null | def reset_positions(self):
"""
Moves the players to a center position
and reset the direction and speed of
the ball randomly within acceptable range.
"""
self.playerx, self.playery = SCREEN_WIDTH-PADDLE_X_DISTANCE, PADDLE_Y_... |
Moves the players to a center position
and reset the direction and speed of
the ball randomly within acceptable range.
| Moves the players to a center position
and reset the direction and speed of
the ball randomly within acceptable range. | [
"Moves",
"the",
"players",
"to",
"a",
"center",
"position",
"and",
"reset",
"the",
"direction",
"and",
"speed",
"of",
"the",
"ball",
"randomly",
"within",
"acceptable",
"range",
"."
] | def reset_positions(self):
self.playerx, self.playery = SCREEN_WIDTH-PADDLE_X_DISTANCE, PADDLE_Y_DISTANCE
self.cpux, self.cpuy = PADDLE_X_DISTANCE, PADDLE_Y_DISTANCE
self.ballx, self.bally = SCREEN_WIDTH/2, SCREEN_HEIGHT/2
self.ball_speed_x = random.choice... | [
"def",
"reset_positions",
"(",
"self",
")",
":",
"self",
".",
"playerx",
",",
"self",
".",
"playery",
"=",
"SCREEN_WIDTH",
"-",
"PADDLE_X_DISTANCE",
",",
"PADDLE_Y_DISTANCE",
"self",
".",
"cpux",
",",
"self",
".",
"cpuy",
"=",
"PADDLE_X_DISTANCE",
",",
"PADD... | Moves the players to a center position
and reset the direction and speed of
the ball randomly within acceptable range. | [
"Moves",
"the",
"players",
"to",
"a",
"center",
"position",
"and",
"reset",
"the",
"direction",
"and",
"speed",
"of",
"the",
"ball",
"randomly",
"within",
"acceptable",
"range",
"."
] | [
"\"\"\"\n Moves the players to a center position\n and reset the direction and speed of\n the ball randomly within acceptable range.\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
75bc8317bbac87601e8fbccc0bed5e02605ac6e6 | mimoralea/king-pong | king_pong.py | [
"MIT"
] | Python | frame_step | <not_specific> | def frame_step(self, input_actions):
"""
Moves the state of the game forward
one step with the given input actions
input_actions[0] == 1: do nothing
input_actions[1] == 1: move up
input_actions[2] == 1: move down
... |
Moves the state of the game forward
one step with the given input actions
input_actions[0] == 1: do nothing
input_actions[1] == 1: move up
input_actions[2] == 1: move down
sum(input_actions) == 1
| Moves the state of the game forward
one step with the given input actions
| [
"Moves",
"the",
"state",
"of",
"the",
"game",
"forward",
"one",
"step",
"with",
"the",
"given",
"input",
"actions"
] | def frame_step(self, input_actions):
pygame.event.pump()
if sum(input_actions) != 1:
raise ValueError('Multiple input actions!')
if input_actions[1] == 1:
self.playery = np.maximum(0,
... | [
"def",
"frame_step",
"(",
"self",
",",
"input_actions",
")",
":",
"pygame",
".",
"event",
".",
"pump",
"(",
")",
"if",
"sum",
"(",
"input_actions",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'Multiple input actions!'",
")",
"if",
"input_actions",
"[... | Moves the state of the game forward
one step with the given input actions | [
"Moves",
"the",
"state",
"of",
"the",
"game",
"forward",
"one",
"step",
"with",
"the",
"given",
"input",
"actions"
] | [
"\"\"\"\n Moves the state of the game forward\n one step with the given input actions\n\n input_actions[0] == 1: do nothing\n input_actions[1] == 1: move up\n input_actions[2] == 1: move down\n\n sum(input_actions) == 1\n ... | [
{
"param": "self",
"type": null
},
{
"param": "input_actions",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "input_actions",
"type": null,
"docstring": null,
"docstring_t... |
75bc8317bbac87601e8fbccc0bed5e02605ac6e6 | mimoralea/king-pong | king_pong.py | [
"MIT"
] | Python | move_ball | <not_specific> | def move_ball(self):
"""
Move the ball in game state
it calculates boundaries and it clips
the ball positioning when it is overlapping
with walls or paddles
return rewards when right player makes contact with the ball
... |
Move the ball in game state
it calculates boundaries and it clips
the ball positioning when it is overlapping
with walls or paddles
return rewards when right player makes contact with the ball
and when ball leaves the game... | Move the ball in game state
it calculates boundaries and it clips
the ball positioning when it is overlapping
with walls or paddles
return rewards when right player makes contact with the ball
and when ball leaves the game screen on the left side | [
"Move",
"the",
"ball",
"in",
"game",
"state",
"it",
"calculates",
"boundaries",
"and",
"it",
"clips",
"the",
"ball",
"positioning",
"when",
"it",
"is",
"overlapping",
"with",
"walls",
"or",
"paddles",
"return",
"rewards",
"when",
"right",
"player",
"makes",
... | def move_ball(self):
reward = 0.0
prev_x, prev_y = self.ballx, self.bally
next_x, next_y = self.ballx + self.ball_speed_x, self.bally + self.ball_speed_y
ball_trajectory = LineString([(prev_x, prev_y), (next_x, next_y)])
upper_wall = LineSt... | [
"def",
"move_ball",
"(",
"self",
")",
":",
"reward",
"=",
"0.0",
"prev_x",
",",
"prev_y",
"=",
"self",
".",
"ballx",
",",
"self",
".",
"bally",
"next_x",
",",
"next_y",
"=",
"self",
".",
"ballx",
"+",
"self",
".",
"ball_speed_x",
",",
"self",
".",
... | Move the ball in game state
it calculates boundaries and it clips
the ball positioning when it is overlapping
with walls or paddles | [
"Move",
"the",
"ball",
"in",
"game",
"state",
"it",
"calculates",
"boundaries",
"and",
"it",
"clips",
"the",
"ball",
"positioning",
"when",
"it",
"is",
"overlapping",
"with",
"walls",
"or",
"paddles"
] | [
"\"\"\"\n Move the ball in game state\n it calculates boundaries and it clips\n the ball positioning when it is overlapping\n with walls or paddles\n\n return rewards when right player makes contact with the ball\n and when ba... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
75bc8317bbac87601e8fbccc0bed5e02605ac6e6 | mimoralea/king-pong | king_pong.py | [
"MIT"
] | Python | draw_scores | null | def draw_scores(self):
"""
To be called when playing against
human only so that numbers pixels don't
interfere with learning
"""
cpu_score = SCORE_FONT.render(str(self.score[0]), 1, (255, 255, 255))
cpu_games... |
To be called when playing against
human only so that numbers pixels don't
interfere with learning
| To be called when playing against
human only so that numbers pixels don't
interfere with learning | [
"To",
"be",
"called",
"when",
"playing",
"against",
"human",
"only",
"so",
"that",
"numbers",
"pixels",
"don",
"'",
"t",
"interfere",
"with",
"learning"
] | def draw_scores(self):
cpu_score = SCORE_FONT.render(str(self.score[0]), 1, (255, 255, 255))
cpu_games = GAMES_FONT.render(str(self.games[0]), 1, (255, 255, 255))
my_score = SCORE_FONT.render(str(self.score[1]), 1, (255, 255, 255))
my_games = GAMES_FONT.re... | [
"def",
"draw_scores",
"(",
"self",
")",
":",
"cpu_score",
"=",
"SCORE_FONT",
".",
"render",
"(",
"str",
"(",
"self",
".",
"score",
"[",
"0",
"]",
")",
",",
"1",
",",
"(",
"255",
",",
"255",
",",
"255",
")",
")",
"cpu_games",
"=",
"GAMES_FONT",
".... | To be called when playing against
human only so that numbers pixels don't
interfere with learning | [
"To",
"be",
"called",
"when",
"playing",
"against",
"human",
"only",
"so",
"that",
"numbers",
"pixels",
"don",
"'",
"t",
"interfere",
"with",
"learning"
] | [
"\"\"\"\n To be called when playing against\n human only so that numbers pixels don't\n interfere with learning\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
75bc8317bbac87601e8fbccc0bed5e02605ac6e6 | mimoralea/king-pong | king_pong.py | [
"MIT"
] | Python | complete_drawing | null | def complete_drawing(self):
"""
Force the drawing of the screens
"""
if self.print_scores: self.draw_scores()
pygame.display.flip()
if self.auto_draw: FPS_CLOCK.tick(QFPS)
else: FPS_CLOCK.tick(FPS) |
Force the drawing of the screens
| Force the drawing of the screens | [
"Force",
"the",
"drawing",
"of",
"the",
"screens"
] | def complete_drawing(self):
if self.print_scores: self.draw_scores()
pygame.display.flip()
if self.auto_draw: FPS_CLOCK.tick(QFPS)
else: FPS_CLOCK.tick(FPS) | [
"def",
"complete_drawing",
"(",
"self",
")",
":",
"if",
"self",
".",
"print_scores",
":",
"self",
".",
"draw_scores",
"(",
")",
"pygame",
".",
"display",
".",
"flip",
"(",
")",
"if",
"self",
".",
"auto_draw",
":",
"FPS_CLOCK",
".",
"tick",
"(",
"QFPS",... | Force the drawing of the screens | [
"Force",
"the",
"drawing",
"of",
"the",
"screens"
] | [
"\"\"\"\n Force the drawing of the screens\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
75bc8317bbac87601e8fbccc0bed5e02605ac6e6 | mimoralea/king-pong | king_pong.py | [
"MIT"
] | Python | flip_and_spin_ball | null | def flip_and_spin_ball(self):
"""
When ball makes contact with the upper
or lower ends of either paddle, the ball
will potentially randomly increase the y axis speed
and be return with the same speed
"""
self... |
When ball makes contact with the upper
or lower ends of either paddle, the ball
will potentially randomly increase the y axis speed
and be return with the same speed
| When ball makes contact with the upper
or lower ends of either paddle, the ball
will potentially randomly increase the y axis speed
and be return with the same speed | [
"When",
"ball",
"makes",
"contact",
"with",
"the",
"upper",
"or",
"lower",
"ends",
"of",
"either",
"paddle",
"the",
"ball",
"will",
"potentially",
"randomly",
"increase",
"the",
"y",
"axis",
"speed",
"and",
"be",
"return",
"with",
"the",
"same",
"speed"
] | def flip_and_spin_ball(self):
self.ball_speed_x *= -1
self.ball_speed_y *= random.randint(1000, 1200)/1000. | [
"def",
"flip_and_spin_ball",
"(",
"self",
")",
":",
"self",
".",
"ball_speed_x",
"*=",
"-",
"1",
"self",
".",
"ball_speed_y",
"*=",
"random",
".",
"randint",
"(",
"1000",
",",
"1200",
")",
"/",
"1000."
] | When ball makes contact with the upper
or lower ends of either paddle, the ball
will potentially randomly increase the y axis speed
and be return with the same speed | [
"When",
"ball",
"makes",
"contact",
"with",
"the",
"upper",
"or",
"lower",
"ends",
"of",
"either",
"paddle",
"the",
"ball",
"will",
"potentially",
"randomly",
"increase",
"the",
"y",
"axis",
"speed",
"and",
"be",
"return",
"with",
"the",
"same",
"speed"
] | [
"\"\"\"\n When ball makes contact with the upper\n or lower ends of either paddle, the ball\n will potentially randomly increase the y axis speed\n and be return with the same speed\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
75bc8317bbac87601e8fbccc0bed5e02605ac6e6 | mimoralea/king-pong | king_pong.py | [
"MIT"
] | Python | flip_and_speed_ball | null | def flip_and_speed_ball(self):
"""
When the ball makes contact with the center
of either paddle, it will return the ball with
potentially an increase in the x axis speed
y axis remains untouched
"""
self.ball... |
When the ball makes contact with the center
of either paddle, it will return the ball with
potentially an increase in the x axis speed
y axis remains untouched
| When the ball makes contact with the center
of either paddle, it will return the ball with
potentially an increase in the x axis speed
y axis remains untouched | [
"When",
"the",
"ball",
"makes",
"contact",
"with",
"the",
"center",
"of",
"either",
"paddle",
"it",
"will",
"return",
"the",
"ball",
"with",
"potentially",
"an",
"increase",
"in",
"the",
"x",
"axis",
"speed",
"y",
"axis",
"remains",
"untouched"
] | def flip_and_speed_ball(self):
self.ball_speed_x *= -1
self.ball_speed_x *= random.randint(1000, 1200)/1000. | [
"def",
"flip_and_speed_ball",
"(",
"self",
")",
":",
"self",
".",
"ball_speed_x",
"*=",
"-",
"1",
"self",
".",
"ball_speed_x",
"*=",
"random",
".",
"randint",
"(",
"1000",
",",
"1200",
")",
"/",
"1000."
] | When the ball makes contact with the center
of either paddle, it will return the ball with
potentially an increase in the x axis speed
y axis remains untouched | [
"When",
"the",
"ball",
"makes",
"contact",
"with",
"the",
"center",
"of",
"either",
"paddle",
"it",
"will",
"return",
"the",
"ball",
"with",
"potentially",
"an",
"increase",
"in",
"the",
"x",
"axis",
"speed",
"y",
"axis",
"remains",
"untouched"
] | [
"\"\"\"\n When the ball makes contact with the center\n of either paddle, it will return the ball with\n potentially an increase in the x axis speed\n y axis remains untouched\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
75bc8317bbac87601e8fbccc0bed5e02605ac6e6 | mimoralea/king-pong | king_pong.py | [
"MIT"
] | Python | main | null | def main(argv):
"""
When called `python king_pong.py`
a CPU is allocated to play against a human
"""
game_state = GameState(auto_draw = False)
# 2 game_states of 1 point
game_state.first_to = [3, 2]
game_state.top_speed = 5
while True:
... |
When called `python king_pong.py`
a CPU is allocated to play against a human
| When called `python king_pong.py`
a CPU is allocated to play against a human | [
"When",
"called",
"`",
"python",
"king_pong",
".",
"py",
"`",
"a",
"CPU",
"is",
"allocated",
"to",
"play",
"against",
"a",
"human"
] | def main(argv):
game_state = GameState(auto_draw = False)
game_state.first_to = [3, 2]
game_state.top_speed = 5
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
keys = pygame.key.... | [
"def",
"main",
"(",
"argv",
")",
":",
"game_state",
"=",
"GameState",
"(",
"auto_draw",
"=",
"False",
")",
"game_state",
".",
"first_to",
"=",
"[",
"3",
",",
"2",
"]",
"game_state",
".",
"top_speed",
"=",
"5",
"while",
"True",
":",
"for",
"event",
"i... | When called `python king_pong.py`
a CPU is allocated to play against a human | [
"When",
"called",
"`",
"python",
"king_pong",
".",
"py",
"`",
"a",
"CPU",
"is",
"allocated",
"to",
"play",
"against",
"a",
"human"
] | [
"\"\"\"\n When called `python king_pong.py`\n a CPU is allocated to play against a human\n \"\"\"",
"# 2 game_states of 1 point"
] | [
{
"param": "argv",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "argv",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
08a559cec827ace529da82b6b1ec2d7a2f1f2d98 | mimoralea/king-pong | agent.py | [
"MIT"
] | Python | save_progress | <not_specific> | def save_progress(self, stack):
"""
Save the current progress of the agent,
that is the readout values, the hidden layer values,
the images in the current stack of the agent
and the current neural network
"""
log.info('saving current stack')
for i in range... |
Save the current progress of the agent,
that is the readout values, the hidden layer values,
the images in the current stack of the agent
and the current neural network
| Save the current progress of the agent,
that is the readout values, the hidden layer values,
the images in the current stack of the agent
and the current neural network | [
"Save",
"the",
"current",
"progress",
"of",
"the",
"agent",
"that",
"is",
"the",
"readout",
"values",
"the",
"hidden",
"layer",
"values",
"the",
"images",
"in",
"the",
"current",
"stack",
"of",
"the",
"agent",
"and",
"the",
"current",
"neural",
"network"
] | def save_progress(self, stack):
log.info('saving current stack')
for i in range(stack.shape[2]):
current_percept_path = self.percepts_directory + '/frame' + \
str(self.step) + '-' + str(i) +'.png'
self.perception.save_percepts(current_percept_pa... | [
"def",
"save_progress",
"(",
"self",
",",
"stack",
")",
":",
"log",
".",
"info",
"(",
"'saving current stack'",
")",
"for",
"i",
"in",
"range",
"(",
"stack",
".",
"shape",
"[",
"2",
"]",
")",
":",
"current_percept_path",
"=",
"self",
".",
"percepts_direc... | Save the current progress of the agent,
that is the readout values, the hidden layer values,
the images in the current stack of the agent
and the current neural network | [
"Save",
"the",
"current",
"progress",
"of",
"the",
"agent",
"that",
"is",
"the",
"readout",
"values",
"the",
"hidden",
"layer",
"values",
"the",
"images",
"in",
"the",
"current",
"stack",
"of",
"the",
"agent",
"and",
"the",
"current",
"neural",
"network"
] | [
"\"\"\"\n Save the current progress of the agent,\n that is the readout values, the hidden layer values,\n the images in the current stack of the agent\n and the current neural network\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "stack",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "stack",
"type": null,
"docstring": null,
"docstring_tokens": ... |
08a559cec827ace529da82b6b1ec2d7a2f1f2d98 | mimoralea/king-pong | agent.py | [
"MIT"
] | Python | load_progress | null | def load_progress(self):
"""
Loads the progress from the agent deep network
"""
file_loaded = self.perception.attempt_restore(self.networks_directory)
if file_loaded:
log.info('loaded successfully => ' + str(file_loaded))
else:
log.info("didn't fin... |
Loads the progress from the agent deep network
| Loads the progress from the agent deep network | [
"Loads",
"the",
"progress",
"from",
"the",
"agent",
"deep",
"network"
] | def load_progress(self):
file_loaded = self.perception.attempt_restore(self.networks_directory)
if file_loaded:
log.info('loaded successfully => ' + str(file_loaded))
else:
log.info("didn't find any saved network") | [
"def",
"load_progress",
"(",
"self",
")",
":",
"file_loaded",
"=",
"self",
".",
"perception",
".",
"attempt_restore",
"(",
"self",
".",
"networks_directory",
")",
"if",
"file_loaded",
":",
"log",
".",
"info",
"(",
"'loaded successfully => '",
"+",
"str",
"(",
... | Loads the progress from the agent deep network | [
"Loads",
"the",
"progress",
"from",
"the",
"agent",
"deep",
"network"
] | [
"\"\"\"\n Loads the progress from the agent deep network\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
08a559cec827ace529da82b6b1ec2d7a2f1f2d98 | mimoralea/king-pong | agent.py | [
"MIT"
] | Python | select_action | <not_specific> | def select_action(self, x_t = None):
"""
Selects either an epsilon random action
or just the best action according to the
current state of the neural network
"""
a_t = np.zeros([self.nactions])
do_action = 0
if x_t is None or random.random() <= self.epsilo... |
Selects either an epsilon random action
or just the best action according to the
current state of the neural network
| Selects either an epsilon random action
or just the best action according to the
current state of the neural network | [
"Selects",
"either",
"an",
"epsilon",
"random",
"action",
"or",
"just",
"the",
"best",
"action",
"according",
"to",
"the",
"current",
"state",
"of",
"the",
"neural",
"network"
] | def select_action(self, x_t = None):
a_t = np.zeros([self.nactions])
do_action = 0
if x_t is None or random.random() <= self.epsilon:
log.debug('random action selected with epsilon ' + str(self.epsilon))
do_action = random.randrange(self.nactions)
else:
... | [
"def",
"select_action",
"(",
"self",
",",
"x_t",
"=",
"None",
")",
":",
"a_t",
"=",
"np",
".",
"zeros",
"(",
"[",
"self",
".",
"nactions",
"]",
")",
"do_action",
"=",
"0",
"if",
"x_t",
"is",
"None",
"or",
"random",
".",
"random",
"(",
")",
"<=",
... | Selects either an epsilon random action
or just the best action according to the
current state of the neural network | [
"Selects",
"either",
"an",
"epsilon",
"random",
"action",
"or",
"just",
"the",
"best",
"action",
"according",
"to",
"the",
"current",
"state",
"of",
"the",
"neural",
"network"
] | [
"\"\"\"\n Selects either an epsilon random action\n or just the best action according to the\n current state of the neural network\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "x_t",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "x_t",
"type": null,
"docstring": null,
"docstring_tokens": []... |
08a559cec827ace529da82b6b1ec2d7a2f1f2d98 | mimoralea/king-pong | agent.py | [
"MIT"
] | Python | remember | null | def remember(self, sars):
"""
Inserts a state action reward new_state
observation into the memory bank
and pops the oldest memory if limit was
a limit reached
"""
self.memory.append(sars)
log.debug('new sars observation inserted')
log.debug('befor... |
Inserts a state action reward new_state
observation into the memory bank
and pops the oldest memory if limit was
a limit reached
| Inserts a state action reward new_state
observation into the memory bank
and pops the oldest memory if limit was
a limit reached | [
"Inserts",
"a",
"state",
"action",
"reward",
"new_state",
"observation",
"into",
"the",
"memory",
"bank",
"and",
"pops",
"the",
"oldest",
"memory",
"if",
"limit",
"was",
"a",
"limit",
"reached"
] | def remember(self, sars):
self.memory.append(sars)
log.debug('new sars observation inserted')
log.debug('before memory size ' + str(len(self.memory)))
if len(self.memory) > self.memory_max_len:
log.debug('memory reached the max size. Removing oldest memory')
self.... | [
"def",
"remember",
"(",
"self",
",",
"sars",
")",
":",
"self",
".",
"memory",
".",
"append",
"(",
"sars",
")",
"log",
".",
"debug",
"(",
"'new sars observation inserted'",
")",
"log",
".",
"debug",
"(",
"'before memory size '",
"+",
"str",
"(",
"len",
"(... | Inserts a state action reward new_state
observation into the memory bank
and pops the oldest memory if limit was
a limit reached | [
"Inserts",
"a",
"state",
"action",
"reward",
"new_state",
"observation",
"into",
"the",
"memory",
"bank",
"and",
"pops",
"the",
"oldest",
"memory",
"if",
"limit",
"was",
"a",
"limit",
"reached"
] | [
"\"\"\"\n Inserts a state action reward new_state\n observation into the memory bank\n and pops the oldest memory if limit was\n a limit reached\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "sars",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "sars",
"type": null,
"docstring": null,
"docstring_tokens": [... |
08a559cec827ace529da82b6b1ec2d7a2f1f2d98 | mimoralea/king-pong | agent.py | [
"MIT"
] | Python | learn_maybe | <not_specific> | def learn_maybe(self):
"""
This is the main training loop.
The agent would leave early if the train
attribute is not set to True and if the
observe period hasn't been completed.
It basically grabs a self.batch_size sample from the
memory bank, extrans the sars ob... |
This is the main training loop.
The agent would leave early if the train
attribute is not set to True and if the
observe period hasn't been completed.
It basically grabs a self.batch_size sample from the
memory bank, extrans the sars observations and it
batch tr... | This is the main training loop.
The agent would leave early if the train
attribute is not set to True and if the
observe period hasn't been completed.
It basically grabs a self.batch_size sample from the
memory bank, extrans the sars observations and it
batch trains the deep neural network | [
"This",
"is",
"the",
"main",
"training",
"loop",
".",
"The",
"agent",
"would",
"leave",
"early",
"if",
"the",
"train",
"attribute",
"is",
"not",
"set",
"to",
"True",
"and",
"if",
"the",
"observe",
"period",
"hasn",
"'",
"t",
"been",
"completed",
".",
"... | def learn_maybe(self):
if not self.train or self.step <= self.observe:
log.debug('No training the network. Train is set to ' + str(self.train) +
'. Current step is ' + str(self.step) +
' and observation period will end after ' + str(self.observe))
... | [
"def",
"learn_maybe",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"train",
"or",
"self",
".",
"step",
"<=",
"self",
".",
"observe",
":",
"log",
".",
"debug",
"(",
"'No training the network. Train is set to '",
"+",
"str",
"(",
"self",
".",
"train",
... | This is the main training loop. | [
"This",
"is",
"the",
"main",
"training",
"loop",
"."
] | [
"\"\"\"\n This is the main training loop.\n The agent would leave early if the train\n attribute is not set to True and if the\n observe period hasn't been completed.\n\n It basically grabs a self.batch_size sample from the\n memory bank, extrans the sars observations and i... | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
08a559cec827ace529da82b6b1ec2d7a2f1f2d98 | mimoralea/king-pong | agent.py | [
"MIT"
] | Python | act_and_perceive | <not_specific> | def act_and_perceive(self, action_selected, percept_stack):
"""
Acts in the environment. That is, it moves the game
one step further by passing the selected action,
it then reads what the environment had to say about that
and finally preprocesses the image into the format and
... |
Acts in the environment. That is, it moves the game
one step further by passing the selected action,
it then reads what the environment had to say about that
and finally preprocesses the image into the format and
size used by the network and appends the new image into the front
... | Acts in the environment. That is, it moves the game
one step further by passing the selected action,
it then reads what the environment had to say about that
and finally preprocesses the image into the format and
size used by the network and appends the new image into the front
of the image stack | [
"Acts",
"in",
"the",
"environment",
".",
"That",
"is",
"it",
"moves",
"the",
"game",
"one",
"step",
"further",
"by",
"passing",
"the",
"selected",
"action",
"it",
"then",
"reads",
"what",
"the",
"environment",
"had",
"to",
"say",
"about",
"that",
"and",
... | def act_and_perceive(self, action_selected, percept_stack):
log.debug('acting with ' + str(action_selected))
new_percept, reward = self.environment.frame_step(action_selected)
log.debug('got reward of ' + str(reward))
new_percept = self.perception.preprocess_percepts(new_percept)
... | [
"def",
"act_and_perceive",
"(",
"self",
",",
"action_selected",
",",
"percept_stack",
")",
":",
"log",
".",
"debug",
"(",
"'acting with '",
"+",
"str",
"(",
"action_selected",
")",
")",
"new_percept",
",",
"reward",
"=",
"self",
".",
"environment",
".",
"fra... | Acts in the environment. | [
"Acts",
"in",
"the",
"environment",
"."
] | [
"\"\"\"\n Acts in the environment. That is, it moves the game\n one step further by passing the selected action,\n it then reads what the environment had to say about that\n and finally preprocesses the image into the format and\n size used by the network and appends the new image... | [
{
"param": "self",
"type": null
},
{
"param": "action_selected",
"type": null
},
{
"param": "percept_stack",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "action_selected",
"type": null,
"docstring": null,
"docstring... |
08a559cec827ace529da82b6b1ec2d7a2f1f2d98 | mimoralea/king-pong | agent.py | [
"MIT"
] | Python | exist | null | def exist(self, percept_stack):
"""
Main agent loop that selects and action, acts, remembers
what happen, learns, updates, saves the progress and
decides if it should die
"""
log.debug('entering main agent loop')
while True:
start = time.time()
... |
Main agent loop that selects and action, acts, remembers
what happen, learns, updates, saves the progress and
decides if it should die
| Main agent loop that selects and action, acts, remembers
what happen, learns, updates, saves the progress and
decides if it should die | [
"Main",
"agent",
"loop",
"that",
"selects",
"and",
"action",
"acts",
"remembers",
"what",
"happen",
"learns",
"updates",
"saves",
"the",
"progress",
"and",
"decides",
"if",
"it",
"should",
"die"
] | def exist(self, percept_stack):
log.debug('entering main agent loop')
while True:
start = time.time()
action_selected = self.select_action(percept_stack)
new_percept_stack, reward = self.act_and_perceive(action_selected, percept_stack)
log.debug("act and p... | [
"def",
"exist",
"(",
"self",
",",
"percept_stack",
")",
":",
"log",
".",
"debug",
"(",
"'entering main agent loop'",
")",
"while",
"True",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"action_selected",
"=",
"self",
".",
"select_action",
"(",
"percept... | Main agent loop that selects and action, acts, remembers
what happen, learns, updates, saves the progress and
decides if it should die | [
"Main",
"agent",
"loop",
"that",
"selects",
"and",
"action",
"acts",
"remembers",
"what",
"happen",
"learns",
"updates",
"saves",
"the",
"progress",
"and",
"decides",
"if",
"it",
"should",
"die"
] | [
"\"\"\"\n Main agent loop that selects and action, acts, remembers\n what happen, learns, updates, saves the progress and\n decides if it should die\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "percept_stack",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "percept_stack",
"type": null,
"docstring": null,
"docstring_t... |
08a559cec827ace529da82b6b1ec2d7a2f1f2d98 | mimoralea/king-pong | agent.py | [
"MIT"
] | Python | main | null | def main(args):
"""
Sets up the environment, loads the agent, prepares the
first action and moves the game a single frame
and then enters the agents main loop
"""
log.info('Verbose output enabled ' + str(log.getLogger().getEffectiveLevel()))
log.debug(args)
npixels, nactions, nimages = ... |
Sets up the environment, loads the agent, prepares the
first action and moves the game a single frame
and then enters the agents main loop
| Sets up the environment, loads the agent, prepares the
first action and moves the game a single frame
and then enters the agents main loop | [
"Sets",
"up",
"the",
"environment",
"loads",
"the",
"agent",
"prepares",
"the",
"first",
"action",
"and",
"moves",
"the",
"game",
"a",
"single",
"frame",
"and",
"then",
"enters",
"the",
"agents",
"main",
"loop"
] | def main(args):
log.info('Verbose output enabled ' + str(log.getLogger().getEffectiveLevel()))
log.debug(args)
npixels, nactions, nimages = 80, 3, 4
agent = DeepLearningAgent(npixels, npixels, nactions, nimages, args.reset, args.train)
log.info('agent loaded successfully')
agent.environment.firs... | [
"def",
"main",
"(",
"args",
")",
":",
"log",
".",
"info",
"(",
"'Verbose output enabled '",
"+",
"str",
"(",
"log",
".",
"getLogger",
"(",
")",
".",
"getEffectiveLevel",
"(",
")",
")",
")",
"log",
".",
"debug",
"(",
"args",
")",
"npixels",
",",
"nact... | Sets up the environment, loads the agent, prepares the
first action and moves the game a single frame
and then enters the agents main loop | [
"Sets",
"up",
"the",
"environment",
"loads",
"the",
"agent",
"prepares",
"the",
"first",
"action",
"and",
"moves",
"the",
"game",
"a",
"single",
"frame",
"and",
"then",
"enters",
"the",
"agents",
"main",
"loop"
] | [
"\"\"\"\n Sets up the environment, loads the agent, prepares the\n first action and moves the game a single frame\n and then enters the agents main loop\n \"\"\"",
"# 0 action is do nothing, 1 is up, 2 is down"
] | [
{
"param": "args",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "args",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
aa7b1b31aa76080edd0039406e49c8777b5a7235 | architecture-building-systems/esoreader | esoreader.py | [
"MIT"
] | Python | read | <not_specific> | def read(eso_file_path):
"""Read in an .eso file and return the data dictionary and a dictionary
representing the data.
NOTE: this function is here for backward compatibilty reasons. Use
read_from_path() instead to obtain an EsoFile object.
"""
eso = read_from_path(eso_file_path)
retu... | Read in an .eso file and return the data dictionary and a dictionary
representing the data.
NOTE: this function is here for backward compatibilty reasons. Use
read_from_path() instead to obtain an EsoFile object.
| Read in an .eso file and return the data dictionary and a dictionary
representing the data.
NOTE: this function is here for backward compatibilty reasons. Use
read_from_path() instead to obtain an EsoFile object. | [
"Read",
"in",
"an",
".",
"eso",
"file",
"and",
"return",
"the",
"data",
"dictionary",
"and",
"a",
"dictionary",
"representing",
"the",
"data",
".",
"NOTE",
":",
"this",
"function",
"is",
"here",
"for",
"backward",
"compatibilty",
"reasons",
".",
"Use",
"re... | def read(eso_file_path):
eso = read_from_path(eso_file_path)
return eso.dd, eso.data | [
"def",
"read",
"(",
"eso_file_path",
")",
":",
"eso",
"=",
"read_from_path",
"(",
"eso_file_path",
")",
"return",
"eso",
".",
"dd",
",",
"eso",
".",
"data"
] | Read in an .eso file and return the data dictionary and a dictionary
representing the data. | [
"Read",
"in",
"an",
".",
"eso",
"file",
"and",
"return",
"the",
"data",
"dictionary",
"and",
"a",
"dictionary",
"representing",
"the",
"data",
"."
] | [
"\"\"\"Read in an .eso file and return the data dictionary and a dictionary\r\n representing the data.\r\n NOTE: this function is here for backward compatibilty reasons. Use\r\n read_from_path() instead to obtain an EsoFile object.\r\n \"\"\""
] | [
{
"param": "eso_file_path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "eso_file_path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
aa7b1b31aa76080edd0039406e49c8777b5a7235 | architecture-building-systems/esoreader | esoreader.py | [
"MIT"
] | Python | read_from_path | <not_specific> | def read_from_path(eso_file_path):
"""
read in a .eso file and return an EsoFile object that can be used
to read in pandas DataFrame and Series objects.
"""
with open(eso_file_path, 'r') as eso_file:
eso = EsoFile(eso_file)
return eso |
read in a .eso file and return an EsoFile object that can be used
to read in pandas DataFrame and Series objects.
| read in a .eso file and return an EsoFile object that can be used
to read in pandas DataFrame and Series objects. | [
"read",
"in",
"a",
".",
"eso",
"file",
"and",
"return",
"an",
"EsoFile",
"object",
"that",
"can",
"be",
"used",
"to",
"read",
"in",
"pandas",
"DataFrame",
"and",
"Series",
"objects",
"."
] | def read_from_path(eso_file_path):
with open(eso_file_path, 'r') as eso_file:
eso = EsoFile(eso_file)
return eso | [
"def",
"read_from_path",
"(",
"eso_file_path",
")",
":",
"with",
"open",
"(",
"eso_file_path",
",",
"'r'",
")",
"as",
"eso_file",
":",
"eso",
"=",
"EsoFile",
"(",
"eso_file",
")",
"return",
"eso"
] | read in a .eso file and return an EsoFile object that can be used
to read in pandas DataFrame and Series objects. | [
"read",
"in",
"a",
".",
"eso",
"file",
"and",
"return",
"an",
"EsoFile",
"object",
"that",
"can",
"be",
"used",
"to",
"read",
"in",
"pandas",
"DataFrame",
"and",
"Series",
"objects",
"."
] | [
"\"\"\"\r\n read in a .eso file and return an EsoFile object that can be used\r\n to read in pandas DataFrame and Series objects.\r\n \"\"\""
] | [
{
"param": "eso_file_path",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "eso_file_path",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
aa7b1b31aa76080edd0039406e49c8777b5a7235 | architecture-building-systems/esoreader | esoreader.py | [
"MIT"
] | Python | build_index | null | def build_index(self):
"""builds a reverse index for finding ids.
"""
for id, value in self.variables.items():
reporting_frequency, key, variable, unit = value
self.index[reporting_frequency, key, variable] = id | builds a reverse index for finding ids.
| builds a reverse index for finding ids. | [
"builds",
"a",
"reverse",
"index",
"for",
"finding",
"ids",
"."
] | def build_index(self):
for id, value in self.variables.items():
reporting_frequency, key, variable, unit = value
self.index[reporting_frequency, key, variable] = id | [
"def",
"build_index",
"(",
"self",
")",
":",
"for",
"id",
",",
"value",
"in",
"self",
".",
"variables",
".",
"items",
"(",
")",
":",
"reporting_frequency",
",",
"key",
",",
"variable",
",",
"unit",
"=",
"value",
"self",
".",
"index",
"[",
"reporting_fr... | builds a reverse index for finding ids. | [
"builds",
"a",
"reverse",
"index",
"for",
"finding",
"ids",
"."
] | [
"\"\"\"builds a reverse index for finding ids.\r\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
aa7b1b31aa76080edd0039406e49c8777b5a7235 | architecture-building-systems/esoreader | esoreader.py | [
"MIT"
] | Python | find_variable | <not_specific> | def find_variable(self, search):
"""returns the coordinates (timestep, key, variable_name) in the
data dictionary that can be used to find an index. The search is case
insensitive."""
return [(timestep, key, variable_name)
for timestep, key, variable_name in self.ind... | returns the coordinates (timestep, key, variable_name) in the
data dictionary that can be used to find an index. The search is case
insensitive. | returns the coordinates (timestep, key, variable_name) in the
data dictionary that can be used to find an index. The search is case
insensitive. | [
"returns",
"the",
"coordinates",
"(",
"timestep",
"key",
"variable_name",
")",
"in",
"the",
"data",
"dictionary",
"that",
"can",
"be",
"used",
"to",
"find",
"an",
"index",
".",
"The",
"search",
"is",
"case",
"insensitive",
"."
] | def find_variable(self, search):
return [(timestep, key, variable_name)
for timestep, key, variable_name in self.index.keys()
if search.lower() in variable_name.lower()] | [
"def",
"find_variable",
"(",
"self",
",",
"search",
")",
":",
"return",
"[",
"(",
"timestep",
",",
"key",
",",
"variable_name",
")",
"for",
"timestep",
",",
"key",
",",
"variable_name",
"in",
"self",
".",
"index",
".",
"keys",
"(",
")",
"if",
"search",... | returns the coordinates (timestep, key, variable_name) in the
data dictionary that can be used to find an index. | [
"returns",
"the",
"coordinates",
"(",
"timestep",
"key",
"variable_name",
")",
"in",
"the",
"data",
"dictionary",
"that",
"can",
"be",
"used",
"to",
"find",
"an",
"index",
"."
] | [
"\"\"\"returns the coordinates (timestep, key, variable_name) in the\r\n data dictionary that can be used to find an index. The search is case\r\n insensitive.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "search",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "search",
"type": null,
"docstring": null,
"docstring_tokens":... |
aa7b1b31aa76080edd0039406e49c8777b5a7235 | architecture-building-systems/esoreader | esoreader.py | [
"MIT"
] | Python | find_variable | <not_specific> | def find_variable(self, search, key=None, frequency='TimeStep'):
"""returns the coordinates (timestep, key, variable_name) in the
data dictionary that can be used to find an index. The search is case
insensitive and need only be specified partially."""
variables = self.dd.find_variab... | returns the coordinates (timestep, key, variable_name) in the
data dictionary that can be used to find an index. The search is case
insensitive and need only be specified partially. | returns the coordinates (timestep, key, variable_name) in the
data dictionary that can be used to find an index. The search is case
insensitive and need only be specified partially. | [
"returns",
"the",
"coordinates",
"(",
"timestep",
"key",
"variable_name",
")",
"in",
"the",
"data",
"dictionary",
"that",
"can",
"be",
"used",
"to",
"find",
"an",
"index",
".",
"The",
"search",
"is",
"case",
"insensitive",
"and",
"need",
"only",
"be",
"spe... | def find_variable(self, search, key=None, frequency='TimeStep'):
variables = self.dd.find_variable(search)
variables = [v for v in variables
if v[0].lower() == frequency.lower()]
if key:
variables = [v for v in variables
if v[1].lower() =... | [
"def",
"find_variable",
"(",
"self",
",",
"search",
",",
"key",
"=",
"None",
",",
"frequency",
"=",
"'TimeStep'",
")",
":",
"variables",
"=",
"self",
".",
"dd",
".",
"find_variable",
"(",
"search",
")",
"variables",
"=",
"[",
"v",
"for",
"v",
"in",
"... | returns the coordinates (timestep, key, variable_name) in the
data dictionary that can be used to find an index. | [
"returns",
"the",
"coordinates",
"(",
"timestep",
"key",
"variable_name",
")",
"in",
"the",
"data",
"dictionary",
"that",
"can",
"be",
"used",
"to",
"find",
"an",
"index",
"."
] | [
"\"\"\"returns the coordinates (timestep, key, variable_name) in the\r\n data dictionary that can be used to find an index. The search is case\r\n insensitive and need only be specified partially.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "search",
"type": null
},
{
"param": "key",
"type": null
},
{
"param": "frequency",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "search",
"type": null,
"docstring": null,
"docstring_tokens":... |
aa7b1b31aa76080edd0039406e49c8777b5a7235 | architecture-building-systems/esoreader | esoreader.py | [
"MIT"
] | Python | to_frame | <not_specific> | def to_frame(self, search, key=None, frequency='TimeStep', index=None, use_key_for_columns=True):
"""
creates a pandas DataFrame objects with a column for every variable
that matches the search pattern and key. An None key matches all keys.
NOTE: The frequency *has* to be the same fo... |
creates a pandas DataFrame objects with a column for every variable
that matches the search pattern and key. An None key matches all keys.
NOTE: The frequency *has* to be the same for all variables selected.
(uses find_variable to select the variables)
| creates a pandas DataFrame objects with a column for every variable
that matches the search pattern and key. An None key matches all keys.
NOTE: The frequency *has* to be the same for all variables selected.
(uses find_variable to select the variables) | [
"creates",
"a",
"pandas",
"DataFrame",
"objects",
"with",
"a",
"column",
"for",
"every",
"variable",
"that",
"matches",
"the",
"search",
"pattern",
"and",
"key",
".",
"An",
"None",
"key",
"matches",
"all",
"keys",
".",
"NOTE",
":",
"The",
"frequency",
"*",... | def to_frame(self, search, key=None, frequency='TimeStep', index=None, use_key_for_columns=True):
from pandas import DataFrame
variables = self.find_variable(search, key=key, frequency=frequency)
if use_key_for_columns:
data = {v[1]: self.data[self.dd.index[v]] for v in variables}
... | [
"def",
"to_frame",
"(",
"self",
",",
"search",
",",
"key",
"=",
"None",
",",
"frequency",
"=",
"'TimeStep'",
",",
"index",
"=",
"None",
",",
"use_key_for_columns",
"=",
"True",
")",
":",
"from",
"pandas",
"import",
"DataFrame",
"variables",
"=",
"self",
... | creates a pandas DataFrame objects with a column for every variable
that matches the search pattern and key. | [
"creates",
"a",
"pandas",
"DataFrame",
"objects",
"with",
"a",
"column",
"for",
"every",
"variable",
"that",
"matches",
"the",
"search",
"pattern",
"and",
"key",
"."
] | [
"\"\"\"\r\n creates a pandas DataFrame objects with a column for every variable\r\n that matches the search pattern and key. An None key matches all keys.\r\n NOTE: The frequency *has* to be the same for all variables selected.\r\n (uses find_variable to select the variables)\r\n ... | [
{
"param": "self",
"type": null
},
{
"param": "search",
"type": null
},
{
"param": "key",
"type": null
},
{
"param": "frequency",
"type": null
},
{
"param": "index",
"type": null
},
{
"param": "use_key_for_columns",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "search",
"type": null,
"docstring": null,
"docstring_tokens":... |
aa7b1b31aa76080edd0039406e49c8777b5a7235 | architecture-building-systems/esoreader | esoreader.py | [
"MIT"
] | Python | _read_data_dictionary | <not_specific> | def _read_data_dictionary(self):
"""parses the head of the eso_file, returning the data dictionary.
the file object eso_file is advanced to the position needed by
read_data.
"""
version, timestamp = [s.strip() for s
in self.eso_file.readline().... | parses the head of the eso_file, returning the data dictionary.
the file object eso_file is advanced to the position needed by
read_data.
| parses the head of the eso_file, returning the data dictionary.
the file object eso_file is advanced to the position needed by
read_data. | [
"parses",
"the",
"head",
"of",
"the",
"eso_file",
"returning",
"the",
"data",
"dictionary",
".",
"the",
"file",
"object",
"eso_file",
"is",
"advanced",
"to",
"the",
"position",
"needed",
"by",
"read_data",
"."
] | def _read_data_dictionary(self):
version, timestamp = [s.strip() for s
in self.eso_file.readline().split(',')[-2:]]
dd = DataDictionary(version, timestamp)
line = self.eso_file.readline().strip()
while line != 'End of Data Dictionary':
line, repo... | [
"def",
"_read_data_dictionary",
"(",
"self",
")",
":",
"version",
",",
"timestamp",
"=",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"self",
".",
"eso_file",
".",
"readline",
"(",
")",
".",
"split",
"(",
"','",
")",
"[",
"-",
"2",
":",
"]... | parses the head of the eso_file, returning the data dictionary. | [
"parses",
"the",
"head",
"of",
"the",
"eso_file",
"returning",
"the",
"data",
"dictionary",
"."
] | [
"\"\"\"parses the head of the eso_file, returning the data dictionary.\r\n the file object eso_file is advanced to the position needed by\r\n read_data.\r\n \"\"\"",
"# ignore the lines that aren't report variables\r"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
aa7b1b31aa76080edd0039406e49c8777b5a7235 | architecture-building-systems/esoreader | esoreader.py | [
"MIT"
] | Python | _read_data | <not_specific> | def _read_data(self):
'''parse the data from the .eso file returning,
NOTE: eso_file should be the same file object that was passed to
read_data_dictionary(eso_file) to obtain dd.'''
data = {} # id => [value]
for id in self.dd.variables.keys():
data[id] = []
... | parse the data from the .eso file returning,
NOTE: eso_file should be the same file object that was passed to
read_data_dictionary(eso_file) to obtain dd. | parse the data from the .eso file returning,
NOTE: eso_file should be the same file object that was passed to
read_data_dictionary(eso_file) to obtain dd. | [
"parse",
"the",
"data",
"from",
"the",
".",
"eso",
"file",
"returning",
"NOTE",
":",
"eso_file",
"should",
"be",
"the",
"same",
"file",
"object",
"that",
"was",
"passed",
"to",
"read_data_dictionary",
"(",
"eso_file",
")",
"to",
"obtain",
"dd",
"."
] | def _read_data(self):
data = {}
for id in self.dd.variables.keys():
data[id] = []
for line in self.eso_file:
if line.startswith('End of Data'):
break
fields = [f.strip() for f in line.split(',')]
id = int(fields[0])
if... | [
"def",
"_read_data",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"for",
"id",
"in",
"self",
".",
"dd",
".",
"variables",
".",
"keys",
"(",
")",
":",
"data",
"[",
"id",
"]",
"=",
"[",
"]",
"for",
"line",
"in",
"self",
".",
"eso_file",
":",
"... | parse the data from the .eso file returning,
NOTE: eso_file should be the same file object that was passed to
read_data_dictionary(eso_file) to obtain dd. | [
"parse",
"the",
"data",
"from",
"the",
".",
"eso",
"file",
"returning",
"NOTE",
":",
"eso_file",
"should",
"be",
"the",
"same",
"file",
"object",
"that",
"was",
"passed",
"to",
"read_data_dictionary",
"(",
"eso_file",
")",
"to",
"obtain",
"dd",
"."
] | [
"'''parse the data from the .eso file returning,\r\n NOTE: eso_file should be the same file object that was passed to\r\n read_data_dictionary(eso_file) to obtain dd.'''",
"# id => [value]\r",
"# skip entries that are not output:variables\r"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
d173bacf892e0ad8ce4540fe4c7b4d70f6b2a94e | evgenii-nikishin/omd | cartpole/omd.py | [
"MIT"
] | Python | constraint_func | <not_specific> | def constraint_func(self, params_T, params_Q, replay, rng, target_params_Q):
'''Parameterized by T function giving grad_Q (Bellman-error) = 0 constraint.
'''
replay_model, _ = self.batch_real_to_model(params_T, replay, rng)
grads, aux_out = jax.grad(self.loss_Q, has_aux=True)(
params_Q, target_par... | Parameterized by T function giving grad_Q (Bellman-error) = 0 constraint.
| Parameterized by T function giving grad_Q (Bellman-error) = 0 constraint. | [
"Parameterized",
"by",
"T",
"function",
"giving",
"grad_Q",
"(",
"Bellman",
"-",
"error",
")",
"=",
"0",
"constraint",
"."
] | def constraint_func(self, params_T, params_Q, replay, rng, target_params_Q):
replay_model, _ = self.batch_real_to_model(params_T, replay, rng)
grads, aux_out = jax.grad(self.loss_Q, has_aux=True)(
params_Q, target_params_Q, replay_model)
return grads | [
"def",
"constraint_func",
"(",
"self",
",",
"params_T",
",",
"params_Q",
",",
"replay",
",",
"rng",
",",
"target_params_Q",
")",
":",
"replay_model",
",",
"_",
"=",
"self",
".",
"batch_real_to_model",
"(",
"params_T",
",",
"replay",
",",
"rng",
")",
"grads... | Parameterized by T function giving grad_Q (Bellman-error) = 0 constraint. | [
"Parameterized",
"by",
"T",
"function",
"giving",
"grad_Q",
"(",
"Bellman",
"-",
"error",
")",
"=",
"0",
"constraint",
"."
] | [
"'''Parameterized by T function giving grad_Q (Bellman-error) = 0 constraint.\n '''"
] | [
{
"param": "self",
"type": null
},
{
"param": "params_T",
"type": null
},
{
"param": "params_Q",
"type": null
},
{
"param": "replay",
"type": null
},
{
"param": "rng",
"type": null
},
{
"param": "target_params_Q",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "params_T",
"type": null,
"docstring": null,
"docstring_tokens... |
7d7da1e225412585d496e05d487351df12a09ed3 | evgenii-nikishin/omd | mujoco/jax_rl/agents/omd/model.py | [
"MIT"
] | Python | fwd_solver | <not_specific> | def fwd_solver(constraint_func: Callable, omd: ModelActorCriticTemp,
model_params: Params, batch: Batch, discount: float, tau: float,
target_entropy: float):
"""Get Q_* satisfying the constraint (approximately). Makes K grad updates.
"""
for _ in range(FLAGS.config.inner_steps... | Get Q_* satisfying the constraint (approximately). Makes K grad updates.
| Get Q_* satisfying the constraint (approximately). Makes K grad updates. | [
"Get",
"Q_",
"*",
"satisfying",
"the",
"constraint",
"(",
"approximately",
")",
".",
"Makes",
"K",
"grad",
"updates",
"."
] | def fwd_solver(constraint_func: Callable, omd: ModelActorCriticTemp,
model_params: Params, batch: Batch, discount: float, tau: float,
target_entropy: float):
for _ in range(FLAGS.config.inner_steps):
omd, critic_info = critic.update(omd,
... | [
"def",
"fwd_solver",
"(",
"constraint_func",
":",
"Callable",
",",
"omd",
":",
"ModelActorCriticTemp",
",",
"model_params",
":",
"Params",
",",
"batch",
":",
"Batch",
",",
"discount",
":",
"float",
",",
"tau",
":",
"float",
",",
"target_entropy",
":",
"float... | Get Q_* satisfying the constraint (approximately). | [
"Get",
"Q_",
"*",
"satisfying",
"the",
"constraint",
"(",
"approximately",
")",
"."
] | [
"\"\"\"Get Q_* satisfying the constraint (approximately). Makes K grad updates.\n \"\"\"",
"# note that actor and temp do not use next_observations and rewards"
] | [
{
"param": "constraint_func",
"type": "Callable"
},
{
"param": "omd",
"type": "ModelActorCriticTemp"
},
{
"param": "model_params",
"type": "Params"
},
{
"param": "batch",
"type": "Batch"
},
{
"param": "discount",
"type": "float"
},
{
"param": "tau",
... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "constraint_func",
"type": "Callable",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "omd",
"type": "ModelActorCriticTemp",
"docstring":... |
419d484a213bce334b8f466ddc487b4de43f6a55 | estin/django-json-rpc | jsonrpc/proxy.py | [
"MIT"
] | Python | send_payload | <not_specific> | def send_payload(self, params):
"""Performs the actual sending action and returns the result"""
return urllib.urlopen(self.service_url,
dumps({
"jsonrpc": self.version,
"method": self.service_name,
'params': params,
... | Performs the actual sending action and returns the result | Performs the actual sending action and returns the result | [
"Performs",
"the",
"actual",
"sending",
"action",
"and",
"returns",
"the",
"result"
] | def send_payload(self, params):
return urllib.urlopen(self.service_url,
dumps({
"jsonrpc": self.version,
"method": self.service_name,
'params': params,
'id': str(uuid.uuid1())})).read() | [
"def",
"send_payload",
"(",
"self",
",",
"params",
")",
":",
"return",
"urllib",
".",
"urlopen",
"(",
"self",
".",
"service_url",
",",
"dumps",
"(",
"{",
"\"jsonrpc\"",
":",
"self",
".",
"version",
",",
"\"method\"",
":",
"self",
".",
"service_name",
","... | Performs the actual sending action and returns the result | [
"Performs",
"the",
"actual",
"sending",
"action",
"and",
"returns",
"the",
"result"
] | [
"\"\"\"Performs the actual sending action and returns the result\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "params",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "params",
"type": null,
"docstring": null,
"docstring_tokens":... |
5f913d237cce9d491844bd8e4dc1c5d01ccaea01 | zapisnicar/epsracun | eracuni/browser.py | [
"MIT"
] | Python | firefox | webdriver | def firefox(config: Config) -> webdriver:
"""
Start browser with disabled "Save PDF" dialog
Download files to var folder
"""
my_options = Options()
if config.headless:
my_options.headless = True
my_options.add_argument('--window-size=1920,1200')
my_profile = webdriver.Firefox... |
Start browser with disabled "Save PDF" dialog
Download files to var folder
| Start browser with disabled "Save PDF" dialog
Download files to var folder | [
"Start",
"browser",
"with",
"disabled",
"\"",
"Save",
"PDF",
"\"",
"dialog",
"Download",
"files",
"to",
"var",
"folder"
] | def firefox(config: Config) -> webdriver:
my_options = Options()
if config.headless:
my_options.headless = True
my_options.add_argument('--window-size=1920,1200')
my_profile = webdriver.FirefoxProfile()
my_profile.set_preference('general.useragent.override', config.user_agent)
my_pro... | [
"def",
"firefox",
"(",
"config",
":",
"Config",
")",
"->",
"webdriver",
":",
"my_options",
"=",
"Options",
"(",
")",
"if",
"config",
".",
"headless",
":",
"my_options",
".",
"headless",
"=",
"True",
"my_options",
".",
"add_argument",
"(",
"'--window-size=192... | Start browser with disabled "Save PDF" dialog
Download files to var folder | [
"Start",
"browser",
"with",
"disabled",
"\"",
"Save",
"PDF",
"\"",
"dialog",
"Download",
"files",
"to",
"var",
"folder"
] | [
"\"\"\"\n Start browser with disabled \"Save PDF\" dialog\n Download files to var folder\n \"\"\""
] | [
{
"param": "config",
"type": "Config"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "config",
"type": "Config",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
5f913d237cce9d491844bd8e4dc1c5d01ccaea01 | zapisnicar/epsracun | eracuni/browser.py | [
"MIT"
] | Python | find_first_by_id | webdriver | def find_first_by_id(browser: webdriver, target: str) -> webdriver:
"""
Locate web element by id attribute
Return first one
Catch No Such Element Exception error, report problem to stderr and quit with exit code 1
"""
try:
element = browser.find_element_by_id(target)
return eleme... |
Locate web element by id attribute
Return first one
Catch No Such Element Exception error, report problem to stderr and quit with exit code 1
| Locate web element by id attribute
Return first one
Catch No Such Element Exception error, report problem to stderr and quit with exit code 1 | [
"Locate",
"web",
"element",
"by",
"id",
"attribute",
"Return",
"first",
"one",
"Catch",
"No",
"Such",
"Element",
"Exception",
"error",
"report",
"problem",
"to",
"stderr",
"and",
"quit",
"with",
"exit",
"code",
"1"
] | def find_first_by_id(browser: webdriver, target: str) -> webdriver:
try:
element = browser.find_element_by_id(target)
return element
except NoSuchElementException:
print(f"Can't find id: {target}", file=sys.stderr)
browser.quit()
sys.exit(1) | [
"def",
"find_first_by_id",
"(",
"browser",
":",
"webdriver",
",",
"target",
":",
"str",
")",
"->",
"webdriver",
":",
"try",
":",
"element",
"=",
"browser",
".",
"find_element_by_id",
"(",
"target",
")",
"return",
"element",
"except",
"NoSuchElementException",
... | Locate web element by id attribute
Return first one
Catch No Such Element Exception error, report problem to stderr and quit with exit code 1 | [
"Locate",
"web",
"element",
"by",
"id",
"attribute",
"Return",
"first",
"one",
"Catch",
"No",
"Such",
"Element",
"Exception",
"error",
"report",
"problem",
"to",
"stderr",
"and",
"quit",
"with",
"exit",
"code",
"1"
] | [
"\"\"\"\n Locate web element by id attribute\n Return first one\n Catch No Such Element Exception error, report problem to stderr and quit with exit code 1\n \"\"\""
] | [
{
"param": "browser",
"type": "webdriver"
},
{
"param": "target",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "browser",
"type": "webdriver",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "target",
"type": "str",
"docstring": null,
"docstri... |
5f913d237cce9d491844bd8e4dc1c5d01ccaea01 | zapisnicar/epsracun | eracuni/browser.py | [
"MIT"
] | Python | find_first_by_css | webdriver | def find_first_by_css(browser: webdriver, target: str) -> webdriver:
"""
Locate web element by css selector
Return first one
Catch No Such Element Exception error, report problem to stderr and quit with exit code 1
"""
try:
element = browser.find_element_by_css_selector(target)
r... |
Locate web element by css selector
Return first one
Catch No Such Element Exception error, report problem to stderr and quit with exit code 1
| Locate web element by css selector
Return first one
Catch No Such Element Exception error, report problem to stderr and quit with exit code 1 | [
"Locate",
"web",
"element",
"by",
"css",
"selector",
"Return",
"first",
"one",
"Catch",
"No",
"Such",
"Element",
"Exception",
"error",
"report",
"problem",
"to",
"stderr",
"and",
"quit",
"with",
"exit",
"code",
"1"
] | def find_first_by_css(browser: webdriver, target: str) -> webdriver:
try:
element = browser.find_element_by_css_selector(target)
return element
except NoSuchElementException:
print(f"Can't find CSS selector: {target}", file=sys.stderr)
browser.quit()
sys.exit(1) | [
"def",
"find_first_by_css",
"(",
"browser",
":",
"webdriver",
",",
"target",
":",
"str",
")",
"->",
"webdriver",
":",
"try",
":",
"element",
"=",
"browser",
".",
"find_element_by_css_selector",
"(",
"target",
")",
"return",
"element",
"except",
"NoSuchElementExc... | Locate web element by css selector
Return first one
Catch No Such Element Exception error, report problem to stderr and quit with exit code 1 | [
"Locate",
"web",
"element",
"by",
"css",
"selector",
"Return",
"first",
"one",
"Catch",
"No",
"Such",
"Element",
"Exception",
"error",
"report",
"problem",
"to",
"stderr",
"and",
"quit",
"with",
"exit",
"code",
"1"
] | [
"\"\"\"\n Locate web element by css selector\n Return first one\n Catch No Such Element Exception error, report problem to stderr and quit with exit code 1\n \"\"\""
] | [
{
"param": "browser",
"type": "webdriver"
},
{
"param": "target",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "browser",
"type": "webdriver",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "target",
"type": "str",
"docstring": null,
"docstri... |
5f913d237cce9d491844bd8e4dc1c5d01ccaea01 | zapisnicar/epsracun | eracuni/browser.py | [
"MIT"
] | Python | find_all_by_css | List[Any] | def find_all_by_css(browser: webdriver, target: str) -> List[Any]:
"""
Locate all web elements by css selector
Return list of elements
Catch No Such Element Exception error, report problem to stderr and quit with exit code 1
"""
try:
elements = browser.find_elements_by_css_selector(targe... |
Locate all web elements by css selector
Return list of elements
Catch No Such Element Exception error, report problem to stderr and quit with exit code 1
| Locate all web elements by css selector
Return list of elements
Catch No Such Element Exception error, report problem to stderr and quit with exit code 1 | [
"Locate",
"all",
"web",
"elements",
"by",
"css",
"selector",
"Return",
"list",
"of",
"elements",
"Catch",
"No",
"Such",
"Element",
"Exception",
"error",
"report",
"problem",
"to",
"stderr",
"and",
"quit",
"with",
"exit",
"code",
"1"
] | def find_all_by_css(browser: webdriver, target: str) -> List[Any]:
try:
elements = browser.find_elements_by_css_selector(target)
return elements
except NoSuchElementException:
print(f"Can't find CSS selector: {target}", file=sys.stderr)
browser.quit()
sys.exit(1) | [
"def",
"find_all_by_css",
"(",
"browser",
":",
"webdriver",
",",
"target",
":",
"str",
")",
"->",
"List",
"[",
"Any",
"]",
":",
"try",
":",
"elements",
"=",
"browser",
".",
"find_elements_by_css_selector",
"(",
"target",
")",
"return",
"elements",
"except",
... | Locate all web elements by css selector
Return list of elements
Catch No Such Element Exception error, report problem to stderr and quit with exit code 1 | [
"Locate",
"all",
"web",
"elements",
"by",
"css",
"selector",
"Return",
"list",
"of",
"elements",
"Catch",
"No",
"Such",
"Element",
"Exception",
"error",
"report",
"problem",
"to",
"stderr",
"and",
"quit",
"with",
"exit",
"code",
"1"
] | [
"\"\"\"\n Locate all web elements by css selector\n Return list of elements\n Catch No Such Element Exception error, report problem to stderr and quit with exit code 1\n \"\"\""
] | [
{
"param": "browser",
"type": "webdriver"
},
{
"param": "target",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "browser",
"type": "webdriver",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "target",
"type": "str",
"docstring": null,
"docstri... |
5f913d237cce9d491844bd8e4dc1c5d01ccaea01 | zapisnicar/epsracun | eracuni/browser.py | [
"MIT"
] | Python | remove_element_by_css | None | def remove_element_by_css(browser: webdriver, target: str) -> None:
"""
Locate element by CSS selector, and remove it from DOM, with JavasScript code
"""
browser.execute_script(f"""
var element = document.querySelector("{target}");
if (element)
element.parentNode.removeChild(element);
... |
Locate element by CSS selector, and remove it from DOM, with JavasScript code
| Locate element by CSS selector, and remove it from DOM, with JavasScript code | [
"Locate",
"element",
"by",
"CSS",
"selector",
"and",
"remove",
"it",
"from",
"DOM",
"with",
"JavasScript",
"code"
] | def remove_element_by_css(browser: webdriver, target: str) -> None:
browser.execute_script(f"""
var element = document.querySelector("{target}");
if (element)
element.parentNode.removeChild(element);
""") | [
"def",
"remove_element_by_css",
"(",
"browser",
":",
"webdriver",
",",
"target",
":",
"str",
")",
"->",
"None",
":",
"browser",
".",
"execute_script",
"(",
"f\"\"\"\n var element = document.querySelector(\"{target}\");\n if (element)\n element.parentNode.removeChild(... | Locate element by CSS selector, and remove it from DOM, with JavasScript code | [
"Locate",
"element",
"by",
"CSS",
"selector",
"and",
"remove",
"it",
"from",
"DOM",
"with",
"JavasScript",
"code"
] | [
"\"\"\"\n Locate element by CSS selector, and remove it from DOM, with JavasScript code\n \"\"\""
] | [
{
"param": "browser",
"type": "webdriver"
},
{
"param": "target",
"type": "str"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "browser",
"type": "webdriver",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "target",
"type": "str",
"docstring": null,
"docstri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.