repo stringclasses 85
values | path stringlengths 8 121 | func_name stringlengths 1 82 | original_string stringlengths 112 65.5k | language stringclasses 1
value | code stringlengths 112 65.5k | code_tokens listlengths 20 4.09k | docstring stringlengths 3 46.3k | docstring_tokens listlengths 1 564 | sha stringclasses 85
values | url stringlengths 93 218 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler.xmlrpc_run | def xmlrpc_run(self, port=23333, bind='127.0.0.1', logRequests=False):
'''Start xmlrpc interface'''
from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication
application = WSGIXMLRPCApplication()
application.register_function(self.quit, '_quit')
application.register_function(... | python | def xmlrpc_run(self, port=23333, bind='127.0.0.1', logRequests=False):
'''Start xmlrpc interface'''
from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication
application = WSGIXMLRPCApplication()
application.register_function(self.quit, '_quit')
application.register_function(... | [
"def",
"xmlrpc_run",
"(",
"self",
",",
"port",
"=",
"23333",
",",
"bind",
"=",
"'127.0.0.1'",
",",
"logRequests",
"=",
"False",
")",
":",
"from",
"pyspider",
".",
"libs",
".",
"wsgi_xmlrpc",
"import",
"WSGIXMLRPCApplication",
"application",
"=",
"WSGIXMLRPCApp... | Start xmlrpc interface | [
"Start",
"xmlrpc",
"interface"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L705-L811 | train |
binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler.on_new_request | def on_new_request(self, task):
'''Called when a new request is arrived'''
task['status'] = self.taskdb.ACTIVE
self.insert_task(task)
self.put_task(task)
project = task['project']
self._cnt['5m'].event((project, 'pending'), +1)
self._cnt['1h'].event((project, 'pe... | python | def on_new_request(self, task):
'''Called when a new request is arrived'''
task['status'] = self.taskdb.ACTIVE
self.insert_task(task)
self.put_task(task)
project = task['project']
self._cnt['5m'].event((project, 'pending'), +1)
self._cnt['1h'].event((project, 'pe... | [
"def",
"on_new_request",
"(",
"self",
",",
"task",
")",
":",
"task",
"[",
"'status'",
"]",
"=",
"self",
".",
"taskdb",
".",
"ACTIVE",
"self",
".",
"insert_task",
"(",
"task",
")",
"self",
".",
"put_task",
"(",
"task",
")",
"project",
"=",
"task",
"["... | Called when a new request is arrived | [
"Called",
"when",
"a",
"new",
"request",
"is",
"arrived"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L825-L837 | train |
binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler.on_old_request | def on_old_request(self, task, old_task):
'''Called when a crawled task is arrived'''
now = time.time()
_schedule = task.get('schedule', self.default_schedule)
old_schedule = old_task.get('schedule', {})
if _schedule.get('force_update') and self.projects[task['project']].task_q... | python | def on_old_request(self, task, old_task):
'''Called when a crawled task is arrived'''
now = time.time()
_schedule = task.get('schedule', self.default_schedule)
old_schedule = old_task.get('schedule', {})
if _schedule.get('force_update') and self.projects[task['project']].task_q... | [
"def",
"on_old_request",
"(",
"self",
",",
"task",
",",
"old_task",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"_schedule",
"=",
"task",
".",
"get",
"(",
"'schedule'",
",",
"self",
".",
"default_schedule",
")",
"old_schedule",
"=",
"old_task",
... | Called when a crawled task is arrived | [
"Called",
"when",
"a",
"crawled",
"task",
"is",
"arrived"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L839-L887 | train |
binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler.on_task_status | def on_task_status(self, task):
'''Called when a status pack is arrived'''
try:
procesok = task['track']['process']['ok']
if not self.projects[task['project']].task_queue.done(task['taskid']):
logging.error('not processing pack: %(project)s:%(taskid)s %(url)s', ta... | python | def on_task_status(self, task):
'''Called when a status pack is arrived'''
try:
procesok = task['track']['process']['ok']
if not self.projects[task['project']].task_queue.done(task['taskid']):
logging.error('not processing pack: %(project)s:%(taskid)s %(url)s', ta... | [
"def",
"on_task_status",
"(",
"self",
",",
"task",
")",
":",
"try",
":",
"procesok",
"=",
"task",
"[",
"'track'",
"]",
"[",
"'process'",
"]",
"[",
"'ok'",
"]",
"if",
"not",
"self",
".",
"projects",
"[",
"task",
"[",
"'project'",
"]",
"]",
".",
"tas... | Called when a status pack is arrived | [
"Called",
"when",
"a",
"status",
"pack",
"is",
"arrived"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L889-L912 | train |
binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler.on_task_done | def on_task_done(self, task):
'''Called when a task is done and success, called by `on_task_status`'''
task['status'] = self.taskdb.SUCCESS
task['lastcrawltime'] = time.time()
if 'schedule' in task:
if task['schedule'].get('auto_recrawl') and 'age' in task['schedule']:
... | python | def on_task_done(self, task):
'''Called when a task is done and success, called by `on_task_status`'''
task['status'] = self.taskdb.SUCCESS
task['lastcrawltime'] = time.time()
if 'schedule' in task:
if task['schedule'].get('auto_recrawl') and 'age' in task['schedule']:
... | [
"def",
"on_task_done",
"(",
"self",
",",
"task",
")",
":",
"task",
"[",
"'status'",
"]",
"=",
"self",
".",
"taskdb",
".",
"SUCCESS",
"task",
"[",
"'lastcrawltime'",
"]",
"=",
"time",
".",
"time",
"(",
")",
"if",
"'schedule'",
"in",
"task",
":",
"if",... | Called when a task is done and success, called by `on_task_status` | [
"Called",
"when",
"a",
"task",
"is",
"done",
"and",
"success",
"called",
"by",
"on_task_status"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L914-L935 | train |
binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler.on_task_failed | def on_task_failed(self, task):
'''Called when a task is failed, called by `on_task_status`'''
if 'schedule' not in task:
old_task = self.taskdb.get_task(task['project'], task['taskid'], fields=['schedule'])
if old_task is None:
logging.error('unknown status pack... | python | def on_task_failed(self, task):
'''Called when a task is failed, called by `on_task_status`'''
if 'schedule' not in task:
old_task = self.taskdb.get_task(task['project'], task['taskid'], fields=['schedule'])
if old_task is None:
logging.error('unknown status pack... | [
"def",
"on_task_failed",
"(",
"self",
",",
"task",
")",
":",
"if",
"'schedule'",
"not",
"in",
"task",
":",
"old_task",
"=",
"self",
".",
"taskdb",
".",
"get_task",
"(",
"task",
"[",
"'project'",
"]",
",",
"task",
"[",
"'taskid'",
"]",
",",
"fields",
... | Called when a task is failed, called by `on_task_status` | [
"Called",
"when",
"a",
"task",
"is",
"failed",
"called",
"by",
"on_task_status"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L937-L988 | train |
binux/pyspider | pyspider/scheduler/scheduler.py | Scheduler.on_select_task | def on_select_task(self, task):
'''Called when a task is selected to fetch & process'''
# inject informations about project
logger.info('select %(project)s:%(taskid)s %(url)s', task)
project_info = self.projects.get(task['project'])
assert project_info, 'no such project'
... | python | def on_select_task(self, task):
'''Called when a task is selected to fetch & process'''
# inject informations about project
logger.info('select %(project)s:%(taskid)s %(url)s', task)
project_info = self.projects.get(task['project'])
assert project_info, 'no such project'
... | [
"def",
"on_select_task",
"(",
"self",
",",
"task",
")",
":",
"# inject informations about project",
"logger",
".",
"info",
"(",
"'select %(project)s:%(taskid)s %(url)s'",
",",
"task",
")",
"project_info",
"=",
"self",
".",
"projects",
".",
"get",
"(",
"task",
"[",... | Called when a task is selected to fetch & process | [
"Called",
"when",
"a",
"task",
"is",
"selected",
"to",
"fetch",
"&",
"process"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L990-L1008 | train |
binux/pyspider | pyspider/scheduler/scheduler.py | OneScheduler._check_select | def _check_select(self):
"""
interactive mode of select tasks
"""
if not self.interactive:
return super(OneScheduler, self)._check_select()
# waiting for running tasks
if self.running_task > 0:
return
is_crawled = []
def run(proj... | python | def _check_select(self):
"""
interactive mode of select tasks
"""
if not self.interactive:
return super(OneScheduler, self)._check_select()
# waiting for running tasks
if self.running_task > 0:
return
is_crawled = []
def run(proj... | [
"def",
"_check_select",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"interactive",
":",
"return",
"super",
"(",
"OneScheduler",
",",
"self",
")",
".",
"_check_select",
"(",
")",
"# waiting for running tasks",
"if",
"self",
".",
"running_task",
">",
"0",... | interactive mode of select tasks | [
"interactive",
"mode",
"of",
"select",
"tasks"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L1022-L1104 | train |
binux/pyspider | pyspider/scheduler/scheduler.py | OneScheduler.on_task_status | def on_task_status(self, task):
"""Ignore not processing error in interactive mode"""
if not self.interactive:
super(OneScheduler, self).on_task_status(task)
try:
procesok = task['track']['process']['ok']
except KeyError as e:
logger.error("Bad status... | python | def on_task_status(self, task):
"""Ignore not processing error in interactive mode"""
if not self.interactive:
super(OneScheduler, self).on_task_status(task)
try:
procesok = task['track']['process']['ok']
except KeyError as e:
logger.error("Bad status... | [
"def",
"on_task_status",
"(",
"self",
",",
"task",
")",
":",
"if",
"not",
"self",
".",
"interactive",
":",
"super",
"(",
"OneScheduler",
",",
"self",
")",
".",
"on_task_status",
"(",
"task",
")",
"try",
":",
"procesok",
"=",
"task",
"[",
"'track'",
"]"... | Ignore not processing error in interactive mode | [
"Ignore",
"not",
"processing",
"error",
"in",
"interactive",
"mode"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/scheduler.py#L1112-L1134 | train |
binux/pyspider | pyspider/processor/project_module.py | ProjectManager.build_module | def build_module(project, env=None):
'''Build project script as module'''
from pyspider.libs import base_handler
assert 'name' in project, 'need name of project'
assert 'script' in project, 'need script of project'
if env is None:
env = {}
# fix for old non-p... | python | def build_module(project, env=None):
'''Build project script as module'''
from pyspider.libs import base_handler
assert 'name' in project, 'need name of project'
assert 'script' in project, 'need script of project'
if env is None:
env = {}
# fix for old non-p... | [
"def",
"build_module",
"(",
"project",
",",
"env",
"=",
"None",
")",
":",
"from",
"pyspider",
".",
"libs",
"import",
"base_handler",
"assert",
"'name'",
"in",
"project",
",",
"'need name of project'",
"assert",
"'script'",
"in",
"project",
",",
"'need script of ... | Build project script as module | [
"Build",
"project",
"script",
"as",
"module"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L32-L87 | train |
binux/pyspider | pyspider/processor/project_module.py | ProjectManager._need_update | def _need_update(self, project_name, updatetime=None, md5sum=None):
'''Check if project_name need update'''
if project_name not in self.projects:
return True
elif md5sum and md5sum != self.projects[project_name]['info'].get('md5sum'):
return True
elif updatetime a... | python | def _need_update(self, project_name, updatetime=None, md5sum=None):
'''Check if project_name need update'''
if project_name not in self.projects:
return True
elif md5sum and md5sum != self.projects[project_name]['info'].get('md5sum'):
return True
elif updatetime a... | [
"def",
"_need_update",
"(",
"self",
",",
"project_name",
",",
"updatetime",
"=",
"None",
",",
"md5sum",
"=",
"None",
")",
":",
"if",
"project_name",
"not",
"in",
"self",
".",
"projects",
":",
"return",
"True",
"elif",
"md5sum",
"and",
"md5sum",
"!=",
"se... | Check if project_name need update | [
"Check",
"if",
"project_name",
"need",
"update"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L96-L106 | train |
binux/pyspider | pyspider/processor/project_module.py | ProjectManager._check_projects | def _check_projects(self):
'''Check projects by last update time'''
for project in self.projectdb.check_update(self.last_check_projects,
['name', 'updatetime']):
if project['name'] not in self.projects:
continue
i... | python | def _check_projects(self):
'''Check projects by last update time'''
for project in self.projectdb.check_update(self.last_check_projects,
['name', 'updatetime']):
if project['name'] not in self.projects:
continue
i... | [
"def",
"_check_projects",
"(",
"self",
")",
":",
"for",
"project",
"in",
"self",
".",
"projectdb",
".",
"check_update",
"(",
"self",
".",
"last_check_projects",
",",
"[",
"'name'",
",",
"'updatetime'",
"]",
")",
":",
"if",
"project",
"[",
"'name'",
"]",
... | Check projects by last update time | [
"Check",
"projects",
"by",
"last",
"update",
"time"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L108-L116 | train |
binux/pyspider | pyspider/processor/project_module.py | ProjectManager._update_project | def _update_project(self, project_name):
'''Update one project from database'''
project = self.projectdb.get(project_name)
if not project:
return None
return self._load_project(project) | python | def _update_project(self, project_name):
'''Update one project from database'''
project = self.projectdb.get(project_name)
if not project:
return None
return self._load_project(project) | [
"def",
"_update_project",
"(",
"self",
",",
"project_name",
")",
":",
"project",
"=",
"self",
".",
"projectdb",
".",
"get",
"(",
"project_name",
")",
"if",
"not",
"project",
":",
"return",
"None",
"return",
"self",
".",
"_load_project",
"(",
"project",
")"... | Update one project from database | [
"Update",
"one",
"project",
"from",
"database"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L118-L123 | train |
binux/pyspider | pyspider/processor/project_module.py | ProjectManager._load_project | def _load_project(self, project):
'''Load project into self.projects from project info dict'''
try:
project['md5sum'] = utils.md5string(project['script'])
ret = self.build_module(project, self.env)
self.projects[project['name']] = ret
except Exception as e:
... | python | def _load_project(self, project):
'''Load project into self.projects from project info dict'''
try:
project['md5sum'] = utils.md5string(project['script'])
ret = self.build_module(project, self.env)
self.projects[project['name']] = ret
except Exception as e:
... | [
"def",
"_load_project",
"(",
"self",
",",
"project",
")",
":",
"try",
":",
"project",
"[",
"'md5sum'",
"]",
"=",
"utils",
".",
"md5string",
"(",
"project",
"[",
"'script'",
"]",
")",
"ret",
"=",
"self",
".",
"build_module",
"(",
"project",
",",
"self",... | Load project into self.projects from project info dict | [
"Load",
"project",
"into",
"self",
".",
"projects",
"from",
"project",
"info",
"dict"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L125-L146 | train |
binux/pyspider | pyspider/processor/project_module.py | ProjectManager.get | def get(self, project_name, updatetime=None, md5sum=None):
'''get project data object, return None if not exists'''
if time.time() - self.last_check_projects > self.CHECK_PROJECTS_INTERVAL:
self._check_projects()
if self._need_update(project_name, updatetime, md5sum):
sel... | python | def get(self, project_name, updatetime=None, md5sum=None):
'''get project data object, return None if not exists'''
if time.time() - self.last_check_projects > self.CHECK_PROJECTS_INTERVAL:
self._check_projects()
if self._need_update(project_name, updatetime, md5sum):
sel... | [
"def",
"get",
"(",
"self",
",",
"project_name",
",",
"updatetime",
"=",
"None",
",",
"md5sum",
"=",
"None",
")",
":",
"if",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"last_check_projects",
">",
"self",
".",
"CHECK_PROJECTS_INTERVAL",
":",
"self",
... | get project data object, return None if not exists | [
"get",
"project",
"data",
"object",
"return",
"None",
"if",
"not",
"exists"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/processor/project_module.py#L148-L154 | train |
binux/pyspider | pyspider/fetcher/cookie_utils.py | MockResponse.get_all | def get_all(self, name, default=None):
"""make cookie python 3 version use this instead of getheaders"""
if default is None:
default = []
return self._headers.get_list(name) or default | python | def get_all(self, name, default=None):
"""make cookie python 3 version use this instead of getheaders"""
if default is None:
default = []
return self._headers.get_list(name) or default | [
"def",
"get_all",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"None",
":",
"default",
"=",
"[",
"]",
"return",
"self",
".",
"_headers",
".",
"get_list",
"(",
"name",
")",
"or",
"default"
] | make cookie python 3 version use this instead of getheaders | [
"make",
"cookie",
"python",
"3",
"version",
"use",
"this",
"instead",
"of",
"getheaders"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/cookie_utils.py#L23-L27 | train |
binux/pyspider | pyspider/database/redis/taskdb.py | TaskDB.status_count | def status_count(self, project):
'''
return a dict
'''
pipe = self.redis.pipeline(transaction=False)
for status in range(1, 5):
pipe.scard(self._gen_status_key(project, status))
ret = pipe.execute()
result = {}
for status, count in enumerate(r... | python | def status_count(self, project):
'''
return a dict
'''
pipe = self.redis.pipeline(transaction=False)
for status in range(1, 5):
pipe.scard(self._gen_status_key(project, status))
ret = pipe.execute()
result = {}
for status, count in enumerate(r... | [
"def",
"status_count",
"(",
"self",
",",
"project",
")",
":",
"pipe",
"=",
"self",
".",
"redis",
".",
"pipeline",
"(",
"transaction",
"=",
"False",
")",
"for",
"status",
"in",
"range",
"(",
"1",
",",
"5",
")",
":",
"pipe",
".",
"scard",
"(",
"self"... | return a dict | [
"return",
"a",
"dict"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/database/redis/taskdb.py#L118-L131 | train |
binux/pyspider | pyspider/libs/multiprocessing_queue.py | SharedCounter.increment | def increment(self, n=1):
""" Increment the counter by n (default = 1) """
with self.count.get_lock():
self.count.value += n | python | def increment(self, n=1):
""" Increment the counter by n (default = 1) """
with self.count.get_lock():
self.count.value += n | [
"def",
"increment",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"with",
"self",
".",
"count",
".",
"get_lock",
"(",
")",
":",
"self",
".",
"count",
".",
"value",
"+=",
"n"
] | Increment the counter by n (default = 1) | [
"Increment",
"the",
"counter",
"by",
"n",
"(",
"default",
"=",
"1",
")"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/multiprocessing_queue.py#L25-L28 | train |
binux/pyspider | pyspider/database/elasticsearch/taskdb.py | TaskDB.refresh | def refresh(self):
"""
Explicitly refresh one or more index, making all operations
performed since the last refresh available for search.
"""
self._changed = False
self.es.indices.refresh(index=self.index) | python | def refresh(self):
"""
Explicitly refresh one or more index, making all operations
performed since the last refresh available for search.
"""
self._changed = False
self.es.indices.refresh(index=self.index) | [
"def",
"refresh",
"(",
"self",
")",
":",
"self",
".",
"_changed",
"=",
"False",
"self",
".",
"es",
".",
"indices",
".",
"refresh",
"(",
"index",
"=",
"self",
".",
"index",
")"
] | Explicitly refresh one or more index, making all operations
performed since the last refresh available for search. | [
"Explicitly",
"refresh",
"one",
"or",
"more",
"index",
"making",
"all",
"operations",
"performed",
"since",
"the",
"last",
"refresh",
"available",
"for",
"search",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/database/elasticsearch/taskdb.py#L119-L125 | train |
binux/pyspider | pyspider/fetcher/tornado_fetcher.py | Fetcher.send_result | def send_result(self, type, task, result):
'''Send fetch result to processor'''
if self.outqueue:
try:
self.outqueue.put((task, result))
except Exception as e:
logger.exception(e) | python | def send_result(self, type, task, result):
'''Send fetch result to processor'''
if self.outqueue:
try:
self.outqueue.put((task, result))
except Exception as e:
logger.exception(e) | [
"def",
"send_result",
"(",
"self",
",",
"type",
",",
"task",
",",
"result",
")",
":",
"if",
"self",
".",
"outqueue",
":",
"try",
":",
"self",
".",
"outqueue",
".",
"put",
"(",
"(",
"task",
",",
"result",
")",
")",
"except",
"Exception",
"as",
"e",
... | Send fetch result to processor | [
"Send",
"fetch",
"result",
"to",
"processor"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L108-L114 | train |
binux/pyspider | pyspider/fetcher/tornado_fetcher.py | Fetcher.async_fetch | def async_fetch(self, task, callback=None):
'''Do one fetch'''
url = task.get('url', 'data:,')
if callback is None:
callback = self.send_result
type = 'None'
start_time = time.time()
try:
if url.startswith('data:'):
type = 'data'
... | python | def async_fetch(self, task, callback=None):
'''Do one fetch'''
url = task.get('url', 'data:,')
if callback is None:
callback = self.send_result
type = 'None'
start_time = time.time()
try:
if url.startswith('data:'):
type = 'data'
... | [
"def",
"async_fetch",
"(",
"self",
",",
"task",
",",
"callback",
"=",
"None",
")",
":",
"url",
"=",
"task",
".",
"get",
"(",
"'url'",
",",
"'data:,'",
")",
"if",
"callback",
"is",
"None",
":",
"callback",
"=",
"self",
".",
"send_result",
"type",
"=",... | Do one fetch | [
"Do",
"one",
"fetch"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L123-L153 | train |
binux/pyspider | pyspider/fetcher/tornado_fetcher.py | Fetcher.sync_fetch | def sync_fetch(self, task):
'''Synchronization fetch, usually used in xmlrpc thread'''
if not self._running:
return self.ioloop.run_sync(functools.partial(self.async_fetch, task, lambda t, _, r: True))
wait_result = threading.Condition()
_result = {}
def callback(ty... | python | def sync_fetch(self, task):
'''Synchronization fetch, usually used in xmlrpc thread'''
if not self._running:
return self.ioloop.run_sync(functools.partial(self.async_fetch, task, lambda t, _, r: True))
wait_result = threading.Condition()
_result = {}
def callback(ty... | [
"def",
"sync_fetch",
"(",
"self",
",",
"task",
")",
":",
"if",
"not",
"self",
".",
"_running",
":",
"return",
"self",
".",
"ioloop",
".",
"run_sync",
"(",
"functools",
".",
"partial",
"(",
"self",
".",
"async_fetch",
",",
"task",
",",
"lambda",
"t",
... | Synchronization fetch, usually used in xmlrpc thread | [
"Synchronization",
"fetch",
"usually",
"used",
"in",
"xmlrpc",
"thread"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L155-L176 | train |
binux/pyspider | pyspider/fetcher/tornado_fetcher.py | Fetcher.data_fetch | def data_fetch(self, url, task):
'''A fake fetcher for dataurl'''
self.on_fetch('data', task)
result = {}
result['orig_url'] = url
result['content'] = dataurl.decode(url)
result['headers'] = {}
result['status_code'] = 200
result['url'] = url
result... | python | def data_fetch(self, url, task):
'''A fake fetcher for dataurl'''
self.on_fetch('data', task)
result = {}
result['orig_url'] = url
result['content'] = dataurl.decode(url)
result['headers'] = {}
result['status_code'] = 200
result['url'] = url
result... | [
"def",
"data_fetch",
"(",
"self",
",",
"url",
",",
"task",
")",
":",
"self",
".",
"on_fetch",
"(",
"'data'",
",",
"task",
")",
"result",
"=",
"{",
"}",
"result",
"[",
"'orig_url'",
"]",
"=",
"url",
"result",
"[",
"'content'",
"]",
"=",
"dataurl",
"... | A fake fetcher for dataurl | [
"A",
"fake",
"fetcher",
"for",
"dataurl"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L178-L200 | train |
binux/pyspider | pyspider/fetcher/tornado_fetcher.py | Fetcher.http_fetch | def http_fetch(self, url, task):
'''HTTP fetcher'''
start_time = time.time()
self.on_fetch('http', task)
handle_error = lambda x: self.handle_error('http', url, task, start_time, x)
# setup request parameters
fetch = self.pack_tornado_request_parameters(url, task)
... | python | def http_fetch(self, url, task):
'''HTTP fetcher'''
start_time = time.time()
self.on_fetch('http', task)
handle_error = lambda x: self.handle_error('http', url, task, start_time, x)
# setup request parameters
fetch = self.pack_tornado_request_parameters(url, task)
... | [
"def",
"http_fetch",
"(",
"self",
",",
"url",
",",
"task",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"on_fetch",
"(",
"'http'",
",",
"task",
")",
"handle_error",
"=",
"lambda",
"x",
":",
"self",
".",
"handle_error",
"("... | HTTP fetcher | [
"HTTP",
"fetcher"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L327-L428 | train |
binux/pyspider | pyspider/fetcher/tornado_fetcher.py | Fetcher.phantomjs_fetch | def phantomjs_fetch(self, url, task):
'''Fetch with phantomjs proxy'''
start_time = time.time()
self.on_fetch('phantomjs', task)
handle_error = lambda x: self.handle_error('phantomjs', url, task, start_time, x)
# check phantomjs proxy is enabled
if not self.phantomjs_pro... | python | def phantomjs_fetch(self, url, task):
'''Fetch with phantomjs proxy'''
start_time = time.time()
self.on_fetch('phantomjs', task)
handle_error = lambda x: self.handle_error('phantomjs', url, task, start_time, x)
# check phantomjs proxy is enabled
if not self.phantomjs_pro... | [
"def",
"phantomjs_fetch",
"(",
"self",
",",
"url",
",",
"task",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"on_fetch",
"(",
"'phantomjs'",
",",
"task",
")",
"handle_error",
"=",
"lambda",
"x",
":",
"self",
".",
"handle_err... | Fetch with phantomjs proxy | [
"Fetch",
"with",
"phantomjs",
"proxy"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L431-L529 | train |
binux/pyspider | pyspider/fetcher/tornado_fetcher.py | Fetcher.run | def run(self):
'''Run loop'''
logger.info("fetcher starting...")
def queue_loop():
if not self.outqueue or not self.inqueue:
return
while not self._quit:
try:
if self.outqueue.full():
break
... | python | def run(self):
'''Run loop'''
logger.info("fetcher starting...")
def queue_loop():
if not self.outqueue or not self.inqueue:
return
while not self._quit:
try:
if self.outqueue.full():
break
... | [
"def",
"run",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"fetcher starting...\"",
")",
"def",
"queue_loop",
"(",
")",
":",
"if",
"not",
"self",
".",
"outqueue",
"or",
"not",
"self",
".",
"inqueue",
":",
"return",
"while",
"not",
"self",
".",
... | Run loop | [
"Run",
"loop"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L743-L778 | train |
binux/pyspider | pyspider/fetcher/tornado_fetcher.py | Fetcher.quit | def quit(self):
'''Quit fetcher'''
self._running = False
self._quit = True
self.ioloop.add_callback(self.ioloop.stop)
if hasattr(self, 'xmlrpc_server'):
self.xmlrpc_ioloop.add_callback(self.xmlrpc_server.stop)
self.xmlrpc_ioloop.add_callback(self.xmlrpc_io... | python | def quit(self):
'''Quit fetcher'''
self._running = False
self._quit = True
self.ioloop.add_callback(self.ioloop.stop)
if hasattr(self, 'xmlrpc_server'):
self.xmlrpc_ioloop.add_callback(self.xmlrpc_server.stop)
self.xmlrpc_ioloop.add_callback(self.xmlrpc_io... | [
"def",
"quit",
"(",
"self",
")",
":",
"self",
".",
"_running",
"=",
"False",
"self",
".",
"_quit",
"=",
"True",
"self",
".",
"ioloop",
".",
"add_callback",
"(",
"self",
".",
"ioloop",
".",
"stop",
")",
"if",
"hasattr",
"(",
"self",
",",
"'xmlrpc_serv... | Quit fetcher | [
"Quit",
"fetcher"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L780-L787 | train |
binux/pyspider | pyspider/fetcher/tornado_fetcher.py | Fetcher.xmlrpc_run | def xmlrpc_run(self, port=24444, bind='127.0.0.1', logRequests=False):
'''Run xmlrpc server'''
import umsgpack
from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication
try:
from xmlrpc.client import Binary
except ImportError:
from xmlrpclib import Binar... | python | def xmlrpc_run(self, port=24444, bind='127.0.0.1', logRequests=False):
'''Run xmlrpc server'''
import umsgpack
from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication
try:
from xmlrpc.client import Binary
except ImportError:
from xmlrpclib import Binar... | [
"def",
"xmlrpc_run",
"(",
"self",
",",
"port",
"=",
"24444",
",",
"bind",
"=",
"'127.0.0.1'",
",",
"logRequests",
"=",
"False",
")",
":",
"import",
"umsgpack",
"from",
"pyspider",
".",
"libs",
".",
"wsgi_xmlrpc",
"import",
"WSGIXMLRPCApplication",
"try",
":"... | Run xmlrpc server | [
"Run",
"xmlrpc",
"server"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L792-L825 | train |
binux/pyspider | pyspider/fetcher/tornado_fetcher.py | Fetcher.on_result | def on_result(self, type, task, result):
'''Called after task fetched'''
status_code = result.get('status_code', 599)
if status_code != 599:
status_code = (int(status_code) / 100 * 100)
self._cnt['5m'].event((task.get('project'), status_code), +1)
self._cnt['1h'].even... | python | def on_result(self, type, task, result):
'''Called after task fetched'''
status_code = result.get('status_code', 599)
if status_code != 599:
status_code = (int(status_code) / 100 * 100)
self._cnt['5m'].event((task.get('project'), status_code), +1)
self._cnt['1h'].even... | [
"def",
"on_result",
"(",
"self",
",",
"type",
",",
"task",
",",
"result",
")",
":",
"status_code",
"=",
"result",
".",
"get",
"(",
"'status_code'",
",",
"599",
")",
"if",
"status_code",
"!=",
"599",
":",
"status_code",
"=",
"(",
"int",
"(",
"status_cod... | Called after task fetched | [
"Called",
"after",
"task",
"fetched"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L831-L846 | train |
binux/pyspider | pyspider/libs/counter.py | CounterValue.to_dict | def to_dict(self, get_value=None):
"""Dump counters as a dict"""
result = {}
for key, value in iteritems(self):
if isinstance(value, BaseCounter):
if get_value is not None:
value = getattr(value, get_value)
result[key] = value
... | python | def to_dict(self, get_value=None):
"""Dump counters as a dict"""
result = {}
for key, value in iteritems(self):
if isinstance(value, BaseCounter):
if get_value is not None:
value = getattr(value, get_value)
result[key] = value
... | [
"def",
"to_dict",
"(",
"self",
",",
"get_value",
"=",
"None",
")",
":",
"result",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"BaseCounter",
")",
":",
"if",
"get_value",
... | Dump counters as a dict | [
"Dump",
"counters",
"as",
"a",
"dict"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L316-L326 | train |
binux/pyspider | pyspider/libs/counter.py | CounterManager.value | def value(self, key, value=1):
"""Set value of a counter by counter key"""
if isinstance(key, six.string_types):
key = (key, )
# assert all(isinstance(k, six.string_types) for k in key)
assert isinstance(key, tuple), "event key type error"
if key not in self.counters:... | python | def value(self, key, value=1):
"""Set value of a counter by counter key"""
if isinstance(key, six.string_types):
key = (key, )
# assert all(isinstance(k, six.string_types) for k in key)
assert isinstance(key, tuple), "event key type error"
if key not in self.counters:... | [
"def",
"value",
"(",
"self",
",",
"key",
",",
"value",
"=",
"1",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"six",
".",
"string_types",
")",
":",
"key",
"=",
"(",
"key",
",",
")",
"# assert all(isinstance(k, six.string_types) for k in key)",
"assert",
... | Set value of a counter by counter key | [
"Set",
"value",
"of",
"a",
"counter",
"by",
"counter",
"key"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L355-L364 | train |
binux/pyspider | pyspider/libs/counter.py | CounterManager.trim | def trim(self):
"""Clear not used counters"""
for key, value in list(iteritems(self.counters)):
if value.empty():
del self.counters[key] | python | def trim(self):
"""Clear not used counters"""
for key, value in list(iteritems(self.counters)):
if value.empty():
del self.counters[key] | [
"def",
"trim",
"(",
"self",
")",
":",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"iteritems",
"(",
"self",
".",
"counters",
")",
")",
":",
"if",
"value",
".",
"empty",
"(",
")",
":",
"del",
"self",
".",
"counters",
"[",
"key",
"]"
] | Clear not used counters | [
"Clear",
"not",
"used",
"counters"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L366-L370 | train |
binux/pyspider | pyspider/libs/counter.py | CounterManager.to_dict | def to_dict(self, get_value=None):
"""Dump counters as a dict"""
self.trim()
result = {}
for key, value in iteritems(self.counters):
if get_value is not None:
value = getattr(value, get_value)
r = result
for _key in key[:-1]:
... | python | def to_dict(self, get_value=None):
"""Dump counters as a dict"""
self.trim()
result = {}
for key, value in iteritems(self.counters):
if get_value is not None:
value = getattr(value, get_value)
r = result
for _key in key[:-1]:
... | [
"def",
"to_dict",
"(",
"self",
",",
"get_value",
"=",
"None",
")",
":",
"self",
".",
"trim",
"(",
")",
"result",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"self",
".",
"counters",
")",
":",
"if",
"get_value",
"is",
"not",
... | Dump counters as a dict | [
"Dump",
"counters",
"as",
"a",
"dict"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L410-L421 | train |
binux/pyspider | pyspider/libs/counter.py | CounterManager.dump | def dump(self, filename):
"""Dump counters to file"""
try:
with open(filename, 'wb') as fp:
cPickle.dump(self.counters, fp)
except Exception as e:
logging.warning("can't dump counter to file %s: %s", filename, e)
return False
return Tru... | python | def dump(self, filename):
"""Dump counters to file"""
try:
with open(filename, 'wb') as fp:
cPickle.dump(self.counters, fp)
except Exception as e:
logging.warning("can't dump counter to file %s: %s", filename, e)
return False
return Tru... | [
"def",
"dump",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"fp",
":",
"cPickle",
".",
"dump",
"(",
"self",
".",
"counters",
",",
"fp",
")",
"except",
"Exception",
"as",
"e",
":",
"l... | Dump counters to file | [
"Dump",
"counters",
"to",
"file"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L423-L431 | train |
binux/pyspider | pyspider/libs/counter.py | CounterManager.load | def load(self, filename):
"""Load counters to file"""
try:
with open(filename, 'rb') as fp:
self.counters = cPickle.load(fp)
except:
logging.debug("can't load counter from file: %s", filename)
return False
return True | python | def load(self, filename):
"""Load counters to file"""
try:
with open(filename, 'rb') as fp:
self.counters = cPickle.load(fp)
except:
logging.debug("can't load counter from file: %s", filename)
return False
return True | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fp",
":",
"self",
".",
"counters",
"=",
"cPickle",
".",
"load",
"(",
"fp",
")",
"except",
":",
"logging",
".",
"debug",
"... | Load counters to file | [
"Load",
"counters",
"to",
"file"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L433-L441 | train |
binux/pyspider | pyspider/run.py | cli | def cli(ctx, **kwargs):
"""
A powerful spider system in python.
"""
if kwargs['add_sys_path']:
sys.path.append(os.getcwd())
logging.config.fileConfig(kwargs['logging_config'])
# get db from env
for db in ('taskdb', 'projectdb', 'resultdb'):
if kwargs[db] is not None:
... | python | def cli(ctx, **kwargs):
"""
A powerful spider system in python.
"""
if kwargs['add_sys_path']:
sys.path.append(os.getcwd())
logging.config.fileConfig(kwargs['logging_config'])
# get db from env
for db in ('taskdb', 'projectdb', 'resultdb'):
if kwargs[db] is not None:
... | [
"def",
"cli",
"(",
"ctx",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
"[",
"'add_sys_path'",
"]",
":",
"sys",
".",
"path",
".",
"append",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"logging",
".",
"config",
".",
"fileConfig",
"(",
"kwargs",
... | A powerful spider system in python. | [
"A",
"powerful",
"spider",
"system",
"in",
"python",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L91-L173 | train |
binux/pyspider | pyspider/run.py | scheduler | def scheduler(ctx, xmlrpc, xmlrpc_host, xmlrpc_port,
inqueue_limit, delete_time, active_tasks, loop_limit, fail_pause_num,
scheduler_cls, threads, get_object=False):
"""
Run Scheduler, only one scheduler is allowed.
"""
g = ctx.obj
Scheduler = load_cls(None, None, schedul... | python | def scheduler(ctx, xmlrpc, xmlrpc_host, xmlrpc_port,
inqueue_limit, delete_time, active_tasks, loop_limit, fail_pause_num,
scheduler_cls, threads, get_object=False):
"""
Run Scheduler, only one scheduler is allowed.
"""
g = ctx.obj
Scheduler = load_cls(None, None, schedul... | [
"def",
"scheduler",
"(",
"ctx",
",",
"xmlrpc",
",",
"xmlrpc_host",
",",
"xmlrpc_port",
",",
"inqueue_limit",
",",
"delete_time",
",",
"active_tasks",
",",
"loop_limit",
",",
"fail_pause_num",
",",
"scheduler_cls",
",",
"threads",
",",
"get_object",
"=",
"False",... | Run Scheduler, only one scheduler is allowed. | [
"Run",
"Scheduler",
"only",
"one",
"scheduler",
"is",
"allowed",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L192-L220 | train |
binux/pyspider | pyspider/run.py | fetcher | def fetcher(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, poolsize, proxy, user_agent,
timeout, phantomjs_endpoint, puppeteer_endpoint, splash_endpoint, fetcher_cls,
async_mode=True, get_object=False, no_input=False):
"""
Run Fetcher.
"""
g = ctx.obj
Fetcher = load_cls(None, None, f... | python | def fetcher(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, poolsize, proxy, user_agent,
timeout, phantomjs_endpoint, puppeteer_endpoint, splash_endpoint, fetcher_cls,
async_mode=True, get_object=False, no_input=False):
"""
Run Fetcher.
"""
g = ctx.obj
Fetcher = load_cls(None, None, f... | [
"def",
"fetcher",
"(",
"ctx",
",",
"xmlrpc",
",",
"xmlrpc_host",
",",
"xmlrpc_port",
",",
"poolsize",
",",
"proxy",
",",
"user_agent",
",",
"timeout",
",",
"phantomjs_endpoint",
",",
"puppeteer_endpoint",
",",
"splash_endpoint",
",",
"fetcher_cls",
",",
"async_m... | Run Fetcher. | [
"Run",
"Fetcher",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L237-L269 | train |
binux/pyspider | pyspider/run.py | processor | def processor(ctx, processor_cls, process_time_limit, enable_stdout_capture=True, get_object=False):
"""
Run Processor.
"""
g = ctx.obj
Processor = load_cls(None, None, processor_cls)
processor = Processor(projectdb=g.projectdb,
inqueue=g.fetcher2processor, status_queu... | python | def processor(ctx, processor_cls, process_time_limit, enable_stdout_capture=True, get_object=False):
"""
Run Processor.
"""
g = ctx.obj
Processor = load_cls(None, None, processor_cls)
processor = Processor(projectdb=g.projectdb,
inqueue=g.fetcher2processor, status_queu... | [
"def",
"processor",
"(",
"ctx",
",",
"processor_cls",
",",
"process_time_limit",
",",
"enable_stdout_capture",
"=",
"True",
",",
"get_object",
"=",
"False",
")",
":",
"g",
"=",
"ctx",
".",
"obj",
"Processor",
"=",
"load_cls",
"(",
"None",
",",
"None",
",",... | Run Processor. | [
"Run",
"Processor",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L277-L294 | train |
binux/pyspider | pyspider/run.py | result_worker | def result_worker(ctx, result_cls, get_object=False):
"""
Run result worker.
"""
g = ctx.obj
ResultWorker = load_cls(None, None, result_cls)
result_worker = ResultWorker(resultdb=g.resultdb, inqueue=g.processor2result)
g.instances.append(result_worker)
if g.get('testing_mode') or get_o... | python | def result_worker(ctx, result_cls, get_object=False):
"""
Run result worker.
"""
g = ctx.obj
ResultWorker = load_cls(None, None, result_cls)
result_worker = ResultWorker(resultdb=g.resultdb, inqueue=g.processor2result)
g.instances.append(result_worker)
if g.get('testing_mode') or get_o... | [
"def",
"result_worker",
"(",
"ctx",
",",
"result_cls",
",",
"get_object",
"=",
"False",
")",
":",
"g",
"=",
"ctx",
".",
"obj",
"ResultWorker",
"=",
"load_cls",
"(",
"None",
",",
"None",
",",
"result_cls",
")",
"result_worker",
"=",
"ResultWorker",
"(",
"... | Run result worker. | [
"Run",
"result",
"worker",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L301-L314 | train |
binux/pyspider | pyspider/run.py | webui | def webui(ctx, host, port, cdn, scheduler_rpc, fetcher_rpc, max_rate, max_burst,
username, password, need_auth, webui_instance, process_time_limit, get_object=False):
"""
Run WebUI
"""
app = load_cls(None, None, webui_instance)
g = ctx.obj
app.config['taskdb'] = g.taskdb
app.confi... | python | def webui(ctx, host, port, cdn, scheduler_rpc, fetcher_rpc, max_rate, max_burst,
username, password, need_auth, webui_instance, process_time_limit, get_object=False):
"""
Run WebUI
"""
app = load_cls(None, None, webui_instance)
g = ctx.obj
app.config['taskdb'] = g.taskdb
app.confi... | [
"def",
"webui",
"(",
"ctx",
",",
"host",
",",
"port",
",",
"cdn",
",",
"scheduler_rpc",
",",
"fetcher_rpc",
",",
"max_rate",
",",
"max_burst",
",",
"username",
",",
"password",
",",
"need_auth",
",",
"webui_instance",
",",
"process_time_limit",
",",
"get_obj... | Run WebUI | [
"Run",
"WebUI"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L337-L393 | train |
binux/pyspider | pyspider/run.py | phantomjs | def phantomjs(ctx, phantomjs_path, port, auto_restart, args):
"""
Run phantomjs fetcher if phantomjs is installed.
"""
args = args or ctx.default_map and ctx.default_map.get('args', [])
import subprocess
g = ctx.obj
_quit = []
phantomjs_fetcher = os.path.join(
os.path.dirname(py... | python | def phantomjs(ctx, phantomjs_path, port, auto_restart, args):
"""
Run phantomjs fetcher if phantomjs is installed.
"""
args = args or ctx.default_map and ctx.default_map.get('args', [])
import subprocess
g = ctx.obj
_quit = []
phantomjs_fetcher = os.path.join(
os.path.dirname(py... | [
"def",
"phantomjs",
"(",
"ctx",
",",
"phantomjs_path",
",",
"port",
",",
"auto_restart",
",",
"args",
")",
":",
"args",
"=",
"args",
"or",
"ctx",
".",
"default_map",
"and",
"ctx",
".",
"default_map",
".",
"get",
"(",
"'args'",
",",
"[",
"]",
")",
"im... | Run phantomjs fetcher if phantomjs is installed. | [
"Run",
"phantomjs",
"fetcher",
"if",
"phantomjs",
"is",
"installed",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L402-L443 | train |
binux/pyspider | pyspider/run.py | puppeteer | def puppeteer(ctx, port, auto_restart, args):
"""
Run puppeteer fetcher if puppeteer is installed.
"""
import subprocess
g = ctx.obj
_quit = []
puppeteer_fetcher = os.path.join(
os.path.dirname(pyspider.__file__), 'fetcher/puppeteer_fetcher.js')
cmd = ['node', puppeteer_fetcher,... | python | def puppeteer(ctx, port, auto_restart, args):
"""
Run puppeteer fetcher if puppeteer is installed.
"""
import subprocess
g = ctx.obj
_quit = []
puppeteer_fetcher = os.path.join(
os.path.dirname(pyspider.__file__), 'fetcher/puppeteer_fetcher.js')
cmd = ['node', puppeteer_fetcher,... | [
"def",
"puppeteer",
"(",
"ctx",
",",
"port",
",",
"auto_restart",
",",
"args",
")",
":",
"import",
"subprocess",
"g",
"=",
"ctx",
".",
"obj",
"_quit",
"=",
"[",
"]",
"puppeteer_fetcher",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
... | Run puppeteer fetcher if puppeteer is installed. | [
"Run",
"puppeteer",
"fetcher",
"if",
"puppeteer",
"is",
"installed",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L450-L486 | train |
binux/pyspider | pyspider/run.py | all | def all(ctx, fetcher_num, processor_num, result_worker_num, run_in):
"""
Run all the components in subprocess or thread
"""
ctx.obj['debug'] = False
g = ctx.obj
# FIXME: py34 cannot run components with threads
if run_in == 'subprocess' and os.name != 'nt':
run_in = utils.run_in_sub... | python | def all(ctx, fetcher_num, processor_num, result_worker_num, run_in):
"""
Run all the components in subprocess or thread
"""
ctx.obj['debug'] = False
g = ctx.obj
# FIXME: py34 cannot run components with threads
if run_in == 'subprocess' and os.name != 'nt':
run_in = utils.run_in_sub... | [
"def",
"all",
"(",
"ctx",
",",
"fetcher_num",
",",
"processor_num",
",",
"result_worker_num",
",",
"run_in",
")",
":",
"ctx",
".",
"obj",
"[",
"'debug'",
"]",
"=",
"False",
"g",
"=",
"ctx",
".",
"obj",
"# FIXME: py34 cannot run components with threads",
"if",
... | Run all the components in subprocess or thread | [
"Run",
"all",
"the",
"components",
"in",
"subprocess",
"or",
"thread"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L498-L570 | train |
binux/pyspider | pyspider/run.py | bench | def bench(ctx, fetcher_num, processor_num, result_worker_num, run_in, total, show,
taskdb_bench, message_queue_bench, all_bench):
"""
Run Benchmark test.
In bench mode, in-memory sqlite database is used instead of on-disk sqlite database.
"""
from pyspider.libs import bench
from pyspid... | python | def bench(ctx, fetcher_num, processor_num, result_worker_num, run_in, total, show,
taskdb_bench, message_queue_bench, all_bench):
"""
Run Benchmark test.
In bench mode, in-memory sqlite database is used instead of on-disk sqlite database.
"""
from pyspider.libs import bench
from pyspid... | [
"def",
"bench",
"(",
"ctx",
",",
"fetcher_num",
",",
"processor_num",
",",
"result_worker_num",
",",
"run_in",
",",
"total",
",",
"show",
",",
"taskdb_bench",
",",
"message_queue_bench",
",",
"all_bench",
")",
":",
"from",
"pyspider",
".",
"libs",
"import",
... | Run Benchmark test.
In bench mode, in-memory sqlite database is used instead of on-disk sqlite database. | [
"Run",
"Benchmark",
"test",
".",
"In",
"bench",
"mode",
"in",
"-",
"memory",
"sqlite",
"database",
"is",
"used",
"instead",
"of",
"on",
"-",
"disk",
"sqlite",
"database",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L589-L711 | train |
binux/pyspider | pyspider/run.py | one | def one(ctx, interactive, enable_phantomjs, enable_puppeteer, scripts):
"""
One mode not only means all-in-one, it runs every thing in one process over
tornado.ioloop, for debug purpose
"""
ctx.obj['debug'] = False
g = ctx.obj
g['testing_mode'] = True
if scripts:
from pyspider.... | python | def one(ctx, interactive, enable_phantomjs, enable_puppeteer, scripts):
"""
One mode not only means all-in-one, it runs every thing in one process over
tornado.ioloop, for debug purpose
"""
ctx.obj['debug'] = False
g = ctx.obj
g['testing_mode'] = True
if scripts:
from pyspider.... | [
"def",
"one",
"(",
"ctx",
",",
"interactive",
",",
"enable_phantomjs",
",",
"enable_puppeteer",
",",
"scripts",
")",
":",
"ctx",
".",
"obj",
"[",
"'debug'",
"]",
"=",
"False",
"g",
"=",
"ctx",
".",
"obj",
"g",
"[",
"'testing_mode'",
"]",
"=",
"True",
... | One mode not only means all-in-one, it runs every thing in one process over
tornado.ioloop, for debug purpose | [
"One",
"mode",
"not",
"only",
"means",
"all",
"-",
"in",
"-",
"one",
"it",
"runs",
"every",
"thing",
"in",
"one",
"process",
"over",
"tornado",
".",
"ioloop",
"for",
"debug",
"purpose"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L723-L793 | train |
binux/pyspider | pyspider/run.py | send_message | def send_message(ctx, scheduler_rpc, project, message):
"""
Send Message to project from command line
"""
if isinstance(scheduler_rpc, six.string_types):
scheduler_rpc = connect_rpc(ctx, None, scheduler_rpc)
if scheduler_rpc is None and os.environ.get('SCHEDULER_NAME'):
scheduler_rpc... | python | def send_message(ctx, scheduler_rpc, project, message):
"""
Send Message to project from command line
"""
if isinstance(scheduler_rpc, six.string_types):
scheduler_rpc = connect_rpc(ctx, None, scheduler_rpc)
if scheduler_rpc is None and os.environ.get('SCHEDULER_NAME'):
scheduler_rpc... | [
"def",
"send_message",
"(",
"ctx",
",",
"scheduler_rpc",
",",
"project",
",",
"message",
")",
":",
"if",
"isinstance",
"(",
"scheduler_rpc",
",",
"six",
".",
"string_types",
")",
":",
"scheduler_rpc",
"=",
"connect_rpc",
"(",
"ctx",
",",
"None",
",",
"sche... | Send Message to project from command line | [
"Send",
"Message",
"to",
"project",
"from",
"command",
"line"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L801-L823 | train |
binux/pyspider | pyspider/libs/pprint.py | pprint | def pprint(object, stream=None, indent=1, width=80, depth=None):
"""Pretty-print a Python object to a stream [default is sys.stdout]."""
printer = PrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object) | python | def pprint(object, stream=None, indent=1, width=80, depth=None):
"""Pretty-print a Python object to a stream [default is sys.stdout]."""
printer = PrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object) | [
"def",
"pprint",
"(",
"object",
",",
"stream",
"=",
"None",
",",
"indent",
"=",
"1",
",",
"width",
"=",
"80",
",",
"depth",
"=",
"None",
")",
":",
"printer",
"=",
"PrettyPrinter",
"(",
"stream",
"=",
"stream",
",",
"indent",
"=",
"indent",
",",
"wi... | Pretty-print a Python object to a stream [default is sys.stdout]. | [
"Pretty",
"-",
"print",
"a",
"Python",
"object",
"to",
"a",
"stream",
"[",
"default",
"is",
"sys",
".",
"stdout",
"]",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/pprint.py#L54-L58 | train |
binux/pyspider | pyspider/libs/pprint.py | pformat | def pformat(object, indent=1, width=80, depth=None):
"""Format a Python object into a pretty-printed representation."""
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object) | python | def pformat(object, indent=1, width=80, depth=None):
"""Format a Python object into a pretty-printed representation."""
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object) | [
"def",
"pformat",
"(",
"object",
",",
"indent",
"=",
"1",
",",
"width",
"=",
"80",
",",
"depth",
"=",
"None",
")",
":",
"return",
"PrettyPrinter",
"(",
"indent",
"=",
"indent",
",",
"width",
"=",
"width",
",",
"depth",
"=",
"depth",
")",
".",
"pfor... | Format a Python object into a pretty-printed representation. | [
"Format",
"a",
"Python",
"object",
"into",
"a",
"pretty",
"-",
"printed",
"representation",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/pprint.py#L61-L63 | train |
binux/pyspider | pyspider/libs/pprint.py | PrettyPrinter.format | def format(self, object, context, maxlevels, level):
"""Format object for a specific context, returning a string
and flags indicating whether the representation is 'readable'
and whether the object represents a recursive construct.
"""
return _safe_repr(object, context, maxlevels... | python | def format(self, object, context, maxlevels, level):
"""Format object for a specific context, returning a string
and flags indicating whether the representation is 'readable'
and whether the object represents a recursive construct.
"""
return _safe_repr(object, context, maxlevels... | [
"def",
"format",
"(",
"self",
",",
"object",
",",
"context",
",",
"maxlevels",
",",
"level",
")",
":",
"return",
"_safe_repr",
"(",
"object",
",",
"context",
",",
"maxlevels",
",",
"level",
")"
] | Format object for a specific context, returning a string
and flags indicating whether the representation is 'readable'
and whether the object represents a recursive construct. | [
"Format",
"object",
"for",
"a",
"specific",
"context",
"returning",
"a",
"string",
"and",
"flags",
"indicating",
"whether",
"the",
"representation",
"is",
"readable",
"and",
"whether",
"the",
"object",
"represents",
"a",
"recursive",
"construct",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/pprint.py#L243-L248 | train |
binux/pyspider | pyspider/result/result_worker.py | ResultWorker.on_result | def on_result(self, task, result):
'''Called every result'''
if not result:
return
if 'taskid' in task and 'project' in task and 'url' in task:
logger.info('result %s:%s %s -> %.30r' % (
task['project'], task['taskid'], task['url'], result))
re... | python | def on_result(self, task, result):
'''Called every result'''
if not result:
return
if 'taskid' in task and 'project' in task and 'url' in task:
logger.info('result %s:%s %s -> %.30r' % (
task['project'], task['taskid'], task['url'], result))
re... | [
"def",
"on_result",
"(",
"self",
",",
"task",
",",
"result",
")",
":",
"if",
"not",
"result",
":",
"return",
"if",
"'taskid'",
"in",
"task",
"and",
"'project'",
"in",
"task",
"and",
"'url'",
"in",
"task",
":",
"logger",
".",
"info",
"(",
"'result %s:%s... | Called every result | [
"Called",
"every",
"result"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/result/result_worker.py#L27-L42 | train |
binux/pyspider | pyspider/result/result_worker.py | ResultWorker.run | def run(self):
'''Run loop'''
logger.info("result_worker starting...")
while not self._quit:
try:
task, result = self.inqueue.get(timeout=1)
self.on_result(task, result)
except Queue.Empty as e:
continue
except ... | python | def run(self):
'''Run loop'''
logger.info("result_worker starting...")
while not self._quit:
try:
task, result = self.inqueue.get(timeout=1)
self.on_result(task, result)
except Queue.Empty as e:
continue
except ... | [
"def",
"run",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"result_worker starting...\"",
")",
"while",
"not",
"self",
".",
"_quit",
":",
"try",
":",
"task",
",",
"result",
"=",
"self",
".",
"inqueue",
".",
"get",
"(",
"timeout",
"=",
"1",
")... | Run loop | [
"Run",
"loop"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/result/result_worker.py#L47-L66 | train |
binux/pyspider | pyspider/result/result_worker.py | OneResultWorker.on_result | def on_result(self, task, result):
'''Called every result'''
if not result:
return
if 'taskid' in task and 'project' in task and 'url' in task:
logger.info('result %s:%s %s -> %.30r' % (
task['project'], task['taskid'], task['url'], result))
pr... | python | def on_result(self, task, result):
'''Called every result'''
if not result:
return
if 'taskid' in task and 'project' in task and 'url' in task:
logger.info('result %s:%s %s -> %.30r' % (
task['project'], task['taskid'], task['url'], result))
pr... | [
"def",
"on_result",
"(",
"self",
",",
"task",
",",
"result",
")",
":",
"if",
"not",
"result",
":",
"return",
"if",
"'taskid'",
"in",
"task",
"and",
"'project'",
"in",
"task",
"and",
"'url'",
"in",
"task",
":",
"logger",
".",
"info",
"(",
"'result %s:%s... | Called every result | [
"Called",
"every",
"result"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/result/result_worker.py#L71-L87 | train |
binux/pyspider | pyspider/scheduler/token_bucket.py | Bucket.get | def get(self):
'''Get the number of tokens in bucket'''
now = time.time()
if self.bucket >= self.burst:
self.last_update = now
return self.bucket
bucket = self.rate * (now - self.last_update)
self.mutex.acquire()
if bucket > 1:
self.buc... | python | def get(self):
'''Get the number of tokens in bucket'''
now = time.time()
if self.bucket >= self.burst:
self.last_update = now
return self.bucket
bucket = self.rate * (now - self.last_update)
self.mutex.acquire()
if bucket > 1:
self.buc... | [
"def",
"get",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"self",
".",
"bucket",
">=",
"self",
".",
"burst",
":",
"self",
".",
"last_update",
"=",
"now",
"return",
"self",
".",
"bucket",
"bucket",
"=",
"self",
".",
"ra... | Get the number of tokens in bucket | [
"Get",
"the",
"number",
"of",
"tokens",
"in",
"bucket"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/token_bucket.py#L33-L47 | train |
binux/pyspider | tools/migrate.py | migrate | def migrate(pool, from_connection, to_connection):
"""
Migrate tool for pyspider
"""
f = connect_database(from_connection)
t = connect_database(to_connection)
if isinstance(f, ProjectDB):
for each in f.get_all():
each = unicode_obj(each)
logging.info("projectdb: ... | python | def migrate(pool, from_connection, to_connection):
"""
Migrate tool for pyspider
"""
f = connect_database(from_connection)
t = connect_database(to_connection)
if isinstance(f, ProjectDB):
for each in f.get_all():
each = unicode_obj(each)
logging.info("projectdb: ... | [
"def",
"migrate",
"(",
"pool",
",",
"from_connection",
",",
"to_connection",
")",
":",
"f",
"=",
"connect_database",
"(",
"from_connection",
")",
"t",
"=",
"connect_database",
"(",
"to_connection",
")",
"if",
"isinstance",
"(",
"f",
",",
"ProjectDB",
")",
":... | Migrate tool for pyspider | [
"Migrate",
"tool",
"for",
"pyspider"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/tools/migrate.py#L43-L65 | train |
binux/pyspider | pyspider/libs/dataurl.py | encode | def encode(data, mime_type='', charset='utf-8', base64=True):
"""
Encode data to DataURL
"""
if isinstance(data, six.text_type):
data = data.encode(charset)
else:
charset = None
if base64:
data = utils.text(b64encode(data))
else:
data = utils.text(quote(data))... | python | def encode(data, mime_type='', charset='utf-8', base64=True):
"""
Encode data to DataURL
"""
if isinstance(data, six.text_type):
data = data.encode(charset)
else:
charset = None
if base64:
data = utils.text(b64encode(data))
else:
data = utils.text(quote(data))... | [
"def",
"encode",
"(",
"data",
",",
"mime_type",
"=",
"''",
",",
"charset",
"=",
"'utf-8'",
",",
"base64",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"text_type",
")",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"char... | Encode data to DataURL | [
"Encode",
"data",
"to",
"DataURL"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/dataurl.py#L14-L38 | train |
binux/pyspider | pyspider/libs/dataurl.py | decode | def decode(data_url):
"""
Decode DataURL data
"""
metadata, data = data_url.rsplit(',', 1)
_, metadata = metadata.split('data:', 1)
parts = metadata.split(';')
if parts[-1] == 'base64':
data = b64decode(data)
else:
data = unquote(data)
for part in parts:
if p... | python | def decode(data_url):
"""
Decode DataURL data
"""
metadata, data = data_url.rsplit(',', 1)
_, metadata = metadata.split('data:', 1)
parts = metadata.split(';')
if parts[-1] == 'base64':
data = b64decode(data)
else:
data = unquote(data)
for part in parts:
if p... | [
"def",
"decode",
"(",
"data_url",
")",
":",
"metadata",
",",
"data",
"=",
"data_url",
".",
"rsplit",
"(",
"','",
",",
"1",
")",
"_",
",",
"metadata",
"=",
"metadata",
".",
"split",
"(",
"'data:'",
",",
"1",
")",
"parts",
"=",
"metadata",
".",
"spli... | Decode DataURL data | [
"Decode",
"DataURL",
"data"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/dataurl.py#L41-L56 | train |
binux/pyspider | pyspider/libs/url.py | _build_url | def _build_url(url, _params):
"""Build the actual URL to use."""
# Support for unicode domain names and paths.
scheme, netloc, path, params, query, fragment = urlparse(url)
netloc = netloc.encode('idna').decode('utf-8')
if not path:
path = '/'
if six.PY2:
if isinstance(scheme, ... | python | def _build_url(url, _params):
"""Build the actual URL to use."""
# Support for unicode domain names and paths.
scheme, netloc, path, params, query, fragment = urlparse(url)
netloc = netloc.encode('idna').decode('utf-8')
if not path:
path = '/'
if six.PY2:
if isinstance(scheme, ... | [
"def",
"_build_url",
"(",
"url",
",",
"_params",
")",
":",
"# Support for unicode domain names and paths.",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
"=",
"urlparse",
"(",
"url",
")",
"netloc",
"=",
"netloc",
".",
"e... | Build the actual URL to use. | [
"Build",
"the",
"actual",
"URL",
"to",
"use",
"."
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/url.py#L29-L59 | train |
binux/pyspider | pyspider/libs/url.py | quote_chinese | def quote_chinese(url, encodeing="utf-8"):
"""Quote non-ascii characters"""
if isinstance(url, six.text_type):
return quote_chinese(url.encode(encodeing))
if six.PY3:
res = [six.int2byte(b).decode('latin-1') if b < 128 else '%%%02X' % b for b in url]
else:
res = [b if ord(b) < 12... | python | def quote_chinese(url, encodeing="utf-8"):
"""Quote non-ascii characters"""
if isinstance(url, six.text_type):
return quote_chinese(url.encode(encodeing))
if six.PY3:
res = [six.int2byte(b).decode('latin-1') if b < 128 else '%%%02X' % b for b in url]
else:
res = [b if ord(b) < 12... | [
"def",
"quote_chinese",
"(",
"url",
",",
"encodeing",
"=",
"\"utf-8\"",
")",
":",
"if",
"isinstance",
"(",
"url",
",",
"six",
".",
"text_type",
")",
":",
"return",
"quote_chinese",
"(",
"url",
".",
"encode",
"(",
"encodeing",
")",
")",
"if",
"six",
"."... | Quote non-ascii characters | [
"Quote",
"non",
"-",
"ascii",
"characters"
] | 3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9 | https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/url.py#L62-L70 | train |
lanpa/tensorboardX | examples/demo_caffe2.py | DownloadResource | def DownloadResource(url, path):
'''Downloads resources from s3 by url and unzips them to the provided path'''
import requests
from six import BytesIO
import zipfile
print("Downloading... {} to {}".format(url, path))
r = requests.get(url, stream=True)
z = zipfile.ZipFile(BytesIO(r.content))
... | python | def DownloadResource(url, path):
'''Downloads resources from s3 by url and unzips them to the provided path'''
import requests
from six import BytesIO
import zipfile
print("Downloading... {} to {}".format(url, path))
r = requests.get(url, stream=True)
z = zipfile.ZipFile(BytesIO(r.content))
... | [
"def",
"DownloadResource",
"(",
"url",
",",
"path",
")",
":",
"import",
"requests",
"from",
"six",
"import",
"BytesIO",
"import",
"zipfile",
"print",
"(",
"\"Downloading... {} to {}\"",
".",
"format",
"(",
"url",
",",
"path",
")",
")",
"r",
"=",
"requests",
... | Downloads resources from s3 by url and unzips them to the provided path | [
"Downloads",
"resources",
"from",
"s3",
"by",
"url",
"and",
"unzips",
"them",
"to",
"the",
"provided",
"path"
] | 0bf6c07d97b0745654fd9fab8ee3261ec707f253 | https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L28-L37 | train |
lanpa/tensorboardX | examples/demo_caffe2.py | AddLeNetModel | def AddLeNetModel(model, data):
'''
This part is the standard LeNet model: from data to the softmax prediction.
For each convolutional layer we specify dim_in - number of input channels
and dim_out - number or output channels. Also each Conv and MaxPool layer changes the
image size. For example, ke... | python | def AddLeNetModel(model, data):
'''
This part is the standard LeNet model: from data to the softmax prediction.
For each convolutional layer we specify dim_in - number of input channels
and dim_out - number or output channels. Also each Conv and MaxPool layer changes the
image size. For example, ke... | [
"def",
"AddLeNetModel",
"(",
"model",
",",
"data",
")",
":",
"# Image size: 28 x 28 -> 24 x 24",
"conv1",
"=",
"brew",
".",
"conv",
"(",
"model",
",",
"data",
",",
"'conv1'",
",",
"dim_in",
"=",
"1",
",",
"dim_out",
"=",
"20",
",",
"kernel",
"=",
"5",
... | This part is the standard LeNet model: from data to the softmax prediction.
For each convolutional layer we specify dim_in - number of input channels
and dim_out - number or output channels. Also each Conv and MaxPool layer changes the
image size. For example, kernel of size 5 reduces each side of an image... | [
"This",
"part",
"is",
"the",
"standard",
"LeNet",
"model",
":",
"from",
"data",
"to",
"the",
"softmax",
"prediction",
"."
] | 0bf6c07d97b0745654fd9fab8ee3261ec707f253 | https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L102-L127 | train |
lanpa/tensorboardX | examples/demo_caffe2.py | AddAccuracy | def AddAccuracy(model, softmax, label):
"""Adds an accuracy op to the model"""
accuracy = brew.accuracy(model, [softmax, label], "accuracy")
return accuracy | python | def AddAccuracy(model, softmax, label):
"""Adds an accuracy op to the model"""
accuracy = brew.accuracy(model, [softmax, label], "accuracy")
return accuracy | [
"def",
"AddAccuracy",
"(",
"model",
",",
"softmax",
",",
"label",
")",
":",
"accuracy",
"=",
"brew",
".",
"accuracy",
"(",
"model",
",",
"[",
"softmax",
",",
"label",
"]",
",",
"\"accuracy\"",
")",
"return",
"accuracy"
] | Adds an accuracy op to the model | [
"Adds",
"an",
"accuracy",
"op",
"to",
"the",
"model"
] | 0bf6c07d97b0745654fd9fab8ee3261ec707f253 | https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L130-L133 | train |
lanpa/tensorboardX | examples/demo_caffe2.py | AddTrainingOperators | def AddTrainingOperators(model, softmax, label):
"""Adds training operators to the model."""
xent = model.LabelCrossEntropy([softmax, label], 'xent')
# compute the expected loss
loss = model.AveragedLoss(xent, "loss")
# track the accuracy of the model
AddAccuracy(model, softmax, label)
# use... | python | def AddTrainingOperators(model, softmax, label):
"""Adds training operators to the model."""
xent = model.LabelCrossEntropy([softmax, label], 'xent')
# compute the expected loss
loss = model.AveragedLoss(xent, "loss")
# track the accuracy of the model
AddAccuracy(model, softmax, label)
# use... | [
"def",
"AddTrainingOperators",
"(",
"model",
",",
"softmax",
",",
"label",
")",
":",
"xent",
"=",
"model",
".",
"LabelCrossEntropy",
"(",
"[",
"softmax",
",",
"label",
"]",
",",
"'xent'",
")",
"# compute the expected loss",
"loss",
"=",
"model",
".",
"Averag... | Adds training operators to the model. | [
"Adds",
"training",
"operators",
"to",
"the",
"model",
"."
] | 0bf6c07d97b0745654fd9fab8ee3261ec707f253 | https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L136-L160 | train |
lanpa/tensorboardX | examples/demo_caffe2.py | AddBookkeepingOperators | def AddBookkeepingOperators(model):
"""This adds a few bookkeeping operators that we can inspect later.
These operators do not affect the training procedure: they only collect
statistics and prints them to file or to logs.
"""
# Print basically prints out the content of the blob. to_file=1 routes t... | python | def AddBookkeepingOperators(model):
"""This adds a few bookkeeping operators that we can inspect later.
These operators do not affect the training procedure: they only collect
statistics and prints them to file or to logs.
"""
# Print basically prints out the content of the blob. to_file=1 routes t... | [
"def",
"AddBookkeepingOperators",
"(",
"model",
")",
":",
"# Print basically prints out the content of the blob. to_file=1 routes the",
"# printed output to a file. The file is going to be stored under",
"# root_folder/[blob name]",
"model",
".",
"Print",
"(",
"'accuracy'",
",",
"[... | This adds a few bookkeeping operators that we can inspect later.
These operators do not affect the training procedure: they only collect
statistics and prints them to file or to logs. | [
"This",
"adds",
"a",
"few",
"bookkeeping",
"operators",
"that",
"we",
"can",
"inspect",
"later",
"."
] | 0bf6c07d97b0745654fd9fab8ee3261ec707f253 | https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L163-L178 | train |
lanpa/tensorboardX | examples/chainer/plain_logger/net.py | VAE.get_loss_func | def get_loss_func(self, C=1.0, k=1):
"""Get loss function of VAE.
The loss value is equal to ELBO (Evidence Lower Bound)
multiplied by -1.
Args:
C (int): Usually this is 1.0. Can be changed to control the
second term of ELBO bound, which works as regularizat... | python | def get_loss_func(self, C=1.0, k=1):
"""Get loss function of VAE.
The loss value is equal to ELBO (Evidence Lower Bound)
multiplied by -1.
Args:
C (int): Usually this is 1.0. Can be changed to control the
second term of ELBO bound, which works as regularizat... | [
"def",
"get_loss_func",
"(",
"self",
",",
"C",
"=",
"1.0",
",",
"k",
"=",
"1",
")",
":",
"def",
"lf",
"(",
"x",
")",
":",
"mu",
",",
"ln_var",
"=",
"self",
".",
"encode",
"(",
"x",
")",
"batchsize",
"=",
"len",
"(",
"mu",
".",
"data",
")",
... | Get loss function of VAE.
The loss value is equal to ELBO (Evidence Lower Bound)
multiplied by -1.
Args:
C (int): Usually this is 1.0. Can be changed to control the
second term of ELBO bound, which works as regularization.
k (int): Number of Monte Carlo ... | [
"Get",
"loss",
"function",
"of",
"VAE",
"."
] | 0bf6c07d97b0745654fd9fab8ee3261ec707f253 | https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/chainer/plain_logger/net.py#L41-L65 | train |
keras-rl/keras-rl | rl/core.py | Agent.fit | def fit(self, env, nb_steps, action_repetition=1, callbacks=None, verbose=1,
visualize=False, nb_max_start_steps=0, start_step_policy=None, log_interval=10000,
nb_max_episode_steps=None):
"""Trains the agent on the given environment.
# Arguments
env: (`Env` instance)... | python | def fit(self, env, nb_steps, action_repetition=1, callbacks=None, verbose=1,
visualize=False, nb_max_start_steps=0, start_step_policy=None, log_interval=10000,
nb_max_episode_steps=None):
"""Trains the agent on the given environment.
# Arguments
env: (`Env` instance)... | [
"def",
"fit",
"(",
"self",
",",
"env",
",",
"nb_steps",
",",
"action_repetition",
"=",
"1",
",",
"callbacks",
"=",
"None",
",",
"verbose",
"=",
"1",
",",
"visualize",
"=",
"False",
",",
"nb_max_start_steps",
"=",
"0",
",",
"start_step_policy",
"=",
"None... | Trains the agent on the given environment.
# Arguments
env: (`Env` instance): Environment that the agent interacts with. See [Env](#env) for details.
nb_steps (integer): Number of training steps to be performed.
action_repetition (integer): Number of times the agent repeats ... | [
"Trains",
"the",
"agent",
"on",
"the",
"given",
"environment",
"."
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/core.py#L53-L238 | train |
keras-rl/keras-rl | rl/core.py | Processor.process_step | def process_step(self, observation, reward, done, info):
"""Processes an entire step by applying the processor to the observation, reward, and info arguments.
# Arguments
observation (object): An observation as obtained by the environment.
reward (float): A reward as obtained by... | python | def process_step(self, observation, reward, done, info):
"""Processes an entire step by applying the processor to the observation, reward, and info arguments.
# Arguments
observation (object): An observation as obtained by the environment.
reward (float): A reward as obtained by... | [
"def",
"process_step",
"(",
"self",
",",
"observation",
",",
"reward",
",",
"done",
",",
"info",
")",
":",
"observation",
"=",
"self",
".",
"process_observation",
"(",
"observation",
")",
"reward",
"=",
"self",
".",
"process_reward",
"(",
"reward",
")",
"i... | Processes an entire step by applying the processor to the observation, reward, and info arguments.
# Arguments
observation (object): An observation as obtained by the environment.
reward (float): A reward as obtained by the environment.
done (boolean): `True` if the environm... | [
"Processes",
"an",
"entire",
"step",
"by",
"applying",
"the",
"processor",
"to",
"the",
"observation",
"reward",
"and",
"info",
"arguments",
"."
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/core.py#L511-L526 | train |
keras-rl/keras-rl | rl/policy.py | LinearAnnealedPolicy.get_current_value | def get_current_value(self):
"""Return current annealing value
# Returns
Value to use in annealing
"""
if self.agent.training:
# Linear annealed: f(x) = ax + b.
a = -float(self.value_max - self.value_min) / float(self.nb_steps)
b = float(s... | python | def get_current_value(self):
"""Return current annealing value
# Returns
Value to use in annealing
"""
if self.agent.training:
# Linear annealed: f(x) = ax + b.
a = -float(self.value_max - self.value_min) / float(self.nb_steps)
b = float(s... | [
"def",
"get_current_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"agent",
".",
"training",
":",
"# Linear annealed: f(x) = ax + b.",
"a",
"=",
"-",
"float",
"(",
"self",
".",
"value_max",
"-",
"self",
".",
"value_min",
")",
"/",
"float",
"(",
"self",
... | Return current annealing value
# Returns
Value to use in annealing | [
"Return",
"current",
"annealing",
"value"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L62-L75 | train |
keras-rl/keras-rl | rl/policy.py | LinearAnnealedPolicy.select_action | def select_action(self, **kwargs):
"""Choose an action to perform
# Returns
Action to take (int)
"""
setattr(self.inner_policy, self.attr, self.get_current_value())
return self.inner_policy.select_action(**kwargs) | python | def select_action(self, **kwargs):
"""Choose an action to perform
# Returns
Action to take (int)
"""
setattr(self.inner_policy, self.attr, self.get_current_value())
return self.inner_policy.select_action(**kwargs) | [
"def",
"select_action",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"setattr",
"(",
"self",
".",
"inner_policy",
",",
"self",
".",
"attr",
",",
"self",
".",
"get_current_value",
"(",
")",
")",
"return",
"self",
".",
"inner_policy",
".",
"select_actio... | Choose an action to perform
# Returns
Action to take (int) | [
"Choose",
"an",
"action",
"to",
"perform"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L77-L84 | train |
keras-rl/keras-rl | rl/policy.py | LinearAnnealedPolicy.get_config | def get_config(self):
"""Return configurations of LinearAnnealedPolicy
# Returns
Dict of config
"""
config = super(LinearAnnealedPolicy, self).get_config()
config['attr'] = self.attr
config['value_max'] = self.value_max
config['value_min'] = self.valu... | python | def get_config(self):
"""Return configurations of LinearAnnealedPolicy
# Returns
Dict of config
"""
config = super(LinearAnnealedPolicy, self).get_config()
config['attr'] = self.attr
config['value_max'] = self.value_max
config['value_min'] = self.valu... | [
"def",
"get_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"LinearAnnealedPolicy",
",",
"self",
")",
".",
"get_config",
"(",
")",
"config",
"[",
"'attr'",
"]",
"=",
"self",
".",
"attr",
"config",
"[",
"'value_max'",
"]",
"=",
"self",
".",... | Return configurations of LinearAnnealedPolicy
# Returns
Dict of config | [
"Return",
"configurations",
"of",
"LinearAnnealedPolicy"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L105-L118 | train |
keras-rl/keras-rl | rl/policy.py | SoftmaxPolicy.select_action | def select_action(self, nb_actions, probs):
"""Return the selected action
# Arguments
probs (np.ndarray) : Probabilty for each action
# Returns
action
"""
action = np.random.choice(range(nb_actions), p=probs)
return action | python | def select_action(self, nb_actions, probs):
"""Return the selected action
# Arguments
probs (np.ndarray) : Probabilty for each action
# Returns
action
"""
action = np.random.choice(range(nb_actions), p=probs)
return action | [
"def",
"select_action",
"(",
"self",
",",
"nb_actions",
",",
"probs",
")",
":",
"action",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"range",
"(",
"nb_actions",
")",
",",
"p",
"=",
"probs",
")",
"return",
"action"
] | Return the selected action
# Arguments
probs (np.ndarray) : Probabilty for each action
# Returns
action | [
"Return",
"the",
"selected",
"action"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L128-L139 | train |
keras-rl/keras-rl | rl/policy.py | EpsGreedyQPolicy.select_action | def select_action(self, q_values):
"""Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action
"""
assert q_values.ndim == 1
nb_actions = q_values.shape[0]
if n... | python | def select_action(self, q_values):
"""Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action
"""
assert q_values.ndim == 1
nb_actions = q_values.shape[0]
if n... | [
"def",
"select_action",
"(",
"self",
",",
"q_values",
")",
":",
"assert",
"q_values",
".",
"ndim",
"==",
"1",
"nb_actions",
"=",
"q_values",
".",
"shape",
"[",
"0",
"]",
"if",
"np",
".",
"random",
".",
"uniform",
"(",
")",
"<",
"self",
".",
"eps",
... | Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action | [
"Return",
"the",
"selected",
"action"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L153-L169 | train |
keras-rl/keras-rl | rl/policy.py | EpsGreedyQPolicy.get_config | def get_config(self):
"""Return configurations of EpsGreedyQPolicy
# Returns
Dict of config
"""
config = super(EpsGreedyQPolicy, self).get_config()
config['eps'] = self.eps
return config | python | def get_config(self):
"""Return configurations of EpsGreedyQPolicy
# Returns
Dict of config
"""
config = super(EpsGreedyQPolicy, self).get_config()
config['eps'] = self.eps
return config | [
"def",
"get_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"EpsGreedyQPolicy",
",",
"self",
")",
".",
"get_config",
"(",
")",
"config",
"[",
"'eps'",
"]",
"=",
"self",
".",
"eps",
"return",
"config"
] | Return configurations of EpsGreedyQPolicy
# Returns
Dict of config | [
"Return",
"configurations",
"of",
"EpsGreedyQPolicy"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L171-L179 | train |
keras-rl/keras-rl | rl/policy.py | GreedyQPolicy.select_action | def select_action(self, q_values):
"""Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action
"""
assert q_values.ndim == 1
action = np.argmax(q_values)
return ... | python | def select_action(self, q_values):
"""Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action
"""
assert q_values.ndim == 1
action = np.argmax(q_values)
return ... | [
"def",
"select_action",
"(",
"self",
",",
"q_values",
")",
":",
"assert",
"q_values",
".",
"ndim",
"==",
"1",
"action",
"=",
"np",
".",
"argmax",
"(",
"q_values",
")",
"return",
"action"
] | Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action | [
"Return",
"the",
"selected",
"action"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L187-L198 | train |
keras-rl/keras-rl | rl/policy.py | BoltzmannQPolicy.get_config | def get_config(self):
"""Return configurations of BoltzmannQPolicy
# Returns
Dict of config
"""
config = super(BoltzmannQPolicy, self).get_config()
config['tau'] = self.tau
config['clip'] = self.clip
return config | python | def get_config(self):
"""Return configurations of BoltzmannQPolicy
# Returns
Dict of config
"""
config = super(BoltzmannQPolicy, self).get_config()
config['tau'] = self.tau
config['clip'] = self.clip
return config | [
"def",
"get_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"BoltzmannQPolicy",
",",
"self",
")",
".",
"get_config",
"(",
")",
"config",
"[",
"'tau'",
"]",
"=",
"self",
".",
"tau",
"config",
"[",
"'clip'",
"]",
"=",
"self",
".",
"clip",
... | Return configurations of BoltzmannQPolicy
# Returns
Dict of config | [
"Return",
"configurations",
"of",
"BoltzmannQPolicy"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L230-L239 | train |
keras-rl/keras-rl | rl/policy.py | MaxBoltzmannQPolicy.select_action | def select_action(self, q_values):
"""Return the selected action
The selected action follows the BoltzmannQPolicy with probability epsilon
or return the Greedy Policy with probability (1 - epsilon)
# Arguments
q_values (np.ndarray): List of the estimations of Q for each acti... | python | def select_action(self, q_values):
"""Return the selected action
The selected action follows the BoltzmannQPolicy with probability epsilon
or return the Greedy Policy with probability (1 - epsilon)
# Arguments
q_values (np.ndarray): List of the estimations of Q for each acti... | [
"def",
"select_action",
"(",
"self",
",",
"q_values",
")",
":",
"assert",
"q_values",
".",
"ndim",
"==",
"1",
"q_values",
"=",
"q_values",
".",
"astype",
"(",
"'float64'",
")",
"nb_actions",
"=",
"q_values",
".",
"shape",
"[",
"0",
"]",
"if",
"np",
"."... | Return the selected action
The selected action follows the BoltzmannQPolicy with probability epsilon
or return the Greedy Policy with probability (1 - epsilon)
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection ac... | [
"Return",
"the",
"selected",
"action",
"The",
"selected",
"action",
"follows",
"the",
"BoltzmannQPolicy",
"with",
"probability",
"epsilon",
"or",
"return",
"the",
"Greedy",
"Policy",
"with",
"probability",
"(",
"1",
"-",
"epsilon",
")"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L257-L278 | train |
keras-rl/keras-rl | rl/policy.py | MaxBoltzmannQPolicy.get_config | def get_config(self):
"""Return configurations of MaxBoltzmannQPolicy
# Returns
Dict of config
"""
config = super(MaxBoltzmannQPolicy, self).get_config()
config['eps'] = self.eps
config['tau'] = self.tau
config['clip'] = self.clip
return confi... | python | def get_config(self):
"""Return configurations of MaxBoltzmannQPolicy
# Returns
Dict of config
"""
config = super(MaxBoltzmannQPolicy, self).get_config()
config['eps'] = self.eps
config['tau'] = self.tau
config['clip'] = self.clip
return confi... | [
"def",
"get_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"MaxBoltzmannQPolicy",
",",
"self",
")",
".",
"get_config",
"(",
")",
"config",
"[",
"'eps'",
"]",
"=",
"self",
".",
"eps",
"config",
"[",
"'tau'",
"]",
"=",
"self",
".",
"tau",... | Return configurations of MaxBoltzmannQPolicy
# Returns
Dict of config | [
"Return",
"configurations",
"of",
"MaxBoltzmannQPolicy"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L280-L290 | train |
keras-rl/keras-rl | rl/policy.py | BoltzmannGumbelQPolicy.select_action | def select_action(self, q_values):
"""Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action
"""
# We can't use BGE during testing, since we don't have access to the
#... | python | def select_action(self, q_values):
"""Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action
"""
# We can't use BGE during testing, since we don't have access to the
#... | [
"def",
"select_action",
"(",
"self",
",",
"q_values",
")",
":",
"# We can't use BGE during testing, since we don't have access to the",
"# action_counts at the end of training.",
"assert",
"self",
".",
"agent",
".",
"training",
",",
"\"BoltzmannGumbelQPolicy should only be used for... | Return the selected action
# Arguments
q_values (np.ndarray): List of the estimations of Q for each action
# Returns
Selection action | [
"Return",
"the",
"selected",
"action"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L314-L346 | train |
keras-rl/keras-rl | rl/policy.py | BoltzmannGumbelQPolicy.get_config | def get_config(self):
"""Return configurations of BoltzmannGumbelQPolicy
# Returns
Dict of config
"""
config = super(BoltzmannGumbelQPolicy, self).get_config()
config['C'] = self.C
return config | python | def get_config(self):
"""Return configurations of BoltzmannGumbelQPolicy
# Returns
Dict of config
"""
config = super(BoltzmannGumbelQPolicy, self).get_config()
config['C'] = self.C
return config | [
"def",
"get_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"BoltzmannGumbelQPolicy",
",",
"self",
")",
".",
"get_config",
"(",
")",
"config",
"[",
"'C'",
"]",
"=",
"self",
".",
"C",
"return",
"config"
] | Return configurations of BoltzmannGumbelQPolicy
# Returns
Dict of config | [
"Return",
"configurations",
"of",
"BoltzmannGumbelQPolicy"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L348-L356 | train |
keras-rl/keras-rl | rl/callbacks.py | CallbackList._set_env | def _set_env(self, env):
""" Set environment for each callback in callbackList """
for callback in self.callbacks:
if callable(getattr(callback, '_set_env', None)):
callback._set_env(env) | python | def _set_env(self, env):
""" Set environment for each callback in callbackList """
for callback in self.callbacks:
if callable(getattr(callback, '_set_env', None)):
callback._set_env(env) | [
"def",
"_set_env",
"(",
"self",
",",
"env",
")",
":",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"if",
"callable",
"(",
"getattr",
"(",
"callback",
",",
"'_set_env'",
",",
"None",
")",
")",
":",
"callback",
".",
"_set_env",
"(",
"env",
"... | Set environment for each callback in callbackList | [
"Set",
"environment",
"for",
"each",
"callback",
"in",
"callbackList"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L45-L49 | train |
keras-rl/keras-rl | rl/callbacks.py | CallbackList.on_episode_begin | def on_episode_begin(self, episode, logs={}):
""" Called at beginning of each episode for each callback in callbackList"""
for callback in self.callbacks:
# Check if callback supports the more appropriate `on_episode_begin` callback.
# If not, fall back to `on_epoch_begin` to be ... | python | def on_episode_begin(self, episode, logs={}):
""" Called at beginning of each episode for each callback in callbackList"""
for callback in self.callbacks:
# Check if callback supports the more appropriate `on_episode_begin` callback.
# If not, fall back to `on_epoch_begin` to be ... | [
"def",
"on_episode_begin",
"(",
"self",
",",
"episode",
",",
"logs",
"=",
"{",
"}",
")",
":",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"# Check if callback supports the more appropriate `on_episode_begin` callback.",
"# If not, fall back to `on_epoch_begin` t... | Called at beginning of each episode for each callback in callbackList | [
"Called",
"at",
"beginning",
"of",
"each",
"episode",
"for",
"each",
"callback",
"in",
"callbackList"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L51-L59 | train |
keras-rl/keras-rl | rl/callbacks.py | CallbackList.on_episode_end | def on_episode_end(self, episode, logs={}):
""" Called at end of each episode for each callback in callbackList"""
for callback in self.callbacks:
# Check if callback supports the more appropriate `on_episode_end` callback.
# If not, fall back to `on_epoch_end` to be compatible w... | python | def on_episode_end(self, episode, logs={}):
""" Called at end of each episode for each callback in callbackList"""
for callback in self.callbacks:
# Check if callback supports the more appropriate `on_episode_end` callback.
# If not, fall back to `on_epoch_end` to be compatible w... | [
"def",
"on_episode_end",
"(",
"self",
",",
"episode",
",",
"logs",
"=",
"{",
"}",
")",
":",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"# Check if callback supports the more appropriate `on_episode_end` callback.",
"# If not, fall back to `on_epoch_end` to be c... | Called at end of each episode for each callback in callbackList | [
"Called",
"at",
"end",
"of",
"each",
"episode",
"for",
"each",
"callback",
"in",
"callbackList"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L61-L69 | train |
keras-rl/keras-rl | rl/callbacks.py | CallbackList.on_step_begin | def on_step_begin(self, step, logs={}):
""" Called at beginning of each step for each callback in callbackList"""
for callback in self.callbacks:
# Check if callback supports the more appropriate `on_step_begin` callback.
# If not, fall back to `on_batch_begin` to be compatible w... | python | def on_step_begin(self, step, logs={}):
""" Called at beginning of each step for each callback in callbackList"""
for callback in self.callbacks:
# Check if callback supports the more appropriate `on_step_begin` callback.
# If not, fall back to `on_batch_begin` to be compatible w... | [
"def",
"on_step_begin",
"(",
"self",
",",
"step",
",",
"logs",
"=",
"{",
"}",
")",
":",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"# Check if callback supports the more appropriate `on_step_begin` callback.",
"# If not, fall back to `on_batch_begin` to be comp... | Called at beginning of each step for each callback in callbackList | [
"Called",
"at",
"beginning",
"of",
"each",
"step",
"for",
"each",
"callback",
"in",
"callbackList"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L71-L79 | train |
keras-rl/keras-rl | rl/callbacks.py | CallbackList.on_step_end | def on_step_end(self, step, logs={}):
""" Called at end of each step for each callback in callbackList"""
for callback in self.callbacks:
# Check if callback supports the more appropriate `on_step_end` callback.
# If not, fall back to `on_batch_end` to be compatible with built-in... | python | def on_step_end(self, step, logs={}):
""" Called at end of each step for each callback in callbackList"""
for callback in self.callbacks:
# Check if callback supports the more appropriate `on_step_end` callback.
# If not, fall back to `on_batch_end` to be compatible with built-in... | [
"def",
"on_step_end",
"(",
"self",
",",
"step",
",",
"logs",
"=",
"{",
"}",
")",
":",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"# Check if callback supports the more appropriate `on_step_end` callback.",
"# If not, fall back to `on_batch_end` to be compatible... | Called at end of each step for each callback in callbackList | [
"Called",
"at",
"end",
"of",
"each",
"step",
"for",
"each",
"callback",
"in",
"callbackList"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L81-L89 | train |
keras-rl/keras-rl | rl/callbacks.py | CallbackList.on_action_begin | def on_action_begin(self, action, logs={}):
""" Called at beginning of each action for each callback in callbackList"""
for callback in self.callbacks:
if callable(getattr(callback, 'on_action_begin', None)):
callback.on_action_begin(action, logs=logs) | python | def on_action_begin(self, action, logs={}):
""" Called at beginning of each action for each callback in callbackList"""
for callback in self.callbacks:
if callable(getattr(callback, 'on_action_begin', None)):
callback.on_action_begin(action, logs=logs) | [
"def",
"on_action_begin",
"(",
"self",
",",
"action",
",",
"logs",
"=",
"{",
"}",
")",
":",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"if",
"callable",
"(",
"getattr",
"(",
"callback",
",",
"'on_action_begin'",
",",
"None",
")",
")",
":",... | Called at beginning of each action for each callback in callbackList | [
"Called",
"at",
"beginning",
"of",
"each",
"action",
"for",
"each",
"callback",
"in",
"callbackList"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L91-L95 | train |
keras-rl/keras-rl | rl/callbacks.py | CallbackList.on_action_end | def on_action_end(self, action, logs={}):
""" Called at end of each action for each callback in callbackList"""
for callback in self.callbacks:
if callable(getattr(callback, 'on_action_end', None)):
callback.on_action_end(action, logs=logs) | python | def on_action_end(self, action, logs={}):
""" Called at end of each action for each callback in callbackList"""
for callback in self.callbacks:
if callable(getattr(callback, 'on_action_end', None)):
callback.on_action_end(action, logs=logs) | [
"def",
"on_action_end",
"(",
"self",
",",
"action",
",",
"logs",
"=",
"{",
"}",
")",
":",
"for",
"callback",
"in",
"self",
".",
"callbacks",
":",
"if",
"callable",
"(",
"getattr",
"(",
"callback",
",",
"'on_action_end'",
",",
"None",
")",
")",
":",
"... | Called at end of each action for each callback in callbackList | [
"Called",
"at",
"end",
"of",
"each",
"action",
"for",
"each",
"callback",
"in",
"callbackList"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L97-L101 | train |
keras-rl/keras-rl | rl/callbacks.py | TrainEpisodeLogger.on_train_begin | def on_train_begin(self, logs):
""" Print training values at beginning of training """
self.train_start = timeit.default_timer()
self.metrics_names = self.model.metrics_names
print('Training for {} steps ...'.format(self.params['nb_steps'])) | python | def on_train_begin(self, logs):
""" Print training values at beginning of training """
self.train_start = timeit.default_timer()
self.metrics_names = self.model.metrics_names
print('Training for {} steps ...'.format(self.params['nb_steps'])) | [
"def",
"on_train_begin",
"(",
"self",
",",
"logs",
")",
":",
"self",
".",
"train_start",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"self",
".",
"metrics_names",
"=",
"self",
".",
"model",
".",
"metrics_names",
"print",
"(",
"'Training for {} steps ...'",
... | Print training values at beginning of training | [
"Print",
"training",
"values",
"at",
"beginning",
"of",
"training"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L133-L137 | train |
keras-rl/keras-rl | rl/callbacks.py | TrainEpisodeLogger.on_train_end | def on_train_end(self, logs):
""" Print training time at end of training """
duration = timeit.default_timer() - self.train_start
print('done, took {:.3f} seconds'.format(duration)) | python | def on_train_end(self, logs):
""" Print training time at end of training """
duration = timeit.default_timer() - self.train_start
print('done, took {:.3f} seconds'.format(duration)) | [
"def",
"on_train_end",
"(",
"self",
",",
"logs",
")",
":",
"duration",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"-",
"self",
".",
"train_start",
"print",
"(",
"'done, took {:.3f} seconds'",
".",
"format",
"(",
"duration",
")",
")"
] | Print training time at end of training | [
"Print",
"training",
"time",
"at",
"end",
"of",
"training"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L139-L142 | train |
keras-rl/keras-rl | rl/callbacks.py | TrainEpisodeLogger.on_episode_begin | def on_episode_begin(self, episode, logs):
""" Reset environment variables at beginning of each episode """
self.episode_start[episode] = timeit.default_timer()
self.observations[episode] = []
self.rewards[episode] = []
self.actions[episode] = []
self.metrics[episode] = [... | python | def on_episode_begin(self, episode, logs):
""" Reset environment variables at beginning of each episode """
self.episode_start[episode] = timeit.default_timer()
self.observations[episode] = []
self.rewards[episode] = []
self.actions[episode] = []
self.metrics[episode] = [... | [
"def",
"on_episode_begin",
"(",
"self",
",",
"episode",
",",
"logs",
")",
":",
"self",
".",
"episode_start",
"[",
"episode",
"]",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"self",
".",
"observations",
"[",
"episode",
"]",
"=",
"[",
"]",
"self",
".... | Reset environment variables at beginning of each episode | [
"Reset",
"environment",
"variables",
"at",
"beginning",
"of",
"each",
"episode"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L144-L150 | train |
keras-rl/keras-rl | rl/callbacks.py | TrainEpisodeLogger.on_episode_end | def on_episode_end(self, episode, logs):
""" Compute and print training statistics of the episode when done """
duration = timeit.default_timer() - self.episode_start[episode]
episode_steps = len(self.observations[episode])
# Format all metrics.
metrics = np.array(self.metrics[e... | python | def on_episode_end(self, episode, logs):
""" Compute and print training statistics of the episode when done """
duration = timeit.default_timer() - self.episode_start[episode]
episode_steps = len(self.observations[episode])
# Format all metrics.
metrics = np.array(self.metrics[e... | [
"def",
"on_episode_end",
"(",
"self",
",",
"episode",
",",
"logs",
")",
":",
"duration",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"-",
"self",
".",
"episode_start",
"[",
"episode",
"]",
"episode_steps",
"=",
"len",
"(",
"self",
".",
"observations",
... | Compute and print training statistics of the episode when done | [
"Compute",
"and",
"print",
"training",
"statistics",
"of",
"the",
"episode",
"when",
"done"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L152-L203 | train |
keras-rl/keras-rl | rl/callbacks.py | TrainEpisodeLogger.on_step_end | def on_step_end(self, step, logs):
""" Update statistics of episode after each step """
episode = logs['episode']
self.observations[episode].append(logs['observation'])
self.rewards[episode].append(logs['reward'])
self.actions[episode].append(logs['action'])
self.metrics[... | python | def on_step_end(self, step, logs):
""" Update statistics of episode after each step """
episode = logs['episode']
self.observations[episode].append(logs['observation'])
self.rewards[episode].append(logs['reward'])
self.actions[episode].append(logs['action'])
self.metrics[... | [
"def",
"on_step_end",
"(",
"self",
",",
"step",
",",
"logs",
")",
":",
"episode",
"=",
"logs",
"[",
"'episode'",
"]",
"self",
".",
"observations",
"[",
"episode",
"]",
".",
"append",
"(",
"logs",
"[",
"'observation'",
"]",
")",
"self",
".",
"rewards",
... | Update statistics of episode after each step | [
"Update",
"statistics",
"of",
"episode",
"after",
"each",
"step"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L205-L212 | train |
keras-rl/keras-rl | rl/callbacks.py | TrainIntervalLogger.reset | def reset(self):
""" Reset statistics """
self.interval_start = timeit.default_timer()
self.progbar = Progbar(target=self.interval)
self.metrics = []
self.infos = []
self.info_names = None
self.episode_rewards = [] | python | def reset(self):
""" Reset statistics """
self.interval_start = timeit.default_timer()
self.progbar = Progbar(target=self.interval)
self.metrics = []
self.infos = []
self.info_names = None
self.episode_rewards = [] | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"interval_start",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"self",
".",
"progbar",
"=",
"Progbar",
"(",
"target",
"=",
"self",
".",
"interval",
")",
"self",
".",
"metrics",
"=",
"[",
"]",
"sel... | Reset statistics | [
"Reset",
"statistics"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L221-L228 | train |
keras-rl/keras-rl | rl/callbacks.py | TrainIntervalLogger.on_step_begin | def on_step_begin(self, step, logs):
""" Print metrics if interval is over """
if self.step % self.interval == 0:
if len(self.episode_rewards) > 0:
metrics = np.array(self.metrics)
assert metrics.shape == (self.interval, len(self.metrics_names))
... | python | def on_step_begin(self, step, logs):
""" Print metrics if interval is over """
if self.step % self.interval == 0:
if len(self.episode_rewards) > 0:
metrics = np.array(self.metrics)
assert metrics.shape == (self.interval, len(self.metrics_names))
... | [
"def",
"on_step_begin",
"(",
"self",
",",
"step",
",",
"logs",
")",
":",
"if",
"self",
".",
"step",
"%",
"self",
".",
"interval",
"==",
"0",
":",
"if",
"len",
"(",
"self",
".",
"episode_rewards",
")",
">",
"0",
":",
"metrics",
"=",
"np",
".",
"ar... | Print metrics if interval is over | [
"Print",
"metrics",
"if",
"interval",
"is",
"over"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L241-L265 | train |
keras-rl/keras-rl | rl/callbacks.py | TrainIntervalLogger.on_step_end | def on_step_end(self, step, logs):
""" Update progression bar at the end of each step """
if self.info_names is None:
self.info_names = logs['info'].keys()
values = [('reward', logs['reward'])]
if KERAS_VERSION > '2.1.3':
self.progbar.update((self.step % self.inte... | python | def on_step_end(self, step, logs):
""" Update progression bar at the end of each step """
if self.info_names is None:
self.info_names = logs['info'].keys()
values = [('reward', logs['reward'])]
if KERAS_VERSION > '2.1.3':
self.progbar.update((self.step % self.inte... | [
"def",
"on_step_end",
"(",
"self",
",",
"step",
",",
"logs",
")",
":",
"if",
"self",
".",
"info_names",
"is",
"None",
":",
"self",
".",
"info_names",
"=",
"logs",
"[",
"'info'",
"]",
".",
"keys",
"(",
")",
"values",
"=",
"[",
"(",
"'reward'",
",",
... | Update progression bar at the end of each step | [
"Update",
"progression",
"bar",
"at",
"the",
"end",
"of",
"each",
"step"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L267-L279 | train |
keras-rl/keras-rl | rl/callbacks.py | FileLogger.on_episode_begin | def on_episode_begin(self, episode, logs):
""" Initialize metrics at the beginning of each episode """
assert episode not in self.metrics
assert episode not in self.starts
self.metrics[episode] = []
self.starts[episode] = timeit.default_timer() | python | def on_episode_begin(self, episode, logs):
""" Initialize metrics at the beginning of each episode """
assert episode not in self.metrics
assert episode not in self.starts
self.metrics[episode] = []
self.starts[episode] = timeit.default_timer() | [
"def",
"on_episode_begin",
"(",
"self",
",",
"episode",
",",
"logs",
")",
":",
"assert",
"episode",
"not",
"in",
"self",
".",
"metrics",
"assert",
"episode",
"not",
"in",
"self",
".",
"starts",
"self",
".",
"metrics",
"[",
"episode",
"]",
"=",
"[",
"]"... | Initialize metrics at the beginning of each episode | [
"Initialize",
"metrics",
"at",
"the",
"beginning",
"of",
"each",
"episode"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L305-L310 | train |
keras-rl/keras-rl | rl/callbacks.py | FileLogger.on_episode_end | def on_episode_end(self, episode, logs):
""" Compute and print metrics at the end of each episode """
duration = timeit.default_timer() - self.starts[episode]
metrics = self.metrics[episode]
if np.isnan(metrics).all():
mean_metrics = np.array([np.nan for _ in self.metrics_n... | python | def on_episode_end(self, episode, logs):
""" Compute and print metrics at the end of each episode """
duration = timeit.default_timer() - self.starts[episode]
metrics = self.metrics[episode]
if np.isnan(metrics).all():
mean_metrics = np.array([np.nan for _ in self.metrics_n... | [
"def",
"on_episode_end",
"(",
"self",
",",
"episode",
",",
"logs",
")",
":",
"duration",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"-",
"self",
".",
"starts",
"[",
"episode",
"]",
"metrics",
"=",
"self",
".",
"metrics",
"[",
"episode",
"]",
"if",
... | Compute and print metrics at the end of each episode | [
"Compute",
"and",
"print",
"metrics",
"at",
"the",
"end",
"of",
"each",
"episode"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L312-L336 | train |
keras-rl/keras-rl | rl/callbacks.py | FileLogger.save_data | def save_data(self):
""" Save metrics in a json file """
if len(self.data.keys()) == 0:
return
# Sort everything by episode.
assert 'episode' in self.data
sorted_indexes = np.argsort(self.data['episode'])
sorted_data = {}
for key, values in self.data.... | python | def save_data(self):
""" Save metrics in a json file """
if len(self.data.keys()) == 0:
return
# Sort everything by episode.
assert 'episode' in self.data
sorted_indexes = np.argsort(self.data['episode'])
sorted_data = {}
for key, values in self.data.... | [
"def",
"save_data",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"data",
".",
"keys",
"(",
")",
")",
"==",
"0",
":",
"return",
"# Sort everything by episode.",
"assert",
"'episode'",
"in",
"self",
".",
"data",
"sorted_indexes",
"=",
"np",
".",
... | Save metrics in a json file | [
"Save",
"metrics",
"in",
"a",
"json",
"file"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L342-L360 | train |
keras-rl/keras-rl | rl/callbacks.py | ModelIntervalCheckpoint.on_step_end | def on_step_end(self, step, logs={}):
""" Save weights at interval steps during training """
self.total_steps += 1
if self.total_steps % self.interval != 0:
# Nothing to do.
return
filepath = self.filepath.format(step=self.total_steps, **logs)
if self.ver... | python | def on_step_end(self, step, logs={}):
""" Save weights at interval steps during training """
self.total_steps += 1
if self.total_steps % self.interval != 0:
# Nothing to do.
return
filepath = self.filepath.format(step=self.total_steps, **logs)
if self.ver... | [
"def",
"on_step_end",
"(",
"self",
",",
"step",
",",
"logs",
"=",
"{",
"}",
")",
":",
"self",
".",
"total_steps",
"+=",
"1",
"if",
"self",
".",
"total_steps",
"%",
"self",
".",
"interval",
"!=",
"0",
":",
"# Nothing to do.",
"return",
"filepath",
"=",
... | Save weights at interval steps during training | [
"Save",
"weights",
"at",
"interval",
"steps",
"during",
"training"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L377-L387 | train |
keras-rl/keras-rl | rl/memory.py | sample_batch_indexes | def sample_batch_indexes(low, high, size):
"""Return a sample of (size) unique elements between low and high
# Argument
low (int): The minimum value for our samples
high (int): The maximum value for our samples
size (int): The number of samples to pick
# Returns... | python | def sample_batch_indexes(low, high, size):
"""Return a sample of (size) unique elements between low and high
# Argument
low (int): The minimum value for our samples
high (int): The maximum value for our samples
size (int): The number of samples to pick
# Returns... | [
"def",
"sample_batch_indexes",
"(",
"low",
",",
"high",
",",
"size",
")",
":",
"if",
"high",
"-",
"low",
">=",
"size",
":",
"# We have enough data. Draw without replacement, that is each index is unique in the",
"# batch. We cannot use `np.random.choice` here because it is horrib... | Return a sample of (size) unique elements between low and high
# Argument
low (int): The minimum value for our samples
high (int): The maximum value for our samples
size (int): The number of samples to pick
# Returns
A list of samples of length size, wit... | [
"Return",
"a",
"sample",
"of",
"(",
"size",
")",
"unique",
"elements",
"between",
"low",
"and",
"high"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/memory.py#L14-L42 | train |
keras-rl/keras-rl | rl/memory.py | zeroed_observation | def zeroed_observation(observation):
"""Return an array of zeros with same shape as given observation
# Argument
observation (list): List of observation
# Return
A np.ndarray of zeros with observation.shape
"""
if hasattr(observation, 'shape'):
return np.zeros(observati... | python | def zeroed_observation(observation):
"""Return an array of zeros with same shape as given observation
# Argument
observation (list): List of observation
# Return
A np.ndarray of zeros with observation.shape
"""
if hasattr(observation, 'shape'):
return np.zeros(observati... | [
"def",
"zeroed_observation",
"(",
"observation",
")",
":",
"if",
"hasattr",
"(",
"observation",
",",
"'shape'",
")",
":",
"return",
"np",
".",
"zeros",
"(",
"observation",
".",
"shape",
")",
"elif",
"hasattr",
"(",
"observation",
",",
"'__iter__'",
")",
":... | Return an array of zeros with same shape as given observation
# Argument
observation (list): List of observation
# Return
A np.ndarray of zeros with observation.shape | [
"Return",
"an",
"array",
"of",
"zeros",
"with",
"same",
"shape",
"as",
"given",
"observation"
] | e6efb0d8297ec38d704a3110b5d6ed74d09a05e3 | https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/memory.py#L85-L102 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.