repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.view_package_path | def view_package_path(self, package: str) -> _PATH:
'''Print the path to the APK of the given.'''
if package not in self.view_packgets_list():
raise NoSuchPackageException(
f'There is no such package {package!r}.')
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'pm', 'path', package)
return output[8:-1] | python | def view_package_path(self, package: str) -> _PATH:
'''Print the path to the APK of the given.'''
if package not in self.view_packgets_list():
raise NoSuchPackageException(
f'There is no such package {package!r}.')
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'pm', 'path', package)
return output[8:-1] | [
"def",
"view_package_path",
"(",
"self",
",",
"package",
":",
"str",
")",
"->",
"_PATH",
":",
"if",
"package",
"not",
"in",
"self",
".",
"view_packgets_list",
"(",
")",
":",
"raise",
"NoSuchPackageException",
"(",
"f'There is no such package {package!r}.'",
")",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'pm'",
",",
"'path'",
",",
"package",
")",
"return",
"output",
"[",
"8",
":",
"-",
"1",
"]"
]
| Print the path to the APK of the given. | [
"Print",
"the",
"path",
"to",
"the",
"APK",
"of",
"the",
"given",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L372-L379 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.view_focused_activity | def view_focused_activity(self) -> str:
'''View focused activity.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'activity', 'activities')
return re.findall(r'mFocusedActivity: .+(com[a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)', output)[0] | python | def view_focused_activity(self) -> str:
'''View focused activity.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'activity', 'activities')
return re.findall(r'mFocusedActivity: .+(com[a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)', output)[0] | [
"def",
"view_focused_activity",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'dumpsys'",
",",
"'activity'",
",",
"'activities'",
")",
"return",
"re",
".",
"findall",
"(",
"r'mFocusedActivity: .+(com[a-zA-Z0-9\\.]+/.[a-zA-Z0-9\\.]+)'",
",",
"output",
")",
"[",
"0",
"]"
]
| View focused activity. | [
"View",
"focused",
"activity",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L388-L392 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.view_running_services | def view_running_services(self, package: str='') -> str:
'''View running services.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'activity', 'services', package)
return output | python | def view_running_services(self, package: str='') -> str:
'''View running services.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'activity', 'services', package)
return output | [
"def",
"view_running_services",
"(",
"self",
",",
"package",
":",
"str",
"=",
"''",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'dumpsys'",
",",
"'activity'",
",",
"'services'",
",",
"package",
")",
"return",
"output"
]
| View running services. | [
"View",
"running",
"services",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L394-L398 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.view_package_info | def view_package_info(self, package: str='') -> str:
'''View package detail information.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'package', package)
return output | python | def view_package_info(self, package: str='') -> str:
'''View package detail information.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'package', package)
return output | [
"def",
"view_package_info",
"(",
"self",
",",
"package",
":",
"str",
"=",
"''",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'dumpsys'",
",",
"'package'",
",",
"package",
")",
"return",
"output"
]
| View package detail information. | [
"View",
"package",
"detail",
"information",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L400-L404 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.view_current_app_behavior | def view_current_app_behavior(self) -> str:
'''View application behavior in the current window.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'window', 'windows')
return re.findall(r'mCurrentFocus=.+(com[a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)', output)[0] | python | def view_current_app_behavior(self) -> str:
'''View application behavior in the current window.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'window', 'windows')
return re.findall(r'mCurrentFocus=.+(com[a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)', output)[0] | [
"def",
"view_current_app_behavior",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'dumpsys'",
",",
"'window'",
",",
"'windows'",
")",
"return",
"re",
".",
"findall",
"(",
"r'mCurrentFocus=.+(com[a-zA-Z0-9\\.]+/.[a-zA-Z0-9\\.]+)'",
",",
"output",
")",
"[",
"0",
"]"
]
| View application behavior in the current window. | [
"View",
"application",
"behavior",
"in",
"the",
"current",
"window",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L406-L410 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.view_surface_app_activity | def view_surface_app_activity(self) -> str:
'''Get package with activity of applications that are running in the foreground.'''
output, error = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'window', 'w')
return re.findall(r"name=([a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)", output) | python | def view_surface_app_activity(self) -> str:
'''Get package with activity of applications that are running in the foreground.'''
output, error = self._execute(
'-s', self.device_sn, 'shell', 'dumpsys', 'window', 'w')
return re.findall(r"name=([a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)", output) | [
"def",
"view_surface_app_activity",
"(",
"self",
")",
"->",
"str",
":",
"output",
",",
"error",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'dumpsys'",
",",
"'window'",
",",
"'w'",
")",
"return",
"re",
".",
"findall",
"(",
"r\"name=([a-zA-Z0-9\\.]+/.[a-zA-Z0-9\\.]+)\"",
",",
"output",
")"
]
| Get package with activity of applications that are running in the foreground. | [
"Get",
"package",
"with",
"activity",
"of",
"applications",
"that",
"are",
"running",
"in",
"the",
"foreground",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L412-L416 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.app_start_service | def app_start_service(self, *args) -> None:
'''Start a service.'''
_, error = self._execute('-s', self.device_sn,
'shell', 'am', 'startservice', *args)
if error and error.startswith('Error'):
raise ApplicationsException(error.split(':', 1)[-1].strip()) | python | def app_start_service(self, *args) -> None:
'''Start a service.'''
_, error = self._execute('-s', self.device_sn,
'shell', 'am', 'startservice', *args)
if error and error.startswith('Error'):
raise ApplicationsException(error.split(':', 1)[-1].strip()) | [
"def",
"app_start_service",
"(",
"self",
",",
"*",
"args",
")",
"->",
"None",
":",
"_",
",",
"error",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'am'",
",",
"'startservice'",
",",
"*",
"args",
")",
"if",
"error",
"and",
"error",
".",
"startswith",
"(",
"'Error'",
")",
":",
"raise",
"ApplicationsException",
"(",
"error",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
")"
]
| Start a service. | [
"Start",
"a",
"service",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L444-L449 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.app_broadcast | def app_broadcast(self, *args) -> None:
'''Send a broadcast.'''
_, error = self._execute('-s', self.device_sn, 'shell',
'am', 'broadcast', *args)
if error:
raise ApplicationsException(error.split(':', 1)[-1].strip()) | python | def app_broadcast(self, *args) -> None:
'''Send a broadcast.'''
_, error = self._execute('-s', self.device_sn, 'shell',
'am', 'broadcast', *args)
if error:
raise ApplicationsException(error.split(':', 1)[-1].strip()) | [
"def",
"app_broadcast",
"(",
"self",
",",
"*",
"args",
")",
"->",
"None",
":",
"_",
",",
"error",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'am'",
",",
"'broadcast'",
",",
"*",
"args",
")",
"if",
"error",
":",
"raise",
"ApplicationsException",
"(",
"error",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
")"
]
| Send a broadcast. | [
"Send",
"a",
"broadcast",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L458-L463 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.app_trim_memory | def app_trim_memory(self, pid: int or str, level: str = 'RUNNING_LOW') -> None:
'''Trim memory.
Args:
level: HIDDEN | RUNNING_MODERATE | BACKGROUNDRUNNING_LOW | \
MODERATE | RUNNING_CRITICAL | COMPLETE
'''
_, error = self._execute('-s', self.device_sn, 'shell',
'am', 'send-trim-memory', str(pid), level)
if error and error.startswith('Error'):
raise ApplicationsException(error.split(':', 1)[-1].strip()) | python | def app_trim_memory(self, pid: int or str, level: str = 'RUNNING_LOW') -> None:
'''Trim memory.
Args:
level: HIDDEN | RUNNING_MODERATE | BACKGROUNDRUNNING_LOW | \
MODERATE | RUNNING_CRITICAL | COMPLETE
'''
_, error = self._execute('-s', self.device_sn, 'shell',
'am', 'send-trim-memory', str(pid), level)
if error and error.startswith('Error'):
raise ApplicationsException(error.split(':', 1)[-1].strip()) | [
"def",
"app_trim_memory",
"(",
"self",
",",
"pid",
":",
"int",
"or",
"str",
",",
"level",
":",
"str",
"=",
"'RUNNING_LOW'",
")",
"->",
"None",
":",
"_",
",",
"error",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'am'",
",",
"'send-trim-memory'",
",",
"str",
"(",
"pid",
")",
",",
"level",
")",
"if",
"error",
"and",
"error",
".",
"startswith",
"(",
"'Error'",
")",
":",
"raise",
"ApplicationsException",
"(",
"error",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"-",
"1",
"]",
".",
"strip",
"(",
")",
")"
]
| Trim memory.
Args:
level: HIDDEN | RUNNING_MODERATE | BACKGROUNDRUNNING_LOW | \
MODERATE | RUNNING_CRITICAL | COMPLETE | [
"Trim",
"memory",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L470-L480 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.app_start_up_time | def app_start_up_time(self, package: str) -> str:
'''Get the time it took to launch your application.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'am', 'start', '-W', package)
return re.findall('TotalTime: \d+', output)[0] | python | def app_start_up_time(self, package: str) -> str:
'''Get the time it took to launch your application.'''
output, _ = self._execute(
'-s', self.device_sn, 'shell', 'am', 'start', '-W', package)
return re.findall('TotalTime: \d+', output)[0] | [
"def",
"app_start_up_time",
"(",
"self",
",",
"package",
":",
"str",
")",
"->",
"str",
":",
"output",
",",
"_",
"=",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'am'",
",",
"'start'",
",",
"'-W'",
",",
"package",
")",
"return",
"re",
".",
"findall",
"(",
"'TotalTime: \\d+'",
",",
"output",
")",
"[",
"0",
"]"
]
| Get the time it took to launch your application. | [
"Get",
"the",
"time",
"it",
"took",
"to",
"launch",
"your",
"application",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L482-L486 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.click | def click(self, x: int, y: int) -> None:
'''Simulate finger click.'''
self._execute('-s', self.device_sn, 'shell',
'input', 'tap', str(x), str(y)) | python | def click(self, x: int, y: int) -> None:
'''Simulate finger click.'''
self._execute('-s', self.device_sn, 'shell',
'input', 'tap', str(x), str(y)) | [
"def",
"click",
"(",
"self",
",",
"x",
":",
"int",
",",
"y",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'input'",
",",
"'tap'",
",",
"str",
"(",
"x",
")",
",",
"str",
"(",
"y",
")",
")"
]
| Simulate finger click. | [
"Simulate",
"finger",
"click",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L523-L526 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.send_keyevents | def send_keyevents(self, keyevent: int) -> None:
'''Simulates typing keyevents.'''
self._execute('-s', self.device_sn, 'shell',
'input', 'keyevent', str(keyevent)) | python | def send_keyevents(self, keyevent: int) -> None:
'''Simulates typing keyevents.'''
self._execute('-s', self.device_sn, 'shell',
'input', 'keyevent', str(keyevent)) | [
"def",
"send_keyevents",
"(",
"self",
",",
"keyevent",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'input'",
",",
"'keyevent'",
",",
"str",
"(",
"keyevent",
")",
")"
]
| Simulates typing keyevents. | [
"Simulates",
"typing",
"keyevents",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L548-L551 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.send_keyevents_long_press | def send_keyevents_long_press(self, keyevent: int) -> None:
'''Simulates typing keyevents long press.'''
self._execute('-s', self.device_sn, 'shell',
'input', 'keyevent', '--longpress', str(keyevent)) | python | def send_keyevents_long_press(self, keyevent: int) -> None:
'''Simulates typing keyevents long press.'''
self._execute('-s', self.device_sn, 'shell',
'input', 'keyevent', '--longpress', str(keyevent)) | [
"def",
"send_keyevents_long_press",
"(",
"self",
",",
"keyevent",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'input'",
",",
"'keyevent'",
",",
"'--longpress'",
",",
"str",
"(",
"keyevent",
")",
")"
]
| Simulates typing keyevents long press. | [
"Simulates",
"typing",
"keyevents",
"long",
"press",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L553-L556 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.uidump | def uidump(self, local: _PATH = None) -> None:
'''Get the current interface layout file.'''
local = local if local else self._temp
self._execute('-s', self.device_sn, 'shell', 'uiautomator',
'dump', '--compressed', '/data/local/tmp/uidump.xml')
self.pull('/data/local/tmp/uidump.xml', local)
ui = html.fromstring(open(local, 'rb').read())
self._nodes = ui.iter(tag="node") | python | def uidump(self, local: _PATH = None) -> None:
'''Get the current interface layout file.'''
local = local if local else self._temp
self._execute('-s', self.device_sn, 'shell', 'uiautomator',
'dump', '--compressed', '/data/local/tmp/uidump.xml')
self.pull('/data/local/tmp/uidump.xml', local)
ui = html.fromstring(open(local, 'rb').read())
self._nodes = ui.iter(tag="node") | [
"def",
"uidump",
"(",
"self",
",",
"local",
":",
"_PATH",
"=",
"None",
")",
"->",
"None",
":",
"local",
"=",
"local",
"if",
"local",
"else",
"self",
".",
"_temp",
"self",
".",
"_execute",
"(",
"'-s'",
",",
"self",
".",
"device_sn",
",",
"'shell'",
",",
"'uiautomator'",
",",
"'dump'",
",",
"'--compressed'",
",",
"'/data/local/tmp/uidump.xml'",
")",
"self",
".",
"pull",
"(",
"'/data/local/tmp/uidump.xml'",
",",
"local",
")",
"ui",
"=",
"html",
".",
"fromstring",
"(",
"open",
"(",
"local",
",",
"'rb'",
")",
".",
"read",
"(",
")",
")",
"self",
".",
"_nodes",
"=",
"ui",
".",
"iter",
"(",
"tag",
"=",
"\"node\"",
")"
]
| Get the current interface layout file. | [
"Get",
"the",
"current",
"interface",
"layout",
"file",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L574-L581 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.find_element | def find_element(self, value, by=By.ID, update=False) -> Elements:
'''Find a element or the first element.'''
if update or not self._nodes:
self.uidump()
for node in self._nodes:
if node.attrib[by] == value:
bounds = node.attrib['bounds']
coord = list(map(int, re.findall(r'\d+', bounds)))
click_point = (coord[0] + coord[2]) / \
2, (coord[1] + coord[3]) / 2
return self._element_cls(self, node.attrib, by, value, coord, click_point)
raise NoSuchElementException(f'No such element: {by}={value!r}.') | python | def find_element(self, value, by=By.ID, update=False) -> Elements:
'''Find a element or the first element.'''
if update or not self._nodes:
self.uidump()
for node in self._nodes:
if node.attrib[by] == value:
bounds = node.attrib['bounds']
coord = list(map(int, re.findall(r'\d+', bounds)))
click_point = (coord[0] + coord[2]) / \
2, (coord[1] + coord[3]) / 2
return self._element_cls(self, node.attrib, by, value, coord, click_point)
raise NoSuchElementException(f'No such element: {by}={value!r}.') | [
"def",
"find_element",
"(",
"self",
",",
"value",
",",
"by",
"=",
"By",
".",
"ID",
",",
"update",
"=",
"False",
")",
"->",
"Elements",
":",
"if",
"update",
"or",
"not",
"self",
".",
"_nodes",
":",
"self",
".",
"uidump",
"(",
")",
"for",
"node",
"in",
"self",
".",
"_nodes",
":",
"if",
"node",
".",
"attrib",
"[",
"by",
"]",
"==",
"value",
":",
"bounds",
"=",
"node",
".",
"attrib",
"[",
"'bounds'",
"]",
"coord",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"re",
".",
"findall",
"(",
"r'\\d+'",
",",
"bounds",
")",
")",
")",
"click_point",
"=",
"(",
"coord",
"[",
"0",
"]",
"+",
"coord",
"[",
"2",
"]",
")",
"/",
"2",
",",
"(",
"coord",
"[",
"1",
"]",
"+",
"coord",
"[",
"3",
"]",
")",
"/",
"2",
"return",
"self",
".",
"_element_cls",
"(",
"self",
",",
"node",
".",
"attrib",
",",
"by",
",",
"value",
",",
"coord",
",",
"click_point",
")",
"raise",
"NoSuchElementException",
"(",
"f'No such element: {by}={value!r}.'",
")"
]
| Find a element or the first element. | [
"Find",
"a",
"element",
"or",
"the",
"first",
"element",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L583-L594 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.find_elements_by_name | def find_elements_by_name(self, name, update=False) -> Elements:
'''Finds multiple elements by name.
Args:
name: The name of the elements to be found.
update: If the interface has changed, this option should be True.
Returns:
A list with elements if any was found. An empty list if not.
Raises:
NoSuchElementException - If the element wasn't found.
Usage:
elements = driver.find_elements_by_name('foo')
'''
return self.find_elements(by=By.NAME, value=name, update=update) | python | def find_elements_by_name(self, name, update=False) -> Elements:
'''Finds multiple elements by name.
Args:
name: The name of the elements to be found.
update: If the interface has changed, this option should be True.
Returns:
A list with elements if any was found. An empty list if not.
Raises:
NoSuchElementException - If the element wasn't found.
Usage:
elements = driver.find_elements_by_name('foo')
'''
return self.find_elements(by=By.NAME, value=name, update=update) | [
"def",
"find_elements_by_name",
"(",
"self",
",",
"name",
",",
"update",
"=",
"False",
")",
"->",
"Elements",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"NAME",
",",
"value",
"=",
"name",
",",
"update",
"=",
"update",
")"
]
| Finds multiple elements by name.
Args:
name: The name of the elements to be found.
update: If the interface has changed, this option should be True.
Returns:
A list with elements if any was found. An empty list if not.
Raises:
NoSuchElementException - If the element wasn't found.
Usage:
elements = driver.find_elements_by_name('foo') | [
"Finds",
"multiple",
"elements",
"by",
"name",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L667-L683 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.find_element_by_class | def find_element_by_class(self, class_, update=False) -> Elements:
'''Finds an element by class.
Args:
class_: The class of the element to be found.
update: If the interface has changed, this option should be True.
Returns:
The element if it was found.
Raises:
NoSuchElementException - If the element wasn't found.
Usage:
element = driver.find_element_by_class('foo')
'''
return self.find_element(by=By.CLASS, value=class_, update=update) | python | def find_element_by_class(self, class_, update=False) -> Elements:
'''Finds an element by class.
Args:
class_: The class of the element to be found.
update: If the interface has changed, this option should be True.
Returns:
The element if it was found.
Raises:
NoSuchElementException - If the element wasn't found.
Usage:
element = driver.find_element_by_class('foo')
'''
return self.find_element(by=By.CLASS, value=class_, update=update) | [
"def",
"find_element_by_class",
"(",
"self",
",",
"class_",
",",
"update",
"=",
"False",
")",
"->",
"Elements",
":",
"return",
"self",
".",
"find_element",
"(",
"by",
"=",
"By",
".",
"CLASS",
",",
"value",
"=",
"class_",
",",
"update",
"=",
"update",
")"
]
| Finds an element by class.
Args:
class_: The class of the element to be found.
update: If the interface has changed, this option should be True.
Returns:
The element if it was found.
Raises:
NoSuchElementException - If the element wasn't found.
Usage:
element = driver.find_element_by_class('foo') | [
"Finds",
"an",
"element",
"by",
"class",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L685-L701 | train |
fjwCode/cerium | cerium/androiddriver.py | BaseAndroidDriver.find_elements_by_class | def find_elements_by_class(self, class_, update=False) -> Elements:
'''Finds multiple elements by class.
Args:
class_: The class of the elements to be found.
update: If the interface has changed, this option should be True.
Returns:
A list with elements if any was found. An empty list if not.
Raises:
NoSuchElementException - If the element wasn't found.
Usage:
elements = driver.find_elements_by_class('foo')
'''
return self.find_elements(by=By.CLASS, value=class_, update=update) | python | def find_elements_by_class(self, class_, update=False) -> Elements:
'''Finds multiple elements by class.
Args:
class_: The class of the elements to be found.
update: If the interface has changed, this option should be True.
Returns:
A list with elements if any was found. An empty list if not.
Raises:
NoSuchElementException - If the element wasn't found.
Usage:
elements = driver.find_elements_by_class('foo')
'''
return self.find_elements(by=By.CLASS, value=class_, update=update) | [
"def",
"find_elements_by_class",
"(",
"self",
",",
"class_",
",",
"update",
"=",
"False",
")",
"->",
"Elements",
":",
"return",
"self",
".",
"find_elements",
"(",
"by",
"=",
"By",
".",
"CLASS",
",",
"value",
"=",
"class_",
",",
"update",
"=",
"update",
")"
]
| Finds multiple elements by class.
Args:
class_: The class of the elements to be found.
update: If the interface has changed, this option should be True.
Returns:
A list with elements if any was found. An empty list if not.
Raises:
NoSuchElementException - If the element wasn't found.
Usage:
elements = driver.find_elements_by_class('foo') | [
"Finds",
"multiple",
"elements",
"by",
"class",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L703-L719 | train |
fjwCode/cerium | cerium/androiddriver.py | AndroidDriver.unlock | def unlock(self, password, width=1080, length=1920) -> None:
'''Unlock screen.'''
self.wake()
self.swipe_up(width, length)
self.send_keys(str(password)) | python | def unlock(self, password, width=1080, length=1920) -> None:
'''Unlock screen.'''
self.wake()
self.swipe_up(width, length)
self.send_keys(str(password)) | [
"def",
"unlock",
"(",
"self",
",",
"password",
",",
"width",
"=",
"1080",
",",
"length",
"=",
"1920",
")",
"->",
"None",
":",
"self",
".",
"wake",
"(",
")",
"self",
".",
"swipe_up",
"(",
"width",
",",
"length",
")",
"self",
".",
"send_keys",
"(",
"str",
"(",
"password",
")",
")"
]
| Unlock screen. | [
"Unlock",
"screen",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L755-L759 | train |
fjwCode/cerium | cerium/androiddriver.py | AndroidDriver.make_a_call | def make_a_call(self, number: int or str = 18268237856) -> None:
'''Make a call.'''
self.app_start_action(Actions.CALL, '-d', 'tel:{}'.format(str(number))) | python | def make_a_call(self, number: int or str = 18268237856) -> None:
'''Make a call.'''
self.app_start_action(Actions.CALL, '-d', 'tel:{}'.format(str(number))) | [
"def",
"make_a_call",
"(",
"self",
",",
"number",
":",
"int",
"or",
"str",
"=",
"18268237856",
")",
"->",
"None",
":",
"self",
".",
"app_start_action",
"(",
"Actions",
".",
"CALL",
",",
"'-d'",
",",
"'tel:{}'",
".",
"format",
"(",
"str",
"(",
"number",
")",
")",
")"
]
| Make a call. | [
"Make",
"a",
"call",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L809-L811 | train |
fjwCode/cerium | cerium/androiddriver.py | AndroidDriver.swipe_left | def swipe_left(self, width: int = 1080, length: int = 1920) -> None:
'''Swipe left.'''
self.swipe(0.8*width, 0.5*length, 0.2*width, 0.5*length) | python | def swipe_left(self, width: int = 1080, length: int = 1920) -> None:
'''Swipe left.'''
self.swipe(0.8*width, 0.5*length, 0.2*width, 0.5*length) | [
"def",
"swipe_left",
"(",
"self",
",",
"width",
":",
"int",
"=",
"1080",
",",
"length",
":",
"int",
"=",
"1920",
")",
"->",
"None",
":",
"self",
".",
"swipe",
"(",
"0.8",
"*",
"width",
",",
"0.5",
"*",
"length",
",",
"0.2",
"*",
"width",
",",
"0.5",
"*",
"length",
")"
]
| Swipe left. | [
"Swipe",
"left",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L817-L819 | train |
fjwCode/cerium | cerium/androiddriver.py | AndroidDriver.swipe_right | def swipe_right(self, width: int = 1080, length: int = 1920) -> None:
'''Swipe right.'''
self.swipe(0.2*width, 0.5*length, 0.8*width, 0.5*length) | python | def swipe_right(self, width: int = 1080, length: int = 1920) -> None:
'''Swipe right.'''
self.swipe(0.2*width, 0.5*length, 0.8*width, 0.5*length) | [
"def",
"swipe_right",
"(",
"self",
",",
"width",
":",
"int",
"=",
"1080",
",",
"length",
":",
"int",
"=",
"1920",
")",
"->",
"None",
":",
"self",
".",
"swipe",
"(",
"0.2",
"*",
"width",
",",
"0.5",
"*",
"length",
",",
"0.8",
"*",
"width",
",",
"0.5",
"*",
"length",
")"
]
| Swipe right. | [
"Swipe",
"right",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L821-L823 | train |
fjwCode/cerium | cerium/androiddriver.py | AndroidDriver.swipe_up | def swipe_up(self, width: int = 1080, length: int = 1920) -> None:
'''Swipe up.'''
self.swipe(0.5*width, 0.8*length, 0.5*width, 0.2*length) | python | def swipe_up(self, width: int = 1080, length: int = 1920) -> None:
'''Swipe up.'''
self.swipe(0.5*width, 0.8*length, 0.5*width, 0.2*length) | [
"def",
"swipe_up",
"(",
"self",
",",
"width",
":",
"int",
"=",
"1080",
",",
"length",
":",
"int",
"=",
"1920",
")",
"->",
"None",
":",
"self",
".",
"swipe",
"(",
"0.5",
"*",
"width",
",",
"0.8",
"*",
"length",
",",
"0.5",
"*",
"width",
",",
"0.2",
"*",
"length",
")"
]
| Swipe up. | [
"Swipe",
"up",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L825-L827 | train |
fjwCode/cerium | cerium/androiddriver.py | AndroidDriver.swipe_down | def swipe_down(self, width: int = 1080, length: int = 1920) -> None:
'''Swipe down.'''
self.swipe(0.5*width, 0.2*length, 0.5*width, 0.8*length) | python | def swipe_down(self, width: int = 1080, length: int = 1920) -> None:
'''Swipe down.'''
self.swipe(0.5*width, 0.2*length, 0.5*width, 0.8*length) | [
"def",
"swipe_down",
"(",
"self",
",",
"width",
":",
"int",
"=",
"1080",
",",
"length",
":",
"int",
"=",
"1920",
")",
"->",
"None",
":",
"self",
".",
"swipe",
"(",
"0.5",
"*",
"width",
",",
"0.2",
"*",
"length",
",",
"0.5",
"*",
"width",
",",
"0.8",
"*",
"length",
")"
]
| Swipe down. | [
"Swipe",
"down",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L829-L831 | train |
mardix/Mocha | mocha/contrib/views/contact_us.py | Main._register | def _register(cls, app, **kwargs):
""" Reset some params """
# nav
nav = __options__.get("nav", {})
nav.setdefault("title", "Contact")
nav.setdefault("visible", True)
nav.setdefault("order", 100)
title = nav.pop("title")
render.nav.add(title, cls.page, **nav)
# route
kwargs["base_route"] = __options__.get("route", "/contact/")
# App Option
data = {
"recipients": __options__.get("recipients"),
"success_message": __options__.get("success_message",
"Message sent. Thanks!")
}
@app.before_first_request
def setup():
if db._IS_OK_:
try:
app_data.set(APP_DATA_KEY, data, init=True)
except Exception as ex:
logging.fatal("mocha.contrib.app_data has not been setup. Need to run `mocha :dbsync`")
abort(500)
# Call the register
super(cls, cls)._register(app, **kwargs) | python | def _register(cls, app, **kwargs):
""" Reset some params """
# nav
nav = __options__.get("nav", {})
nav.setdefault("title", "Contact")
nav.setdefault("visible", True)
nav.setdefault("order", 100)
title = nav.pop("title")
render.nav.add(title, cls.page, **nav)
# route
kwargs["base_route"] = __options__.get("route", "/contact/")
# App Option
data = {
"recipients": __options__.get("recipients"),
"success_message": __options__.get("success_message",
"Message sent. Thanks!")
}
@app.before_first_request
def setup():
if db._IS_OK_:
try:
app_data.set(APP_DATA_KEY, data, init=True)
except Exception as ex:
logging.fatal("mocha.contrib.app_data has not been setup. Need to run `mocha :dbsync`")
abort(500)
# Call the register
super(cls, cls)._register(app, **kwargs) | [
"def",
"_register",
"(",
"cls",
",",
"app",
",",
"*",
"*",
"kwargs",
")",
":",
"# nav",
"nav",
"=",
"__options__",
".",
"get",
"(",
"\"nav\"",
",",
"{",
"}",
")",
"nav",
".",
"setdefault",
"(",
"\"title\"",
",",
"\"Contact\"",
")",
"nav",
".",
"setdefault",
"(",
"\"visible\"",
",",
"True",
")",
"nav",
".",
"setdefault",
"(",
"\"order\"",
",",
"100",
")",
"title",
"=",
"nav",
".",
"pop",
"(",
"\"title\"",
")",
"render",
".",
"nav",
".",
"add",
"(",
"title",
",",
"cls",
".",
"page",
",",
"*",
"*",
"nav",
")",
"# route",
"kwargs",
"[",
"\"base_route\"",
"]",
"=",
"__options__",
".",
"get",
"(",
"\"route\"",
",",
"\"/contact/\"",
")",
"# App Option",
"data",
"=",
"{",
"\"recipients\"",
":",
"__options__",
".",
"get",
"(",
"\"recipients\"",
")",
",",
"\"success_message\"",
":",
"__options__",
".",
"get",
"(",
"\"success_message\"",
",",
"\"Message sent. Thanks!\"",
")",
"}",
"@",
"app",
".",
"before_first_request",
"def",
"setup",
"(",
")",
":",
"if",
"db",
".",
"_IS_OK_",
":",
"try",
":",
"app_data",
".",
"set",
"(",
"APP_DATA_KEY",
",",
"data",
",",
"init",
"=",
"True",
")",
"except",
"Exception",
"as",
"ex",
":",
"logging",
".",
"fatal",
"(",
"\"mocha.contrib.app_data has not been setup. Need to run `mocha :dbsync`\"",
")",
"abort",
"(",
"500",
")",
"# Call the register",
"super",
"(",
"cls",
",",
"cls",
")",
".",
"_register",
"(",
"app",
",",
"*",
"*",
"kwargs",
")"
]
| Reset some params | [
"Reset",
"some",
"params"
]
| bce481cb31a0972061dd99bc548701411dcb9de3 | https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/contrib/views/contact_us.py#L37-L68 | train |
Kortemme-Lab/klab | klab/deprecated/rosettahelper.py | saturateHexColor | def saturateHexColor(hexcolor, adjustment = 1.0):
'''Takes in an RGB color in 6-character hexadecimal with an optional preceding hash character.
Returns the RGB color in the same format adjusted by saturation by the second parameter.'''
assert(adjustment >= 0 and len(hexcolor) >= 1)
prefix = ""
if hexcolor[0] == '#':
hexcolor = hexcolor[1:]
prefix = "#"
assert(len(hexcolor) == 6)
if adjustment == 1.0:
return "%s%s" % (prefix, hexcolor)
else:
hsvColor = list(colorsys.rgb_to_hsv(int(hexcolor[0:2], 16)/255.0, int(hexcolor[2:4], 16)/255.0, int(hexcolor[4:6], 16)/255.0))
hsvColor[1] = min(1.0, hsvColor[1] * adjustment)
rgbColor = [min(255, 255 * v) for v in colorsys.hsv_to_rgb(hsvColor[0], hsvColor[1], hsvColor[2])]
return "%s%.2x%.2x%.2x" % (prefix, rgbColor[0], rgbColor[1], rgbColor[2]) | python | def saturateHexColor(hexcolor, adjustment = 1.0):
'''Takes in an RGB color in 6-character hexadecimal with an optional preceding hash character.
Returns the RGB color in the same format adjusted by saturation by the second parameter.'''
assert(adjustment >= 0 and len(hexcolor) >= 1)
prefix = ""
if hexcolor[0] == '#':
hexcolor = hexcolor[1:]
prefix = "#"
assert(len(hexcolor) == 6)
if adjustment == 1.0:
return "%s%s" % (prefix, hexcolor)
else:
hsvColor = list(colorsys.rgb_to_hsv(int(hexcolor[0:2], 16)/255.0, int(hexcolor[2:4], 16)/255.0, int(hexcolor[4:6], 16)/255.0))
hsvColor[1] = min(1.0, hsvColor[1] * adjustment)
rgbColor = [min(255, 255 * v) for v in colorsys.hsv_to_rgb(hsvColor[0], hsvColor[1], hsvColor[2])]
return "%s%.2x%.2x%.2x" % (prefix, rgbColor[0], rgbColor[1], rgbColor[2]) | [
"def",
"saturateHexColor",
"(",
"hexcolor",
",",
"adjustment",
"=",
"1.0",
")",
":",
"assert",
"(",
"adjustment",
">=",
"0",
"and",
"len",
"(",
"hexcolor",
")",
">=",
"1",
")",
"prefix",
"=",
"\"\"",
"if",
"hexcolor",
"[",
"0",
"]",
"==",
"'#'",
":",
"hexcolor",
"=",
"hexcolor",
"[",
"1",
":",
"]",
"prefix",
"=",
"\"#\"",
"assert",
"(",
"len",
"(",
"hexcolor",
")",
"==",
"6",
")",
"if",
"adjustment",
"==",
"1.0",
":",
"return",
"\"%s%s\"",
"%",
"(",
"prefix",
",",
"hexcolor",
")",
"else",
":",
"hsvColor",
"=",
"list",
"(",
"colorsys",
".",
"rgb_to_hsv",
"(",
"int",
"(",
"hexcolor",
"[",
"0",
":",
"2",
"]",
",",
"16",
")",
"/",
"255.0",
",",
"int",
"(",
"hexcolor",
"[",
"2",
":",
"4",
"]",
",",
"16",
")",
"/",
"255.0",
",",
"int",
"(",
"hexcolor",
"[",
"4",
":",
"6",
"]",
",",
"16",
")",
"/",
"255.0",
")",
")",
"hsvColor",
"[",
"1",
"]",
"=",
"min",
"(",
"1.0",
",",
"hsvColor",
"[",
"1",
"]",
"*",
"adjustment",
")",
"rgbColor",
"=",
"[",
"min",
"(",
"255",
",",
"255",
"*",
"v",
")",
"for",
"v",
"in",
"colorsys",
".",
"hsv_to_rgb",
"(",
"hsvColor",
"[",
"0",
"]",
",",
"hsvColor",
"[",
"1",
"]",
",",
"hsvColor",
"[",
"2",
"]",
")",
"]",
"return",
"\"%s%.2x%.2x%.2x\"",
"%",
"(",
"prefix",
",",
"rgbColor",
"[",
"0",
"]",
",",
"rgbColor",
"[",
"1",
"]",
",",
"rgbColor",
"[",
"2",
"]",
")"
]
| Takes in an RGB color in 6-character hexadecimal with an optional preceding hash character.
Returns the RGB color in the same format adjusted by saturation by the second parameter. | [
"Takes",
"in",
"an",
"RGB",
"color",
"in",
"6",
"-",
"character",
"hexadecimal",
"with",
"an",
"optional",
"preceding",
"hash",
"character",
".",
"Returns",
"the",
"RGB",
"color",
"in",
"the",
"same",
"format",
"adjusted",
"by",
"saturation",
"by",
"the",
"second",
"parameter",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/deprecated/rosettahelper.py#L157-L173 | train |
cgrok/cr-async | crasync/core.py | Client.get_constants | async def get_constants(self):
'''Get clash royale constants.'''
url = self.BASE + '/constants'
data = await self.request(url)
return Constants(self, data) | python | async def get_constants(self):
'''Get clash royale constants.'''
url = self.BASE + '/constants'
data = await self.request(url)
return Constants(self, data) | [
"async",
"def",
"get_constants",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"BASE",
"+",
"'/constants'",
"data",
"=",
"await",
"self",
".",
"request",
"(",
"url",
")",
"return",
"Constants",
"(",
"self",
",",
"data",
")"
]
| Get clash royale constants. | [
"Get",
"clash",
"royale",
"constants",
"."
]
| f65a968e54704168706d137d1ba662f55f8ab852 | https://github.com/cgrok/cr-async/blob/f65a968e54704168706d137d1ba662f55f8ab852/crasync/core.py#L108-L114 | train |
TheGhouls/oct | oct/utilities/pack.py | pack_turret | def pack_turret(turret, temp_files, base_config_path, path=None):
"""pack a turret into a tar file based on the turret configuration
:param dict turret_config: the turret configuration to pack
:param str tmp_config_file: the path of the temp config file
:param str base_config_path: the base directory of the main configuration file
"""
file_name = turret['name']
files = temp_files[:]
for fname in turret.get('extra_files', []):
if os.path.isabs(fname) or path is None:
files.append(fname)
else:
files.append(os.path.join(path, fname))
if path is not None:
file_name = os.path.join(path, file_name)
tar_file = tarfile.open(file_name + ".tar.gz", 'w:gz')
for f in files:
tar_file.add(os.path.abspath(f), arcname=os.path.basename(f))
script_path = os.path.join(os.path.abspath(base_config_path), turret['script'])
tar_file.add(script_path, arcname=turret['script'])
for f in tar_file.getnames():
print("Added %s" % f)
tar_file.close()
print("Archive %s created" % (tar_file.name))
print("=========================================") | python | def pack_turret(turret, temp_files, base_config_path, path=None):
"""pack a turret into a tar file based on the turret configuration
:param dict turret_config: the turret configuration to pack
:param str tmp_config_file: the path of the temp config file
:param str base_config_path: the base directory of the main configuration file
"""
file_name = turret['name']
files = temp_files[:]
for fname in turret.get('extra_files', []):
if os.path.isabs(fname) or path is None:
files.append(fname)
else:
files.append(os.path.join(path, fname))
if path is not None:
file_name = os.path.join(path, file_name)
tar_file = tarfile.open(file_name + ".tar.gz", 'w:gz')
for f in files:
tar_file.add(os.path.abspath(f), arcname=os.path.basename(f))
script_path = os.path.join(os.path.abspath(base_config_path), turret['script'])
tar_file.add(script_path, arcname=turret['script'])
for f in tar_file.getnames():
print("Added %s" % f)
tar_file.close()
print("Archive %s created" % (tar_file.name))
print("=========================================") | [
"def",
"pack_turret",
"(",
"turret",
",",
"temp_files",
",",
"base_config_path",
",",
"path",
"=",
"None",
")",
":",
"file_name",
"=",
"turret",
"[",
"'name'",
"]",
"files",
"=",
"temp_files",
"[",
":",
"]",
"for",
"fname",
"in",
"turret",
".",
"get",
"(",
"'extra_files'",
",",
"[",
"]",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"fname",
")",
"or",
"path",
"is",
"None",
":",
"files",
".",
"append",
"(",
"fname",
")",
"else",
":",
"files",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"fname",
")",
")",
"if",
"path",
"is",
"not",
"None",
":",
"file_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"file_name",
")",
"tar_file",
"=",
"tarfile",
".",
"open",
"(",
"file_name",
"+",
"\".tar.gz\"",
",",
"'w:gz'",
")",
"for",
"f",
"in",
"files",
":",
"tar_file",
".",
"add",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"f",
")",
",",
"arcname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"f",
")",
")",
"script_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"base_config_path",
")",
",",
"turret",
"[",
"'script'",
"]",
")",
"tar_file",
".",
"add",
"(",
"script_path",
",",
"arcname",
"=",
"turret",
"[",
"'script'",
"]",
")",
"for",
"f",
"in",
"tar_file",
".",
"getnames",
"(",
")",
":",
"print",
"(",
"\"Added %s\"",
"%",
"f",
")",
"tar_file",
".",
"close",
"(",
")",
"print",
"(",
"\"Archive %s created\"",
"%",
"(",
"tar_file",
".",
"name",
")",
")",
"print",
"(",
"\"=========================================\"",
")"
]
| pack a turret into a tar file based on the turret configuration
:param dict turret_config: the turret configuration to pack
:param str tmp_config_file: the path of the temp config file
:param str base_config_path: the base directory of the main configuration file | [
"pack",
"a",
"turret",
"into",
"a",
"tar",
"file",
"based",
"on",
"the",
"turret",
"configuration"
]
| 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/utilities/pack.py#L52-L80 | train |
fjwCode/cerium | cerium/elements.py | Elements.clear | def clear(self) -> None:
"""Clears the text if it's a text entry element."""
self.click()
for i in self.text:
self._parent.send_keyevents(Keys.DEL) | python | def clear(self) -> None:
"""Clears the text if it's a text entry element."""
self.click()
for i in self.text:
self._parent.send_keyevents(Keys.DEL) | [
"def",
"clear",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"click",
"(",
")",
"for",
"i",
"in",
"self",
".",
"text",
":",
"self",
".",
"_parent",
".",
"send_keyevents",
"(",
"Keys",
".",
"DEL",
")"
]
| Clears the text if it's a text entry element. | [
"Clears",
"the",
"text",
"if",
"it",
"s",
"a",
"text",
"entry",
"element",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/elements.py#L81-L85 | train |
Kortemme-Lab/klab | klab/bio/sifts.py | DomainMatch.add | def add(self, domain_accession, domain_type, match_quality):
'''match_quality should be a value between 0 and 1.'''
self.matches[domain_type] = self.matches.get(domain_type, {})
self.matches[domain_type][domain_accession] = match_quality | python | def add(self, domain_accession, domain_type, match_quality):
'''match_quality should be a value between 0 and 1.'''
self.matches[domain_type] = self.matches.get(domain_type, {})
self.matches[domain_type][domain_accession] = match_quality | [
"def",
"add",
"(",
"self",
",",
"domain_accession",
",",
"domain_type",
",",
"match_quality",
")",
":",
"self",
".",
"matches",
"[",
"domain_type",
"]",
"=",
"self",
".",
"matches",
".",
"get",
"(",
"domain_type",
",",
"{",
"}",
")",
"self",
".",
"matches",
"[",
"domain_type",
"]",
"[",
"domain_accession",
"]",
"=",
"match_quality"
]
| match_quality should be a value between 0 and 1. | [
"match_quality",
"should",
"be",
"a",
"value",
"between",
"0",
"and",
"1",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/sifts.py#L129-L132 | train |
Kortemme-Lab/klab | klab/bio/sifts.py | SIFTS._validate | def _validate(self):
'''Tests that the maps agree through composition.'''
# I used to use the assertion "self.atom_to_uniparc_sequence_maps.keys() == self.atom_to_seqres_sequence_maps.keys() == self.seqres_to_uniparc_sequence_maps.keys()"
# but that failed for 2IMM where "self.atom_to_uniparc_sequence_maps.keys() == self.seqres_to_uniparc_sequence_maps.keys() == []" but THAT fails for 1IR3 so I removed
# the assertions entirely.
for c, m in self.atom_to_seqres_sequence_maps.iteritems():
if self.seqres_to_uniparc_sequence_maps.keys():
atom_uniparc_keys = set(self.atom_to_uniparc_sequence_maps.get(c, {}).keys())
atom_seqres_keys = set(self.atom_to_seqres_sequence_maps.get(c, {}).keys())
assert(atom_uniparc_keys.intersection(atom_seqres_keys) == atom_uniparc_keys)
for k, v in m.map.iteritems():
uparc_id_1, uparc_id_2 = None, None
try:
uparc_id_1 = self.seqres_to_uniparc_sequence_maps[c].map[v]
uparc_id_2 = self.atom_to_uniparc_sequence_maps[c].map[k]
except:
continue
assert(uparc_id_1 == uparc_id_2) | python | def _validate(self):
'''Tests that the maps agree through composition.'''
# I used to use the assertion "self.atom_to_uniparc_sequence_maps.keys() == self.atom_to_seqres_sequence_maps.keys() == self.seqres_to_uniparc_sequence_maps.keys()"
# but that failed for 2IMM where "self.atom_to_uniparc_sequence_maps.keys() == self.seqres_to_uniparc_sequence_maps.keys() == []" but THAT fails for 1IR3 so I removed
# the assertions entirely.
for c, m in self.atom_to_seqres_sequence_maps.iteritems():
if self.seqres_to_uniparc_sequence_maps.keys():
atom_uniparc_keys = set(self.atom_to_uniparc_sequence_maps.get(c, {}).keys())
atom_seqres_keys = set(self.atom_to_seqres_sequence_maps.get(c, {}).keys())
assert(atom_uniparc_keys.intersection(atom_seqres_keys) == atom_uniparc_keys)
for k, v in m.map.iteritems():
uparc_id_1, uparc_id_2 = None, None
try:
uparc_id_1 = self.seqres_to_uniparc_sequence_maps[c].map[v]
uparc_id_2 = self.atom_to_uniparc_sequence_maps[c].map[k]
except:
continue
assert(uparc_id_1 == uparc_id_2) | [
"def",
"_validate",
"(",
"self",
")",
":",
"# I used to use the assertion \"self.atom_to_uniparc_sequence_maps.keys() == self.atom_to_seqres_sequence_maps.keys() == self.seqres_to_uniparc_sequence_maps.keys()\"",
"# but that failed for 2IMM where \"self.atom_to_uniparc_sequence_maps.keys() == self.seqres_to_uniparc_sequence_maps.keys() == []\" but THAT fails for 1IR3 so I removed",
"# the assertions entirely.",
"for",
"c",
",",
"m",
"in",
"self",
".",
"atom_to_seqres_sequence_maps",
".",
"iteritems",
"(",
")",
":",
"if",
"self",
".",
"seqres_to_uniparc_sequence_maps",
".",
"keys",
"(",
")",
":",
"atom_uniparc_keys",
"=",
"set",
"(",
"self",
".",
"atom_to_uniparc_sequence_maps",
".",
"get",
"(",
"c",
",",
"{",
"}",
")",
".",
"keys",
"(",
")",
")",
"atom_seqres_keys",
"=",
"set",
"(",
"self",
".",
"atom_to_seqres_sequence_maps",
".",
"get",
"(",
"c",
",",
"{",
"}",
")",
".",
"keys",
"(",
")",
")",
"assert",
"(",
"atom_uniparc_keys",
".",
"intersection",
"(",
"atom_seqres_keys",
")",
"==",
"atom_uniparc_keys",
")",
"for",
"k",
",",
"v",
"in",
"m",
".",
"map",
".",
"iteritems",
"(",
")",
":",
"uparc_id_1",
",",
"uparc_id_2",
"=",
"None",
",",
"None",
"try",
":",
"uparc_id_1",
"=",
"self",
".",
"seqres_to_uniparc_sequence_maps",
"[",
"c",
"]",
".",
"map",
"[",
"v",
"]",
"uparc_id_2",
"=",
"self",
".",
"atom_to_uniparc_sequence_maps",
"[",
"c",
"]",
".",
"map",
"[",
"k",
"]",
"except",
":",
"continue",
"assert",
"(",
"uparc_id_1",
"==",
"uparc_id_2",
")"
]
| Tests that the maps agree through composition. | [
"Tests",
"that",
"the",
"maps",
"agree",
"through",
"composition",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/sifts.py#L729-L747 | train |
adaptive-learning/proso-apps | proso_user/views_classes.py | classes | def classes(request):
"""Get all classes of current user"""
if not request.user.is_authenticated() or not hasattr(request.user, "userprofile"):
return render_json(request, {
'error': _('User is not logged in'),
'error_type': 'user_unauthorized'
}, template='user_json.html', status=401)
clss = [c.to_json() for c in Class.objects.filter(owner=request.user.userprofile)]
return render_json(request, clss, status=200, template='user_json.html', help_text=classes.__doc__) | python | def classes(request):
"""Get all classes of current user"""
if not request.user.is_authenticated() or not hasattr(request.user, "userprofile"):
return render_json(request, {
'error': _('User is not logged in'),
'error_type': 'user_unauthorized'
}, template='user_json.html', status=401)
clss = [c.to_json() for c in Class.objects.filter(owner=request.user.userprofile)]
return render_json(request, clss, status=200, template='user_json.html', help_text=classes.__doc__) | [
"def",
"classes",
"(",
"request",
")",
":",
"if",
"not",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
"or",
"not",
"hasattr",
"(",
"request",
".",
"user",
",",
"\"userprofile\"",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'User is not logged in'",
")",
",",
"'error_type'",
":",
"'user_unauthorized'",
"}",
",",
"template",
"=",
"'user_json.html'",
",",
"status",
"=",
"401",
")",
"clss",
"=",
"[",
"c",
".",
"to_json",
"(",
")",
"for",
"c",
"in",
"Class",
".",
"objects",
".",
"filter",
"(",
"owner",
"=",
"request",
".",
"user",
".",
"userprofile",
")",
"]",
"return",
"render_json",
"(",
"request",
",",
"clss",
",",
"status",
"=",
"200",
",",
"template",
"=",
"'user_json.html'",
",",
"help_text",
"=",
"classes",
".",
"__doc__",
")"
]
| Get all classes of current user | [
"Get",
"all",
"classes",
"of",
"current",
"user"
]
| 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views_classes.py#L13-L23 | train |
adaptive-learning/proso-apps | proso_user/views_classes.py | create_class | def create_class(request):
"""Create new class
POST parameters (JSON):
name:
Human readable name of class
code (optional):
unique code of class used for joining to class
"""
if request.method == 'GET':
return render(request, 'classes_create.html', {}, help_text=create_class.__doc__)
if request.method == 'POST':
if not request.user.is_authenticated() or not hasattr(request.user, "userprofile"):
return render_json(request, {
'error': _('User is not logged in.'),
'error_type': 'user_unauthorized'
}, template='classes_create.html', status=401)
data = json_body(request.body.decode("utf-8"))
if 'code' in data and Class.objects.filter(code=data['code']).exists():
return render_json(request, {
'error': _('A class with this code already exists.'),
'error_type': 'class_with_code_exists'
}, template='classes_create.html', status=400)
if 'name' not in data or not data['name']:
return render_json(request, {'error': _('Class name is missing.'), 'error_type': 'missing_class_name'},
template='classes_create.html', status=400)
cls = Class(name=data['name'], owner=request.user.userprofile)
if 'code' in data:
cls.code = data['code']
cls.save()
return render_json(request, cls.to_json(), template='classes_create.html', status=201)
else:
return HttpResponseBadRequest("method %s is not allowed".format(request.method)) | python | def create_class(request):
"""Create new class
POST parameters (JSON):
name:
Human readable name of class
code (optional):
unique code of class used for joining to class
"""
if request.method == 'GET':
return render(request, 'classes_create.html', {}, help_text=create_class.__doc__)
if request.method == 'POST':
if not request.user.is_authenticated() or not hasattr(request.user, "userprofile"):
return render_json(request, {
'error': _('User is not logged in.'),
'error_type': 'user_unauthorized'
}, template='classes_create.html', status=401)
data = json_body(request.body.decode("utf-8"))
if 'code' in data and Class.objects.filter(code=data['code']).exists():
return render_json(request, {
'error': _('A class with this code already exists.'),
'error_type': 'class_with_code_exists'
}, template='classes_create.html', status=400)
if 'name' not in data or not data['name']:
return render_json(request, {'error': _('Class name is missing.'), 'error_type': 'missing_class_name'},
template='classes_create.html', status=400)
cls = Class(name=data['name'], owner=request.user.userprofile)
if 'code' in data:
cls.code = data['code']
cls.save()
return render_json(request, cls.to_json(), template='classes_create.html', status=201)
else:
return HttpResponseBadRequest("method %s is not allowed".format(request.method)) | [
"def",
"create_class",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"return",
"render",
"(",
"request",
",",
"'classes_create.html'",
",",
"{",
"}",
",",
"help_text",
"=",
"create_class",
".",
"__doc__",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"if",
"not",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
"or",
"not",
"hasattr",
"(",
"request",
".",
"user",
",",
"\"userprofile\"",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'User is not logged in.'",
")",
",",
"'error_type'",
":",
"'user_unauthorized'",
"}",
",",
"template",
"=",
"'classes_create.html'",
",",
"status",
"=",
"401",
")",
"data",
"=",
"json_body",
"(",
"request",
".",
"body",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"if",
"'code'",
"in",
"data",
"and",
"Class",
".",
"objects",
".",
"filter",
"(",
"code",
"=",
"data",
"[",
"'code'",
"]",
")",
".",
"exists",
"(",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'A class with this code already exists.'",
")",
",",
"'error_type'",
":",
"'class_with_code_exists'",
"}",
",",
"template",
"=",
"'classes_create.html'",
",",
"status",
"=",
"400",
")",
"if",
"'name'",
"not",
"in",
"data",
"or",
"not",
"data",
"[",
"'name'",
"]",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'Class name is missing.'",
")",
",",
"'error_type'",
":",
"'missing_class_name'",
"}",
",",
"template",
"=",
"'classes_create.html'",
",",
"status",
"=",
"400",
")",
"cls",
"=",
"Class",
"(",
"name",
"=",
"data",
"[",
"'name'",
"]",
",",
"owner",
"=",
"request",
".",
"user",
".",
"userprofile",
")",
"if",
"'code'",
"in",
"data",
":",
"cls",
".",
"code",
"=",
"data",
"[",
"'code'",
"]",
"cls",
".",
"save",
"(",
")",
"return",
"render_json",
"(",
"request",
",",
"cls",
".",
"to_json",
"(",
")",
",",
"template",
"=",
"'classes_create.html'",
",",
"status",
"=",
"201",
")",
"else",
":",
"return",
"HttpResponseBadRequest",
"(",
"\"method %s is not allowed\"",
".",
"format",
"(",
"request",
".",
"method",
")",
")"
]
| Create new class
POST parameters (JSON):
name:
Human readable name of class
code (optional):
unique code of class used for joining to class | [
"Create",
"new",
"class"
]
| 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views_classes.py#L26-L63 | train |
adaptive-learning/proso-apps | proso_user/views_classes.py | join_class | def join_class(request):
"""Join a class
POST parameters (JSON):
code:
code of the class
"""
if request.method == 'GET':
return render(request, 'classes_join.html', {}, help_text=join_class.__doc__)
if request.method == 'POST':
if not request.user.is_authenticated() or not hasattr(request.user, "userprofile"):
return render_json(request, {
'error': _('User is not logged in.'),
'error_type': 'user_unauthorized'
}, template='classes_join.html', status=401)
data = json_body(request.body.decode("utf-8"))
if 'code' not in data or not data['code']:
return render_json(request, {'error': _('Class code is missing.'), 'error_type': 'missing_class_code'},
template='classes_join.html', status=400)
try:
cls = Class.objects.get(code=data['code'])
except Class.DoesNotExist:
return render_json(request, {
'error': _('Class with given code not found.'),
'error_type': 'class_not_found',
}, template='classes_join.html', status=404)
cls.members.add(request.user.userprofile)
return render_json(request, cls.to_json(), template='classes_join.html', status=200)
else:
return HttpResponseBadRequest("method %s is not allowed".format(request.method)) | python | def join_class(request):
"""Join a class
POST parameters (JSON):
code:
code of the class
"""
if request.method == 'GET':
return render(request, 'classes_join.html', {}, help_text=join_class.__doc__)
if request.method == 'POST':
if not request.user.is_authenticated() or not hasattr(request.user, "userprofile"):
return render_json(request, {
'error': _('User is not logged in.'),
'error_type': 'user_unauthorized'
}, template='classes_join.html', status=401)
data = json_body(request.body.decode("utf-8"))
if 'code' not in data or not data['code']:
return render_json(request, {'error': _('Class code is missing.'), 'error_type': 'missing_class_code'},
template='classes_join.html', status=400)
try:
cls = Class.objects.get(code=data['code'])
except Class.DoesNotExist:
return render_json(request, {
'error': _('Class with given code not found.'),
'error_type': 'class_not_found',
}, template='classes_join.html', status=404)
cls.members.add(request.user.userprofile)
return render_json(request, cls.to_json(), template='classes_join.html', status=200)
else:
return HttpResponseBadRequest("method %s is not allowed".format(request.method)) | [
"def",
"join_class",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"return",
"render",
"(",
"request",
",",
"'classes_join.html'",
",",
"{",
"}",
",",
"help_text",
"=",
"join_class",
".",
"__doc__",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"if",
"not",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
"or",
"not",
"hasattr",
"(",
"request",
".",
"user",
",",
"\"userprofile\"",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'User is not logged in.'",
")",
",",
"'error_type'",
":",
"'user_unauthorized'",
"}",
",",
"template",
"=",
"'classes_join.html'",
",",
"status",
"=",
"401",
")",
"data",
"=",
"json_body",
"(",
"request",
".",
"body",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"if",
"'code'",
"not",
"in",
"data",
"or",
"not",
"data",
"[",
"'code'",
"]",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'Class code is missing.'",
")",
",",
"'error_type'",
":",
"'missing_class_code'",
"}",
",",
"template",
"=",
"'classes_join.html'",
",",
"status",
"=",
"400",
")",
"try",
":",
"cls",
"=",
"Class",
".",
"objects",
".",
"get",
"(",
"code",
"=",
"data",
"[",
"'code'",
"]",
")",
"except",
"Class",
".",
"DoesNotExist",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'Class with given code not found.'",
")",
",",
"'error_type'",
":",
"'class_not_found'",
",",
"}",
",",
"template",
"=",
"'classes_join.html'",
",",
"status",
"=",
"404",
")",
"cls",
".",
"members",
".",
"add",
"(",
"request",
".",
"user",
".",
"userprofile",
")",
"return",
"render_json",
"(",
"request",
",",
"cls",
".",
"to_json",
"(",
")",
",",
"template",
"=",
"'classes_join.html'",
",",
"status",
"=",
"200",
")",
"else",
":",
"return",
"HttpResponseBadRequest",
"(",
"\"method %s is not allowed\"",
".",
"format",
"(",
"request",
".",
"method",
")",
")"
]
| Join a class
POST parameters (JSON):
code:
code of the class | [
"Join",
"a",
"class"
]
| 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views_classes.py#L66-L101 | train |
adaptive-learning/proso-apps | proso_user/views_classes.py | create_student | def create_student(request):
""" Create new user in class
POST parameters (JSON):
class:
id of the class
username (optional):
username of student, if not provided username is create based on name
password (optional):
password of student
first_name:
first_name of student
last_name (optional):
last_name of student
email (optional):
e-mail of student
"""
if not get_config('proso_user', 'allow_create_students', default=False):
return render_json(request, {
'error': _('Creation of new users is not allowed.'),
'error_type': 'student_creation_not_allowed'
}, template='class_create_student.html', help_text=create_student.__doc__, status=403)
if request.method == 'GET':
return render(request, 'class_create_student.html', {}, help_text=create_student.__doc__)
if request.method == 'POST':
if not request.user.is_authenticated() or not hasattr(request.user, "userprofile"):
return render_json(request, {
'error': _('User is not logged in.'),
'error_type': 'user_unauthorized'
}, template='class_create_student.html', status=401)
data = json_body(request.body.decode("utf-8"))
try:
cls = Class.objects.get(pk=data['class'], owner=request.user.userprofile)
except (Class.DoesNotExist, KeyError):
return render_json(request, {
'error': _('Class with given id not found.'),
'error_type': 'class_not_found',
}, template='class_create_student.html', status=404)
if 'first_name' not in data or not data['first_name']:
return render_json(request, {
'error': _('First name code is missing.'),
'error_type': 'missing_first_name'
}, template='class_create_student.html', status=400)
user = User(first_name=data['first_name'])
if data.get('last_name'):
user.last_name = data['last_name']
if data.get('email'):
if User.objects.filter(email=data['email']).exists():
return render_json(request, {
'error': _('There is already a user with the given e-mail.'),
'error_type': 'email_exists'
}, template='class_create_student.html', status=400)
user.email = data['email']
if data.get('username'):
if User.objects.filter(username=data['username']).exists():
return render_json(request, {
'error': _('There is already a user with the given username.'),
'error_type': 'username_exists'
}, template='class_create_student.html', status=400)
user.username = data['username']
else:
user.username = get_unused_username(user)
if data.get('password'):
user.set_password(data['password'])
user.save()
cls.members.add(user.userprofile)
return render_json(request, user.userprofile.to_json(nested=True), template='class_create_student.html', status=201)
else:
return HttpResponseBadRequest("method %s is not allowed".format(request.method)) | python | def create_student(request):
""" Create new user in class
POST parameters (JSON):
class:
id of the class
username (optional):
username of student, if not provided username is create based on name
password (optional):
password of student
first_name:
first_name of student
last_name (optional):
last_name of student
email (optional):
e-mail of student
"""
if not get_config('proso_user', 'allow_create_students', default=False):
return render_json(request, {
'error': _('Creation of new users is not allowed.'),
'error_type': 'student_creation_not_allowed'
}, template='class_create_student.html', help_text=create_student.__doc__, status=403)
if request.method == 'GET':
return render(request, 'class_create_student.html', {}, help_text=create_student.__doc__)
if request.method == 'POST':
if not request.user.is_authenticated() or not hasattr(request.user, "userprofile"):
return render_json(request, {
'error': _('User is not logged in.'),
'error_type': 'user_unauthorized'
}, template='class_create_student.html', status=401)
data = json_body(request.body.decode("utf-8"))
try:
cls = Class.objects.get(pk=data['class'], owner=request.user.userprofile)
except (Class.DoesNotExist, KeyError):
return render_json(request, {
'error': _('Class with given id not found.'),
'error_type': 'class_not_found',
}, template='class_create_student.html', status=404)
if 'first_name' not in data or not data['first_name']:
return render_json(request, {
'error': _('First name code is missing.'),
'error_type': 'missing_first_name'
}, template='class_create_student.html', status=400)
user = User(first_name=data['first_name'])
if data.get('last_name'):
user.last_name = data['last_name']
if data.get('email'):
if User.objects.filter(email=data['email']).exists():
return render_json(request, {
'error': _('There is already a user with the given e-mail.'),
'error_type': 'email_exists'
}, template='class_create_student.html', status=400)
user.email = data['email']
if data.get('username'):
if User.objects.filter(username=data['username']).exists():
return render_json(request, {
'error': _('There is already a user with the given username.'),
'error_type': 'username_exists'
}, template='class_create_student.html', status=400)
user.username = data['username']
else:
user.username = get_unused_username(user)
if data.get('password'):
user.set_password(data['password'])
user.save()
cls.members.add(user.userprofile)
return render_json(request, user.userprofile.to_json(nested=True), template='class_create_student.html', status=201)
else:
return HttpResponseBadRequest("method %s is not allowed".format(request.method)) | [
"def",
"create_student",
"(",
"request",
")",
":",
"if",
"not",
"get_config",
"(",
"'proso_user'",
",",
"'allow_create_students'",
",",
"default",
"=",
"False",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'Creation of new users is not allowed.'",
")",
",",
"'error_type'",
":",
"'student_creation_not_allowed'",
"}",
",",
"template",
"=",
"'class_create_student.html'",
",",
"help_text",
"=",
"create_student",
".",
"__doc__",
",",
"status",
"=",
"403",
")",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"return",
"render",
"(",
"request",
",",
"'class_create_student.html'",
",",
"{",
"}",
",",
"help_text",
"=",
"create_student",
".",
"__doc__",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"if",
"not",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
"or",
"not",
"hasattr",
"(",
"request",
".",
"user",
",",
"\"userprofile\"",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'User is not logged in.'",
")",
",",
"'error_type'",
":",
"'user_unauthorized'",
"}",
",",
"template",
"=",
"'class_create_student.html'",
",",
"status",
"=",
"401",
")",
"data",
"=",
"json_body",
"(",
"request",
".",
"body",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"try",
":",
"cls",
"=",
"Class",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"data",
"[",
"'class'",
"]",
",",
"owner",
"=",
"request",
".",
"user",
".",
"userprofile",
")",
"except",
"(",
"Class",
".",
"DoesNotExist",
",",
"KeyError",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'Class with given id not found.'",
")",
",",
"'error_type'",
":",
"'class_not_found'",
",",
"}",
",",
"template",
"=",
"'class_create_student.html'",
",",
"status",
"=",
"404",
")",
"if",
"'first_name'",
"not",
"in",
"data",
"or",
"not",
"data",
"[",
"'first_name'",
"]",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'First name code is missing.'",
")",
",",
"'error_type'",
":",
"'missing_first_name'",
"}",
",",
"template",
"=",
"'class_create_student.html'",
",",
"status",
"=",
"400",
")",
"user",
"=",
"User",
"(",
"first_name",
"=",
"data",
"[",
"'first_name'",
"]",
")",
"if",
"data",
".",
"get",
"(",
"'last_name'",
")",
":",
"user",
".",
"last_name",
"=",
"data",
"[",
"'last_name'",
"]",
"if",
"data",
".",
"get",
"(",
"'email'",
")",
":",
"if",
"User",
".",
"objects",
".",
"filter",
"(",
"email",
"=",
"data",
"[",
"'email'",
"]",
")",
".",
"exists",
"(",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'There is already a user with the given e-mail.'",
")",
",",
"'error_type'",
":",
"'email_exists'",
"}",
",",
"template",
"=",
"'class_create_student.html'",
",",
"status",
"=",
"400",
")",
"user",
".",
"email",
"=",
"data",
"[",
"'email'",
"]",
"if",
"data",
".",
"get",
"(",
"'username'",
")",
":",
"if",
"User",
".",
"objects",
".",
"filter",
"(",
"username",
"=",
"data",
"[",
"'username'",
"]",
")",
".",
"exists",
"(",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'There is already a user with the given username.'",
")",
",",
"'error_type'",
":",
"'username_exists'",
"}",
",",
"template",
"=",
"'class_create_student.html'",
",",
"status",
"=",
"400",
")",
"user",
".",
"username",
"=",
"data",
"[",
"'username'",
"]",
"else",
":",
"user",
".",
"username",
"=",
"get_unused_username",
"(",
"user",
")",
"if",
"data",
".",
"get",
"(",
"'password'",
")",
":",
"user",
".",
"set_password",
"(",
"data",
"[",
"'password'",
"]",
")",
"user",
".",
"save",
"(",
")",
"cls",
".",
"members",
".",
"add",
"(",
"user",
".",
"userprofile",
")",
"return",
"render_json",
"(",
"request",
",",
"user",
".",
"userprofile",
".",
"to_json",
"(",
"nested",
"=",
"True",
")",
",",
"template",
"=",
"'class_create_student.html'",
",",
"status",
"=",
"201",
")",
"else",
":",
"return",
"HttpResponseBadRequest",
"(",
"\"method %s is not allowed\"",
".",
"format",
"(",
"request",
".",
"method",
")",
")"
]
| Create new user in class
POST parameters (JSON):
class:
id of the class
username (optional):
username of student, if not provided username is create based on name
password (optional):
password of student
first_name:
first_name of student
last_name (optional):
last_name of student
email (optional):
e-mail of student | [
"Create",
"new",
"user",
"in",
"class"
]
| 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views_classes.py#L104-L178 | train |
adaptive-learning/proso-apps | proso_user/views_classes.py | login_student | def login_student(request):
"""
Log in student
POST parameters (JSON):
student:
profile id of the student
"""
if not get_config('proso_user', 'allow_login_students', default=False):
return render_json(request, {
'error': _('Log in as student is not allowed.'),
'error_type': 'login_student_not_allowed'
}, template='class_create_student.html', help_text=login_student.__doc__, status=403)
if request.method == 'GET':
return render(request, 'class_login_student.html', {}, help_text=login_student.__doc__)
elif request.method == 'POST':
if not request.user.is_authenticated() or not hasattr(request.user, "userprofile"):
return render_json(request, {
'error': _('User is not logged in.'),
'error_type': 'user_unauthorized'
}, template='class_create_student.html', status=401)
data = json_body(request.body.decode("utf-8"))
try:
student = User.objects.get(userprofile=data.get('student'),
userprofile__classes__owner=request.user.userprofile)
except User.DoesNotExist:
return render_json(request, {
'error': _('Student not found'),
'error_type': 'student_not_found'
}, template='class_login_student.html', status=401)
if not student.is_active:
return render_json(request, {
'error': _('The account has not been activated.'),
'error_type': 'account_not_activated'
}, template='class_login_student.html', status=401)
student.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, student)
request.method = "GET"
return profile(request)
else:
return HttpResponseBadRequest("method %s is not allowed".format(request.method)) | python | def login_student(request):
"""
Log in student
POST parameters (JSON):
student:
profile id of the student
"""
if not get_config('proso_user', 'allow_login_students', default=False):
return render_json(request, {
'error': _('Log in as student is not allowed.'),
'error_type': 'login_student_not_allowed'
}, template='class_create_student.html', help_text=login_student.__doc__, status=403)
if request.method == 'GET':
return render(request, 'class_login_student.html', {}, help_text=login_student.__doc__)
elif request.method == 'POST':
if not request.user.is_authenticated() or not hasattr(request.user, "userprofile"):
return render_json(request, {
'error': _('User is not logged in.'),
'error_type': 'user_unauthorized'
}, template='class_create_student.html', status=401)
data = json_body(request.body.decode("utf-8"))
try:
student = User.objects.get(userprofile=data.get('student'),
userprofile__classes__owner=request.user.userprofile)
except User.DoesNotExist:
return render_json(request, {
'error': _('Student not found'),
'error_type': 'student_not_found'
}, template='class_login_student.html', status=401)
if not student.is_active:
return render_json(request, {
'error': _('The account has not been activated.'),
'error_type': 'account_not_activated'
}, template='class_login_student.html', status=401)
student.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, student)
request.method = "GET"
return profile(request)
else:
return HttpResponseBadRequest("method %s is not allowed".format(request.method)) | [
"def",
"login_student",
"(",
"request",
")",
":",
"if",
"not",
"get_config",
"(",
"'proso_user'",
",",
"'allow_login_students'",
",",
"default",
"=",
"False",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'Log in as student is not allowed.'",
")",
",",
"'error_type'",
":",
"'login_student_not_allowed'",
"}",
",",
"template",
"=",
"'class_create_student.html'",
",",
"help_text",
"=",
"login_student",
".",
"__doc__",
",",
"status",
"=",
"403",
")",
"if",
"request",
".",
"method",
"==",
"'GET'",
":",
"return",
"render",
"(",
"request",
",",
"'class_login_student.html'",
",",
"{",
"}",
",",
"help_text",
"=",
"login_student",
".",
"__doc__",
")",
"elif",
"request",
".",
"method",
"==",
"'POST'",
":",
"if",
"not",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
"or",
"not",
"hasattr",
"(",
"request",
".",
"user",
",",
"\"userprofile\"",
")",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'User is not logged in.'",
")",
",",
"'error_type'",
":",
"'user_unauthorized'",
"}",
",",
"template",
"=",
"'class_create_student.html'",
",",
"status",
"=",
"401",
")",
"data",
"=",
"json_body",
"(",
"request",
".",
"body",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"try",
":",
"student",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"userprofile",
"=",
"data",
".",
"get",
"(",
"'student'",
")",
",",
"userprofile__classes__owner",
"=",
"request",
".",
"user",
".",
"userprofile",
")",
"except",
"User",
".",
"DoesNotExist",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'Student not found'",
")",
",",
"'error_type'",
":",
"'student_not_found'",
"}",
",",
"template",
"=",
"'class_login_student.html'",
",",
"status",
"=",
"401",
")",
"if",
"not",
"student",
".",
"is_active",
":",
"return",
"render_json",
"(",
"request",
",",
"{",
"'error'",
":",
"_",
"(",
"'The account has not been activated.'",
")",
",",
"'error_type'",
":",
"'account_not_activated'",
"}",
",",
"template",
"=",
"'class_login_student.html'",
",",
"status",
"=",
"401",
")",
"student",
".",
"backend",
"=",
"'django.contrib.auth.backends.ModelBackend'",
"login",
"(",
"request",
",",
"student",
")",
"request",
".",
"method",
"=",
"\"GET\"",
"return",
"profile",
"(",
"request",
")",
"else",
":",
"return",
"HttpResponseBadRequest",
"(",
"\"method %s is not allowed\"",
".",
"format",
"(",
"request",
".",
"method",
")",
")"
]
| Log in student
POST parameters (JSON):
student:
profile id of the student | [
"Log",
"in",
"student"
]
| 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_user/views_classes.py#L181-L222 | train |
ZEDGR/pychal | challonge/participants.py | create | def create(tournament, name, **params):
"""Add a participant to a tournament."""
params.update({"name": name})
return api.fetch_and_parse(
"POST",
"tournaments/%s/participants" % tournament,
"participant",
**params) | python | def create(tournament, name, **params):
"""Add a participant to a tournament."""
params.update({"name": name})
return api.fetch_and_parse(
"POST",
"tournaments/%s/participants" % tournament,
"participant",
**params) | [
"def",
"create",
"(",
"tournament",
",",
"name",
",",
"*",
"*",
"params",
")",
":",
"params",
".",
"update",
"(",
"{",
"\"name\"",
":",
"name",
"}",
")",
"return",
"api",
".",
"fetch_and_parse",
"(",
"\"POST\"",
",",
"\"tournaments/%s/participants\"",
"%",
"tournament",
",",
"\"participant\"",
",",
"*",
"*",
"params",
")"
]
| Add a participant to a tournament. | [
"Add",
"a",
"participant",
"to",
"a",
"tournament",
"."
]
| 3600fa9e0557a2a14eb1ad0c0711d28dad3693d7 | https://github.com/ZEDGR/pychal/blob/3600fa9e0557a2a14eb1ad0c0711d28dad3693d7/challonge/participants.py#L11-L19 | train |
fjwCode/cerium | cerium/commands.py | Commands._build_cmd | def _build_cmd(self, args: Union[list, tuple]) -> str:
'''Build command.'''
cmd = [self.path]
cmd.extend(args)
return cmd | python | def _build_cmd(self, args: Union[list, tuple]) -> str:
'''Build command.'''
cmd = [self.path]
cmd.extend(args)
return cmd | [
"def",
"_build_cmd",
"(",
"self",
",",
"args",
":",
"Union",
"[",
"list",
",",
"tuple",
"]",
")",
"->",
"str",
":",
"cmd",
"=",
"[",
"self",
".",
"path",
"]",
"cmd",
".",
"extend",
"(",
"args",
")",
"return",
"cmd"
]
| Build command. | [
"Build",
"command",
"."
]
| f6e06e0dcf83a0bc924828e9d6cb81383ed2364f | https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/commands.py#L53-L57 | train |
TheGhouls/oct | oct/results/graphs.py | get_local_time | def get_local_time(index):
"""Localize datetime for better output in graphs
:param pandas.DateTimeIndex index: pandas datetime index
:return: aware time objet
:rtype: datetime.time
"""
dt = index.to_pydatetime()
dt = dt.replace(tzinfo=pytz.utc)
return dt.astimezone(tzlocal()).time() | python | def get_local_time(index):
"""Localize datetime for better output in graphs
:param pandas.DateTimeIndex index: pandas datetime index
:return: aware time objet
:rtype: datetime.time
"""
dt = index.to_pydatetime()
dt = dt.replace(tzinfo=pytz.utc)
return dt.astimezone(tzlocal()).time() | [
"def",
"get_local_time",
"(",
"index",
")",
":",
"dt",
"=",
"index",
".",
"to_pydatetime",
"(",
")",
"dt",
"=",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"return",
"dt",
".",
"astimezone",
"(",
"tzlocal",
"(",
")",
")",
".",
"time",
"(",
")"
]
| Localize datetime for better output in graphs
:param pandas.DateTimeIndex index: pandas datetime index
:return: aware time objet
:rtype: datetime.time | [
"Localize",
"datetime",
"for",
"better",
"output",
"in",
"graphs"
]
| 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/graphs.py#L9-L18 | train |
TheGhouls/oct | oct/results/graphs.py | resp_graph_raw | def resp_graph_raw(dataframe, image_name, dir='./'):
"""Response time graph for raw data
:param pandas.DataFrame dataframe: the raw results dataframe
:param str image_name: the output file name
:param str dir: the output directory
:return: None
"""
factor = int(len(dataframe) / 10)
df = dataframe.reset_index()
fig = pygal.Dot(stroke=False,
x_label_rotation=25,
x_title='Elapsed Time In Test (secs)',
y_title='Average Response Time (secs)',
js=('scripts/pygal-tooltip.min.js',))
try:
grp = df.groupby(pd.cut(df.index, np.arange(0, len(df), factor)))
fig.x_labels = [x for x in grp.first()['epoch']]
fig.title = image_name.split('.')[0]
fig.add('Time', [x for x in grp.describe()['scriptrun_time'].unstack()['mean'].round(2)])
except ZeroDivisionError:
print("Not enough data for raw graph")
fig.render_to_file(filename=os.path.join(dir, image_name)) | python | def resp_graph_raw(dataframe, image_name, dir='./'):
"""Response time graph for raw data
:param pandas.DataFrame dataframe: the raw results dataframe
:param str image_name: the output file name
:param str dir: the output directory
:return: None
"""
factor = int(len(dataframe) / 10)
df = dataframe.reset_index()
fig = pygal.Dot(stroke=False,
x_label_rotation=25,
x_title='Elapsed Time In Test (secs)',
y_title='Average Response Time (secs)',
js=('scripts/pygal-tooltip.min.js',))
try:
grp = df.groupby(pd.cut(df.index, np.arange(0, len(df), factor)))
fig.x_labels = [x for x in grp.first()['epoch']]
fig.title = image_name.split('.')[0]
fig.add('Time', [x for x in grp.describe()['scriptrun_time'].unstack()['mean'].round(2)])
except ZeroDivisionError:
print("Not enough data for raw graph")
fig.render_to_file(filename=os.path.join(dir, image_name)) | [
"def",
"resp_graph_raw",
"(",
"dataframe",
",",
"image_name",
",",
"dir",
"=",
"'./'",
")",
":",
"factor",
"=",
"int",
"(",
"len",
"(",
"dataframe",
")",
"/",
"10",
")",
"df",
"=",
"dataframe",
".",
"reset_index",
"(",
")",
"fig",
"=",
"pygal",
".",
"Dot",
"(",
"stroke",
"=",
"False",
",",
"x_label_rotation",
"=",
"25",
",",
"x_title",
"=",
"'Elapsed Time In Test (secs)'",
",",
"y_title",
"=",
"'Average Response Time (secs)'",
",",
"js",
"=",
"(",
"'scripts/pygal-tooltip.min.js'",
",",
")",
")",
"try",
":",
"grp",
"=",
"df",
".",
"groupby",
"(",
"pd",
".",
"cut",
"(",
"df",
".",
"index",
",",
"np",
".",
"arange",
"(",
"0",
",",
"len",
"(",
"df",
")",
",",
"factor",
")",
")",
")",
"fig",
".",
"x_labels",
"=",
"[",
"x",
"for",
"x",
"in",
"grp",
".",
"first",
"(",
")",
"[",
"'epoch'",
"]",
"]",
"fig",
".",
"title",
"=",
"image_name",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"fig",
".",
"add",
"(",
"'Time'",
",",
"[",
"x",
"for",
"x",
"in",
"grp",
".",
"describe",
"(",
")",
"[",
"'scriptrun_time'",
"]",
".",
"unstack",
"(",
")",
"[",
"'mean'",
"]",
".",
"round",
"(",
"2",
")",
"]",
")",
"except",
"ZeroDivisionError",
":",
"print",
"(",
"\"Not enough data for raw graph\"",
")",
"fig",
".",
"render_to_file",
"(",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"image_name",
")",
")"
]
| Response time graph for raw data
:param pandas.DataFrame dataframe: the raw results dataframe
:param str image_name: the output file name
:param str dir: the output directory
:return: None | [
"Response",
"time",
"graph",
"for",
"raw",
"data"
]
| 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/graphs.py#L21-L43 | train |
TheGhouls/oct | oct/results/graphs.py | resp_graph | def resp_graph(dataframe, image_name, dir='./'):
"""Response time graph for bucketed data
:param pandas.DataFrame dataframe: dataframe containing all data
:param str image_name: the output file name
:param str dir: the output directory
:return: None
"""
fig = pygal.TimeLine(x_title='Elapsed Time In Test (secs)',
y_title='Response Time (secs)',
x_label_rotation=25,
js=('scripts/pygal-tooltip.min.js',))
fig.add('AVG', [(get_local_time(index), row['mean'] if pd.notnull(row['mean']) else None)
for index, row in dataframe.iterrows()])
fig.add('90%', [(get_local_time(index), row['90%'] if pd.notnull(row['90%']) else None)
for index, row in dataframe.iterrows()])
fig.add('80%', [(get_local_time(index), row['80%'] if pd.notnull(row['80%']) else None)
for index, row in dataframe.iterrows()])
fig.render_to_file(filename=os.path.join(dir, image_name)) | python | def resp_graph(dataframe, image_name, dir='./'):
"""Response time graph for bucketed data
:param pandas.DataFrame dataframe: dataframe containing all data
:param str image_name: the output file name
:param str dir: the output directory
:return: None
"""
fig = pygal.TimeLine(x_title='Elapsed Time In Test (secs)',
y_title='Response Time (secs)',
x_label_rotation=25,
js=('scripts/pygal-tooltip.min.js',))
fig.add('AVG', [(get_local_time(index), row['mean'] if pd.notnull(row['mean']) else None)
for index, row in dataframe.iterrows()])
fig.add('90%', [(get_local_time(index), row['90%'] if pd.notnull(row['90%']) else None)
for index, row in dataframe.iterrows()])
fig.add('80%', [(get_local_time(index), row['80%'] if pd.notnull(row['80%']) else None)
for index, row in dataframe.iterrows()])
fig.render_to_file(filename=os.path.join(dir, image_name)) | [
"def",
"resp_graph",
"(",
"dataframe",
",",
"image_name",
",",
"dir",
"=",
"'./'",
")",
":",
"fig",
"=",
"pygal",
".",
"TimeLine",
"(",
"x_title",
"=",
"'Elapsed Time In Test (secs)'",
",",
"y_title",
"=",
"'Response Time (secs)'",
",",
"x_label_rotation",
"=",
"25",
",",
"js",
"=",
"(",
"'scripts/pygal-tooltip.min.js'",
",",
")",
")",
"fig",
".",
"add",
"(",
"'AVG'",
",",
"[",
"(",
"get_local_time",
"(",
"index",
")",
",",
"row",
"[",
"'mean'",
"]",
"if",
"pd",
".",
"notnull",
"(",
"row",
"[",
"'mean'",
"]",
")",
"else",
"None",
")",
"for",
"index",
",",
"row",
"in",
"dataframe",
".",
"iterrows",
"(",
")",
"]",
")",
"fig",
".",
"add",
"(",
"'90%'",
",",
"[",
"(",
"get_local_time",
"(",
"index",
")",
",",
"row",
"[",
"'90%'",
"]",
"if",
"pd",
".",
"notnull",
"(",
"row",
"[",
"'90%'",
"]",
")",
"else",
"None",
")",
"for",
"index",
",",
"row",
"in",
"dataframe",
".",
"iterrows",
"(",
")",
"]",
")",
"fig",
".",
"add",
"(",
"'80%'",
",",
"[",
"(",
"get_local_time",
"(",
"index",
")",
",",
"row",
"[",
"'80%'",
"]",
"if",
"pd",
".",
"notnull",
"(",
"row",
"[",
"'80%'",
"]",
")",
"else",
"None",
")",
"for",
"index",
",",
"row",
"in",
"dataframe",
".",
"iterrows",
"(",
")",
"]",
")",
"fig",
".",
"render_to_file",
"(",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"image_name",
")",
")"
]
| Response time graph for bucketed data
:param pandas.DataFrame dataframe: dataframe containing all data
:param str image_name: the output file name
:param str dir: the output directory
:return: None | [
"Response",
"time",
"graph",
"for",
"bucketed",
"data"
]
| 7e9bddeb3b8495a26442b1c86744e9fb187fe88f | https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/graphs.py#L46-L64 | train |
assamite/creamas | creamas/core/artifact.py | Artifact.add_eval | def add_eval(self, agent, e, fr=None):
"""Add or change agent's evaluation of the artifact with given framing
information.
:param agent: Name of the agent which did the evaluation.
:param float e: Evaluation for the artifact.
:param object fr: Framing information for the evaluation.
"""
self._evals[agent.name] = e
self._framings[agent.name] = fr | python | def add_eval(self, agent, e, fr=None):
"""Add or change agent's evaluation of the artifact with given framing
information.
:param agent: Name of the agent which did the evaluation.
:param float e: Evaluation for the artifact.
:param object fr: Framing information for the evaluation.
"""
self._evals[agent.name] = e
self._framings[agent.name] = fr | [
"def",
"add_eval",
"(",
"self",
",",
"agent",
",",
"e",
",",
"fr",
"=",
"None",
")",
":",
"self",
".",
"_evals",
"[",
"agent",
".",
"name",
"]",
"=",
"e",
"self",
".",
"_framings",
"[",
"agent",
".",
"name",
"]",
"=",
"fr"
]
| Add or change agent's evaluation of the artifact with given framing
information.
:param agent: Name of the agent which did the evaluation.
:param float e: Evaluation for the artifact.
:param object fr: Framing information for the evaluation. | [
"Add",
"or",
"change",
"agent",
"s",
"evaluation",
"of",
"the",
"artifact",
"with",
"given",
"framing",
"information",
"."
]
| 54dc3e31c97a3f938e58272f8ab80b6bcafeff58 | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/core/artifact.py#L63-L72 | train |
TUNE-Archive/freight_forwarder | freight_forwarder/container/container.py | Container.attach | def attach(self, stdout=True, stderr=True, stream=True, logs=False):
"""
Keeping this simple until we need to extend later.
"""
try:
data = parse_stream(self.client.attach(self.id, stdout, stderr, stream, logs))
except KeyboardInterrupt:
logger.warning(
"service container: {0} has been interrupted. "
"The container will be stopped but will not be deleted.".format(self.name)
)
data = None
self.stop()
return data | python | def attach(self, stdout=True, stderr=True, stream=True, logs=False):
"""
Keeping this simple until we need to extend later.
"""
try:
data = parse_stream(self.client.attach(self.id, stdout, stderr, stream, logs))
except KeyboardInterrupt:
logger.warning(
"service container: {0} has been interrupted. "
"The container will be stopped but will not be deleted.".format(self.name)
)
data = None
self.stop()
return data | [
"def",
"attach",
"(",
"self",
",",
"stdout",
"=",
"True",
",",
"stderr",
"=",
"True",
",",
"stream",
"=",
"True",
",",
"logs",
"=",
"False",
")",
":",
"try",
":",
"data",
"=",
"parse_stream",
"(",
"self",
".",
"client",
".",
"attach",
"(",
"self",
".",
"id",
",",
"stdout",
",",
"stderr",
",",
"stream",
",",
"logs",
")",
")",
"except",
"KeyboardInterrupt",
":",
"logger",
".",
"warning",
"(",
"\"service container: {0} has been interrupted. \"",
"\"The container will be stopped but will not be deleted.\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"data",
"=",
"None",
"self",
".",
"stop",
"(",
")",
"return",
"data"
]
| Keeping this simple until we need to extend later. | [
"Keeping",
"this",
"simple",
"until",
"we",
"need",
"to",
"extend",
"later",
"."
]
| 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/container.py#L84-L99 | train |
TUNE-Archive/freight_forwarder | freight_forwarder/container/container.py | Container.start | def start(self, attach=False):
"""
Start a container. If the container is running it will return itself.
returns a running Container.
"""
if self.state()['running']:
logger.info('is already running.', extra={'formatter': 'container', 'container': self.name})
return True
else:
try:
logger.info(
'is being started.', extra={'formatter': 'container', 'container': self.name}
)
# returns None on success
self.client.start(self.id)
if self._transcribe:
self.start_transcribing()
except APIError as e:
#
# This is some bs... I assume that its needed because of dockers changes in 1.18 api.
# I will resolve this next week when we stop passing properties to start.
if e.response.status_code == 500:
self.client.start(self.id)
else:
raise RuntimeError("Docker Error: {0}".format(e.explanation))
if attach:
self.attach()
exit_code = self.wait()
else:
exit_code = self._wait_for_exit_code()
return True if exit_code == 0 else False | python | def start(self, attach=False):
"""
Start a container. If the container is running it will return itself.
returns a running Container.
"""
if self.state()['running']:
logger.info('is already running.', extra={'formatter': 'container', 'container': self.name})
return True
else:
try:
logger.info(
'is being started.', extra={'formatter': 'container', 'container': self.name}
)
# returns None on success
self.client.start(self.id)
if self._transcribe:
self.start_transcribing()
except APIError as e:
#
# This is some bs... I assume that its needed because of dockers changes in 1.18 api.
# I will resolve this next week when we stop passing properties to start.
if e.response.status_code == 500:
self.client.start(self.id)
else:
raise RuntimeError("Docker Error: {0}".format(e.explanation))
if attach:
self.attach()
exit_code = self.wait()
else:
exit_code = self._wait_for_exit_code()
return True if exit_code == 0 else False | [
"def",
"start",
"(",
"self",
",",
"attach",
"=",
"False",
")",
":",
"if",
"self",
".",
"state",
"(",
")",
"[",
"'running'",
"]",
":",
"logger",
".",
"info",
"(",
"'is already running.'",
",",
"extra",
"=",
"{",
"'formatter'",
":",
"'container'",
",",
"'container'",
":",
"self",
".",
"name",
"}",
")",
"return",
"True",
"else",
":",
"try",
":",
"logger",
".",
"info",
"(",
"'is being started.'",
",",
"extra",
"=",
"{",
"'formatter'",
":",
"'container'",
",",
"'container'",
":",
"self",
".",
"name",
"}",
")",
"# returns None on success",
"self",
".",
"client",
".",
"start",
"(",
"self",
".",
"id",
")",
"if",
"self",
".",
"_transcribe",
":",
"self",
".",
"start_transcribing",
"(",
")",
"except",
"APIError",
"as",
"e",
":",
"#",
"# This is some bs... I assume that its needed because of dockers changes in 1.18 api.",
"# I will resolve this next week when we stop passing properties to start.",
"if",
"e",
".",
"response",
".",
"status_code",
"==",
"500",
":",
"self",
".",
"client",
".",
"start",
"(",
"self",
".",
"id",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Docker Error: {0}\"",
".",
"format",
"(",
"e",
".",
"explanation",
")",
")",
"if",
"attach",
":",
"self",
".",
"attach",
"(",
")",
"exit_code",
"=",
"self",
".",
"wait",
"(",
")",
"else",
":",
"exit_code",
"=",
"self",
".",
"_wait_for_exit_code",
"(",
")",
"return",
"True",
"if",
"exit_code",
"==",
"0",
"else",
"False"
]
| Start a container. If the container is running it will return itself.
returns a running Container. | [
"Start",
"a",
"container",
".",
"If",
"the",
"container",
"is",
"running",
"it",
"will",
"return",
"itself",
"."
]
| 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/container.py#L139-L176 | train |
TUNE-Archive/freight_forwarder | freight_forwarder/container/container.py | Container.stop | def stop(self):
"""
stop the container
"""
logger.info('is being stopped', extra={'formatter': 'container', 'container': self.name})
response = self.client.stop(self.id)
while self.state()['running']:
time.sleep(1)
return response | python | def stop(self):
"""
stop the container
"""
logger.info('is being stopped', extra={'formatter': 'container', 'container': self.name})
response = self.client.stop(self.id)
while self.state()['running']:
time.sleep(1)
return response | [
"def",
"stop",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'is being stopped'",
",",
"extra",
"=",
"{",
"'formatter'",
":",
"'container'",
",",
"'container'",
":",
"self",
".",
"name",
"}",
")",
"response",
"=",
"self",
".",
"client",
".",
"stop",
"(",
"self",
".",
"id",
")",
"while",
"self",
".",
"state",
"(",
")",
"[",
"'running'",
"]",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"return",
"response"
]
| stop the container | [
"stop",
"the",
"container"
]
| 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/container.py#L218-L228 | train |
TUNE-Archive/freight_forwarder | freight_forwarder/container/container.py | Container.dump_logs | def dump_logs(self):
"""dump entirety of the container logs to stdout
:returns None
"""
msg = "log dump: \n"
if self._transcribe:
if self._transcribe_queue:
while not self._transcribe_queue.empty():
logs = self._transcribe_queue.get()
if isinstance(logs, six.binary_type):
logs = logs.decode(encoding='UTF-8', errors="ignore")
msg = '{0} {1}'.format(msg, logs)
else:
logs = self.client.logs(self.id, stdout=True, stderr=True, stream=False, timestamps=False, tail='all')
if isinstance(logs, six.binary_type):
logs = logs.decode(encoding='UTF-8', errors="ignore")
msg = '{0}{1}'.format(msg, logs)
logger.error(msg) | python | def dump_logs(self):
"""dump entirety of the container logs to stdout
:returns None
"""
msg = "log dump: \n"
if self._transcribe:
if self._transcribe_queue:
while not self._transcribe_queue.empty():
logs = self._transcribe_queue.get()
if isinstance(logs, six.binary_type):
logs = logs.decode(encoding='UTF-8', errors="ignore")
msg = '{0} {1}'.format(msg, logs)
else:
logs = self.client.logs(self.id, stdout=True, stderr=True, stream=False, timestamps=False, tail='all')
if isinstance(logs, six.binary_type):
logs = logs.decode(encoding='UTF-8', errors="ignore")
msg = '{0}{1}'.format(msg, logs)
logger.error(msg) | [
"def",
"dump_logs",
"(",
"self",
")",
":",
"msg",
"=",
"\"log dump: \\n\"",
"if",
"self",
".",
"_transcribe",
":",
"if",
"self",
".",
"_transcribe_queue",
":",
"while",
"not",
"self",
".",
"_transcribe_queue",
".",
"empty",
"(",
")",
":",
"logs",
"=",
"self",
".",
"_transcribe_queue",
".",
"get",
"(",
")",
"if",
"isinstance",
"(",
"logs",
",",
"six",
".",
"binary_type",
")",
":",
"logs",
"=",
"logs",
".",
"decode",
"(",
"encoding",
"=",
"'UTF-8'",
",",
"errors",
"=",
"\"ignore\"",
")",
"msg",
"=",
"'{0} {1}'",
".",
"format",
"(",
"msg",
",",
"logs",
")",
"else",
":",
"logs",
"=",
"self",
".",
"client",
".",
"logs",
"(",
"self",
".",
"id",
",",
"stdout",
"=",
"True",
",",
"stderr",
"=",
"True",
",",
"stream",
"=",
"False",
",",
"timestamps",
"=",
"False",
",",
"tail",
"=",
"'all'",
")",
"if",
"isinstance",
"(",
"logs",
",",
"six",
".",
"binary_type",
")",
":",
"logs",
"=",
"logs",
".",
"decode",
"(",
"encoding",
"=",
"'UTF-8'",
",",
"errors",
"=",
"\"ignore\"",
")",
"msg",
"=",
"'{0}{1}'",
".",
"format",
"(",
"msg",
",",
"logs",
")",
"logger",
".",
"error",
"(",
"msg",
")"
]
| dump entirety of the container logs to stdout
:returns None | [
"dump",
"entirety",
"of",
"the",
"container",
"logs",
"to",
"stdout"
]
| 6ea4a49f474ec04abb8bb81b175c774a16b5312f | https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/container.py#L238-L260 | train |
uw-it-aca/uw-restclients-sws | uw_sws/registration.py | _registrations_for_section_with_active_flag | def _registrations_for_section_with_active_flag(section, is_active,
transcriptable_course=""):
"""
Returns a list of all uw_sws.models.Registration objects
for a section. There can be duplicates for a person.
If is_active is True, the objects will have is_active set to True.
Otherwise, is_active is undefined, and out of scope for this method.
"""
instructor_reg_id = ""
if (section.is_independent_study and
section.independent_study_instructor_regid is not None):
instructor_reg_id = section.independent_study_instructor_regid
params = [
("curriculum_abbreviation", section.curriculum_abbr),
("instructor_reg_id", instructor_reg_id),
("course_number", section.course_number),
("verbose", "true"),
("year", section.term.year),
("quarter", section.term.quarter),
("is_active", "true" if is_active else ""),
("section_id", section.section_id),
]
if transcriptable_course != "":
params.append(("transcriptable_course", transcriptable_course,))
url = "{}?{}".format(registration_res_url_prefix, urlencode(params))
return _json_to_registrations(get_resource(url), section) | python | def _registrations_for_section_with_active_flag(section, is_active,
transcriptable_course=""):
"""
Returns a list of all uw_sws.models.Registration objects
for a section. There can be duplicates for a person.
If is_active is True, the objects will have is_active set to True.
Otherwise, is_active is undefined, and out of scope for this method.
"""
instructor_reg_id = ""
if (section.is_independent_study and
section.independent_study_instructor_regid is not None):
instructor_reg_id = section.independent_study_instructor_regid
params = [
("curriculum_abbreviation", section.curriculum_abbr),
("instructor_reg_id", instructor_reg_id),
("course_number", section.course_number),
("verbose", "true"),
("year", section.term.year),
("quarter", section.term.quarter),
("is_active", "true" if is_active else ""),
("section_id", section.section_id),
]
if transcriptable_course != "":
params.append(("transcriptable_course", transcriptable_course,))
url = "{}?{}".format(registration_res_url_prefix, urlencode(params))
return _json_to_registrations(get_resource(url), section) | [
"def",
"_registrations_for_section_with_active_flag",
"(",
"section",
",",
"is_active",
",",
"transcriptable_course",
"=",
"\"\"",
")",
":",
"instructor_reg_id",
"=",
"\"\"",
"if",
"(",
"section",
".",
"is_independent_study",
"and",
"section",
".",
"independent_study_instructor_regid",
"is",
"not",
"None",
")",
":",
"instructor_reg_id",
"=",
"section",
".",
"independent_study_instructor_regid",
"params",
"=",
"[",
"(",
"\"curriculum_abbreviation\"",
",",
"section",
".",
"curriculum_abbr",
")",
",",
"(",
"\"instructor_reg_id\"",
",",
"instructor_reg_id",
")",
",",
"(",
"\"course_number\"",
",",
"section",
".",
"course_number",
")",
",",
"(",
"\"verbose\"",
",",
"\"true\"",
")",
",",
"(",
"\"year\"",
",",
"section",
".",
"term",
".",
"year",
")",
",",
"(",
"\"quarter\"",
",",
"section",
".",
"term",
".",
"quarter",
")",
",",
"(",
"\"is_active\"",
",",
"\"true\"",
"if",
"is_active",
"else",
"\"\"",
")",
",",
"(",
"\"section_id\"",
",",
"section",
".",
"section_id",
")",
",",
"]",
"if",
"transcriptable_course",
"!=",
"\"\"",
":",
"params",
".",
"append",
"(",
"(",
"\"transcriptable_course\"",
",",
"transcriptable_course",
",",
")",
")",
"url",
"=",
"\"{}?{}\"",
".",
"format",
"(",
"registration_res_url_prefix",
",",
"urlencode",
"(",
"params",
")",
")",
"return",
"_json_to_registrations",
"(",
"get_resource",
"(",
"url",
")",
",",
"section",
")"
]
| Returns a list of all uw_sws.models.Registration objects
for a section. There can be duplicates for a person.
If is_active is True, the objects will have is_active set to True.
Otherwise, is_active is undefined, and out of scope for this method. | [
"Returns",
"a",
"list",
"of",
"all",
"uw_sws",
".",
"models",
".",
"Registration",
"objects",
"for",
"a",
"section",
".",
"There",
"can",
"be",
"duplicates",
"for",
"a",
"person",
".",
"If",
"is_active",
"is",
"True",
"the",
"objects",
"will",
"have",
"is_active",
"set",
"to",
"True",
".",
"Otherwise",
"is_active",
"is",
"undefined",
"and",
"out",
"of",
"scope",
"for",
"this",
"method",
"."
]
| 4d36776dcca36855fc15c1b8fe7650ae045194cf | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/registration.py#L40-L69 | train |
uw-it-aca/uw-restclients-sws | uw_sws/registration.py | _json_to_registrations | def _json_to_registrations(data, section):
"""
Returns a list of all uw_sws.models.Registration objects
"""
registrations = []
person_threads = {}
for reg_data in data.get("Registrations", []):
registration = Registration()
registration.section = section
registration.is_active = reg_data["IsActive"]
registration.is_credit = reg_data["IsCredit"]
registration.is_auditor = reg_data["Auditor"]
registration.is_independent_start = reg_data["IsIndependentStart"]
if len(reg_data["StartDate"]):
registration.start_date = parse(reg_data["StartDate"])
if len(reg_data["EndDate"]):
registration.end_date = parse(reg_data["EndDate"])
if len(reg_data["RequestDate"]):
registration.request_date = parse(reg_data["RequestDate"])
registration.request_status = reg_data["RequestStatus"]
registration.duplicate_code = reg_data["DuplicateCode"]
registration.credits = reg_data["Credits"]
registration.repository_timestamp = datetime.strptime(
reg_data["RepositoryTimeStamp"], "%m/%d/%Y %H:%M:%S %p")
registration.repeat_course = reg_data["RepeatCourse"]
registration.grade = reg_data["Grade"]
registration._uwregid = reg_data["Person"]["RegID"]
if registration._uwregid not in person_threads:
thread = SWSPersonByRegIDThread()
thread.regid = registration._uwregid
thread.start()
person_threads[registration._uwregid] = thread
registrations.append(registration)
for registration in registrations:
thread = person_threads[registration._uwregid]
thread.join()
registration.person = thread.person
del registration._uwregid
return registrations | python | def _json_to_registrations(data, section):
"""
Returns a list of all uw_sws.models.Registration objects
"""
registrations = []
person_threads = {}
for reg_data in data.get("Registrations", []):
registration = Registration()
registration.section = section
registration.is_active = reg_data["IsActive"]
registration.is_credit = reg_data["IsCredit"]
registration.is_auditor = reg_data["Auditor"]
registration.is_independent_start = reg_data["IsIndependentStart"]
if len(reg_data["StartDate"]):
registration.start_date = parse(reg_data["StartDate"])
if len(reg_data["EndDate"]):
registration.end_date = parse(reg_data["EndDate"])
if len(reg_data["RequestDate"]):
registration.request_date = parse(reg_data["RequestDate"])
registration.request_status = reg_data["RequestStatus"]
registration.duplicate_code = reg_data["DuplicateCode"]
registration.credits = reg_data["Credits"]
registration.repository_timestamp = datetime.strptime(
reg_data["RepositoryTimeStamp"], "%m/%d/%Y %H:%M:%S %p")
registration.repeat_course = reg_data["RepeatCourse"]
registration.grade = reg_data["Grade"]
registration._uwregid = reg_data["Person"]["RegID"]
if registration._uwregid not in person_threads:
thread = SWSPersonByRegIDThread()
thread.regid = registration._uwregid
thread.start()
person_threads[registration._uwregid] = thread
registrations.append(registration)
for registration in registrations:
thread = person_threads[registration._uwregid]
thread.join()
registration.person = thread.person
del registration._uwregid
return registrations | [
"def",
"_json_to_registrations",
"(",
"data",
",",
"section",
")",
":",
"registrations",
"=",
"[",
"]",
"person_threads",
"=",
"{",
"}",
"for",
"reg_data",
"in",
"data",
".",
"get",
"(",
"\"Registrations\"",
",",
"[",
"]",
")",
":",
"registration",
"=",
"Registration",
"(",
")",
"registration",
".",
"section",
"=",
"section",
"registration",
".",
"is_active",
"=",
"reg_data",
"[",
"\"IsActive\"",
"]",
"registration",
".",
"is_credit",
"=",
"reg_data",
"[",
"\"IsCredit\"",
"]",
"registration",
".",
"is_auditor",
"=",
"reg_data",
"[",
"\"Auditor\"",
"]",
"registration",
".",
"is_independent_start",
"=",
"reg_data",
"[",
"\"IsIndependentStart\"",
"]",
"if",
"len",
"(",
"reg_data",
"[",
"\"StartDate\"",
"]",
")",
":",
"registration",
".",
"start_date",
"=",
"parse",
"(",
"reg_data",
"[",
"\"StartDate\"",
"]",
")",
"if",
"len",
"(",
"reg_data",
"[",
"\"EndDate\"",
"]",
")",
":",
"registration",
".",
"end_date",
"=",
"parse",
"(",
"reg_data",
"[",
"\"EndDate\"",
"]",
")",
"if",
"len",
"(",
"reg_data",
"[",
"\"RequestDate\"",
"]",
")",
":",
"registration",
".",
"request_date",
"=",
"parse",
"(",
"reg_data",
"[",
"\"RequestDate\"",
"]",
")",
"registration",
".",
"request_status",
"=",
"reg_data",
"[",
"\"RequestStatus\"",
"]",
"registration",
".",
"duplicate_code",
"=",
"reg_data",
"[",
"\"DuplicateCode\"",
"]",
"registration",
".",
"credits",
"=",
"reg_data",
"[",
"\"Credits\"",
"]",
"registration",
".",
"repository_timestamp",
"=",
"datetime",
".",
"strptime",
"(",
"reg_data",
"[",
"\"RepositoryTimeStamp\"",
"]",
",",
"\"%m/%d/%Y %H:%M:%S %p\"",
")",
"registration",
".",
"repeat_course",
"=",
"reg_data",
"[",
"\"RepeatCourse\"",
"]",
"registration",
".",
"grade",
"=",
"reg_data",
"[",
"\"Grade\"",
"]",
"registration",
".",
"_uwregid",
"=",
"reg_data",
"[",
"\"Person\"",
"]",
"[",
"\"RegID\"",
"]",
"if",
"registration",
".",
"_uwregid",
"not",
"in",
"person_threads",
":",
"thread",
"=",
"SWSPersonByRegIDThread",
"(",
")",
"thread",
".",
"regid",
"=",
"registration",
".",
"_uwregid",
"thread",
".",
"start",
"(",
")",
"person_threads",
"[",
"registration",
".",
"_uwregid",
"]",
"=",
"thread",
"registrations",
".",
"append",
"(",
"registration",
")",
"for",
"registration",
"in",
"registrations",
":",
"thread",
"=",
"person_threads",
"[",
"registration",
".",
"_uwregid",
"]",
"thread",
".",
"join",
"(",
")",
"registration",
".",
"person",
"=",
"thread",
".",
"person",
"del",
"registration",
".",
"_uwregid",
"return",
"registrations"
]
| Returns a list of all uw_sws.models.Registration objects | [
"Returns",
"a",
"list",
"of",
"all",
"uw_sws",
".",
"models",
".",
"Registration",
"objects"
]
| 4d36776dcca36855fc15c1b8fe7650ae045194cf | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/registration.py#L72-L114 | train |
uw-it-aca/uw-restclients-sws | uw_sws/registration.py | get_credits_by_section_and_regid | def get_credits_by_section_and_regid(section, regid):
"""
Returns a uw_sws.models.Registration object
for the section and regid passed in.
"""
deprecation("Use get_credits_by_reg_url")
# note trailing comma in URL, it's required for the optional dup_code param
url = "{}{},{},{},{},{},{},.json".format(
reg_credits_url_prefix,
section.term.year,
section.term.quarter,
re.sub(' ', '%20', section.curriculum_abbr),
section.course_number,
section.section_id,
regid
)
reg_data = get_resource(url)
try:
return Decimal(reg_data['Credits'].strip())
except InvalidOperation:
pass | python | def get_credits_by_section_and_regid(section, regid):
"""
Returns a uw_sws.models.Registration object
for the section and regid passed in.
"""
deprecation("Use get_credits_by_reg_url")
# note trailing comma in URL, it's required for the optional dup_code param
url = "{}{},{},{},{},{},{},.json".format(
reg_credits_url_prefix,
section.term.year,
section.term.quarter,
re.sub(' ', '%20', section.curriculum_abbr),
section.course_number,
section.section_id,
regid
)
reg_data = get_resource(url)
try:
return Decimal(reg_data['Credits'].strip())
except InvalidOperation:
pass | [
"def",
"get_credits_by_section_and_regid",
"(",
"section",
",",
"regid",
")",
":",
"deprecation",
"(",
"\"Use get_credits_by_reg_url\"",
")",
"# note trailing comma in URL, it's required for the optional dup_code param",
"url",
"=",
"\"{}{},{},{},{},{},{},.json\"",
".",
"format",
"(",
"reg_credits_url_prefix",
",",
"section",
".",
"term",
".",
"year",
",",
"section",
".",
"term",
".",
"quarter",
",",
"re",
".",
"sub",
"(",
"' '",
",",
"'%20'",
",",
"section",
".",
"curriculum_abbr",
")",
",",
"section",
".",
"course_number",
",",
"section",
".",
"section_id",
",",
"regid",
")",
"reg_data",
"=",
"get_resource",
"(",
"url",
")",
"try",
":",
"return",
"Decimal",
"(",
"reg_data",
"[",
"'Credits'",
"]",
".",
"strip",
"(",
")",
")",
"except",
"InvalidOperation",
":",
"pass"
]
| Returns a uw_sws.models.Registration object
for the section and regid passed in. | [
"Returns",
"a",
"uw_sws",
".",
"models",
".",
"Registration",
"object",
"for",
"the",
"section",
"and",
"regid",
"passed",
"in",
"."
]
| 4d36776dcca36855fc15c1b8fe7650ae045194cf | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/registration.py#L141-L163 | train |
uw-it-aca/uw-restclients-sws | uw_sws/registration.py | get_schedule_by_regid_and_term | def get_schedule_by_regid_and_term(regid, term,
non_time_schedule_instructors=True,
per_section_prefetch_callback=None,
transcriptable_course="", **kwargs):
"""
Returns a uw_sws.models.ClassSchedule object
for the regid and term passed in.
"""
if "include_instructor_not_on_time_schedule" in kwargs:
include = kwargs["include_instructor_not_on_time_schedule"]
non_time_schedule_instructors = include
params = [
('reg_id', regid),
]
if transcriptable_course != "":
params.append(("transcriptable_course", transcriptable_course,))
params.extend([
('quarter', term.quarter),
('is_active', 'true'),
('year', term.year),
])
url = "{}?{}".format(registration_res_url_prefix, urlencode(params))
return _json_to_schedule(get_resource(url), term, regid,
non_time_schedule_instructors,
per_section_prefetch_callback) | python | def get_schedule_by_regid_and_term(regid, term,
non_time_schedule_instructors=True,
per_section_prefetch_callback=None,
transcriptable_course="", **kwargs):
"""
Returns a uw_sws.models.ClassSchedule object
for the regid and term passed in.
"""
if "include_instructor_not_on_time_schedule" in kwargs:
include = kwargs["include_instructor_not_on_time_schedule"]
non_time_schedule_instructors = include
params = [
('reg_id', regid),
]
if transcriptable_course != "":
params.append(("transcriptable_course", transcriptable_course,))
params.extend([
('quarter', term.quarter),
('is_active', 'true'),
('year', term.year),
])
url = "{}?{}".format(registration_res_url_prefix, urlencode(params))
return _json_to_schedule(get_resource(url), term, regid,
non_time_schedule_instructors,
per_section_prefetch_callback) | [
"def",
"get_schedule_by_regid_and_term",
"(",
"regid",
",",
"term",
",",
"non_time_schedule_instructors",
"=",
"True",
",",
"per_section_prefetch_callback",
"=",
"None",
",",
"transcriptable_course",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"include_instructor_not_on_time_schedule\"",
"in",
"kwargs",
":",
"include",
"=",
"kwargs",
"[",
"\"include_instructor_not_on_time_schedule\"",
"]",
"non_time_schedule_instructors",
"=",
"include",
"params",
"=",
"[",
"(",
"'reg_id'",
",",
"regid",
")",
",",
"]",
"if",
"transcriptable_course",
"!=",
"\"\"",
":",
"params",
".",
"append",
"(",
"(",
"\"transcriptable_course\"",
",",
"transcriptable_course",
",",
")",
")",
"params",
".",
"extend",
"(",
"[",
"(",
"'quarter'",
",",
"term",
".",
"quarter",
")",
",",
"(",
"'is_active'",
",",
"'true'",
")",
",",
"(",
"'year'",
",",
"term",
".",
"year",
")",
",",
"]",
")",
"url",
"=",
"\"{}?{}\"",
".",
"format",
"(",
"registration_res_url_prefix",
",",
"urlencode",
"(",
"params",
")",
")",
"return",
"_json_to_schedule",
"(",
"get_resource",
"(",
"url",
")",
",",
"term",
",",
"regid",
",",
"non_time_schedule_instructors",
",",
"per_section_prefetch_callback",
")"
]
| Returns a uw_sws.models.ClassSchedule object
for the regid and term passed in. | [
"Returns",
"a",
"uw_sws",
".",
"models",
".",
"ClassSchedule",
"object",
"for",
"the",
"regid",
"and",
"term",
"passed",
"in",
"."
]
| 4d36776dcca36855fc15c1b8fe7650ae045194cf | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/registration.py#L178-L207 | train |
uw-it-aca/uw-restclients-sws | uw_sws/registration.py | _add_credits_grade_to_section | def _add_credits_grade_to_section(url, section):
"""
Given the registration url passed in,
add credits, grade, grade date in the section object
"""
section_reg_data = get_resource(url)
if section_reg_data is not None:
section.student_grade = section_reg_data['Grade']
section.is_auditor = section_reg_data['Auditor']
if len(section_reg_data['GradeDate']) > 0:
section.grade_date = parse(section_reg_data["GradeDate"]).date()
try:
raw_credits = section_reg_data['Credits'].strip()
section.student_credits = Decimal(raw_credits)
except InvalidOperation:
pass | python | def _add_credits_grade_to_section(url, section):
"""
Given the registration url passed in,
add credits, grade, grade date in the section object
"""
section_reg_data = get_resource(url)
if section_reg_data is not None:
section.student_grade = section_reg_data['Grade']
section.is_auditor = section_reg_data['Auditor']
if len(section_reg_data['GradeDate']) > 0:
section.grade_date = parse(section_reg_data["GradeDate"]).date()
try:
raw_credits = section_reg_data['Credits'].strip()
section.student_credits = Decimal(raw_credits)
except InvalidOperation:
pass | [
"def",
"_add_credits_grade_to_section",
"(",
"url",
",",
"section",
")",
":",
"section_reg_data",
"=",
"get_resource",
"(",
"url",
")",
"if",
"section_reg_data",
"is",
"not",
"None",
":",
"section",
".",
"student_grade",
"=",
"section_reg_data",
"[",
"'Grade'",
"]",
"section",
".",
"is_auditor",
"=",
"section_reg_data",
"[",
"'Auditor'",
"]",
"if",
"len",
"(",
"section_reg_data",
"[",
"'GradeDate'",
"]",
")",
">",
"0",
":",
"section",
".",
"grade_date",
"=",
"parse",
"(",
"section_reg_data",
"[",
"\"GradeDate\"",
"]",
")",
".",
"date",
"(",
")",
"try",
":",
"raw_credits",
"=",
"section_reg_data",
"[",
"'Credits'",
"]",
".",
"strip",
"(",
")",
"section",
".",
"student_credits",
"=",
"Decimal",
"(",
"raw_credits",
")",
"except",
"InvalidOperation",
":",
"pass"
]
| Given the registration url passed in,
add credits, grade, grade date in the section object | [
"Given",
"the",
"registration",
"url",
"passed",
"in",
"add",
"credits",
"grade",
"grade",
"date",
"in",
"the",
"section",
"object"
]
| 4d36776dcca36855fc15c1b8fe7650ae045194cf | https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/registration.py#L326-L341 | train |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/discrete_model.py | DiscreteModel.find_transition | def find_transition(self, gene: Gene, multiplexes: Tuple[Multiplex, ...]) -> Transition:
"""
Find and return a transition in the model for the given gene and multiplexes.
Raise an AttributeError if there is no multiplex in the graph with the given name.
"""
multiplexes = tuple(multiplex for multiplex in multiplexes if gene in multiplex.genes)
for transition in self.transitions:
if transition.gene == gene and set(transition.multiplexes) == set(multiplexes):
return transition
raise AttributeError(f'transition K_{gene.name}' + ''.join(f"+{multiplex!r}" for multiplex in multiplexes) + ' does not exist') | python | def find_transition(self, gene: Gene, multiplexes: Tuple[Multiplex, ...]) -> Transition:
"""
Find and return a transition in the model for the given gene and multiplexes.
Raise an AttributeError if there is no multiplex in the graph with the given name.
"""
multiplexes = tuple(multiplex for multiplex in multiplexes if gene in multiplex.genes)
for transition in self.transitions:
if transition.gene == gene and set(transition.multiplexes) == set(multiplexes):
return transition
raise AttributeError(f'transition K_{gene.name}' + ''.join(f"+{multiplex!r}" for multiplex in multiplexes) + ' does not exist') | [
"def",
"find_transition",
"(",
"self",
",",
"gene",
":",
"Gene",
",",
"multiplexes",
":",
"Tuple",
"[",
"Multiplex",
",",
"...",
"]",
")",
"->",
"Transition",
":",
"multiplexes",
"=",
"tuple",
"(",
"multiplex",
"for",
"multiplex",
"in",
"multiplexes",
"if",
"gene",
"in",
"multiplex",
".",
"genes",
")",
"for",
"transition",
"in",
"self",
".",
"transitions",
":",
"if",
"transition",
".",
"gene",
"==",
"gene",
"and",
"set",
"(",
"transition",
".",
"multiplexes",
")",
"==",
"set",
"(",
"multiplexes",
")",
":",
"return",
"transition",
"raise",
"AttributeError",
"(",
"f'transition K_{gene.name}'",
"+",
"''",
".",
"join",
"(",
"f\"+{multiplex!r}\"",
"for",
"multiplex",
"in",
"multiplexes",
")",
"+",
"' does not exist'",
")"
]
| Find and return a transition in the model for the given gene and multiplexes.
Raise an AttributeError if there is no multiplex in the graph with the given name. | [
"Find",
"and",
"return",
"a",
"transition",
"in",
"the",
"model",
"for",
"the",
"given",
"gene",
"and",
"multiplexes",
".",
"Raise",
"an",
"AttributeError",
"if",
"there",
"is",
"no",
"multiplex",
"in",
"the",
"graph",
"with",
"the",
"given",
"name",
"."
]
| f37a2f9358c1ce49f21c4a868b904da5dcd4614f | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/discrete_model.py#L43-L52 | train |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/discrete_model.py | DiscreteModel.available_state | def available_state(self, state: State) -> Tuple[State, ...]:
""" Return the state reachable from a given state. """
result = []
for gene in self.genes:
result.extend(self.available_state_for_gene(gene, state))
if len(result) > 1 and state in result:
result.remove(state)
return tuple(result) | python | def available_state(self, state: State) -> Tuple[State, ...]:
""" Return the state reachable from a given state. """
result = []
for gene in self.genes:
result.extend(self.available_state_for_gene(gene, state))
if len(result) > 1 and state in result:
result.remove(state)
return tuple(result) | [
"def",
"available_state",
"(",
"self",
",",
"state",
":",
"State",
")",
"->",
"Tuple",
"[",
"State",
",",
"...",
"]",
":",
"result",
"=",
"[",
"]",
"for",
"gene",
"in",
"self",
".",
"genes",
":",
"result",
".",
"extend",
"(",
"self",
".",
"available_state_for_gene",
"(",
"gene",
",",
"state",
")",
")",
"if",
"len",
"(",
"result",
")",
">",
"1",
"and",
"state",
"in",
"result",
":",
"result",
".",
"remove",
"(",
"state",
")",
"return",
"tuple",
"(",
"result",
")"
]
| Return the state reachable from a given state. | [
"Return",
"the",
"state",
"reachable",
"from",
"a",
"given",
"state",
"."
]
| f37a2f9358c1ce49f21c4a868b904da5dcd4614f | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/discrete_model.py#L54-L61 | train |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/discrete_model.py | DiscreteModel.available_state_for_gene | def available_state_for_gene(self, gene: Gene, state: State) -> Tuple[State, ...]:
""" Return the state reachable from a given state for a particular gene. """
result: List[State] = []
active_multiplex: Tuple[Multiplex] = gene.active_multiplex(state)
transition: Transition = self.find_transition(gene, active_multiplex)
current_state: int = state[gene]
done = set()
for target_state in transition.states:
target_state: int = self._state_after_transition(current_state, target_state)
if target_state not in done:
done.add(target_state)
new_state: State = state.copy()
new_state[gene] = target_state
result.append(new_state)
return tuple(result) | python | def available_state_for_gene(self, gene: Gene, state: State) -> Tuple[State, ...]:
""" Return the state reachable from a given state for a particular gene. """
result: List[State] = []
active_multiplex: Tuple[Multiplex] = gene.active_multiplex(state)
transition: Transition = self.find_transition(gene, active_multiplex)
current_state: int = state[gene]
done = set()
for target_state in transition.states:
target_state: int = self._state_after_transition(current_state, target_state)
if target_state not in done:
done.add(target_state)
new_state: State = state.copy()
new_state[gene] = target_state
result.append(new_state)
return tuple(result) | [
"def",
"available_state_for_gene",
"(",
"self",
",",
"gene",
":",
"Gene",
",",
"state",
":",
"State",
")",
"->",
"Tuple",
"[",
"State",
",",
"...",
"]",
":",
"result",
":",
"List",
"[",
"State",
"]",
"=",
"[",
"]",
"active_multiplex",
":",
"Tuple",
"[",
"Multiplex",
"]",
"=",
"gene",
".",
"active_multiplex",
"(",
"state",
")",
"transition",
":",
"Transition",
"=",
"self",
".",
"find_transition",
"(",
"gene",
",",
"active_multiplex",
")",
"current_state",
":",
"int",
"=",
"state",
"[",
"gene",
"]",
"done",
"=",
"set",
"(",
")",
"for",
"target_state",
"in",
"transition",
".",
"states",
":",
"target_state",
":",
"int",
"=",
"self",
".",
"_state_after_transition",
"(",
"current_state",
",",
"target_state",
")",
"if",
"target_state",
"not",
"in",
"done",
":",
"done",
".",
"add",
"(",
"target_state",
")",
"new_state",
":",
"State",
"=",
"state",
".",
"copy",
"(",
")",
"new_state",
"[",
"gene",
"]",
"=",
"target_state",
"result",
".",
"append",
"(",
"new_state",
")",
"return",
"tuple",
"(",
"result",
")"
]
| Return the state reachable from a given state for a particular gene. | [
"Return",
"the",
"state",
"reachable",
"from",
"a",
"given",
"state",
"for",
"a",
"particular",
"gene",
"."
]
| f37a2f9358c1ce49f21c4a868b904da5dcd4614f | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/discrete_model.py#L63-L77 | train |
Kortemme-Lab/klab | klab/biblio/pubmed.py | convert_single | def convert_single(ID, from_type, to_type):
'''Convenience function wrapper for convert. Takes a single ID and converts it from from_type to to_type.
The return value is the ID in the scheme of to_type.'''
if from_type not in converter_types:
raise PubMedConverterTypeException(from_type)
if to_type not in converter_types:
raise PubMedConverterTypeException(to_type)
results = convert([ID], from_type)
if ID in results:
return results[ID].get(to_type)
else:
return results[ID.upper()].get(to_type) | python | def convert_single(ID, from_type, to_type):
'''Convenience function wrapper for convert. Takes a single ID and converts it from from_type to to_type.
The return value is the ID in the scheme of to_type.'''
if from_type not in converter_types:
raise PubMedConverterTypeException(from_type)
if to_type not in converter_types:
raise PubMedConverterTypeException(to_type)
results = convert([ID], from_type)
if ID in results:
return results[ID].get(to_type)
else:
return results[ID.upper()].get(to_type) | [
"def",
"convert_single",
"(",
"ID",
",",
"from_type",
",",
"to_type",
")",
":",
"if",
"from_type",
"not",
"in",
"converter_types",
":",
"raise",
"PubMedConverterTypeException",
"(",
"from_type",
")",
"if",
"to_type",
"not",
"in",
"converter_types",
":",
"raise",
"PubMedConverterTypeException",
"(",
"to_type",
")",
"results",
"=",
"convert",
"(",
"[",
"ID",
"]",
",",
"from_type",
")",
"if",
"ID",
"in",
"results",
":",
"return",
"results",
"[",
"ID",
"]",
".",
"get",
"(",
"to_type",
")",
"else",
":",
"return",
"results",
"[",
"ID",
".",
"upper",
"(",
")",
"]",
".",
"get",
"(",
"to_type",
")"
]
| Convenience function wrapper for convert. Takes a single ID and converts it from from_type to to_type.
The return value is the ID in the scheme of to_type. | [
"Convenience",
"function",
"wrapper",
"for",
"convert",
".",
"Takes",
"a",
"single",
"ID",
"and",
"converts",
"it",
"from",
"from_type",
"to",
"to_type",
".",
"The",
"return",
"value",
"is",
"the",
"ID",
"in",
"the",
"scheme",
"of",
"to_type",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/biblio/pubmed.py#L89-L102 | train |
PBR/MQ2 | MQ2/mq2.py | cli_main | def cli_main(): # pragma: no cover
""" Main function when running from CLI. """
if '--debug' in sys.argv:
LOG.setLevel(logging.DEBUG)
elif '--verbose' in sys.argv:
LOG.setLevel(logging.INFO)
args = _get_arguments()
try:
plugin, folder = get_plugin_and_folder(
inputzip=args.inputzip,
inputdir=args.inputdir,
inputfile=args.inputfile)
LOG.debug('Plugin: %s -- Folder: %s' % (plugin.name, folder))
run_mq2(
plugin, folder, lod_threshold=args.lod, session=args.session)
except MQ2Exception as err:
print(err)
return 1
return 0 | python | def cli_main(): # pragma: no cover
""" Main function when running from CLI. """
if '--debug' in sys.argv:
LOG.setLevel(logging.DEBUG)
elif '--verbose' in sys.argv:
LOG.setLevel(logging.INFO)
args = _get_arguments()
try:
plugin, folder = get_plugin_and_folder(
inputzip=args.inputzip,
inputdir=args.inputdir,
inputfile=args.inputfile)
LOG.debug('Plugin: %s -- Folder: %s' % (plugin.name, folder))
run_mq2(
plugin, folder, lod_threshold=args.lod, session=args.session)
except MQ2Exception as err:
print(err)
return 1
return 0 | [
"def",
"cli_main",
"(",
")",
":",
"# pragma: no cover",
"if",
"'--debug'",
"in",
"sys",
".",
"argv",
":",
"LOG",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"elif",
"'--verbose'",
"in",
"sys",
".",
"argv",
":",
"LOG",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"args",
"=",
"_get_arguments",
"(",
")",
"try",
":",
"plugin",
",",
"folder",
"=",
"get_plugin_and_folder",
"(",
"inputzip",
"=",
"args",
".",
"inputzip",
",",
"inputdir",
"=",
"args",
".",
"inputdir",
",",
"inputfile",
"=",
"args",
".",
"inputfile",
")",
"LOG",
".",
"debug",
"(",
"'Plugin: %s -- Folder: %s'",
"%",
"(",
"plugin",
".",
"name",
",",
"folder",
")",
")",
"run_mq2",
"(",
"plugin",
",",
"folder",
",",
"lod_threshold",
"=",
"args",
".",
"lod",
",",
"session",
"=",
"args",
".",
"session",
")",
"except",
"MQ2Exception",
"as",
"err",
":",
"print",
"(",
"err",
")",
"return",
"1",
"return",
"0"
]
| Main function when running from CLI. | [
"Main",
"function",
"when",
"running",
"from",
"CLI",
"."
]
| 6d84dea47e6751333004743f588f03158e35c28d | https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/mq2.py#L95-L114 | train |
ronhanson/python-tbx | tbx/service.py | Service.loop | def loop(self):
"""
Run the demo suite in a loop.
"""
logging.info("Running %s in loop mode." % self.service_name)
res = None
while True:
try:
res = self.run()
time.sleep(self.loop_duration)
except KeyboardInterrupt:
logging.warning("Keyboard Interrupt during loop, stopping %s service now..." % self.service_name)
break
except Exception as e:
logging.exception("Error in %s main loop! (%s)" % (self.service_name, e))
raise e
return res | python | def loop(self):
"""
Run the demo suite in a loop.
"""
logging.info("Running %s in loop mode." % self.service_name)
res = None
while True:
try:
res = self.run()
time.sleep(self.loop_duration)
except KeyboardInterrupt:
logging.warning("Keyboard Interrupt during loop, stopping %s service now..." % self.service_name)
break
except Exception as e:
logging.exception("Error in %s main loop! (%s)" % (self.service_name, e))
raise e
return res | [
"def",
"loop",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"\"Running %s in loop mode.\"",
"%",
"self",
".",
"service_name",
")",
"res",
"=",
"None",
"while",
"True",
":",
"try",
":",
"res",
"=",
"self",
".",
"run",
"(",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"loop_duration",
")",
"except",
"KeyboardInterrupt",
":",
"logging",
".",
"warning",
"(",
"\"Keyboard Interrupt during loop, stopping %s service now...\"",
"%",
"self",
".",
"service_name",
")",
"break",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"exception",
"(",
"\"Error in %s main loop! (%s)\"",
"%",
"(",
"self",
".",
"service_name",
",",
"e",
")",
")",
"raise",
"e",
"return",
"res"
]
| Run the demo suite in a loop. | [
"Run",
"the",
"demo",
"suite",
"in",
"a",
"loop",
"."
]
| 87f72ae0cadecafbcd144f1e930181fba77f6b83 | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/service.py#L70-L87 | train |
uogbuji/versa | tools/py/writer/rdf.py | prep | def prep(s, p, o):
'''
Prepare a triple for rdflib
'''
def bnode_check(r):
return isinstance(r, mock_bnode) or r.startswith('VERSABLANKNODE_')
s = BNode() if bnode_check(s) else URIRef(s)
p = URIRef(p)
o = BNode() if bnode_check(o) else (URIRef(o) if isinstance(o, I) else Literal(o))
return s, p, o | python | def prep(s, p, o):
'''
Prepare a triple for rdflib
'''
def bnode_check(r):
return isinstance(r, mock_bnode) or r.startswith('VERSABLANKNODE_')
s = BNode() if bnode_check(s) else URIRef(s)
p = URIRef(p)
o = BNode() if bnode_check(o) else (URIRef(o) if isinstance(o, I) else Literal(o))
return s, p, o | [
"def",
"prep",
"(",
"s",
",",
"p",
",",
"o",
")",
":",
"def",
"bnode_check",
"(",
"r",
")",
":",
"return",
"isinstance",
"(",
"r",
",",
"mock_bnode",
")",
"or",
"r",
".",
"startswith",
"(",
"'VERSABLANKNODE_'",
")",
"s",
"=",
"BNode",
"(",
")",
"if",
"bnode_check",
"(",
"s",
")",
"else",
"URIRef",
"(",
"s",
")",
"p",
"=",
"URIRef",
"(",
"p",
")",
"o",
"=",
"BNode",
"(",
")",
"if",
"bnode_check",
"(",
"o",
")",
"else",
"(",
"URIRef",
"(",
"o",
")",
"if",
"isinstance",
"(",
"o",
",",
"I",
")",
"else",
"Literal",
"(",
"o",
")",
")",
"return",
"s",
",",
"p",
",",
"o"
]
| Prepare a triple for rdflib | [
"Prepare",
"a",
"triple",
"for",
"rdflib"
]
| f092ffc7ed363a5b170890955168500f32de0dd5 | https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/writer/rdf.py#L44-L54 | train |
adaptive-learning/proso-apps | proso_common/json_enrich.py | url | def url(request, json_list, nested, url_name='show_{}', ignore_get=None):
"""
Enrich the given list of objects, so they have URL.
Args:
request (django.http.request.HttpRequest): request which is currently processed
json_list (list): list of dicts (JSON objects to be enriched)
url_name (str|fun): pattern to create a url name taking object_type
ignore_get (list): list of GET parameters which are ignored when the URL is generated
Returns:
list: list of dicts (enriched JSON objects)
"""
if not ignore_get:
ignore_get = []
if isinstance(url_name, str):
url_string = str(url_name)
url_name = lambda x: url_string.format(x)
urls = cache.get('proso_urls')
if urls is None:
urls = {}
else:
urls = json_lib.loads(urls)
cache_updated = False
pass_string = pass_get_parameters_string(request, ignore_get)
for json in json_list:
if 'object_type' not in json or 'id' not in json:
continue
key = 'show_%s_%s' % (json['object_type'], json['id'])
if key in urls:
json['url'] = urls[key]
else:
cache_updated = True
json['url'] = reverse(url_name(json['object_type']), kwargs={'id': json['id']})
urls[key] = json['url']
json['url'] = append_get_parameters(json['url'], pass_string)
if cache_updated:
cache.set('proso_urls', json_lib.dumps(urls), CACHE_EXPIRATION) | python | def url(request, json_list, nested, url_name='show_{}', ignore_get=None):
"""
Enrich the given list of objects, so they have URL.
Args:
request (django.http.request.HttpRequest): request which is currently processed
json_list (list): list of dicts (JSON objects to be enriched)
url_name (str|fun): pattern to create a url name taking object_type
ignore_get (list): list of GET parameters which are ignored when the URL is generated
Returns:
list: list of dicts (enriched JSON objects)
"""
if not ignore_get:
ignore_get = []
if isinstance(url_name, str):
url_string = str(url_name)
url_name = lambda x: url_string.format(x)
urls = cache.get('proso_urls')
if urls is None:
urls = {}
else:
urls = json_lib.loads(urls)
cache_updated = False
pass_string = pass_get_parameters_string(request, ignore_get)
for json in json_list:
if 'object_type' not in json or 'id' not in json:
continue
key = 'show_%s_%s' % (json['object_type'], json['id'])
if key in urls:
json['url'] = urls[key]
else:
cache_updated = True
json['url'] = reverse(url_name(json['object_type']), kwargs={'id': json['id']})
urls[key] = json['url']
json['url'] = append_get_parameters(json['url'], pass_string)
if cache_updated:
cache.set('proso_urls', json_lib.dumps(urls), CACHE_EXPIRATION) | [
"def",
"url",
"(",
"request",
",",
"json_list",
",",
"nested",
",",
"url_name",
"=",
"'show_{}'",
",",
"ignore_get",
"=",
"None",
")",
":",
"if",
"not",
"ignore_get",
":",
"ignore_get",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"url_name",
",",
"str",
")",
":",
"url_string",
"=",
"str",
"(",
"url_name",
")",
"url_name",
"=",
"lambda",
"x",
":",
"url_string",
".",
"format",
"(",
"x",
")",
"urls",
"=",
"cache",
".",
"get",
"(",
"'proso_urls'",
")",
"if",
"urls",
"is",
"None",
":",
"urls",
"=",
"{",
"}",
"else",
":",
"urls",
"=",
"json_lib",
".",
"loads",
"(",
"urls",
")",
"cache_updated",
"=",
"False",
"pass_string",
"=",
"pass_get_parameters_string",
"(",
"request",
",",
"ignore_get",
")",
"for",
"json",
"in",
"json_list",
":",
"if",
"'object_type'",
"not",
"in",
"json",
"or",
"'id'",
"not",
"in",
"json",
":",
"continue",
"key",
"=",
"'show_%s_%s'",
"%",
"(",
"json",
"[",
"'object_type'",
"]",
",",
"json",
"[",
"'id'",
"]",
")",
"if",
"key",
"in",
"urls",
":",
"json",
"[",
"'url'",
"]",
"=",
"urls",
"[",
"key",
"]",
"else",
":",
"cache_updated",
"=",
"True",
"json",
"[",
"'url'",
"]",
"=",
"reverse",
"(",
"url_name",
"(",
"json",
"[",
"'object_type'",
"]",
")",
",",
"kwargs",
"=",
"{",
"'id'",
":",
"json",
"[",
"'id'",
"]",
"}",
")",
"urls",
"[",
"key",
"]",
"=",
"json",
"[",
"'url'",
"]",
"json",
"[",
"'url'",
"]",
"=",
"append_get_parameters",
"(",
"json",
"[",
"'url'",
"]",
",",
"pass_string",
")",
"if",
"cache_updated",
":",
"cache",
".",
"set",
"(",
"'proso_urls'",
",",
"json_lib",
".",
"dumps",
"(",
"urls",
")",
",",
"CACHE_EXPIRATION",
")"
]
| Enrich the given list of objects, so they have URL.
Args:
request (django.http.request.HttpRequest): request which is currently processed
json_list (list): list of dicts (JSON objects to be enriched)
url_name (str|fun): pattern to create a url name taking object_type
ignore_get (list): list of GET parameters which are ignored when the URL is generated
Returns:
list: list of dicts (enriched JSON objects) | [
"Enrich",
"the",
"given",
"list",
"of",
"objects",
"so",
"they",
"have",
"URL",
"."
]
| 8278c72e498d6ef8d392cc47b48473f4ec037142 | https://github.com/adaptive-learning/proso-apps/blob/8278c72e498d6ef8d392cc47b48473f4ec037142/proso_common/json_enrich.py#L13-L50 | train |
clement-alexandre/TotemBionet | totembionet/src/discrete_model/state.py | State.sub_state_by_gene_name | def sub_state_by_gene_name(self, *gene_names: str) -> 'State':
"""
Create a sub state with only the gene passed in arguments.
Example
-------
>>> state.sub_state_by_gene_name('operon')
{operon: 2}
>>> state.sub_state_by_gene_name('mucuB')
{mucuB: 0}
"""
return State({gene: state for gene, state in self.items() if gene.name in gene_names}) | python | def sub_state_by_gene_name(self, *gene_names: str) -> 'State':
"""
Create a sub state with only the gene passed in arguments.
Example
-------
>>> state.sub_state_by_gene_name('operon')
{operon: 2}
>>> state.sub_state_by_gene_name('mucuB')
{mucuB: 0}
"""
return State({gene: state for gene, state in self.items() if gene.name in gene_names}) | [
"def",
"sub_state_by_gene_name",
"(",
"self",
",",
"*",
"gene_names",
":",
"str",
")",
"->",
"'State'",
":",
"return",
"State",
"(",
"{",
"gene",
":",
"state",
"for",
"gene",
",",
"state",
"in",
"self",
".",
"items",
"(",
")",
"if",
"gene",
".",
"name",
"in",
"gene_names",
"}",
")"
]
| Create a sub state with only the gene passed in arguments.
Example
-------
>>> state.sub_state_by_gene_name('operon')
{operon: 2}
>>> state.sub_state_by_gene_name('mucuB')
{mucuB: 0} | [
"Create",
"a",
"sub",
"state",
"with",
"only",
"the",
"gene",
"passed",
"in",
"arguments",
"."
]
| f37a2f9358c1ce49f21c4a868b904da5dcd4614f | https://github.com/clement-alexandre/TotemBionet/blob/f37a2f9358c1ce49f21c4a868b904da5dcd4614f/totembionet/src/discrete_model/state.py#L41-L54 | train |
peergradeio/flask-mongo-profiler | flask_mongo_profiler/utils.py | combine_events_to_queries | def combine_events_to_queries(_mongo_events):
"""Combines pymongo.monitoring events to queries.
CommandStartedEvent has queries information.
CommandSuccessfulEvent has timing information.
Iterate over events and map against mongo's request_id (the query).
"""
queries = {} # map on the request_id
for event in _mongo_events:
if event.request_id not in queries:
try:
connection = ProfilingQueryConnection(*event.connection_id)
except NameError:
connection = event.connection_id
queries[event.request_id] = dict( # all event types have this
command_name=event.command_name,
# Unpack host,
connection=connection,
operation_id=event.operation_id,
)
if isinstance(event, pymongo.monitoring.CommandStartedEvent):
queries[event.request_id].update(
command=sanitize_dict(event.command.to_dict()),
database_name=event.database_name,
)
elif isinstance(event, pymongo.monitoring.CommandSucceededEvent):
queries[event.request_id].update(duration=event.duration_micros / 1000)
elif isinstance(event, pymongo.monitoring.CommandFailedEvent):
queries[event.request_id].update(
failure=sanitize_dict(event.failure),
duration=event.duration_micros / 1000,
)
return queries.values() | python | def combine_events_to_queries(_mongo_events):
"""Combines pymongo.monitoring events to queries.
CommandStartedEvent has queries information.
CommandSuccessfulEvent has timing information.
Iterate over events and map against mongo's request_id (the query).
"""
queries = {} # map on the request_id
for event in _mongo_events:
if event.request_id not in queries:
try:
connection = ProfilingQueryConnection(*event.connection_id)
except NameError:
connection = event.connection_id
queries[event.request_id] = dict( # all event types have this
command_name=event.command_name,
# Unpack host,
connection=connection,
operation_id=event.operation_id,
)
if isinstance(event, pymongo.monitoring.CommandStartedEvent):
queries[event.request_id].update(
command=sanitize_dict(event.command.to_dict()),
database_name=event.database_name,
)
elif isinstance(event, pymongo.monitoring.CommandSucceededEvent):
queries[event.request_id].update(duration=event.duration_micros / 1000)
elif isinstance(event, pymongo.monitoring.CommandFailedEvent):
queries[event.request_id].update(
failure=sanitize_dict(event.failure),
duration=event.duration_micros / 1000,
)
return queries.values() | [
"def",
"combine_events_to_queries",
"(",
"_mongo_events",
")",
":",
"queries",
"=",
"{",
"}",
"# map on the request_id",
"for",
"event",
"in",
"_mongo_events",
":",
"if",
"event",
".",
"request_id",
"not",
"in",
"queries",
":",
"try",
":",
"connection",
"=",
"ProfilingQueryConnection",
"(",
"*",
"event",
".",
"connection_id",
")",
"except",
"NameError",
":",
"connection",
"=",
"event",
".",
"connection_id",
"queries",
"[",
"event",
".",
"request_id",
"]",
"=",
"dict",
"(",
"# all event types have this",
"command_name",
"=",
"event",
".",
"command_name",
",",
"# Unpack host,",
"connection",
"=",
"connection",
",",
"operation_id",
"=",
"event",
".",
"operation_id",
",",
")",
"if",
"isinstance",
"(",
"event",
",",
"pymongo",
".",
"monitoring",
".",
"CommandStartedEvent",
")",
":",
"queries",
"[",
"event",
".",
"request_id",
"]",
".",
"update",
"(",
"command",
"=",
"sanitize_dict",
"(",
"event",
".",
"command",
".",
"to_dict",
"(",
")",
")",
",",
"database_name",
"=",
"event",
".",
"database_name",
",",
")",
"elif",
"isinstance",
"(",
"event",
",",
"pymongo",
".",
"monitoring",
".",
"CommandSucceededEvent",
")",
":",
"queries",
"[",
"event",
".",
"request_id",
"]",
".",
"update",
"(",
"duration",
"=",
"event",
".",
"duration_micros",
"/",
"1000",
")",
"elif",
"isinstance",
"(",
"event",
",",
"pymongo",
".",
"monitoring",
".",
"CommandFailedEvent",
")",
":",
"queries",
"[",
"event",
".",
"request_id",
"]",
".",
"update",
"(",
"failure",
"=",
"sanitize_dict",
"(",
"event",
".",
"failure",
")",
",",
"duration",
"=",
"event",
".",
"duration_micros",
"/",
"1000",
",",
")",
"return",
"queries",
".",
"values",
"(",
")"
]
| Combines pymongo.monitoring events to queries.
CommandStartedEvent has queries information.
CommandSuccessfulEvent has timing information.
Iterate over events and map against mongo's request_id (the query). | [
"Combines",
"pymongo",
".",
"monitoring",
"events",
"to",
"queries",
"."
]
| a267eeb49fea07c9a24fb370bd9d7a90ed313ccf | https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/utils.py#L60-L96 | train |
brunato/lograptor | lograptor/api.py | lograptor | def lograptor(files, patterns=None, matcher='ruled', cfgfiles=None, apps=None, hosts=None,
filters=None, time_period=None, time_range=None, case=False, invert=False,
word=False, files_with_match=None, count=False, quiet=False, max_count=0,
only_matching=False, line_number=False, with_filename=None,
ip_lookup=False, uid_lookup=False, anonymize=False, thread=False,
before_context=0, after_context=0, context=0):
"""
Run lograptor with arguments. Experimental feature to use the log processor into
generic Python scripts. This part is still under development, do not use.
:param files: Input files. Each argument can be a file path or a glob pathname.
:param patterns: Regex patterns, select the log line if at least one pattern matches.
:param matcher: Matcher engine, can be 'ruled' (default), 'unruled' or 'unparsed'.
:param cfgfiles: use a specific configuration file.
:param apps: process the log lines related to a list of applications.
:param hosts: process the log lines related to a list of hosts.
:param filters: process the log lines that match all the conditions for rule's field values.
:param time_range: process the log lines related to a time range.
:param time_period: restrict the search scope to a date or a date interval.
:param case: ignore case distinctions, defaults to `False`.
:param invert: invert the sense of patterns regexp matching.
:param word: force PATTERN to match only whole words.
:param files_with_match: get only names of FILEs containing matches, defaults is `False`.
:param count: get only a count of matching lines per FILE.
:param quiet: suppress all normal output.
:param max_count: stop after NUM matches.
:param only_matching: get only the part of a line matching PATTERN.
:param line_number: get line number with output lines.
:param with_filename: get or suppress the file name for each match.
:param ip_lookup: translate IP addresses to DNS names.
:param uid_lookup: translate numeric UIDs to usernames.
:param anonymize: anonymize defined rule's fields value.
:param thread: get the lines of logs related to each log line selected.
:param before_context: get NUM lines of leading context for each log line selected.
:param after_context: get NUM lines of trailing context for each log line selected.
:param context: get NUM lines of output context for each log line selected.
:return:
"""
cli_parser = create_argument_parser()
args = cli_parser.parse_args()
args.files = files
args.matcher = matcher
args.cfgfiles = cfgfiles
args.time_period = time_period
args.time_range = time_range
args.case = case
args.invert = invert
args.word = word
args.files_with_match = files_with_match
args.count = count
args.quiet = quiet
args.max_count = max_count
args.only_matching = only_matching
args.line_number = line_number
args.with_filename = with_filename
args.anonymize = anonymize
args.ip_lookup = ip_lookup
args.uid_lookup = uid_lookup
args.thread = thread
args.context = context
args.after_context = after_context
args.before_context = before_context
args.patterns = [''] if patterns is None else patterns
if apps is not None:
args.apps = apps
if hosts is not None:
args.hosts = hosts
if filters is not None:
args.filters = filters
_lograptor = LogRaptor(args)
return _lograptor() | python | def lograptor(files, patterns=None, matcher='ruled', cfgfiles=None, apps=None, hosts=None,
filters=None, time_period=None, time_range=None, case=False, invert=False,
word=False, files_with_match=None, count=False, quiet=False, max_count=0,
only_matching=False, line_number=False, with_filename=None,
ip_lookup=False, uid_lookup=False, anonymize=False, thread=False,
before_context=0, after_context=0, context=0):
"""
Run lograptor with arguments. Experimental feature to use the log processor into
generic Python scripts. This part is still under development, do not use.
:param files: Input files. Each argument can be a file path or a glob pathname.
:param patterns: Regex patterns, select the log line if at least one pattern matches.
:param matcher: Matcher engine, can be 'ruled' (default), 'unruled' or 'unparsed'.
:param cfgfiles: use a specific configuration file.
:param apps: process the log lines related to a list of applications.
:param hosts: process the log lines related to a list of hosts.
:param filters: process the log lines that match all the conditions for rule's field values.
:param time_range: process the log lines related to a time range.
:param time_period: restrict the search scope to a date or a date interval.
:param case: ignore case distinctions, defaults to `False`.
:param invert: invert the sense of patterns regexp matching.
:param word: force PATTERN to match only whole words.
:param files_with_match: get only names of FILEs containing matches, defaults is `False`.
:param count: get only a count of matching lines per FILE.
:param quiet: suppress all normal output.
:param max_count: stop after NUM matches.
:param only_matching: get only the part of a line matching PATTERN.
:param line_number: get line number with output lines.
:param with_filename: get or suppress the file name for each match.
:param ip_lookup: translate IP addresses to DNS names.
:param uid_lookup: translate numeric UIDs to usernames.
:param anonymize: anonymize defined rule's fields value.
:param thread: get the lines of logs related to each log line selected.
:param before_context: get NUM lines of leading context for each log line selected.
:param after_context: get NUM lines of trailing context for each log line selected.
:param context: get NUM lines of output context for each log line selected.
:return:
"""
cli_parser = create_argument_parser()
args = cli_parser.parse_args()
args.files = files
args.matcher = matcher
args.cfgfiles = cfgfiles
args.time_period = time_period
args.time_range = time_range
args.case = case
args.invert = invert
args.word = word
args.files_with_match = files_with_match
args.count = count
args.quiet = quiet
args.max_count = max_count
args.only_matching = only_matching
args.line_number = line_number
args.with_filename = with_filename
args.anonymize = anonymize
args.ip_lookup = ip_lookup
args.uid_lookup = uid_lookup
args.thread = thread
args.context = context
args.after_context = after_context
args.before_context = before_context
args.patterns = [''] if patterns is None else patterns
if apps is not None:
args.apps = apps
if hosts is not None:
args.hosts = hosts
if filters is not None:
args.filters = filters
_lograptor = LogRaptor(args)
return _lograptor() | [
"def",
"lograptor",
"(",
"files",
",",
"patterns",
"=",
"None",
",",
"matcher",
"=",
"'ruled'",
",",
"cfgfiles",
"=",
"None",
",",
"apps",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"time_period",
"=",
"None",
",",
"time_range",
"=",
"None",
",",
"case",
"=",
"False",
",",
"invert",
"=",
"False",
",",
"word",
"=",
"False",
",",
"files_with_match",
"=",
"None",
",",
"count",
"=",
"False",
",",
"quiet",
"=",
"False",
",",
"max_count",
"=",
"0",
",",
"only_matching",
"=",
"False",
",",
"line_number",
"=",
"False",
",",
"with_filename",
"=",
"None",
",",
"ip_lookup",
"=",
"False",
",",
"uid_lookup",
"=",
"False",
",",
"anonymize",
"=",
"False",
",",
"thread",
"=",
"False",
",",
"before_context",
"=",
"0",
",",
"after_context",
"=",
"0",
",",
"context",
"=",
"0",
")",
":",
"cli_parser",
"=",
"create_argument_parser",
"(",
")",
"args",
"=",
"cli_parser",
".",
"parse_args",
"(",
")",
"args",
".",
"files",
"=",
"files",
"args",
".",
"matcher",
"=",
"matcher",
"args",
".",
"cfgfiles",
"=",
"cfgfiles",
"args",
".",
"time_period",
"=",
"time_period",
"args",
".",
"time_range",
"=",
"time_range",
"args",
".",
"case",
"=",
"case",
"args",
".",
"invert",
"=",
"invert",
"args",
".",
"word",
"=",
"word",
"args",
".",
"files_with_match",
"=",
"files_with_match",
"args",
".",
"count",
"=",
"count",
"args",
".",
"quiet",
"=",
"quiet",
"args",
".",
"max_count",
"=",
"max_count",
"args",
".",
"only_matching",
"=",
"only_matching",
"args",
".",
"line_number",
"=",
"line_number",
"args",
".",
"with_filename",
"=",
"with_filename",
"args",
".",
"anonymize",
"=",
"anonymize",
"args",
".",
"ip_lookup",
"=",
"ip_lookup",
"args",
".",
"uid_lookup",
"=",
"uid_lookup",
"args",
".",
"thread",
"=",
"thread",
"args",
".",
"context",
"=",
"context",
"args",
".",
"after_context",
"=",
"after_context",
"args",
".",
"before_context",
"=",
"before_context",
"args",
".",
"patterns",
"=",
"[",
"''",
"]",
"if",
"patterns",
"is",
"None",
"else",
"patterns",
"if",
"apps",
"is",
"not",
"None",
":",
"args",
".",
"apps",
"=",
"apps",
"if",
"hosts",
"is",
"not",
"None",
":",
"args",
".",
"hosts",
"=",
"hosts",
"if",
"filters",
"is",
"not",
"None",
":",
"args",
".",
"filters",
"=",
"filters",
"_lograptor",
"=",
"LogRaptor",
"(",
"args",
")",
"return",
"_lograptor",
"(",
")"
]
| Run lograptor with arguments. Experimental feature to use the log processor into
generic Python scripts. This part is still under development, do not use.
:param files: Input files. Each argument can be a file path or a glob pathname.
:param patterns: Regex patterns, select the log line if at least one pattern matches.
:param matcher: Matcher engine, can be 'ruled' (default), 'unruled' or 'unparsed'.
:param cfgfiles: use a specific configuration file.
:param apps: process the log lines related to a list of applications.
:param hosts: process the log lines related to a list of hosts.
:param filters: process the log lines that match all the conditions for rule's field values.
:param time_range: process the log lines related to a time range.
:param time_period: restrict the search scope to a date or a date interval.
:param case: ignore case distinctions, defaults to `False`.
:param invert: invert the sense of patterns regexp matching.
:param word: force PATTERN to match only whole words.
:param files_with_match: get only names of FILEs containing matches, defaults is `False`.
:param count: get only a count of matching lines per FILE.
:param quiet: suppress all normal output.
:param max_count: stop after NUM matches.
:param only_matching: get only the part of a line matching PATTERN.
:param line_number: get line number with output lines.
:param with_filename: get or suppress the file name for each match.
:param ip_lookup: translate IP addresses to DNS names.
:param uid_lookup: translate numeric UIDs to usernames.
:param anonymize: anonymize defined rule's fields value.
:param thread: get the lines of logs related to each log line selected.
:param before_context: get NUM lines of leading context for each log line selected.
:param after_context: get NUM lines of trailing context for each log line selected.
:param context: get NUM lines of output context for each log line selected.
:return: | [
"Run",
"lograptor",
"with",
"arguments",
".",
"Experimental",
"feature",
"to",
"use",
"the",
"log",
"processor",
"into",
"generic",
"Python",
"scripts",
".",
"This",
"part",
"is",
"still",
"under",
"development",
"do",
"not",
"use",
"."
]
| b1f09fe1b429ed15110610092704ef12d253f3c9 | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/api.py#L341-L413 | train |
46elks/elkme | elkme/config.py | generate_config | def generate_config(conf):
"""
Generates a configuration file using the ConfigParser library that
can be saved to a file for subsequent reads
"""
c = {}
def to_key(key, default):
if conf.get(key):
c[key] = '{} = {}'.format(key, conf.get(key))
else:
c[key] = default
to_key('username', '# username = u1234...')
to_key('password', '# password = secret...')
to_key('from', '# from = elkme')
to_key('to', '# to = +46700000000')
return (True, c) | python | def generate_config(conf):
"""
Generates a configuration file using the ConfigParser library that
can be saved to a file for subsequent reads
"""
c = {}
def to_key(key, default):
if conf.get(key):
c[key] = '{} = {}'.format(key, conf.get(key))
else:
c[key] = default
to_key('username', '# username = u1234...')
to_key('password', '# password = secret...')
to_key('from', '# from = elkme')
to_key('to', '# to = +46700000000')
return (True, c) | [
"def",
"generate_config",
"(",
"conf",
")",
":",
"c",
"=",
"{",
"}",
"def",
"to_key",
"(",
"key",
",",
"default",
")",
":",
"if",
"conf",
".",
"get",
"(",
"key",
")",
":",
"c",
"[",
"key",
"]",
"=",
"'{} = {}'",
".",
"format",
"(",
"key",
",",
"conf",
".",
"get",
"(",
"key",
")",
")",
"else",
":",
"c",
"[",
"key",
"]",
"=",
"default",
"to_key",
"(",
"'username'",
",",
"'# username = u1234...'",
")",
"to_key",
"(",
"'password'",
",",
"'# password = secret...'",
")",
"to_key",
"(",
"'from'",
",",
"'# from = elkme'",
")",
"to_key",
"(",
"'to'",
",",
"'# to = +46700000000'",
")",
"return",
"(",
"True",
",",
"c",
")"
]
| Generates a configuration file using the ConfigParser library that
can be saved to a file for subsequent reads | [
"Generates",
"a",
"configuration",
"file",
"using",
"the",
"ConfigParser",
"library",
"that",
"can",
"be",
"saved",
"to",
"a",
"file",
"for",
"subsequent",
"reads"
]
| 6ebdce6f8ac852fc6f714d1f1b836f2777fece4e | https://github.com/46elks/elkme/blob/6ebdce6f8ac852fc6f714d1f1b836f2777fece4e/elkme/config.py#L144-L161 | train |
Kortemme-Lab/klab | klab/bio/rcsb.py | retrieve_xml | def retrieve_xml(pdb_id, silent = True):
'''The RCSB website now compresses XML files.'''
xml_gz = retrieve_file_from_RCSB(get_rcsb_files_connection(), "/download/%s.xml.gz" % pdb_id, silent = silent)
cf = StringIO.StringIO()
cf.write(xml_gz)
cf.seek(0)
df = gzip.GzipFile(fileobj = cf, mode='rb')
contents = df.read()
df.close()
return contents | python | def retrieve_xml(pdb_id, silent = True):
'''The RCSB website now compresses XML files.'''
xml_gz = retrieve_file_from_RCSB(get_rcsb_files_connection(), "/download/%s.xml.gz" % pdb_id, silent = silent)
cf = StringIO.StringIO()
cf.write(xml_gz)
cf.seek(0)
df = gzip.GzipFile(fileobj = cf, mode='rb')
contents = df.read()
df.close()
return contents | [
"def",
"retrieve_xml",
"(",
"pdb_id",
",",
"silent",
"=",
"True",
")",
":",
"xml_gz",
"=",
"retrieve_file_from_RCSB",
"(",
"get_rcsb_files_connection",
"(",
")",
",",
"\"/download/%s.xml.gz\"",
"%",
"pdb_id",
",",
"silent",
"=",
"silent",
")",
"cf",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"cf",
".",
"write",
"(",
"xml_gz",
")",
"cf",
".",
"seek",
"(",
"0",
")",
"df",
"=",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"cf",
",",
"mode",
"=",
"'rb'",
")",
"contents",
"=",
"df",
".",
"read",
"(",
")",
"df",
".",
"close",
"(",
")",
"return",
"contents"
]
| The RCSB website now compresses XML files. | [
"The",
"RCSB",
"website",
"now",
"compresses",
"XML",
"files",
"."
]
| 6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/rcsb.py#L92-L101 | train |
projectshift/shift-boiler | boiler/log/mail.py | mail_logger | def mail_logger(app, level = None):
"""
Get mail logger
Returns configured instance of mail logger ready to be attached to app.
Important: app.config['DEBUG'] must be False!
:param app: application instance
:param level: mail errors of this level
:return: SMTPHandler
"""
credentials = None
if app.config['MAIL_USERNAME'] and app.config['MAIL_PASSWORD']:
credentials = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
secure = None
if app.config['MAIL_USE_TLS']:
secure = tuple()
# @todo: move to configuration
config = dict(
mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
fromaddr=app.config['MAIL_DEFAULT_SENDER'],
toaddrs=app.config['ADMINS'],
credentials = credentials,
subject='Application exception',
secure = secure,
timeout=1.0
)
mail_handler = SMTPHandler(**config)
if level is None: level = logging.ERROR
mail_handler.setLevel(level)
mail_log_format = '''
Message type: %(levelname)s
Location: %(pathname)s:%(lineno)d
Module: %(module)s
Function: %(funcName)s
Time: %(asctime)s
Message:
%(message)s
'''
mail_handler.setFormatter(logging.Formatter(mail_log_format))
return mail_handler | python | def mail_logger(app, level = None):
"""
Get mail logger
Returns configured instance of mail logger ready to be attached to app.
Important: app.config['DEBUG'] must be False!
:param app: application instance
:param level: mail errors of this level
:return: SMTPHandler
"""
credentials = None
if app.config['MAIL_USERNAME'] and app.config['MAIL_PASSWORD']:
credentials = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
secure = None
if app.config['MAIL_USE_TLS']:
secure = tuple()
# @todo: move to configuration
config = dict(
mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
fromaddr=app.config['MAIL_DEFAULT_SENDER'],
toaddrs=app.config['ADMINS'],
credentials = credentials,
subject='Application exception',
secure = secure,
timeout=1.0
)
mail_handler = SMTPHandler(**config)
if level is None: level = logging.ERROR
mail_handler.setLevel(level)
mail_log_format = '''
Message type: %(levelname)s
Location: %(pathname)s:%(lineno)d
Module: %(module)s
Function: %(funcName)s
Time: %(asctime)s
Message:
%(message)s
'''
mail_handler.setFormatter(logging.Formatter(mail_log_format))
return mail_handler | [
"def",
"mail_logger",
"(",
"app",
",",
"level",
"=",
"None",
")",
":",
"credentials",
"=",
"None",
"if",
"app",
".",
"config",
"[",
"'MAIL_USERNAME'",
"]",
"and",
"app",
".",
"config",
"[",
"'MAIL_PASSWORD'",
"]",
":",
"credentials",
"=",
"(",
"app",
".",
"config",
"[",
"'MAIL_USERNAME'",
"]",
",",
"app",
".",
"config",
"[",
"'MAIL_PASSWORD'",
"]",
")",
"secure",
"=",
"None",
"if",
"app",
".",
"config",
"[",
"'MAIL_USE_TLS'",
"]",
":",
"secure",
"=",
"tuple",
"(",
")",
"# @todo: move to configuration",
"config",
"=",
"dict",
"(",
"mailhost",
"=",
"(",
"app",
".",
"config",
"[",
"'MAIL_SERVER'",
"]",
",",
"app",
".",
"config",
"[",
"'MAIL_PORT'",
"]",
")",
",",
"fromaddr",
"=",
"app",
".",
"config",
"[",
"'MAIL_DEFAULT_SENDER'",
"]",
",",
"toaddrs",
"=",
"app",
".",
"config",
"[",
"'ADMINS'",
"]",
",",
"credentials",
"=",
"credentials",
",",
"subject",
"=",
"'Application exception'",
",",
"secure",
"=",
"secure",
",",
"timeout",
"=",
"1.0",
")",
"mail_handler",
"=",
"SMTPHandler",
"(",
"*",
"*",
"config",
")",
"if",
"level",
"is",
"None",
":",
"level",
"=",
"logging",
".",
"ERROR",
"mail_handler",
".",
"setLevel",
"(",
"level",
")",
"mail_log_format",
"=",
"'''\n Message type: %(levelname)s\n Location: %(pathname)s:%(lineno)d\n Module: %(module)s\n Function: %(funcName)s\n Time: %(asctime)s\n\n Message:\n\n %(message)s\n '''",
"mail_handler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"mail_log_format",
")",
")",
"return",
"mail_handler"
]
| Get mail logger
Returns configured instance of mail logger ready to be attached to app.
Important: app.config['DEBUG'] must be False!
:param app: application instance
:param level: mail errors of this level
:return: SMTPHandler | [
"Get",
"mail",
"logger",
"Returns",
"configured",
"instance",
"of",
"mail",
"logger",
"ready",
"to",
"be",
"attached",
"to",
"app",
"."
]
| 8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b | https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/log/mail.py#L5-L53 | train |
trendels/rhino | rhino/util.py | dual_use_decorator | def dual_use_decorator(fn):
"""Turn a function into a decorator that can be called with or without
arguments."""
@functools.wraps(fn)
def decorator(*args, **kw):
if len(args) == 1 and not kw and callable(args[0]):
return fn()(args[0])
else:
return fn(*args, **kw)
return decorator | python | def dual_use_decorator(fn):
"""Turn a function into a decorator that can be called with or without
arguments."""
@functools.wraps(fn)
def decorator(*args, **kw):
if len(args) == 1 and not kw and callable(args[0]):
return fn()(args[0])
else:
return fn(*args, **kw)
return decorator | [
"def",
"dual_use_decorator",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"not",
"kw",
"and",
"callable",
"(",
"args",
"[",
"0",
"]",
")",
":",
"return",
"fn",
"(",
")",
"(",
"args",
"[",
"0",
"]",
")",
"else",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"return",
"decorator"
]
| Turn a function into a decorator that can be called with or without
arguments. | [
"Turn",
"a",
"function",
"into",
"a",
"decorator",
"that",
"can",
"be",
"called",
"with",
"or",
"without",
"arguments",
"."
]
| f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/util.py#L46-L55 | train |
trendels/rhino | rhino/util.py | get_args | def get_args(obj):
"""Get a list of argument names for a callable."""
if inspect.isfunction(obj):
return inspect.getargspec(obj).args
elif inspect.ismethod(obj):
return inspect.getargspec(obj).args[1:]
elif inspect.isclass(obj):
return inspect.getargspec(obj.__init__).args[1:]
elif hasattr(obj, '__call__'):
return inspect.getargspec(obj.__call__).args[1:]
else:
raise TypeError("Can't inspect signature of '%s' object." % obj) | python | def get_args(obj):
"""Get a list of argument names for a callable."""
if inspect.isfunction(obj):
return inspect.getargspec(obj).args
elif inspect.ismethod(obj):
return inspect.getargspec(obj).args[1:]
elif inspect.isclass(obj):
return inspect.getargspec(obj.__init__).args[1:]
elif hasattr(obj, '__call__'):
return inspect.getargspec(obj.__call__).args[1:]
else:
raise TypeError("Can't inspect signature of '%s' object." % obj) | [
"def",
"get_args",
"(",
"obj",
")",
":",
"if",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
":",
"return",
"inspect",
".",
"getargspec",
"(",
"obj",
")",
".",
"args",
"elif",
"inspect",
".",
"ismethod",
"(",
"obj",
")",
":",
"return",
"inspect",
".",
"getargspec",
"(",
"obj",
")",
".",
"args",
"[",
"1",
":",
"]",
"elif",
"inspect",
".",
"isclass",
"(",
"obj",
")",
":",
"return",
"inspect",
".",
"getargspec",
"(",
"obj",
".",
"__init__",
")",
".",
"args",
"[",
"1",
":",
"]",
"elif",
"hasattr",
"(",
"obj",
",",
"'__call__'",
")",
":",
"return",
"inspect",
".",
"getargspec",
"(",
"obj",
".",
"__call__",
")",
".",
"args",
"[",
"1",
":",
"]",
"else",
":",
"raise",
"TypeError",
"(",
"\"Can't inspect signature of '%s' object.\"",
"%",
"obj",
")"
]
| Get a list of argument names for a callable. | [
"Get",
"a",
"list",
"of",
"argument",
"names",
"for",
"a",
"callable",
"."
]
| f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/util.py#L70-L81 | train |
trendels/rhino | rhino/util.py | apply_ctx | def apply_ctx(fn, ctx):
"""Return fn with ctx partially applied, if requested.
If the `fn` callable accepts an argument named "ctx", returns a
functools.partial object with ctx=ctx applied, else returns `fn` unchanged.
For this to work, the 'ctx' argument must come after any arguments that are
passed as positional arguments. For example, 'ctx' must be the 2nd argument
for request handlers, serializers and deserializers, that are always called
with one positional argument (the request, object to serialize, and input
filehandle, respectively).
"""
if 'ctx' in get_args(fn):
return functools.partial(fn, ctx=ctx)
else:
return fn | python | def apply_ctx(fn, ctx):
"""Return fn with ctx partially applied, if requested.
If the `fn` callable accepts an argument named "ctx", returns a
functools.partial object with ctx=ctx applied, else returns `fn` unchanged.
For this to work, the 'ctx' argument must come after any arguments that are
passed as positional arguments. For example, 'ctx' must be the 2nd argument
for request handlers, serializers and deserializers, that are always called
with one positional argument (the request, object to serialize, and input
filehandle, respectively).
"""
if 'ctx' in get_args(fn):
return functools.partial(fn, ctx=ctx)
else:
return fn | [
"def",
"apply_ctx",
"(",
"fn",
",",
"ctx",
")",
":",
"if",
"'ctx'",
"in",
"get_args",
"(",
"fn",
")",
":",
"return",
"functools",
".",
"partial",
"(",
"fn",
",",
"ctx",
"=",
"ctx",
")",
"else",
":",
"return",
"fn"
]
| Return fn with ctx partially applied, if requested.
If the `fn` callable accepts an argument named "ctx", returns a
functools.partial object with ctx=ctx applied, else returns `fn` unchanged.
For this to work, the 'ctx' argument must come after any arguments that are
passed as positional arguments. For example, 'ctx' must be the 2nd argument
for request handlers, serializers and deserializers, that are always called
with one positional argument (the request, object to serialize, and input
filehandle, respectively). | [
"Return",
"fn",
"with",
"ctx",
"partially",
"applied",
"if",
"requested",
"."
]
| f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/util.py#L84-L99 | train |
trendels/rhino | rhino/util.py | log_exception | def log_exception(exc_info=None, stream=None):
"""Log the 'exc_info' tuple in the server log."""
exc_info = exc_info or sys.exc_info()
stream = stream or sys.stderr
try:
from traceback import print_exception
print_exception(exc_info[0], exc_info[1], exc_info[2], None, stream)
stream.flush()
finally:
exc_info = None | python | def log_exception(exc_info=None, stream=None):
"""Log the 'exc_info' tuple in the server log."""
exc_info = exc_info or sys.exc_info()
stream = stream or sys.stderr
try:
from traceback import print_exception
print_exception(exc_info[0], exc_info[1], exc_info[2], None, stream)
stream.flush()
finally:
exc_info = None | [
"def",
"log_exception",
"(",
"exc_info",
"=",
"None",
",",
"stream",
"=",
"None",
")",
":",
"exc_info",
"=",
"exc_info",
"or",
"sys",
".",
"exc_info",
"(",
")",
"stream",
"=",
"stream",
"or",
"sys",
".",
"stderr",
"try",
":",
"from",
"traceback",
"import",
"print_exception",
"print_exception",
"(",
"exc_info",
"[",
"0",
"]",
",",
"exc_info",
"[",
"1",
"]",
",",
"exc_info",
"[",
"2",
"]",
",",
"None",
",",
"stream",
")",
"stream",
".",
"flush",
"(",
")",
"finally",
":",
"exc_info",
"=",
"None"
]
| Log the 'exc_info' tuple in the server log. | [
"Log",
"the",
"exc_info",
"tuple",
"in",
"the",
"server",
"log",
"."
]
| f1f0ef21b6080a2bd130b38b5bef163074c94aed | https://github.com/trendels/rhino/blob/f1f0ef21b6080a2bd130b38b5bef163074c94aed/rhino/util.py#L102-L111 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy._create_get_request | def _create_get_request(self, resource, billomat_id='', command=None, params=None):
"""
Creates a get request and return the response data
"""
if not params:
params = {}
if not command:
command = ''
else:
command = '/' + command
assert (isinstance(resource, str))
if billomat_id:
assert (isinstance(billomat_id, int) or isinstance(billomat_id, str))
if isinstance(billomat_id, int):
billomat_id = str(billomat_id)
response = self.session.get(
url=self.api_url + resource + ('/' + billomat_id if billomat_id else '') + command,
params=params,
)
return self._handle_response(response) | python | def _create_get_request(self, resource, billomat_id='', command=None, params=None):
"""
Creates a get request and return the response data
"""
if not params:
params = {}
if not command:
command = ''
else:
command = '/' + command
assert (isinstance(resource, str))
if billomat_id:
assert (isinstance(billomat_id, int) or isinstance(billomat_id, str))
if isinstance(billomat_id, int):
billomat_id = str(billomat_id)
response = self.session.get(
url=self.api_url + resource + ('/' + billomat_id if billomat_id else '') + command,
params=params,
)
return self._handle_response(response) | [
"def",
"_create_get_request",
"(",
"self",
",",
"resource",
",",
"billomat_id",
"=",
"''",
",",
"command",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"if",
"not",
"command",
":",
"command",
"=",
"''",
"else",
":",
"command",
"=",
"'/'",
"+",
"command",
"assert",
"(",
"isinstance",
"(",
"resource",
",",
"str",
")",
")",
"if",
"billomat_id",
":",
"assert",
"(",
"isinstance",
"(",
"billomat_id",
",",
"int",
")",
"or",
"isinstance",
"(",
"billomat_id",
",",
"str",
")",
")",
"if",
"isinstance",
"(",
"billomat_id",
",",
"int",
")",
":",
"billomat_id",
"=",
"str",
"(",
"billomat_id",
")",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
"=",
"self",
".",
"api_url",
"+",
"resource",
"+",
"(",
"'/'",
"+",
"billomat_id",
"if",
"billomat_id",
"else",
"''",
")",
"+",
"command",
",",
"params",
"=",
"params",
",",
")",
"return",
"self",
".",
"_handle_response",
"(",
"response",
")"
]
| Creates a get request and return the response data | [
"Creates",
"a",
"get",
"request",
"and",
"return",
"the",
"response",
"data"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L40-L63 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy._create_put_request | def _create_put_request(self, resource, billomat_id, command=None, send_data=None):
"""
Creates a put request and return the response data
"""
assert (isinstance(resource, str))
if isinstance(billomat_id, int):
billomat_id = str(billomat_id)
if not command:
command = ''
else:
command = '/' + command
response = self.session.put(
url=self.api_url + resource + '/' + billomat_id + command,
data=json.dumps(send_data),
)
return self._handle_response(response) | python | def _create_put_request(self, resource, billomat_id, command=None, send_data=None):
"""
Creates a put request and return the response data
"""
assert (isinstance(resource, str))
if isinstance(billomat_id, int):
billomat_id = str(billomat_id)
if not command:
command = ''
else:
command = '/' + command
response = self.session.put(
url=self.api_url + resource + '/' + billomat_id + command,
data=json.dumps(send_data),
)
return self._handle_response(response) | [
"def",
"_create_put_request",
"(",
"self",
",",
"resource",
",",
"billomat_id",
",",
"command",
"=",
"None",
",",
"send_data",
"=",
"None",
")",
":",
"assert",
"(",
"isinstance",
"(",
"resource",
",",
"str",
")",
")",
"if",
"isinstance",
"(",
"billomat_id",
",",
"int",
")",
":",
"billomat_id",
"=",
"str",
"(",
"billomat_id",
")",
"if",
"not",
"command",
":",
"command",
"=",
"''",
"else",
":",
"command",
"=",
"'/'",
"+",
"command",
"response",
"=",
"self",
".",
"session",
".",
"put",
"(",
"url",
"=",
"self",
".",
"api_url",
"+",
"resource",
"+",
"'/'",
"+",
"billomat_id",
"+",
"command",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"send_data",
")",
",",
")",
"return",
"self",
".",
"_handle_response",
"(",
"response",
")"
]
| Creates a put request and return the response data | [
"Creates",
"a",
"put",
"request",
"and",
"return",
"the",
"response",
"data"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L87-L106 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy._create_delete_request | def _create_delete_request(self, resource, billomat_id):
"""
Creates a post request and return the response data
"""
assert (isinstance(resource, str))
if isinstance(billomat_id, int):
billomat_id = str(billomat_id)
response = self.session.delete(
url=self.api_url + resource + '/' + billomat_id,
)
return self._handle_response(response) | python | def _create_delete_request(self, resource, billomat_id):
"""
Creates a post request and return the response data
"""
assert (isinstance(resource, str))
if isinstance(billomat_id, int):
billomat_id = str(billomat_id)
response = self.session.delete(
url=self.api_url + resource + '/' + billomat_id,
)
return self._handle_response(response) | [
"def",
"_create_delete_request",
"(",
"self",
",",
"resource",
",",
"billomat_id",
")",
":",
"assert",
"(",
"isinstance",
"(",
"resource",
",",
"str",
")",
")",
"if",
"isinstance",
"(",
"billomat_id",
",",
"int",
")",
":",
"billomat_id",
"=",
"str",
"(",
"billomat_id",
")",
"response",
"=",
"self",
".",
"session",
".",
"delete",
"(",
"url",
"=",
"self",
".",
"api_url",
"+",
"resource",
"+",
"'/'",
"+",
"billomat_id",
",",
")",
"return",
"self",
".",
"_handle_response",
"(",
"response",
")"
]
| Creates a post request and return the response data | [
"Creates",
"a",
"post",
"request",
"and",
"return",
"the",
"response",
"data"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L108-L121 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy._handle_failed_response | def _handle_failed_response(self, response):
"""
Handle the failed response and check for rate limit exceeded
If rate limit exceeded it runs the rate_limit_exceeded function which you should overwrite
:param response: requests.Response
:type response: requests.Reponse
:return: None
:rtype: None
"""
if response.status_code == requests.codes.too_many_requests:
return self.rate_limit_exceeded(response)
else:
response.raise_for_status() | python | def _handle_failed_response(self, response):
"""
Handle the failed response and check for rate limit exceeded
If rate limit exceeded it runs the rate_limit_exceeded function which you should overwrite
:param response: requests.Response
:type response: requests.Reponse
:return: None
:rtype: None
"""
if response.status_code == requests.codes.too_many_requests:
return self.rate_limit_exceeded(response)
else:
response.raise_for_status() | [
"def",
"_handle_failed_response",
"(",
"self",
",",
"response",
")",
":",
"if",
"response",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"too_many_requests",
":",
"return",
"self",
".",
"rate_limit_exceeded",
"(",
"response",
")",
"else",
":",
"response",
".",
"raise_for_status",
"(",
")"
]
| Handle the failed response and check for rate limit exceeded
If rate limit exceeded it runs the rate_limit_exceeded function which you should overwrite
:param response: requests.Response
:type response: requests.Reponse
:return: None
:rtype: None | [
"Handle",
"the",
"failed",
"response",
"and",
"check",
"for",
"rate",
"limit",
"exceeded",
"If",
"rate",
"limit",
"exceeded",
"it",
"runs",
"the",
"rate_limit_exceeded",
"function",
"which",
"you",
"should",
"overwrite"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L139-L152 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy._get_resource_per_page | def _get_resource_per_page(self, resource, per_page=1000, page=1, params=None):
"""
Gets specific data per resource page and per page
"""
assert (isinstance(resource, str))
common_params = {'per_page': per_page, 'page': page}
if not params:
params = common_params
else:
params.update(common_params)
return self._create_get_request(resource=resource, params=params) | python | def _get_resource_per_page(self, resource, per_page=1000, page=1, params=None):
"""
Gets specific data per resource page and per page
"""
assert (isinstance(resource, str))
common_params = {'per_page': per_page, 'page': page}
if not params:
params = common_params
else:
params.update(common_params)
return self._create_get_request(resource=resource, params=params) | [
"def",
"_get_resource_per_page",
"(",
"self",
",",
"resource",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"assert",
"(",
"isinstance",
"(",
"resource",
",",
"str",
")",
")",
"common_params",
"=",
"{",
"'per_page'",
":",
"per_page",
",",
"'page'",
":",
"page",
"}",
"if",
"not",
"params",
":",
"params",
"=",
"common_params",
"else",
":",
"params",
".",
"update",
"(",
"common_params",
")",
"return",
"self",
".",
"_create_get_request",
"(",
"resource",
"=",
"resource",
",",
"params",
"=",
"params",
")"
]
| Gets specific data per resource page and per page | [
"Gets",
"specific",
"data",
"per",
"resource",
"page",
"and",
"per",
"page"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L179-L190 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.resolve_response_data | def resolve_response_data(head_key, data_key, data):
"""
Resolves the responses you get from billomat
If you have done a get_one_element request then you will get a dictionary
If you have done a get_all_elements request then you will get a list with all elements in it
:param head_key: the head key e.g: CLIENTS
:param data_key: the data key e.g: CLIENT
:param data: the responses you got
:return: dict or list
"""
new_data = []
if isinstance(data, list):
for data_row in data:
if head_key in data_row and data_key in data_row[head_key]:
if isinstance(data_row[head_key][data_key], list):
new_data += data_row[head_key][data_key]
else:
new_data.append(data_row[head_key][data_key])
elif data_key in data_row:
return data_row[data_key]
else:
if head_key in data and data_key in data[head_key]:
new_data += data[head_key][data_key]
elif data_key in data:
return data[data_key]
return new_data | python | def resolve_response_data(head_key, data_key, data):
"""
Resolves the responses you get from billomat
If you have done a get_one_element request then you will get a dictionary
If you have done a get_all_elements request then you will get a list with all elements in it
:param head_key: the head key e.g: CLIENTS
:param data_key: the data key e.g: CLIENT
:param data: the responses you got
:return: dict or list
"""
new_data = []
if isinstance(data, list):
for data_row in data:
if head_key in data_row and data_key in data_row[head_key]:
if isinstance(data_row[head_key][data_key], list):
new_data += data_row[head_key][data_key]
else:
new_data.append(data_row[head_key][data_key])
elif data_key in data_row:
return data_row[data_key]
else:
if head_key in data and data_key in data[head_key]:
new_data += data[head_key][data_key]
elif data_key in data:
return data[data_key]
return new_data | [
"def",
"resolve_response_data",
"(",
"head_key",
",",
"data_key",
",",
"data",
")",
":",
"new_data",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"for",
"data_row",
"in",
"data",
":",
"if",
"head_key",
"in",
"data_row",
"and",
"data_key",
"in",
"data_row",
"[",
"head_key",
"]",
":",
"if",
"isinstance",
"(",
"data_row",
"[",
"head_key",
"]",
"[",
"data_key",
"]",
",",
"list",
")",
":",
"new_data",
"+=",
"data_row",
"[",
"head_key",
"]",
"[",
"data_key",
"]",
"else",
":",
"new_data",
".",
"append",
"(",
"data_row",
"[",
"head_key",
"]",
"[",
"data_key",
"]",
")",
"elif",
"data_key",
"in",
"data_row",
":",
"return",
"data_row",
"[",
"data_key",
"]",
"else",
":",
"if",
"head_key",
"in",
"data",
"and",
"data_key",
"in",
"data",
"[",
"head_key",
"]",
":",
"new_data",
"+=",
"data",
"[",
"head_key",
"]",
"[",
"data_key",
"]",
"elif",
"data_key",
"in",
"data",
":",
"return",
"data",
"[",
"data_key",
"]",
"return",
"new_data"
]
| Resolves the responses you get from billomat
If you have done a get_one_element request then you will get a dictionary
If you have done a get_all_elements request then you will get a list with all elements in it
:param head_key: the head key e.g: CLIENTS
:param data_key: the data key e.g: CLIENT
:param data: the responses you got
:return: dict or list | [
"Resolves",
"the",
"responses",
"you",
"get",
"from",
"billomat",
"If",
"you",
"have",
"done",
"a",
"get_one_element",
"request",
"then",
"you",
"will",
"get",
"a",
"dictionary",
"If",
"you",
"have",
"done",
"a",
"get_all_elements",
"request",
"then",
"you",
"will",
"get",
"a",
"list",
"with",
"all",
"elements",
"in",
"it"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L193-L220 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_clients_per_page | def get_clients_per_page(self, per_page=1000, page=1, params=None):
"""
Get clients per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=CLIENTS, per_page=per_page, page=page, params=params) | python | def get_clients_per_page(self, per_page=1000, page=1, params=None):
"""
Get clients per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=CLIENTS, per_page=per_page, page=page, params=params) | [
"def",
"get_clients_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"CLIENTS",
",",
"per_page",
"=",
"per_page",
",",
"page",
"=",
"page",
",",
"params",
"=",
"params",
")"
]
| Get clients per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | [
"Get",
"clients",
"per",
"page"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L241-L250 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_all_clients | def get_all_clients(self, params=None):
"""
Get all clients
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
return self._iterate_through_pages(
get_function=self.get_clients_per_page,
resource=CLIENTS,
**{'params': params}
) | python | def get_all_clients(self, params=None):
"""
Get all clients
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
return self._iterate_through_pages(
get_function=self.get_clients_per_page,
resource=CLIENTS,
**{'params': params}
) | [
"def",
"get_all_clients",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"get_function",
"=",
"self",
".",
"get_clients_per_page",
",",
"resource",
"=",
"CLIENTS",
",",
"*",
"*",
"{",
"'params'",
":",
"params",
"}",
")"
]
| Get all clients
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list | [
"Get",
"all",
"clients",
"This",
"will",
"iterate",
"over",
"all",
"pages",
"until",
"it",
"gets",
"all",
"elements",
".",
"So",
"if",
"the",
"rate",
"limit",
"exceeded",
"it",
"will",
"throw",
"an",
"Exception",
"and",
"you",
"will",
"get",
"nothing"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L252-L265 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.update_client | def update_client(self, client_id, client_dict):
"""
Updates a client
:param client_id: the client id
:param client_dict: dict
:return: dict
"""
return self._create_put_request(
resource=CLIENTS,
billomat_id=client_id,
send_data=client_dict
) | python | def update_client(self, client_id, client_dict):
"""
Updates a client
:param client_id: the client id
:param client_dict: dict
:return: dict
"""
return self._create_put_request(
resource=CLIENTS,
billomat_id=client_id,
send_data=client_dict
) | [
"def",
"update_client",
"(",
"self",
",",
"client_id",
",",
"client_dict",
")",
":",
"return",
"self",
".",
"_create_put_request",
"(",
"resource",
"=",
"CLIENTS",
",",
"billomat_id",
"=",
"client_id",
",",
"send_data",
"=",
"client_dict",
")"
]
| Updates a client
:param client_id: the client id
:param client_dict: dict
:return: dict | [
"Updates",
"a",
"client"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L285-L297 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_client_properties_per_page | def get_client_properties_per_page(self, per_page=1000, page=1, params=None):
"""
Get client properties per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(
resource=CLIENT_PROPERTIES,
per_page=per_page,
page=page,
params=params
) | python | def get_client_properties_per_page(self, per_page=1000, page=1, params=None):
"""
Get client properties per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(
resource=CLIENT_PROPERTIES,
per_page=per_page,
page=page,
params=params
) | [
"def",
"get_client_properties_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"CLIENT_PROPERTIES",
",",
"per_page",
"=",
"per_page",
",",
"page",
"=",
"page",
",",
"params",
"=",
"params",
")"
]
| Get client properties per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | [
"Get",
"client",
"properties",
"per",
"page"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L315-L329 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_client_tags_per_page | def get_client_tags_per_page(self, per_page=1000, page=1, params=None):
"""
Get client tags per page
If you search tags, you can only search by client_id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(
resource=CLIENT_TAGS,
per_page=per_page,
page=page,
params=params
) | python | def get_client_tags_per_page(self, per_page=1000, page=1, params=None):
"""
Get client tags per page
If you search tags, you can only search by client_id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(
resource=CLIENT_TAGS,
per_page=per_page,
page=page,
params=params
) | [
"def",
"get_client_tags_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"CLIENT_TAGS",
",",
"per_page",
"=",
"per_page",
",",
"page",
"=",
"page",
",",
"params",
"=",
"params",
")"
]
| Get client tags per page
If you search tags, you can only search by client_id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | [
"Get",
"client",
"tags",
"per",
"page"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L371-L387 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_all_client_tags | def get_all_client_tags(self, params=None):
"""
Get all client tags
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
return self._iterate_through_pages(
get_function=self.get_client_tags_per_page,
resource=CLIENT_TAGS,
**{'params': params}
) | python | def get_all_client_tags(self, params=None):
"""
Get all client tags
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
return self._iterate_through_pages(
get_function=self.get_client_tags_per_page,
resource=CLIENT_TAGS,
**{'params': params}
) | [
"def",
"get_all_client_tags",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"get_function",
"=",
"self",
".",
"get_client_tags_per_page",
",",
"resource",
"=",
"CLIENT_TAGS",
",",
"*",
"*",
"{",
"'params'",
":",
"params",
"}",
")"
]
| Get all client tags
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list | [
"Get",
"all",
"client",
"tags",
"This",
"will",
"iterate",
"over",
"all",
"pages",
"until",
"it",
"gets",
"all",
"elements",
".",
"So",
"if",
"the",
"rate",
"limit",
"exceeded",
"it",
"will",
"throw",
"an",
"Exception",
"and",
"you",
"will",
"get",
"nothing"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L389-L402 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_contacts_of_client_per_page | def get_contacts_of_client_per_page(self, client_id, per_page=1000, page=1):
"""
Get contacts of client per page
:param client_id: the client id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
"""
return self._get_resource_per_page(
resource=CONTACTS,
per_page=per_page,
page=page,
params={'client_id': client_id},
) | python | def get_contacts_of_client_per_page(self, client_id, per_page=1000, page=1):
"""
Get contacts of client per page
:param client_id: the client id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
"""
return self._get_resource_per_page(
resource=CONTACTS,
per_page=per_page,
page=page,
params={'client_id': client_id},
) | [
"def",
"get_contacts_of_client_per_page",
"(",
"self",
",",
"client_id",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"CONTACTS",
",",
"per_page",
"=",
"per_page",
",",
"page",
"=",
"page",
",",
"params",
"=",
"{",
"'client_id'",
":",
"client_id",
"}",
",",
")"
]
| Get contacts of client per page
:param client_id: the client id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list | [
"Get",
"contacts",
"of",
"client",
"per",
"page"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L438-L452 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.update_contact_of_client | def update_contact_of_client(self, contact_id, contact_dict):
"""
Updates a contact
:param contact_id: the id of the contact
:param contact_dict: dict
:return: dict
"""
return self._create_put_request(resource=CONTACTS, billomat_id=contact_id, send_data=contact_dict) | python | def update_contact_of_client(self, contact_id, contact_dict):
"""
Updates a contact
:param contact_id: the id of the contact
:param contact_dict: dict
:return: dict
"""
return self._create_put_request(resource=CONTACTS, billomat_id=contact_id, send_data=contact_dict) | [
"def",
"update_contact_of_client",
"(",
"self",
",",
"contact_id",
",",
"contact_dict",
")",
":",
"return",
"self",
".",
"_create_put_request",
"(",
"resource",
"=",
"CONTACTS",
",",
"billomat_id",
"=",
"contact_id",
",",
"send_data",
"=",
"contact_dict",
")"
]
| Updates a contact
:param contact_id: the id of the contact
:param contact_dict: dict
:return: dict | [
"Updates",
"a",
"contact"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L487-L495 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_suppliers_per_page | def get_suppliers_per_page(self, per_page=1000, page=1, params=None):
"""
Get suppliers per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=SUPPLIERS, per_page=per_page, page=page, params=params) | python | def get_suppliers_per_page(self, per_page=1000, page=1, params=None):
"""
Get suppliers per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=SUPPLIERS, per_page=per_page, page=page, params=params) | [
"def",
"get_suppliers_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"SUPPLIERS",
",",
"per_page",
"=",
"per_page",
",",
"page",
"=",
"page",
",",
"params",
"=",
"params",
")"
]
| Get suppliers per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | [
"Get",
"suppliers",
"per",
"page"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L513-L522 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_all_suppliers | def get_all_suppliers(self, params=None):
"""
Get all suppliers
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
if not params:
params = {}
return self._iterate_through_pages(
get_function=self.get_suppliers_per_page,
resource=SUPPLIERS,
**{'params': params}
) | python | def get_all_suppliers(self, params=None):
"""
Get all suppliers
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
if not params:
params = {}
return self._iterate_through_pages(
get_function=self.get_suppliers_per_page,
resource=SUPPLIERS,
**{'params': params}
) | [
"def",
"get_all_suppliers",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"get_function",
"=",
"self",
".",
"get_suppliers_per_page",
",",
"resource",
"=",
"SUPPLIERS",
",",
"*",
"*",
"{",
"'params'",
":",
"params",
"}",
")"
]
| Get all suppliers
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list | [
"Get",
"all",
"suppliers",
"This",
"will",
"iterate",
"over",
"all",
"pages",
"until",
"it",
"gets",
"all",
"elements",
".",
"So",
"if",
"the",
"rate",
"limit",
"exceeded",
"it",
"will",
"throw",
"an",
"Exception",
"and",
"you",
"will",
"get",
"nothing"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L524-L539 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.update_supplier | def update_supplier(self, supplier_id, supplier_dict):
"""
Updates a supplier
:param supplier_id: the supplier id
:param supplier_dict: dict
:return: dict
"""
return self._create_put_request(resource=SUPPLIERS, billomat_id=supplier_id, send_data=supplier_dict) | python | def update_supplier(self, supplier_id, supplier_dict):
"""
Updates a supplier
:param supplier_id: the supplier id
:param supplier_dict: dict
:return: dict
"""
return self._create_put_request(resource=SUPPLIERS, billomat_id=supplier_id, send_data=supplier_dict) | [
"def",
"update_supplier",
"(",
"self",
",",
"supplier_id",
",",
"supplier_dict",
")",
":",
"return",
"self",
".",
"_create_put_request",
"(",
"resource",
"=",
"SUPPLIERS",
",",
"billomat_id",
"=",
"supplier_id",
",",
"send_data",
"=",
"supplier_dict",
")"
]
| Updates a supplier
:param supplier_id: the supplier id
:param supplier_dict: dict
:return: dict | [
"Updates",
"a",
"supplier"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L559-L567 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_supplier_properties_per_page | def get_supplier_properties_per_page(self, per_page=1000, page=1, params=None):
"""
Get supplier properties per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=SUPPLIER_PROPERTIES, per_page=per_page, page=page, params=params) | python | def get_supplier_properties_per_page(self, per_page=1000, page=1, params=None):
"""
Get supplier properties per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=SUPPLIER_PROPERTIES, per_page=per_page, page=page, params=params) | [
"def",
"get_supplier_properties_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"SUPPLIER_PROPERTIES",
",",
"per_page",
"=",
"per_page",
",",
"page",
"=",
"page",
",",
"params",
"=",
"params",
")"
]
| Get supplier properties per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | [
"Get",
"supplier",
"properties",
"per",
"page"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L585-L594 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_tags_of_supplier_per_page | def get_tags_of_supplier_per_page(self, supplier_id, per_page=1000, page=1):
"""
Get tags of suppliers per page
:param supplier_id: the supplier id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
"""
return self._get_resource_per_page(
resource=SUPPLIER_TAGS,
per_page=per_page,
page=page,
params={'supplier_id': supplier_id},
) | python | def get_tags_of_supplier_per_page(self, supplier_id, per_page=1000, page=1):
"""
Get tags of suppliers per page
:param supplier_id: the supplier id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
"""
return self._get_resource_per_page(
resource=SUPPLIER_TAGS,
per_page=per_page,
page=page,
params={'supplier_id': supplier_id},
) | [
"def",
"get_tags_of_supplier_per_page",
"(",
"self",
",",
"supplier_id",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"SUPPLIER_TAGS",
",",
"per_page",
"=",
"per_page",
",",
"page",
"=",
"page",
",",
"params",
"=",
"{",
"'supplier_id'",
":",
"supplier_id",
"}",
",",
")"
]
| Get tags of suppliers per page
:param supplier_id: the supplier id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list | [
"Get",
"tags",
"of",
"suppliers",
"per",
"page"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L637-L651 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_articles_per_page | def get_articles_per_page(self, per_page=1000, page=1, params=None):
"""
Get articles per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=ARTICLES, per_page=per_page, page=page, params=params) | python | def get_articles_per_page(self, per_page=1000, page=1, params=None):
"""
Get articles per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=ARTICLES, per_page=per_page, page=page, params=params) | [
"def",
"get_articles_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"ARTICLES",
",",
"per_page",
"=",
"per_page",
",",
"page",
"=",
"page",
",",
"params",
"=",
"params",
")"
]
| Get articles per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | [
"Get",
"articles",
"per",
"page"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L701-L710 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_all_articles | def get_all_articles(self, params=None):
"""
Get all articles
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
if not params:
params = {}
return self._iterate_through_pages(self.get_articles_per_page, resource=ARTICLES, **{'params': params}) | python | def get_all_articles(self, params=None):
"""
Get all articles
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
if not params:
params = {}
return self._iterate_through_pages(self.get_articles_per_page, resource=ARTICLES, **{'params': params}) | [
"def",
"get_all_articles",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"self",
".",
"get_articles_per_page",
",",
"resource",
"=",
"ARTICLES",
",",
"*",
"*",
"{",
"'params'",
":",
"params",
"}",
")"
]
| Get all articles
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list | [
"Get",
"all",
"articles",
"This",
"will",
"iterate",
"over",
"all",
"pages",
"until",
"it",
"gets",
"all",
"elements",
".",
"So",
"if",
"the",
"rate",
"limit",
"exceeded",
"it",
"will",
"throw",
"an",
"Exception",
"and",
"you",
"will",
"get",
"nothing"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L712-L723 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.update_article | def update_article(self, article_id, article_dict):
"""
Updates an article
:param article_id: the article id
:param article_dict: dict
:return: dict
"""
return self._create_put_request(resource=ARTICLES, billomat_id=article_id, send_data=article_dict) | python | def update_article(self, article_id, article_dict):
"""
Updates an article
:param article_id: the article id
:param article_dict: dict
:return: dict
"""
return self._create_put_request(resource=ARTICLES, billomat_id=article_id, send_data=article_dict) | [
"def",
"update_article",
"(",
"self",
",",
"article_id",
",",
"article_dict",
")",
":",
"return",
"self",
".",
"_create_put_request",
"(",
"resource",
"=",
"ARTICLES",
",",
"billomat_id",
"=",
"article_id",
",",
"send_data",
"=",
"article_dict",
")"
]
| Updates an article
:param article_id: the article id
:param article_dict: dict
:return: dict | [
"Updates",
"an",
"article"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L743-L751 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_article_properties_per_page | def get_article_properties_per_page(self, per_page=1000, page=1, params=None):
"""
Get article properties per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=ARTICLE_PROPERTIES, per_page=per_page, page=page, params=params) | python | def get_article_properties_per_page(self, per_page=1000, page=1, params=None):
"""
Get article properties per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=ARTICLE_PROPERTIES, per_page=per_page, page=page, params=params) | [
"def",
"get_article_properties_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"ARTICLE_PROPERTIES",
",",
"per_page",
"=",
"per_page",
",",
"page",
"=",
"page",
",",
"params",
"=",
"params",
")"
]
| Get article properties per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | [
"Get",
"article",
"properties",
"per",
"page"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L769-L778 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_all_article_properties | def get_all_article_properties(self, params=None):
"""
Get all article properties
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
if not params:
params = {}
return self._iterate_through_pages(
get_function=self.get_article_properties_per_page,
resource=ARTICLE_PROPERTIES,
**{'params': params}
) | python | def get_all_article_properties(self, params=None):
"""
Get all article properties
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
if not params:
params = {}
return self._iterate_through_pages(
get_function=self.get_article_properties_per_page,
resource=ARTICLE_PROPERTIES,
**{'params': params}
) | [
"def",
"get_all_article_properties",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"get_function",
"=",
"self",
".",
"get_article_properties_per_page",
",",
"resource",
"=",
"ARTICLE_PROPERTIES",
",",
"*",
"*",
"{",
"'params'",
":",
"params",
"}",
")"
]
| Get all article properties
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list | [
"Get",
"all",
"article",
"properties",
"This",
"will",
"iterate",
"over",
"all",
"pages",
"until",
"it",
"gets",
"all",
"elements",
".",
"So",
"if",
"the",
"rate",
"limit",
"exceeded",
"it",
"will",
"throw",
"an",
"Exception",
"and",
"you",
"will",
"get",
"nothing"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L780-L795 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_tags_of_article_per_page | def get_tags_of_article_per_page(self, article_id, per_page=1000, page=1):
"""
Get articles tags per page
:param article_id: the article id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
"""
return self._get_resource_per_page(
resource=ARTICLE_TAGS,
per_page=per_page,
page=page,
params={'article_id': article_id},
) | python | def get_tags_of_article_per_page(self, article_id, per_page=1000, page=1):
"""
Get articles tags per page
:param article_id: the article id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
"""
return self._get_resource_per_page(
resource=ARTICLE_TAGS,
per_page=per_page,
page=page,
params={'article_id': article_id},
) | [
"def",
"get_tags_of_article_per_page",
"(",
"self",
",",
"article_id",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"ARTICLE_TAGS",
",",
"per_page",
"=",
"per_page",
",",
"page",
"=",
"page",
",",
"params",
"=",
"{",
"'article_id'",
":",
"article_id",
"}",
",",
")"
]
| Get articles tags per page
:param article_id: the article id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list | [
"Get",
"articles",
"tags",
"per",
"page"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L821-L835 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_all_tags_of_article | def get_all_tags_of_article(self, article_id):
"""
Get all tags of article
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param article_id: the article id
:return: list
"""
return self._iterate_through_pages(
get_function=self.get_tags_of_article_per_page,
resource=ARTICLE_TAGS,
**{'article_id': article_id}
) | python | def get_all_tags_of_article(self, article_id):
"""
Get all tags of article
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param article_id: the article id
:return: list
"""
return self._iterate_through_pages(
get_function=self.get_tags_of_article_per_page,
resource=ARTICLE_TAGS,
**{'article_id': article_id}
) | [
"def",
"get_all_tags_of_article",
"(",
"self",
",",
"article_id",
")",
":",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"get_function",
"=",
"self",
".",
"get_tags_of_article_per_page",
",",
"resource",
"=",
"ARTICLE_TAGS",
",",
"*",
"*",
"{",
"'article_id'",
":",
"article_id",
"}",
")"
]
| Get all tags of article
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param article_id: the article id
:return: list | [
"Get",
"all",
"tags",
"of",
"article",
"This",
"will",
"iterate",
"over",
"all",
"pages",
"until",
"it",
"gets",
"all",
"elements",
".",
"So",
"if",
"the",
"rate",
"limit",
"exceeded",
"it",
"will",
"throw",
"an",
"Exception",
"and",
"you",
"will",
"get",
"nothing"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L837-L850 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_units_per_page | def get_units_per_page(self, per_page=1000, page=1, params=None):
"""
Get units per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=UNITS, per_page=per_page, page=page, params=params) | python | def get_units_per_page(self, per_page=1000, page=1, params=None):
"""
Get units per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=UNITS, per_page=per_page, page=page, params=params) | [
"def",
"get_units_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"UNITS",
",",
"per_page",
"=",
"per_page",
",",
"page",
"=",
"page",
",",
"params",
"=",
"params",
")"
]
| Get units per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | [
"Get",
"units",
"per",
"page"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L886-L895 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_all_units | def get_all_units(self, params=None):
"""
Get all units
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
if not params:
params = {}
return self._iterate_through_pages(self.get_units_per_page, resource=UNITS, **{'params': params}) | python | def get_all_units(self, params=None):
"""
Get all units
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
if not params:
params = {}
return self._iterate_through_pages(self.get_units_per_page, resource=UNITS, **{'params': params}) | [
"def",
"get_all_units",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"self",
".",
"get_units_per_page",
",",
"resource",
"=",
"UNITS",
",",
"*",
"*",
"{",
"'params'",
":",
"params",
"}",
")"
]
| Get all units
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list | [
"Get",
"all",
"units",
"This",
"will",
"iterate",
"over",
"all",
"pages",
"until",
"it",
"gets",
"all",
"elements",
".",
"So",
"if",
"the",
"rate",
"limit",
"exceeded",
"it",
"will",
"throw",
"an",
"Exception",
"and",
"you",
"will",
"get",
"nothing"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L897-L908 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.update_unit | def update_unit(self, unit_id, unit_dict):
"""
Updates an unit
:param unit_id: the unit id
:param unit_dict: dict
:return: dict
"""
return self._create_put_request(resource=UNITS, billomat_id=unit_id, send_data=unit_dict) | python | def update_unit(self, unit_id, unit_dict):
"""
Updates an unit
:param unit_id: the unit id
:param unit_dict: dict
:return: dict
"""
return self._create_put_request(resource=UNITS, billomat_id=unit_id, send_data=unit_dict) | [
"def",
"update_unit",
"(",
"self",
",",
"unit_id",
",",
"unit_dict",
")",
":",
"return",
"self",
".",
"_create_put_request",
"(",
"resource",
"=",
"UNITS",
",",
"billomat_id",
"=",
"unit_id",
",",
"send_data",
"=",
"unit_dict",
")"
]
| Updates an unit
:param unit_id: the unit id
:param unit_dict: dict
:return: dict | [
"Updates",
"an",
"unit"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L928-L936 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_invoices_per_page | def get_invoices_per_page(self, per_page=1000, page=1, params=None):
"""
Get invoices per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=INVOICES, per_page=per_page, page=page, params=params) | python | def get_invoices_per_page(self, per_page=1000, page=1, params=None):
"""
Get invoices per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list
"""
return self._get_resource_per_page(resource=INVOICES, per_page=per_page, page=page, params=params) | [
"def",
"get_invoices_per_page",
"(",
"self",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"INVOICES",
",",
"per_page",
"=",
"per_page",
",",
"page",
"=",
"page",
",",
"params",
"=",
"params",
")"
]
| Get invoices per page
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:param params: Search parameters. Default: {}
:return: list | [
"Get",
"invoices",
"per",
"page"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L954-L963 | train |
bykof/billomapy | billomapy/billomapy.py | Billomapy.get_all_invoices | def get_all_invoices(self, params=None):
"""
Get all invoices
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
if not params:
params = {}
return self._iterate_through_pages(self.get_invoices_per_page, resource=INVOICES, **{'params': params}) | python | def get_all_invoices(self, params=None):
"""
Get all invoices
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
if not params:
params = {}
return self._iterate_through_pages(self.get_invoices_per_page, resource=INVOICES, **{'params': params}) | [
"def",
"get_all_invoices",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"{",
"}",
"return",
"self",
".",
"_iterate_through_pages",
"(",
"self",
".",
"get_invoices_per_page",
",",
"resource",
"=",
"INVOICES",
",",
"*",
"*",
"{",
"'params'",
":",
"params",
"}",
")"
]
| Get all invoices
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list | [
"Get",
"all",
"invoices",
"This",
"will",
"iterate",
"over",
"all",
"pages",
"until",
"it",
"gets",
"all",
"elements",
".",
"So",
"if",
"the",
"rate",
"limit",
"exceeded",
"it",
"will",
"throw",
"an",
"Exception",
"and",
"you",
"will",
"get",
"nothing"
]
| a28ba69fd37654fa145d0411d52c200e7f8984ab | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L965-L976 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.