repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.handle_end_signal | def handle_end_signal(self):
"""
Catch some system signals to handle them internaly
"""
try:
signal.signal(signal.SIGTERM, self.catch_end_signal)
signal.signal(signal.SIGINT, self.catch_end_signal)
except ValueError:
self.log('Signals cannot be... | python | def handle_end_signal(self):
"""
Catch some system signals to handle them internaly
"""
try:
signal.signal(signal.SIGTERM, self.catch_end_signal)
signal.signal(signal.SIGINT, self.catch_end_signal)
except ValueError:
self.log('Signals cannot be... | [
"def",
"handle_end_signal",
"(",
"self",
")",
":",
"try",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"self",
".",
"catch_end_signal",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"self",
".",
"catch_end_signal",
... | Catch some system signals to handle them internaly | [
"Catch",
"some",
"system",
"signals",
"to",
"handle",
"them",
"internaly"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L156-L164 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.stop_handling_end_signal | def stop_handling_end_signal(self):
"""
Stop handling the SIGINT and SIGTERM signals
"""
try:
signal.signal(signal.SIGTERM, signal.SIG_DFL)
signal.signal(signal.SIGINT, signal.SIG_DFL)
except ValueError:
self.log('Signals cannot be caught in a ... | python | def stop_handling_end_signal(self):
"""
Stop handling the SIGINT and SIGTERM signals
"""
try:
signal.signal(signal.SIGTERM, signal.SIG_DFL)
signal.signal(signal.SIGINT, signal.SIG_DFL)
except ValueError:
self.log('Signals cannot be caught in a ... | [
"def",
"stop_handling_end_signal",
"(",
"self",
")",
":",
"try",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"signal",
".",
"SIG_DFL",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIG_DFL",
")",
... | Stop handling the SIGINT and SIGTERM signals | [
"Stop",
"handling",
"the",
"SIGINT",
"and",
"SIGTERM",
"signals"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L166-L174 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.set_logger | def set_logger(self):
"""
Prepare the logger, using self.logger_name and self.logger_level
"""
self.logger = logging.getLogger(self.logger_name)
self.logger.setLevel(self.logger_level) | python | def set_logger(self):
"""
Prepare the logger, using self.logger_name and self.logger_level
"""
self.logger = logging.getLogger(self.logger_name)
self.logger.setLevel(self.logger_level) | [
"def",
"set_logger",
"(",
"self",
")",
":",
"self",
".",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"self",
".",
"logger_name",
")",
"self",
".",
"logger",
".",
"setLevel",
"(",
"self",
".",
"logger_level",
")"
] | Prepare the logger, using self.logger_name and self.logger_level | [
"Prepare",
"the",
"logger",
"using",
"self",
".",
"logger_name",
"and",
"self",
".",
"logger_level"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L176-L181 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.id | def id(self):
"""
Return an identifier for the worker to use in logging
"""
if not hasattr(self, '_id'):
self._id = str(threading.current_thread().ident + id(self))[-6:]
return self._id | python | def id(self):
"""
Return an identifier for the worker to use in logging
"""
if not hasattr(self, '_id'):
self._id = str(threading.current_thread().ident + id(self))[-6:]
return self._id | [
"def",
"id",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_id'",
")",
":",
"self",
".",
"_id",
"=",
"str",
"(",
"threading",
".",
"current_thread",
"(",
")",
".",
"ident",
"+",
"id",
"(",
"self",
")",
")",
"[",
"-",
"6",
... | Return an identifier for the worker to use in logging | [
"Return",
"an",
"identifier",
"for",
"the",
"worker",
"to",
"use",
"in",
"logging"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L184-L190 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.log | def log(self, message, level='info'):
"""
Call self.logger with the given level (default to "info") and message
"""
getattr(self.logger, level)('[%s] %s' % (self.id, message)) | python | def log(self, message, level='info'):
"""
Call self.logger with the given level (default to "info") and message
"""
getattr(self.logger, level)('[%s] %s' % (self.id, message)) | [
"def",
"log",
"(",
"self",
",",
"message",
",",
"level",
"=",
"'info'",
")",
":",
"getattr",
"(",
"self",
".",
"logger",
",",
"level",
")",
"(",
"'[%s] %s'",
"%",
"(",
"self",
".",
"id",
",",
"message",
")",
")"
] | Call self.logger with the given level (default to "info") and message | [
"Call",
"self",
".",
"logger",
"with",
"the",
"given",
"level",
"(",
"default",
"to",
"info",
")",
"and",
"message"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L192-L196 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.must_stop | def must_stop(self):
"""
Return True if the worker must stop when the current loop is over.
"""
return bool(self.terminate_gracefuly and self.end_signal_caught
or self.num_loops >= self.max_loops or self.end_forced
or self.wanted_end_date and datetime.ut... | python | def must_stop(self):
"""
Return True if the worker must stop when the current loop is over.
"""
return bool(self.terminate_gracefuly and self.end_signal_caught
or self.num_loops >= self.max_loops or self.end_forced
or self.wanted_end_date and datetime.ut... | [
"def",
"must_stop",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"terminate_gracefuly",
"and",
"self",
".",
"end_signal_caught",
"or",
"self",
".",
"num_loops",
">=",
"self",
".",
"max_loops",
"or",
"self",
".",
"end_forced",
"or",
"self",
".... | Return True if the worker must stop when the current loop is over. | [
"Return",
"True",
"if",
"the",
"worker",
"must",
"stop",
"when",
"the",
"current",
"loop",
"is",
"over",
"."
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L205-L211 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.set_status | def set_status(self, status):
"""
Save the new status and call all defined callbacks
"""
self.status = status
for callback in self._update_status_callbacks:
callback(self) | python | def set_status(self, status):
"""
Save the new status and call all defined callbacks
"""
self.status = status
for callback in self._update_status_callbacks:
callback(self) | [
"def",
"set_status",
"(",
"self",
",",
"status",
")",
":",
"self",
".",
"status",
"=",
"status",
"for",
"callback",
"in",
"self",
".",
"_update_status_callbacks",
":",
"callback",
"(",
"self",
")"
] | Save the new status and call all defined callbacks | [
"Save",
"the",
"new",
"status",
"and",
"call",
"all",
"defined",
"callbacks"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L213-L219 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.wait_for_job | def wait_for_job(self):
"""
Use a redis blocking list call to wait for a job, and return it.
"""
blpop_result = self.connection.blpop(self.keys, self.timeout)
if blpop_result is None:
return None
queue_redis_key, job_ident = blpop_result
self.set_statu... | python | def wait_for_job(self):
"""
Use a redis blocking list call to wait for a job, and return it.
"""
blpop_result = self.connection.blpop(self.keys, self.timeout)
if blpop_result is None:
return None
queue_redis_key, job_ident = blpop_result
self.set_statu... | [
"def",
"wait_for_job",
"(",
"self",
")",
":",
"blpop_result",
"=",
"self",
".",
"connection",
".",
"blpop",
"(",
"self",
".",
"keys",
",",
"self",
".",
"timeout",
")",
"if",
"blpop_result",
"is",
"None",
":",
"return",
"None",
"queue_redis_key",
",",
"jo... | Use a redis blocking list call to wait for a job, and return it. | [
"Use",
"a",
"redis",
"blocking",
"list",
"call",
"to",
"wait",
"for",
"a",
"job",
"and",
"return",
"it",
"."
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L227-L236 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.get_queue | def get_queue(self, queue_redis_key):
"""
Return a queue based on the key used in redis to store the list
"""
try:
queue_pk = int(queue_redis_key.split(':')[-2])
except:
raise DoesNotExist('Unable to get the queue from the key %s' % queue_redis_key)
... | python | def get_queue(self, queue_redis_key):
"""
Return a queue based on the key used in redis to store the list
"""
try:
queue_pk = int(queue_redis_key.split(':')[-2])
except:
raise DoesNotExist('Unable to get the queue from the key %s' % queue_redis_key)
... | [
"def",
"get_queue",
"(",
"self",
",",
"queue_redis_key",
")",
":",
"try",
":",
"queue_pk",
"=",
"int",
"(",
"queue_redis_key",
".",
"split",
"(",
"':'",
")",
"[",
"-",
"2",
"]",
")",
"except",
":",
"raise",
"DoesNotExist",
"(",
"'Unable to get the queue fr... | Return a queue based on the key used in redis to store the list | [
"Return",
"a",
"queue",
"based",
"on",
"the",
"key",
"used",
"in",
"redis",
"to",
"store",
"the",
"list"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L244-L252 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.catch_end_signal | def catch_end_signal(self, signum, frame):
"""
When a SIGINT/SIGTERM signal is caught, this method is called, asking
for the worker to terminate as soon as possible.
"""
if self.end_signal_caught:
self.log('Previous signal caught, will end soon')
return
... | python | def catch_end_signal(self, signum, frame):
"""
When a SIGINT/SIGTERM signal is caught, this method is called, asking
for the worker to terminate as soon as possible.
"""
if self.end_signal_caught:
self.log('Previous signal caught, will end soon')
return
... | [
"def",
"catch_end_signal",
"(",
"self",
",",
"signum",
",",
"frame",
")",
":",
"if",
"self",
".",
"end_signal_caught",
":",
"self",
".",
"log",
"(",
"'Previous signal caught, will end soon'",
")",
"return",
"signal_name",
"=",
"dict",
"(",
"(",
"getattr",
"(",... | When a SIGINT/SIGTERM signal is caught, this method is called, asking
for the worker to terminate as soon as possible. | [
"When",
"a",
"SIGINT",
"/",
"SIGTERM",
"signal",
"is",
"caught",
"this",
"method",
"is",
"called",
"asking",
"for",
"the",
"worker",
"to",
"terminate",
"as",
"soon",
"as",
"possible",
"."
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L254-L274 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.update_keys | def update_keys(self):
"""
Update the redis keys to listen for new jobs priorities.
"""
self.keys = self.queue_model.get_waiting_keys(self.queues)
if not self.keys:
self.log('No queues yet', level='warning')
self.last_update_keys = datetime.utcnow() | python | def update_keys(self):
"""
Update the redis keys to listen for new jobs priorities.
"""
self.keys = self.queue_model.get_waiting_keys(self.queues)
if not self.keys:
self.log('No queues yet', level='warning')
self.last_update_keys = datetime.utcnow() | [
"def",
"update_keys",
"(",
"self",
")",
":",
"self",
".",
"keys",
"=",
"self",
".",
"queue_model",
".",
"get_waiting_keys",
"(",
"self",
".",
"queues",
")",
"if",
"not",
"self",
".",
"keys",
":",
"self",
".",
"log",
"(",
"'No queues yet'",
",",
"level"... | Update the redis keys to listen for new jobs priorities. | [
"Update",
"the",
"redis",
"keys",
"to",
"listen",
"for",
"new",
"jobs",
"priorities",
"."
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L285-L293 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.run | def run(self):
"""
The main method of the worker. Will ask redis for list items via
blocking calls, get jobs from them, try to execute these jobs, and end
when needed.
"""
# if status is not None, we already had a run !
if self.status:
self.set_status(... | python | def run(self):
"""
The main method of the worker. Will ask redis for list items via
blocking calls, get jobs from them, try to execute these jobs, and end
when needed.
"""
# if status is not None, we already had a run !
if self.status:
self.set_status(... | [
"def",
"run",
"(",
"self",
")",
":",
"# if status is not None, we already had a run !",
"if",
"self",
".",
"status",
":",
"self",
".",
"set_status",
"(",
"'aborted'",
")",
"raise",
"LimpydJobsException",
"(",
"'This worker run is already terminated'",
")",
"self",
"."... | The main method of the worker. Will ask redis for list items via
blocking calls, get jobs from them, try to execute these jobs, and end
when needed. | [
"The",
"main",
"method",
"of",
"the",
"worker",
".",
"Will",
"ask",
"redis",
"for",
"list",
"items",
"via",
"blocking",
"calls",
"get",
"jobs",
"from",
"them",
"try",
"to",
"execute",
"these",
"jobs",
"and",
"end",
"when",
"needed",
"."
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L313-L351 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.elapsed | def elapsed(self):
"""
Return a timedelta representation of the time passed sine the worker
was running.
"""
if not self.start_date:
return None
return (self.end_date or datetime.utcnow()) - self.start_date | python | def elapsed(self):
"""
Return a timedelta representation of the time passed sine the worker
was running.
"""
if not self.start_date:
return None
return (self.end_date or datetime.utcnow()) - self.start_date | [
"def",
"elapsed",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"start_date",
":",
"return",
"None",
"return",
"(",
"self",
".",
"end_date",
"or",
"datetime",
".",
"utcnow",
"(",
")",
")",
"-",
"self",
".",
"start_date"
] | Return a timedelta representation of the time passed sine the worker
was running. | [
"Return",
"a",
"timedelta",
"representation",
"of",
"the",
"time",
"passed",
"sine",
"the",
"worker",
"was",
"running",
"."
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L354-L361 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.requeue_delayed_jobs | def requeue_delayed_jobs(self):
"""
Requeue each delayed job that are now ready to be executed
"""
failures = []
for queue in self.queue_model.get_all_by_priority(self.queues):
failures.extend(queue.requeue_delayed_jobs())
self.last_requeue_delayed = datetime... | python | def requeue_delayed_jobs(self):
"""
Requeue each delayed job that are now ready to be executed
"""
failures = []
for queue in self.queue_model.get_all_by_priority(self.queues):
failures.extend(queue.requeue_delayed_jobs())
self.last_requeue_delayed = datetime... | [
"def",
"requeue_delayed_jobs",
"(",
"self",
")",
":",
"failures",
"=",
"[",
"]",
"for",
"queue",
"in",
"self",
".",
"queue_model",
".",
"get_all_by_priority",
"(",
"self",
".",
"queues",
")",
":",
"failures",
".",
"extend",
"(",
"queue",
".",
"requeue_dela... | Requeue each delayed job that are now ready to be executed | [
"Requeue",
"each",
"delayed",
"job",
"that",
"are",
"now",
"ready",
"to",
"be",
"executed"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L363-L374 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker._main_loop | def _main_loop(self):
"""
Run jobs until must_stop returns True
"""
fetch_priorities_delay = timedelta(seconds=self.fetch_priorities_delay)
fetch_delayed_delay = timedelta(seconds=self.fetch_delayed_delay)
while not self.must_stop():
self.set_status('waiting'... | python | def _main_loop(self):
"""
Run jobs until must_stop returns True
"""
fetch_priorities_delay = timedelta(seconds=self.fetch_priorities_delay)
fetch_delayed_delay = timedelta(seconds=self.fetch_delayed_delay)
while not self.must_stop():
self.set_status('waiting'... | [
"def",
"_main_loop",
"(",
"self",
")",
":",
"fetch_priorities_delay",
"=",
"timedelta",
"(",
"seconds",
"=",
"self",
".",
"fetch_priorities_delay",
")",
"fetch_delayed_delay",
"=",
"timedelta",
"(",
"seconds",
"=",
"self",
".",
"fetch_delayed_delay",
")",
"while",... | Run jobs until must_stop returns True | [
"Run",
"jobs",
"until",
"must_stop",
"returns",
"True"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L376-L443 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.job_error | def job_error(self, job, queue, exception, trace=None):
"""
Called when an exception was raised during the execute call for a job.
"""
to_be_requeued = not job.must_be_cancelled_on_error and self.requeue_times and self.requeue_times >= int(job.tries.hget() or 0)
if not to_be_req... | python | def job_error(self, job, queue, exception, trace=None):
"""
Called when an exception was raised during the execute call for a job.
"""
to_be_requeued = not job.must_be_cancelled_on_error and self.requeue_times and self.requeue_times >= int(job.tries.hget() or 0)
if not to_be_req... | [
"def",
"job_error",
"(",
"self",
",",
"job",
",",
"queue",
",",
"exception",
",",
"trace",
"=",
"None",
")",
":",
"to_be_requeued",
"=",
"not",
"job",
".",
"must_be_cancelled_on_error",
"and",
"self",
".",
"requeue_times",
"and",
"self",
".",
"requeue_times"... | Called when an exception was raised during the execute call for a job. | [
"Called",
"when",
"an",
"exception",
"was",
"raised",
"during",
"the",
"execute",
"call",
"for",
"a",
"job",
"."
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L458-L490 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.requeue_job | def requeue_job(self, job, queue, priority, delayed_for=None):
"""
Requeue a job in a queue with the given priority, possibly delayed
"""
job.requeue(queue_name=queue._cached_name,
priority=priority,
delayed_for=delayed_for,
que... | python | def requeue_job(self, job, queue, priority, delayed_for=None):
"""
Requeue a job in a queue with the given priority, possibly delayed
"""
job.requeue(queue_name=queue._cached_name,
priority=priority,
delayed_for=delayed_for,
que... | [
"def",
"requeue_job",
"(",
"self",
",",
"job",
",",
"queue",
",",
"priority",
",",
"delayed_for",
"=",
"None",
")",
":",
"job",
".",
"requeue",
"(",
"queue_name",
"=",
"queue",
".",
"_cached_name",
",",
"priority",
"=",
"priority",
",",
"delayed_for",
"=... | Requeue a job in a queue with the given priority, possibly delayed | [
"Requeue",
"a",
"job",
"in",
"a",
"queue",
"with",
"the",
"given",
"priority",
"possibly",
"delayed"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L492-L504 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.job_error_message | def job_error_message(self, job, queue, to_be_requeued, exception, trace=None):
"""
Return the message to log when a job raised an error
"""
return '[%s|%s|%s] error: %s [%s]' % (queue._cached_name,
job.pk.get(),
job._cached_ident... | python | def job_error_message(self, job, queue, to_be_requeued, exception, trace=None):
"""
Return the message to log when a job raised an error
"""
return '[%s|%s|%s] error: %s [%s]' % (queue._cached_name,
job.pk.get(),
job._cached_ident... | [
"def",
"job_error_message",
"(",
"self",
",",
"job",
",",
"queue",
",",
"to_be_requeued",
",",
"exception",
",",
"trace",
"=",
"None",
")",
":",
"return",
"'[%s|%s|%s] error: %s [%s]'",
"%",
"(",
"queue",
".",
"_cached_name",
",",
"job",
".",
"pk",
".",
"g... | Return the message to log when a job raised an error | [
"Return",
"the",
"message",
"to",
"log",
"when",
"a",
"job",
"raised",
"an",
"error"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L506-L514 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.job_requeue_message | def job_requeue_message(self, job, queue):
"""
Return the message to log when a job is requeued
"""
priority, delayed_until = job.hmget('priority', 'delayed_until')
msg = '[%s|%s|%s] requeued with priority %s'
args = [queue._cached_name, job.pk.get(), job._cached_identif... | python | def job_requeue_message(self, job, queue):
"""
Return the message to log when a job is requeued
"""
priority, delayed_until = job.hmget('priority', 'delayed_until')
msg = '[%s|%s|%s] requeued with priority %s'
args = [queue._cached_name, job.pk.get(), job._cached_identif... | [
"def",
"job_requeue_message",
"(",
"self",
",",
"job",
",",
"queue",
")",
":",
"priority",
",",
"delayed_until",
"=",
"job",
".",
"hmget",
"(",
"'priority'",
",",
"'delayed_until'",
")",
"msg",
"=",
"'[%s|%s|%s] requeued with priority %s'",
"args",
"=",
"[",
"... | Return the message to log when a job is requeued | [
"Return",
"the",
"message",
"to",
"log",
"when",
"a",
"job",
"is",
"requeued"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L516-L529 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.job_success | def job_success(self, job, queue, job_result):
"""
Called just after an execute call was successful.
job_result is the value returned by the callback, if any.
"""
job.queued.delete()
job.hmset(end=str(datetime.utcnow()), status=STATUSES.SUCCESS)
queue.success.rpus... | python | def job_success(self, job, queue, job_result):
"""
Called just after an execute call was successful.
job_result is the value returned by the callback, if any.
"""
job.queued.delete()
job.hmset(end=str(datetime.utcnow()), status=STATUSES.SUCCESS)
queue.success.rpus... | [
"def",
"job_success",
"(",
"self",
",",
"job",
",",
"queue",
",",
"job_result",
")",
":",
"job",
".",
"queued",
".",
"delete",
"(",
")",
"job",
".",
"hmset",
"(",
"end",
"=",
"str",
"(",
"datetime",
".",
"utcnow",
"(",
")",
")",
",",
"status",
"=... | Called just after an execute call was successful.
job_result is the value returned by the callback, if any. | [
"Called",
"just",
"after",
"an",
"execute",
"call",
"was",
"successful",
".",
"job_result",
"is",
"the",
"value",
"returned",
"by",
"the",
"callback",
"if",
"any",
"."
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L531-L541 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.job_success_message | def job_success_message(self, job, queue, job_result):
"""
Return the message to log when a job is successful
"""
return '[%s|%s|%s] success, in %s' % (queue._cached_name, job.pk.get(),
job._cached_identifier, job.duration) | python | def job_success_message(self, job, queue, job_result):
"""
Return the message to log when a job is successful
"""
return '[%s|%s|%s] success, in %s' % (queue._cached_name, job.pk.get(),
job._cached_identifier, job.duration) | [
"def",
"job_success_message",
"(",
"self",
",",
"job",
",",
"queue",
",",
"job_result",
")",
":",
"return",
"'[%s|%s|%s] success, in %s'",
"%",
"(",
"queue",
".",
"_cached_name",
",",
"job",
".",
"pk",
".",
"get",
"(",
")",
",",
"job",
".",
"_cached_identi... | Return the message to log when a job is successful | [
"Return",
"the",
"message",
"to",
"log",
"when",
"a",
"job",
"is",
"successful"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L543-L548 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.job_started | def job_started(self, job, queue):
"""
Called just before the execution of the job
"""
job.hmset(start=str(datetime.utcnow()), status=STATUSES.RUNNING)
job.tries.hincrby(1)
self.log(self.job_started_message(job, queue))
if hasattr(job, 'on_started'):
j... | python | def job_started(self, job, queue):
"""
Called just before the execution of the job
"""
job.hmset(start=str(datetime.utcnow()), status=STATUSES.RUNNING)
job.tries.hincrby(1)
self.log(self.job_started_message(job, queue))
if hasattr(job, 'on_started'):
j... | [
"def",
"job_started",
"(",
"self",
",",
"job",
",",
"queue",
")",
":",
"job",
".",
"hmset",
"(",
"start",
"=",
"str",
"(",
"datetime",
".",
"utcnow",
"(",
")",
")",
",",
"status",
"=",
"STATUSES",
".",
"RUNNING",
")",
"job",
".",
"tries",
".",
"h... | Called just before the execution of the job | [
"Called",
"just",
"before",
"the",
"execution",
"of",
"the",
"job"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L550-L558 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.job_started_message | def job_started_message(self, job, queue):
"""
Return the message to log just befre the execution of the job
"""
return '[%s|%s|%s] starting' % (queue._cached_name, job.pk.get(),
job._cached_identifier) | python | def job_started_message(self, job, queue):
"""
Return the message to log just befre the execution of the job
"""
return '[%s|%s|%s] starting' % (queue._cached_name, job.pk.get(),
job._cached_identifier) | [
"def",
"job_started_message",
"(",
"self",
",",
"job",
",",
"queue",
")",
":",
"return",
"'[%s|%s|%s] starting'",
"%",
"(",
"queue",
".",
"_cached_name",
",",
"job",
".",
"pk",
".",
"get",
"(",
")",
",",
"job",
".",
"_cached_identifier",
")"
] | Return the message to log just befre the execution of the job | [
"Return",
"the",
"message",
"to",
"log",
"just",
"befre",
"the",
"execution",
"of",
"the",
"job"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L560-L565 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.job_skipped | def job_skipped(self, job, queue):
"""
Called if a job, before trying to run it, has not the "waiting" status,
or, after run, if its status was set to "canceled"
"""
job.queued.delete()
self.log(self.job_skipped_message(job, queue), level='warning')
if hasattr(job... | python | def job_skipped(self, job, queue):
"""
Called if a job, before trying to run it, has not the "waiting" status,
or, after run, if its status was set to "canceled"
"""
job.queued.delete()
self.log(self.job_skipped_message(job, queue), level='warning')
if hasattr(job... | [
"def",
"job_skipped",
"(",
"self",
",",
"job",
",",
"queue",
")",
":",
"job",
".",
"queued",
".",
"delete",
"(",
")",
"self",
".",
"log",
"(",
"self",
".",
"job_skipped_message",
"(",
"job",
",",
"queue",
")",
",",
"level",
"=",
"'warning'",
")",
"... | Called if a job, before trying to run it, has not the "waiting" status,
or, after run, if its status was set to "canceled" | [
"Called",
"if",
"a",
"job",
"before",
"trying",
"to",
"run",
"it",
"has",
"not",
"the",
"waiting",
"status",
"or",
"after",
"run",
"if",
"its",
"status",
"was",
"set",
"to",
"canceled"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L567-L575 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.job_skipped_message | def job_skipped_message(self, job, queue):
"""
Return the message to log when a job was skipped
"""
return '[%s|%s|%s] job skipped (current status: %s)' % (
queue._cached_name,
job.pk.get(),
job._cached_identifier,
STATUSES.... | python | def job_skipped_message(self, job, queue):
"""
Return the message to log when a job was skipped
"""
return '[%s|%s|%s] job skipped (current status: %s)' % (
queue._cached_name,
job.pk.get(),
job._cached_identifier,
STATUSES.... | [
"def",
"job_skipped_message",
"(",
"self",
",",
"job",
",",
"queue",
")",
":",
"return",
"'[%s|%s|%s] job skipped (current status: %s)'",
"%",
"(",
"queue",
".",
"_cached_name",
",",
"job",
".",
"pk",
".",
"get",
"(",
")",
",",
"job",
".",
"_cached_identifier"... | Return the message to log when a job was skipped | [
"Return",
"the",
"message",
"to",
"log",
"when",
"a",
"job",
"was",
"skipped"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L577-L585 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.job_delayed | def job_delayed(self, job, queue):
"""
Called if a job, before trying to run it, has the "delayed" status, or,
after run, if its status was set to "delayed"
If delayed_until was not set, or is invalid, set it to 60sec in the future
"""
delayed_until = job.delayed_until.hg... | python | def job_delayed(self, job, queue):
"""
Called if a job, before trying to run it, has the "delayed" status, or,
after run, if its status was set to "delayed"
If delayed_until was not set, or is invalid, set it to 60sec in the future
"""
delayed_until = job.delayed_until.hg... | [
"def",
"job_delayed",
"(",
"self",
",",
"job",
",",
"queue",
")",
":",
"delayed_until",
"=",
"job",
".",
"delayed_until",
".",
"hget",
"(",
")",
"if",
"delayed_until",
":",
"try",
":",
"delayed_until",
"=",
"compute_delayed_until",
"(",
"delayed_until",
"=",... | Called if a job, before trying to run it, has the "delayed" status, or,
after run, if its status was set to "delayed"
If delayed_until was not set, or is invalid, set it to 60sec in the future | [
"Called",
"if",
"a",
"job",
"before",
"trying",
"to",
"run",
"it",
"has",
"the",
"delayed",
"status",
"or",
"after",
"run",
"if",
"its",
"status",
"was",
"set",
"to",
"delayed",
"If",
"delayed_until",
"was",
"not",
"set",
"or",
"is",
"invalid",
"set",
... | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L587-L613 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | Worker.job_delayed_message | def job_delayed_message(self, job, queue):
"""
Return the message to log when a job was delayed just before or during
its execution
"""
return '[%s|%s|%s] job delayed until %s' % (
queue._cached_name,
job.pk.get(),
job._cached_ident... | python | def job_delayed_message(self, job, queue):
"""
Return the message to log when a job was delayed just before or during
its execution
"""
return '[%s|%s|%s] job delayed until %s' % (
queue._cached_name,
job.pk.get(),
job._cached_ident... | [
"def",
"job_delayed_message",
"(",
"self",
",",
"job",
",",
"queue",
")",
":",
"return",
"'[%s|%s|%s] job delayed until %s'",
"%",
"(",
"queue",
".",
"_cached_name",
",",
"job",
".",
"pk",
".",
"get",
"(",
")",
",",
"job",
".",
"_cached_identifier",
",",
"... | Return the message to log when a job was delayed just before or during
its execution | [
"Return",
"the",
"message",
"to",
"log",
"when",
"a",
"job",
"was",
"delayed",
"just",
"before",
"or",
"during",
"its",
"execution"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L615-L624 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | WorkerConfig.create_parser | def create_parser(self):
"""
Create and return the ``OptionParser`` which will be used to
parse the arguments to the worker.
"""
return OptionParser(prog=self.prog_name,
usage=self.usage(),
version='%%prog %s' % self.get_ve... | python | def create_parser(self):
"""
Create and return the ``OptionParser`` which will be used to
parse the arguments to the worker.
"""
return OptionParser(prog=self.prog_name,
usage=self.usage(),
version='%%prog %s' % self.get_ve... | [
"def",
"create_parser",
"(",
"self",
")",
":",
"return",
"OptionParser",
"(",
"prog",
"=",
"self",
".",
"prog_name",
",",
"usage",
"=",
"self",
".",
"usage",
"(",
")",
",",
"version",
"=",
"'%%prog %s'",
"%",
"self",
".",
"get_version",
"(",
")",
",",
... | Create and return the ``OptionParser`` which will be used to
parse the arguments to the worker. | [
"Create",
"and",
"return",
"the",
"OptionParser",
"which",
"will",
"be",
"used",
"to",
"parse",
"the",
"arguments",
"to",
"the",
"worker",
"."
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L740-L749 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | WorkerConfig.manage_options | def manage_options(self):
"""
Create a parser given the command-line arguments, creates a parser
Return True if the programme must exit.
"""
self.parser = self.create_parser()
self.options, self.args = self.parser.parse_args(self.argv)
self.do_imports()
... | python | def manage_options(self):
"""
Create a parser given the command-line arguments, creates a parser
Return True if the programme must exit.
"""
self.parser = self.create_parser()
self.options, self.args = self.parser.parse_args(self.argv)
self.do_imports()
... | [
"def",
"manage_options",
"(",
"self",
")",
":",
"self",
".",
"parser",
"=",
"self",
".",
"create_parser",
"(",
")",
"self",
".",
"options",
",",
"self",
".",
"args",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"self",
".",
"argv",
")",
"self"... | Create a parser given the command-line arguments, creates a parser
Return True if the programme must exit. | [
"Create",
"a",
"parser",
"given",
"the",
"command",
"-",
"line",
"arguments",
"creates",
"a",
"parser",
"Return",
"True",
"if",
"the",
"programme",
"must",
"exit",
"."
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L751-L800 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | WorkerConfig.do_import | def do_import(self, name, default):
"""
Import the given option (use default values if not defined on command line)
"""
try:
option = getattr(self.options, name)
if option:
klass = import_class(option)
else:
klass = defa... | python | def do_import(self, name, default):
"""
Import the given option (use default values if not defined on command line)
"""
try:
option = getattr(self.options, name)
if option:
klass = import_class(option)
else:
klass = defa... | [
"def",
"do_import",
"(",
"self",
",",
"name",
",",
"default",
")",
":",
"try",
":",
"option",
"=",
"getattr",
"(",
"self",
".",
"options",
",",
"name",
")",
"if",
"option",
":",
"klass",
"=",
"import_class",
"(",
"option",
")",
"else",
":",
"klass",
... | Import the given option (use default values if not defined on command line) | [
"Import",
"the",
"given",
"option",
"(",
"use",
"default",
"values",
"if",
"not",
"defined",
"on",
"command",
"line",
")"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L802-L814 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | WorkerConfig.do_imports | def do_imports(self):
"""
Import all importable options
"""
self.do_import('worker_class', Worker)
self.do_import('queue_model', self.options.worker_class.queue_model)
self.do_import('error_model', self.options.worker_class.error_model)
self.do_import('callback', ... | python | def do_imports(self):
"""
Import all importable options
"""
self.do_import('worker_class', Worker)
self.do_import('queue_model', self.options.worker_class.queue_model)
self.do_import('error_model', self.options.worker_class.error_model)
self.do_import('callback', ... | [
"def",
"do_imports",
"(",
"self",
")",
":",
"self",
".",
"do_import",
"(",
"'worker_class'",
",",
"Worker",
")",
"self",
".",
"do_import",
"(",
"'queue_model'",
",",
"self",
".",
"options",
".",
"worker_class",
".",
"queue_model",
")",
"self",
".",
"do_imp... | Import all importable options | [
"Import",
"all",
"importable",
"options"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L816-L823 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | WorkerConfig.print_options | def print_options(self):
"""
Print all options as parsed by the script
"""
options = []
print("The script is running with the following options:")
options.append(("dry_run", self.options.dry_run))
options.append(("worker_config", self.__class__))
datab... | python | def print_options(self):
"""
Print all options as parsed by the script
"""
options = []
print("The script is running with the following options:")
options.append(("dry_run", self.options.dry_run))
options.append(("worker_config", self.__class__))
datab... | [
"def",
"print_options",
"(",
"self",
")",
":",
"options",
"=",
"[",
"]",
"print",
"(",
"\"The script is running with the following options:\"",
")",
"options",
".",
"append",
"(",
"(",
"\"dry_run\"",
",",
"self",
".",
"options",
".",
"dry_run",
")",
")",
"opti... | Print all options as parsed by the script | [
"Print",
"all",
"options",
"as",
"parsed",
"by",
"the",
"script"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L825-L857 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | WorkerConfig.execute | def execute(self):
"""
Main method to call to run the worker
"""
self.prepare_models()
self.prepare_worker()
if self.options.print_options:
self.print_options()
self.run() | python | def execute(self):
"""
Main method to call to run the worker
"""
self.prepare_models()
self.prepare_worker()
if self.options.print_options:
self.print_options()
self.run() | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"prepare_models",
"(",
")",
"self",
".",
"prepare_worker",
"(",
")",
"if",
"self",
".",
"options",
".",
"print_options",
":",
"self",
".",
"print_options",
"(",
")",
"self",
".",
"run",
"(",
")"
] | Main method to call to run the worker | [
"Main",
"method",
"to",
"call",
"to",
"run",
"the",
"worker"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L859-L867 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | WorkerConfig.prepare_models | def prepare_models(self):
"""
If a database config ws given as argument, apply it to our models
"""
if self.database_config:
for model in (self.options.queue_model, self.options.error_model):
model.database.reset(**self.database_config) | python | def prepare_models(self):
"""
If a database config ws given as argument, apply it to our models
"""
if self.database_config:
for model in (self.options.queue_model, self.options.error_model):
model.database.reset(**self.database_config) | [
"def",
"prepare_models",
"(",
"self",
")",
":",
"if",
"self",
".",
"database_config",
":",
"for",
"model",
"in",
"(",
"self",
".",
"options",
".",
"queue_model",
",",
"self",
".",
"options",
".",
"error_model",
")",
":",
"model",
".",
"database",
".",
... | If a database config ws given as argument, apply it to our models | [
"If",
"a",
"database",
"config",
"ws",
"given",
"as",
"argument",
"apply",
"it",
"to",
"our",
"models"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L869-L875 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | WorkerConfig.prepare_worker_options | def prepare_worker_options(self):
"""
Prepare (and return as a dict) all options to be passed to the worker
"""
worker_options = dict()
for option_name in (self.options.worker_class.parameters):
option = getattr(self.options, option_name)
if option is not ... | python | def prepare_worker_options(self):
"""
Prepare (and return as a dict) all options to be passed to the worker
"""
worker_options = dict()
for option_name in (self.options.worker_class.parameters):
option = getattr(self.options, option_name)
if option is not ... | [
"def",
"prepare_worker_options",
"(",
"self",
")",
":",
"worker_options",
"=",
"dict",
"(",
")",
"for",
"option_name",
"in",
"(",
"self",
".",
"options",
".",
"worker_class",
".",
"parameters",
")",
":",
"option",
"=",
"getattr",
"(",
"self",
".",
"options... | Prepare (and return as a dict) all options to be passed to the worker | [
"Prepare",
"(",
"and",
"return",
"as",
"a",
"dict",
")",
"all",
"options",
"to",
"be",
"passed",
"to",
"the",
"worker"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L877-L886 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | WorkerConfig.prepare_worker | def prepare_worker(self):
"""
Prepare the worker, ready to be launched: prepare options, create a
log handler if none, and manage dry_run options
"""
worker_options = self.prepare_worker_options()
self.worker = self.options.worker_class(**worker_options)
if self.u... | python | def prepare_worker(self):
"""
Prepare the worker, ready to be launched: prepare options, create a
log handler if none, and manage dry_run options
"""
worker_options = self.prepare_worker_options()
self.worker = self.options.worker_class(**worker_options)
if self.u... | [
"def",
"prepare_worker",
"(",
"self",
")",
":",
"worker_options",
"=",
"self",
".",
"prepare_worker_options",
"(",
")",
"self",
".",
"worker",
"=",
"self",
".",
"options",
".",
"worker_class",
"(",
"*",
"*",
"worker_options",
")",
"if",
"self",
".",
"updat... | Prepare the worker, ready to be launched: prepare options, create a
log handler if none, and manage dry_run options | [
"Prepare",
"the",
"worker",
"ready",
"to",
"be",
"launched",
":",
"prepare",
"options",
"create",
"a",
"log",
"handler",
"if",
"none",
"and",
"manage",
"dry_run",
"options"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L888-L914 |
limpyd/redis-limpyd-jobs | limpyd_jobs/workers.py | WorkerConfig.get_proc_title | def get_proc_title(self):
"""
Create the title for the current process (set by `update_proc_title`)
"""
has_worker = bool(getattr(self, 'worker', None))
title_parts = [self.prog_name.replace('.py', ('#%s' % self.worker.id) if has_worker else '')]
status = 'init'
... | python | def get_proc_title(self):
"""
Create the title for the current process (set by `update_proc_title`)
"""
has_worker = bool(getattr(self, 'worker', None))
title_parts = [self.prog_name.replace('.py', ('#%s' % self.worker.id) if has_worker else '')]
status = 'init'
... | [
"def",
"get_proc_title",
"(",
"self",
")",
":",
"has_worker",
"=",
"bool",
"(",
"getattr",
"(",
"self",
",",
"'worker'",
",",
"None",
")",
")",
"title_parts",
"=",
"[",
"self",
".",
"prog_name",
".",
"replace",
"(",
"'.py'",
",",
"(",
"'#%s'",
"%",
"... | Create the title for the current process (set by `update_proc_title`) | [
"Create",
"the",
"title",
"for",
"the",
"current",
"process",
"(",
"set",
"by",
"update_proc_title",
")"
] | train | https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L922-L959 |
Robpol86/docoptcfg | docoptcfg.py | settable_options | def settable_options(doc, argv, ignore, options_first):
"""Determine which options we can set, which ones are boolean, and which ones are repeatable.
All set items are option long names.
:param str doc: Docstring from docoptcfg().
:param iter argv: CLI arguments from docoptcfg().
:param iter ignor... | python | def settable_options(doc, argv, ignore, options_first):
"""Determine which options we can set, which ones are boolean, and which ones are repeatable.
All set items are option long names.
:param str doc: Docstring from docoptcfg().
:param iter argv: CLI arguments from docoptcfg().
:param iter ignor... | [
"def",
"settable_options",
"(",
"doc",
",",
"argv",
",",
"ignore",
",",
"options_first",
")",
":",
"settable",
",",
"booleans",
",",
"repeatable",
",",
"short_map",
"=",
"set",
"(",
")",
",",
"set",
"(",
")",
",",
"set",
"(",
")",
",",
"dict",
"(",
... | Determine which options we can set, which ones are boolean, and which ones are repeatable.
All set items are option long names.
:param str doc: Docstring from docoptcfg().
:param iter argv: CLI arguments from docoptcfg().
:param iter ignore: Options to ignore from docoptcfg().
:param bool options_... | [
"Determine",
"which",
"options",
"we",
"can",
"set",
"which",
"ones",
"are",
"boolean",
"and",
"which",
"ones",
"are",
"repeatable",
"."
] | train | https://github.com/Robpol86/docoptcfg/blob/3746dc263549f7f3ef5a86e739d588546b084bde/docoptcfg.py#L39-L79 |
Robpol86/docoptcfg | docoptcfg.py | get_env | def get_env(key, env_prefix, boolean, repeatable):
"""Get one value from environment variable(s).
:raise KeyError: If option not in environment variables.
:param str key: Option long name (e.g. --config).
:param str env_prefix: Variable name prefix from docoptcfg().
:param bool boolean: Is this a ... | python | def get_env(key, env_prefix, boolean, repeatable):
"""Get one value from environment variable(s).
:raise KeyError: If option not in environment variables.
:param str key: Option long name (e.g. --config).
:param str env_prefix: Variable name prefix from docoptcfg().
:param bool boolean: Is this a ... | [
"def",
"get_env",
"(",
"key",
",",
"env_prefix",
",",
"boolean",
",",
"repeatable",
")",
":",
"env_name",
"=",
"'{0}{1}'",
".",
"format",
"(",
"env_prefix",
",",
"key",
"[",
"2",
":",
"]",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
".",
"upper",
... | Get one value from environment variable(s).
:raise KeyError: If option not in environment variables.
:param str key: Option long name (e.g. --config).
:param str env_prefix: Variable name prefix from docoptcfg().
:param bool boolean: Is this a boolean/flag option?
:param bool repeatable: Is this o... | [
"Get",
"one",
"value",
"from",
"environment",
"variable",
"(",
"s",
")",
"."
] | train | https://github.com/Robpol86/docoptcfg/blob/3746dc263549f7f3ef5a86e739d588546b084bde/docoptcfg.py#L82-L123 |
Robpol86/docoptcfg | docoptcfg.py | values_from_env | def values_from_env(env_prefix, settable, booleans, repeatable):
"""Get all values from environment variables.
:param str env_prefix: Argument from docoptcfg().
:param iter settable: Option long names available to set by config file.
:param iter booleans: Option long names of boolean/flag types.
:p... | python | def values_from_env(env_prefix, settable, booleans, repeatable):
"""Get all values from environment variables.
:param str env_prefix: Argument from docoptcfg().
:param iter settable: Option long names available to set by config file.
:param iter booleans: Option long names of boolean/flag types.
:p... | [
"def",
"values_from_env",
"(",
"env_prefix",
",",
"settable",
",",
"booleans",
",",
"repeatable",
")",
":",
"defaults_env",
"=",
"dict",
"(",
")",
"for",
"key",
"in",
"settable",
":",
"try",
":",
"defaults_env",
"[",
"key",
"]",
"=",
"get_env",
"(",
"key... | Get all values from environment variables.
:param str env_prefix: Argument from docoptcfg().
:param iter settable: Option long names available to set by config file.
:param iter booleans: Option long names of boolean/flag types.
:param iter repeatable: Option long names of repeatable options.
:ret... | [
"Get",
"all",
"values",
"from",
"environment",
"variables",
"."
] | train | https://github.com/Robpol86/docoptcfg/blob/3746dc263549f7f3ef5a86e739d588546b084bde/docoptcfg.py#L126-L143 |
Robpol86/docoptcfg | docoptcfg.py | get_opt | def get_opt(key, config, section, booleans, repeatable):
"""Get one value from config file.
:raise DocoptcfgFileError: If an option is the wrong type.
:param str key: Option long name (e.g. --config).
:param ConfigParser config: ConfigParser instance with config file data already loaded.
:param st... | python | def get_opt(key, config, section, booleans, repeatable):
"""Get one value from config file.
:raise DocoptcfgFileError: If an option is the wrong type.
:param str key: Option long name (e.g. --config).
:param ConfigParser config: ConfigParser instance with config file data already loaded.
:param st... | [
"def",
"get_opt",
"(",
"key",
",",
"config",
",",
"section",
",",
"booleans",
",",
"repeatable",
")",
":",
"# Handle repeatable non-boolean options (e.g. --file=file1.txt --file=file2.txt).",
"if",
"key",
"in",
"repeatable",
"and",
"key",
"not",
"in",
"booleans",
":",... | Get one value from config file.
:raise DocoptcfgFileError: If an option is the wrong type.
:param str key: Option long name (e.g. --config).
:param ConfigParser config: ConfigParser instance with config file data already loaded.
:param str section: Section in config file to focus on.
:param iter b... | [
"Get",
"one",
"value",
"from",
"config",
"file",
"."
] | train | https://github.com/Robpol86/docoptcfg/blob/3746dc263549f7f3ef5a86e739d588546b084bde/docoptcfg.py#L146-L178 |
Robpol86/docoptcfg | docoptcfg.py | values_from_file | def values_from_file(docopt_dict, config_option, settable, booleans, repeatable):
"""Parse config file and read settable values.
Can be overridden by both command line arguments and environment variables.
:raise DocoptcfgError: If `config_option` isn't found in docstring.
:raise DocoptcfgFileError: On... | python | def values_from_file(docopt_dict, config_option, settable, booleans, repeatable):
"""Parse config file and read settable values.
Can be overridden by both command line arguments and environment variables.
:raise DocoptcfgError: If `config_option` isn't found in docstring.
:raise DocoptcfgFileError: On... | [
"def",
"values_from_file",
"(",
"docopt_dict",
",",
"config_option",
",",
"settable",
",",
"booleans",
",",
"repeatable",
")",
":",
"section",
"=",
"docopt",
".",
"DocoptExit",
".",
"usage",
".",
"split",
"(",
")",
"[",
"1",
"]",
"settable",
"=",
"set",
... | Parse config file and read settable values.
Can be overridden by both command line arguments and environment variables.
:raise DocoptcfgError: If `config_option` isn't found in docstring.
:raise DocoptcfgFileError: On any error while trying to read and parse config file.
:param dict docopt_dict: Dict... | [
"Parse",
"config",
"file",
"and",
"read",
"settable",
"values",
"."
] | train | https://github.com/Robpol86/docoptcfg/blob/3746dc263549f7f3ef5a86e739d588546b084bde/docoptcfg.py#L181-L231 |
Robpol86/docoptcfg | docoptcfg.py | docoptcfg | def docoptcfg(doc, argv=None, env_prefix=None, config_option=None, ignore=None, *args, **kwargs):
"""Pass most args/kwargs to docopt. Handle `env_prefix` and `config_option`.
:raise DocoptcfgError: If `config_option` isn't found in docstring.
:raise DocoptcfgFileError: On any error while trying to read and... | python | def docoptcfg(doc, argv=None, env_prefix=None, config_option=None, ignore=None, *args, **kwargs):
"""Pass most args/kwargs to docopt. Handle `env_prefix` and `config_option`.
:raise DocoptcfgError: If `config_option` isn't found in docstring.
:raise DocoptcfgFileError: On any error while trying to read and... | [
"def",
"docoptcfg",
"(",
"doc",
",",
"argv",
"=",
"None",
",",
"env_prefix",
"=",
"None",
",",
"config_option",
"=",
"None",
",",
"ignore",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"docopt_dict",
"=",
"docopt",
".",
"docopt",... | Pass most args/kwargs to docopt. Handle `env_prefix` and `config_option`.
:raise DocoptcfgError: If `config_option` isn't found in docstring.
:raise DocoptcfgFileError: On any error while trying to read and parse config file (if enabled).
:param str doc: Docstring passed to docopt.
:param iter argv: s... | [
"Pass",
"most",
"args",
"/",
"kwargs",
"to",
"docopt",
".",
"Handle",
"env_prefix",
"and",
"config_option",
"."
] | train | https://github.com/Robpol86/docoptcfg/blob/3746dc263549f7f3ef5a86e739d588546b084bde/docoptcfg.py#L234-L279 |
TC01/calcpkg | calcrepo/repo.py | CalcRepository.setRepoData | def setRepoData(self, searchString, category="", extension="", math=False, game=False, searchFiles=False):
"""Call this function with all the settings to use for future operations on a repository, must be called FIRST"""
self.searchString = searchString
self.category = category
self.math = math
self.game = ga... | python | def setRepoData(self, searchString, category="", extension="", math=False, game=False, searchFiles=False):
"""Call this function with all the settings to use for future operations on a repository, must be called FIRST"""
self.searchString = searchString
self.category = category
self.math = math
self.game = ga... | [
"def",
"setRepoData",
"(",
"self",
",",
"searchString",
",",
"category",
"=",
"\"\"",
",",
"extension",
"=",
"\"\"",
",",
"math",
"=",
"False",
",",
"game",
"=",
"False",
",",
"searchFiles",
"=",
"False",
")",
":",
"self",
".",
"searchString",
"=",
"se... | Call this function with all the settings to use for future operations on a repository, must be called FIRST | [
"Call",
"this",
"function",
"with",
"all",
"the",
"settings",
"to",
"use",
"for",
"future",
"operations",
"on",
"a",
"repository",
"must",
"be",
"called",
"FIRST"
] | train | https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/repo.py#L37-L44 |
TC01/calcpkg | calcrepo/repo.py | CalcRepository.setOutputObject | def setOutputObject(self, newOutput=output.CalcpkgOutput(True, True)):
"""Set an object where all output from calcpkg will be redirected to for this repository"""
self.output = newOutput | python | def setOutputObject(self, newOutput=output.CalcpkgOutput(True, True)):
"""Set an object where all output from calcpkg will be redirected to for this repository"""
self.output = newOutput | [
"def",
"setOutputObject",
"(",
"self",
",",
"newOutput",
"=",
"output",
".",
"CalcpkgOutput",
"(",
"True",
",",
"True",
")",
")",
":",
"self",
".",
"output",
"=",
"newOutput"
] | Set an object where all output from calcpkg will be redirected to for this repository | [
"Set",
"an",
"object",
"where",
"all",
"output",
"from",
"calcpkg",
"will",
"be",
"redirected",
"to",
"for",
"this",
"repository"
] | train | https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/repo.py#L46-L48 |
TC01/calcpkg | calcrepo/repo.py | CalcRepository.searchIndex | def searchIndex(self, printData=True):
"""Search the index with all the repo's specified parameters"""
backupValue = copy.deepcopy(self.output.printData)
self.output.printData = printData
self.data = self.index.search(self.searchString, self.category, self.math, self.game, self.searchFiles, self.extension)
se... | python | def searchIndex(self, printData=True):
"""Search the index with all the repo's specified parameters"""
backupValue = copy.deepcopy(self.output.printData)
self.output.printData = printData
self.data = self.index.search(self.searchString, self.category, self.math, self.game, self.searchFiles, self.extension)
se... | [
"def",
"searchIndex",
"(",
"self",
",",
"printData",
"=",
"True",
")",
":",
"backupValue",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"output",
".",
"printData",
")",
"self",
".",
"output",
".",
"printData",
"=",
"printData",
"self",
".",
"data",
... | Search the index with all the repo's specified parameters | [
"Search",
"the",
"index",
"with",
"all",
"the",
"repo",
"s",
"specified",
"parameters"
] | train | https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/repo.py#L53-L59 |
TC01/calcpkg | calcrepo/repo.py | CalcRepository.countIndex | def countIndex(self):
"""A wrapper for the count function in calcrepo.index; count using specified parameters"""
self.data = self.index.count(self.searchString, self.category, self.math, self.game, self.searchFiles, self.extension) | python | def countIndex(self):
"""A wrapper for the count function in calcrepo.index; count using specified parameters"""
self.data = self.index.count(self.searchString, self.category, self.math, self.game, self.searchFiles, self.extension) | [
"def",
"countIndex",
"(",
"self",
")",
":",
"self",
".",
"data",
"=",
"self",
".",
"index",
".",
"count",
"(",
"self",
".",
"searchString",
",",
"self",
".",
"category",
",",
"self",
".",
"math",
",",
"self",
".",
"game",
",",
"self",
".",
"searchF... | A wrapper for the count function in calcrepo.index; count using specified parameters | [
"A",
"wrapper",
"for",
"the",
"count",
"function",
"in",
"calcrepo",
".",
"index",
";",
"count",
"using",
"specified",
"parameters"
] | train | https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/repo.py#L61-L63 |
TC01/calcpkg | calcrepo/repo.py | CalcRepository.getDownloadUrls | def getDownloadUrls(self):
"""Return a list of the urls to download from"""
data = self.searchIndex(False)
fileUrls = []
for datum in data:
fileUrl = self.formatDownloadUrl(datum[0])
fileUrls.append(fileUrl)
return fileUrls | python | def getDownloadUrls(self):
"""Return a list of the urls to download from"""
data = self.searchIndex(False)
fileUrls = []
for datum in data:
fileUrl = self.formatDownloadUrl(datum[0])
fileUrls.append(fileUrl)
return fileUrls | [
"def",
"getDownloadUrls",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"searchIndex",
"(",
"False",
")",
"fileUrls",
"=",
"[",
"]",
"for",
"datum",
"in",
"data",
":",
"fileUrl",
"=",
"self",
".",
"formatDownloadUrl",
"(",
"datum",
"[",
"0",
"]",
... | Return a list of the urls to download from | [
"Return",
"a",
"list",
"of",
"the",
"urls",
"to",
"download",
"from"
] | train | https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/repo.py#L65-L72 |
TC01/calcpkg | calcrepo/repo.py | CalcRepository.getFileInfos | def getFileInfos(self):
"""Return a list of FileInfo objects"""
data = self.searchIndex(False)
self.data = data
self.printd(" ")
fileInfos = []
for datum in data:
try:
fileInfo = self.getFileInfo(datum[0], datum[1])
fileInfos.append(fileInfo)
except NotImplementedError:
self.printd("Error:... | python | def getFileInfos(self):
"""Return a list of FileInfo objects"""
data = self.searchIndex(False)
self.data = data
self.printd(" ")
fileInfos = []
for datum in data:
try:
fileInfo = self.getFileInfo(datum[0], datum[1])
fileInfos.append(fileInfo)
except NotImplementedError:
self.printd("Error:... | [
"def",
"getFileInfos",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"searchIndex",
"(",
"False",
")",
"self",
".",
"data",
"=",
"data",
"self",
".",
"printd",
"(",
"\" \"",
")",
"fileInfos",
"=",
"[",
"]",
"for",
"datum",
"in",
"data",
":",
"tr... | Return a list of FileInfo objects | [
"Return",
"a",
"list",
"of",
"FileInfo",
"objects"
] | train | https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/repo.py#L74-L87 |
TC01/calcpkg | calcrepo/repo.py | CalcRepository.downloadFiles | def downloadFiles(self, prompt=True, extract=False):
"""Download files from the repository"""
#First, get the download urls
data = self.data
downloadUrls = self.getDownloadUrls()
#Then, confirm the user wants to do this
if prompt:
confirm = raw_input("Download files [Y/N]? ")
if confirm.lower() != ... | python | def downloadFiles(self, prompt=True, extract=False):
"""Download files from the repository"""
#First, get the download urls
data = self.data
downloadUrls = self.getDownloadUrls()
#Then, confirm the user wants to do this
if prompt:
confirm = raw_input("Download files [Y/N]? ")
if confirm.lower() != ... | [
"def",
"downloadFiles",
"(",
"self",
",",
"prompt",
"=",
"True",
",",
"extract",
"=",
"False",
")",
":",
"#First, get the download urls",
"data",
"=",
"self",
".",
"data",
"downloadUrls",
"=",
"self",
".",
"getDownloadUrls",
"(",
")",
"#Then, confirm the user wa... | Download files from the repository | [
"Download",
"files",
"from",
"the",
"repository"
] | train | https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/repo.py#L89-L166 |
TC01/calcpkg | calcrepo/repo.py | CalcRepository.downloadFileFromUrl | def downloadFileFromUrl(self, url):
"""Given a URL, download the specified file"""
fullurl = self.baseUrl + url
try:
urlobj = urllib2.urlopen(fullurl)
contents = urlobj.read()
except urllib2.HTTPError, e:
self.printd("HTTP error:", e.code, url)
return None
except urllib2.URLError, e:
self.print... | python | def downloadFileFromUrl(self, url):
"""Given a URL, download the specified file"""
fullurl = self.baseUrl + url
try:
urlobj = urllib2.urlopen(fullurl)
contents = urlobj.read()
except urllib2.HTTPError, e:
self.printd("HTTP error:", e.code, url)
return None
except urllib2.URLError, e:
self.print... | [
"def",
"downloadFileFromUrl",
"(",
"self",
",",
"url",
")",
":",
"fullurl",
"=",
"self",
".",
"baseUrl",
"+",
"url",
"try",
":",
"urlobj",
"=",
"urllib2",
".",
"urlopen",
"(",
"fullurl",
")",
"contents",
"=",
"urlobj",
".",
"read",
"(",
")",
"except",
... | Given a URL, download the specified file | [
"Given",
"a",
"URL",
"download",
"the",
"specified",
"file"
] | train | https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/repo.py#L185-L198 |
TC01/calcpkg | calcrepo/repo.py | CalcRepository.openIndex | def openIndex(self, filename, description):
"""Attempt to delete and recreate an index, returns open file object or None."""
try:
os.remove(filename)
self.printd(" Deleted old " + description)
except:
self.printd(" No " + description + " found")
# Now, attempt to open a new index
try:
files ... | python | def openIndex(self, filename, description):
"""Attempt to delete and recreate an index, returns open file object or None."""
try:
os.remove(filename)
self.printd(" Deleted old " + description)
except:
self.printd(" No " + description + " found")
# Now, attempt to open a new index
try:
files ... | [
"def",
"openIndex",
"(",
"self",
",",
"filename",
",",
"description",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"filename",
")",
"self",
".",
"printd",
"(",
"\" Deleted old \"",
"+",
"description",
")",
"except",
":",
"self",
".",
"printd",
"(",
... | Attempt to delete and recreate an index, returns open file object or None. | [
"Attempt",
"to",
"delete",
"and",
"recreate",
"an",
"index",
"returns",
"open",
"file",
"object",
"or",
"None",
"."
] | train | https://github.com/TC01/calcpkg/blob/5168f606264620a090b42a64354331d208b00d5f/calcrepo/repo.py#L200-L214 |
rikrd/inspire | inspirespeech/htk_model.py | load_model | def load_model(*args):
"""Load an HTK model from one ore more files.
:param args: Filenames of the model (e.g. macros hmmdefs)
:return: The model as an OrderedDict()
"""
text = ''
for fnm in args:
text += open(fnm).read()
text += '\n'
parser = htk_model_parser.htk_modelPars... | python | def load_model(*args):
"""Load an HTK model from one ore more files.
:param args: Filenames of the model (e.g. macros hmmdefs)
:return: The model as an OrderedDict()
"""
text = ''
for fnm in args:
text += open(fnm).read()
text += '\n'
parser = htk_model_parser.htk_modelPars... | [
"def",
"load_model",
"(",
"*",
"args",
")",
":",
"text",
"=",
"''",
"for",
"fnm",
"in",
"args",
":",
"text",
"+=",
"open",
"(",
"fnm",
")",
".",
"read",
"(",
")",
"text",
"+=",
"'\\n'",
"parser",
"=",
"htk_model_parser",
".",
"htk_modelParser",
"(",
... | Load an HTK model from one ore more files.
:param args: Filenames of the model (e.g. macros hmmdefs)
:return: The model as an OrderedDict() | [
"Load",
"an",
"HTK",
"model",
"from",
"one",
"ore",
"more",
"files",
"."
] | train | https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/htk_model.py#L85-L103 |
rikrd/inspire | inspirespeech/htk_model.py | save_model | def save_model(model, filename):
"""Save the model into a file.
:param model: HTK model to be saved
:param filename: File where to save the model
"""
with open(filename, 'w') as f:
f.write(serialize_model(model)) | python | def save_model(model, filename):
"""Save the model into a file.
:param model: HTK model to be saved
:param filename: File where to save the model
"""
with open(filename, 'w') as f:
f.write(serialize_model(model)) | [
"def",
"save_model",
"(",
"model",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"serialize_model",
"(",
"model",
")",
")"
] | Save the model into a file.
:param model: HTK model to be saved
:param filename: File where to save the model | [
"Save",
"the",
"model",
"into",
"a",
"file",
"."
] | train | https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/htk_model.py#L306-L313 |
rikrd/inspire | inspirespeech/htk_model.py | serialize_model | def serialize_model(model):
"""Serialize the HTK model into a file.
:param model: Model to be serialized
"""
result = ''
# First serialize the macros
for macro in model['macros']:
if macro.get('options', None):
result += '~o '
for option in macro['options']['de... | python | def serialize_model(model):
"""Serialize the HTK model into a file.
:param model: Model to be serialized
"""
result = ''
# First serialize the macros
for macro in model['macros']:
if macro.get('options', None):
result += '~o '
for option in macro['options']['de... | [
"def",
"serialize_model",
"(",
"model",
")",
":",
"result",
"=",
"''",
"# First serialize the macros",
"for",
"macro",
"in",
"model",
"[",
"'macros'",
"]",
":",
"if",
"macro",
".",
"get",
"(",
"'options'",
",",
"None",
")",
":",
"result",
"+=",
"'~o '",
... | Serialize the HTK model into a file.
:param model: Model to be serialized | [
"Serialize",
"the",
"HTK",
"model",
"into",
"a",
"file",
"."
] | train | https://github.com/rikrd/inspire/blob/e281c0266a9a9633f34ab70f9c3ad58036c19b59/inspirespeech/htk_model.py#L316-L360 |
ch3pjw/junction | jcn/display_elements.py | ABCDisplayElement._do_crop | def _do_crop(self, lines, width, height, x_crop, y_crop):
'''Crops a list of strings to the specified width/height
'''
lines = crop_or_expand(
lines, height, default=[self.fillchar * width],
scheme=self._schemes[y_crop])
for i, line in enumerate(lines):
... | python | def _do_crop(self, lines, width, height, x_crop, y_crop):
'''Crops a list of strings to the specified width/height
'''
lines = crop_or_expand(
lines, height, default=[self.fillchar * width],
scheme=self._schemes[y_crop])
for i, line in enumerate(lines):
... | [
"def",
"_do_crop",
"(",
"self",
",",
"lines",
",",
"width",
",",
"height",
",",
"x_crop",
",",
"y_crop",
")",
":",
"lines",
"=",
"crop_or_expand",
"(",
"lines",
",",
"height",
",",
"default",
"=",
"[",
"self",
".",
"fillchar",
"*",
"width",
"]",
",",... | Crops a list of strings to the specified width/height | [
"Crops",
"a",
"list",
"of",
"strings",
"to",
"the",
"specified",
"width",
"/",
"height"
] | train | https://github.com/ch3pjw/junction/blob/7d0c4d279589bee8ae7b3ac4dee2ab425c0b1b0e/jcn/display_elements.py#L43-L53 |
sassoo/goldman | goldman/api.py | API._load_resources | def _load_resources(self):
""" Load all the native goldman resources.
The route or API endpoint will be automatically determined
based on the resource object instance passed in.
INFO: Only our Model based resources are supported when
auto-generating API endpoints.
... | python | def _load_resources(self):
""" Load all the native goldman resources.
The route or API endpoint will be automatically determined
based on the resource object instance passed in.
INFO: Only our Model based resources are supported when
auto-generating API endpoints.
... | [
"def",
"_load_resources",
"(",
"self",
")",
":",
"for",
"resource",
"in",
"self",
".",
"RESOURCES",
":",
"if",
"isinstance",
"(",
"resource",
",",
"goldman",
".",
"ModelsResource",
")",
":",
"route",
"=",
"'/%s'",
"%",
"resource",
".",
"rtype",
"elif",
"... | Load all the native goldman resources.
The route or API endpoint will be automatically determined
based on the resource object instance passed in.
INFO: Only our Model based resources are supported when
auto-generating API endpoints. | [
"Load",
"all",
"the",
"native",
"goldman",
"resources",
"."
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/api.py#L55-L75 |
sassoo/goldman | goldman/api.py | API._error_serializer | def _error_serializer(req, exc): # pylint: disable=unused-argument
""" Serializer for native falcon HTTPError exceptions.
We override the default serializer with our own so we
can ensure the errors are serialized in a JSON API
compliant format.
Surprisingly, most falcon error ... | python | def _error_serializer(req, exc): # pylint: disable=unused-argument
""" Serializer for native falcon HTTPError exceptions.
We override the default serializer with our own so we
can ensure the errors are serialized in a JSON API
compliant format.
Surprisingly, most falcon error ... | [
"def",
"_error_serializer",
"(",
"req",
",",
"exc",
")",
":",
"# pylint: disable=unused-argument",
"error",
"=",
"{",
"'detail'",
":",
"exc",
".",
"description",
",",
"'title'",
":",
"exc",
".",
"title",
",",
"'status'",
":",
"exc",
".",
"status",
",",
"}"... | Serializer for native falcon HTTPError exceptions.
We override the default serializer with our own so we
can ensure the errors are serialized in a JSON API
compliant format.
Surprisingly, most falcon error attributes map directly
to the JSON API spec. The few that don't can be ... | [
"Serializer",
"for",
"native",
"falcon",
"HTTPError",
"exceptions",
"."
] | train | https://github.com/sassoo/goldman/blob/b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2/goldman/api.py#L108-L145 |
lambdalisue/maidenhair | src/maidenhair/utils/peakset.py | find_peakset | def find_peakset(dataset, basecolumn=-1, method='', where=None):
"""
Find peakset from the dataset
Parameters
-----------
dataset : list
A list of data
basecolumn : int
An index of column for finding peaks
method : str
A method name of numpy for finding peaks
whe... | python | def find_peakset(dataset, basecolumn=-1, method='', where=None):
"""
Find peakset from the dataset
Parameters
-----------
dataset : list
A list of data
basecolumn : int
An index of column for finding peaks
method : str
A method name of numpy for finding peaks
whe... | [
"def",
"find_peakset",
"(",
"dataset",
",",
"basecolumn",
"=",
"-",
"1",
",",
"method",
"=",
"''",
",",
"where",
"=",
"None",
")",
":",
"peakset",
"=",
"[",
"]",
"where_i",
"=",
"None",
"for",
"data",
"in",
"dataset",
":",
"base",
"=",
"data",
"[",... | Find peakset from the dataset
Parameters
-----------
dataset : list
A list of data
basecolumn : int
An index of column for finding peaks
method : str
A method name of numpy for finding peaks
where : function
A function which recieve ``data`` and return numpy inde... | [
"Find",
"peakset",
"from",
"the",
"dataset"
] | train | https://github.com/lambdalisue/maidenhair/blob/d5095c1087d1f4d71cc57410492151d2803a9f0d/src/maidenhair/utils/peakset.py#L9-L49 |
praekeltfoundation/seed-control-interface-service | seed_control_interface_service/utils.py | normalise_string | def normalise_string(string):
""" Strips trailing whitespace from string, lowercases it and replaces
spaces with underscores
"""
string = (string.strip()).lower()
return re.sub(r'\W+', '_', string) | python | def normalise_string(string):
""" Strips trailing whitespace from string, lowercases it and replaces
spaces with underscores
"""
string = (string.strip()).lower()
return re.sub(r'\W+', '_', string) | [
"def",
"normalise_string",
"(",
"string",
")",
":",
"string",
"=",
"(",
"string",
".",
"strip",
"(",
")",
")",
".",
"lower",
"(",
")",
"return",
"re",
".",
"sub",
"(",
"r'\\W+'",
",",
"'_'",
",",
"string",
")"
] | Strips trailing whitespace from string, lowercases it and replaces
spaces with underscores | [
"Strips",
"trailing",
"whitespace",
"from",
"string",
"lowercases",
"it",
"and",
"replaces",
"spaces",
"with",
"underscores"
] | train | https://github.com/praekeltfoundation/seed-control-interface-service/blob/0c8ec58ae61e72d4443e6c9a4d8b7dd12dd8a86e/seed_control_interface_service/utils.py#L6-L11 |
praekeltfoundation/seed-control-interface-service | seed_control_interface_service/utils.py | json_decode | def json_decode(data):
"""
Decodes the given JSON as primitives
"""
if isinstance(data, six.binary_type):
data = data.decode('utf-8')
return json.loads(data) | python | def json_decode(data):
"""
Decodes the given JSON as primitives
"""
if isinstance(data, six.binary_type):
data = data.decode('utf-8')
return json.loads(data) | [
"def",
"json_decode",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"binary_type",
")",
":",
"data",
"=",
"data",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"json",
".",
"loads",
"(",
"data",
")"
] | Decodes the given JSON as primitives | [
"Decodes",
"the",
"given",
"JSON",
"as",
"primitives"
] | train | https://github.com/praekeltfoundation/seed-control-interface-service/blob/0c8ec58ae61e72d4443e6c9a4d8b7dd12dd8a86e/seed_control_interface_service/utils.py#L14-L21 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/wstools/logging.py | gridLog | def gridLog(**kw):
"""Send GLRecord, Distributed Logging Utilities
If the scheme is passed as a keyword parameter
the value is expected to be a callable function
that takes 2 parameters: url, outputStr
GRIDLOG_ON -- turn grid logging on
GRIDLOG_DEST -- provide URL destination
"""
impo... | python | def gridLog(**kw):
"""Send GLRecord, Distributed Logging Utilities
If the scheme is passed as a keyword parameter
the value is expected to be a callable function
that takes 2 parameters: url, outputStr
GRIDLOG_ON -- turn grid logging on
GRIDLOG_DEST -- provide URL destination
"""
impo... | [
"def",
"gridLog",
"(",
"*",
"*",
"kw",
")",
":",
"import",
"os",
"if",
"not",
"bool",
"(",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'GRIDLOG_ON'",
",",
"0",
")",
")",
")",
":",
"return",
"url",
"=",
"os",
".",
"environ",
".",
"get",
... | Send GLRecord, Distributed Logging Utilities
If the scheme is passed as a keyword parameter
the value is expected to be a callable function
that takes 2 parameters: url, outputStr
GRIDLOG_ON -- turn grid logging on
GRIDLOG_DEST -- provide URL destination | [
"Send",
"GLRecord",
"Distributed",
"Logging",
"Utilities",
"If",
"the",
"scheme",
"is",
"passed",
"as",
"a",
"keyword",
"parameter",
"the",
"value",
"is",
"expected",
"to",
"be",
"a",
"callable",
"function",
"that",
"takes",
"2",
"parameters",
":",
"url",
"o... | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/logging.py#L185-L209 |
rameshg87/pyremotevbox | pyremotevbox/ZSI/wstools/logging.py | BasicLogger.write | def write(self, *args):
'''Write convenience function; writes strings.
'''
for s in args: self.out.write(s)
event = ''.join(*args) | python | def write(self, *args):
'''Write convenience function; writes strings.
'''
for s in args: self.out.write(s)
event = ''.join(*args) | [
"def",
"write",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"s",
"in",
"args",
":",
"self",
".",
"out",
".",
"write",
"(",
"s",
")",
"event",
"=",
"''",
".",
"join",
"(",
"*",
"args",
")"
] | Write convenience function; writes strings. | [
"Write",
"convenience",
"function",
";",
"writes",
"strings",
"."
] | train | https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/logging.py#L65-L69 |
pip-services3-python/pip-services3-components-python | pip_services3_components/count/LogCounters.py | LogCounters._save | def _save(self, counters):
"""
Saves the current counters measurements.
:param counters: current counters measurements to be saves.
"""
if self._logger == None:
return
if len(counters) == 0:
return
# Sort counters by name
counters... | python | def _save(self, counters):
"""
Saves the current counters measurements.
:param counters: current counters measurements to be saves.
"""
if self._logger == None:
return
if len(counters) == 0:
return
# Sort counters by name
counters... | [
"def",
"_save",
"(",
"self",
",",
"counters",
")",
":",
"if",
"self",
".",
"_logger",
"==",
"None",
":",
"return",
"if",
"len",
"(",
"counters",
")",
"==",
"0",
":",
"return",
"# Sort counters by name",
"counters",
"=",
"sorted",
"(",
"counters",
",",
... | Saves the current counters measurements.
:param counters: current counters measurements to be saves. | [
"Saves",
"the",
"current",
"counters",
"measurements",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/LogCounters.py#L87-L102 |
noirbizarre/minibench | minibench/utils.py | humanize | def humanize(text):
'''Transform code conventions to human readable strings'''
words = []
for part in text.split('_'):
for word in RE_CAMEL.findall(part) or [part]:
words.append(word.lower())
words[0] = words[0].title()
return ' '.join(words) | python | def humanize(text):
'''Transform code conventions to human readable strings'''
words = []
for part in text.split('_'):
for word in RE_CAMEL.findall(part) or [part]:
words.append(word.lower())
words[0] = words[0].title()
return ' '.join(words) | [
"def",
"humanize",
"(",
"text",
")",
":",
"words",
"=",
"[",
"]",
"for",
"part",
"in",
"text",
".",
"split",
"(",
"'_'",
")",
":",
"for",
"word",
"in",
"RE_CAMEL",
".",
"findall",
"(",
"part",
")",
"or",
"[",
"part",
"]",
":",
"words",
".",
"ap... | Transform code conventions to human readable strings | [
"Transform",
"code",
"conventions",
"to",
"human",
"readable",
"strings"
] | train | https://github.com/noirbizarre/minibench/blob/a1ac66dc075181c62bb3c0d3a26beb5c46d5f4ab/minibench/utils.py#L9-L16 |
mbodenhamer/syn | syn/types/a/ne.py | is_visit_primitive | def is_visit_primitive(obj):
'''Returns true if properly visiting the object returns only the object itself.'''
from .base import visit
if (isinstance(obj, tuple(PRIMITIVE_TYPES)) and not isinstance(obj, STR)
and not isinstance(obj, bytes)):
return True
if (isinstance(obj, CONTAINERS) an... | python | def is_visit_primitive(obj):
'''Returns true if properly visiting the object returns only the object itself.'''
from .base import visit
if (isinstance(obj, tuple(PRIMITIVE_TYPES)) and not isinstance(obj, STR)
and not isinstance(obj, bytes)):
return True
if (isinstance(obj, CONTAINERS) an... | [
"def",
"is_visit_primitive",
"(",
"obj",
")",
":",
"from",
".",
"base",
"import",
"visit",
"if",
"(",
"isinstance",
"(",
"obj",
",",
"tuple",
"(",
"PRIMITIVE_TYPES",
")",
")",
"and",
"not",
"isinstance",
"(",
"obj",
",",
"STR",
")",
"and",
"not",
"isin... | Returns true if properly visiting the object returns only the object itself. | [
"Returns",
"true",
"if",
"properly",
"visiting",
"the",
"object",
"returns",
"only",
"the",
"object",
"itself",
"."
] | train | https://github.com/mbodenhamer/syn/blob/aeaa3ad8a49bac8f50cf89b6f1fe97ad43d1d258/syn/types/a/ne.py#L516-L529 |
pip-services3-python/pip-services3-components-python | pip_services3_components/cache/MemoryCache.py | MemoryCache.configure | def configure(self, config):
"""
Configures component by passing configuration parameters.
:param config: configuration parameters to be set.
"""
self._timeout = config.get_as_long_with_default("options.timeout", self._default_timeout)
self._max_size = config.get_as_long... | python | def configure(self, config):
"""
Configures component by passing configuration parameters.
:param config: configuration parameters to be set.
"""
self._timeout = config.get_as_long_with_default("options.timeout", self._default_timeout)
self._max_size = config.get_as_long... | [
"def",
"configure",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"_timeout",
"=",
"config",
".",
"get_as_long_with_default",
"(",
"\"options.timeout\"",
",",
"self",
".",
"_default_timeout",
")",
"self",
".",
"_max_size",
"=",
"config",
".",
"get_as_long... | Configures component by passing configuration parameters.
:param config: configuration parameters to be set. | [
"Configures",
"component",
"by",
"passing",
"configuration",
"parameters",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/cache/MemoryCache.py#L56-L63 |
pip-services3-python/pip-services3-components-python | pip_services3_components/cache/MemoryCache.py | MemoryCache.clear | def clear(self, correlation_id):
"""
Clears component state.
:param correlation_id: (optional) transaction id to trace execution through call chain.
"""
self._lock.acquire()
try:
self._cache = {}
finally:
self._lock.release() | python | def clear(self, correlation_id):
"""
Clears component state.
:param correlation_id: (optional) transaction id to trace execution through call chain.
"""
self._lock.acquire()
try:
self._cache = {}
finally:
self._lock.release() | [
"def",
"clear",
"(",
"self",
",",
"correlation_id",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_cache",
"=",
"{",
"}",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | Clears component state.
:param correlation_id: (optional) transaction id to trace execution through call chain. | [
"Clears",
"component",
"state",
"."
] | train | https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/cache/MemoryCache.py#L181-L191 |
ronaldguillen/wave | wave/decorators.py | rest_verbs | def rest_verbs(http_method_names=None):
"""
Decorator that converts a function-based view into an RestView subclass.
Takes a list of allowed methods for the view as an argument.
"""
http_method_names = ['GET'] if (http_method_names is None) else http_method_names
def decorator(func):
... | python | def rest_verbs(http_method_names=None):
"""
Decorator that converts a function-based view into an RestView subclass.
Takes a list of allowed methods for the view as an argument.
"""
http_method_names = ['GET'] if (http_method_names is None) else http_method_names
def decorator(func):
... | [
"def",
"rest_verbs",
"(",
"http_method_names",
"=",
"None",
")",
":",
"http_method_names",
"=",
"[",
"'GET'",
"]",
"if",
"(",
"http_method_names",
"is",
"None",
")",
"else",
"http_method_names",
"def",
"decorator",
"(",
"func",
")",
":",
"WrappedRestView",
"="... | Decorator that converts a function-based view into an RestView subclass.
Takes a list of allowed methods for the view as an argument. | [
"Decorator",
"that",
"converts",
"a",
"function",
"-",
"based",
"view",
"into",
"an",
"RestView",
"subclass",
".",
"Takes",
"a",
"list",
"of",
"allowed",
"methods",
"for",
"the",
"view",
"as",
"an",
"argument",
"."
] | train | https://github.com/ronaldguillen/wave/blob/20bb979c917f7634d8257992e6d449dc751256a9/wave/decorators.py#L18-L76 |
minorg/pastpy | py/src/pastpy/gen/database/database_configuration.py | DatabaseConfiguration.read | def read(cls, iprot):
'''
Read a new object from the given input protocol and return the object.
:type iprot: thryft.protocol._input_protocol._InputProtocol
:rtype: pastpy.gen.database.database_configuration.DatabaseConfiguration
'''
init_kwds = {}
iprot.read_s... | python | def read(cls, iprot):
'''
Read a new object from the given input protocol and return the object.
:type iprot: thryft.protocol._input_protocol._InputProtocol
:rtype: pastpy.gen.database.database_configuration.DatabaseConfiguration
'''
init_kwds = {}
iprot.read_s... | [
"def",
"read",
"(",
"cls",
",",
"iprot",
")",
":",
"init_kwds",
"=",
"{",
"}",
"iprot",
".",
"read_struct_begin",
"(",
")",
"while",
"True",
":",
"ifield_name",
",",
"ifield_type",
",",
"_ifield_id",
"=",
"iprot",
".",
"read_field_begin",
"(",
")",
"if",... | Read a new object from the given input protocol and return the object.
:type iprot: thryft.protocol._input_protocol._InputProtocol
:rtype: pastpy.gen.database.database_configuration.DatabaseConfiguration | [
"Read",
"a",
"new",
"object",
"from",
"the",
"given",
"input",
"protocol",
"and",
"return",
"the",
"object",
"."
] | train | https://github.com/minorg/pastpy/blob/7d5d6d511629481850216565e7451b5dcb8027a9/py/src/pastpy/gen/database/database_configuration.py#L241-L265 |
minorg/pastpy | py/src/pastpy/gen/database/database_configuration.py | DatabaseConfiguration.write | def write(self, oprot):
'''
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.database_configuration.DatabaseConfiguration
'''
oprot.write_struct_begin('DatabaseConfi... | python | def write(self, oprot):
'''
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.database_configuration.DatabaseConfiguration
'''
oprot.write_struct_begin('DatabaseConfi... | [
"def",
"write",
"(",
"self",
",",
"oprot",
")",
":",
"oprot",
".",
"write_struct_begin",
"(",
"'DatabaseConfiguration'",
")",
"if",
"self",
".",
"dbf",
"is",
"not",
"None",
":",
"oprot",
".",
"write_field_begin",
"(",
"name",
"=",
"'dbf'",
",",
"type",
"... | Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.database_configuration.DatabaseConfiguration | [
"Write",
"this",
"object",
"to",
"the",
"given",
"output",
"protocol",
"and",
"return",
"self",
"."
] | train | https://github.com/minorg/pastpy/blob/7d5d6d511629481850216565e7451b5dcb8027a9/py/src/pastpy/gen/database/database_configuration.py#L280-L309 |
Bouni/swisshydrodata | swisshydrodata/__init__.py | SwissHydroData.get_stations | def get_stations(self):
""" Return a list of all stations IDs """
request = requests.get("{}/stations".format(
self.base_url))
if request.status_code != 200:
return None
return request.json() | python | def get_stations(self):
""" Return a list of all stations IDs """
request = requests.get("{}/stations".format(
self.base_url))
if request.status_code != 200:
return None
return request.json() | [
"def",
"get_stations",
"(",
"self",
")",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"\"{}/stations\"",
".",
"format",
"(",
"self",
".",
"base_url",
")",
")",
"if",
"request",
".",
"status_code",
"!=",
"200",
":",
"return",
"None",
"return",
"reque... | Return a list of all stations IDs | [
"Return",
"a",
"list",
"of",
"all",
"stations",
"IDs"
] | train | https://github.com/Bouni/swisshydrodata/blob/6434e5927560e53b6b6b5d9c1c85de5cc351da3a/swisshydrodata/__init__.py#L21-L27 |
Bouni/swisshydrodata | swisshydrodata/__init__.py | SwissHydroData.get_station_temperature_datetime | def get_station_temperature_datetime(self, station_id):
""" Return temperature measurement datetime for a given station """
request = requests.get(
"{}/station/{}/parameters/temperature/datetime".format(
self.base_url, station_id))
if request.status_code != 200:
... | python | def get_station_temperature_datetime(self, station_id):
""" Return temperature measurement datetime for a given station """
request = requests.get(
"{}/station/{}/parameters/temperature/datetime".format(
self.base_url, station_id))
if request.status_code != 200:
... | [
"def",
"get_station_temperature_datetime",
"(",
"self",
",",
"station_id",
")",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"\"{}/station/{}/parameters/temperature/datetime\"",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"station_id",
")",
")",
"if",
"... | Return temperature measurement datetime for a given station | [
"Return",
"temperature",
"measurement",
"datetime",
"for",
"a",
"given",
"station"
] | train | https://github.com/Bouni/swisshydrodata/blob/6434e5927560e53b6b6b5d9c1c85de5cc351da3a/swisshydrodata/__init__.py#L94-L101 |
Bouni/swisshydrodata | swisshydrodata/__init__.py | SwissHydroData.get_station_temperature_value | def get_station_temperature_value(self, station_id):
""" Return temperature value for a given station """
request = requests.get(
"{}/station/{}/parameters/temperature/value".format(
self.base_url, station_id))
if request.status_code != 200:
return None
... | python | def get_station_temperature_value(self, station_id):
""" Return temperature value for a given station """
request = requests.get(
"{}/station/{}/parameters/temperature/value".format(
self.base_url, station_id))
if request.status_code != 200:
return None
... | [
"def",
"get_station_temperature_value",
"(",
"self",
",",
"station_id",
")",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"\"{}/station/{}/parameters/temperature/value\"",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"station_id",
")",
")",
"if",
"reques... | Return temperature value for a given station | [
"Return",
"temperature",
"value",
"for",
"a",
"given",
"station"
] | train | https://github.com/Bouni/swisshydrodata/blob/6434e5927560e53b6b6b5d9c1c85de5cc351da3a/swisshydrodata/__init__.py#L103-L110 |
lumpywizard/check_email_status | check_email_status/__init__.py | check_email_status | def check_email_status(mx_resolver, recipient_address, sender_address, smtp_timeout=10, helo_hostname=None):
"""
Checks if an email might be valid by getting the status from the SMTP server.
:param mx_resolver: MXResolver
:param recipient_address: string
:param sender_address: string
:param smt... | python | def check_email_status(mx_resolver, recipient_address, sender_address, smtp_timeout=10, helo_hostname=None):
"""
Checks if an email might be valid by getting the status from the SMTP server.
:param mx_resolver: MXResolver
:param recipient_address: string
:param sender_address: string
:param smt... | [
"def",
"check_email_status",
"(",
"mx_resolver",
",",
"recipient_address",
",",
"sender_address",
",",
"smtp_timeout",
"=",
"10",
",",
"helo_hostname",
"=",
"None",
")",
":",
"domain",
"=",
"recipient_address",
"[",
"recipient_address",
".",
"find",
"(",
"'@'",
... | Checks if an email might be valid by getting the status from the SMTP server.
:param mx_resolver: MXResolver
:param recipient_address: string
:param sender_address: string
:param smtp_timeout: integer
:param helo_hostname: string
:return: dict | [
"Checks",
"if",
"an",
"email",
"might",
"be",
"valid",
"by",
"getting",
"the",
"status",
"from",
"the",
"SMTP",
"server",
"."
] | train | https://github.com/lumpywizard/check_email_status/blob/3a4c5dc42ada61325d5d9baad9e2b1b78084ee2f/check_email_status/__init__.py#L6-L59 |
acsone/streamingxmlwriter | streamingxmlwriter/core.py | _StreamingXMLWriter.start_namespace | def start_namespace(self, prefix, uri):
""" Declare a namespace prefix
Use prefix=None to set the default namespace.
"""
self._g.startPrefixMapping(prefix, uri)
self._ns[prefix] = uri | python | def start_namespace(self, prefix, uri):
""" Declare a namespace prefix
Use prefix=None to set the default namespace.
"""
self._g.startPrefixMapping(prefix, uri)
self._ns[prefix] = uri | [
"def",
"start_namespace",
"(",
"self",
",",
"prefix",
",",
"uri",
")",
":",
"self",
".",
"_g",
".",
"startPrefixMapping",
"(",
"prefix",
",",
"uri",
")",
"self",
".",
"_ns",
"[",
"prefix",
"]",
"=",
"uri"
] | Declare a namespace prefix
Use prefix=None to set the default namespace. | [
"Declare",
"a",
"namespace",
"prefix"
] | train | https://github.com/acsone/streamingxmlwriter/blob/68a7f48c4edf1fb310cf2518f7d183ab8d5dfe42/streamingxmlwriter/core.py#L174-L180 |
acsone/streamingxmlwriter | streamingxmlwriter/core.py | _StreamingXMLWriter.end_namespace | def end_namespace(self, prefix):
""" Undeclare a namespace prefix. """
del self._ns[prefix]
self._g.endPrefixMapping(prefix) | python | def end_namespace(self, prefix):
""" Undeclare a namespace prefix. """
del self._ns[prefix]
self._g.endPrefixMapping(prefix) | [
"def",
"end_namespace",
"(",
"self",
",",
"prefix",
")",
":",
"del",
"self",
".",
"_ns",
"[",
"prefix",
"]",
"self",
".",
"_g",
".",
"endPrefixMapping",
"(",
"prefix",
")"
] | Undeclare a namespace prefix. | [
"Undeclare",
"a",
"namespace",
"prefix",
"."
] | train | https://github.com/acsone/streamingxmlwriter/blob/68a7f48c4edf1fb310cf2518f7d183ab8d5dfe42/streamingxmlwriter/core.py#L182-L185 |
acsone/streamingxmlwriter | streamingxmlwriter/core.py | _StreamingXMLWriter.resolve_namespace | def resolve_namespace(self, qname):
""" Obtain (uri, name) from a qualified name """
if ':' in qname:
prefix, name = qname.split(':', 1)
uri = self._ns[prefix]
else:
name = qname
if None in self._ns:
uri = self._ns[None]
... | python | def resolve_namespace(self, qname):
""" Obtain (uri, name) from a qualified name """
if ':' in qname:
prefix, name = qname.split(':', 1)
uri = self._ns[prefix]
else:
name = qname
if None in self._ns:
uri = self._ns[None]
... | [
"def",
"resolve_namespace",
"(",
"self",
",",
"qname",
")",
":",
"if",
"':'",
"in",
"qname",
":",
"prefix",
",",
"name",
"=",
"qname",
".",
"split",
"(",
"':'",
",",
"1",
")",
"uri",
"=",
"self",
".",
"_ns",
"[",
"prefix",
"]",
"else",
":",
"name... | Obtain (uri, name) from a qualified name | [
"Obtain",
"(",
"uri",
"name",
")",
"from",
"a",
"qualified",
"name"
] | train | https://github.com/acsone/streamingxmlwriter/blob/68a7f48c4edf1fb310cf2518f7d183ab8d5dfe42/streamingxmlwriter/core.py#L187-L198 |
rosenbrockc/acorn | server/ui/views.py | _get_colors | def _get_colors(n):
"""Returns n unique and "evenly" spaced colors for the backgrounds
of the projects.
Args:
n (int): The number of unique colors wanted.
Returns:
colors (list of str): The colors in hex form.
"""
import matplotlib.pyplot as plt
from matplotlib.colors impo... | python | def _get_colors(n):
"""Returns n unique and "evenly" spaced colors for the backgrounds
of the projects.
Args:
n (int): The number of unique colors wanted.
Returns:
colors (list of str): The colors in hex form.
"""
import matplotlib.pyplot as plt
from matplotlib.colors impo... | [
"def",
"_get_colors",
"(",
"n",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"from",
"matplotlib",
".",
"colors",
"import",
"rgb2hex",
"as",
"r2h",
"from",
"numpy",
"import",
"linspace",
"cols",
"=",
"linspace",
"(",
"0.05",
",",
".95",
... | Returns n unique and "evenly" spaced colors for the backgrounds
of the projects.
Args:
n (int): The number of unique colors wanted.
Returns:
colors (list of str): The colors in hex form. | [
"Returns",
"n",
"unique",
"and",
"evenly",
"spaced",
"colors",
"for",
"the",
"backgrounds",
"of",
"the",
"projects",
"."
] | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/server/ui/views.py#L12-L29 |
rosenbrockc/acorn | server/ui/views.py | _color_variant | def _color_variant(hex_color, brightness_offset=1):
"""Takes a color like #87c95f and produces a lighter or darker variant.
Code adapted from method proposed by Chase Seibert at:
http://chase-seibert.github.io/blog/2011/07/29/python-calculate-lighterdarker-rgb-colors.html.
Args:
hex_color (... | python | def _color_variant(hex_color, brightness_offset=1):
"""Takes a color like #87c95f and produces a lighter or darker variant.
Code adapted from method proposed by Chase Seibert at:
http://chase-seibert.github.io/blog/2011/07/29/python-calculate-lighterdarker-rgb-colors.html.
Args:
hex_color (... | [
"def",
"_color_variant",
"(",
"hex_color",
",",
"brightness_offset",
"=",
"1",
")",
":",
"if",
"len",
"(",
"hex_color",
")",
"!=",
"7",
":",
"raise",
"Exception",
"(",
"\"Passed %s into color_variant(), needs to be in #87c95f format.\"",
"%",
"hex_color",
")",
"rgb_... | Takes a color like #87c95f and produces a lighter or darker variant.
Code adapted from method proposed by Chase Seibert at:
http://chase-seibert.github.io/blog/2011/07/29/python-calculate-lighterdarker-rgb-colors.html.
Args:
hex_color (str): The original hex color.
brightness_offset (in... | [
"Takes",
"a",
"color",
"like",
"#87c95f",
"and",
"produces",
"a",
"lighter",
"or",
"darker",
"variant",
".",
"Code",
"adapted",
"from",
"method",
"proposed",
"by",
"Chase",
"Seibert",
"at",
":",
"http",
":",
"//",
"chase",
"-",
"seibert",
".",
"github",
... | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/server/ui/views.py#L31-L59 |
rosenbrockc/acorn | server/ui/views.py | _make_projcet_list | def _make_projcet_list(path):
"""Returns a dictionaries in which each project is a key and the
tasks are stored as a list within that dictionaly element.
Args:
path (str): The path to the folder containing the *.json files.
Returns:
projects (list of dict): A dictionary in whic... | python | def _make_projcet_list(path):
"""Returns a dictionaries in which each project is a key and the
tasks are stored as a list within that dictionaly element.
Args:
path (str): The path to the folder containing the *.json files.
Returns:
projects (list of dict): A dictionary in whic... | [
"def",
"_make_projcet_list",
"(",
"path",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"from",
"matplotlib",
".",
"colors",
"import",
"LinearSegmentedColormap",
"from",
"matplotlib",
".",
"colors",
"import",
"rgb2hex",
"as",
"r2h",
"from",
"numpy",
"i... | Returns a dictionaries in which each project is a key and the
tasks are stored as a list within that dictionaly element.
Args:
path (str): The path to the folder containing the *.json files.
Returns:
projects (list of dict): A dictionary in which each project is a key
co... | [
"Returns",
"a",
"dictionaries",
"in",
"which",
"each",
"project",
"is",
"a",
"key",
"and",
"the",
"tasks",
"are",
"stored",
"as",
"a",
"list",
"within",
"that",
"dictionaly",
"element",
".",
"Args",
":",
"path",
"(",
"str",
")",
":",
"The",
"path",
"to... | train | https://github.com/rosenbrockc/acorn/blob/9a44d1a1ad8bfc2c54a6b56d9efe54433a797820/server/ui/views.py#L62-L105 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | build_prefixes | def build_prefixes(namespaces=None):
"""Internal function takes a list of prefix, namespace uri tuples and
generates a SPARQL PREFIX string.
Args:
namespaces(list): List of tuples, defaults to BIBFRAME and
Schema.org
Returns:
string
"""
if namespaces i... | python | def build_prefixes(namespaces=None):
"""Internal function takes a list of prefix, namespace uri tuples and
generates a SPARQL PREFIX string.
Args:
namespaces(list): List of tuples, defaults to BIBFRAME and
Schema.org
Returns:
string
"""
if namespaces i... | [
"def",
"build_prefixes",
"(",
"namespaces",
"=",
"None",
")",
":",
"if",
"namespaces",
"is",
"None",
":",
"namespaces",
"=",
"[",
"(",
"'bf'",
",",
"str",
"(",
"BIBFRAME",
")",
")",
",",
"(",
"'schema'",
",",
"str",
"(",
"SCHEMA_ORG",
")",
")",
"]",
... | Internal function takes a list of prefix, namespace uri tuples and
generates a SPARQL PREFIX string.
Args:
namespaces(list): List of tuples, defaults to BIBFRAME and
Schema.org
Returns:
string | [
"Internal",
"function",
"takes",
"a",
"list",
"of",
"prefix",
"namespace",
"uri",
"tuples",
"and",
"generates",
"a",
"SPARQL",
"PREFIX",
"string",
"."
] | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L55-L79 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | copy_graph | def copy_graph(subject, existing_graph):
"""Function takes a subject and an existing graph, returns a new graph with
all predicate and objects of the existing graph copied to the new_graph with
subject as the new subject
Args:
subject(rdflib.URIRef): A URIRef subject
existing_graph(rdfl... | python | def copy_graph(subject, existing_graph):
"""Function takes a subject and an existing graph, returns a new graph with
all predicate and objects of the existing graph copied to the new_graph with
subject as the new subject
Args:
subject(rdflib.URIRef): A URIRef subject
existing_graph(rdfl... | [
"def",
"copy_graph",
"(",
"subject",
",",
"existing_graph",
")",
":",
"new_graph",
"=",
"rdflib",
".",
"Graph",
"(",
")",
"for",
"predicate",
",",
"object_",
"in",
"existing_graph",
".",
"predicate_objects",
"(",
")",
":",
"new_graph",
".",
"add",
"(",
"("... | Function takes a subject and an existing graph, returns a new graph with
all predicate and objects of the existing graph copied to the new_graph with
subject as the new subject
Args:
subject(rdflib.URIRef): A URIRef subject
existing_graph(rdflib.Graph): A rdflib.Graph
Returns:
... | [
"Function",
"takes",
"a",
"subject",
"and",
"an",
"existing",
"graph",
"returns",
"a",
"new",
"graph",
"with",
"all",
"predicate",
"and",
"objects",
"of",
"the",
"existing",
"graph",
"copied",
"to",
"the",
"new_graph",
"with",
"subject",
"as",
"the",
"new",
... | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L81-L96 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.init_app | def init_app(self, app):
"""
Initializes a Flask app object for the extension.
Args:
app(Flask): Flask app
"""
app.config.setdefault('FEDORA_BASE_URL', 'http://localhost:8080')
if hasattr(app, 'teardown_appcontext'):
app.teardown_appcontext(self.t... | python | def init_app(self, app):
"""
Initializes a Flask app object for the extension.
Args:
app(Flask): Flask app
"""
app.config.setdefault('FEDORA_BASE_URL', 'http://localhost:8080')
if hasattr(app, 'teardown_appcontext'):
app.teardown_appcontext(self.t... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"app",
".",
"config",
".",
"setdefault",
"(",
"'FEDORA_BASE_URL'",
",",
"'http://localhost:8080'",
")",
"if",
"hasattr",
"(",
"app",
",",
"'teardown_appcontext'",
")",
":",
"app",
".",
"teardown_appcontext"... | Initializes a Flask app object for the extension.
Args:
app(Flask): Flask app | [
"Initializes",
"a",
"Flask",
"app",
"object",
"for",
"the",
"extension",
"."
] | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L202-L213 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.create_transaction | def create_transaction(self):
"""Method creates a new transaction resource and sets instance's
transaction."""
request = urlllib.request.urlopen(
urllib.parse.urljoin(self.base_url, 'fcr:tx'))
self.transaction = request.read() | python | def create_transaction(self):
"""Method creates a new transaction resource and sets instance's
transaction."""
request = urlllib.request.urlopen(
urllib.parse.urljoin(self.base_url, 'fcr:tx'))
self.transaction = request.read() | [
"def",
"create_transaction",
"(",
"self",
")",
":",
"request",
"=",
"urlllib",
".",
"request",
".",
"urlopen",
"(",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"'fcr:tx'",
")",
")",
"self",
".",
"transaction",
"=",
"request... | Method creates a new transaction resource and sets instance's
transaction. | [
"Method",
"creates",
"a",
"new",
"transaction",
"resource",
"and",
"sets",
"instance",
"s",
"transaction",
"."
] | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L215-L220 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.connect | def connect(self,
fedora_url,
data=None,
method='Get'):
"""Method attempts to connect to REST servers of the Fedora
Commons repository using optional data parameter.
Args:
fedora_url(string): Fedora URL
data(dict): Data to ... | python | def connect(self,
fedora_url,
data=None,
method='Get'):
"""Method attempts to connect to REST servers of the Fedora
Commons repository using optional data parameter.
Args:
fedora_url(string): Fedora URL
data(dict): Data to ... | [
"def",
"connect",
"(",
"self",
",",
"fedora_url",
",",
"data",
"=",
"None",
",",
"method",
"=",
"'Get'",
")",
":",
"if",
"data",
"is",
"None",
":",
"data",
"=",
"{",
"}",
"if",
"not",
"fedora_url",
".",
"startswith",
"(",
"\"http\"",
")",
":",
"fed... | Method attempts to connect to REST servers of the Fedora
Commons repository using optional data parameter.
Args:
fedora_url(string): Fedora URL
data(dict): Data to through to REST endpoint
method(str): REST Method, defaults to GET
Returns:
result... | [
"Method",
"attempts",
"to",
"connect",
"to",
"REST",
"servers",
"of",
"the",
"Fedora",
"Commons",
"repository",
"using",
"optional",
"data",
"parameter",
"."
] | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L223-L261 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.as_json | def as_json(self,
entity_url,
context=None):
"""Method takes a entity uri and attempts to return the Fedora Object
as a JSON-LD.
Args:
entity_url(str): Fedora Commons URL of Entity
context(None): Returns JSON-LD with Context, default is No... | python | def as_json(self,
entity_url,
context=None):
"""Method takes a entity uri and attempts to return the Fedora Object
as a JSON-LD.
Args:
entity_url(str): Fedora Commons URL of Entity
context(None): Returns JSON-LD with Context, default is No... | [
"def",
"as_json",
"(",
"self",
",",
"entity_url",
",",
"context",
"=",
"None",
")",
":",
"try",
":",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"entity_url",
")",
"except",
"urllib",
".",
"error",
".",
"HTTPError",
":",
"raise",
"ValueError",
"(",
... | Method takes a entity uri and attempts to return the Fedora Object
as a JSON-LD.
Args:
entity_url(str): Fedora Commons URL of Entity
context(None): Returns JSON-LD with Context, default is None
Returns:
str: JSON-LD of Fedora Object | [
"Method",
"takes",
"a",
"entity",
"uri",
"and",
"attempts",
"to",
"return",
"the",
"Fedora",
"Object",
"as",
"a",
"JSON",
"-",
"LD",
"."
] | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L263-L285 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.create | def create(self, uri=None, graph=None, data=None):
"""Method takes an optional URI and graph, first checking if the URL is already
present in Fedora, if not, creates a Fedora Object with the graph as
properties. If URI is None, uses Fedora 4 default PID minter to create
the object's URI.... | python | def create(self, uri=None, graph=None, data=None):
"""Method takes an optional URI and graph, first checking if the URL is already
present in Fedora, if not, creates a Fedora Object with the graph as
properties. If URI is None, uses Fedora 4 default PID minter to create
the object's URI.... | [
"def",
"create",
"(",
"self",
",",
"uri",
"=",
"None",
",",
"graph",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"if",
"uri",
"is",
"not",
"None",
":",
"existing_entity",
"=",
"self",
".",
"__dedup__",
"(",
"rdflib",
".",
"URIRef",
"(",
"uri",... | Method takes an optional URI and graph, first checking if the URL is already
present in Fedora, if not, creates a Fedora Object with the graph as
properties. If URI is None, uses Fedora 4 default PID minter to create
the object's URI.
Args:
uri(string): String of URI, defaul... | [
"Method",
"takes",
"an",
"optional",
"URI",
"and",
"graph",
"first",
"checking",
"if",
"the",
"URL",
"is",
"already",
"present",
"in",
"Fedora",
"if",
"not",
"creates",
"a",
"Fedora",
"Object",
"with",
"the",
"graph",
"as",
"properties",
".",
"If",
"URI",
... | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L288-L318 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.delete | def delete(self, uri):
"""Method deletes a Fedora Object in the repository
Args:
uri(str): URI of Fedora Object
"""
try:
self.connect(uri, method='DELETE')
return True
except urllib.error.HTTPError:
return False | python | def delete(self, uri):
"""Method deletes a Fedora Object in the repository
Args:
uri(str): URI of Fedora Object
"""
try:
self.connect(uri, method='DELETE')
return True
except urllib.error.HTTPError:
return False | [
"def",
"delete",
"(",
"self",
",",
"uri",
")",
":",
"try",
":",
"self",
".",
"connect",
"(",
"uri",
",",
"method",
"=",
"'DELETE'",
")",
"return",
"True",
"except",
"urllib",
".",
"error",
".",
"HTTPError",
":",
"return",
"False"
] | Method deletes a Fedora Object in the repository
Args:
uri(str): URI of Fedora Object | [
"Method",
"deletes",
"a",
"Fedora",
"Object",
"in",
"the",
"repository"
] | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L321-L331 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.exists | def exists(self, uri):
"""Method returns true is the entity exists in the Repository,
false, otherwise
Args:
uri(str): Entity URI
Returns:
bool
"""
##entity_uri = "/".join([self.base_url, entity_id])
try:
urllib.request.urlope... | python | def exists(self, uri):
"""Method returns true is the entity exists in the Repository,
false, otherwise
Args:
uri(str): Entity URI
Returns:
bool
"""
##entity_uri = "/".join([self.base_url, entity_id])
try:
urllib.request.urlope... | [
"def",
"exists",
"(",
"self",
",",
"uri",
")",
":",
"##entity_uri = \"/\".join([self.base_url, entity_id])",
"try",
":",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"uri",
")",
"return",
"True",
"except",
"urllib",
".",
"error",
".",
"HTTPError",
":",
"retu... | Method returns true is the entity exists in the Repository,
false, otherwise
Args:
uri(str): Entity URI
Returns:
bool | [
"Method",
"returns",
"true",
"is",
"the",
"entity",
"exists",
"in",
"the",
"Repository",
"false",
"otherwise"
] | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L335-L350 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.flush | def flush(self):
"""Method flushes repository, deleting all objects"""
base_graph = rdflib.Graph().parse('{}/rest'.format(self.base_url))
has_child = rdflib.URIRef(
'http://fedora.info/definitions/v4/repository#hasChild')
for obj in base_graph.objects(predicate=has_child):
... | python | def flush(self):
"""Method flushes repository, deleting all objects"""
base_graph = rdflib.Graph().parse('{}/rest'.format(self.base_url))
has_child = rdflib.URIRef(
'http://fedora.info/definitions/v4/repository#hasChild')
for obj in base_graph.objects(predicate=has_child):
... | [
"def",
"flush",
"(",
"self",
")",
":",
"base_graph",
"=",
"rdflib",
".",
"Graph",
"(",
")",
".",
"parse",
"(",
"'{}/rest'",
".",
"format",
"(",
"self",
".",
"base_url",
")",
")",
"has_child",
"=",
"rdflib",
".",
"URIRef",
"(",
"'http://fedora.info/defini... | Method flushes repository, deleting all objects | [
"Method",
"flushes",
"repository",
"deleting",
"all",
"objects"
] | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L352-L358 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.insert | def insert(self,
entity_id,
property_uri,
value):
"""Method inserts a new entity's property in Fedora4 Repository
Args:
entity_id(string): Unique ID of Fedora object
property_uri(string): URI of property
value: Value of th... | python | def insert(self,
entity_id,
property_uri,
value):
"""Method inserts a new entity's property in Fedora4 Repository
Args:
entity_id(string): Unique ID of Fedora object
property_uri(string): URI of property
value: Value of th... | [
"def",
"insert",
"(",
"self",
",",
"entity_id",
",",
"property_uri",
",",
"value",
")",
":",
"if",
"not",
"entity_id",
".",
"startswith",
"(",
"\"http\"",
")",
":",
"entity_uri",
"=",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"self",
".",
"base_url",
... | Method inserts a new entity's property in Fedora4 Repository
Args:
entity_id(string): Unique ID of Fedora object
property_uri(string): URI of property
value: Value of the property, can be literal or URI reference
Returns:
boolean: True if successful chan... | [
"Method",
"inserts",
"a",
"new",
"entity",
"s",
"property",
"in",
"Fedora4",
"Repository"
] | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L360-L406 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.read | def read(self, uri):
"""Method takes uri and creates a RDF graph from Fedora Repository
Args:
uri(str): URI of Fedora URI
Returns:
rdflib.Graph
"""
read_response = self.connect(uri)
fedora_graph = rdflib.Graph().parse(
data=read_respo... | python | def read(self, uri):
"""Method takes uri and creates a RDF graph from Fedora Repository
Args:
uri(str): URI of Fedora URI
Returns:
rdflib.Graph
"""
read_response = self.connect(uri)
fedora_graph = rdflib.Graph().parse(
data=read_respo... | [
"def",
"read",
"(",
"self",
",",
"uri",
")",
":",
"read_response",
"=",
"self",
".",
"connect",
"(",
"uri",
")",
"fedora_graph",
"=",
"rdflib",
".",
"Graph",
"(",
")",
".",
"parse",
"(",
"data",
"=",
"read_response",
".",
"read",
"(",
")",
",",
"fo... | Method takes uri and creates a RDF graph from Fedora Repository
Args:
uri(str): URI of Fedora URI
Returns:
rdflib.Graph | [
"Method",
"takes",
"uri",
"and",
"creates",
"a",
"RDF",
"graph",
"from",
"Fedora",
"Repository"
] | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L409-L422 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.remove | def remove(self,
entity_id,
property_uri,
value):
"""Method removes a triple for the given/subject.
Args:
entity_id(string): Fedora Object ID, ideally URI of the subject
property_uri(string):
value(string):
Return... | python | def remove(self,
entity_id,
property_uri,
value):
"""Method removes a triple for the given/subject.
Args:
entity_id(string): Fedora Object ID, ideally URI of the subject
property_uri(string):
value(string):
Return... | [
"def",
"remove",
"(",
"self",
",",
"entity_id",
",",
"property_uri",
",",
"value",
")",
":",
"if",
"not",
"entity_id",
".",
"startswith",
"(",
"\"http\"",
")",
":",
"entity_uri",
"=",
"urllib",
".",
"parse",
".",
"urljoin",
"(",
"self",
".",
"base_url",
... | Method removes a triple for the given/subject.
Args:
entity_id(string): Fedora Object ID, ideally URI of the subject
property_uri(string):
value(string):
Return:
boolean: True if triple was removed from the object | [
"Method",
"removes",
"a",
"triple",
"for",
"the",
"given",
"/",
"subject",
"."
] | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L424-L461 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.replace | def replace(self,
entity_id,
property_name,
old_value,
value):
"""Method replaces a triple for the given entity/subject. Property
name is from the schema.org vocabulary.
Args:
entity_id(string): Unique ID of Fedora obje... | python | def replace(self,
entity_id,
property_name,
old_value,
value):
"""Method replaces a triple for the given entity/subject. Property
name is from the schema.org vocabulary.
Args:
entity_id(string): Unique ID of Fedora obje... | [
"def",
"replace",
"(",
"self",
",",
"entity_id",
",",
"property_name",
",",
"old_value",
",",
"value",
")",
":",
"if",
"not",
"entity_id",
".",
"startswith",
"(",
"\"http\"",
")",
":",
"entity_uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"self",
".",
"base... | Method replaces a triple for the given entity/subject. Property
name is from the schema.org vocabulary.
Args:
entity_id(string): Unique ID of Fedora object
property_name(string): Prefix and property name i.e. schema:name
old_value(string): Literal or URI of old value... | [
"Method",
"replaces",
"a",
"triple",
"for",
"the",
"given",
"entity",
"/",
"subject",
".",
"Property",
"name",
"is",
"from",
"the",
"schema",
".",
"org",
"vocabulary",
"."
] | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L464-L503 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.search | def search(self, query_term):
"""DEPRECIATED
Method takes a query term and searches Fedora Repository using SPARQL
search endpoint and returns a RDF graph of the search results.
Args:
query_term(str): String to search repository
Returns:
rdflib.Graph()
... | python | def search(self, query_term):
"""DEPRECIATED
Method takes a query term and searches Fedora Repository using SPARQL
search endpoint and returns a RDF graph of the search results.
Args:
query_term(str): String to search repository
Returns:
rdflib.Graph()
... | [
"def",
"search",
"(",
"self",
",",
"query_term",
")",
":",
"fedora_search_url",
"=",
"\"/\"",
".",
"join",
"(",
"[",
"self",
".",
"base_url",
",",
"'rest'",
",",
"'fcr:search'",
"]",
")",
"fedora_search_url",
"=",
"\"{}?{}\"",
".",
"format",
"(",
"fedora_s... | DEPRECIATED
Method takes a query term and searches Fedora Repository using SPARQL
search endpoint and returns a RDF graph of the search results.
Args:
query_term(str): String to search repository
Returns:
rdflib.Graph() | [
"DEPRECIATED",
"Method",
"takes",
"a",
"query",
"term",
"and",
"searches",
"Fedora",
"Repository",
"using",
"SPARQL",
"search",
"endpoint",
"and",
"returns",
"a",
"RDF",
"graph",
"of",
"the",
"search",
"results",
"."
] | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L505-L531 |
jermnelson/flask-fedora-commons | flask_fedora_commons/__init__.py | Repository.sparql | def sparql(self, statement, end_point='fcr:sparql', accept_format='text/csv'):
"""DEPRECIATED
Method takes and executes a generic SPARQL statement and returns
the result. NOTE: The Fedora 4 supports a limited subset of SPARQL,
see <https://wiki.duraspace.org/display/FF/RESTful+HTTP+API+-... | python | def sparql(self, statement, end_point='fcr:sparql', accept_format='text/csv'):
"""DEPRECIATED
Method takes and executes a generic SPARQL statement and returns
the result. NOTE: The Fedora 4 supports a limited subset of SPARQL,
see <https://wiki.duraspace.org/display/FF/RESTful+HTTP+API+-... | [
"def",
"sparql",
"(",
"self",
",",
"statement",
",",
"end_point",
"=",
"'fcr:sparql'",
",",
"accept_format",
"=",
"'text/csv'",
")",
":",
"request",
"=",
"urllib",
".",
"request",
".",
"Request",
"(",
"'/'",
".",
"join",
"(",
"[",
"self",
".",
"base_url"... | DEPRECIATED
Method takes and executes a generic SPARQL statement and returns
the result. NOTE: The Fedora 4 supports a limited subset of SPARQL,
see <https://wiki.duraspace.org/display/FF/RESTful+HTTP+API+-+Search#RESTfulHTTPAPI-Search-SPARQLEndpoint>
for more information.
Args:... | [
"DEPRECIATED",
"Method",
"takes",
"and",
"executes",
"a",
"generic",
"SPARQL",
"statement",
"and",
"returns",
"the",
"result",
".",
"NOTE",
":",
"The",
"Fedora",
"4",
"supports",
"a",
"limited",
"subset",
"of",
"SPARQL",
"see",
"<https",
":",
"//",
"wiki",
... | train | https://github.com/jermnelson/flask-fedora-commons/blob/81cee0d8c9e79fa2bdd1a101facb9e8c0f307af4/flask_fedora_commons/__init__.py#L534-L557 |
etcher-be/emiz | emiz/weather/mission_weather/mission_weather.py | _get_season | def _get_season(_datetime: typing.Optional[date] = None) -> typing.Tuple[str, int]:
"""
Finds the current season based on now() and gives a dummy temperature
Returns: tuple of season name, temperature
"""
if _datetime is None:
_actual_datetime: date = datetime.now().date().replace(year=Y)
... | python | def _get_season(_datetime: typing.Optional[date] = None) -> typing.Tuple[str, int]:
"""
Finds the current season based on now() and gives a dummy temperature
Returns: tuple of season name, temperature
"""
if _datetime is None:
_actual_datetime: date = datetime.now().date().replace(year=Y)
... | [
"def",
"_get_season",
"(",
"_datetime",
":",
"typing",
".",
"Optional",
"[",
"date",
"]",
"=",
"None",
")",
"->",
"typing",
".",
"Tuple",
"[",
"str",
",",
"int",
"]",
":",
"if",
"_datetime",
"is",
"None",
":",
"_actual_datetime",
":",
"date",
"=",
"d... | Finds the current season based on now() and gives a dummy temperature
Returns: tuple of season name, temperature | [
"Finds",
"the",
"current",
"season",
"based",
"on",
"now",
"()",
"and",
"gives",
"a",
"dummy",
"temperature"
] | train | https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/weather/mission_weather/mission_weather.py#L41-L52 |
etcher-be/emiz | emiz/weather/mission_weather/mission_weather.py | MissionWeather._normalize_direction | def _normalize_direction(heading: int) -> int:
"""
Make sure that 0 < heading < 360
Args:
heading: base heading
Returns: corrected heading
"""
while heading > 359:
heading = int(heading - 359)
while heading < 0:
heading = int... | python | def _normalize_direction(heading: int) -> int:
"""
Make sure that 0 < heading < 360
Args:
heading: base heading
Returns: corrected heading
"""
while heading > 359:
heading = int(heading - 359)
while heading < 0:
heading = int... | [
"def",
"_normalize_direction",
"(",
"heading",
":",
"int",
")",
"->",
"int",
":",
"while",
"heading",
">",
"359",
":",
"heading",
"=",
"int",
"(",
"heading",
"-",
"359",
")",
"while",
"heading",
"<",
"0",
":",
"heading",
"=",
"int",
"(",
"heading",
"... | Make sure that 0 < heading < 360
Args:
heading: base heading
Returns: corrected heading | [
"Make",
"sure",
"that",
"0",
"<",
"heading",
"<",
"360"
] | train | https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/weather/mission_weather/mission_weather.py#L102-L116 |
etcher-be/emiz | emiz/weather/mission_weather/mission_weather.py | MissionWeather._gauss | def _gauss(mean: int, sigma: int) -> int:
"""
Creates a variation from a base value
Args:
mean: base value
sigma: gaussian sigma
Returns: random value
"""
return int(random.gauss(mean, sigma)) | python | def _gauss(mean: int, sigma: int) -> int:
"""
Creates a variation from a base value
Args:
mean: base value
sigma: gaussian sigma
Returns: random value
"""
return int(random.gauss(mean, sigma)) | [
"def",
"_gauss",
"(",
"mean",
":",
"int",
",",
"sigma",
":",
"int",
")",
"->",
"int",
":",
"return",
"int",
"(",
"random",
".",
"gauss",
"(",
"mean",
",",
"sigma",
")",
")"
] | Creates a variation from a base value
Args:
mean: base value
sigma: gaussian sigma
Returns: random value | [
"Creates",
"a",
"variation",
"from",
"a",
"base",
"value"
] | train | https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/weather/mission_weather/mission_weather.py#L119-L130 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.