partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
Fetcher.phantomjs_fetch
Fetch with phantomjs proxy
pyspider/fetcher/tornado_fetcher.py
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): '''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...
[ "Fetch", "with", "phantomjs", "proxy" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L431-L529
[ "def", "phantomjs_fetch", "(", "self", ",", "url", ",", "task", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "self", ".", "on_fetch", "(", "'phantomjs'", ",", "task", ")", "handle_error", "=", "lambda", "x", ":", "self", ".", "handle_err...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
Fetcher.run
Run loop
pyspider/fetcher/tornado_fetcher.py
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): '''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 ...
[ "Run", "loop" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L743-L778
[ "def", "run", "(", "self", ")", ":", "logger", ".", "info", "(", "\"fetcher starting...\"", ")", "def", "queue_loop", "(", ")", ":", "if", "not", "self", ".", "outqueue", "or", "not", "self", ".", "inqueue", ":", "return", "while", "not", "self", ".", ...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
Fetcher.quit
Quit fetcher
pyspider/fetcher/tornado_fetcher.py
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): '''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...
[ "Quit", "fetcher" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L780-L787
[ "def", "quit", "(", "self", ")", ":", "self", ".", "_running", "=", "False", "self", ".", "_quit", "=", "True", "self", ".", "ioloop", ".", "add_callback", "(", "self", ".", "ioloop", ".", "stop", ")", "if", "hasattr", "(", "self", ",", "'xmlrpc_serv...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
Fetcher.xmlrpc_run
Run xmlrpc server
pyspider/fetcher/tornado_fetcher.py
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): '''Run xmlrpc server''' import umsgpack from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication try: from xmlrpc.client import Binary except ImportError: from xmlrpclib import Binar...
[ "Run", "xmlrpc", "server" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L792-L825
[ "def", "xmlrpc_run", "(", "self", ",", "port", "=", "24444", ",", "bind", "=", "'127.0.0.1'", ",", "logRequests", "=", "False", ")", ":", "import", "umsgpack", "from", "pyspider", ".", "libs", ".", "wsgi_xmlrpc", "import", "WSGIXMLRPCApplication", "try", ":"...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
Fetcher.on_result
Called after task fetched
pyspider/fetcher/tornado_fetcher.py
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): '''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...
[ "Called", "after", "task", "fetched" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/fetcher/tornado_fetcher.py#L831-L846
[ "def", "on_result", "(", "self", ",", "type", ",", "task", ",", "result", ")", ":", "status_code", "=", "result", ".", "get", "(", "'status_code'", ",", "599", ")", "if", "status_code", "!=", "599", ":", "status_code", "=", "(", "int", "(", "status_cod...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
CounterValue.to_dict
Dump counters as a dict
pyspider/libs/counter.py
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): """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 ...
[ "Dump", "counters", "as", "a", "dict" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L316-L326
[ "def", "to_dict", "(", "self", ",", "get_value", "=", "None", ")", ":", "result", "=", "{", "}", "for", "key", ",", "value", "in", "iteritems", "(", "self", ")", ":", "if", "isinstance", "(", "value", ",", "BaseCounter", ")", ":", "if", "get_value", ...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
CounterManager.value
Set value of a counter by counter key
pyspider/libs/counter.py
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): """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:...
[ "Set", "value", "of", "a", "counter", "by", "counter", "key" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L355-L364
[ "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", ...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
CounterManager.trim
Clear not used counters
pyspider/libs/counter.py
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): """Clear not used counters""" for key, value in list(iteritems(self.counters)): if value.empty(): del self.counters[key]
[ "Clear", "not", "used", "counters" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L366-L370
[ "def", "trim", "(", "self", ")", ":", "for", "key", ",", "value", "in", "list", "(", "iteritems", "(", "self", ".", "counters", ")", ")", ":", "if", "value", ".", "empty", "(", ")", ":", "del", "self", ".", "counters", "[", "key", "]" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
CounterManager.to_dict
Dump counters as a dict
pyspider/libs/counter.py
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): """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]: ...
[ "Dump", "counters", "as", "a", "dict" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L410-L421
[ "def", "to_dict", "(", "self", ",", "get_value", "=", "None", ")", ":", "self", ".", "trim", "(", ")", "result", "=", "{", "}", "for", "key", ",", "value", "in", "iteritems", "(", "self", ".", "counters", ")", ":", "if", "get_value", "is", "not", ...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
CounterManager.dump
Dump counters to file
pyspider/libs/counter.py
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): """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...
[ "Dump", "counters", "to", "file" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L423-L431
[ "def", "dump", "(", "self", ",", "filename", ")", ":", "try", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "fp", ":", "cPickle", ".", "dump", "(", "self", ".", "counters", ",", "fp", ")", "except", "Exception", "as", "e", ":", "l...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
CounterManager.load
Load counters to file
pyspider/libs/counter.py
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): """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
[ "Load", "counters", "to", "file" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/counter.py#L433-L441
[ "def", "load", "(", "self", ",", "filename", ")", ":", "try", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fp", ":", "self", ".", "counters", "=", "cPickle", ".", "load", "(", "fp", ")", "except", ":", "logging", ".", "debug", "...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
cli
A powerful spider system in python.
pyspider/run.py
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): """ 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: ...
[ "A", "powerful", "spider", "system", "in", "python", "." ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L91-L173
[ "def", "cli", "(", "ctx", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", "[", "'add_sys_path'", "]", ":", "sys", ".", "path", ".", "append", "(", "os", ".", "getcwd", "(", ")", ")", "logging", ".", "config", ".", "fileConfig", "(", "kwargs", ...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
scheduler
Run Scheduler, only one scheduler is allowed.
pyspider/run.py
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. """ g = ctx.obj Scheduler = load_cls(None, None, schedul...
[ "Run", "Scheduler", "only", "one", "scheduler", "is", "allowed", "." ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L192-L220
[ "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",...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
fetcher
Run Fetcher.
pyspider/run.py
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_mode=True, get_object=False, no_input=False): """ Run Fetcher. """ g = ctx.obj Fetcher = load_cls(None, None, f...
[ "Run", "Fetcher", "." ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L237-L269
[ "def", "fetcher", "(", "ctx", ",", "xmlrpc", ",", "xmlrpc_host", ",", "xmlrpc_port", ",", "poolsize", ",", "proxy", ",", "user_agent", ",", "timeout", ",", "phantomjs_endpoint", ",", "puppeteer_endpoint", ",", "splash_endpoint", ",", "fetcher_cls", ",", "async_m...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
processor
Run Processor.
pyspider/run.py
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): """ Run Processor. """ g = ctx.obj Processor = load_cls(None, None, processor_cls) processor = Processor(projectdb=g.projectdb, inqueue=g.fetcher2processor, status_queu...
[ "Run", "Processor", "." ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L277-L294
[ "def", "processor", "(", "ctx", ",", "processor_cls", ",", "process_time_limit", ",", "enable_stdout_capture", "=", "True", ",", "get_object", "=", "False", ")", ":", "g", "=", "ctx", ".", "obj", "Processor", "=", "load_cls", "(", "None", ",", "None", ",",...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
result_worker
Run result worker.
pyspider/run.py
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): """ 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...
[ "Run", "result", "worker", "." ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L301-L314
[ "def", "result_worker", "(", "ctx", ",", "result_cls", ",", "get_object", "=", "False", ")", ":", "g", "=", "ctx", ".", "obj", "ResultWorker", "=", "load_cls", "(", "None", ",", "None", ",", "result_cls", ")", "result_worker", "=", "ResultWorker", "(", "...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
webui
Run WebUI
pyspider/run.py
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_object=False): """ Run WebUI """ app = load_cls(None, None, webui_instance) g = ctx.obj app.config['taskdb'] = g.taskdb app.confi...
[ "Run", "WebUI" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L337-L393
[ "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...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
phantomjs
Run phantomjs fetcher if phantomjs is installed.
pyspider/run.py
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): """ 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...
[ "Run", "phantomjs", "fetcher", "if", "phantomjs", "is", "installed", "." ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L402-L443
[ "def", "phantomjs", "(", "ctx", ",", "phantomjs_path", ",", "port", ",", "auto_restart", ",", "args", ")", ":", "args", "=", "args", "or", "ctx", ".", "default_map", "and", "ctx", ".", "default_map", ".", "get", "(", "'args'", ",", "[", "]", ")", "im...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
puppeteer
Run puppeteer fetcher if puppeteer is installed.
pyspider/run.py
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): """ 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,...
[ "Run", "puppeteer", "fetcher", "if", "puppeteer", "is", "installed", "." ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L450-L486
[ "def", "puppeteer", "(", "ctx", ",", "port", ",", "auto_restart", ",", "args", ")", ":", "import", "subprocess", "g", "=", "ctx", ".", "obj", "_quit", "=", "[", "]", "puppeteer_fetcher", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
all
Run all the components in subprocess or thread
pyspider/run.py
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): """ 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...
[ "Run", "all", "the", "components", "in", "subprocess", "or", "thread" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L498-L570
[ "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", ...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
bench
Run Benchmark test. In bench mode, in-memory sqlite database is used instead of on-disk sqlite database.
pyspider/run.py
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): """ 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...
[ "Run", "Benchmark", "test", ".", "In", "bench", "mode", "in", "-", "memory", "sqlite", "database", "is", "used", "instead", "of", "on", "-", "disk", "sqlite", "database", "." ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L589-L711
[ "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", ...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
one
One mode not only means all-in-one, it runs every thing in one process over tornado.ioloop, for debug purpose
pyspider/run.py
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): """ 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....
[ "One", "mode", "not", "only", "means", "all", "-", "in", "-", "one", "it", "runs", "every", "thing", "in", "one", "process", "over", "tornado", ".", "ioloop", "for", "debug", "purpose" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L723-L793
[ "def", "one", "(", "ctx", ",", "interactive", ",", "enable_phantomjs", ",", "enable_puppeteer", ",", "scripts", ")", ":", "ctx", ".", "obj", "[", "'debug'", "]", "=", "False", "g", "=", "ctx", ".", "obj", "g", "[", "'testing_mode'", "]", "=", "True", ...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
send_message
Send Message to project from command line
pyspider/run.py
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): """ 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...
[ "Send", "Message", "to", "project", "from", "command", "line" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L801-L823
[ "def", "send_message", "(", "ctx", ",", "scheduler_rpc", ",", "project", ",", "message", ")", ":", "if", "isinstance", "(", "scheduler_rpc", ",", "six", ".", "string_types", ")", ":", "scheduler_rpc", "=", "connect_rpc", "(", "ctx", ",", "None", ",", "sche...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
pprint
Pretty-print a Python object to a stream [default is sys.stdout].
pyspider/libs/pprint.py
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): """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)
[ "Pretty", "-", "print", "a", "Python", "object", "to", "a", "stream", "[", "default", "is", "sys", ".", "stdout", "]", "." ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/pprint.py#L54-L58
[ "def", "pprint", "(", "object", ",", "stream", "=", "None", ",", "indent", "=", "1", ",", "width", "=", "80", ",", "depth", "=", "None", ")", ":", "printer", "=", "PrettyPrinter", "(", "stream", "=", "stream", ",", "indent", "=", "indent", ",", "wi...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
pformat
Format a Python object into a pretty-printed representation.
pyspider/libs/pprint.py
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): """Format a Python object into a pretty-printed representation.""" return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
[ "Format", "a", "Python", "object", "into", "a", "pretty", "-", "printed", "representation", "." ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/pprint.py#L61-L63
[ "def", "pformat", "(", "object", ",", "indent", "=", "1", ",", "width", "=", "80", ",", "depth", "=", "None", ")", ":", "return", "PrettyPrinter", "(", "indent", "=", "indent", ",", "width", "=", "width", ",", "depth", "=", "depth", ")", ".", "pfor...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
PrettyPrinter.format
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.
pyspider/libs/pprint.py
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): """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...
[ "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", "." ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/pprint.py#L243-L248
[ "def", "format", "(", "self", ",", "object", ",", "context", ",", "maxlevels", ",", "level", ")", ":", "return", "_safe_repr", "(", "object", ",", "context", ",", "maxlevels", ",", "level", ")" ]
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
ResultWorker.on_result
Called every result
pyspider/result/result_worker.py
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): '''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...
[ "Called", "every", "result" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/result/result_worker.py#L27-L42
[ "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...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
ResultWorker.run
Run loop
pyspider/result/result_worker.py
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): '''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 ...
[ "Run", "loop" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/result/result_worker.py#L47-L66
[ "def", "run", "(", "self", ")", ":", "logger", ".", "info", "(", "\"result_worker starting...\"", ")", "while", "not", "self", ".", "_quit", ":", "try", ":", "task", ",", "result", "=", "self", ".", "inqueue", ".", "get", "(", "timeout", "=", "1", ")...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
OneResultWorker.on_result
Called every result
pyspider/result/result_worker.py
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): '''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...
[ "Called", "every", "result" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/result/result_worker.py#L71-L87
[ "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...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
Bucket.get
Get the number of tokens in bucket
pyspider/scheduler/token_bucket.py
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): '''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...
[ "Get", "the", "number", "of", "tokens", "in", "bucket" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/scheduler/token_bucket.py#L33-L47
[ "def", "get", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "if", "self", ".", "bucket", ">=", "self", ".", "burst", ":", "self", ".", "last_update", "=", "now", "return", "self", ".", "bucket", "bucket", "=", "self", ".", "ra...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
migrate
Migrate tool for pyspider
tools/migrate.py
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): """ 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: ...
[ "Migrate", "tool", "for", "pyspider" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/tools/migrate.py#L43-L65
[ "def", "migrate", "(", "pool", ",", "from_connection", ",", "to_connection", ")", ":", "f", "=", "connect_database", "(", "from_connection", ")", "t", "=", "connect_database", "(", "to_connection", ")", "if", "isinstance", "(", "f", ",", "ProjectDB", ")", ":...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
encode
Encode data to DataURL
pyspider/libs/dataurl.py
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): """ 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))...
[ "Encode", "data", "to", "DataURL" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/dataurl.py#L14-L38
[ "def", "encode", "(", "data", ",", "mime_type", "=", "''", ",", "charset", "=", "'utf-8'", ",", "base64", "=", "True", ")", ":", "if", "isinstance", "(", "data", ",", "six", ".", "text_type", ")", ":", "data", "=", "data", ".", "encode", "(", "char...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
decode
Decode DataURL data
pyspider/libs/dataurl.py
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): """ 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...
[ "Decode", "DataURL", "data" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/dataurl.py#L41-L56
[ "def", "decode", "(", "data_url", ")", ":", "metadata", ",", "data", "=", "data_url", ".", "rsplit", "(", "','", ",", "1", ")", "_", ",", "metadata", "=", "metadata", ".", "split", "(", "'data:'", ",", "1", ")", "parts", "=", "metadata", ".", "spli...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
_build_url
Build the actual URL to use.
pyspider/libs/url.py
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): """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, ...
[ "Build", "the", "actual", "URL", "to", "use", "." ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/url.py#L29-L59
[ "def", "_build_url", "(", "url", ",", "_params", ")", ":", "# Support for unicode domain names and paths.", "scheme", ",", "netloc", ",", "path", ",", "params", ",", "query", ",", "fragment", "=", "urlparse", "(", "url", ")", "netloc", "=", "netloc", ".", "e...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
quote_chinese
Quote non-ascii characters
pyspider/libs/url.py
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"): """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...
[ "Quote", "non", "-", "ascii", "characters" ]
binux/pyspider
python
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/url.py#L62-L70
[ "def", "quote_chinese", "(", "url", ",", "encodeing", "=", "\"utf-8\"", ")", ":", "if", "isinstance", "(", "url", ",", "six", ".", "text_type", ")", ":", "return", "quote_chinese", "(", "url", ".", "encode", "(", "encodeing", ")", ")", "if", "six", "."...
3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9
train
DownloadResource
Downloads resources from s3 by url and unzips them to the provided path
examples/demo_caffe2.py
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): '''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)) ...
[ "Downloads", "resources", "from", "s3", "by", "url", "and", "unzips", "them", "to", "the", "provided", "path" ]
lanpa/tensorboardX
python
https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L28-L37
[ "def", "DownloadResource", "(", "url", ",", "path", ")", ":", "import", "requests", "from", "six", "import", "BytesIO", "import", "zipfile", "print", "(", "\"Downloading... {} to {}\"", ".", "format", "(", "url", ",", "path", ")", ")", "r", "=", "requests", ...
0bf6c07d97b0745654fd9fab8ee3261ec707f253
train
AddLeNetModel
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...
examples/demo_caffe2.py
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): ''' 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...
[ "This", "part", "is", "the", "standard", "LeNet", "model", ":", "from", "data", "to", "the", "softmax", "prediction", "." ]
lanpa/tensorboardX
python
https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L102-L127
[ "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", ...
0bf6c07d97b0745654fd9fab8ee3261ec707f253
train
AddAccuracy
Adds an accuracy op to the model
examples/demo_caffe2.py
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): """Adds an accuracy op to the model""" accuracy = brew.accuracy(model, [softmax, label], "accuracy") return accuracy
[ "Adds", "an", "accuracy", "op", "to", "the", "model" ]
lanpa/tensorboardX
python
https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L130-L133
[ "def", "AddAccuracy", "(", "model", ",", "softmax", ",", "label", ")", ":", "accuracy", "=", "brew", ".", "accuracy", "(", "model", ",", "[", "softmax", ",", "label", "]", ",", "\"accuracy\"", ")", "return", "accuracy" ]
0bf6c07d97b0745654fd9fab8ee3261ec707f253
train
AddTrainingOperators
Adds training operators to the model.
examples/demo_caffe2.py
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): """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...
[ "Adds", "training", "operators", "to", "the", "model", "." ]
lanpa/tensorboardX
python
https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L136-L160
[ "def", "AddTrainingOperators", "(", "model", ",", "softmax", ",", "label", ")", ":", "xent", "=", "model", ".", "LabelCrossEntropy", "(", "[", "softmax", ",", "label", "]", ",", "'xent'", ")", "# compute the expected loss", "loss", "=", "model", ".", "Averag...
0bf6c07d97b0745654fd9fab8ee3261ec707f253
train
AddBookkeepingOperators
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.
examples/demo_caffe2.py
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): """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...
[ "This", "adds", "a", "few", "bookkeeping", "operators", "that", "we", "can", "inspect", "later", "." ]
lanpa/tensorboardX
python
https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/demo_caffe2.py#L163-L178
[ "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'", ",", "[...
0bf6c07d97b0745654fd9fab8ee3261ec707f253
train
VAE.get_loss_func
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 ...
examples/chainer/plain_logger/net.py
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): """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...
[ "Get", "loss", "function", "of", "VAE", "." ]
lanpa/tensorboardX
python
https://github.com/lanpa/tensorboardX/blob/0bf6c07d97b0745654fd9fab8ee3261ec707f253/examples/chainer/plain_logger/net.py#L41-L65
[ "def", "get_loss_func", "(", "self", ",", "C", "=", "1.0", ",", "k", "=", "1", ")", ":", "def", "lf", "(", "x", ")", ":", "mu", ",", "ln_var", "=", "self", ".", "encode", "(", "x", ")", "batchsize", "=", "len", "(", "mu", ".", "data", ")", ...
0bf6c07d97b0745654fd9fab8ee3261ec707f253
train
Agent.fit
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 ...
rl/core.py
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, log_interval=10000, nb_max_episode_steps=None): """Trains the agent on the given environment. # Arguments env: (`Env` instance)...
[ "Trains", "the", "agent", "on", "the", "given", "environment", "." ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/core.py#L53-L238
[ "def", "fit", "(", "self", ",", "env", ",", "nb_steps", ",", "action_repetition", "=", "1", ",", "callbacks", "=", "None", ",", "verbose", "=", "1", ",", "visualize", "=", "False", ",", "nb_max_start_steps", "=", "0", ",", "start_step_policy", "=", "None...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
Processor.process_step
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...
rl/core.py
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): """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...
[ "Processes", "an", "entire", "step", "by", "applying", "the", "processor", "to", "the", "observation", "reward", "and", "info", "arguments", "." ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/core.py#L511-L526
[ "def", "process_step", "(", "self", ",", "observation", ",", "reward", ",", "done", ",", "info", ")", ":", "observation", "=", "self", ".", "process_observation", "(", "observation", ")", "reward", "=", "self", ".", "process_reward", "(", "reward", ")", "i...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
LinearAnnealedPolicy.get_current_value
Return current annealing value # Returns Value to use in annealing
rl/policy.py
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): """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...
[ "Return", "current", "annealing", "value" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L62-L75
[ "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", ...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
LinearAnnealedPolicy.select_action
Choose an action to perform # Returns Action to take (int)
rl/policy.py
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): """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)
[ "Choose", "an", "action", "to", "perform" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L77-L84
[ "def", "select_action", "(", "self", ",", "*", "*", "kwargs", ")", ":", "setattr", "(", "self", ".", "inner_policy", ",", "self", ".", "attr", ",", "self", ".", "get_current_value", "(", ")", ")", "return", "self", ".", "inner_policy", ".", "select_actio...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
LinearAnnealedPolicy.get_config
Return configurations of LinearAnnealedPolicy # Returns Dict of config
rl/policy.py
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): """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...
[ "Return", "configurations", "of", "LinearAnnealedPolicy" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L105-L118
[ "def", "get_config", "(", "self", ")", ":", "config", "=", "super", "(", "LinearAnnealedPolicy", ",", "self", ")", ".", "get_config", "(", ")", "config", "[", "'attr'", "]", "=", "self", ".", "attr", "config", "[", "'value_max'", "]", "=", "self", ".",...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
SoftmaxPolicy.select_action
Return the selected action # Arguments probs (np.ndarray) : Probabilty for each action # Returns action
rl/policy.py
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): """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
[ "Return", "the", "selected", "action" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L128-L139
[ "def", "select_action", "(", "self", ",", "nb_actions", ",", "probs", ")", ":", "action", "=", "np", ".", "random", ".", "choice", "(", "range", "(", "nb_actions", ")", ",", "p", "=", "probs", ")", "return", "action" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
EpsGreedyQPolicy.select_action
Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action
rl/policy.py
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): """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...
[ "Return", "the", "selected", "action" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L153-L169
[ "def", "select_action", "(", "self", ",", "q_values", ")", ":", "assert", "q_values", ".", "ndim", "==", "1", "nb_actions", "=", "q_values", ".", "shape", "[", "0", "]", "if", "np", ".", "random", ".", "uniform", "(", ")", "<", "self", ".", "eps", ...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
EpsGreedyQPolicy.get_config
Return configurations of EpsGreedyQPolicy # Returns Dict of config
rl/policy.py
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): """Return configurations of EpsGreedyQPolicy # Returns Dict of config """ config = super(EpsGreedyQPolicy, self).get_config() config['eps'] = self.eps return config
[ "Return", "configurations", "of", "EpsGreedyQPolicy" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L171-L179
[ "def", "get_config", "(", "self", ")", ":", "config", "=", "super", "(", "EpsGreedyQPolicy", ",", "self", ")", ".", "get_config", "(", ")", "config", "[", "'eps'", "]", "=", "self", ".", "eps", "return", "config" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
GreedyQPolicy.select_action
Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action
rl/policy.py
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): """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 ...
[ "Return", "the", "selected", "action" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L187-L198
[ "def", "select_action", "(", "self", ",", "q_values", ")", ":", "assert", "q_values", ".", "ndim", "==", "1", "action", "=", "np", ".", "argmax", "(", "q_values", ")", "return", "action" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
BoltzmannQPolicy.get_config
Return configurations of BoltzmannQPolicy # Returns Dict of config
rl/policy.py
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): """Return configurations of BoltzmannQPolicy # Returns Dict of config """ config = super(BoltzmannQPolicy, self).get_config() config['tau'] = self.tau config['clip'] = self.clip return config
[ "Return", "configurations", "of", "BoltzmannQPolicy" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L230-L239
[ "def", "get_config", "(", "self", ")", ":", "config", "=", "super", "(", "BoltzmannQPolicy", ",", "self", ")", ".", "get_config", "(", ")", "config", "[", "'tau'", "]", "=", "self", ".", "tau", "config", "[", "'clip'", "]", "=", "self", ".", "clip", ...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
MaxBoltzmannQPolicy.select_action
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...
rl/policy.py
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): """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...
[ "Return", "the", "selected", "action", "The", "selected", "action", "follows", "the", "BoltzmannQPolicy", "with", "probability", "epsilon", "or", "return", "the", "Greedy", "Policy", "with", "probability", "(", "1", "-", "epsilon", ")" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L257-L278
[ "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", "."...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
MaxBoltzmannQPolicy.get_config
Return configurations of MaxBoltzmannQPolicy # Returns Dict of config
rl/policy.py
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): """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...
[ "Return", "configurations", "of", "MaxBoltzmannQPolicy" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L280-L290
[ "def", "get_config", "(", "self", ")", ":", "config", "=", "super", "(", "MaxBoltzmannQPolicy", ",", "self", ")", ".", "get_config", "(", ")", "config", "[", "'eps'", "]", "=", "self", ".", "eps", "config", "[", "'tau'", "]", "=", "self", ".", "tau",...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
BoltzmannGumbelQPolicy.select_action
Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action
rl/policy.py
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): """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 #...
[ "Return", "the", "selected", "action" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L314-L346
[ "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...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
BoltzmannGumbelQPolicy.get_config
Return configurations of BoltzmannGumbelQPolicy # Returns Dict of config
rl/policy.py
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): """Return configurations of BoltzmannGumbelQPolicy # Returns Dict of config """ config = super(BoltzmannGumbelQPolicy, self).get_config() config['C'] = self.C return config
[ "Return", "configurations", "of", "BoltzmannGumbelQPolicy" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/policy.py#L348-L356
[ "def", "get_config", "(", "self", ")", ":", "config", "=", "super", "(", "BoltzmannGumbelQPolicy", ",", "self", ")", ".", "get_config", "(", ")", "config", "[", "'C'", "]", "=", "self", ".", "C", "return", "config" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
CallbackList._set_env
Set environment for each callback in callbackList
rl/callbacks.py
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): """ Set environment for each callback in callbackList """ for callback in self.callbacks: if callable(getattr(callback, '_set_env', None)): callback._set_env(env)
[ "Set", "environment", "for", "each", "callback", "in", "callbackList" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L45-L49
[ "def", "_set_env", "(", "self", ",", "env", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "if", "callable", "(", "getattr", "(", "callback", ",", "'_set_env'", ",", "None", ")", ")", ":", "callback", ".", "_set_env", "(", "env", "...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
CallbackList.on_episode_begin
Called at beginning of each episode for each callback in callbackList
rl/callbacks.py
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={}): """ 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 ...
[ "Called", "at", "beginning", "of", "each", "episode", "for", "each", "callback", "in", "callbackList" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L51-L59
[ "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...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
CallbackList.on_episode_end
Called at end of each episode for each callback in callbackList
rl/callbacks.py
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={}): """ 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...
[ "Called", "at", "end", "of", "each", "episode", "for", "each", "callback", "in", "callbackList" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L61-L69
[ "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...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
CallbackList.on_step_begin
Called at beginning of each step for each callback in callbackList
rl/callbacks.py
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={}): """ 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...
[ "Called", "at", "beginning", "of", "each", "step", "for", "each", "callback", "in", "callbackList" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L71-L79
[ "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...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
CallbackList.on_step_end
Called at end of each step for each callback in callbackList
rl/callbacks.py
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={}): """ 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...
[ "Called", "at", "end", "of", "each", "step", "for", "each", "callback", "in", "callbackList" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L81-L89
[ "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...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
CallbackList.on_action_begin
Called at beginning of each action for each callback in callbackList
rl/callbacks.py
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={}): """ 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)
[ "Called", "at", "beginning", "of", "each", "action", "for", "each", "callback", "in", "callbackList" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L91-L95
[ "def", "on_action_begin", "(", "self", ",", "action", ",", "logs", "=", "{", "}", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "if", "callable", "(", "getattr", "(", "callback", ",", "'on_action_begin'", ",", "None", ")", ")", ":",...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
CallbackList.on_action_end
Called at end of each action for each callback in callbackList
rl/callbacks.py
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={}): """ 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)
[ "Called", "at", "end", "of", "each", "action", "for", "each", "callback", "in", "callbackList" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L97-L101
[ "def", "on_action_end", "(", "self", ",", "action", ",", "logs", "=", "{", "}", ")", ":", "for", "callback", "in", "self", ".", "callbacks", ":", "if", "callable", "(", "getattr", "(", "callback", ",", "'on_action_end'", ",", "None", ")", ")", ":", "...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
TrainEpisodeLogger.on_train_begin
Print training values at beginning of training
rl/callbacks.py
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): """ 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']))
[ "Print", "training", "values", "at", "beginning", "of", "training" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L133-L137
[ "def", "on_train_begin", "(", "self", ",", "logs", ")", ":", "self", ".", "train_start", "=", "timeit", ".", "default_timer", "(", ")", "self", ".", "metrics_names", "=", "self", ".", "model", ".", "metrics_names", "print", "(", "'Training for {} steps ...'", ...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
TrainEpisodeLogger.on_train_end
Print training time at end of training
rl/callbacks.py
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): """ Print training time at end of training """ duration = timeit.default_timer() - self.train_start print('done, took {:.3f} seconds'.format(duration))
[ "Print", "training", "time", "at", "end", "of", "training" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L139-L142
[ "def", "on_train_end", "(", "self", ",", "logs", ")", ":", "duration", "=", "timeit", ".", "default_timer", "(", ")", "-", "self", ".", "train_start", "print", "(", "'done, took {:.3f} seconds'", ".", "format", "(", "duration", ")", ")" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
TrainEpisodeLogger.on_episode_begin
Reset environment variables at beginning of each episode
rl/callbacks.py
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): """ 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] = [...
[ "Reset", "environment", "variables", "at", "beginning", "of", "each", "episode" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L144-L150
[ "def", "on_episode_begin", "(", "self", ",", "episode", ",", "logs", ")", ":", "self", ".", "episode_start", "[", "episode", "]", "=", "timeit", ".", "default_timer", "(", ")", "self", ".", "observations", "[", "episode", "]", "=", "[", "]", "self", "....
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
TrainEpisodeLogger.on_episode_end
Compute and print training statistics of the episode when done
rl/callbacks.py
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): """ 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...
[ "Compute", "and", "print", "training", "statistics", "of", "the", "episode", "when", "done" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L152-L203
[ "def", "on_episode_end", "(", "self", ",", "episode", ",", "logs", ")", ":", "duration", "=", "timeit", ".", "default_timer", "(", ")", "-", "self", ".", "episode_start", "[", "episode", "]", "episode_steps", "=", "len", "(", "self", ".", "observations", ...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
TrainEpisodeLogger.on_step_end
Update statistics of episode after each step
rl/callbacks.py
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): """ 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[...
[ "Update", "statistics", "of", "episode", "after", "each", "step" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L205-L212
[ "def", "on_step_end", "(", "self", ",", "step", ",", "logs", ")", ":", "episode", "=", "logs", "[", "'episode'", "]", "self", ".", "observations", "[", "episode", "]", ".", "append", "(", "logs", "[", "'observation'", "]", ")", "self", ".", "rewards", ...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
TrainIntervalLogger.reset
Reset statistics
rl/callbacks.py
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): """ 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 = []
[ "Reset", "statistics" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L221-L228
[ "def", "reset", "(", "self", ")", ":", "self", ".", "interval_start", "=", "timeit", ".", "default_timer", "(", ")", "self", ".", "progbar", "=", "Progbar", "(", "target", "=", "self", ".", "interval", ")", "self", ".", "metrics", "=", "[", "]", "sel...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
TrainIntervalLogger.on_step_begin
Print metrics if interval is over
rl/callbacks.py
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): """ 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)) ...
[ "Print", "metrics", "if", "interval", "is", "over" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L241-L265
[ "def", "on_step_begin", "(", "self", ",", "step", ",", "logs", ")", ":", "if", "self", ".", "step", "%", "self", ".", "interval", "==", "0", ":", "if", "len", "(", "self", ".", "episode_rewards", ")", ">", "0", ":", "metrics", "=", "np", ".", "ar...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
TrainIntervalLogger.on_step_end
Update progression bar at the end of each step
rl/callbacks.py
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): """ 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...
[ "Update", "progression", "bar", "at", "the", "end", "of", "each", "step" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L267-L279
[ "def", "on_step_end", "(", "self", ",", "step", ",", "logs", ")", ":", "if", "self", ".", "info_names", "is", "None", ":", "self", ".", "info_names", "=", "logs", "[", "'info'", "]", ".", "keys", "(", ")", "values", "=", "[", "(", "'reward'", ",", ...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
FileLogger.on_episode_begin
Initialize metrics at the beginning of each episode
rl/callbacks.py
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): """ 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()
[ "Initialize", "metrics", "at", "the", "beginning", "of", "each", "episode" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L305-L310
[ "def", "on_episode_begin", "(", "self", ",", "episode", ",", "logs", ")", ":", "assert", "episode", "not", "in", "self", ".", "metrics", "assert", "episode", "not", "in", "self", ".", "starts", "self", ".", "metrics", "[", "episode", "]", "=", "[", "]"...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
FileLogger.on_episode_end
Compute and print metrics at the end of each episode
rl/callbacks.py
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): """ 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...
[ "Compute", "and", "print", "metrics", "at", "the", "end", "of", "each", "episode" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L312-L336
[ "def", "on_episode_end", "(", "self", ",", "episode", ",", "logs", ")", ":", "duration", "=", "timeit", ".", "default_timer", "(", ")", "-", "self", ".", "starts", "[", "episode", "]", "metrics", "=", "self", ".", "metrics", "[", "episode", "]", "if", ...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
FileLogger.save_data
Save metrics in a json file
rl/callbacks.py
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): """ 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....
[ "Save", "metrics", "in", "a", "json", "file" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L342-L360
[ "def", "save_data", "(", "self", ")", ":", "if", "len", "(", "self", ".", "data", ".", "keys", "(", ")", ")", "==", "0", ":", "return", "# Sort everything by episode.", "assert", "'episode'", "in", "self", ".", "data", "sorted_indexes", "=", "np", ".", ...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
ModelIntervalCheckpoint.on_step_end
Save weights at interval steps during training
rl/callbacks.py
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={}): """ 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...
[ "Save", "weights", "at", "interval", "steps", "during", "training" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/callbacks.py#L377-L387
[ "def", "on_step_end", "(", "self", ",", "step", ",", "logs", "=", "{", "}", ")", ":", "self", ".", "total_steps", "+=", "1", "if", "self", ".", "total_steps", "%", "self", ".", "interval", "!=", "0", ":", "# Nothing to do.", "return", "filepath", "=", ...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
sample_batch_indexes
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...
rl/memory.py
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): """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...
[ "Return", "a", "sample", "of", "(", "size", ")", "unique", "elements", "between", "low", "and", "high" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/memory.py#L14-L42
[ "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...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
zeroed_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
rl/memory.py
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): """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...
[ "Return", "an", "array", "of", "zeros", "with", "same", "shape", "as", "given", "observation" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/memory.py#L85-L102
[ "def", "zeroed_observation", "(", "observation", ")", ":", "if", "hasattr", "(", "observation", ",", "'shape'", ")", ":", "return", "np", ".", "zeros", "(", "observation", ".", "shape", ")", "elif", "hasattr", "(", "observation", ",", "'__iter__'", ")", ":...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
Memory.get_recent_state
Return list of last observations # Argument current_observation (object): Last observation # Returns A list of the last observations
rl/memory.py
def get_recent_state(self, current_observation): """Return list of last observations # Argument current_observation (object): Last observation # Returns A list of the last observations """ # This code is slightly complicated by the fact that subsequent o...
def get_recent_state(self, current_observation): """Return list of last observations # Argument current_observation (object): Last observation # Returns A list of the last observations """ # This code is slightly complicated by the fact that subsequent o...
[ "Return", "list", "of", "last", "observations" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/memory.py#L120-L144
[ "def", "get_recent_state", "(", "self", ",", "current_observation", ")", ":", "# This code is slightly complicated by the fact that subsequent observations might be", "# from different episodes. We ensure that an experience never spans multiple episodes.", "# This is probably not that important ...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
SequentialMemory.sample
Return a randomized batch of experiences # Argument batch_size (int): Size of the all batch batch_idxs (int): Indexes to extract # Returns A list of experiences randomly selected
rl/memory.py
def sample(self, batch_size, batch_idxs=None): """Return a randomized batch of experiences # Argument batch_size (int): Size of the all batch batch_idxs (int): Indexes to extract # Returns A list of experiences randomly selected """ # It is no...
def sample(self, batch_size, batch_idxs=None): """Return a randomized batch of experiences # Argument batch_size (int): Size of the all batch batch_idxs (int): Indexes to extract # Returns A list of experiences randomly selected """ # It is no...
[ "Return", "a", "randomized", "batch", "of", "experiences" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/memory.py#L171-L239
[ "def", "sample", "(", "self", ",", "batch_size", ",", "batch_idxs", "=", "None", ")", ":", "# It is not possible to tell whether the first state in the memory is terminal, because it", "# would require access to the \"terminal\" flag associated to the previous state. As a result", "# we ...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
SequentialMemory.append
Append an observation to the memory # Argument observation (dict): Observation returned by environment action (int): Action taken to obtain this observation reward (float): Reward obtained by taking this action terminal (boolean): Is the state terminal
rl/memory.py
def append(self, observation, action, reward, terminal, training=True): """Append an observation to the memory # Argument observation (dict): Observation returned by environment action (int): Action taken to obtain this observation reward (float): Reward obtained by ...
def append(self, observation, action, reward, terminal, training=True): """Append an observation to the memory # Argument observation (dict): Observation returned by environment action (int): Action taken to obtain this observation reward (float): Reward obtained by ...
[ "Append", "an", "observation", "to", "the", "memory" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/memory.py#L241-L258
[ "def", "append", "(", "self", ",", "observation", ",", "action", ",", "reward", ",", "terminal", ",", "training", "=", "True", ")", ":", "super", "(", "SequentialMemory", ",", "self", ")", ".", "append", "(", "observation", ",", "action", ",", "reward", ...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
SequentialMemory.get_config
Return configurations of SequentialMemory # Returns Dict of config
rl/memory.py
def get_config(self): """Return configurations of SequentialMemory # Returns Dict of config """ config = super(SequentialMemory, self).get_config() config['limit'] = self.limit return config
def get_config(self): """Return configurations of SequentialMemory # Returns Dict of config """ config = super(SequentialMemory, self).get_config() config['limit'] = self.limit return config
[ "Return", "configurations", "of", "SequentialMemory" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/memory.py#L269-L277
[ "def", "get_config", "(", "self", ")", ":", "config", "=", "super", "(", "SequentialMemory", ",", "self", ")", ".", "get_config", "(", ")", "config", "[", "'limit'", "]", "=", "self", ".", "limit", "return", "config" ]
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
EpisodeParameterMemory.sample
Return a randomized batch of params and rewards # Argument batch_size (int): Size of the all batch batch_idxs (int): Indexes to extract # Returns A list of params randomly selected and a list of associated rewards
rl/memory.py
def sample(self, batch_size, batch_idxs=None): """Return a randomized batch of params and rewards # Argument batch_size (int): Size of the all batch batch_idxs (int): Indexes to extract # Returns A list of params randomly selected and a list of associated rew...
def sample(self, batch_size, batch_idxs=None): """Return a randomized batch of params and rewards # Argument batch_size (int): Size of the all batch batch_idxs (int): Indexes to extract # Returns A list of params randomly selected and a list of associated rew...
[ "Return", "a", "randomized", "batch", "of", "params", "and", "rewards" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/memory.py#L289-L307
[ "def", "sample", "(", "self", ",", "batch_size", ",", "batch_idxs", "=", "None", ")", ":", "if", "batch_idxs", "is", "None", ":", "batch_idxs", "=", "sample_batch_indexes", "(", "0", ",", "self", ".", "nb_entries", ",", "size", "=", "batch_size", ")", "a...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
EpisodeParameterMemory.append
Append a reward to the memory # Argument observation (dict): Observation returned by environment action (int): Action taken to obtain this observation reward (float): Reward obtained by taking this action terminal (boolean): Is the state terminal
rl/memory.py
def append(self, observation, action, reward, terminal, training=True): """Append a reward to the memory # Argument observation (dict): Observation returned by environment action (int): Action taken to obtain this observation reward (float): Reward obtained by taking...
def append(self, observation, action, reward, terminal, training=True): """Append a reward to the memory # Argument observation (dict): Observation returned by environment action (int): Action taken to obtain this observation reward (float): Reward obtained by taking...
[ "Append", "a", "reward", "to", "the", "memory" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/memory.py#L309-L320
[ "def", "append", "(", "self", ",", "observation", ",", "action", ",", "reward", ",", "terminal", ",", "training", "=", "True", ")", ":", "super", "(", "EpisodeParameterMemory", ",", "self", ")", ".", "append", "(", "observation", ",", "action", ",", "rew...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
EpisodeParameterMemory.finalize_episode
Closes the current episode, sums up rewards and stores the parameters # Argument params (object): Parameters associated with the episode to be stored and then retrieved back in sample()
rl/memory.py
def finalize_episode(self, params): """Closes the current episode, sums up rewards and stores the parameters # Argument params (object): Parameters associated with the episode to be stored and then retrieved back in sample() """ total_reward = sum(self.intermediate_rewards) ...
def finalize_episode(self, params): """Closes the current episode, sums up rewards and stores the parameters # Argument params (object): Parameters associated with the episode to be stored and then retrieved back in sample() """ total_reward = sum(self.intermediate_rewards) ...
[ "Closes", "the", "current", "episode", "sums", "up", "rewards", "and", "stores", "the", "parameters" ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/memory.py#L322-L331
[ "def", "finalize_episode", "(", "self", ",", "params", ")", ":", "total_reward", "=", "sum", "(", "self", ".", "intermediate_rewards", ")", "self", ".", "total_rewards", ".", "append", "(", "total_reward", ")", "self", ".", "params", ".", "append", "(", "p...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
make_gym_env
Create a wrapped, SubprocVecEnv for Gym Environments.
rl/common/cmd_util.py
def make_gym_env(env_id, num_env=2, seed=123, wrapper_kwargs=None, start_index=0): """ Create a wrapped, SubprocVecEnv for Gym Environments. """ if wrapper_kwargs is None: wrapper_kwargs = {} def make_env(rank): # pylint: disable=C0111 def _thunk(): env = gym.make(env_id...
def make_gym_env(env_id, num_env=2, seed=123, wrapper_kwargs=None, start_index=0): """ Create a wrapped, SubprocVecEnv for Gym Environments. """ if wrapper_kwargs is None: wrapper_kwargs = {} def make_env(rank): # pylint: disable=C0111 def _thunk(): env = gym.make(env_id...
[ "Create", "a", "wrapped", "SubprocVecEnv", "for", "Gym", "Environments", "." ]
keras-rl/keras-rl
python
https://github.com/keras-rl/keras-rl/blob/e6efb0d8297ec38d704a3110b5d6ed74d09a05e3/rl/common/cmd_util.py#L7-L22
[ "def", "make_gym_env", "(", "env_id", ",", "num_env", "=", "2", ",", "seed", "=", "123", ",", "wrapper_kwargs", "=", "None", ",", "start_index", "=", "0", ")", ":", "if", "wrapper_kwargs", "is", "None", ":", "wrapper_kwargs", "=", "{", "}", "def", "mak...
e6efb0d8297ec38d704a3110b5d6ed74d09a05e3
train
invoke_common_options
Common CLI options shared by "local invoke" and "local start-api" commands :param f: Callback passed by Click
samcli/commands/local/cli_common/options.py
def invoke_common_options(f): """ Common CLI options shared by "local invoke" and "local start-api" commands :param f: Callback passed by Click """ invoke_options = [ template_click_option(), click.option('--env-vars', '-n', type=click.Path(exists=True), ...
def invoke_common_options(f): """ Common CLI options shared by "local invoke" and "local start-api" commands :param f: Callback passed by Click """ invoke_options = [ template_click_option(), click.option('--env-vars', '-n', type=click.Path(exists=True), ...
[ "Common", "CLI", "options", "shared", "by", "local", "invoke", "and", "local", "start", "-", "api", "commands" ]
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/cli_common/options.py#L73-L130
[ "def", "invoke_common_options", "(", "f", ")", ":", "invoke_options", "=", "[", "template_click_option", "(", ")", ",", "click", ".", "option", "(", "'--env-vars'", ",", "'-n'", ",", "type", "=", "click", ".", "Path", "(", "exists", "=", "True", ")", ","...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
get_or_default_template_file_name
Default value for the template file name option is more complex than what Click can handle. This method either returns user provided file name or one of the two default options (template.yaml/template.yml) depending on the file that exists :param ctx: Click Context :param param: Param name :param p...
samcli/commands/_utils/options.py
def get_or_default_template_file_name(ctx, param, provided_value, include_build): """ Default value for the template file name option is more complex than what Click can handle. This method either returns user provided file name or one of the two default options (template.yaml/template.yml) depending on...
def get_or_default_template_file_name(ctx, param, provided_value, include_build): """ Default value for the template file name option is more complex than what Click can handle. This method either returns user provided file name or one of the two default options (template.yaml/template.yml) depending on...
[ "Default", "value", "for", "the", "template", "file", "name", "option", "is", "more", "complex", "than", "what", "Click", "can", "handle", ".", "This", "method", "either", "returns", "user", "provided", "file", "name", "or", "one", "of", "the", "two", "def...
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/_utils/options.py#L18-L50
[ "def", "get_or_default_template_file_name", "(", "ctx", ",", "param", ",", "provided_value", ",", "include_build", ")", ":", "search_paths", "=", "[", "\"template.yaml\"", ",", "\"template.yml\"", ",", "]", "if", "include_build", ":", "search_paths", ".", "insert", ...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
template_click_option
Click Option for template option
samcli/commands/_utils/options.py
def template_click_option(include_build=True): """ Click Option for template option """ return click.option('--template', '-t', default=_TEMPLATE_OPTION_DEFAULT_VALUE, type=click.Path(), envvar="SAM_TEMPLATE_FILE", ...
def template_click_option(include_build=True): """ Click Option for template option """ return click.option('--template', '-t', default=_TEMPLATE_OPTION_DEFAULT_VALUE, type=click.Path(), envvar="SAM_TEMPLATE_FILE", ...
[ "Click", "Option", "for", "template", "option" ]
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/_utils/options.py#L73-L83
[ "def", "template_click_option", "(", "include_build", "=", "True", ")", ":", "return", "click", ".", "option", "(", "'--template'", ",", "'-t'", ",", "default", "=", "_TEMPLATE_OPTION_DEFAULT_VALUE", ",", "type", "=", "click", ".", "Path", "(", ")", ",", "en...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
create_tarball
Context Manger that creates the tarball of the Docker Context to use for building the image Parameters ---------- tar_paths dict(str, str) Key representing a full path to the file or directory and the Value representing the path within the tarball Yields ------ The tarball file
samcli/lib/utils/tar.py
def create_tarball(tar_paths): """ Context Manger that creates the tarball of the Docker Context to use for building the image Parameters ---------- tar_paths dict(str, str) Key representing a full path to the file or directory and the Value representing the path within the tarball Yie...
def create_tarball(tar_paths): """ Context Manger that creates the tarball of the Docker Context to use for building the image Parameters ---------- tar_paths dict(str, str) Key representing a full path to the file or directory and the Value representing the path within the tarball Yie...
[ "Context", "Manger", "that", "creates", "the", "tarball", "of", "the", "Docker", "Context", "to", "use", "for", "building", "the", "image" ]
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/utils/tar.py#L11-L37
[ "def", "create_tarball", "(", "tar_paths", ")", ":", "tarballfile", "=", "TemporaryFile", "(", ")", "with", "tarfile", ".", "open", "(", "fileobj", "=", "tarballfile", ",", "mode", "=", "'w'", ")", "as", "archive", ":", "for", "path_on_system", ",", "path_...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
LocalLambdaService.start
Creates and starts the Local Lambda Invoke service. This method will block until the service is stopped manually using an interrupt. After the service is started, callers can make HTTP requests to the endpoint to invoke the Lambda function and receive a response. NOTE: This is a blocking call t...
samcli/commands/local/lib/local_lambda_service.py
def start(self): """ Creates and starts the Local Lambda Invoke service. This method will block until the service is stopped manually using an interrupt. After the service is started, callers can make HTTP requests to the endpoint to invoke the Lambda function and receive a response. ...
def start(self): """ Creates and starts the Local Lambda Invoke service. This method will block until the service is stopped manually using an interrupt. After the service is started, callers can make HTTP requests to the endpoint to invoke the Lambda function and receive a response. ...
[ "Creates", "and", "starts", "the", "Local", "Lambda", "Invoke", "service", ".", "This", "method", "will", "block", "until", "the", "service", "is", "stopped", "manually", "using", "an", "interrupt", ".", "After", "the", "service", "is", "started", "callers", ...
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/local_lambda_service.py#L35-L58
[ "def", "start", "(", "self", ")", ":", "# We care about passing only stderr to the Service and not stdout because stdout from Docker container", "# contains the response to the API which is sent out as HTTP response. Only stderr needs to be printed", "# to the console or a log file. stderr from Dock...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
SamFunctionProvider._extract_functions
Extracts and returns function information from the given dictionary of SAM/CloudFormation resources. This method supports functions defined with AWS::Serverless::Function and AWS::Lambda::Function :param dict resources: Dictionary of SAM/CloudFormation resources :return dict(string : samcli.com...
samcli/commands/local/lib/sam_function_provider.py
def _extract_functions(resources): """ Extracts and returns function information from the given dictionary of SAM/CloudFormation resources. This method supports functions defined with AWS::Serverless::Function and AWS::Lambda::Function :param dict resources: Dictionary of SAM/CloudForma...
def _extract_functions(resources): """ Extracts and returns function information from the given dictionary of SAM/CloudFormation resources. This method supports functions defined with AWS::Serverless::Function and AWS::Lambda::Function :param dict resources: Dictionary of SAM/CloudForma...
[ "Extracts", "and", "returns", "function", "information", "from", "the", "given", "dictionary", "of", "SAM", "/", "CloudFormation", "resources", ".", "This", "method", "supports", "functions", "defined", "with", "AWS", "::", "Serverless", "::", "Function", "and", ...
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_function_provider.py#L81-L108
[ "def", "_extract_functions", "(", "resources", ")", ":", "result", "=", "{", "}", "for", "name", ",", "resource", "in", "resources", ".", "items", "(", ")", ":", "resource_type", "=", "resource", ".", "get", "(", "\"Type\"", ")", "resource_properties", "="...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
SamFunctionProvider._convert_sam_function_resource
Converts a AWS::Serverless::Function resource to a Function configuration usable by the provider. :param string name: LogicalID of the resource NOTE: This is *not* the function name because not all functions declare a name :param dict resource_properties: Properties of this resource ...
samcli/commands/local/lib/sam_function_provider.py
def _convert_sam_function_resource(name, resource_properties, layers): """ Converts a AWS::Serverless::Function resource to a Function configuration usable by the provider. :param string name: LogicalID of the resource NOTE: This is *not* the function name because not all functions ...
def _convert_sam_function_resource(name, resource_properties, layers): """ Converts a AWS::Serverless::Function resource to a Function configuration usable by the provider. :param string name: LogicalID of the resource NOTE: This is *not* the function name because not all functions ...
[ "Converts", "a", "AWS", "::", "Serverless", "::", "Function", "resource", "to", "a", "Function", "configuration", "usable", "by", "the", "provider", "." ]
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_function_provider.py#L111-L135
[ "def", "_convert_sam_function_resource", "(", "name", ",", "resource_properties", ",", "layers", ")", ":", "codeuri", "=", "SamFunctionProvider", ".", "_extract_sam_function_codeuri", "(", "name", ",", "resource_properties", ",", "\"CodeUri\"", ")", "LOG", ".", "debug...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
SamFunctionProvider._extract_sam_function_codeuri
Extracts the SAM Function CodeUri from the Resource Properties Parameters ---------- name str LogicalId of the resource resource_properties dict Dictionary representing the Properties of the Resource code_property_key str Property Key of the c...
samcli/commands/local/lib/sam_function_provider.py
def _extract_sam_function_codeuri(name, resource_properties, code_property_key): """ Extracts the SAM Function CodeUri from the Resource Properties Parameters ---------- name str LogicalId of the resource resource_properties dict Dictionary repres...
def _extract_sam_function_codeuri(name, resource_properties, code_property_key): """ Extracts the SAM Function CodeUri from the Resource Properties Parameters ---------- name str LogicalId of the resource resource_properties dict Dictionary repres...
[ "Extracts", "the", "SAM", "Function", "CodeUri", "from", "the", "Resource", "Properties" ]
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_function_provider.py#L138-L163
[ "def", "_extract_sam_function_codeuri", "(", "name", ",", "resource_properties", ",", "code_property_key", ")", ":", "codeuri", "=", "resource_properties", ".", "get", "(", "code_property_key", ",", "SamFunctionProvider", ".", "_DEFAULT_CODEURI", ")", "# CodeUri can be a ...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
SamFunctionProvider._convert_lambda_function_resource
Converts a AWS::Serverless::Function resource to a Function configuration usable by the provider. :param string name: LogicalID of the resource NOTE: This is *not* the function name because not all functions declare a name :param dict resource_properties: Properties of this resource ...
samcli/commands/local/lib/sam_function_provider.py
def _convert_lambda_function_resource(name, resource_properties, layers): # pylint: disable=invalid-name """ Converts a AWS::Serverless::Function resource to a Function configuration usable by the provider. :param string name: LogicalID of the resource NOTE: This is *not* the function name bec...
def _convert_lambda_function_resource(name, resource_properties, layers): # pylint: disable=invalid-name """ Converts a AWS::Serverless::Function resource to a Function configuration usable by the provider. :param string name: LogicalID of the resource NOTE: This is *not* the function name bec...
[ "Converts", "a", "AWS", "::", "Serverless", "::", "Function", "resource", "to", "a", "Function", "configuration", "usable", "by", "the", "provider", "." ]
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_function_provider.py#L166-L192
[ "def", "_convert_lambda_function_resource", "(", "name", ",", "resource_properties", ",", "layers", ")", ":", "# pylint: disable=invalid-name", "# CodeUri is set to \".\" in order to get code locally from current directory. AWS::Lambda::Function's ``Code``", "# property does not support spec...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
SamFunctionProvider._extract_lambda_function_code
Extracts the Lambda Function Code from the Resource Properties Parameters ---------- resource_properties dict Dictionary representing the Properties of the Resource code_property_key str Property Key of the code on the Resource Returns ------- ...
samcli/commands/local/lib/sam_function_provider.py
def _extract_lambda_function_code(resource_properties, code_property_key): """ Extracts the Lambda Function Code from the Resource Properties Parameters ---------- resource_properties dict Dictionary representing the Properties of the Resource code_property_k...
def _extract_lambda_function_code(resource_properties, code_property_key): """ Extracts the Lambda Function Code from the Resource Properties Parameters ---------- resource_properties dict Dictionary representing the Properties of the Resource code_property_k...
[ "Extracts", "the", "Lambda", "Function", "Code", "from", "the", "Resource", "Properties" ]
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_function_provider.py#L195-L217
[ "def", "_extract_lambda_function_code", "(", "resource_properties", ",", "code_property_key", ")", ":", "codeuri", "=", "resource_properties", ".", "get", "(", "code_property_key", ",", "SamFunctionProvider", ".", "_DEFAULT_CODEURI", ")", "if", "isinstance", "(", "codeu...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
SamFunctionProvider._parse_layer_info
Creates a list of Layer objects that are represented by the resources and the list of layers Parameters ---------- list_of_layers List(str) List of layers that are defined within the Layers Property on a function resources dict The Resources dictionary defined in...
samcli/commands/local/lib/sam_function_provider.py
def _parse_layer_info(list_of_layers, resources): """ Creates a list of Layer objects that are represented by the resources and the list of layers Parameters ---------- list_of_layers List(str) List of layers that are defined within the Layers Property on a function ...
def _parse_layer_info(list_of_layers, resources): """ Creates a list of Layer objects that are represented by the resources and the list of layers Parameters ---------- list_of_layers List(str) List of layers that are defined within the Layers Property on a function ...
[ "Creates", "a", "list", "of", "Layer", "objects", "that", "are", "represented", "by", "the", "resources", "and", "the", "list", "of", "layers" ]
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/sam_function_provider.py#L220-L270
[ "def", "_parse_layer_info", "(", "list_of_layers", ",", "resources", ")", ":", "layers", "=", "[", "]", "for", "layer", "in", "list_of_layers", ":", "# If the layer is a string, assume it is the arn", "if", "isinstance", "(", "layer", ",", "six", ".", "string_types"...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
EnvironmentVariables.resolve
Resolves the values from different sources and returns a dict of environment variables to use when running the function locally. :return dict: Dict where key is the variable name and value is the value of the variable. Both key and values are strings
samcli/local/lambdafn/env_vars.py
def resolve(self): """ Resolves the values from different sources and returns a dict of environment variables to use when running the function locally. :return dict: Dict where key is the variable name and value is the value of the variable. Both key and values are strings ...
def resolve(self): """ Resolves the values from different sources and returns a dict of environment variables to use when running the function locally. :return dict: Dict where key is the variable name and value is the value of the variable. Both key and values are strings ...
[ "Resolves", "the", "values", "from", "different", "sources", "and", "returns", "a", "dict", "of", "environment", "variables", "to", "use", "when", "running", "the", "function", "locally", "." ]
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/env_vars.py#L77-L104
[ "def", "resolve", "(", "self", ")", ":", "# AWS_* variables must always be passed to the function, but user has the choice to override them", "result", "=", "self", ".", "_get_aws_variables", "(", ")", "# Default value for the variable gets lowest priority", "for", "name", ",", "...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
EnvironmentVariables._get_aws_variables
Returns the AWS specific environment variables that should be available in the Lambda runtime. They are prefixed it "AWS_*". :return dict: Name and value of AWS environment variable
samcli/local/lambdafn/env_vars.py
def _get_aws_variables(self): """ Returns the AWS specific environment variables that should be available in the Lambda runtime. They are prefixed it "AWS_*". :return dict: Name and value of AWS environment variable """ result = { # Variable that says this f...
def _get_aws_variables(self): """ Returns the AWS specific environment variables that should be available in the Lambda runtime. They are prefixed it "AWS_*". :return dict: Name and value of AWS environment variable """ result = { # Variable that says this f...
[ "Returns", "the", "AWS", "specific", "environment", "variables", "that", "should", "be", "available", "in", "the", "Lambda", "runtime", ".", "They", "are", "prefixed", "it", "AWS_", "*", "." ]
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/env_vars.py#L136-L173
[ "def", "_get_aws_variables", "(", "self", ")", ":", "result", "=", "{", "# Variable that says this function is running in Local Lambda", "\"AWS_SAM_LOCAL\"", ":", "\"true\"", ",", "# Function configuration", "\"AWS_LAMBDA_FUNCTION_MEMORY_SIZE\"", ":", "str", "(", "self", ".",...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
EnvironmentVariables._stringify_value
This method stringifies values of environment variables. If the value of the method is a list or dictionary, then this method will replace it with empty string. Values of environment variables in Lambda must be a string. List or dictionary usually means they are intrinsic functions which have not been r...
samcli/local/lambdafn/env_vars.py
def _stringify_value(self, value): """ This method stringifies values of environment variables. If the value of the method is a list or dictionary, then this method will replace it with empty string. Values of environment variables in Lambda must be a string. List or dictionary usually m...
def _stringify_value(self, value): """ This method stringifies values of environment variables. If the value of the method is a list or dictionary, then this method will replace it with empty string. Values of environment variables in Lambda must be a string. List or dictionary usually m...
[ "This", "method", "stringifies", "values", "of", "environment", "variables", ".", "If", "the", "value", "of", "the", "method", "is", "a", "list", "or", "dictionary", "then", "this", "method", "will", "replace", "it", "with", "empty", "string", ".", "Values",...
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/env_vars.py#L175-L204
[ "def", "_stringify_value", "(", "self", ",", "value", ")", ":", "# List/dict/None values are replaced with a blank", "if", "isinstance", "(", "value", ",", "(", "dict", ",", "list", ",", "tuple", ")", ")", "or", "value", "is", "None", ":", "result", "=", "se...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
Container.create
Calls Docker API to creates the Docker container instance. Creating the container does *not* run the container. Use ``start`` method to run the container :return string: ID of the created container :raise RuntimeError: If this method is called after a container already has been created
samcli/local/docker/container.py
def create(self): """ Calls Docker API to creates the Docker container instance. Creating the container does *not* run the container. Use ``start`` method to run the container :return string: ID of the created container :raise RuntimeError: If this method is called after a conta...
def create(self): """ Calls Docker API to creates the Docker container instance. Creating the container does *not* run the container. Use ``start`` method to run the container :return string: ID of the created container :raise RuntimeError: If this method is called after a conta...
[ "Calls", "Docker", "API", "to", "creates", "the", "Docker", "container", "instance", ".", "Creating", "the", "container", "does", "*", "not", "*", "run", "the", "container", ".", "Use", "start", "method", "to", "run", "the", "container" ]
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/container.py#L75-L137
[ "def", "create", "(", "self", ")", ":", "if", "self", ".", "is_created", "(", ")", ":", "raise", "RuntimeError", "(", "\"This container already exists. Cannot create again.\"", ")", "LOG", ".", "info", "(", "\"Mounting %s as %s:ro,delegated inside runtime container\"", ...
c05af5e7378c6f05f7d82ad3f0bca17204177db6
train
Container.delete
Removes a container that was created earlier.
samcli/local/docker/container.py
def delete(self): """ Removes a container that was created earlier. """ if not self.is_created(): LOG.debug("Container was not created. Skipping deletion") return try: self.docker_client.containers\ .get(self.id)\ ...
def delete(self): """ Removes a container that was created earlier. """ if not self.is_created(): LOG.debug("Container was not created. Skipping deletion") return try: self.docker_client.containers\ .get(self.id)\ ...
[ "Removes", "a", "container", "that", "was", "created", "earlier", "." ]
awslabs/aws-sam-cli
python
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/container.py#L139-L163
[ "def", "delete", "(", "self", ")", ":", "if", "not", "self", ".", "is_created", "(", ")", ":", "LOG", ".", "debug", "(", "\"Container was not created. Skipping deletion\"", ")", "return", "try", ":", "self", ".", "docker_client", ".", "containers", ".", "get...
c05af5e7378c6f05f7d82ad3f0bca17204177db6